code
stringlengths
2
1.05M
/* * @Author: Mike Reich * @Date: 2015-07-16 08:47:51 * @Last Modified 2016-05-20 */ 'use strict'; import {PluginManager} from '../../lib/' describe("PluginManager", () => { describe("Load", () => { var instance; it("should not be null", () => PluginManager.should.not.be.null) it("should be instantiated", () => (instance = new PluginManager()).should.not.be.null) }) })
var Asteroid = require('asteroids-asteroid'); var Bullet = module.exports = function(initializer){ Asteroid.call(this, initializer); } Bullet.prototype = new Asteroid(); Bullet.prototype.ttl = function(timeToDeath){ if (timeToDeath != undefined) { this.timeToDeath = timeToDeath; } return this.timeToDeath != undefined ? this.timeToDeath : Number.POSITIVE_INFINITY; } Bullet.prototype.tick = function(){ Asteroid.prototype.tick.call(this); var ttl = Math.max(this.ttl() - 1, 0); if (ttl === 0) { this.notifyOf('died'); } this.ttl(ttl); }
const DEFAULT_PUBLICATION = 'meteor_table_generic_pub'; const DEFAULT_TEMPLATE = 'meteor_table_generic_template'; const DEFAULT_ENTRIES = [10, 25, 50, 100]; /** * The global namespace for Tables * @namespace Tables */ Tables = {}; Tables.registered = {}; Tables.registerTable = function (options) { if (typeof options.table_id !== 'string') throw new Error('Options must specify table_id'); if (options.table_id in Tables) throw new Error('Table with table_id: '+options.table_id+' already registered.') if (!(options.collection instanceof Mongo.Collection)) throw new Error('Options must specify collection'); if (!(options.fields instanceof Object)) throw new Error('Options must specify column fields'); if ('selector' in options && !(options.selector instanceof Object)) throw new Error('Selector must by instance of Object'); if ('extra_fields' in options && !(options.extra_fields instanceof Array)) throw new Error('Extra fields must by instance of Array'); if ('dynamic_fields' in options && !(options.dynamic_fields instanceof Array)) throw new Error('Extra fields must by instance of Array'); if ('entries' in options && !(options.entries instanceof Array)) throw new Error('Entries option must by instance of Array'); if ('default_sort' in options && !(options.default_sort instanceof Object)) throw new Error('Default sort must by instance of Object'); if ('state_save' in options && (typeof options.state_save !== 'boolean')) throw new Error('State save option must by instance of boolean'); Tables.registered[options.table_id] = {}; Tables.registered[options.table_id].pub = options.publication || DEFAULT_PUBLICATION; Tables.registered[options.table_id].template = options.template || DEFAULT_TEMPLATE; Tables.registered[options.table_id].selector = options.selector; Tables.registered[options.table_id].collection = options.collection; Tables.registered[options.table_id].fields = options.fields; Tables.registered[options.table_id].entries = options.entries || DEFAULT_ENTRIES; Tables.registered[options.table_id].default_sort = options.default_sort || Helpers.generateDefaultSortingCriteria(options.fields.get()); if ('extra_fields' in options) Tables.registered[options.table_id].extra_fields = options.extra_fields; if ('state_save' in options) Tables.registered[options.table_id].state_save = options.state_save; if ('dynamic_fields' in options) { Tables.registered[options.table_id].dynamic_fields = options.dynamic_fields; Tables.registered[options.table_id].session_id = options.table_id.concat('_new_columns'); } return Tables.registered[options.table_id]; };
$(function () { // Selection modal gets closed (cancelled or saved) $("#selection-modal").on("hidden.bs.modal", function () { updateSelection(); }); // User clicks save button in selection modal $("#selection-modal-save").on("click", function () { var entries = []; $("td.selection-highlight").each(function () { entries.push({ id: $(this).data("entryid"), date: moment(new Date($(this).data("date"))).format("YYYY-MM-DD"), type: $("#selection-modal-type").val(), memberId: $(this).data("memberid") }); }); loadDataFromBackend("entries/" + Teams.getCurrent(), "PUT", function () { updateData(); $("#selection-modal").modal("hide"); }, JSON.stringify(entries)); }); var selectionStart = null; var tableContainer = $("#table-container"); // User presses the mouse button tableContainer.on("mousedown", "td.selectable", function () { selectionStart = { date: new Date($(this).data("date")), memberId: $(this).data("memberid") }; updateSelection($(this).data("memberid"), selectionStart.date, new Date($(this).data("date"))); return false;// Prevent showing text selection }); // User moves mouse over a selectable cell tableContainer.on("mouseover", "td.selectable", function () { if (selectionStart && selectionStart.memberId == $(this).data("memberid")) { updateSelection($(this).data("memberid"), selectionStart.date, new Date($(this).data("date"))); } }); // User released the mouse button tableContainer.on("mouseup", "td.selectable", function () { if (selectionStart && selectionStart.memberId == $(this).data("memberid")) { updateSelection($(this).data("memberid"), selectionStart.date, new Date($(this).data("date"))); var modal = $("#selection-modal"); var startDate = moment(selectionStart.date); var endDate = moment(new Date($(this).data("date"))); if (startDate.isSame(endDate)) { $("#selection-modal-date").text(startDate.format("L")); } else { $("#selection-modal-date").text(startDate.format("L") + " - " + endDate.format("L")); } $("#selection-modal-username").text(TeamMembers.list[$(this).data("memberid")].username); $("#selection-modal-type").val(""); modal.modal("show"); } else { updateSelection(); } selectionStart = null; }); }); /** * Update the current selection (highlights selected cells, removes highlighting from not selected cells). * * @param memberId int The ID of the team member * @param startDate moment The start date of the selection * @param endDate moment The end date of the selection */ function updateSelection(memberId, startDate, endDate) { var cells = $("#table-container").find("td.selectable"); var elements = cells.filter(function () { if ($(this).data("memberid") != memberId) { return false; } var date = moment(new Date($(this).data("date"))); return !(date.isBefore(startDate) || date.isAfter(endDate)); }); cells.not(elements).removeClass("selection-highlight"); elements.addClass("selection-highlight"); }
/*! jQuery v3.2.0 | (c) JS Foundation and other contributors | jquery.org/license */ !function (a, b) { "use strict"; "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) { "use strict"; var c = [], d = a.document, e = Object.getPrototypeOf, f = c.slice, g = c.concat, h = c.push, i = c.indexOf, j = {}, k = j.toString, l = j.hasOwnProperty, m = l.toString, n = m.call(Object), o = {}; function p(a, b) { b = b || d; var c = b.createElement("script"); c.text = a, b.head.appendChild(c).parentNode.removeChild(c) } var q = "3.2.0", r = function (a, b) { return new r.fn.init(a, b) }, s = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, t = /^-ms-/, u = /-([a-z])/g, v = function (a, b) { return b.toUpperCase() }; r.fn = r.prototype = { jquery: q, constructor: r, length: 0, toArray: function () { return f.call(this) }, get: function (a) { return null == a ? f.call(this) : a < 0 ? this[a + this.length] : this[a] }, pushStack: function (a) { var b = r.merge(this.constructor(), a); return b.prevObject = this, b }, each: function (a) { return r.each(this, a) }, map: function (a) { return this.pushStack(r.map(this, function (b, c) { return a.call(b, c, b) })) }, slice: function () { return this.pushStack(f.apply(this, arguments)) }, first: function () { return this.eq(0) }, last: function () { return this.eq(-1) }, eq: function (a) { var b = this.length, c = +a + (a < 0 ? b : 0); return this.pushStack(c >= 0 && c < b ? [this[c]] : []) }, end: function () { return this.prevObject || this.constructor() }, push: h, sort: c.sort, splice: c.splice }, r.extend = r.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 || r.isFunction(g) || (g = {}), h === i && (g = this, h--); h < i; h++)if (null != (a = arguments[h]))for (b in a)c = g[b], d = a[b], g !== d && (j && d && (r.isPlainObject(d) || (e = Array.isArray(d))) ? (e ? (e = !1, f = c && Array.isArray(c) ? c : []) : f = c && r.isPlainObject(c) ? c : {}, g[b] = r.extend(j, f, d)) : void 0 !== d && (g[b] = d)); return g }, r.extend({ expando: "jQuery" + (q + Math.random()).replace(/\D/g, ""), isReady: !0, error: function (a) { throw new Error(a) }, noop: function () { }, isFunction: function (a) { return "function" === r.type(a) }, isWindow: function (a) { return null != a && a === a.window }, isNumeric: function (a) { var b = r.type(a); return ("number" === b || "string" === b) && !isNaN(a - parseFloat(a)) }, isPlainObject: function (a) { var b, c; return !(!a || "[object Object]" !== k.call(a)) && (!(b = e(a)) || (c = l.call(b, "constructor") && b.constructor, "function" == typeof c && m.call(c) === n)) }, isEmptyObject: function (a) { var b; for (b in a)return !1; return !0 }, type: function (a) { return null == a ? a + "" : "object" == typeof a || "function" == typeof a ? j[k.call(a)] || "object" : typeof a }, globalEval: function (a) { p(a) }, camelCase: function (a) { return a.replace(t, "ms-").replace(u, v) }, each: function (a, b) { var c, d = 0; if (w(a)) { for (c = a.length; d < c; d++)if (b.call(a[d], d, a[d]) === !1)break } else for (d in a)if (b.call(a[d], d, a[d]) === !1)break; return a }, trim: function (a) { return null == a ? "" : (a + "").replace(s, "") }, makeArray: function (a, b) { var c = b || []; return null != a && (w(Object(a)) ? r.merge(c, "string" == typeof a ? [a] : a) : h.call(c, a)), c }, inArray: function (a, b, c) { return null == b ? -1 : i.call(b, a, c) }, merge: function (a, b) { for (var c = +b.length, d = 0, e = a.length; d < c; 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; f < g; f++)d = !b(a[f], f), d !== h && e.push(a[f]); return e }, map: function (a, b, c) { var d, e, f = 0, h = []; if (w(a))for (d = a.length; f < d; f++)e = b(a[f], f, c), null != e && h.push(e); else for (f in a)e = b(a[f], f, c), null != e && h.push(e); return g.apply([], h) }, guid: 1, proxy: function (a, b) { var c, d, e; if ("string" == typeof b && (c = a[b], b = a, a = c), r.isFunction(a))return d = f.call(arguments, 2), e = function () { return a.apply(b || this, d.concat(f.call(arguments))) }, e.guid = a.guid = a.guid || r.guid++, e }, now: Date.now, support: o }), "function" == typeof Symbol && (r.fn[Symbol.iterator] = c[Symbol.iterator]), r.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "), function (a, b) { j["[object " + b + "]"] = b.toLowerCase() }); function w(a) { var b = !!a && "length" in a && a.length, c = r.type(a); return "function" !== c && !r.isWindow(a) && ("array" === c || 0 === b || "number" == typeof b && b > 0 && b - 1 in a) } var x = function (a) { var b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u = "sizzle" + 1 * new Date, v = a.document, w = 0, x = 0, y = ha(), z = ha(), A = ha(), B = function (a, b) { return a === b && (l = !0), 0 }, C = {}.hasOwnProperty, D = [], E = D.pop, F = D.push, G = D.push, H = D.slice, I = function (a, b) { for (var c = 0, d = a.length; c < d; c++)if (a[c] === b)return c; 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-]|[^\0-\\xa0])+", M = "\\[" + K + "*(" + L + ")(?:" + K + "*([*^$|!~]?=)" + K + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + L + "))|)" + K + "*\\]", N = ":(" + L + ")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|" + M + ")*)|.*)\\)|)", O = new RegExp(K + "+", "g"), 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(N), U = new RegExp("^" + L + "$"), V = { ID: new RegExp("^#(" + L + ")"), CLASS: new RegExp("^\\.(" + L + ")"), TAG: new RegExp("^(" + L + "|[*])"), ATTR: new RegExp("^" + M), PSEUDO: new RegExp("^" + N), 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-]+))$/, $ = /[+~]/, _ = new RegExp("\\\\([\\da-f]{1,6}" + K + "?|(" + K + ")|.)", "ig"), aa = function (a, b, c) { var d = "0x" + b - 65536; return d !== d || c ? b : d < 0 ? String.fromCharCode(d + 65536) : String.fromCharCode(d >> 10 | 55296, 1023 & d | 56320) }, ba = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, ca = function (a, b) { return b ? "\0" === a ? "\ufffd" : a.slice(0, -1) + "\\" + a.charCodeAt(a.length - 1).toString(16) + " " : "\\" + a }, da = function () { m() }, ea = ta(function (a) { return a.disabled === !0 && ("form" in a || "label" in a) }, {dir: "parentNode", next: "legend"}); try { G.apply(D = H.call(v.childNodes), v.childNodes), D[v.childNodes.length].nodeType } catch (fa) { 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 ga(a, b, d, e) { var f, h, j, k, l, o, r, s = b && b.ownerDocument, w = b ? b.nodeType : 9; if (d = d || [], "string" != typeof a || !a || 1 !== w && 9 !== w && 11 !== w)return d; if (!e && ((b ? b.ownerDocument || b : v) !== n && m(b), b = b || n, p)) { if (11 !== w && (l = Z.exec(a)))if (f = l[1]) { if (9 === w) { if (!(j = b.getElementById(f)))return d; if (j.id === f)return d.push(j), d } else if (s && (j = s.getElementById(f)) && t(b, j) && j.id === f)return d.push(j), d } else { if (l[2])return G.apply(d, b.getElementsByTagName(a)), d; if ((f = l[3]) && c.getElementsByClassName && b.getElementsByClassName)return G.apply(d, b.getElementsByClassName(f)), d } if (c.qsa && !A[a + " "] && (!q || !q.test(a))) { if (1 !== w) s = b, r = a; else if ("object" !== b.nodeName.toLowerCase()) { (k = b.getAttribute("id")) ? k = k.replace(ba, ca) : b.setAttribute("id", k = u), o = g(a), h = o.length; while (h--)o[h] = "#" + k + " " + sa(o[h]); r = o.join(","), s = $.test(a) && qa(b.parentNode) || b } if (r)try { return G.apply(d, s.querySelectorAll(r)), d } catch (x) { } finally { k === u && b.removeAttribute("id") } } } return i(a.replace(P, "$1"), b, d, e) } function ha() { var a = []; function b(c, e) { return a.push(c + " ") > d.cacheLength && delete b[a.shift()], b[c + " "] = e } return b } function ia(a) { return a[u] = !0, a } function ja(a) { var b = n.createElement("fieldset"); try { return !!a(b) } catch (c) { return !1 } finally { b.parentNode && b.parentNode.removeChild(b), b = null } } function ka(a, b) { var c = a.split("|"), e = c.length; while (e--)d.attrHandle[c[e]] = b } function la(a, b) { var c = b && a, d = c && 1 === a.nodeType && 1 === b.nodeType && a.sourceIndex - b.sourceIndex; if (d)return d; if (c)while (c = c.nextSibling)if (c === b)return -1; return a ? 1 : -1 } function ma(a) { return function (b) { var c = b.nodeName.toLowerCase(); return "input" === c && b.type === a } } function na(a) { return function (b) { var c = b.nodeName.toLowerCase(); return ("input" === c || "button" === c) && b.type === a } } function oa(a) { return function (b) { return "form" in b ? b.parentNode && b.disabled === !1 ? "label" in b ? "label" in b.parentNode ? b.parentNode.disabled === a : b.disabled === a : b.isDisabled === a || b.isDisabled !== !a && ea(b) === a : b.disabled === a : "label" in b && b.disabled === a } } function pa(a) { return ia(function (b) { return b = +b, ia(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 qa(a) { return a && "undefined" != typeof a.getElementsByTagName && a } c = ga.support = {}, f = ga.isXML = function (a) { var b = a && (a.ownerDocument || a).documentElement; return !!b && "HTML" !== b.nodeName }, m = ga.setDocument = function (a) { var b, e, g = a ? a.ownerDocument || a : v; return g !== n && 9 === g.nodeType && g.documentElement ? (n = g, o = n.documentElement, p = !f(n), v !== n && (e = n.defaultView) && e.top !== e && (e.addEventListener ? e.addEventListener("unload", da, !1) : e.attachEvent && e.attachEvent("onunload", da)), c.attributes = ja(function (a) { return a.className = "i", !a.getAttribute("className") }), c.getElementsByTagName = ja(function (a) { return a.appendChild(n.createComment("")), !a.getElementsByTagName("*").length }), c.getElementsByClassName = Y.test(n.getElementsByClassName), c.getById = ja(function (a) { return o.appendChild(a).id = u, !n.getElementsByName || !n.getElementsByName(u).length }), c.getById ? (d.filter.ID = function (a) { var b = a.replace(_, aa); return function (a) { return a.getAttribute("id") === b } }, d.find.ID = function (a, b) { if ("undefined" != typeof b.getElementById && p) { var c = b.getElementById(a); return c ? [c] : [] } }) : (d.filter.ID = function (a) { var b = a.replace(_, aa); return function (a) { var c = "undefined" != typeof a.getAttributeNode && a.getAttributeNode("id"); return c && c.value === b } }, d.find.ID = function (a, b) { if ("undefined" != typeof b.getElementById && p) { var c, d, e, f = b.getElementById(a); if (f) { if (c = f.getAttributeNode("id"), c && c.value === a)return [f]; e = b.getElementsByName(a), d = 0; while (f = e[d++])if (c = f.getAttributeNode("id"), c && c.value === a)return [f] } return [] } }), d.find.TAG = c.getElementsByTagName ? function (a, b) { return "undefined" != typeof b.getElementsByTagName ? b.getElementsByTagName(a) : c.qsa ? b.querySelectorAll(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) { if ("undefined" != typeof b.getElementsByClassName && p)return b.getElementsByClassName(a) }, r = [], q = [], (c.qsa = Y.test(n.querySelectorAll)) && (ja(function (a) { o.appendChild(a).innerHTML = "<a id='" + u + "'></a><select id='" + u + "-\r\\' msallowcapture=''><option selected=''></option></select>", a.querySelectorAll("[msallowcapture^='']").length && q.push("[*^$]=" + K + "*(?:''|\"\")"), a.querySelectorAll("[selected]").length || q.push("\\[" + K + "*(?:value|" + J + ")"), a.querySelectorAll("[id~=" + u + "-]").length || q.push("~="), a.querySelectorAll(":checked").length || q.push(":checked"), a.querySelectorAll("a#" + u + "+*").length || q.push(".#.+[+~]") }), ja(function (a) { a.innerHTML = "<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>"; var b = n.createElement("input"); b.setAttribute("type", "hidden"), a.appendChild(b).setAttribute("name", "D"), a.querySelectorAll("[name=d]").length && q.push("name" + K + "*[*^$|!~]?="), 2 !== a.querySelectorAll(":enabled").length && q.push(":enabled", ":disabled"), o.appendChild(a).disabled = !0, 2 !== a.querySelectorAll(":disabled").length && q.push(":enabled", ":disabled"), a.querySelectorAll("*,:x"), q.push(",.*:") })), (c.matchesSelector = Y.test(s = o.matches || o.webkitMatchesSelector || o.mozMatchesSelector || o.oMatchesSelector || o.msMatchesSelector)) && ja(function (a) { c.disconnectedMatch = s.call(a, "*"), s.call(a, "[s!='']:x"), r.push("!=", N) }), q = q.length && new RegExp(q.join("|")), r = r.length && new RegExp(r.join("|")), b = Y.test(o.compareDocumentPosition), t = b || Y.test(o.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 }, B = b ? function (a, b) { if (a === b)return l = !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 === n || a.ownerDocument === v && t(v, a) ? -1 : b === n || b.ownerDocument === v && t(v, b) ? 1 : k ? I(k, a) - I(k, b) : 0 : 4 & d ? -1 : 1) } : function (a, b) { if (a === b)return l = !0, 0; var c, d = 0, e = a.parentNode, f = b.parentNode, g = [a], h = [b]; if (!e || !f)return a === n ? -1 : b === n ? 1 : e ? -1 : f ? 1 : k ? I(k, a) - I(k, b) : 0; if (e === f)return la(a, b); c = a; while (c = c.parentNode)g.unshift(c); c = b; while (c = c.parentNode)h.unshift(c); while (g[d] === h[d])d++; return d ? la(g[d], h[d]) : g[d] === v ? -1 : h[d] === v ? 1 : 0 }, n) : n }, ga.matches = function (a, b) { return ga(a, null, null, b) }, ga.matchesSelector = function (a, b) { if ((a.ownerDocument || a) !== n && m(a), b = b.replace(S, "='$1']"), c.matchesSelector && p && !A[b + " "] && (!r || !r.test(b)) && (!q || !q.test(b)))try { var d = s.call(a, b); if (d || c.disconnectedMatch || a.document && 11 !== a.document.nodeType)return d } catch (e) { } return ga(b, n, null, [a]).length > 0 }, ga.contains = function (a, b) { return (a.ownerDocument || a) !== n && m(a), t(a, b) }, ga.attr = function (a, b) { (a.ownerDocument || a) !== n && m(a); var e = d.attrHandle[b.toLowerCase()], f = e && C.call(d.attrHandle, b.toLowerCase()) ? e(a, b, !p) : void 0; return void 0 !== f ? f : c.attributes || !p ? a.getAttribute(b) : (f = a.getAttributeNode(b)) && f.specified ? f.value : null }, ga.escape = function (a) { return (a + "").replace(ba, ca) }, ga.error = function (a) { throw new Error("Syntax error, unrecognized expression: " + a) }, ga.uniqueSort = function (a) { var b, d = [], e = 0, f = 0; if (l = !c.detectDuplicates, k = !c.sortStable && a.slice(0), a.sort(B), l) { while (b = a[f++])b === a[f] && (e = d.push(f)); while (e--)a.splice(d[e], 1) } return k = null, a }, e = ga.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 = ga.selectors = { cacheLength: 50, createPseudo: ia, 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(_, aa), a[3] = (a[3] || a[4] || a[5] || "").replace(_, aa), "~=" === 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] || ga.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] && ga.error(a[0]), a }, PSEUDO: function (a) { var b, c = !a[6] && a[2]; return V.CHILD.test(a[0]) ? null : (a[3] ? a[2] = a[4] || a[5] || "" : c && T.test(c) && (b = g(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(_, aa).toLowerCase(); return "*" === a ? function () { return !0 } : function (a) { return a.nodeName && a.nodeName.toLowerCase() === b } }, CLASS: function (a) { var b = y[a + " "]; return b || (b = new RegExp("(^|" + K + ")" + a + "(" + K + "|$)")) && y(a, function (a) { return b.test("string" == typeof a.className && a.className || "undefined" != typeof a.getAttribute && a.getAttribute("class") || "") }) }, ATTR: function (a, b, c) { return function (d) { var e = ga.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.replace(O, " ") + " ").indexOf(c) > -1 : "|=" === b && (e === c || e.slice(0, c.length + 1) === c + "-")) } }, 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(), s = !i && !h, t = !1; if (q) { if (f) { while (p) { m = b; while (m = m[p])if (h ? m.nodeName.toLowerCase() === r : 1 === m.nodeType)return !1; o = p = "only" === a && !o && "nextSibling" } return !0 } if (o = [g ? q.firstChild : q.lastChild], g && s) { m = q, l = m[u] || (m[u] = {}), k = l[m.uniqueID] || (l[m.uniqueID] = {}), j = k[a] || [], n = j[0] === w && j[1], t = n && j[2], m = n && q.childNodes[n]; while (m = ++n && m && m[p] || (t = n = 0) || o.pop())if (1 === m.nodeType && ++t && m === b) { k[a] = [w, n, t]; break } } else if (s && (m = b, l = m[u] || (m[u] = {}), k = l[m.uniqueID] || (l[m.uniqueID] = {}), j = k[a] || [], n = j[0] === w && j[1], t = n), t === !1)while (m = ++n && m && m[p] || (t = n = 0) || o.pop())if ((h ? m.nodeName.toLowerCase() === r : 1 === m.nodeType) && ++t && (s && (l = m[u] || (m[u] = {}), k = l[m.uniqueID] || (l[m.uniqueID] = {}), k[a] = [w, t]), m === b))break; return t -= e, t === d || t % d === 0 && t / d >= 0 } } }, PSEUDO: function (a, b) { var c, e = d.pseudos[a] || d.setFilters[a.toLowerCase()] || ga.error("unsupported pseudo: " + a); return e[u] ? e(b) : e.length > 1 ? (c = [a, a, "", b], d.setFilters.hasOwnProperty(a.toLowerCase()) ? ia(function (a, c) { var d, f = e(a, b), g = f.length; while (g--)d = I(a, f[g]), a[d] = !(c[d] = f[g]) }) : function (a) { return e(a, 0, c) }) : e } }, pseudos: { not: ia(function (a) { var b = [], c = [], d = h(a.replace(P, "$1")); return d[u] ? ia(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), b[0] = null, !c.pop() } }), has: ia(function (a) { return function (b) { return ga(a, b).length > 0 } }), contains: ia(function (a) { return a = a.replace(_, aa), function (b) { return (b.textContent || b.innerText || e(b)).indexOf(a) > -1 } }), lang: ia(function (a) { return U.test(a || "") || ga.error("unsupported lang: " + a), a = a.replace(_, aa).toLowerCase(), function (b) { var c; do if (c = p ? 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 === o }, focus: function (a) { return a === n.activeElement && (!n.hasFocus || n.hasFocus()) && !!(a.type || a.href || ~a.tabIndex) }, enabled: oa(!1), disabled: oa(!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: pa(function () { return [0] }), last: pa(function (a, b) { return [b - 1] }), eq: pa(function (a, b, c) { return [c < 0 ? c + b : c] }), even: pa(function (a, b) { for (var c = 0; c < b; c += 2)a.push(c); return a }), odd: pa(function (a, b) { for (var c = 1; c < b; c += 2)a.push(c); return a }), lt: pa(function (a, b, c) { for (var d = c < 0 ? c + b : c; --d >= 0;)a.push(d); return a }), gt: pa(function (a, b, c) { for (var d = c < 0 ? 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] = ma(b); for (b in{submit: !0, reset: !0})d.pseudos[b] = na(b); function ra() { } ra.prototype = d.filters = d.pseudos, d.setFilters = new ra, g = ga.tokenize = function (a, b) { var c, e, f, g, h, i, j, k = z[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 ? ga.error(a) : z(a, i).slice(0) }; function sa(a) { for (var b = 0, c = a.length, d = ""; b < c; b++)d += a[b].value; return d } function ta(a, b, c) { var d = b.dir, e = b.next, f = e || d, g = c && "parentNode" === f, h = x++; return b.first ? function (b, c, e) { while (b = b[d])if (1 === b.nodeType || g)return a(b, c, e); return !1 } : function (b, c, i) { var j, k, l, m = [w, h]; if (i) { while (b = b[d])if ((1 === b.nodeType || g) && a(b, c, i))return !0 } else while (b = b[d])if (1 === b.nodeType || g)if (l = b[u] || (b[u] = {}), k = l[b.uniqueID] || (l[b.uniqueID] = {}), e && e === b.nodeName.toLowerCase()) b = b[d] || b; else { if ((j = k[f]) && j[0] === w && j[1] === h)return m[2] = j[2]; if (k[f] = m, m[2] = a(b, c, i))return !0 } return !1 } } function ua(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 va(a, b, c) { for (var d = 0, e = b.length; d < e; d++)ga(a, b[d], c); return c } function wa(a, b, c, d, e) { for (var f, g = [], h = 0, i = a.length, j = null != b; h < i; h++)(f = a[h]) && (c && !c(f, d, e) || (g.push(f), j && b.push(h))); return g } function xa(a, b, c, d, e, f) { return d && !d[u] && (d = xa(d)), e && !e[u] && (e = xa(e, f)), ia(function (f, g, h, i) { var j, k, l, m = [], n = [], o = g.length, p = f || va(b || "*", h.nodeType ? [h] : h, []), q = !a || !f && b ? p : wa(p, m, a, h, i), r = c ? e || (f ? a : o || d) ? [] : g : q; if (c && c(q, r, h, i), d) { j = wa(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(f, l) : m[k]) > -1 && (f[j] = !(g[j] = l)) } } else r = wa(r === g ? r.splice(o, r.length) : r), e ? e(null, g, r, i) : G.apply(g, r) }) } function ya(a) { for (var b, c, e, f = a.length, g = d.relative[a[0].type], h = g || d.relative[" "], i = g ? 1 : 0, k = ta(function (a) { return a === b }, h, !0), l = ta(function (a) { return I(b, a) > -1 }, h, !0), m = [function (a, c, d) { var e = !g && (d || c !== j) || ((b = c).nodeType ? k(a, c, d) : l(a, c, d)); return b = null, e }]; i < f; i++)if (c = d.relative[a[i].type]) m = [ta(ua(m), c)]; else { if (c = d.filter[a[i].type].apply(null, a[i].matches), c[u]) { for (e = ++i; e < f; e++)if (d.relative[a[e].type])break; return xa(i > 1 && ua(m), i > 1 && sa(a.slice(0, i - 1).concat({value: " " === a[i - 2].type ? "*" : ""})).replace(P, "$1"), c, i < e && ya(a.slice(i, e)), e < f && ya(a = a.slice(e)), e < f && sa(a)) } m.push(c) } return ua(m) } function za(a, b) { var c = b.length > 0, e = a.length > 0, f = function (f, g, h, i, k) { var l, o, q, r = 0, s = "0", t = f && [], u = [], v = j, x = f || e && d.find.TAG("*", k), y = w += null == v ? 1 : Math.random() || .1, z = x.length; for (k && (j = g === n || g || k); s !== z && null != (l = x[s]); s++) { if (e && l) { o = 0, g || l.ownerDocument === n || (m(l), h = !p); while (q = a[o++])if (q(l, g || n, h)) { i.push(l); break } k && (w = y) } c && ((l = !q && l) && r--, f && t.push(l)) } if (r += s, c && s !== r) { o = 0; while (q = b[o++])q(t, u, g, h); if (f) { if (r > 0)while (s--)t[s] || u[s] || (u[s] = E.call(i)); u = wa(u) } G.apply(i, u), k && !f && u.length > 0 && r + b.length > 1 && ga.uniqueSort(i) } return k && (w = y, j = v), t }; return c ? ia(f) : f } return h = ga.compile = function (a, b) { var c, d = [], e = [], f = A[a + " "]; if (!f) { b || (b = g(a)), c = b.length; while (c--)f = ya(b[c]), f[u] ? d.push(f) : e.push(f); f = A(a, za(e, d)), f.selector = a } return f }, i = ga.select = function (a, b, c, e) { var f, i, j, k, l, m = "function" == typeof a && a, n = !e && g(a = m.selector || a); if (c = c || [], 1 === n.length) { if (i = n[0] = n[0].slice(0), i.length > 2 && "ID" === (j = i[0]).type && 9 === b.nodeType && p && d.relative[i[1].type]) { if (b = (d.find.ID(j.matches[0].replace(_, aa), b) || [])[0], !b)return c; m && (b = b.parentNode), a = a.slice(i.shift().value.length) } f = V.needsContext.test(a) ? 0 : i.length; while (f--) { if (j = i[f], d.relative[k = j.type])break; if ((l = d.find[k]) && (e = l(j.matches[0].replace(_, aa), $.test(i[0].type) && qa(b.parentNode) || b))) { if (i.splice(f, 1), a = e.length && sa(i), !a)return G.apply(c, e), c; break } } } return (m || h(a, n))(e, b, !p, c, !b || $.test(a) && qa(b.parentNode) || b), c }, c.sortStable = u.split("").sort(B).join("") === u, c.detectDuplicates = !!l, m(), c.sortDetached = ja(function (a) { return 1 & a.compareDocumentPosition(n.createElement("fieldset")) }), ja(function (a) { return a.innerHTML = "<a href='#'></a>", "#" === a.firstChild.getAttribute("href") }) || ka("type|href|height|width", function (a, b, c) { if (!c)return a.getAttribute(b, "type" === b.toLowerCase() ? 1 : 2) }), c.attributes && ja(function (a) { return a.innerHTML = "<input/>", a.firstChild.setAttribute("value", ""), "" === a.firstChild.getAttribute("value") }) || ka("value", function (a, b, c) { if (!c && "input" === a.nodeName.toLowerCase())return a.defaultValue }), ja(function (a) { return null == a.getAttribute("disabled") }) || ka(J, function (a, b, c) { var d; if (!c)return a[b] === !0 ? b.toLowerCase() : (d = a.getAttributeNode(b)) && d.specified ? d.value : null }), ga }(a); r.find = x, r.expr = x.selectors, r.expr[":"] = r.expr.pseudos, r.uniqueSort = r.unique = x.uniqueSort, r.text = x.getText, r.isXMLDoc = x.isXML, r.contains = x.contains, r.escapeSelector = x.escape; var y = function (a, b, c) { var d = [], e = void 0 !== c; while ((a = a[b]) && 9 !== a.nodeType)if (1 === a.nodeType) { if (e && r(a).is(c))break; d.push(a) } return d }, z = function (a, b) { for (var c = []; a; a = a.nextSibling)1 === a.nodeType && a !== b && c.push(a); return c }, A = r.expr.match.needsContext; function B(a, b) { return a.nodeName && a.nodeName.toLowerCase() === b.toLowerCase() } var C = /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i, D = /^.[^:#\[\.,]*$/; function E(a, b, c) { return r.isFunction(b) ? r.grep(a, function (a, d) { return !!b.call(a, d, a) !== c }) : b.nodeType ? r.grep(a, function (a) { return a === b !== c }) : "string" != typeof b ? r.grep(a, function (a) { return i.call(b, a) > -1 !== c }) : D.test(b) ? r.filter(b, a, c) : (b = r.filter(b, a), r.grep(a, function (a) { return i.call(b, a) > -1 !== c && 1 === a.nodeType })) } r.filter = function (a, b, c) { var d = b[0]; return c && (a = ":not(" + a + ")"), 1 === b.length && 1 === d.nodeType ? r.find.matchesSelector(d, a) ? [d] : [] : r.find.matches(a, r.grep(b, function (a) { return 1 === a.nodeType })) }, r.fn.extend({ find: function (a) { var b, c, d = this.length, e = this; if ("string" != typeof a)return this.pushStack(r(a).filter(function () { for (b = 0; b < d; b++)if (r.contains(e[b], this))return !0 })); for (c = this.pushStack([]), b = 0; b < d; b++)r.find(a, e[b], c); return d > 1 ? r.uniqueSort(c) : c }, filter: function (a) { return this.pushStack(E(this, a || [], !1)) }, not: function (a) { return this.pushStack(E(this, a || [], !0)) }, is: function (a) { return !!E(this, "string" == typeof a && A.test(a) ? r(a) : a || [], !1).length } }); var F, G = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, H = r.fn.init = function (a, b, c) { var e, f; if (!a)return this; if (c = c || F, "string" == typeof a) { if (e = "<" === a[0] && ">" === a[a.length - 1] && a.length >= 3 ? [null, a, null] : G.exec(a), !e || !e[1] && b)return !b || b.jquery ? (b || c).find(a) : this.constructor(b).find(a); if (e[1]) { if (b = b instanceof r ? b[0] : b, r.merge(this, r.parseHTML(e[1], b && b.nodeType ? b.ownerDocument || b : d, !0)), C.test(e[1]) && r.isPlainObject(b))for (e in b)r.isFunction(this[e]) ? this[e](b[e]) : this.attr(e, b[e]); return this } return f = d.getElementById(e[2]), f && (this[0] = f, this.length = 1), this } return a.nodeType ? (this[0] = a, this.length = 1, this) : r.isFunction(a) ? void 0 !== c.ready ? c.ready(a) : a(r) : r.makeArray(a, this) }; H.prototype = r.fn, F = r(d); var I = /^(?:parents|prev(?:Until|All))/, J = {children: !0, contents: !0, next: !0, prev: !0}; r.fn.extend({ has: function (a) { var b = r(a, this), c = b.length; return this.filter(function () { for (var a = 0; a < c; a++)if (r.contains(this, b[a]))return !0 }) }, closest: function (a, b) { var c, d = 0, e = this.length, f = [], g = "string" != typeof a && r(a); if (!A.test(a))for (; d < e; d++)for (c = this[d]; c && c !== b; c = c.parentNode)if (c.nodeType < 11 && (g ? g.index(c) > -1 : 1 === c.nodeType && r.find.matchesSelector(c, a))) { f.push(c); break } return this.pushStack(f.length > 1 ? r.uniqueSort(f) : f) }, index: function (a) { return a ? "string" == typeof a ? i.call(r(a), this[0]) : i.call(this, a.jquery ? a[0] : a) : this[0] && this[0].parentNode ? this.first().prevAll().length : -1 }, add: function (a, b) { return this.pushStack(r.uniqueSort(r.merge(this.get(), r(a, b)))) }, addBack: function (a) { return this.add(null == a ? this.prevObject : this.prevObject.filter(a)) } }); function K(a, b) { while ((a = a[b]) && 1 !== a.nodeType); return a } r.each({ parent: function (a) { var b = a.parentNode; return b && 11 !== b.nodeType ? b : null }, parents: function (a) { return y(a, "parentNode") }, parentsUntil: function (a, b, c) { return y(a, "parentNode", c) }, next: function (a) { return K(a, "nextSibling") }, prev: function (a) { return K(a, "previousSibling") }, nextAll: function (a) { return y(a, "nextSibling") }, prevAll: function (a) { return y(a, "previousSibling") }, nextUntil: function (a, b, c) { return y(a, "nextSibling", c) }, prevUntil: function (a, b, c) { return y(a, "previousSibling", c) }, siblings: function (a) { return z((a.parentNode || {}).firstChild, a) }, children: function (a) { return z(a.firstChild) }, contents: function (a) { return B(a, "iframe") ? a.contentDocument : (B(a, "template") && (a = a.content || a), r.merge([], a.childNodes)) } }, function (a, b) { r.fn[a] = function (c, d) { var e = r.map(this, b, c); return "Until" !== a.slice(-5) && (d = c), d && "string" == typeof d && (e = r.filter(d, e)), this.length > 1 && (J[a] || r.uniqueSort(e), I.test(a) && e.reverse()), this.pushStack(e) } }); var L = /[^\x20\t\r\n\f]+/g; function M(a) { var b = {}; return r.each(a.match(L) || [], function (a, c) { b[c] = !0 }), b } r.Callbacks = function (a) { a = "string" == typeof a ? M(a) : r.extend({}, a); var b, c, d, e, f = [], g = [], h = -1, i = function () { for (e = e || a.once, d = b = !0; g.length; h = -1) { c = g.shift(); while (++h < f.length)f[h].apply(c[0], c[1]) === !1 && a.stopOnFalse && (h = f.length, c = !1) } a.memory || (c = !1), b = !1, e && (f = c ? [] : "") }, j = { add: function () { return f && (c && !b && (h = f.length - 1, g.push(c)), function d(b) { r.each(b, function (b, c) { r.isFunction(c) ? a.unique && j.has(c) || f.push(c) : c && c.length && "string" !== r.type(c) && d(c) }) }(arguments), c && !b && i()), this }, remove: function () { return r.each(arguments, function (a, b) { var c; while ((c = r.inArray(b, f, c)) > -1)f.splice(c, 1), c <= h && h-- }), this }, has: function (a) { return a ? r.inArray(a, f) > -1 : f.length > 0 }, empty: function () { return f && (f = []), this }, disable: function () { return e = g = [], f = c = "", this }, disabled: function () { return !f }, lock: function () { return e = g = [], c || b || (f = c = ""), this }, locked: function () { return !!e }, fireWith: function (a, c) { return e || (c = c || [], c = [a, c.slice ? c.slice() : c], g.push(c), b || i()), this }, fire: function () { return j.fireWith(this, arguments), this }, fired: function () { return !!d } }; return j }; function N(a) { return a } function O(a) { throw a } function P(a, b, c, d) { var e; try { a && r.isFunction(e = a.promise) ? e.call(a).done(b).fail(c) : a && r.isFunction(e = a.then) ? e.call(a, b, c) : b.apply(void 0, [a].slice(d)) } catch (a) { c.apply(void 0, [a]) } } r.extend({ Deferred: function (b) { var c = [["notify", "progress", r.Callbacks("memory"), r.Callbacks("memory"), 2], ["resolve", "done", r.Callbacks("once memory"), r.Callbacks("once memory"), 0, "resolved"], ["reject", "fail", r.Callbacks("once memory"), r.Callbacks("once memory"), 1, "rejected"]], d = "pending", e = { state: function () { return d }, always: function () { return f.done(arguments).fail(arguments), this }, "catch": function (a) { return e.then(null, a) }, pipe: function () { var a = arguments; return r.Deferred(function (b) { r.each(c, function (c, d) { var e = r.isFunction(a[d[4]]) && a[d[4]]; f[d[1]](function () { var a = e && e.apply(this, arguments); a && r.isFunction(a.promise) ? a.promise().progress(b.notify).done(b.resolve).fail(b.reject) : b[d[0] + "With"](this, e ? [a] : arguments) }) }), a = null }).promise() }, then: function (b, d, e) { var f = 0; function g(b, c, d, e) { return function () { var h = this, i = arguments, j = function () { var a, j; if (!(b < f)) { if (a = d.apply(h, i), a === c.promise())throw new TypeError("Thenable self-resolution"); j = a && ("object" == typeof a || "function" == typeof a) && a.then, r.isFunction(j) ? e ? j.call(a, g(f, c, N, e), g(f, c, O, e)) : (f++, j.call(a, g(f, c, N, e), g(f, c, O, e), g(f, c, N, c.notifyWith))) : (d !== N && (h = void 0, i = [a]), (e || c.resolveWith)(h, i)) } }, k = e ? j : function () { try { j() } catch (a) { r.Deferred.exceptionHook && r.Deferred.exceptionHook(a, k.stackTrace), b + 1 >= f && (d !== O && (h = void 0, i = [a]), c.rejectWith(h, i)) } }; b ? k() : (r.Deferred.getStackHook && (k.stackTrace = r.Deferred.getStackHook()), a.setTimeout(k)) } } return r.Deferred(function (a) { c[0][3].add(g(0, a, r.isFunction(e) ? e : N, a.notifyWith)), c[1][3].add(g(0, a, r.isFunction(b) ? b : N)), c[2][3].add(g(0, a, r.isFunction(d) ? d : O)) }).promise() }, promise: function (a) { return null != a ? r.extend(a, e) : e } }, f = {}; return r.each(c, function (a, b) { var g = b[2], h = b[5]; e[b[1]] = g.add, h && g.add(function () { d = h }, c[3 - a][2].disable, c[0][2].lock), g.add(b[3].fire), f[b[0]] = function () { return f[b[0] + "With"](this === f ? void 0 : this, arguments), this }, f[b[0] + "With"] = g.fireWith }), e.promise(f), b && b.call(f, f), f }, when: function (a) { var b = arguments.length, c = b, d = Array(c), e = f.call(arguments), g = r.Deferred(), h = function (a) { return function (c) { d[a] = this, e[a] = arguments.length > 1 ? f.call(arguments) : c, --b || g.resolveWith(d, e) } }; if (b <= 1 && (P(a, g.done(h(c)).resolve, g.reject, !b), "pending" === g.state() || r.isFunction(e[c] && e[c].then)))return g.then(); while (c--)P(e[c], h(c), g.reject); return g.promise() } }); var Q = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; r.Deferred.exceptionHook = function (b, c) { a.console && a.console.warn && b && Q.test(b.name) && a.console.warn("jQuery.Deferred exception: " + b.message, b.stack, c) }, r.readyException = function (b) { a.setTimeout(function () { throw b }) }; var R = r.Deferred(); r.fn.ready = function (a) { return R.then(a)["catch"](function (a) { r.readyException(a) }), this }, r.extend({ isReady: !1, readyWait: 1, ready: function (a) { (a === !0 ? --r.readyWait : r.isReady) || (r.isReady = !0, a !== !0 && --r.readyWait > 0 || R.resolveWith(d, [r])) } }), r.ready.then = R.then; function S() { d.removeEventListener("DOMContentLoaded", S), a.removeEventListener("load", S), r.ready() } "complete" === d.readyState || "loading" !== d.readyState && !d.documentElement.doScroll ? a.setTimeout(r.ready) : (d.addEventListener("DOMContentLoaded", S), a.addEventListener("load", S)); var T = function (a, b, c, d, e, f, g) { var h = 0, i = a.length, j = null == c; if ("object" === r.type(c)) { e = !0; for (h in c)T(a, b, h, c[h], !0, f, g) } else if (void 0 !== d && (e = !0, r.isFunction(d) || (g = !0), j && (g ? (b.call(a, d), b = null) : (j = b, b = function (a, b, c) { return j.call(r(a), c) })), b))for (; h < i; 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 }, U = function (a) { return 1 === a.nodeType || 9 === a.nodeType || !+a.nodeType }; function V() { this.expando = r.expando + V.uid++ } V.uid = 1, V.prototype = { cache: function (a) { var b = a[this.expando]; return b || (b = {}, U(a) && (a.nodeType ? a[this.expando] = b : Object.defineProperty(a, this.expando, { value: b, configurable: !0 }))), b }, set: function (a, b, c) { var d, e = this.cache(a); if ("string" == typeof b) e[r.camelCase(b)] = c; else for (d in b)e[r.camelCase(d)] = b[d]; return e }, get: function (a, b) { return void 0 === b ? this.cache(a) : a[this.expando] && a[this.expando][r.camelCase(b)] }, access: function (a, b, c) { return void 0 === b || b && "string" == typeof b && void 0 === c ? this.get(a, b) : (this.set(a, b, c), void 0 !== c ? c : b) }, remove: function (a, b) { var c, d = a[this.expando]; if (void 0 !== d) { if (void 0 !== b) { Array.isArray(b) ? b = b.map(r.camelCase) : (b = r.camelCase(b), b = b in d ? [b] : b.match(L) || []), c = b.length; while (c--)delete d[b[c]] } (void 0 === b || r.isEmptyObject(d)) && (a.nodeType ? a[this.expando] = void 0 : delete a[this.expando]) } }, hasData: function (a) { var b = a[this.expando]; return void 0 !== b && !r.isEmptyObject(b) } }; var W = new V, X = new V, Y = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, Z = /[A-Z]/g; function $(a) { return "true" === a || "false" !== a && ("null" === a ? null : a === +a + "" ? +a : Y.test(a) ? JSON.parse(a) : a) } function _(a, b, c) { var d; if (void 0 === c && 1 === a.nodeType)if (d = "data-" + b.replace(Z, "-$&").toLowerCase(), c = a.getAttribute(d), "string" == typeof c) { try { c = $(c) } catch (e) { } X.set(a, b, c) } else c = void 0; return c } r.extend({ hasData: function (a) { return X.hasData(a) || W.hasData(a) }, data: function (a, b, c) { return X.access(a, b, c) }, removeData: function (a, b) { X.remove(a, b) }, _data: function (a, b, c) { return W.access(a, b, c) }, _removeData: function (a, b) { W.remove(a, b) } }), r.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 = X.get(f), 1 === f.nodeType && !W.get(f, "hasDataAttrs"))) { c = g.length; while (c--)g[c] && (d = g[c].name, 0 === d.indexOf("data-") && (d = r.camelCase(d.slice(5)), _(f, d, e[d]))); W.set(f, "hasDataAttrs", !0) } return e } return "object" == typeof a ? this.each(function () { X.set(this, a) }) : T(this, function (b) { var c; if (f && void 0 === b) { if (c = X.get(f, a), void 0 !== c)return c; if (c = _(f, a), void 0 !== c)return c } else this.each(function () { X.set(this, a, b) }) }, null, b, arguments.length > 1, null, !0) }, removeData: function (a) { return this.each(function () { X.remove(this, a) }) } }), r.extend({ queue: function (a, b, c) { var d; if (a)return b = (b || "fx") + "queue", d = W.get(a, b), c && (!d || Array.isArray(c) ? d = W.access(a, b, r.makeArray(c)) : d.push(c)), d || [] }, dequeue: function (a, b) { b = b || "fx"; var c = r.queue(a, b), d = c.length, e = c.shift(), f = r._queueHooks(a, b), g = function () { r.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 W.get(a, c) || W.access(a, c, { empty: r.Callbacks("once memory").add(function () { W.remove(a, [b + "queue", c]) }) }) } }), r.fn.extend({ queue: function (a, b) { var c = 2; return "string" != typeof a && (b = a, a = "fx", c--), arguments.length < c ? r.queue(this[0], a) : void 0 === b ? this : this.each(function () { var c = r.queue(this, a, b); r._queueHooks(this, a), "fx" === a && "inprogress" !== c[0] && r.dequeue(this, a) }) }, dequeue: function (a) { return this.each(function () { r.dequeue(this, a) }) }, clearQueue: function (a) { return this.queue(a || "fx", []) }, promise: function (a, b) { var c, d = 1, e = r.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 = W.get(f[g], a + "queueHooks"), c && c.empty && (d++, c.empty.add(h)); return h(), e.promise(b) } }); var aa = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, ba = new RegExp("^(?:([+-])=|)(" + aa + ")([a-z%]*)$", "i"), ca = ["Top", "Right", "Bottom", "Left"], da = function (a, b) { return a = b || a, "none" === a.style.display || "" === a.style.display && r.contains(a.ownerDocument, a) && "none" === r.css(a, "display") }, ea = 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 }; function fa(a, b, c, d) { var e, f = 1, g = 20, h = d ? function () { return d.cur() } : function () { return r.css(a, b, "") }, i = h(), j = c && c[3] || (r.cssNumber[b] ? "" : "px"), k = (r.cssNumber[b] || "px" !== j && +i) && ba.exec(r.css(a, b)); if (k && k[3] !== j) { j = j || k[3], c = c || [], k = +i || 1; do f = f || ".5", k /= f, r.style(a, b, k + j); while (f !== (f = h() / i) && 1 !== f && --g) } return c && (k = +k || +i || 0, e = c[1] ? k + (c[1] + 1) * c[2] : +c[2], d && (d.unit = j, d.start = k, d.end = e)), e } var ga = {}; function ha(a) { var b, c = a.ownerDocument, d = a.nodeName, e = ga[d]; return e ? e : (b = c.body.appendChild(c.createElement(d)), e = r.css(b, "display"), b.parentNode.removeChild(b), "none" === e && (e = "block"), ga[d] = e, e) } function ia(a, b) { for (var c, d, e = [], f = 0, g = a.length; f < g; f++)d = a[f], d.style && (c = d.style.display, b ? ("none" === c && (e[f] = W.get(d, "display") || null, e[f] || (d.style.display = "")), "" === d.style.display && da(d) && (e[f] = ha(d))) : "none" !== c && (e[f] = "none", W.set(d, "display", c))); for (f = 0; f < g; f++)null != e[f] && (a[f].style.display = e[f]); return a } r.fn.extend({ show: function () { return ia(this, !0) }, hide: function () { return ia(this) }, toggle: function (a) { return "boolean" == typeof a ? a ? this.show() : this.hide() : this.each(function () { da(this) ? r(this).show() : r(this).hide() }) } }); var ja = /^(?:checkbox|radio)$/i, ka = /<([a-z][^\/\0>\x20\t\r\n\f]+)/i, la = /^$|\/(?:java|ecma)script/i, ma = { option: [1, "<select multiple='multiple'>", "</select>"], thead: [1, "<table>", "</table>"], col: [2, "<table><colgroup>", "</colgroup></table>"], tr: [2, "<table><tbody>", "</tbody></table>"], td: [3, "<table><tbody><tr>", "</tr></tbody></table>"], _default: [0, "", ""] }; ma.optgroup = ma.option, ma.tbody = ma.tfoot = ma.colgroup = ma.caption = ma.thead, ma.th = ma.td; function na(a, b) { var c; return c = "undefined" != typeof a.getElementsByTagName ? a.getElementsByTagName(b || "*") : "undefined" != typeof a.querySelectorAll ? a.querySelectorAll(b || "*") : [], void 0 === b || b && B(a, b) ? r.merge([a], c) : c } function oa(a, b) { for (var c = 0, d = a.length; c < d; c++)W.set(a[c], "globalEval", !b || W.get(b[c], "globalEval")) } var pa = /<|&#?\w+;/; function qa(a, b, c, d, e) { for (var f, g, h, i, j, k, l = b.createDocumentFragment(), m = [], n = 0, o = a.length; n < o; n++)if (f = a[n], f || 0 === f)if ("object" === r.type(f)) r.merge(m, f.nodeType ? [f] : f); else if (pa.test(f)) { g = g || l.appendChild(b.createElement("div")), h = (ka.exec(f) || ["", ""])[1].toLowerCase(), i = ma[h] || ma._default, g.innerHTML = i[1] + r.htmlPrefilter(f) + i[2], k = i[0]; while (k--)g = g.lastChild; r.merge(m, g.childNodes), g = l.firstChild, g.textContent = "" } else m.push(b.createTextNode(f)); l.textContent = "", n = 0; while (f = m[n++])if (d && r.inArray(f, d) > -1) e && e.push(f); else if (j = r.contains(f.ownerDocument, f), g = na(l.appendChild(f), "script"), j && oa(g), c) { k = 0; while (f = g[k++])la.test(f.type || "") && c.push(f) } return l } !function () { var a = d.createDocumentFragment(), b = a.appendChild(d.createElement("div")), c = d.createElement("input"); c.setAttribute("type", "radio"), c.setAttribute("checked", "checked"), c.setAttribute("name", "t"), b.appendChild(c), o.checkClone = b.cloneNode(!0).cloneNode(!0).lastChild.checked, b.innerHTML = "<textarea>x</textarea>", o.noCloneChecked = !!b.cloneNode(!0).lastChild.defaultValue }(); var ra = d.documentElement, sa = /^key/, ta = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, ua = /^([^.]*)(?:\.(.+)|)/; function va() { return !0 } function wa() { return !1 } function xa() { try { return d.activeElement } catch (a) { } } function ya(a, b, c, d, e, f) { var g, h; if ("object" == typeof b) { "string" != typeof c && (d = d || c, c = void 0); for (h in b)ya(a, h, c, d, b[h], f); return a } if (null == d && null == e ? (e = c, d = c = void 0) : null == e && ("string" == typeof c ? (e = d, d = void 0) : (e = d, d = c, c = void 0)), e === !1) e = wa; else if (!e)return a; return 1 === f && (g = e, e = function (a) { return r().off(a), g.apply(this, arguments) }, e.guid = g.guid || (g.guid = r.guid++)), a.each(function () { r.event.add(this, b, e, d, c) }) } r.event = { global: {}, add: function (a, b, c, d, e) { var f, g, h, i, j, k, l, m, n, o, p, q = W.get(a); if (q) { c.handler && (f = c, c = f.handler, e = f.selector), e && r.find.matchesSelector(ra, e), c.guid || (c.guid = r.guid++), (i = q.events) || (i = q.events = {}), (g = q.handle) || (g = q.handle = function (b) { return "undefined" != typeof r && r.event.triggered !== b.type ? r.event.dispatch.apply(a, arguments) : void 0 }), b = (b || "").match(L) || [""], j = b.length; while (j--)h = ua.exec(b[j]) || [], n = p = h[1], o = (h[2] || "").split(".").sort(), n && (l = r.event.special[n] || {}, n = (e ? l.delegateType : l.bindType) || n, l = r.event.special[n] || {}, k = r.extend({ type: n, origType: p, data: d, handler: c, guid: c.guid, selector: e, needsContext: e && r.expr.match.needsContext.test(e), namespace: o.join(".") }, f), (m = i[n]) || (m = i[n] = [], m.delegateCount = 0, l.setup && l.setup.call(a, d, o, g) !== !1 || a.addEventListener && a.addEventListener(n, g)), l.add && (l.add.call(a, k), k.handler.guid || (k.handler.guid = c.guid)), e ? m.splice(m.delegateCount++, 0, k) : m.push(k), r.event.global[n] = !0) } }, remove: function (a, b, c, d, e) { var f, g, h, i, j, k, l, m, n, o, p, q = W.hasData(a) && W.get(a); if (q && (i = q.events)) { b = (b || "").match(L) || [""], j = b.length; while (j--)if (h = ua.exec(b[j]) || [], n = p = h[1], o = (h[2] || "").split(".").sort(), n) { l = r.event.special[n] || {}, n = (d ? l.delegateType : l.bindType) || n, m = i[n] || [], h = h[2] && new RegExp("(^|\\.)" + o.join("\\.(?:.*\\.|)") + "(\\.|$)"), g = f = m.length; while (f--)k = m[f], !e && p !== k.origType || c && c.guid !== k.guid || h && !h.test(k.namespace) || d && d !== k.selector && ("**" !== d || !k.selector) || (m.splice(f, 1), k.selector && m.delegateCount--, l.remove && l.remove.call(a, k)); g && !m.length && (l.teardown && l.teardown.call(a, o, q.handle) !== !1 || r.removeEvent(a, n, q.handle), delete i[n]) } else for (n in i)r.event.remove(a, n + b[j], c, d, !0); r.isEmptyObject(i) && W.remove(a, "handle events") } }, dispatch: function (a) { var b = r.event.fix(a), c, d, e, f, g, h, i = new Array(arguments.length), j = (W.get(this, "events") || {})[b.type] || [], k = r.event.special[b.type] || {}; for (i[0] = b, c = 1; c < arguments.length; c++)i[c] = arguments[c]; if (b.delegateTarget = this, !k.preDispatch || k.preDispatch.call(this, b) !== !1) { h = r.event.handlers.call(this, b, j), c = 0; while ((f = h[c++]) && !b.isPropagationStopped()) { b.currentTarget = f.elem, d = 0; while ((g = f.handlers[d++]) && !b.isImmediatePropagationStopped())b.rnamespace && !b.rnamespace.test(g.namespace) || (b.handleObj = g, b.data = g.data, e = ((r.event.special[g.origType] || {}).handle || g.handler).apply(f.elem, i), void 0 !== e && (b.result = e) === !1 && (b.preventDefault(), b.stopPropagation())) } return k.postDispatch && k.postDispatch.call(this, b), b.result } }, handlers: function (a, b) { var c, d, e, f, g, h = [], i = b.delegateCount, j = a.target; if (i && j.nodeType && !("click" === a.type && a.button >= 1))for (; j !== this; j = j.parentNode || this)if (1 === j.nodeType && ("click" !== a.type || j.disabled !== !0)) { for (f = [], g = {}, c = 0; c < i; c++)d = b[c], e = d.selector + " ", void 0 === g[e] && (g[e] = d.needsContext ? r(e, this).index(j) > -1 : r.find(e, this, null, [j]).length), g[e] && f.push(d); f.length && h.push({elem: j, handlers: f}) } return j = this, i < b.length && h.push({elem: j, handlers: b.slice(i)}), h }, addProp: function (a, b) { Object.defineProperty(r.Event.prototype, a, { enumerable: !0, configurable: !0, get: r.isFunction(b) ? function () { if (this.originalEvent)return b(this.originalEvent) } : function () { if (this.originalEvent)return this.originalEvent[a] }, set: function (b) { Object.defineProperty(this, a, {enumerable: !0, configurable: !0, writable: !0, value: b}) } }) }, fix: function (a) { return a[r.expando] ? a : new r.Event(a) }, special: { load: {noBubble: !0}, focus: { trigger: function () { if (this !== xa() && this.focus)return this.focus(), !1 }, delegateType: "focusin" }, blur: { trigger: function () { if (this === xa() && this.blur)return this.blur(), !1 }, delegateType: "focusout" }, click: { trigger: function () { if (ja.test(this.type) && this.click && B(this, "input"))return this.click(), !1 }, _default: function (a) { return B(a.target, "a") } }, beforeunload: { postDispatch: function (a) { void 0 !== a.result && a.originalEvent && (a.originalEvent.returnValue = a.result) } } } }, r.removeEvent = function (a, b, c) { a.removeEventListener && a.removeEventListener(b, c) }, r.Event = function (a, b) { return this instanceof r.Event ? (a && a.type ? (this.originalEvent = a, this.type = a.type, this.isDefaultPrevented = a.defaultPrevented || void 0 === a.defaultPrevented && a.returnValue === !1 ? va : wa, this.target = a.target && 3 === a.target.nodeType ? a.target.parentNode : a.target, this.currentTarget = a.currentTarget, this.relatedTarget = a.relatedTarget) : this.type = a, b && r.extend(this, b), this.timeStamp = a && a.timeStamp || r.now(), void(this[r.expando] = !0)) : new r.Event(a, b) }, r.Event.prototype = { constructor: r.Event, isDefaultPrevented: wa, isPropagationStopped: wa, isImmediatePropagationStopped: wa, isSimulated: !1, preventDefault: function () { var a = this.originalEvent; this.isDefaultPrevented = va, a && !this.isSimulated && a.preventDefault() }, stopPropagation: function () { var a = this.originalEvent; this.isPropagationStopped = va, a && !this.isSimulated && a.stopPropagation() }, stopImmediatePropagation: function () { var a = this.originalEvent; this.isImmediatePropagationStopped = va, a && !this.isSimulated && a.stopImmediatePropagation(), this.stopPropagation() } }, r.each({ altKey: !0, bubbles: !0, cancelable: !0, changedTouches: !0, ctrlKey: !0, detail: !0, eventPhase: !0, metaKey: !0, pageX: !0, pageY: !0, shiftKey: !0, view: !0, "char": !0, charCode: !0, key: !0, keyCode: !0, button: !0, buttons: !0, clientX: !0, clientY: !0, offsetX: !0, offsetY: !0, pointerId: !0, pointerType: !0, screenX: !0, screenY: !0, targetTouches: !0, toElement: !0, touches: !0, which: function (a) { var b = a.button; return null == a.which && sa.test(a.type) ? null != a.charCode ? a.charCode : a.keyCode : !a.which && void 0 !== b && ta.test(a.type) ? 1 & b ? 1 : 2 & b ? 3 : 4 & b ? 2 : 0 : a.which } }, r.event.addProp), r.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function (a, b) { r.event.special[a] = { delegateType: b, bindType: b, handle: function (a) { var c, d = this, e = a.relatedTarget, f = a.handleObj; return e && (e === d || r.contains(d, e)) || (a.type = f.origType, c = f.handler.apply(this, arguments), a.type = b), c } } }), r.fn.extend({ on: function (a, b, c, d) { return ya(this, a, b, c, d) }, one: function (a, b, c, d) { return ya(this, a, b, c, d, 1) }, off: function (a, b, c) { var d, e; if (a && a.preventDefault && a.handleObj)return d = a.handleObj, r(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 = wa), this.each(function () { r.event.remove(this, a, c, b) }) } }); var za = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, Aa = /<script|<style|<link/i, Ba = /checked\s*(?:[^=]|=\s*.checked.)/i, Ca = /^true\/(.*)/, Da = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g; function Ea(a, b) { return B(a, "table") && B(11 !== b.nodeType ? b : b.firstChild, "tr") ? r(">tbody", a)[0] || a : a } function Fa(a) { return a.type = (null !== a.getAttribute("type")) + "/" + a.type, a } function Ga(a) { var b = Ca.exec(a.type); return b ? a.type = b[1] : a.removeAttribute("type"), a } function Ha(a, b) { var c, d, e, f, g, h, i, j; if (1 === b.nodeType) { if (W.hasData(a) && (f = W.access(a), g = W.set(b, f), j = f.events)) { delete g.handle, g.events = {}; for (e in j)for (c = 0, d = j[e].length; c < d; c++)r.event.add(b, e, j[e][c]) } X.hasData(a) && (h = X.access(a), i = r.extend({}, h), X.set(b, i)) } } function Ia(a, b) { var c = b.nodeName.toLowerCase(); "input" === c && ja.test(a.type) ? b.checked = a.checked : "input" !== c && "textarea" !== c || (b.defaultValue = a.defaultValue) } function Ja(a, b, c, d) { b = g.apply([], b); var e, f, h, i, j, k, l = 0, m = a.length, n = m - 1, q = b[0], s = r.isFunction(q); if (s || m > 1 && "string" == typeof q && !o.checkClone && Ba.test(q))return a.each(function (e) { var f = a.eq(e); s && (b[0] = q.call(this, e, f.html())), Ja(f, b, c, d) }); if (m && (e = qa(b, a[0].ownerDocument, !1, a, d), f = e.firstChild, 1 === e.childNodes.length && (e = f), f || d)) { for (h = r.map(na(e, "script"), Fa), i = h.length; l < m; l++)j = e, l !== n && (j = r.clone(j, !0, !0), i && r.merge(h, na(j, "script"))), c.call(a[l], j, l); if (i)for (k = h[h.length - 1].ownerDocument, r.map(h, Ga), l = 0; l < i; l++)j = h[l], la.test(j.type || "") && !W.access(j, "globalEval") && r.contains(k, j) && (j.src ? r._evalUrl && r._evalUrl(j.src) : p(j.textContent.replace(Da, ""), k)) } return a } function Ka(a, b, c) { for (var d, e = b ? r.filter(b, a) : a, f = 0; null != (d = e[f]); f++)c || 1 !== d.nodeType || r.cleanData(na(d)), d.parentNode && (c && r.contains(d.ownerDocument, d) && oa(na(d, "script")), d.parentNode.removeChild(d)); return a } r.extend({ htmlPrefilter: function (a) { return a.replace(za, "<$1></$2>") }, clone: function (a, b, c) { var d, e, f, g, h = a.cloneNode(!0), i = r.contains(a.ownerDocument, a); if (!(o.noCloneChecked || 1 !== a.nodeType && 11 !== a.nodeType || r.isXMLDoc(a)))for (g = na(h), f = na(a), d = 0, e = f.length; d < e; d++)Ia(f[d], g[d]); if (b)if (c)for (f = f || na(a), g = g || na(h), d = 0, e = f.length; d < e; d++)Ha(f[d], g[d]); else Ha(a, h); return g = na(h, "script"), g.length > 0 && oa(g, !i && na(a, "script")), h }, cleanData: function (a) { for (var b, c, d, e = r.event.special, f = 0; void 0 !== (c = a[f]); f++)if (U(c)) { if (b = c[W.expando]) { if (b.events)for (d in b.events)e[d] ? r.event.remove(c, d) : r.removeEvent(c, d, b.handle); c[W.expando] = void 0 } c[X.expando] && (c[X.expando] = void 0) } } }), r.fn.extend({ detach: function (a) { return Ka(this, a, !0) }, remove: function (a) { return Ka(this, a) }, text: function (a) { return T(this, function (a) { return void 0 === a ? r.text(this) : this.empty().each(function () { 1 !== this.nodeType && 11 !== this.nodeType && 9 !== this.nodeType || (this.textContent = a) }) }, null, a, arguments.length) }, append: function () { return Ja(this, arguments, function (a) { if (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) { var b = Ea(this, a); b.appendChild(a) } }) }, prepend: function () { return Ja(this, arguments, function (a) { if (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) { var b = Ea(this, a); b.insertBefore(a, b.firstChild) } }) }, before: function () { return Ja(this, arguments, function (a) { this.parentNode && this.parentNode.insertBefore(a, this) }) }, after: function () { return Ja(this, arguments, function (a) { this.parentNode && this.parentNode.insertBefore(a, this.nextSibling) }) }, empty: function () { for (var a, b = 0; null != (a = this[b]); b++)1 === a.nodeType && (r.cleanData(na(a, !1)), a.textContent = ""); return this }, clone: function (a, b) { return a = null != a && a, b = null == b ? a : b, this.map(function () { return r.clone(this, a, b) }) }, html: function (a) { return T(this, function (a) { var b = this[0] || {}, c = 0, d = this.length; if (void 0 === a && 1 === b.nodeType)return b.innerHTML; if ("string" == typeof a && !Aa.test(a) && !ma[(ka.exec(a) || ["", ""])[1].toLowerCase()]) { a = r.htmlPrefilter(a); try { for (; c < d; c++)b = this[c] || {}, 1 === b.nodeType && (r.cleanData(na(b, !1)), b.innerHTML = a); b = 0 } catch (e) { } } b && this.empty().append(a) }, null, a, arguments.length) }, replaceWith: function () { var a = []; return Ja(this, arguments, function (b) { var c = this.parentNode; r.inArray(this, a) < 0 && (r.cleanData(na(this)), c && c.replaceChild(b, this)) }, a) } }), r.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function (a, b) { r.fn[a] = function (a) { for (var c, d = [], e = r(a), f = e.length - 1, g = 0; g <= f; g++)c = g === f ? this : this.clone(!0), r(e[g])[b](c), h.apply(d, c.get()); return this.pushStack(d) } }); var La = /^margin/, Ma = new RegExp("^(" + aa + ")(?!px)[a-z%]+$", "i"), Na = function (b) { var c = b.ownerDocument.defaultView; return c && c.opener || (c = a), c.getComputedStyle(b) }; !function () { function b() { if (i) { i.style.cssText = "box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%", i.innerHTML = "", ra.appendChild(h); var b = a.getComputedStyle(i); c = "1%" !== b.top, g = "2px" === b.marginLeft, e = "4px" === b.width, i.style.marginRight = "50%", f = "4px" === b.marginRight, ra.removeChild(h), i = null } } var c, e, f, g, h = d.createElement("div"), i = d.createElement("div"); i.style && (i.style.backgroundClip = "content-box", i.cloneNode(!0).style.backgroundClip = "", o.clearCloneStyle = "content-box" === i.style.backgroundClip, h.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute", h.appendChild(i), r.extend(o, { pixelPosition: function () { return b(), c }, boxSizingReliable: function () { return b(), e }, pixelMarginRight: function () { return b(), f }, reliableMarginLeft: function () { return b(), g } })) }(); function Oa(a, b, c) { var d, e, f, g, h = a.style; return c = c || Na(a), c && (g = c.getPropertyValue(b) || c[b], "" !== g || r.contains(a.ownerDocument, a) || (g = r.style(a, b)), !o.pixelMarginRight() && Ma.test(g) && La.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 } function Pa(a, b) { return { get: function () { return a() ? void delete this.get : (this.get = b).apply(this, arguments) } } } var Qa = /^(none|table(?!-c[ea]).+)/, Ra = /^--/, Sa = {position: "absolute", visibility: "hidden", display: "block"}, Ta = {letterSpacing: "0", fontWeight: "400"}, Ua = ["Webkit", "Moz", "ms"], Va = d.createElement("div").style; function Wa(a) { if (a in Va)return a; var b = a[0].toUpperCase() + a.slice(1), c = Ua.length; while (c--)if (a = Ua[c] + b, a in Va)return a } function Xa(a) { var b = r.cssProps[a]; return b || (b = r.cssProps[a] = Wa(a) || a), b } function Ya(a, b, c) { var d = ba.exec(b); return d ? Math.max(0, d[2] - (c || 0)) + (d[3] || "px") : b } function Za(a, b, c, d, e) { var f, g = 0; for (f = c === (d ? "border" : "content") ? 4 : "width" === b ? 1 : 0; f < 4; f += 2)"margin" === c && (g += r.css(a, c + ca[f], !0, e)), d ? ("content" === c && (g -= r.css(a, "padding" + ca[f], !0, e)), "margin" !== c && (g -= r.css(a, "border" + ca[f] + "Width", !0, e))) : (g += r.css(a, "padding" + ca[f], !0, e), "padding" !== c && (g += r.css(a, "border" + ca[f] + "Width", !0, e))); return g } function $a(a, b, c) { var d, e = Na(a), f = Oa(a, b, e), g = "border-box" === r.css(a, "boxSizing", !1, e); return Ma.test(f) ? f : (d = g && (o.boxSizingReliable() || f === a.style[b]), f = parseFloat(f) || 0, f + Za(a, b, c || (g ? "border" : "content"), d, e) + "px") } r.extend({ cssHooks: { opacity: { get: function (a, b) { if (b) { var c = Oa(a, "opacity"); return "" === c ? "1" : c } } } }, cssNumber: { animationIterationCount: !0, columnCount: !0, fillOpacity: !0, flexGrow: !0, flexShrink: !0, fontWeight: !0, lineHeight: !0, opacity: !0, order: !0, orphans: !0, widows: !0, zIndex: !0, zoom: !0 }, cssProps: {"float": "cssFloat"}, style: function (a, b, c, d) { if (a && 3 !== a.nodeType && 8 !== a.nodeType && a.style) { var e, f, g, h = r.camelCase(b), i = Ra.test(b), j = a.style; return i || (b = Xa(h)), g = r.cssHooks[b] || r.cssHooks[h], void 0 === c ? g && "get" in g && void 0 !== (e = g.get(a, !1, d)) ? e : j[b] : (f = typeof c, "string" === f && (e = ba.exec(c)) && e[1] && (c = fa(a, b, e), f = "number"), null != c && c === c && ("number" === f && (c += e && e[3] || (r.cssNumber[h] ? "" : "px")), o.clearCloneStyle || "" !== c || 0 !== b.indexOf("background") || (j[b] = "inherit"), g && "set" in g && void 0 === (c = g.set(a, c, d)) || (i ? j.setProperty(b, c) : j[b] = c)), void 0) } }, css: function (a, b, c, d) { var e, f, g, h = r.camelCase(b), i = Ra.test(b); return i || (b = Xa(h)), g = r.cssHooks[b] || r.cssHooks[h], g && "get" in g && (e = g.get(a, !0, c)), void 0 === e && (e = Oa(a, b, d)), "normal" === e && b in Ta && (e = Ta[b]), "" === c || c ? (f = parseFloat(e), c === !0 || isFinite(f) ? f || 0 : e) : e } }), r.each(["height", "width"], function (a, b) { r.cssHooks[b] = { get: function (a, c, d) { if (c)return !Qa.test(r.css(a, "display")) || a.getClientRects().length && a.getBoundingClientRect().width ? $a(a, b, d) : ea(a, Sa, function () { return $a(a, b, d) }) }, set: function (a, c, d) { var e, f = d && Na(a), g = d && Za(a, b, d, "border-box" === r.css(a, "boxSizing", !1, f), f); return g && (e = ba.exec(c)) && "px" !== (e[3] || "px") && (a.style[b] = c, c = r.css(a, b)), Ya(a, c, g) } } }), r.cssHooks.marginLeft = Pa(o.reliableMarginLeft, function (a, b) { if (b)return (parseFloat(Oa(a, "marginLeft")) || a.getBoundingClientRect().left - ea(a, {marginLeft: 0}, function () { return a.getBoundingClientRect().left })) + "px" }), r.each({margin: "", padding: "", border: "Width"}, function (a, b) { r.cssHooks[a + b] = { expand: function (c) { for (var d = 0, e = {}, f = "string" == typeof c ? c.split(" ") : [c]; d < 4; d++)e[a + ca[d] + b] = f[d] || f[d - 2] || f[0]; return e } }, La.test(a) || (r.cssHooks[a + b].set = Ya) }), r.fn.extend({ css: function (a, b) { return T(this, function (a, b, c) { var d, e, f = {}, g = 0; if (Array.isArray(b)) { for (d = Na(a), e = b.length; g < e; g++)f[b[g]] = r.css(a, b[g], !1, d); return f } return void 0 !== c ? r.style(a, b, c) : r.css(a, b) }, a, b, arguments.length > 1) } }); function _a(a, b, c, d, e) { return new _a.prototype.init(a, b, c, d, e) } r.Tween = _a, _a.prototype = { constructor: _a, init: function (a, b, c, d, e, f) { this.elem = a, this.prop = c, this.easing = e || r.easing._default, this.options = b, this.start = this.now = this.cur(), this.end = d, this.unit = f || (r.cssNumber[c] ? "" : "px") }, cur: function () { var a = _a.propHooks[this.prop]; return a && a.get ? a.get(this) : _a.propHooks._default.get(this) }, run: function (a) { var b, c = _a.propHooks[this.prop]; return this.options.duration ? this.pos = b = r.easing[this.easing](a, this.options.duration * a, 0, 1, this.options.duration) : this.pos = 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) : _a.propHooks._default.set(this), this } }, _a.prototype.init.prototype = _a.prototype, _a.propHooks = { _default: { get: function (a) { var b; return 1 !== a.elem.nodeType || null != a.elem[a.prop] && null == a.elem.style[a.prop] ? a.elem[a.prop] : (b = r.css(a.elem, a.prop, ""), b && "auto" !== b ? b : 0) }, set: function (a) { r.fx.step[a.prop] ? r.fx.step[a.prop](a) : 1 !== a.elem.nodeType || null == a.elem.style[r.cssProps[a.prop]] && !r.cssHooks[a.prop] ? a.elem[a.prop] = a.now : r.style(a.elem, a.prop, a.now + a.unit) } } }, _a.propHooks.scrollTop = _a.propHooks.scrollLeft = { set: function (a) { a.elem.nodeType && a.elem.parentNode && (a.elem[a.prop] = a.now) } }, r.easing = { linear: function (a) { return a }, swing: function (a) { return .5 - Math.cos(a * Math.PI) / 2 }, _default: "swing" }, r.fx = _a.prototype.init, r.fx.step = {}; var ab, bb, cb = /^(?:toggle|show|hide)$/, db = /queueHooks$/; function eb() { bb && (d.hidden === !1 && a.requestAnimationFrame ? a.requestAnimationFrame(eb) : a.setTimeout(eb, r.fx.interval), r.fx.tick()) } function fb() { return a.setTimeout(function () { ab = void 0 }), ab = r.now() } function gb(a, b) { var c, d = 0, e = {height: a}; for (b = b ? 1 : 0; d < 4; d += 2 - b)c = ca[d], e["margin" + c] = e["padding" + c] = a; return b && (e.opacity = e.width = a), e } function hb(a, b, c) { for (var d, e = (kb.tweeners[b] || []).concat(kb.tweeners["*"]), f = 0, g = e.length; f < g; f++)if (d = e[f].call(c, b, a))return d } function ib(a, b, c) { var d, e, f, g, h, i, j, k, l = "width" in b || "height" in b, m = this, n = {}, o = a.style, p = a.nodeType && da(a), q = W.get(a, "fxshow"); c.queue || (g = r._queueHooks(a, "fx"), null == g.unqueued && (g.unqueued = 0, h = g.empty.fire, g.empty.fire = function () { g.unqueued || h() }), g.unqueued++, m.always(function () { m.always(function () { g.unqueued--, r.queue(a, "fx").length || g.empty.fire() }) })); for (d in b)if (e = b[d], cb.test(e)) { if (delete b[d], f = f || "toggle" === e, e === (p ? "hide" : "show")) { if ("show" !== e || !q || void 0 === q[d])continue; p = !0 } n[d] = q && q[d] || r.style(a, d) } if (i = !r.isEmptyObject(b), i || !r.isEmptyObject(n)) { l && 1 === a.nodeType && (c.overflow = [o.overflow, o.overflowX, o.overflowY], j = q && q.display, null == j && (j = W.get(a, "display")), k = r.css(a, "display"), "none" === k && (j ? k = j : (ia([a], !0), j = a.style.display || j, k = r.css(a, "display"), ia([a]))), ("inline" === k || "inline-block" === k && null != j) && "none" === r.css(a, "float") && (i || (m.done(function () { o.display = j }), null == j && (k = o.display, j = "none" === k ? "" : k)), o.display = "inline-block")), c.overflow && (o.overflow = "hidden", m.always(function () { o.overflow = c.overflow[0], o.overflowX = c.overflow[1], o.overflowY = c.overflow[2] })), i = !1; for (d in n)i || (q ? "hidden" in q && (p = q.hidden) : q = W.access(a, "fxshow", {display: j}), f && (q.hidden = !p), p && ia([a], !0), m.done(function () { p || ia([a]), W.remove(a, "fxshow"); for (d in n)r.style(a, d, n[d]) })), i = hb(p ? q[d] : 0, d, m), d in q || (q[d] = i.start, p && (i.end = i.start, i.start = 0)) } } function jb(a, b) { var c, d, e, f, g; for (c in a)if (d = r.camelCase(c), e = b[d], f = a[c], Array.isArray(f) && (e = f[1], f = a[c] = f[0]), c !== d && (a[d] = f, delete a[c]), g = r.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 kb(a, b, c) { var d, e, f = 0, g = kb.prefilters.length, h = r.Deferred().always(function () { delete i.elem }), i = function () { if (e)return !1; for (var b = ab || fb(), c = Math.max(0, j.startTime + j.duration - b), d = c / j.duration || 0, f = 1 - d, g = 0, i = j.tweens.length; g < i; g++)j.tweens[g].run(f); return h.notifyWith(a, [j, f, c]), f < 1 && i ? c : (i || h.notifyWith(a, [j, 1, 0]), h.resolveWith(a, [j]), !1) }, j = h.promise({ elem: a, props: r.extend({}, b), opts: r.extend(!0, {specialEasing: {}, easing: r.easing._default}, c), originalProperties: b, originalOptions: c, startTime: ab || fb(), duration: c.duration, tweens: [], createTween: function (b, c) { var d = r.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; c < d; c++)j.tweens[c].run(1); return b ? (h.notifyWith(a, [j, 1, 0]), h.resolveWith(a, [j, b])) : h.rejectWith(a, [j, b]), this } }), k = j.props; for (jb(k, j.opts.specialEasing); f < g; f++)if (d = kb.prefilters[f].call(j, a, k, j.opts))return r.isFunction(d.stop) && (r._queueHooks(j.elem, j.opts.queue).stop = r.proxy(d.stop, d)), d; return r.map(k, hb, j), r.isFunction(j.opts.start) && j.opts.start.call(a, j), j.progress(j.opts.progress).done(j.opts.done, j.opts.complete).fail(j.opts.fail).always(j.opts.always), r.fx.timer(r.extend(i, { elem: a, anim: j, queue: j.opts.queue })), j } r.Animation = r.extend(kb, { tweeners: { "*": [function (a, b) { var c = this.createTween(a, b); return fa(c.elem, a, ba.exec(b), c), c }] }, tweener: function (a, b) { r.isFunction(a) ? (b = a, a = ["*"]) : a = a.match(L); for (var c, d = 0, e = a.length; d < e; d++)c = a[d], kb.tweeners[c] = kb.tweeners[c] || [], kb.tweeners[c].unshift(b) }, prefilters: [ib], prefilter: function (a, b) { b ? kb.prefilters.unshift(a) : kb.prefilters.push(a) } }), r.speed = function (a, b, c) { var d = a && "object" == typeof a ? r.extend({}, a) : { complete: c || !c && b || r.isFunction(a) && a, duration: a, easing: c && b || b && !r.isFunction(b) && b }; return r.fx.off ? d.duration = 0 : "number" != typeof d.duration && (d.duration in r.fx.speeds ? d.duration = r.fx.speeds[d.duration] : d.duration = r.fx.speeds._default), null != d.queue && d.queue !== !0 || (d.queue = "fx"), d.old = d.complete, d.complete = function () { r.isFunction(d.old) && d.old.call(this), d.queue && r.dequeue(this, d.queue) }, d }, r.fn.extend({ fadeTo: function (a, b, c, d) { return this.filter(da).css("opacity", 0).show().end().animate({opacity: b}, a, c, d) }, animate: function (a, b, c, d) { var e = r.isEmptyObject(a), f = r.speed(b, c, d), g = function () { var b = kb(this, r.extend({}, a), f); (e || W.get(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 = r.timers, g = W.get(this); if (e) g[e] && g[e].stop && d(g[e]); else for (e in g)g[e] && g[e].stop && db.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 || r.dequeue(this, a) }) }, finish: function (a) { return a !== !1 && (a = a || "fx"), this.each(function () { var b, c = W.get(this), d = c[a + "queue"], e = c[a + "queueHooks"], f = r.timers, g = d ? d.length : 0; for (c.finish = !0, r.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; b < g; b++)d[b] && d[b].finish && d[b].finish.call(this); delete c.finish }) } }), r.each(["toggle", "show", "hide"], function (a, b) { var c = r.fn[b]; r.fn[b] = function (a, d, e) { return null == a || "boolean" == typeof a ? c.apply(this, arguments) : this.animate(gb(b, !0), a, d, e) } }), r.each({ slideDown: gb("show"), slideUp: gb("hide"), slideToggle: gb("toggle"), fadeIn: {opacity: "show"}, fadeOut: {opacity: "hide"}, fadeToggle: {opacity: "toggle"} }, function (a, b) { r.fn[a] = function (a, c, d) { return this.animate(b, a, c, d) } }), r.timers = [], r.fx.tick = function () { var a, b = 0, c = r.timers; for (ab = r.now(); b < c.length; b++)a = c[b], a() || c[b] !== a || c.splice(b--, 1); c.length || r.fx.stop(), ab = void 0 }, r.fx.timer = function (a) { r.timers.push(a), r.fx.start() }, r.fx.interval = 13, r.fx.start = function () { bb || (bb = !0, eb()) }, r.fx.stop = function () { bb = null }, r.fx.speeds = {slow: 600, fast: 200, _default: 400}, r.fn.delay = function (b, c) { return b = r.fx ? r.fx.speeds[b] || b : b, c = c || "fx", this.queue(c, function (c, d) { var e = a.setTimeout(c, b); d.stop = function () { a.clearTimeout(e) } }) }, function () { var a = d.createElement("input"), b = d.createElement("select"), c = b.appendChild(d.createElement("option")); a.type = "checkbox", o.checkOn = "" !== a.value, o.optSelected = c.selected, a = d.createElement("input"), a.value = "t", a.type = "radio", o.radioValue = "t" === a.value }(); var lb, mb = r.expr.attrHandle; r.fn.extend({ attr: function (a, b) { return T(this, r.attr, a, b, arguments.length > 1) }, removeAttr: function (a) { return this.each(function () { r.removeAttr(this, a) }) } }), r.extend({ attr: function (a, b, c) { var d, e, f = a.nodeType; if (3 !== f && 8 !== f && 2 !== f)return "undefined" == typeof a.getAttribute ? r.prop(a, b, c) : (1 === f && r.isXMLDoc(a) || (e = r.attrHooks[b.toLowerCase()] || (r.expr.match.bool.test(b) ? lb : void 0)), void 0 !== c ? null === c ? void r.removeAttr(a, b) : e && "set" in e && void 0 !== (d = e.set(a, c, b)) ? d : (a.setAttribute(b, c + ""), c) : e && "get" in e && null !== (d = e.get(a, b)) ? d : (d = r.find.attr(a, b), null == d ? void 0 : d)); }, attrHooks: { type: { set: function (a, b) { if (!o.radioValue && "radio" === b && B(a, "input")) { var c = a.value; return a.setAttribute("type", b), c && (a.value = c), b } } } }, removeAttr: function (a, b) { var c, d = 0, e = b && b.match(L); if (e && 1 === a.nodeType)while (c = e[d++])a.removeAttribute(c) } }), lb = { set: function (a, b, c) { return b === !1 ? r.removeAttr(a, c) : a.setAttribute(c, c), c } }, r.each(r.expr.match.bool.source.match(/\w+/g), function (a, b) { var c = mb[b] || r.find.attr; mb[b] = function (a, b, d) { var e, f, g = b.toLowerCase(); return d || (f = mb[g], mb[g] = e, e = null != c(a, b, d) ? g : null, mb[g] = f), e } }); var nb = /^(?:input|select|textarea|button)$/i, ob = /^(?:a|area)$/i; r.fn.extend({ prop: function (a, b) { return T(this, r.prop, a, b, arguments.length > 1) }, removeProp: function (a) { return this.each(function () { delete this[r.propFix[a] || a] }) } }), r.extend({ prop: function (a, b, c) { var d, e, f = a.nodeType; if (3 !== f && 8 !== f && 2 !== f)return 1 === f && r.isXMLDoc(a) || (b = r.propFix[b] || b, e = r.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 = r.find.attr(a, "tabindex"); return b ? parseInt(b, 10) : nb.test(a.nodeName) || ob.test(a.nodeName) && a.href ? 0 : -1 } } }, propFix: {"for": "htmlFor", "class": "className"} }), o.optSelected || (r.propHooks.selected = { get: function (a) { var b = a.parentNode; return b && b.parentNode && b.parentNode.selectedIndex, null }, set: function (a) { var b = a.parentNode; b && (b.selectedIndex, b.parentNode && b.parentNode.selectedIndex) } }), r.each(["tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable"], function () { r.propFix[this.toLowerCase()] = this }); function pb(a) { var b = a.match(L) || []; return b.join(" ") } function qb(a) { return a.getAttribute && a.getAttribute("class") || "" } r.fn.extend({ addClass: function (a) { var b, c, d, e, f, g, h, i = 0; if (r.isFunction(a))return this.each(function (b) { r(this).addClass(a.call(this, b, qb(this))) }); if ("string" == typeof a && a) { b = a.match(L) || []; while (c = this[i++])if (e = qb(c), d = 1 === c.nodeType && " " + pb(e) + " ") { g = 0; while (f = b[g++])d.indexOf(" " + f + " ") < 0 && (d += f + " "); h = pb(d), e !== h && c.setAttribute("class", h) } } return this }, removeClass: function (a) { var b, c, d, e, f, g, h, i = 0; if (r.isFunction(a))return this.each(function (b) { r(this).removeClass(a.call(this, b, qb(this))) }); if (!arguments.length)return this.attr("class", ""); if ("string" == typeof a && a) { b = a.match(L) || []; while (c = this[i++])if (e = qb(c), d = 1 === c.nodeType && " " + pb(e) + " ") { g = 0; while (f = b[g++])while (d.indexOf(" " + f + " ") > -1)d = d.replace(" " + f + " ", " "); h = pb(d), e !== h && c.setAttribute("class", h) } } return this }, toggleClass: function (a, b) { var c = typeof a; return "boolean" == typeof b && "string" === c ? b ? this.addClass(a) : this.removeClass(a) : r.isFunction(a) ? this.each(function (c) { r(this).toggleClass(a.call(this, c, qb(this), b), b) }) : this.each(function () { var b, d, e, f; if ("string" === c) { d = 0, e = r(this), f = a.match(L) || []; while (b = f[d++])e.hasClass(b) ? e.removeClass(b) : e.addClass(b) } else void 0 !== a && "boolean" !== c || (b = qb(this), b && W.set(this, "__className__", b), this.setAttribute && this.setAttribute("class", b || a === !1 ? "" : W.get(this, "__className__") || "")) }) }, hasClass: function (a) { var b, c, d = 0; b = " " + a + " "; while (c = this[d++])if (1 === c.nodeType && (" " + pb(qb(c)) + " ").indexOf(b) > -1)return !0; return !1 } }); var rb = /\r/g; r.fn.extend({ val: function (a) { var b, c, d, e = this[0]; { if (arguments.length)return d = r.isFunction(a), this.each(function (c) { var e; 1 === this.nodeType && (e = d ? a.call(this, c, r(this).val()) : a, null == e ? e = "" : "number" == typeof e ? e += "" : Array.isArray(e) && (e = r.map(e, function (a) { return null == a ? "" : a + "" })), b = r.valHooks[this.type] || r.valHooks[this.nodeName.toLowerCase()], b && "set" in b && void 0 !== b.set(this, e, "value") || (this.value = e)) }); if (e)return b = r.valHooks[e.type] || r.valHooks[e.nodeName.toLowerCase()], b && "get" in b && void 0 !== (c = b.get(e, "value")) ? c : (c = e.value, "string" == typeof c ? c.replace(rb, "") : null == c ? "" : c) } } }), r.extend({ valHooks: { option: { get: function (a) { var b = r.find.attr(a, "value"); return null != b ? b : pb(r.text(a)) } }, select: { get: function (a) { var b, c, d, e = a.options, f = a.selectedIndex, g = "select-one" === a.type, h = g ? null : [], i = g ? f + 1 : e.length; for (d = f < 0 ? i : g ? f : 0; d < i; d++)if (c = e[d], (c.selected || d === f) && !c.disabled && (!c.parentNode.disabled || !B(c.parentNode, "optgroup"))) { if (b = r(c).val(), g)return b; h.push(b) } return h }, set: function (a, b) { var c, d, e = a.options, f = r.makeArray(b), g = e.length; while (g--)d = e[g], (d.selected = r.inArray(r.valHooks.option.get(d), f) > -1) && (c = !0); return c || (a.selectedIndex = -1), f } } } }), r.each(["radio", "checkbox"], function () { r.valHooks[this] = { set: function (a, b) { if (Array.isArray(b))return a.checked = r.inArray(r(a).val(), b) > -1 } }, o.checkOn || (r.valHooks[this].get = function (a) { return null === a.getAttribute("value") ? "on" : a.value }) }); var sb = /^(?:focusinfocus|focusoutblur)$/; r.extend(r.event, { trigger: function (b, c, e, f) { var g, h, i, j, k, m, n, o = [e || d], p = l.call(b, "type") ? b.type : b, q = l.call(b, "namespace") ? b.namespace.split(".") : []; if (h = i = e = e || d, 3 !== e.nodeType && 8 !== e.nodeType && !sb.test(p + r.event.triggered) && (p.indexOf(".") > -1 && (q = p.split("."), p = q.shift(), q.sort()), k = p.indexOf(":") < 0 && "on" + p, b = b[r.expando] ? b : new r.Event(p, "object" == typeof b && b), b.isTrigger = f ? 2 : 3, b.namespace = q.join("."), b.rnamespace = b.namespace ? new RegExp("(^|\\.)" + q.join("\\.(?:.*\\.|)") + "(\\.|$)") : null, b.result = void 0, b.target || (b.target = e), c = null == c ? [b] : r.makeArray(c, [b]), n = r.event.special[p] || {}, f || !n.trigger || n.trigger.apply(e, c) !== !1)) { if (!f && !n.noBubble && !r.isWindow(e)) { for (j = n.delegateType || p, sb.test(j + p) || (h = h.parentNode); h; h = h.parentNode)o.push(h), i = h; i === (e.ownerDocument || d) && o.push(i.defaultView || i.parentWindow || a) } g = 0; while ((h = o[g++]) && !b.isPropagationStopped())b.type = g > 1 ? j : n.bindType || p, m = (W.get(h, "events") || {})[b.type] && W.get(h, "handle"), m && m.apply(h, c), m = k && h[k], m && m.apply && U(h) && (b.result = m.apply(h, c), b.result === !1 && b.preventDefault()); return b.type = p, f || b.isDefaultPrevented() || n._default && n._default.apply(o.pop(), c) !== !1 || !U(e) || k && r.isFunction(e[p]) && !r.isWindow(e) && (i = e[k], i && (e[k] = null), r.event.triggered = p, e[p](), r.event.triggered = void 0, i && (e[k] = i)), b.result } }, simulate: function (a, b, c) { var d = r.extend(new r.Event, c, {type: a, isSimulated: !0}); r.event.trigger(d, null, b) } }), r.fn.extend({ trigger: function (a, b) { return this.each(function () { r.event.trigger(a, b, this) }) }, triggerHandler: function (a, b) { var c = this[0]; if (c)return r.event.trigger(a, b, c, !0) } }), r.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "), function (a, b) { r.fn[b] = function (a, c) { return arguments.length > 0 ? this.on(b, null, a, c) : this.trigger(b) } }), r.fn.extend({ hover: function (a, b) { return this.mouseenter(a).mouseleave(b || a) } }), o.focusin = "onfocusin" in a, o.focusin || r.each({focus: "focusin", blur: "focusout"}, function (a, b) { var c = function (a) { r.event.simulate(b, a.target, r.event.fix(a)) }; r.event.special[b] = { setup: function () { var d = this.ownerDocument || this, e = W.access(d, b); e || d.addEventListener(a, c, !0), W.access(d, b, (e || 0) + 1) }, teardown: function () { var d = this.ownerDocument || this, e = W.access(d, b) - 1; e ? W.access(d, b, e) : (d.removeEventListener(a, c, !0), W.remove(d, b)) } } }); var tb = a.location, ub = r.now(), vb = /\?/; r.parseXML = function (b) { var c; if (!b || "string" != typeof b)return null; try { c = (new a.DOMParser).parseFromString(b, "text/xml") } catch (d) { c = void 0 } return c && !c.getElementsByTagName("parsererror").length || r.error("Invalid XML: " + b), c }; var wb = /\[\]$/, xb = /\r?\n/g, yb = /^(?:submit|button|image|reset|file)$/i, zb = /^(?:input|select|textarea|keygen)/i; function Ab(a, b, c, d) { var e; if (Array.isArray(b)) r.each(b, function (b, e) { c || wb.test(a) ? d(a, e) : Ab(a + "[" + ("object" == typeof e && null != e ? b : "") + "]", e, c, d) }); else if (c || "object" !== r.type(b)) d(a, b); else for (e in b)Ab(a + "[" + e + "]", b[e], c, d) } r.param = function (a, b) { var c, d = [], e = function (a, b) { var c = r.isFunction(b) ? b() : b; d[d.length] = encodeURIComponent(a) + "=" + encodeURIComponent(null == c ? "" : c) }; if (Array.isArray(a) || a.jquery && !r.isPlainObject(a)) r.each(a, function () { e(this.name, this.value) }); else for (c in a)Ab(c, a[c], b, e); return d.join("&") }, r.fn.extend({ serialize: function () { return r.param(this.serializeArray()) }, serializeArray: function () { return this.map(function () { var a = r.prop(this, "elements"); return a ? r.makeArray(a) : this }).filter(function () { var a = this.type; return this.name && !r(this).is(":disabled") && zb.test(this.nodeName) && !yb.test(a) && (this.checked || !ja.test(a)) }).map(function (a, b) { var c = r(this).val(); return null == c ? null : Array.isArray(c) ? r.map(c, function (a) { return {name: b.name, value: a.replace(xb, "\r\n")} }) : {name: b.name, value: c.replace(xb, "\r\n")} }).get() } }); var Bb = /%20/g, Cb = /#.*$/, Db = /([?&])_=[^&]*/, Eb = /^(.*?):[ \t]*([^\r\n]*)$/gm, Fb = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, Gb = /^(?:GET|HEAD)$/, Hb = /^\/\//, Ib = {}, Jb = {}, Kb = "*/".concat("*"), Lb = d.createElement("a"); Lb.href = tb.href; function Mb(a) { return function (b, c) { "string" != typeof b && (c = b, b = "*"); var d, e = 0, f = b.toLowerCase().match(L) || []; if (r.isFunction(c))while (d = f[e++])"+" === d[0] ? (d = d.slice(1) || "*", (a[d] = a[d] || []).unshift(c)) : (a[d] = a[d] || []).push(c) } } function Nb(a, b, c, d) { var e = {}, f = a === Jb; function g(h) { var i; return e[h] = !0, r.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 Ob(a, b) { var c, d, e = r.ajaxSettings.flatOptions || {}; for (c in b)void 0 !== b[c] && ((e[c] ? a : d || (d = {}))[c] = b[c]); return d && r.extend(!0, a, d), a } function Pb(a, b, c) { var d, e, f, g, h = a.contents, i = a.dataTypes; while ("*" === i[0])i.shift(), void 0 === d && (d = a.mimeType || b.getResponseHeader("Content-Type")); if (d)for (e in h)if (h[e] && h[e].test(d)) { i.unshift(e); break } if (i[0] in c) f = i[0]; else { for (e in c) { if (!i[0] || a.converters[e + " " + i[0]]) { f = e; break } g || (g = e) } f = f || g } if (f)return f !== i[0] && i.unshift(f), c[f] } function Qb(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} } r.extend({ active: 0, lastModified: {}, etag: {}, ajaxSettings: { url: tb.href, type: "GET", isLocal: Fb.test(tb.protocol), global: !0, processData: !0, async: !0, contentType: "application/x-www-form-urlencoded; charset=UTF-8", accepts: { "*": Kb, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: {xml: /\bxml\b/, html: /\bhtml/, json: /\bjson\b/}, responseFields: {xml: "responseXML", text: "responseText", json: "responseJSON"}, converters: {"* text": String, "text html": !0, "text json": JSON.parse, "text xml": r.parseXML}, flatOptions: {url: !0, context: !0} }, ajaxSetup: function (a, b) { return b ? Ob(Ob(a, r.ajaxSettings), b) : Ob(r.ajaxSettings, a) }, ajaxPrefilter: Mb(Ib), ajaxTransport: Mb(Jb), ajax: function (b, c) { "object" == typeof b && (c = b, b = void 0), c = c || {}; var e, f, g, h, i, j, k, l, m, n, o = r.ajaxSetup({}, c), p = o.context || o, q = o.context && (p.nodeType || p.jquery) ? r(p) : r.event, s = r.Deferred(), t = r.Callbacks("once memory"), u = o.statusCode || {}, v = {}, w = {}, x = "canceled", y = { readyState: 0, getResponseHeader: function (a) { var b; if (k) { if (!h) { h = {}; while (b = Eb.exec(g))h[b[1].toLowerCase()] = b[2] } b = h[a.toLowerCase()] } return null == b ? null : b }, getAllResponseHeaders: function () { return k ? g : null }, setRequestHeader: function (a, b) { return null == k && (a = w[a.toLowerCase()] = w[a.toLowerCase()] || a, v[a] = b), this }, overrideMimeType: function (a) { return null == k && (o.mimeType = a), this }, statusCode: function (a) { var b; if (a)if (k) y.always(a[y.status]); else for (b in a)u[b] = [u[b], a[b]]; return this }, abort: function (a) { var b = a || x; return e && e.abort(b), A(0, b), this } }; if (s.promise(y), o.url = ((b || o.url || tb.href) + "").replace(Hb, tb.protocol + "//"), o.type = c.method || c.type || o.method || o.type, o.dataTypes = (o.dataType || "*").toLowerCase().match(L) || [""], null == o.crossDomain) { j = d.createElement("a"); try { j.href = o.url, j.href = j.href, o.crossDomain = Lb.protocol + "//" + Lb.host != j.protocol + "//" + j.host } catch (z) { o.crossDomain = !0 } } if (o.data && o.processData && "string" != typeof o.data && (o.data = r.param(o.data, o.traditional)), Nb(Ib, o, c, y), k)return y; l = r.event && o.global, l && 0 === r.active++ && r.event.trigger("ajaxStart"), o.type = o.type.toUpperCase(), o.hasContent = !Gb.test(o.type), f = o.url.replace(Cb, ""), o.hasContent ? o.data && o.processData && 0 === (o.contentType || "").indexOf("application/x-www-form-urlencoded") && (o.data = o.data.replace(Bb, "+")) : (n = o.url.slice(f.length), o.data && (f += (vb.test(f) ? "&" : "?") + o.data, delete o.data), o.cache === !1 && (f = f.replace(Db, "$1"), n = (vb.test(f) ? "&" : "?") + "_=" + ub++ + n), o.url = f + n), o.ifModified && (r.lastModified[f] && y.setRequestHeader("If-Modified-Since", r.lastModified[f]), r.etag[f] && y.setRequestHeader("If-None-Match", r.etag[f])), (o.data && o.hasContent && o.contentType !== !1 || c.contentType) && y.setRequestHeader("Content-Type", o.contentType), y.setRequestHeader("Accept", o.dataTypes[0] && o.accepts[o.dataTypes[0]] ? o.accepts[o.dataTypes[0]] + ("*" !== o.dataTypes[0] ? ", " + Kb + "; q=0.01" : "") : o.accepts["*"]); for (m in o.headers)y.setRequestHeader(m, o.headers[m]); if (o.beforeSend && (o.beforeSend.call(p, y, o) === !1 || k))return y.abort(); if (x = "abort", t.add(o.complete), y.done(o.success), y.fail(o.error), e = Nb(Jb, o, c, y)) { if (y.readyState = 1, l && q.trigger("ajaxSend", [y, o]), k)return y; o.async && o.timeout > 0 && (i = a.setTimeout(function () { y.abort("timeout") }, o.timeout)); try { k = !1, e.send(v, A) } catch (z) { if (k)throw z; A(-1, z) } } else A(-1, "No Transport"); function A(b, c, d, h) { var j, m, n, v, w, x = c; k || (k = !0, i && a.clearTimeout(i), e = void 0, g = h || "", y.readyState = b > 0 ? 4 : 0, j = b >= 200 && b < 300 || 304 === b, d && (v = Pb(o, y, d)), v = Qb(o, v, y, j), j ? (o.ifModified && (w = y.getResponseHeader("Last-Modified"), w && (r.lastModified[f] = w), w = y.getResponseHeader("etag"), w && (r.etag[f] = w)), 204 === b || "HEAD" === o.type ? x = "nocontent" : 304 === b ? x = "notmodified" : (x = v.state, m = v.data, n = v.error, j = !n)) : (n = x, !b && x || (x = "error", b < 0 && (b = 0))), y.status = b, y.statusText = (c || x) + "", j ? s.resolveWith(p, [m, x, y]) : s.rejectWith(p, [y, x, n]), y.statusCode(u), u = void 0, l && q.trigger(j ? "ajaxSuccess" : "ajaxError", [y, o, j ? m : n]), t.fireWith(p, [y, x]), l && (q.trigger("ajaxComplete", [y, o]), --r.active || r.event.trigger("ajaxStop"))) } return y }, getJSON: function (a, b, c) { return r.get(a, b, c, "json") }, getScript: function (a, b) { return r.get(a, void 0, b, "script") } }), r.each(["get", "post"], function (a, b) { r[b] = function (a, c, d, e) { return r.isFunction(c) && (e = e || d, d = c, c = void 0), r.ajax(r.extend({ url: a, type: b, dataType: e, data: c, success: d }, r.isPlainObject(a) && a)) } }), r._evalUrl = function (a) { return r.ajax({url: a, type: "GET", dataType: "script", cache: !0, async: !1, global: !1, "throws": !0}) }, r.fn.extend({ wrapAll: function (a) { var b; return this[0] && (r.isFunction(a) && (a = a.call(this[0])), b = r(a, this[0].ownerDocument).eq(0).clone(!0), this[0].parentNode && b.insertBefore(this[0]), b.map(function () { var a = this; while (a.firstElementChild)a = a.firstElementChild; return a }).append(this)), this }, wrapInner: function (a) { return r.isFunction(a) ? this.each(function (b) { r(this).wrapInner(a.call(this, b)) }) : this.each(function () { var b = r(this), c = b.contents(); c.length ? c.wrapAll(a) : b.append(a) }) }, wrap: function (a) { var b = r.isFunction(a); return this.each(function (c) { r(this).wrapAll(b ? a.call(this, c) : a) }) }, unwrap: function (a) { return this.parent(a).not("body").each(function () { r(this).replaceWith(this.childNodes) }), this } }), r.expr.pseudos.hidden = function (a) { return !r.expr.pseudos.visible(a) }, r.expr.pseudos.visible = function (a) { return !!(a.offsetWidth || a.offsetHeight || a.getClientRects().length) }, r.ajaxSettings.xhr = function () { try { return new a.XMLHttpRequest } catch (b) { } }; var Rb = {0: 200, 1223: 204}, Sb = r.ajaxSettings.xhr(); o.cors = !!Sb && "withCredentials" in Sb, o.ajax = Sb = !!Sb, r.ajaxTransport(function (b) { var c, d; if (o.cors || Sb && !b.crossDomain)return { send: function (e, f) { var g, h = b.xhr(); if (h.open(b.type, b.url, b.async, b.username, b.password), b.xhrFields)for (g in b.xhrFields)h[g] = b.xhrFields[g]; b.mimeType && h.overrideMimeType && h.overrideMimeType(b.mimeType), b.crossDomain || e["X-Requested-With"] || (e["X-Requested-With"] = "XMLHttpRequest"); for (g in e)h.setRequestHeader(g, e[g]); c = function (a) { return function () { c && (c = d = h.onload = h.onerror = h.onabort = h.onreadystatechange = null, "abort" === a ? h.abort() : "error" === a ? "number" != typeof h.status ? f(0, "error") : f(h.status, h.statusText) : f(Rb[h.status] || h.status, h.statusText, "text" !== (h.responseType || "text") || "string" != typeof h.responseText ? {binary: h.response} : {text: h.responseText}, h.getAllResponseHeaders())) } }, h.onload = c(), d = h.onerror = c("error"), void 0 !== h.onabort ? h.onabort = d : h.onreadystatechange = function () { 4 === h.readyState && a.setTimeout(function () { c && d() }) }, c = c("abort"); try { h.send(b.hasContent && b.data || null) } catch (i) { if (c)throw i } }, abort: function () { c && c() } } }), r.ajaxPrefilter(function (a) { a.crossDomain && (a.contents.script = !1) }), r.ajaxSetup({ accepts: {script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"}, contents: {script: /\b(?:java|ecma)script\b/}, converters: { "text script": function (a) { return r.globalEval(a), a } } }), r.ajaxPrefilter("script", function (a) { void 0 === a.cache && (a.cache = !1), a.crossDomain && (a.type = "GET") }), r.ajaxTransport("script", function (a) { if (a.crossDomain) { var b, c; return { send: function (e, f) { b = r("<script>").prop({charset: a.scriptCharset, src: a.url}).on("load error", c = function (a) { b.remove(), c = null, a && f("error" === a.type ? 404 : 200, a.type) }), d.head.appendChild(b[0]) }, abort: function () { c && c() } } } }); var Tb = [], Ub = /(=)\?(?=&|$)|\?\?/; r.ajaxSetup({ jsonp: "callback", jsonpCallback: function () { var a = Tb.pop() || r.expando + "_" + ub++; return this[a] = !0, a } }), r.ajaxPrefilter("json jsonp", function (b, c, d) { var e, f, g, h = b.jsonp !== !1 && (Ub.test(b.url) ? "url" : "string" == typeof b.data && 0 === (b.contentType || "").indexOf("application/x-www-form-urlencoded") && Ub.test(b.data) && "data"); if (h || "jsonp" === b.dataTypes[0])return e = b.jsonpCallback = r.isFunction(b.jsonpCallback) ? b.jsonpCallback() : b.jsonpCallback, h ? b[h] = b[h].replace(Ub, "$1" + e) : b.jsonp !== !1 && (b.url += (vb.test(b.url) ? "&" : "?") + b.jsonp + "=" + e), b.converters["script json"] = function () { return g || r.error(e + " was not called"), g[0] }, b.dataTypes[0] = "json", f = a[e], a[e] = function () { g = arguments }, d.always(function () { void 0 === f ? r(a).removeProp(e) : a[e] = f, b[e] && (b.jsonpCallback = c.jsonpCallback, Tb.push(e)), g && r.isFunction(f) && f(g[0]), g = f = void 0 }), "script" }), o.createHTMLDocument = function () { var a = d.implementation.createHTMLDocument("").body; return a.innerHTML = "<form></form><form></form>", 2 === a.childNodes.length }(), r.parseHTML = function (a, b, c) { if ("string" != typeof a)return []; "boolean" == typeof b && (c = b, b = !1); var e, f, g; return b || (o.createHTMLDocument ? (b = d.implementation.createHTMLDocument(""), e = b.createElement("base"), e.href = d.location.href, b.head.appendChild(e)) : b = d), f = C.exec(a), g = !c && [], f ? [b.createElement(f[1])] : (f = qa([a], b, g), g && g.length && r(g).remove(), r.merge([], f.childNodes)) }, r.fn.load = function (a, b, c) { var d, e, f, g = this, h = a.indexOf(" "); return h > -1 && (d = pb(a.slice(h)), a = a.slice(0, h)), r.isFunction(b) ? (c = b, b = void 0) : b && "object" == typeof b && (e = "POST"), g.length > 0 && r.ajax({ url: a, type: e || "GET", dataType: "html", data: b }).done(function (a) { f = arguments, g.html(d ? r("<div>").append(r.parseHTML(a)).find(d) : a) }).always(c && function (a, b) { g.each(function () { c.apply(this, f || [a.responseText, b, a]) }) }), this }, r.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function (a, b) { r.fn[b] = function (a) { return this.on(b, a) } }), r.expr.pseudos.animated = function (a) { return r.grep(r.timers, function (b) { return a === b.elem }).length }, r.offset = { setOffset: function (a, b, c) { var d, e, f, g, h, i, j, k = r.css(a, "position"), l = r(a), m = {}; "static" === k && (a.style.position = "relative"), h = l.offset(), f = r.css(a, "top"), i = r.css(a, "left"), j = ("absolute" === k || "fixed" === k) && (f + i).indexOf("auto") > -1, j ? (d = l.position(), g = d.top, e = d.left) : (g = parseFloat(f) || 0, e = parseFloat(i) || 0), r.isFunction(b) && (b = b.call(a, c, r.extend({}, 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) } }, r.fn.extend({ offset: function (a) { if (arguments.length)return void 0 === a ? this : this.each(function (b) { r.offset.setOffset(this, a, b) }); var b, c, d, e, f = this[0]; if (f)return f.getClientRects().length ? (d = f.getBoundingClientRect(), b = f.ownerDocument, c = b.documentElement, e = b.defaultView, { top: d.top + e.pageYOffset - c.clientTop, left: d.left + e.pageXOffset - c.clientLeft }) : {top: 0, left: 0} }, position: function () { if (this[0]) { var a, b, c = this[0], d = {top: 0, left: 0}; return "fixed" === r.css(c, "position") ? b = c.getBoundingClientRect() : (a = this.offsetParent(), b = this.offset(), B(a[0], "html") || (d = a.offset()), d = { top: d.top + r.css(a[0], "borderTopWidth", !0), left: d.left + r.css(a[0], "borderLeftWidth", !0) }), {top: b.top - d.top - r.css(c, "marginTop", !0), left: b.left - d.left - r.css(c, "marginLeft", !0)} } }, offsetParent: function () { return this.map(function () { var a = this.offsetParent; while (a && "static" === r.css(a, "position"))a = a.offsetParent; return a || ra }) } }), r.each({scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function (a, b) { var c = "pageYOffset" === b; r.fn[a] = function (d) { return T(this, function (a, d, e) { var f; return r.isWindow(a) ? f = a : 9 === a.nodeType && (f = a.defaultView), void 0 === e ? f ? f[b] : a[d] : void(f ? f.scrollTo(c ? f.pageXOffset : e, c ? e : f.pageYOffset) : a[d] = e) }, a, d, arguments.length) } }), r.each(["top", "left"], function (a, b) { r.cssHooks[b] = Pa(o.pixelPosition, function (a, c) { if (c)return c = Oa(a, b), Ma.test(c) ? r(a).position()[b] + "px" : c }) }), r.each({Height: "height", Width: "width"}, function (a, b) { r.each({padding: "inner" + a, content: b, "": "outer" + a}, function (c, d) { r.fn[d] = function (e, f) { var g = arguments.length && (c || "boolean" != typeof e), h = c || (e === !0 || f === !0 ? "margin" : "border"); return T(this, function (b, c, e) { var f; return r.isWindow(b) ? 0 === d.indexOf("outer") ? b["inner" + a] : b.document.documentElement["client" + a] : 9 === b.nodeType ? (f = b.documentElement, Math.max(b.body["scroll" + a], f["scroll" + a], b.body["offset" + a], f["offset" + a], f["client" + a])) : void 0 === e ? r.css(b, c, h) : r.style(b, c, e, h) }, b, g ? e : void 0, g) } }) }), r.fn.extend({ 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) }, holdReady: function (a) { a ? r.readyWait++ : r.ready(!0) } }), r.isArray = Array.isArray, r.parseJSON = JSON.parse, r.nodeName = B, "function" == typeof define && define.amd && define("jquery", [], function () { return r }); var Vb = a.jQuery, Wb = a.$; return r.noConflict = function (b) { return a.$ === r && (a.$ = Wb), b && a.jQuery === r && (a.jQuery = Vb), r }, b || (a.jQuery = a.$ = r), r });
/* global ResearchItemTypes, Accomplishment, Project */ module.exports = { tableName: 'research_item_type', attributes: { key: 'STRING', label: 'STRING', shortLabel: { type: 'STRING', columnName: 'short_label' }, type: 'STRING', } };
module.exports = { "env": { "browser": true, "commonjs": true, "es6": true, "node": true, "jquery":true }, "extends": "eslint:recommended", "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true, "jsx": true }, "sourceType": "module" }, "rules": { "semi": [ "error", "always" ], "no-unused-vars": ["off", { "varsIgnorePattern": "^h$" }], "no-console" : "off" } };
'use strict'; //require('colors'); var express = require('express'), bodyParser = require('body-parser'), http = require('http'), path = require('path'), api = require('./routes/api'), cors = require('cors'); var app = express(); app.set('port', process.env.PORT || 9000); app.use(bodyParser.json()); app.use(cors()); app.use(bodyParser.urlencoded({extended: true})); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Methods", "PUT, DELETE"); next(); }); // JSON API /** * My bag */ app.get('/api/bag', api.getMyBag); app.post('/api/bag/', api.addItem); app.put('/api/bag/', api.removeItem); app.delete('/api/bag/:id', api.deleteItem); app.listen(app.get('port'), function () { console.log('✔Express server listening on http://localhost:%d/', app.get('port')); });
/** * Payment * * @copyright Copyright (c) 2015 PAYMILL GmbH (https://www.paymill.com) */ var prefilledInputValues = []; $.noConflict(); jQuery(document).ready(function($) { prefilledInputValues = getFormData(); /** * Get values of PAYMILL-Payment form-inputs * @return {[string]} array of PAYMILL form-input-values */ function getFormData() { var formData = []; $('.paymill_input').each(function() { formData.push($(this).val()); }); return formData; } $('#paymillCardNumber').on('input keyup', function() { $("#paymillCardNumber")[0].className = $("#paymillCardNumber")[0].className.replace(/paymill-card-number-.*/g, ''); var cardnumber = $('#paymillCardNumber').val(); var detector = new BrandDetection(); var brand = detector.detect(cardnumber); if (shouldBrandBeRendered(brand)) { $('#paymillCardNumber').addClass("paymill-card-number-" + brand); if (!detector.validate(cardnumber)) { $('#paymillCardNumber').addClass("paymill-card-number-grayscale"); } } }); function shouldBrandBeRendered(brand) { return (brand !== 'unknown' && ($.inArray(brand, PAYMILL_CC_BRANDS) !== -1 || PAYMILL_CC_BRANDS.length === 0)); } function paymillDebug(message) { if (PAYMILL_DEBUG === "1") { console.log(message); } } $(PAYMILL_PAYMENT_FORM).submit(function(event) { var cc = $('#payment_paymill_cc').attr('checked') === 'checked'; var elv = $('#payment_paymill_elv').attr('checked') === 'checked'; if ((cc && !PAYMILL_COMPLIANCE) || elv) { // prevent form submit event.preventDefault(); clearErrors(); // disable submit-button to prevent multiple clicks $(PAYMILL_NEXT_STEP_BUTTON).attr("disabled", "disabled"); if (!isFastCheckout(cc, elv)) { generateToken(cc, elv); } else { fastCheckout(cc, elv); } } return true; }); $('#payment_paymill_cc').click(clearErrors); $('#payment_paymill_elv').click(clearErrors); function clearErrors() { $(".payment-errors").css("display", "none"); $(".payment-errors").text(""); } function isFastCheckout(cc, elv) { if ((cc && PAYMILL_FASTCHECKOUT_CC) || (elv && PAYMILL_FASTCHECKOUT_ELV)) { var formdata = getFormData(); return prefilledInputValues.toString() === formdata.toString(); } return false; } function fastCheckout() { $("#paymill_form").append("<input type='hidden' name='paymillFastcheckout' value='" + true + "'/>"); result = new Object(); result.token = 'dummyToken'; PaymillResponseHandler(null, result); } function generateToken(cc, elv) { var tokenRequestParams = null; var paymentError; var paymentErrorSelectorType = cc? '.cc' : '.elv'; var paymentError = $( '.payment-errors' + paymentErrorSelectorType ); // remove old errors $('.payment-errors' + paymentErrorSelectorType + ' ul').remove(); // @TODO More and better Debugging Messages paymillDebug('Paymill: Start form validation'); if (cc && validatePaymillCcFormData()) { tokenRequestParams = createCcTokenRequestParams(); } else if (elv && validatePaymillElvFormData()) { tokenRequestParams = createElvTokenRequestParams(); } if (tokenRequestParams !== null) { paymill.createToken(tokenRequestParams, PaymillResponseHandler); } else { paymentError.css("display", "inline-block"); $(PAYMILL_NEXT_STEP_BUTTON).removeAttr("disabled"); } } function PaymillResponseHandler(error, result) { if (error) { paymillDebug('An API error occured:' + error.apierror); // shows errors above the PAYMILL specific part of the form $(".payment-errors").text($("<div/>").html(PAYMILL_TRANSLATION["PAYMILL_" + error.apierror]).text()); $(".payment-errors").css("display", "inline-block"); } else { // Token paymillDebug('Received a token: ' + result.token); // add token into hidden input field for request to the server $(PAYMILL_PAYMENT_FORM).append("<input type='hidden' name='paymillToken' value='" + result.token + "'/>"); $(PAYMILL_PAYMENT_FORM).get(0).submit(); } $(PAYMILL_NEXT_STEP_BUTTON).removeAttr("disabled"); } function validatePaymillElvFormData() { var accountNumber = $('#paymillElvAccount').val(); var bankCode = $('#paymillElvBankCode').val(); var accountHolder = $('#paymillElvHolderName').val(); var valid = true; var errors = []; if (!accountHolder) { errors.push(PAYMILL_TRANSLATION.PAYMILL_VALIDATION_ACCOUNTHOLDER); valid = false; } if (isValueAnIban(accountNumber)) { var iban = new Iban(); if (!iban.validate(accountNumber)) { errors.push( PAYMILL_TRANSLATION.PAYMILL_VALIDATION_IBAN ); valid = false; } if (bankCode === "") { errors.push( PAYMILL_TRANSLATION.PAYMILL_VALIDATION_BIC ); valid = false; } } else { if (!paymill.validateAccountNumber(accountNumber)) { errors.push( PAYMILL_TRANSLATION.PAYMILL_VALIDATION_ACCOUNTNUMBER ); valid = false; } if (!paymill.validateBankCode(bankCode)) { errors.push( PAYMILL_TRANSLATION.PAYMILL_VALIDATION_BANKCODE ); valid = false; } } if (!valid) { createErrorBoxMarkup($(".payment-errors.elv"), errors); return valid; } return valid; } function createElvTokenRequestParams() { var tokenRequestParams = null; var accountNumber = $('#paymillElvAccount').val(); var bankCode = $('#paymillElvBankCode').val(); var accountHolder = $('#paymillElvHolderName').val(); if (isValueAnIban(accountNumber)) { tokenRequestParams = { iban: accountNumber.replace(/\s+/g, ""), bic: bankCode, accountholder: accountHolder }; } else { tokenRequestParams = { number: accountNumber, bank: bankCode, accountholder: accountHolder } } return tokenRequestParams; } function isValueAnIban(inputValue) { return /^\D{2}/.test(inputValue); } function validatePaymillCcFormData() { var valid = true; var errors = []; if (!paymill.validateCardNumber($('#paymillCardNumber').val())) { errors.push( PAYMILL_TRANSLATION.PAYMILL_VALIDATION_CARDNUMBER ); valid = false; } if (!paymill.validateExpiry( $('#paymillCardExpiryMonth').val(), $('#paymillCardExpiryYear').val() )) { errors.push(PAYMILL_TRANSLATION.PAYMILL_VALIDATION_EXP); valid = false; } if (!paymill.validateCvc( $('#paymillCardCvc').val(), $('#paymillCardNumber').val() )) { if (paymill.cardType( $('#paymillCardNumber').val() ).toLowerCase() !== 'maestro') { errors.push(PAYMILL_TRANSLATION.PAYMILL_VALIDATION_CVC); valid = false; } } if (!paymill.validateHolder($('#paymillCardHolderName').val())) { errors.push(PAYMILL_TRANSLATION.PAYMILL_VALIDATION_CARDHOLDER); valid = false; } if (!valid) { createErrorBoxMarkup($(".payment-errors.cc"), errors); return valid; } return valid; } /** * Gathers form-input-values and creates request parameters for * creditcard token request. * @return {object} token request paramaters */ function createCcTokenRequestParams() { var cvc = $('#paymillCardCvc').val(); if (cvc === '') { cvc = '000'; } var tokenRequestParams = { amount_int: PAYMILL_AMOUNT, // E.g. "15" for 0.15 Eur currency: PAYMILL_CURRENCY, // ISO 4217 e.g. "EUR" number: $('#paymillCardNumber').val(), exp_month: $('#paymillCardExpiryMonth').val(), exp_year: $('#paymillCardExpiryYear').val(), cvc: cvc, cardholder: $('#paymillCardHolderName').val() }; return tokenRequestParams; } function createErrorBoxMarkup(paymentErrorsContainer, errors) { var list = $('<ul />').appendTo(paymentErrorsContainer); errors.forEach(function(entry) { $('<li />').text( $("<span />").html(entry).text() ).appendTo(list); }); } });
import awaitify from 'awaitify'; const asyncError = (statusCode) => { return awaitify(function * (req, res) { let viewFilePath = String(statusCode), result = { status: statusCode }; try{ yield awaitify.cb((cb) => res.render(viewFilePath, cb)); res.render(viewFilePath); } catch (err){ return res.status(statusCode).json(result); } }) }; export const notFound = asyncError(404); export const invalidData = asyncError(500);
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import { RNEP } from 'react-native-exoplayer'; import PlayerView from './js/PlayerView'; import data from './data.json'; export default class VideoPlayer extends Component { componentDidMount() { //RNEP.isRateSupported().then((result) => { alert("Change of speed is supported: " + result);}); // RNEP.getMaxSupportedVideoPlayersCount("Calculation") // .then((result) => {alert(" max= "+result.maxSupported+" heap="+result.heapSize+" Mb")}); } render() { const players = data.map((props, idx) => <PlayerView key={idx} {...props} />); return ( <View style={styles.container}> {players} </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#F5FCFF', padding: 48 } }); AppRegistry.registerComponent('VideoPlayer', () => VideoPlayer);
module.exports = function (store) { return { name: 'connect.sid', secret: 'sCzo&53ON&ePY@RwmbRCDd3^h7HiEn*QS%aYDBq5MuNCEale8y', resave: true, saveUninitialized: true, store: store }; };
// Acorn: Loose parser // // This module provides an alternative parser (`parse_dammit`) that // exposes that same interface as `parse`, but will try to parse // anything as JavaScript, repairing syntax error the best it can. // There are circumstances in which it will raise an error and give // up, but they are very rare. The resulting AST will be a mostly // valid JavaScript AST (as per the [Mozilla parser API][api], except // that: // // - Return outside functions is allowed // // - Label consistency (no conflicts, break only to existing labels) // is not enforced. // // - Bogus Identifier nodes with a name of `"✖"` are inserted whenever // the parser got too confused to return anything meaningful. // // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API // // The expected use for this is to *first* try `acorn.parse`, and only // if that fails switch to `parse_dammit`. The loose parser might // parse badly indented code incorrectly, so **don't** use it as // your default parser. // // Quite a lot of acorn.js is duplicated here. The alternative was to // add a *lot* of extra cruft to that file, making it less readable // and slower. Copying and editing the code allowed me to make // invasive changes and simplifications without creating a complicated // tangle. (function(mod) { if (typeof exports == "object" && typeof module == "object") return mod(exports, require("./acorn")); // CommonJS if (typeof define == "function" && define.amd) return define(["exports", "./acorn"], mod); // AMD mod(self.acorn || (self.acorn = {}), self.acorn); // Plain browser env })(function(exports, acorn) { "use strict"; var tt = acorn.tokTypes; var options, input, fetchToken, context; exports.parse_dammit = function(inpt, opts) { if (!opts) opts = {}; input = String(inpt); options = opts; if (!opts.tabSize) opts.tabSize = 4; fetchToken = acorn.tokenize(inpt, opts); sourceFile = options.sourceFile || null; context = []; nextLineStart = 0; ahead.length = 0; next(); return parseTopLevel(); }; var lastEnd, token = {start: 0, end: 0}, ahead = []; var curLineStart, nextLineStart, curIndent, lastEndLoc, sourceFile; function next() { lastEnd = token.end; if (options.locations) lastEndLoc = token.endLoc; if (ahead.length) token = ahead.shift(); else token = readToken(); if (token.start >= nextLineStart) { while (token.start >= nextLineStart) { curLineStart = nextLineStart; nextLineStart = lineEnd(curLineStart) + 1; } curIndent = indentationAfter(curLineStart); } } function readToken() { for (;;) { try { return fetchToken(); } catch(e) { if (!(e instanceof SyntaxError)) throw e; // Try to skip some text, based on the error message, and then continue var msg = e.message, pos = e.raisedAt, replace = true; if (/unterminated/i.test(msg)) { pos = lineEnd(e.pos); if (/string/.test(msg)) { replace = {start: e.pos, end: pos, type: tt.string, value: input.slice(e.pos + 1, pos)}; } else if (/regular expr/i.test(msg)) { var re = input.slice(e.pos, pos); try { re = new RegExp(re); } catch(e) {} replace = {start: e.pos, end: pos, type: tt.regexp, value: re}; } else { replace = false; } } else if (/invalid (unicode|regexp|number)|expecting unicode|octal literal|is reserved|directly after number/i.test(msg)) { while (pos < input.length && !isSpace(input.charCodeAt(pos))) ++pos; } else if (/character escape|expected hexadecimal/i.test(msg)) { while (pos < input.length) { var ch = input.charCodeAt(pos++); if (ch === 34 || ch === 39 || isNewline(ch)) break; } } else if (/unexpected character/i.test(msg)) { pos++; replace = false; } else { throw e; } resetTo(pos); if (replace === true) replace = {start: pos, end: pos, type: tt.name, value: "✖", loc: getDummyLoc()}; if (replace) return replace; } } } function resetTo(pos) { var ch = input.charAt(pos - 1); var reAllowed = !ch || /[\[\{\(,;:?\/*=+\-~!|&%^<>]/.test(ch) || /[enwfd]/.test(ch) && /\b(keywords|case|else|return|throw|new|in|(instance|type)of|delete|void)$/.test(input.slice(pos - 10, pos)); fetchToken.jumpTo(pos, reAllowed); } function lookAhead(n) { // Copy token objects, because fetchToken will overwrite the one // it returns, and in this case we still need it if (!ahead.length) token = {start: token.start, end: token.end, type: token.type, value: token.value}; while (n > ahead.length) { var tok = readToken(); ahead.push({start: tok.from, end: tok.end, type: tok.type, value: tok.value}); } return ahead[n-1]; } var newline = /[\n\r\u2028\u2029]/; function isNewline(ch) { return ch === 10 || ch === 13 || ch === 8232 || ch === 8329; } function isSpace(ch) { return (ch < 14 && ch > 8) || ch === 32 || ch === 160 || isNewline(ch); } function pushCx() { context.push(curIndent); } function popCx() { curIndent = context.pop(); } function lineEnd(pos) { while (pos < input.length && !isNewline(input.charCodeAt(pos))) ++pos; return pos; } function lineStart(pos) { while (pos > 0 && !isNewline(input.charCodeAt(pos - 1))) --pos; return pos; } function indentationAfter(pos) { for (var count = 0;; ++pos) { var ch = input.charCodeAt(pos); if (ch === 32) ++count; else if (ch === 9) count += options.tabSize; else return count; } } function closesBlock(closeTok, indent, line) { if (token.type === closeTok || token.type === tt.eof) return true; if (line != curLineStart && curIndent < indent && tokenStartsLine() && (nextLineStart >= input.length || indentationAfter(nextLineStart) < indent)) return true; return false; } function tokenStartsLine() { for (var p = token.start - 1; p > curLineStart; --p) { var ch = input.charCodeAt(p); if (ch !== 9 && ch !== 32) return false; } return true; } function node_t(start) { this.type = null; this.start = start; this.end = null; } function node_loc_t() { this.start = token.startLoc; this.end = null; if (sourceFile !== null) this.source = sourceFile; } function startNode() { var node = new node_t(token.start); if (options.locations) node.loc = new node_loc_t(); return node } function startNodeFrom(other) { var node = new node_t(other.start); if (options.locations) { node.loc = new node_loc_t(); node.loc.start = other.loc.start; } return node; } function finishNode(node, type) { node.type = type; node.end = lastEnd; if (options.locations) node.loc.end = lastEndLoc; return node; } function getDummyLoc(dummy) { if (options.locations) { var loc = new node_loc_t(); loc.end = { line: loc.start.line, column: loc.start.column + 1 }; return loc; } }; function dummyIdent() { var dummy = new node_t(0); dummy.type = "Identifier"; dummy.end = 0; dummy.name = "✖"; dummy.loc = getDummyLoc(); return dummy; } function isDummy(node) { return node.name == "✖"; } function eat(type) { if (token.type === type) { next(); return true; } } function canInsertSemicolon() { return (token.type === tt.eof || token.type === tt.braceR || newline.test(input.slice(lastEnd, token.start))); } function semicolon() { eat(tt.semi); } function expect(type) { if (eat(type)) return true; if (lookAhead(1).type == type) { next(); next(); return true; } if (lookAhead(2).type == type) { next(); next(); next(); return true; } } function checkLVal(expr) { if (expr.type === "Identifier" || expr.type === "MemberExpression") return expr; return dummyIdent(); } function parseTopLevel() { var node = startNode(); node.body = []; while (token.type !== tt.eof) node.body.push(parseStatement()); return finishNode(node, "Program"); } function parseStatement() { var starttype = token.type, node = startNode(); switch (starttype) { case tt.break: case tt.continue: next(); var isBreak = starttype === tt.break; node.label = token.type === tt.name ? parseIdent() : null; semicolon(); return finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); case tt.debugger: next(); semicolon(); return finishNode(node, "DebuggerStatement"); case tt.do: next(); node.body = parseStatement(); node.test = eat(tt.while) ? parseParenExpression() : dummyIdent(); semicolon(); return finishNode(node, "DoWhileStatement"); case tt.for: next(); pushCx(); expect(tt.parenL); if (token.type === tt.semi) return parseFor(node, null); if (token.type === tt.var) { var init = startNode(); next(); parseVar(init, true); if (init.declarations.length === 1 && eat(tt.in)) return parseForIn(node, init); return parseFor(node, init); } var init = parseExpression(false, true); if (eat(tt.in)) {return parseForIn(node, checkLVal(init));} return parseFor(node, init); case tt.function: next(); return parseFunction(node, true); case tt.if: next(); node.test = parseParenExpression(); node.consequent = parseStatement(); node.alternate = eat(tt.else) ? parseStatement() : null; return finishNode(node, "IfStatement"); case tt.return: next(); if (eat(tt.semi) || canInsertSemicolon()) node.argument = null; else { node.argument = parseExpression(); semicolon(); } return finishNode(node, "ReturnStatement"); case tt.switch: var blockIndent = curIndent, line = curLineStart; next(); node.discriminant = parseParenExpression(); node.cases = []; pushCx(); expect(tt.braceL); for (var cur; !closesBlock(tt.braceR, blockIndent, line);) { if (token.type === tt.case || token.type === tt.default) { var isCase = token.type === tt.case; if (cur) finishNode(cur, "SwitchCase"); node.cases.push(cur = startNode()); cur.consequent = []; next(); if (isCase) cur.test = parseExpression(); else cur.test = null; expect(tt.colon); } else { if (!cur) { node.cases.push(cur = startNode()); cur.consequent = []; cur.test = null; } cur.consequent.push(parseStatement()); } } if (cur) finishNode(cur, "SwitchCase"); popCx(); eat(tt.braceR); return finishNode(node, "SwitchStatement"); case tt.throw: next(); node.argument = parseExpression(); semicolon(); return finishNode(node, "ThrowStatement"); case tt.try: next(); node.block = parseBlock(); node.handlers = []; while (token.type === tt.catch) { var clause = startNode(); next(); expect(tt.parenL); clause.param = parseIdent(); expect(tt.parenR); clause.guard = null; clause.body = parseBlock(); node.handlers.push(finishNode(clause, "CatchClause")); } node.finalizer = eat(tt.finally) ? parseBlock() : null; if (!node.handlers.length && !node.finalizer) return node.block; return finishNode(node, "TryStatement"); case tt.var: next(); node = parseVar(node); semicolon(); return node; case tt.while: next(); node.test = parseParenExpression(); node.body = parseStatement(); return finishNode(node, "WhileStatement"); case tt.with: next(); node.object = parseParenExpression(); node.body = parseStatement(); return finishNode(node, "WithStatement"); case tt.braceL: return parseBlock(); case tt.semi: next(); return finishNode(node, "EmptyStatement"); default: var maybeName = token.value, expr = parseExpression(); if (isDummy(expr)) { next(); if (token.type === tt.eof) return finishNode(node, "EmptyStatement"); return parseStatement(); } else if (starttype === tt.name && expr.type === "Identifier" && eat(tt.colon)) { node.body = parseStatement(); node.label = expr; return finishNode(node, "LabeledStatement"); } else { node.expression = expr; semicolon(); return finishNode(node, "ExpressionStatement"); } } } function parseBlock() { var node = startNode(); pushCx(); expect(tt.braceL); var blockIndent = curIndent, line = curLineStart; node.body = []; while (!closesBlock(tt.braceR, blockIndent, line)) node.body.push(parseStatement()); popCx(); eat(tt.braceR); return finishNode(node, "BlockStatement"); } function parseFor(node, init) { node.init = init; node.test = node.update = null; if (eat(tt.semi) && token.type !== tt.semi) node.test = parseExpression(); if (eat(tt.semi) && token.type !== tt.parenR) node.update = parseExpression(); popCx(); expect(tt.parenR); node.body = parseStatement(); return finishNode(node, "ForStatement"); } function parseForIn(node, init) { node.left = init; node.right = parseExpression(); popCx(); expect(tt.parenR); node.body = parseStatement(); return finishNode(node, "ForInStatement"); } function parseVar(node, noIn) { node.declarations = []; node.kind = "var"; while (token.type === tt.name) { var decl = startNode(); decl.id = parseIdent(); decl.init = eat(tt.eq) ? parseExpression(true, noIn) : null; node.declarations.push(finishNode(decl, "VariableDeclarator")); if (!eat(tt.comma)) break; } return finishNode(node, "VariableDeclaration"); } function parseExpression(noComma, noIn) { var expr = parseMaybeAssign(noIn); if (!noComma && token.type === tt.comma) { var node = startNodeFrom(expr); node.expressions = [expr]; while (eat(tt.comma)) node.expressions.push(parseMaybeAssign(noIn)); return finishNode(node, "SequenceExpression"); } return expr; } function parseParenExpression() { pushCx(); expect(tt.parenL); var val = parseExpression(); popCx(); expect(tt.parenR); return val; } function parseMaybeAssign(noIn) { var left = parseMaybeConditional(noIn); if (token.type.isAssign) { var node = startNodeFrom(left); node.operator = token.value; node.left = checkLVal(left); next(); node.right = parseMaybeAssign(noIn); return finishNode(node, "AssignmentExpression"); } return left; } function parseMaybeConditional(noIn) { var expr = parseExprOps(noIn); if (eat(tt.question)) { var node = startNodeFrom(expr); node.test = expr; node.consequent = parseExpression(true); node.alternate = expect(tt.colon) ? parseExpression(true, noIn) : dummyIdent(); return finishNode(node, "ConditionalExpression"); } return expr; } function parseExprOps(noIn) { var indent = curIndent, line = curLineStart; return parseExprOp(parseMaybeUnary(noIn), -1, noIn, indent, line); } function parseExprOp(left, minPrec, noIn, indent, line) { if (curLineStart != line && curIndent < indent && tokenStartsLine()) return left; var prec = token.type.binop; if (prec != null && (!noIn || token.type !== tt.in)) { if (prec > minPrec) { var node = startNodeFrom(left); node.left = left; node.operator = token.value; next(); if (curLineStart != line && curIndent < indent && tokenStartsLine()) node.right = dummyIdent(); else node.right = parseExprOp(parseMaybeUnary(noIn), prec, noIn, indent, line); var node = finishNode(node, /&&|\|\|/.test(node.operator) ? "LogicalExpression" : "BinaryExpression"); return parseExprOp(node, minPrec, noIn, indent, line); } } return left; } function parseMaybeUnary(noIn) { if (token.type.prefix) { var node = startNode(), update = token.type.isUpdate; node.operator = token.value; node.prefix = true; next(); node.argument = parseMaybeUnary(noIn); if (update) node.argument = checkLVal(node.argument); return finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); } var expr = parseExprSubscripts(); while (token.type.postfix && !canInsertSemicolon()) { var node = startNodeFrom(expr); node.operator = token.value; node.prefix = false; node.argument = checkLVal(expr); next(); expr = finishNode(node, "UpdateExpression"); } return expr; } function parseExprSubscripts() { var indent = curIndent, line = curLineStart; return parseSubscripts(parseExprAtom(), false, curIndent, line); } function parseSubscripts(base, noCalls, startIndent, line) { for (;;) { if (curLineStart != line && curIndent <= startIndent && tokenStartsLine()) { if (token.type == tt.dot && curIndent == startIndent) --startIndent; else return base; } if (eat(tt.dot)) { var node = startNodeFrom(base); node.object = base; if (curLineStart != line && curIndent <= startIndent && tokenStartsLine()) node.property = dummyIdent(); else node.property = parsePropertyName() || dummyIdent(); node.computed = false; base = finishNode(node, "MemberExpression"); } else if (token.type == tt.bracketL) { pushCx(); next(); var node = startNodeFrom(base); node.object = base; node.property = parseExpression(); node.computed = true; popCx(); expect(tt.bracketR); base = finishNode(node, "MemberExpression"); } else if (!noCalls && token.type == tt.parenL) { pushCx(); var node = startNodeFrom(base); node.callee = base; node.arguments = parseExprList(tt.parenR); base = finishNode(node, "CallExpression"); } else { return base; } } } function parseExprAtom() { switch (token.type) { case tt.this: var node = startNode(); next(); return finishNode(node, "ThisExpression"); case tt.name: return parseIdent(); case tt.num: case tt.string: case tt.regexp: var node = startNode(); node.value = token.value; node.raw = input.slice(token.start, token.end); next(); return finishNode(node, "Literal"); case tt.null: case tt.true: case tt.false: var node = startNode(); node.value = token.type.atomValue; node.raw = token.type.keyword next(); return finishNode(node, "Literal"); case tt.parenL: var tokStart1 = token.start; next(); var val = parseExpression(); val.start = tokStart1; val.end = token.end; expect(tt.parenR); return val; case tt.bracketL: var node = startNode(); pushCx(); node.elements = parseExprList(tt.bracketR); return finishNode(node, "ArrayExpression"); case tt.braceL: return parseObj(); case tt.function: var node = startNode(); next(); return parseFunction(node, false); case tt.new: return parseNew(); default: return dummyIdent(); } } function parseNew() { var node = startNode(), startIndent = curIndent, line = curLineStart; next(); node.callee = parseSubscripts(parseExprAtom(), true, startIndent, line); if (token.type == tt.parenL) { pushCx(); node.arguments = parseExprList(tt.parenR); } else { node.arguments = []; } return finishNode(node, "NewExpression"); } function parseObj() { var node = startNode(); node.properties = []; pushCx(); next(); var propIndent = curIndent, line = curLineStart; while (!closesBlock(tt.braceR, propIndent, line)) { var name = parsePropertyName(); if (!name) { if (isDummy(parseExpression(true))) next(); eat(tt.comma); continue; } var prop = {key: name}, isGetSet = false, kind; if (eat(tt.colon)) { prop.value = parseExpression(true); kind = prop.kind = "init"; } else if (options.ecmaVersion >= 5 && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set")) { isGetSet = sawGetSet = true; kind = prop.kind = prop.key.name; prop.key = parsePropertyName() || dummyIdent(); prop.value = parseFunction(startNode(), false); } else { next(); eat(tt.comma); continue; } node.properties.push(prop); eat(tt.comma); } popCx(); eat(tt.braceR); return finishNode(node, "ObjectExpression"); } function parsePropertyName() { if (token.type === tt.num || token.type === tt.string) return parseExprAtom(); if (token.type === tt.name || token.type.keyword) return parseIdent(); } function parseIdent() { var node = startNode(); node.name = token.type === tt.name ? token.value : token.type.keyword; next(); return finishNode(node, "Identifier"); } function parseFunction(node, isStatement) { if (token.type === tt.name) node.id = parseIdent(); else if (isStatement) node.id = dummyIdent(); else node.id = null; node.params = []; pushCx(); expect(tt.parenL); while (token.type == tt.name) { node.params.push(parseIdent()); eat(tt.comma); } popCx(); eat(tt.parenR); node.body = parseBlock(); return finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression"); } function parseExprList(close) { var indent = curIndent + 1, line = curLineStart, elts = []; next(); // Opening bracket while (!closesBlock(close, indent, line)) { var elt = parseExpression(true); if (isDummy(elt)) { if (closesBlock(close, indent, line)) break; next(); } else { elts.push(elt); } while (eat(tt.comma)) {} } popCx(); eat(close); return elts; } });
goog.provide("A.B"); goog.provide("A.B.C"); /** * @constructor * @param {number} n */ A.B = function(n) { /** @type {number} */ this.n = n; }; // Aggressively export rather than create static methods/fields /** @return {number} */ A.B.foo = function() { return 4; }; /** @type {number} */ A.B.num = 8; /** @constructor */ A.B.C = function() {}; /** @return {boolean} */ A.B.C.bar = function() { return false; };
import fetch from 'node-fetch' import moment from 'moment' import fs from 'fs' import { isArray } from 'lodash' /** * getGeoTiff * datasource: https://www.nohrsc.noaa.gov/snowfall/ * NOHRSC uploads geotiffs of snowfall at certain times of day. * We pull the previous 6 hours, 24 hours and season totals of snowfall * by finding the nearest available upload of each geotiff. * Then download each geotiff to a file with a filename corresponding * to the data type (i.e. 6h, 24h, or total) and the date that the * geotiff was uploaded. */ // File info for data source // TODO: make season total file dynamic const filePrefixes = [ { prefix: 'sfav2_CONUS_6h_', filename: '6h', interval: 6 }, { prefix: 'sfav2_CONUS_24h_', filename: '24h', interval: 12 }, { prefix: 'sfav2_CONUS_2017093012_to_', filename: 'total', interval: 12 } ] /** * Takes a moment js date object and returns year, month, date, and hour * in correct string format. * @method getDate * @param {Object} datetime moment js date object * @return {Object} */ const getDate = datetime => { return { year: datetime.format('YYYY'), month: datetime.format('MM'), date: datetime.format('DD'), hour: datetime.format('HH') } } /** * Function that returns the date-based datasource url as well as the * corresponding date-based file stream in order to request the most recent data and * download it into a file. * @method getDateFiles * @param {Object} datetime moment js date object * @param {String} prefix prefix of the filename that determines * the date type (6hr, 24hr, season total) * @param {String} filename prefix of destination filename (6h, 24h, ot total) * @return {Object} object with datasource url string and file stream */ const getDateFiles = (datetime, prefix, filename, directories = ['']) => { const { year, month, date, hour } = getDate(datetime) const yearMonth = `${year}${month}` // const directoryStr = directory ? `${directory}/`: '' // Datasource const url = `https://www.nohrsc.noaa.gov/snowfall/data/${yearMonth}/${prefix}${yearMonth}${date}${hour}.tif` // Destination filename const files = directories.map(directory => `input/${directory}${filename}_${year}-${month}-${date}-${hour}.tiff`) return { url, files } } /** * Function that returns the correct hour to request as data is only updated * at certain hours of the day. * @method getHour * @param {Number} hour current utc hour of the day * @param {Number} interval how often data is updated * @return {Number} the nearest hour where data is availble */ const getHour = (hour, interval = 12) => { // const hours = [0,6,12,18].filter(time => ((time % interval) === 0) && hour >= time) return Math.max(...hours) } /** * Fetches nearest avalable geotiff and downloads it to a file * with a filename that contains the datatype (6h, 24h, and total) * as well as the date and hour of when data was uploaded. * @method fetchFile * @param {String} prefix prefix of the filename that determines * the date type (6hr, 24hr, season total) * @param {Object} utc moment js date object * @param {Number} interval how often data is updated * @param {String} filename prefix of destination filename (6h, 24h, ot total) */ const fetchFile = (prefix, utc, interval, filename, directory, backup = true, cb) => { let { url, files } = getDateFiles(utc, prefix, filename, directory) console.log(`DOWNLOADING: ${url}`); fetch(url) .then(res => { if(res.ok) { files.forEach(file => { const stream = fs.createWriteStream(file) console.log(`OUTPUT: ${file}`); res.body.pipe(stream) }) if(cb) cb(prefix, utc, interval, filename) } else if(backup) { let { url, files } = getDateFiles(utc.subtract(interval, 'hours'), prefix, filename, directory) console.log('FILE DOESN\'T EXIST'); console.log(`TRYING: ${url}`); fetch(url) .then(res => { if(res.ok) { files.forEach(file => { const stream = fs.createWriteStream(file) console.log(`OUTPUT: ${file}`); res.body.pipe(stream) }) if(cb) cb(prefix, utc, interval, filename) } else { console.log('SECONDARY FILE DOESN\'T EXIST EITHER'); } }) } }) .catch((err) => { console.log(err); }) } const getPrevious24h = (prefix, utc, interval, filename) => { [1,2,3].forEach(hour => { utc.subtract(interval, 'hours') fetchFile(prefix, utc, interval, filename, ['combine_6h/'], false, () => {}) }) } // Loop through all the file objects and fetch and download // filePrefixes.forEach(obj => { // const { prefix, interval, filename } = obj // const utc = moment.utc() // const hour = getHour(utc.hour(), interval) // // utc.hour(hour) // // fetchFile(prefix, utc, interval, filename) // }) // Get 6hr const utc6hr = moment.utc() const hour = getHour(utc6hr.hour(), 6) utc6hr.hour(hour) fetchFile('sfav2_CONUS_6h_', utc6hr, 6, '6h', ['', 'combine_6h/'], true, getPrevious24h) // Get season total const utcTotal = moment.utc() if(utcTotal.hour() < 12) { utcTotal.subtract(1, 'days') } utcTotal.hour(12) fetchFile('sfav2_CONUS_2018093012_to_', utcTotal, 12, 'total', [''], true)
/* * Utilities.js * Created by CreaturePhil * * This is where extraneous and important functions are stored. * */ var Utilities = exports.Utilities = { HueToRgb: function (m1, m2, hue) { var v; if (hue < 0) hue += 1; else if (hue > 1) hue -= 1; if (6 * hue < 1) v = m1 + (m2 - m1) * hue * 6; else if (2 * hue < 1) v = m2; else if (3 * hue < 2) v = m1 + (m2 - m1) * (2 / 3 - hue) * 6; else v = m1; return (255 * v).toString(16); }, hashColor: function (name) { var crypto = require('crypto'); var hash = crypto.createHash('md5').update(name).digest('hex'); var H = parseInt(hash.substr(4, 4), 16) % 360; var S = parseInt(hash.substr(0, 4), 16) % 50 + 50; var L = parseInt(hash.substr(8, 4), 16) % 20 + 25; var m1, m2, hue; var r, g, b S /= 100; L /= 100; if (S == 0) r = g = b = (L * 255).toString(16); else { if (L <= 0.5) m2 = L * (S + 1); else m2 = L + S - L * S; m1 = L * 2 - m2; hue = H / 360; r = this.HueToRgb(m1, m2, hue + 1 / 3); g = this.HueToRgb(m1, m2, hue); b = this.HueToRgb(m1, m2, hue - 1 / 3); } return 'rgb(' + r + ', ' + g + ', ' + b + ');'; }, formatAMPM: function(date) { var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'PM' : 'AM'; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0'+minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; }, rank: function(user){ var data = fs.readFileSync('config/db/tourWins.csv','utf8'); var row = (''+data).split("\n"); var list = []; for (var i = row.length; i > -1; i--) { if (!row[i]) continue; var parts = row[i].split(","); list.push([toUserid(parts[0]),Number(parts[1])]); } list.sort(function(a,b){ return a[1] - b[1]; }); var arr = list.filter( function( el ) { return !!~el.indexOf(toUserid(user)); }); if (list.indexOf(arr[0]) === -1) { return 'Not Ranked'; } else { return 'Rank <b>' + (list.length-list.indexOf(arr[0])) + '</b> out of ' + list.length; } }, calcElo: function(winner, loser) { var kFactor = 32; var ratingDifference = loser.elo - winner.elo; var expectedScoreWinner = 1 / ( 1 + Math.pow(10, ratingDifference/400) ); var e = kFactor * (1 - expectedScoreWinner); winner.elo = winner.elo + e; loser.elo = loser.elo - e; var arr = [winner.elo, loser.elo]; return arr; }, botDelay: function(botName, room, message) { setTimeout(function(){ room.add('|c|' + Users.users[toUserid(botName)].group + botName + '|' + message); }, (Math.floor(Math.random() * 6) * 1000)); }, spamProtection: function(user, room, connection, message) { if (user.group === ' ') { // flooding check /*if (user.numMsg >= 5 && user.group === ' ') { room.add('|c|'+ user.name+'|'+message); user.popup(botName+' has muted you for 7 minutes. '+ '(spam)'); room.add(''+user.name+' was muted by '+ botName +' for 7 minutes.' + ' (flooding)'); var alts = user.getAlts(); if (alts.length) room.add(""+user.name+"'s alts were also muted: "+alts.join(", ")); room.add('|unlink|' + user.userid); user.mute(room.id, 7*60*1000); user.numMsg = 0; return false; }*/ // numMsgs reset if (user.connected === false) { user.numMsg = 0; user.warnCounter = 0; } if (user.numMsg != 0){ setTimeout(function() { user.numMsg = 0; }, 6000); } // caps check var capsMatch = message.replace(/[^A-Za-z]/g, '').match(/[A-Z]/g); if (capsMatch && this.toId(message).length > 18 && (capsMatch.length >= Math.floor(this.toId(message).length * 0.8))) { room.add('|c|'+ user.name+'|'+message); user.warnCounter++; if (user.warnCounter >= 3) { user.popup(botName+' has muted you for 7 minutes. (caps)'); room.add(''+user.name+' was muted by '+botName+' for 7 minutes.' + ' (caps)'); var alts = user.getAlts(); if (alts.length) room.add(""+user.name+"'s alts were also muted: "+alts.join(", ")); room.add('|unlink|' + user.userid); user.numMsg = 0; user.warnCounter = 0; user.mute(room.id, 7*60*1000); return false; } room.add(''+user.name+' was warned by '+botName+'.' + ' (caps)'); user.send('|c|~|/warn '+'caps'); return false; } // stretch check var stretchMatch = message.toLowerCase().match(/(.)\1{7,}/g); // matches the same character 8 or more times in a row if (stretchMatch) { room.add('|c|'+ user.name+'|'+message); user.warnCounter++; if (user.warnCounter >= 3) { user.popup(botName+' has muted you for 7 minutes. (stretching)'); room.add(''+user.name+' was muted by '+ botName +' for 7 minutes.' + ' (stretching)'); var alts = user.getAlts(); if (alts.length) room.add(""+user.name+"'s alts were also muted: "+alts.join(", ")); room.add('|unlink|' + user.userid); user.numMsg = 0; user.warnCounter = 0; user.mute(room.id, 7*60*1000); return false; } room.add(''+user.name+' was warned by '+botName+'.' + ' (stretching)'); user.send('|c|~|/warn '+'stretching'); return false; } /*var banWords = ['fuck','bitch','nigga','fag','shit','nigger']; for (var i=0;i<banWords.length;i++) { if (message.toLowerCase().indexOf(banWords[i]) >= 0) { room.add('|c|'+ user.name+'|'+message); if (user.warnCounter >= 3) { user.popup(botName+' has muted you for 7 minutes. (Inappropriate word: ' + banWords[i]+')'); room.add(''+user.name+' was muted by '+ botName +' for 7 minutes. (Inappropriate word: ' + banWords[i]+')'); var alts = user.getAlts(); if (alts.length) room.add(""+user.name+"'s alts were also muted: "+alts.join(", ")); room.add('|unlink|' + user.userid); user.numMsg = 0; user.warnCounter = 0; user.mute(room.id, 7*60*1000); return false; } var botMsg = user.name + ' -> Go ahead, make my day. [Inappropriate word: '+banWords[i]+'] [warning]'; this.botDelay(botName, room, botMsg); user.warnCounter++; return false; } }*/ } }, toId: function(text) { return text.toLowerCase().replace(/[^a-z0-9]/g, ''); }, stdin: function(file, name) { var info = " "; var match = false; var data = fs.readFileSync('config/'+file,'utf8'); var row = (''+data).split("\n"); for (var i = row.length; i > -1; i--) { if (!row[i]) continue; var parts = row[i].split(","); var userid = toUserid(parts[0]); if (toUserid(name) == userid) { info = String(parts[1]); match = true; if (match === true) { break; } } } return info; }, findAvatar: function(name) { var info = ""; for (user in Config.customAvatars) { if (user === name) { return Config.customAvatars[user]; } } return 0; } };
var dojoConfig = { parseOnLoad:true }; var map; require(["esri/map", "dojo/domReady!"], function(Map) { map = new Map("mapDiv", { center: [77.0907573, 28.6454414], zoom: 10, basemap: "streets" }); });
// If no env is set, default to development // This needs to be above all other require() // modules to ensure config gets right setting. // Module dependencies var config = require('./config'), express = require('express'), when = require('when'), _ = require('underscore'), semver = require('semver'), fs = require('fs'), errors = require('./errorHandling'), plugins = require('./plugins'), path = require('path'), Polyglot = require('node-polyglot'), mailer = require('./mail'), helpers = require('./helpers'), middleware = require('./middleware'), routes = require('./routes'), packageInfo = require('../../package.json'), models = require('./models'), permissions = require('./permissions'), uuid = require('node-uuid'), api = require('./api'), hbs = require('express-hbs'), // Variables setup, init, dbHash; // If we're in development mode, require "when/console/monitor" // for help in seeing swallowed promise errors, and log any // stderr messages from bluebird promises. if (process.env.NODE_ENV === 'development') { require('when/monitor/console'); } function doFirstRun() { var firstRunMessage = [ 'Welcome to Ghost.', 'You\'re running under the <strong>', process.env.NODE_ENV, '</strong>environment.', 'Your URL is set to', '<strong>' + config().url + '</strong>.', 'See <a href="http://docs.ghost.org/">http://docs.ghost.org</a> for instructions.' ]; return api.notifications.add({ type: 'info', message: firstRunMessage.join(' '), status: 'persistent', id: 'ghost-first-run' }); } function initDbHashAndFirstRun() { return when(api.settings.read('dbHash')).then(function (hash) { // we already ran this, chill // Holds the dbhash (mainly used for cookie secret) dbHash = hash.value; if (dbHash === null) { var initHash = uuid.v4(); return when(api.settings.edit('dbHash', initHash)).then(function (settings) { dbHash = settings.dbHash; return dbHash; }).then(doFirstRun); } return dbHash.value; }); } // Sets up the express server instance. // Instantiates the ghost singleton, // helpers, routes, middleware, and plugins. // Finally it starts the http server. function setup(server) { // Set up Polygot instance on the require module Polyglot.instance = new Polyglot(); // ### Initialisation when.join( // Initialise the models models.init(), // Calculate paths config.paths.updatePaths(config().url) ).then(function () { // Populate any missing default settings return models.Settings.populateDefaults(); }).then(function () { // Initialize the settings cache return api.init(); }).then(function () { // We must pass the api.settings object // into this method due to circular dependencies. return config.theme.update(api.settings); }).then(function () { return when.join( // Check for or initialise a dbHash. initDbHashAndFirstRun(), // Initialize the permissions actions and objects permissions.init() ); }).then(function () { // Initialize mail return mailer.init(); }).then(function () { var adminHbs = hbs.create(); // ##Configuration // return the correct mime type for woff filess express['static'].mime.define({'application/font-woff': ['woff']}); // ## View engine // set the view engine server.set('view engine', 'hbs'); // Create a hbs instance for admin and init view engine server.set('admin view engine', adminHbs.express3({partialsDir: config.paths().adminViews + 'partials'})); // Load helpers helpers.loadCoreHelpers(adminHbs); // ## Middleware middleware(server, dbHash); // ## Routing // Set up API routes routes.api(server); // Set up Admin routes routes.admin(server); // Set up Frontend routes routes.frontend(server); // Are we using sockets? Custom socket or the default? function getSocket() { if (config().server.hasOwnProperty('socket')) { return _.isString(config().server.socket) ? config().server.socket : path.join(config.path().contentPath, process.env.NODE_ENV + '.socket'); } return false; } function startGhost() { // Tell users if their node version is not supported, and exit if (!semver.satisfies(process.versions.node, packageInfo.engines.node)) { console.log( "\nERROR: Unsupported version of Node".red, "\nGhost needs Node version".red, packageInfo.engines.node.yellow, "you are using version".red, process.versions.node.yellow, "\nPlease go to http://nodejs.org to get a supported version".green ); process.exit(0); } // Startup & Shutdown messages if (process.env.NODE_ENV === 'production') { console.log( "Ghost is running...".green, "\nYour blog is now available on", config().url, "\nCtrl+C to shut down".grey ); // ensure that Ghost exits correctly on Ctrl+C process.on('SIGINT', function () { console.log( "\nGhost has shut down".red, "\nYour blog is now offline" ); process.exit(0); }); } else { console.log( ("Ghost is running in " + process.env.NODE_ENV + "...").green, "\nListening on", getSocket() || config().server.host + ':' + config().server.port, "\nUrl configured as:", config().url, "\nCtrl+C to shut down".grey ); // ensure that Ghost exits correctly on Ctrl+C process.on('SIGINT', function () { console.log( "\nGhost has shutdown".red, "\nGhost was running for", Math.round(process.uptime()), "seconds" ); process.exit(0); }); } } // Initialize plugins then start the server plugins.init().then(function () { // ## Start Ghost App if (getSocket()) { // Make sure the socket is gone before trying to create another fs.unlink(getSocket(), function (err) { /*jslint unparam:true*/ server.listen( getSocket(), startGhost ); fs.chmod(getSocket(), '0744'); }); } else { server.listen( config().server.port, config().server.host, startGhost ); } }); }, function (err) { errors.logErrorAndExit(err); }); } // Initializes the ghost application. function init(app) { if (!app) { app = express(); } // The server and its dependencies require a populated config setup(app); } module.exports = init;
var searchData= [ ['max_5fbuffer',['MAX_BUFFER',['../_serial_device_8h.html#a1d5dab30b404fab91608086105afc78c',1,'SerialDevice.h']]], ['message_5fid',['MESSAGE_ID',['../_r_f_i_d_message_8h.html#a62f2aa97339b42876202f212c647ae43',1,'RFIDMessage.h']]], ['msg_5flength',['MSG_LENGTH',['../_r_f_i_d_message_8h.html#aa204ec58d846f2354e6bd239460db89f',1,'RFIDMessage.h']]] ];
/** * @license * Copyright (c) 2017 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http:polymer.github.io/LICENSE.txt * The complete set of authors may be found at http:polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http:polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http:polymer.github.io/PATENTS.txt */ /* eslint-env node */ 'use strict'; const gulp = require('gulp'); const gulpif = require('gulp-if'); const runseq = require('run-sequence'); const del = require('del'); const eslint = require('gulp-eslint'); const fs = require('fs'); const path = require('path'); const mergeStream = require('merge-stream'); const babel = require('gulp-babel'); const size = require('gulp-size'); const lazypipe = require('lazypipe'); const closure = require('google-closure-compiler').gulp(); const minimalDocument = require('./util/minimalDocument.js') const dom5 = require('dom5'); const parse5 = require('parse5'); const DIST_DIR = 'dist'; const BUNDLED_DIR = path.join(DIST_DIR, 'bundled'); const COMPILED_DIR = path.join(DIST_DIR, 'compiled'); const POLYMER_LEGACY = 'polymer.html'; const POLYMER_ELEMENT = 'polymer-element.html'; const polymer = require('polymer-build'); const PolymerProject = polymer.PolymerProject; const {Transform} = require('stream'); class BackfillStream extends Transform { constructor(fileList) { super({objectMode: true}); this.fileList = fileList; } _transform(file, enc, cb) { if (this.fileList) { const origFile = this.fileList.shift(); // console.log(`rename ${file.path} -> ${origFile.path}`) file.path = origFile.path; } cb(null, file); } _flush(cb) { if (this.fileList && this.fileList.length > 0) { this.fileList.forEach((oldFile) => { // console.log(`pumping fake file ${oldFile.path}`) let newFile = oldFile.clone({deep: true, contents: false}); newFile.contents = new Buffer(''); this.push(newFile); }); } cb(); } } let CLOSURE_LINT_ONLY = false; let firstImportFinder = dom5.predicates.AND(dom5.predicates.hasTagName('link'), dom5.predicates.hasAttrValue('rel', 'import')); const licenseHeader = `/** * @license * Copyright (c) 2017 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */`; class AddClosureTypeImport extends Transform { constructor(entryFileName, typeFileName) { super({objectMode: true}); this.target = path.resolve(entryFileName); this.importPath = path.resolve(typeFileName); } _transform(file, enc, cb) { if (file.path === this.target) { let contents = file.contents.toString(); let html = parse5.parse(contents, {locationInfo: true}); let firstImport = dom5.query(html, firstImportFinder); if (firstImport) { let importPath = path.relative(path.dirname(this.target), this.importPath); let importLink = dom5.constructors.element('link'); dom5.setAttribute(importLink, 'rel', 'import'); dom5.setAttribute(importLink, 'href', importPath); dom5.insertBefore(firstImport.parentNode, firstImport, importLink); dom5.removeFakeRootElements(html); file.contents = Buffer(parse5.serialize(html)); } } cb(null, file); } } gulp.task('clean', () => del([DIST_DIR, 'closure.log'])); gulp.task('closure', ['clean'], () => { let entry, splitRx, joinRx, addClosureTypes; function config(path) { entry = path; joinRx = new RegExp(path.split('/').join('\\/')); splitRx = new RegExp(joinRx.source + '_script_\\d+\\.js$'); addClosureTypes = new AddClosureTypeImport(entry, 'externs/polymer-closure-types.html'); } config('polymer.html'); const project = new PolymerProject({ shell: `./${entry}`, fragments: [ 'bower_components/shadycss/apply-shim.html', 'bower_components/shadycss/custom-style-interface.html' ], extraDependencies: [ addClosureTypes.importPath, 'externs/closure-types.js' ] }); function closureLintLogger(log) { let chalk = require('chalk'); // write out log to use with diffing tools later fs.writeFileSync('closure.log', chalk.stripColor(log)); console.error(log); process.exit(-1); } let closurePluginOptions; if (CLOSURE_LINT_ONLY) { closurePluginOptions = { logger: closureLintLogger } } const closureStream = closure({ compilation_level: 'ADVANCED', language_in: 'ES6_STRICT', language_out: 'ES5_STRICT', warning_level: 'VERBOSE', isolation_mode: 'IIFE', assume_function_wrapper: true, rewrite_polyfills: false, new_type_inf: true, checks_only: CLOSURE_LINT_ONLY, polymer_version: 2, externs: [ 'bower_components/shadycss/externs/shadycss-externs.js', 'externs/webcomponents-externs.js', 'externs/closure-types.js', 'externs/polymer-externs.js', ], extra_annotation_name: [ 'appliesMixin', 'mixinClass', 'mixinFunction', 'polymer', 'customElement' ] }, closurePluginOptions); const closurePipeline = lazypipe() .pipe(() => closureStream) .pipe(() => new BackfillStream(closureStream.fileList_)) // process source files in the project const sources = project.sources(); // process dependencies const dependencies = project.dependencies(); // merge the source and dependencies streams to we can analyze the project const mergedFiles = mergeStream(sources, dependencies); const splitter = new polymer.HtmlSplitter(); return mergedFiles .pipe(addClosureTypes) .pipe(project.bundler()) .pipe(splitter.split()) .pipe(gulpif(splitRx, closurePipeline())) .pipe(splitter.rejoin()) .pipe(gulpif(joinRx, minimalDocument())) .pipe(gulpif(joinRx, size({title: 'closure size', gzip: true, showTotal: false, showFiles: true}))) .pipe(gulp.dest(COMPILED_DIR)) }); gulp.task('lint-closure', (done) => { CLOSURE_LINT_ONLY = true; runseq('closure', done); }) gulp.task('estimate-size', ['clean'], () => { const babelPresets = { presets: [['babili', {regexpConstructors: false, simplifyComparisons: false}]] }; const project = new PolymerProject({ shell: POLYMER_LEGACY, fragments: [ 'bower_components/shadycss/apply-shim.html', 'bower_components/shadycss/custom-style-interface.html' ] }); // process source files in the project const sources = project.sources(); // process dependencies const dependencies = project.dependencies(); // merge the source and dependencies streams to we can analyze the project const mergedFiles = mergeStream(sources, dependencies); const bundledSplitter = new polymer.HtmlSplitter(); const bundlePipe = lazypipe() .pipe(() => bundledSplitter.split()) .pipe(() => gulpif(/\.js$/, babel(babelPresets))) .pipe(() => bundledSplitter.rejoin()) .pipe(minimalDocument) return mergedFiles .pipe(project.bundler()) .pipe(gulpif(/polymer\.html$/, bundlePipe())) .pipe(gulpif(/polymer\.html$/, size({ title: 'bundled size', gzip: true, showTotal: false, showFiles: true }))) // write to the bundled folder .pipe(gulp.dest(BUNDLED_DIR)) }); gulp.task('lint', function() { return gulp.src(['lib/**/*.html', 'test/unit/*.html', 'util/*.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('generate-closure-externs', ['clean'], () => { let genClosure = require('@polymer/gen-closure-declarations').generateDeclarations; return genClosure().then((declarations) => { fs.writeFileSync('externs/closure-types.js', `${licenseHeader}${declarations}`); }); });
const assert = require('assert'); const dns = require('dns'); const StatsD = require('../lib/statsd'); const helpers = require('./helpers/helpers.js'); const closeAll = helpers.closeAll; const createServer = helpers.createServer; const createHotShotsClient = helpers.createHotShotsClient; describe('#init', () => { let server; let statsd; let skipClose = false; const clientType = 'client'; afterEach(done => { if (skipClose) { done(); } else { closeAll(server, statsd, false, done); } server = null; statsd = null; global.statsd = undefined; skipClose = false; delete process.env.DD_AGENT_HOST; delete process.env.DD_DOGSTATSD_PORT; delete process.env.DD_ENTITY_ID; }); it('should set the proper values when specified', () => { // cachedDns isn't tested here, hence the null statsd = createHotShotsClient( ['host', 1234, 'prefix', 'suffix', true, null, true, ['gtag'], 0, 60, false, 0.5, 'udp'], clientType ); assert.strictEqual(statsd.host, 'host'); assert.strictEqual(statsd.port, 1234); assert.strictEqual(statsd.prefix, 'prefix'); assert.strictEqual(statsd.suffix, 'suffix'); assert.strictEqual(statsd, global.statsd); assert.strictEqual(statsd.mock, true); assert.deepStrictEqual(statsd.globalTags, ['gtag']); assert.strictEqual(statsd.maxBufferSize, 0); assert.strictEqual(statsd.bufferFlushInterval, 60); assert.strictEqual(statsd.telegraf, false); assert.strictEqual(statsd.sampleRate, 0.5); assert.strictEqual(statsd.protocol, 'udp'); }); it('should set the proper values with options hash format', () => { // Don't do DNS lookup for this test const originalLookup = dns.lookup; dns.lookup = () => {}; // eslint-disable-line no-empty-function // cachedDns isn't tested here, hence the null statsd = createHotShotsClient({ host: 'host', port: 1234, prefix: 'prefix', suffix: 'suffix', globalize: true, mock: true, globalTags: ['gtag'], sampleRate: 0.6, maxBufferSize: 0, bufferFlushInterval: 60, telegraf: false, protocol: 'tcp' }, clientType); assert.strictEqual(statsd.host, 'host'); assert.strictEqual(statsd.port, 1234); assert.strictEqual(statsd.prefix, 'prefix'); assert.strictEqual(statsd.suffix, 'suffix'); assert.strictEqual(statsd, global.statsd); assert.strictEqual(statsd.mock, true); assert.strictEqual(statsd.sampleRate, 0.6); assert.deepStrictEqual(statsd.globalTags, ['gtag']); assert.strictEqual(statsd.maxBufferSize, 0); assert.strictEqual(statsd.bufferFlushInterval, 60); assert.deepStrictEqual(statsd.telegraf, false); assert.strictEqual(statsd.protocol, 'tcp'); dns.lookup = originalLookup; }); it('should get host and port values from env vars when not specified', () => { // set the DD_AGENT_HOST and DD_DOGSTATSD_PORT env vars process.env.DD_AGENT_HOST = 'envhost'; process.env.DD_DOGSTATSD_PORT = '1234'; statsd = createHotShotsClient({}, clientType); assert.strictEqual(statsd.host, 'envhost'); assert.strictEqual(statsd.port, 1234); assert.strictEqual(statsd.prefix, ''); assert.strictEqual(statsd.suffix, ''); assert.strictEqual(global.statsd, undefined); assert.strictEqual(statsd.mock, undefined); assert.deepStrictEqual(statsd.globalTags, []); assert.ok(!statsd.mock); assert.strictEqual(statsd.sampleRate, 1); assert.strictEqual(statsd.maxBufferSize, 0); assert.strictEqual(statsd.bufferFlushInterval, 1000); assert.strictEqual(statsd.telegraf, false); assert.strictEqual(statsd.protocol, 'udp'); }); it('should set default values when not specified', () => { statsd = createHotShotsClient({}, clientType); assert.strictEqual(statsd.host, undefined); assert.strictEqual(statsd.port, 8125); assert.strictEqual(statsd.prefix, ''); assert.strictEqual(statsd.suffix, ''); assert.strictEqual(global.statsd, undefined); assert.strictEqual(statsd.mock, undefined); assert.deepStrictEqual(statsd.globalTags, []); assert.ok(!statsd.mock); assert.strictEqual(statsd.sampleRate, 1); assert.strictEqual(statsd.maxBufferSize, 0); assert.strictEqual(statsd.bufferFlushInterval, 1000); assert.strictEqual(statsd.telegraf, false); assert.strictEqual(statsd.protocol, 'udp'); }); it('should map global_tags to globalTags for backwards compatibility', () => { statsd = createHotShotsClient({ global_tags: ['gtag'] }, clientType); assert.deepStrictEqual(statsd.globalTags, ['gtag']); }); it('should get the dd.internal.entity_id tag from DD_ENTITY_ID env var', () => { // set the DD_ENTITY_ID env var process.env.DD_ENTITY_ID = '04652bb7-19b7-11e9-9cc6-42010a9c016d'; statsd = createHotShotsClient({}, clientType); assert.deepStrictEqual(statsd.globalTags, ['dd.internal.entity_id:04652bb7-19b7-11e9-9cc6-42010a9c016d']); }); it('should get the dd.internal.entity_id tag from DD_ENTITY_ID env var and append it to existing tags', () => { // set the DD_ENTITY_ID env var process.env.DD_ENTITY_ID = '04652bb7-19b7-11e9-9cc6-42010a9c016d'; statsd = createHotShotsClient({ globalTags: ['gtag'] }, clientType); assert.deepStrictEqual(statsd.globalTags, ['gtag', 'dd.internal.entity_id:04652bb7-19b7-11e9-9cc6-42010a9c016d']); }); it('should not lookup a dns record if dnsCache is not specified', done => { const originalLookup = dns.lookup; // Replace the dns lookup function with our mock dns lookup dns.lookup = () => { assert.ok(false, 'StatsD constructor should not invoke dns.lookup when dnsCache is unspecified'); dns.lookup = originalLookup; }; statsd = createHotShotsClient({ host: 'test' }, clientType); process.nextTick(() => { dns.lookup = originalLookup; done(); }); }); it('should given an error in callbacks for a bad dns record if dnsCache is specified', done => { const originalLookup = dns.lookup; // Replace the dns lookup function with our mock dns lookup dns.lookup = (host, callback) => { return callback(new Error('Bad host')); }; statsd = createHotShotsClient({ host: 'test', cacheDns: true }, clientType); statsd.increment('test', 1, 1, null, err => { assert.strictEqual(err.message, 'Error sending hot-shots message: Error: Bad host'); dns.lookup = originalLookup; done(); }); }); it('should create a global variable set to StatsD() when specified', () => { statsd = createHotShotsClient(['host', 1234, 'prefix', 'suffix', true], clientType); assert.ok(global.statsd instanceof StatsD); }); it('should not create a global variable when not specified', () => { statsd = createHotShotsClient(['host', 1234, 'prefix', 'suffix'], clientType); assert.strictEqual(global.statsd, undefined); }); it('should create a mock Client when mock variable is specified', () => { statsd = createHotShotsClient(['host', 1234, 'prefix', 'suffix', false, false, true], clientType); assert.ok(statsd.mock); }); it('should create a socket variable that is an instance of dgram.Socket', () => { statsd = createHotShotsClient({}, clientType); assert.strictEqual(statsd.socket.type, 'udp'); skipClose = true; }); it('should set the closingFlushInterval option with the provided value', () => { statsd = createHotShotsClient({ closingFlushInterval: 10 }, clientType); assert.strictEqual(statsd.closingFlushInterval, 10); }); it('should set the closingFlushInterval option with the default value', () => { statsd = createHotShotsClient({}, clientType); assert.strictEqual(statsd.closingFlushInterval, 50); }); it('should create a socket variable that is an instance of net.Socket if set to TCP', done => { server = createServer('tcp', opts => { statsd = createHotShotsClient(opts, clientType); assert.strictEqual(statsd.socket.type, 'tcp'); done(); }); }); });
export const KEYS = [ 'AUTHOR', 'CONTRIBUTOR', 'FOLLOW' ]; export const LABELS = Object.freeze({ AUTHOR: "Documents I am author", CONTRIBUTOR: "Documents I am contributor", FOLLOW: "Documents I follow" }); export const CHECKBOX_LABELS = Object.freeze({ AUTHOR: "Documents I am author", CONTRIBUTOR: "Documents I am contributor", FOLLOW: "Documents I follow" }); export const SORT_KEYS = { DATE: 'DATE', NAME: 'NAME' }; export const SORT_KEYS_LIST = [ SORT_KEYS.DATE, SORT_KEYS.NAME ]; export const SORT_LABELS = Object.freeze({ DATE: "Sort by last updated", NAME: "Sort by document name" });
var http = require('http') var url = process.argv[2] http.get(url, res => { res.setEncoding('utf8') res.on('data', chunk => { console.log(chunk) }) res.on('end', () => {}) res.on('error', () => {}) }).on('error', (e) => { console.error(`Got error: ${e.message}`); })
import { combineReducers } from 'redux' import tabs from './tabs' import activeTab from './active-tab' import input from './input' import isInputFocus from './is-input-focus' import isIncognito from './is-incognito' export default combineReducers({ tabs, activeTab, input, isInputFocus, isIncognito, })
class ReplicationInfo { constructor () { this.reset() } reset () { this.progress = 0 this.max = 0 this.buffered = 0 this.queued = 0 } } module.exports = ReplicationInfo
/*global module, console*/ module.exports = function observable(base) { 'use strict'; let listeners = []; base.addEventListener = function (types, listener, priority) { types.split(' ').forEach(function (type) { if (type) { listeners.push({ type: type, listener: listener, priority: priority || 0 }); } }); }; base.listeners = function (type) { return listeners.filter(function (listenerDetails) { return listenerDetails.type === type; }).map(function (listenerDetails) { return listenerDetails.listener; }); }; base.removeEventListener = function (type, listener) { listeners = listeners.filter(function (details) { return details.listener !== listener; }); }; base.dispatchEvent = function (type) { const args = Array.prototype.slice.call(arguments, 1); listeners .filter(function (listenerDetails) { return listenerDetails.type === type; }) .sort(function (firstListenerDetails, secondListenerDetails) { return secondListenerDetails.priority - firstListenerDetails.priority; }) .some(function (listenerDetails) { try { return listenerDetails.listener.apply(undefined, args) === false; } catch (e) { console.log('dispatchEvent failed', e, listenerDetails); } }); }; return base; };
import config from './config'; import { collisionObjs } from './collision'; import { initName } from './utils'; let backBtn = document.querySelector('.back-btn'); let resetBtn = document.querySelector('.reset-btn'); let successMask = document.querySelector('.success-mask'); let goalGetBox = document.querySelector('.goal-get'); let goalTotalBox = document.querySelector('.goal-total'); /** * conf { * len: [x,y,z] * pos: [x,y,z] * color: 0xffffff; * shadow: boolean, * transparent: boolean, * opacity: number, * } */ export function createNormalBlock(conf) { var obj = new THREE.Mesh(new THREE.BoxGeometry(...conf.len), new THREE.MeshLambertMaterial({ map: config.texture[conf.type], transparent: conf.transparent || false, opacity: conf.opacity || 0.45, }) ); obj.position.set(...conf.pos); if(conf.shadow !== false) { obj.castShadow = true; obj.receiveShadow = true; } return obj; } export function createDoor(conf) { let objs = []; let xx = conf.pos[0]; let yy = conf.pos[1]; let zz = conf.pos[2]; let doorH = conf.doorH || 10; let doorW = conf.doorW || 10; let doorT = conf.doorT || 2; objs[0] = new THREE.Mesh(new THREE.BoxGeometry(doorT, doorH, doorT), new THREE.MeshLambertMaterial({ map: config.texture.wood, }) ); if(conf.zz) { objs[0].position.set(xx + (doorW/2 - doorT/2), yy + doorH/2, zz); } else { objs[0].position.set(xx, yy + doorH/2, zz + (doorW/2 - doorT/2)); } objs[1] = new THREE.Mesh(new THREE.BoxGeometry(doorT, doorH, doorT), new THREE.MeshLambertMaterial({ map: config.texture.wood, }) ); if(conf.zz) { objs[1].position.set(xx - (doorW/2 - doorT/2), yy + doorH/2, zz); } else { objs[1].position.set(xx, yy + doorH/2, zz - (doorW/2 - doorT/2)); } if(conf.zz) { objs[2] = new THREE.Mesh(new THREE.BoxGeometry(doorW, doorT, doorT), new THREE.MeshLambertMaterial({ map: config.texture.wood, }) ); } else { objs[2] = new THREE.Mesh(new THREE.BoxGeometry(doorT, doorT, doorW), new THREE.MeshLambertMaterial({ map: config.texture.wood, }) ); } objs[2].position.set(xx, yy + doorH - doorT/2, zz); collisionObjs.push(...objs); objs.forEach((v) => { v.castShadow = true; v.receiveShadow = true; config.scene.add(v); }) } export function createWindow(conf) { let objs = []; let xx = conf.pos[0]; let yy = conf.pos[1]; let zz = conf.pos[2]; let WinL = conf.WinL || 10; let WinT = conf.WinT || 2; let offset = WinL/2 - WinT/2; objs[0] = new THREE.Mesh(new THREE.BoxGeometry(WinT, WinL, WinT), new THREE.MeshLambertMaterial({ map: config.texture.wood, }) ); objs[0].position.set(xx + offset, yy, zz); objs[1] = new THREE.Mesh(new THREE.BoxGeometry(WinT, WinL, WinT), new THREE.MeshLambertMaterial({ map: config.texture.wood, }) ); objs[1].position.set(xx - offset, yy, zz); objs[2] = new THREE.Mesh(new THREE.BoxGeometry(WinL, WinT, WinT), new THREE.MeshLambertMaterial({ map: config.texture.wood, }) ); objs[2].position.set(xx, yy + offset, zz); objs[3] = new THREE.Mesh(new THREE.BoxGeometry(WinL, WinT, WinT), new THREE.MeshLambertMaterial({ map: config.texture.wood, }) ); objs[3].position.set(xx, yy - offset, zz); collisionObjs.push(...objs); objs.forEach((v) => { v.castShadow = true; v.receiveShadow = true; config.scene.add(v); }) } export function createBowl(conf) { let objs = []; let xx = conf.pos[0]; let yy = conf.pos[1]; let zz = conf.pos[2]; let bowlW = conf.bowlW || 20; let sideW = conf.sideW || 2; let bottomH = conf.bottomH || 1; let sideH = conf.sideH || 3; objs[0] = new THREE.Mesh(new THREE.BoxGeometry(bowlW, bottomH, bowlW), new THREE.MeshLambertMaterial({ map: config.texture.dirt, }) ); objs[0].position.set(xx, yy + bottomH/2, zz); objs[1] = new THREE.Mesh(new THREE.BoxGeometry(sideW, sideH, bowlW), new THREE.MeshLambertMaterial({ map: config.texture.dirt, }) ); objs[1].position.set(xx + (bowlW/2 - sideW/2), yy + bottomH + sideH/2, zz); objs[2] = new THREE.Mesh(new THREE.BoxGeometry(sideW, sideH, bowlW), new THREE.MeshLambertMaterial({ map: config.texture.dirt, }) ); objs[2].position.set(xx - (bowlW/2 - sideW/2), yy + bottomH + sideH/2, zz); objs[3] = new THREE.Mesh(new THREE.BoxGeometry(bowlW, sideH, sideW), new THREE.MeshLambertMaterial({ map: config.texture.dirt, }) ); objs[3].position.set(xx, yy + bottomH + sideH/2, zz + (bowlW/2 - sideW/2)); objs[4] = new THREE.Mesh(new THREE.BoxGeometry(bowlW, sideH, sideW), new THREE.MeshLambertMaterial({ map: config.texture.dirt, }) ); objs[4].position.set(xx, yy + bottomH + sideH/2, zz - (bowlW/2 - sideW/2)); collisionObjs.push(...objs); objs.forEach((v) => { v.castShadow = true; v.receiveShadow = true; config.scene.add(v); }) } export function createStairs(conf) { let objs = []; let xx = conf.pos[0]; let yy = conf.pos[1]; let zz = conf.pos[2]; let stairW = conf.stairW || 8; let stairH = conf.stairH || 1; let count = conf.count || 5; for(let i = 0;i < count;i++) { objs[i] = new THREE.Mesh(new THREE.BoxGeometry(stairW, stairH, stairW), new THREE.MeshLambertMaterial({ map: config.texture.stone, }) ); if(conf.xx){ objs[i].position.set(xx + conf.xx*i*stairW/2, yy + stairH/2 + i*stairH, zz); } else if(conf.zz) { objs[i].position.set(xx, yy + stairH/2 + i*stairH, zz + conf.zz*i*stairW/2); } } collisionObjs.push(...objs); objs.forEach((v) => { v.castShadow = true; v.receiveShadow = true; config.scene.add(v); }) } export function createGoal(conf) { var obj = new THREE.Mesh(new THREE.BoxGeometry(3, 3, 3), new THREE.MeshLambertMaterial({ map: config.texture.light, transparent: true, opacity: 0.6, }) ); config.goalTotal++; goalTotalBox.textContent = config.goalTotal; obj.position.set(conf.pos[0], conf.pos[1] + 1.5, conf.pos[2]); obj.name = initName(); obj.penetrable = true; obj.refresh = -1; obj.callback = function() { config.goalGet++; goalGetBox.textContent = config.goalGet; if(config.goalGet === config.goalTotal) { clearInterval(config.timeID); successMask.style.display = 'block'; backBtn.className = 'back-btn back-btn-mask'; resetBtn.className = 'reset-btn reset-btn-mask'; config.isP = true; } }; collisionObjs.push(obj); config.scene.add(obj); }
/* eslint no-unused-expressions: 0 */ /* global sinon */ import LayoutHelpers from "src/layout-helpers"; import { Scale } from "victory-util"; describe("layout-helpers", () => { describe("getBarPosition", () => { let sandbox; beforeEach(() => { sandbox = sinon.sandbox.create(); sandbox.spy(LayoutHelpers, "getYOffset"); sandbox.spy(LayoutHelpers, "adjustX"); }); afterEach(() => { sandbox.restore(); }); const domain = {x: [0, 10], y: [0, 10]}; const range = {x: [0, 100], y: [0, 100]}; const scale = { x: Scale.getBaseScale({scale: "linear"}, "x").domain(domain.x).range(range.x), y: Scale.getBaseScale({scale: "linear"}, "y").domain(domain.y).range(range.y) }; const style = {data: {width: 10, padding: 10}}; const datasets = [ {data: [{x: 1, y: 0}, {x: 2, y: 0}, {x: 3, y: 0}], attrs: {name: "one"}}, {data: [{x: 1, y: 1}, {x: 2, y: 1}, {x: 3, y: 1}], attrs: {name: "two"}}, {data: [{x: 1, y: 2}, {x: 2, y: 2}, {x: 3, y: 2}], attrs: {name: "three"}} ]; it("should not calculate an yOffset if the data is not stacked", () => { const calculatedProps = {scale, domain, range, style, datasets, stacked: false}; const data = {x: 1, y: 1}; const index = {seriesIndex: 1, barIndex: 0}; const barPosition = LayoutHelpers.getBarPosition(data, index, calculatedProps); expect(LayoutHelpers.getYOffset).not.called; expect(LayoutHelpers.adjustX).calledWith(data, index.seriesIndex, calculatedProps) .and.returned(1); expect(barPosition).to.eql({independent: 10, dependent0: 0, dependent1: 10}); }); it("should not adjustX if the data is stacked and doesn't contain categories", () => { const calculatedProps = {scale, domain, range, style, datasets, stacked: true}; const data = {x: 1, y: 2}; const index = {seriesIndex: 2, barIndex: 0}; const barPosition = LayoutHelpers.getBarPosition(data, index, calculatedProps); expect(LayoutHelpers.adjustX).notCalled; expect(LayoutHelpers.getYOffset).calledWith(data, index, calculatedProps) .and.returned(1); expect(barPosition).to.eql({independent: 10, dependent0: 10, dependent1: 30}); }); }); describe("shouldPlotLabel", () => { const datasets = [ {data: [{x: 1, y: 0}, {x: 2, y: 0}, {x: 3, y: 0}], attrs: {name: "one"}}, {data: [{x: 1, y: 1}, {x: 2, y: 1}, {x: 3, y: 1}], attrs: {name: "two"}}, {data: [{x: 1, y: 2}, {x: 2, y: 2}, {x: 3, y: 2}], attrs: {name: "three"}} ]; const labels = ["one", "two", "three"]; it("only plots a label above the center series when bars are not stacked", () => { const props = {labels}; expect(LayoutHelpers.shouldPlotLabel(0, props, datasets)).to.be.false; expect(LayoutHelpers.shouldPlotLabel(1, props, datasets)).to.be.true; expect(LayoutHelpers.shouldPlotLabel(2, props, datasets)).to.be.false; }); it("only plots a label above the last series when bars are stacked", () => { const props = {labels, stacked: true}; expect(LayoutHelpers.shouldPlotLabel(0, props, datasets)).to.be.false; expect(LayoutHelpers.shouldPlotLabel(1, props, datasets)).to.be.false; expect(LayoutHelpers.shouldPlotLabel(2, props, datasets)).to.be.true; }); const individualLabels = [ ["one 1", "two 1", "three 1"], ["one 2", "two 2", "three 2"], ["one 3", "two 3", "three 3"] ]; it("plots a label above every bar in series when individual labels are provided", () => { const props = {labels: individualLabels}; expect(LayoutHelpers.shouldPlotLabel(0, props, datasets)).to.be.true; expect(LayoutHelpers.shouldPlotLabel(1, props, datasets)).to.be.true; expect(LayoutHelpers.shouldPlotLabel(2, props, datasets)).to.be.true; }); }); describe("getLabelIndex", () => { it.skip("determines the label index", () => { }); }); });
var should = require('should'), done = require('../done'), bee = require('../../bee/58.com/job'); describe('58 - 招聘详情', function () { var url = 'http://gz.58.com/zpshengchankaifa/21243256343177x.shtml?PGTID=14290300745240.888409024104476&ClickID=7'; it('抓取招聘信息', done(bee, url)); });
'use strict'; angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication', function($scope, $http, $location, Authentication) { $scope.authentication = Authentication; // If user is signed in then redirect back home if ($scope.authentication.user) $location.path('/databases'); $scope.signup = function() { $http.post('/auth/signup', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/databases'); }).error(function(response) { $scope.error = response.message; }); }; $scope.signin = function() { $http.post('/auth/signin', $scope.credentials).success(function(response) { // If successful we assign the response to the global user model $scope.authentication.user = response; // And redirect to the index page $location.path('/databases'); }).error(function(response) { $scope.error = response.message; }); }; } ]);
'use strict'; /** * Module dependencies. */ var $mongoose = require('mongoose'), Schema = $mongoose.Schema, $async = require('async'), _ = require('lodash'), $aclPlugin = require('../plugins/accessControlListsModel'); var routeSchema = new Schema({ path: { type: String, required: true } }); routeSchema.plugin($aclPlugin, {noadmin: true}); routeSchema.statics.whatResources = function(userId, callback) { var routes = {}; var RouteModel = this; RouteModel.find().exec(function(err, routeDocs) { $async.filter(routeDocs, function(routeDoc, filterRouteDocTaskDone) { routeDoc.isAllowed('read', function(err, isAllowed) { filterRouteDocTaskDone(isAllowed); }); }, function(routeDocsFiltered) { _.forEach(routeDocsFiltered, function(routeDoc) { routes[routeDoc.path] = true; }); callback(null, routes); }); }); }; var Route = $mongoose.model('Route', routeSchema); module.exports = Route;
module.exports = function(sequelize, Sequelize) { // Sequelize user model is initialized earlier as User var Provider = sequelize.define('provider', { id: { autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER}, provider_name: { type: Sequelize.STRING} }); return Provider; }
$(function () { /**** Radar Charts: ChartJs ****/ var radarChartData = { labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Cycling", "Running"], datasets: [ { label: "My First dataset", backgroundColor: "rgba(220,220,220,0.2)", borderColor: "rgba(220,220,220,1)", pointBackgroundColor: "rgba(220,220,220,1)", pointBorderColor: "#fff", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "rgba(220,220,220,1)", data: [65,59,90,81,56,55,40] }, { label: "My Second dataset", backgroundColor: "rgba(49, 157, 181,0.2)", borderColor: "#319DB5", pointBackgroundColor: "#319DB5", pointBorderColor: "#fff", pointHoverBackgroundColor: "#fff", pointHoverBorderColor: "#319DB5", data: [28,48,40,19,96,27,100] } ] }; var ctx = document.getElementById("radar-chart").getContext("2d"); var myRadarChart = new Chart(ctx, { type: 'radar', data: radarChartData, options: { scale: { ticks: { display: false }, gridLines: { color: 'rgba(0,0,0,0.05)' } }, legend:{ display: false }, tooltips : { cornerRadius: 0 } } }); /**** Line Charts: ChartJs ****/ var randomScalingFactor = function(){ return Math.round(Math.random()*100)}; var lineChartData = { labels : ["January","February","March","April","May","June","July"], datasets : [ { label: "My First dataset", backgroundColor : "rgba(220,220,220,0.2)", borderColor : "rgba(220,220,220,1)", pointBackgroundColor : "rgba(220,220,220,1)", pointBorderColor : "#fff", pointHoverBackgroundColor : "#fff", pointHoverBorderColor : "rgba(220,220,220,1)", data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()] }, { label: "My Second dataset", backgroundColor : "rgba(49, 157, 181,0.2)", borderColor : "#319DB5", pointBackgroundColor : "#319DB5", pointBorderColor : "#fff", pointHoverBackgroundColor : "#fff", pointHoverBorderColor : "#319DB5", data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()] } ] } var ctx = document.getElementById("line-chart").getContext("2d"); var myLineChart = new Chart(ctx, { type: 'line', data: lineChartData, options: { scales : { xAxes : [{ gridLines : { color : 'rgba(0,0,0,0.05)' } }], yAxes : [{ gridLines : { color : 'rgba(0,0,0,0.05)' } }] }, legend:{ display: false }, tooltips : { cornerRadius: 0 } } }); /**** Pie Chart : ChartJs ****/ var pieData = { labels: [ "Blue", "Red", "Yellow", "Green", "Dark Grey" ], datasets: [ { data: [300, 40, 100, 40, 120], backgroundColor: [ "rgba(54, 173, 199,0.9)", "rgba(201, 98, 95,0.9)", "rgba(255, 200, 112,0.9)", "rgba(100, 200, 112,0.9)", "rgba(97, 103, 116,0.9)" ], hoverBackgroundColor: [ "rgba(54, 173, 199,1)", "rgba(201, 98, 95,1)", "rgba(255, 200, 112,1)", "rgba(100, 200, 112,1)", "rgba(97, 103, 116,1)" ] }] }; var pieData2 = { labels: [ "Green", "Yellow", "Blue", "Red", "Dark Grey" ], datasets: [ { data: [80, 120, 80, 60, 60], backgroundColor: [ "rgba(27, 184, 152,0.9)", "rgba(255, 200, 112,0.9)", "rgba(54, 173, 199,0.9)", "rgba(201, 98, 95,0.9)", "rgba(97, 103, 116,0.9)" ], hoverBackgroundColor: [ "rgba(27, 184, 152,1)", "rgba(255, 200, 112,1)", "rgba(54, 173, 199,1)", "rgba(201, 98, 95,1)", "rgba(97, 103, 116,1)" ] }] }; var ctx = document.getElementById("pie-chart").getContext("2d"); var myPieChart = new Chart(ctx,{ type: 'pie', data: pieData, options: { legend:{ display: false }, } }); var ctx = document.getElementById("pie-chart2").getContext("2d"); var myPieChart2 = new Chart(ctx,{ type: 'pie', data: pieData2, options: { legend:{ display: false }, } }); /**** Polar Chart : ChartJs ****/ var polarData = { datasets: [{ data: [80,120,80,60,60], backgroundColor: [ "rgba(27, 184, 152,0.9)", "rgba(255, 200, 112,0.9)", "rgba(54, 173, 199,0.9)", "rgba(201, 98, 95,0.9)", "rgba(97, 103, 116,0.9)" ], hoverBackgroundColor: [ "rgba(27, 184, 152,1)", "rgba(255, 200, 112,1)", "rgba(54, 173, 199,1)", "rgba(201, 98, 95,1)", "rgba(97, 103, 116,1)" ] }], labels: [ "Green", "Yellow", "Blue", "Red", "Dark Grey" ] }; var polarData2 = { datasets: [{ data: [300,40,100,50,120], backgroundColor: [ "rgba(54, 173, 199,0.9)", "rgba(201, 98, 95,0.9)", "rgba(255, 200, 112,0.9)", "rgba(27, 184, 152,0.9)", "rgba(97, 103, 116,0.9)" ], hoverBackgroundColor: [ "rgba(54, 173, 199,1)", "rgba(201, 98, 95,1)", "rgba(255, 200, 112,1)", "rgba(27, 184, 152,1)", "rgba(97, 103, 116,1)" ] }], labels: [ "Blue", "Red", "Yellow", "Green", "Dark Grey" ] }; var ctx = document.getElementById("polar-chart").getContext("2d"); var myPolarChart = new Chart(ctx, { data: polarData, type: 'polarArea', options: { legend:{ display: false }, } }); var ctx = document.getElementById("polar-chart2").getContext("2d"); var myPolarChart = new Chart(ctx, { data: polarData2, type: 'polarArea', options: { legend:{ display: false }, } }); });
Dashboard.views.LabelShow = Marionette.View.extend({ template: "#js-label-show", className: "container--small", modelEvents: { "change" : "render" }, regions: { "update": "#js-update-region" }, onRender: function() { this.showChildView('update', new Dashboard.views.LabelUpdate({model: this.model})); } });
var MainApp = Em.Application.create({ LOG_TRANSITIONS: true, ready: function () { MainApp.AppContainerView = Em.ContainerView.extend({}); MainApp.ModalContainerView = Em.ContainerView.extend({}); Ember.run.later(this, function() { MainAppController.getData(); }, 100); } }); var Cities = CollectionArray.create({ paginationSelector: "#cities-paging", itemsPerPage : 6 }); MainAppController = Em.ArrayController.create({ DataState : InputState.create(), sourceUrl : "http://api.openweathermap.org/data/2.5/box/city?bbox=2,32,15,37,10&cluster=yes", getData : function(){ postObject(this.sourceUrl,MainAppController.SuccessData, MainAppController.DataState) }, SuccessData : function(data){ if(data.cod != "200"){ alert("Sorry an error occurred"); return; } Cities.addContent(data.list); cleanLoading(MainAppController.DataState); } }); MainAppView = Ember.View.extend({ actions: { selectCity: function(city) { }, searchCity : function(){ var value = $("#searchCity").val().trim(); if (!value) Cities.cleanFilter(); else Cities.filterContent("name", value.toUpperCase(), true); } } }); function postObject(url,successCallback,context){ setLoading(context); $.getJSON(url, successCallback); } function setLoading(context){ if(context==null) return; context.set("loading","loading-container hidden"); context.set("loading","loading-container"); } function cleanLoading(context){ if(context==null) return; context.set("loading","loading-container"); context.set("loading","loading-container hidden"); }
function updateCountdown(a){var b=document.getElementById("clockdiv"),c=b.querySelector(".months"),d=b.querySelector(".days"),e=b.querySelector(".hours"),f=b.querySelector(".minutes");e.innerHTML=a.hours,d.innerHTML=a.days,c.innerHTML=a.months,f.innerHTML=a.minutes}new WOW({mobile:!1}).init();var timerID=countdown(function(a){updateCountdown(a)},new Date(Date.parse("2017/07/06 09:00")),countdown.MONTHS|countdown.DAYS|countdown.HOURS|countdown.MINUTES);
"use strict"; var quoteLookup = require('../services/quoteLookup.js'); module.exports.quote = (req, res) => { let lookupParam = req.params.quote; quoteLookup.renderPage(lookupParam, res); };
var casper = require('casper').create(); casper.start('http://www.wildesoft.net', function () { this.echo(this.getTitle()); }); casper.thenOpen('http://www.meetup.com/Smart-Devs-User-Group', function () { this.echo(this.getTitle()); this.capture("meetup.jpg"); }); casper.run();
import crypto from "crypto"; import { assign } from "lodash"; import { pluggable } from "pluggable"; /** * Calculate the bundle's hash by invoking `update` with data from the bundle. * `update` should be called with string data only. * * @param {Function} update Updates the ongoing computation of bundle hash. * @param {Object} bundle The bundle object. */ const updateBundleHash = pluggable(function updateBundleHash (update, bundle) { update(JSON.stringify(bundle.moduleHashes), "utf-8"); update(JSON.stringify(!!bundle.entry), "utf-8"); update(JSON.stringify(!!bundle.includeRuntime), "utf-8"); }); /** * Given an otherwise prepared bundle, generate a hash for that bundle and resolve * to that same bundle with a new `hash` property. * * @param {Object} bundle Unhashed bundle. * * @returns {Object} Bundle plus new `hash` property, a 40-character SHA1 * that uniquely identifies the bundle. */ function hashBundle (bundle) { // Node v0.10.x cannot re-use crypto instances after digest is called. bundle.setHash = crypto.createHash("sha1") .update(JSON.stringify(bundle.moduleHashes), "utf-8") .digest("hex"); const shasum = crypto.createHash("sha1"); const update = shasum.update.bind(shasum); return this.updateBundleHash(update, bundle) .then(() => assign({}, bundle, { hash: shasum.digest("base64") .replace(/\//g, "_") .replace(/\+/g, "-") .replace(/=+$/, "") })); } export default pluggable(hashBundle, { updateBundleHash });
const type = { name: "array", structure: [ { name: "type", match: "^array$" }, { name: "content" }, ], child: "content", identify, validate, next, execute, }; module.exports = type; function identify({ current }) { const regexp = new RegExp("^array$"); if (current.content && current.type && Object.keys(current).length === 2 && Array.isArray(current.content) === false && typeof current.content === "object" && regexp.test(current.type)) { return true; } return false; } function validate({ current, ruleConfig, parents, processor }) { const type = processor.identify({ current: current.content, ruleConfig, parents }); type.validate({ current: current.content, ruleConfig, parents: [...parents, type.child], processor }); return true; } function next(current) { return current.content ? current.content : null; } function execute({ rule, data, processor, context }) { return new Promise(async (resolve, reject) => { try { if (Array.isArray(data.current)) { for (const key in data.current) { const value = data.current[key]; data.current[key] = await processor.executeNext({ rule: { ...rule, current: rule.current.content }, data: { ...data, current: value }, context });// eslint-disable-line no-await-in-loop } data.current = data.current.filter(item => item !== null && item !== undefined); } else { data.current = []; } resolve(data.current); } catch (error) { reject(error); } }); }
import Ember from 'ember'; import DS from 'ember-data'; import DSpaceObject from './dspace-object'; export default DSpaceObject.extend({ bundleName: DS.attr('string'), description: DS.attr('string'), format: DS.attr('string'), mimeType: DS.attr('string'), sizeBytes: DS.attr('number'), retrieveLink: DS.attr('string'), sequenceId: DS.attr('number'), parentObject: DS.belongsTo('dspace-object', { async: true }), policies: DS.hasMany('policy'), //checksum: leaving out for now parent: Ember.computed.alias('parentObject'), parentId: Ember.computed.alias('parent.id'), parentType: 'item' });
exports.root_url = "http://jgao.me/"; exports.min_vanity_length = 4; exports.num_of_urls_per_hour = 50; exports.get_query = 'SELECT * FROM urls WHERE segment = {SEGMENT}'; exports.add_query = 'INSERT INTO urls SET url = {URL}, segment = {SEGMENT}, ip = {IP}'; exports.check_url_query = 'SELECT * FROM urls WHERE url = {URL}'; exports.update_views_query = 'UPDATE urls SET num_of_clicks = {VIEWS} WHERE id = {ID}'; exports.insert_view = 'INSERT INTO stats SET ip = {IP}, url_id = {URL_ID}, referer = {REFERER}'; exports.check_ip_query = 'SELECT COUNT(id) as counted FROM urls WHERE datetime_added >= now() - INTERVAL 1 HOUR AND ip = {IP}'; exports.stats_query = 'SELECT * FROM stats WHERE url_id = {URL_ID}'; // end exports.host = 'cmpe281-team11.ckeca33m2obn.us-east-1.rds.amazonaws.com'; exports.user = 'master'; exports.password = 'bluebike'; exports.database = 'CMPE281'; exports.port = '3306';
var $M = require("@effectful/debugger"), $x = $M.context, $ret = $M.ret, $unhandled = $M.unhandled, $brk = $M.brk, $m = $M.module("file.js", null, typeof module === "undefined" ? null : module, null, "$", { __webpack_require__: typeof __webpack_require__ !== "undefined" && __webpack_require__ }, null), $s$1 = [{ a: [1, "1:9-1:10"] }, null, 0], $s$2 = [{ i: [1, "3:6-3:7"] }, $s$1, 1], $m$0 = $M.fun("m$0", "file.js", null, null, [], 0, 2, "1:0-17:0", 32, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $l[1] = $m$1($); $.goto = 2; continue; case 1: $.goto = 2; return $unhandled($.error); case 2: return $ret($.result); default: throw new Error("Invalid state"); } }, null, null, 0, [[0, "1:0-16:1", $s$1], [16, "17:0-17:0", $s$1], [16, "17:0-17:0", $s$1]]), $m$1 = $M.fun("m$1", "a", null, $m$0, [], 0, 2, "1:0-16:1", 0, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $.goto = 1; $brk(); $.state = 1; case 1: $.goto = 2; ($x.call = eff0)(); $.state = 2; case 2: $.goto = 3; $brk(); $.state = 3; case 3: $l[1] = 0; $.goto = 4; $brk(); $.state = 4; case 4: $l[1] = $l[1] + 1; $.goto = 5; $brk(); $.state = 5; case 5: $.goto = 6; ($x.call = eff1)($l[1]); $.state = 6; case 6: $.goto = 7; $brk(); $.state = 7; case 7: if (t) { $.state = 8; } else { $.goto = 20; continue; } case 8: $.goto = 9; $brk(); $.state = 9; case 9: $.goto = 10; ($x.call = eff2)($l[1]); $.state = 10; case 10: $.goto = 11; $brk(); $.state = 11; case 11: $l[1] = $l[1] + 1; $.goto = 12; $brk(); $.state = 12; case 12: $.goto = 13; ($x.call = eff4)($l[1]); $.state = 13; case 13: $.goto = 14; $brk(); $.state = 14; case 14: $.goto = 15; $brk(); $.state = 15; case 15: $.goto = 16; ($x.call = eff5)($l[1]); $.state = 16; case 16: $.goto = 17; $brk(); $.state = 17; case 17: $l[1] = $l[1] + 1; $.goto = 18; $brk(); $.state = 18; case 18: $.goto = 19; ($x.call = eff6)($l[1]); $.state = 19; case 19: $.goto = 24; $brk(); continue; case 20: $.goto = 21; $brk(); $.state = 21; case 21: $.goto = 22; ($x.call = eff3)(); $.state = 22; case 22: $.goto = 14; $brk(); continue; case 23: $.goto = 24; return $unhandled($.error); case 24: return $ret($.result); default: throw new Error("Invalid state"); } }, null, null, 1, [[4, "2:2-2:9", $s$2], [2, "2:2-2:8", $s$2], [4, "3:2-3:12", $s$2], [4, "4:2-4:6", $s$2], [4, "5:2-5:10", $s$2], [2, "5:2-5:9", $s$2], [4, "6:2-12:3", $s$2], [0, null, $s$2], [4, "7:4-7:12", $s$2], [2, "7:4-7:11", $s$2], [4, "8:4-8:8", $s$2], [4, "9:4-9:12", $s$2], [2, "9:4-9:11", $s$2], [36, "10:3-10:3", $s$2], [4, "13:2-13:10", $s$2], [2, "13:2-13:9", $s$2], [4, "14:2-14:6", $s$2], [4, "15:2-15:10", $s$2], [2, "15:2-15:9", $s$2], [36, "16:1-16:1", $s$2], [4, "11:4-11:11", $s$2], [2, "11:4-11:10", $s$2], [36, "12:3-12:3", $s$2], [16, "16:1-16:1", $s$2], [16, "16:1-16:1", $s$2]]); $M.moduleExports();
var randomInArray = require('../src/randomInArray'); describe('randomInArray()', function() { 'use strict'; var array = [1, 'a', {object: true}, true, [1, 2, 3]]; it('only accepts arrays', function() { randomInArray.bind(randomInArray, array).should.not.throw(Error); randomInArray.bind(randomInArray, null).should.throw(Error); }); it('returns a member of the array', function() { var i = 5; while (i) { array.should.include(randomInArray(array)); i -= 1; } }); });
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2019 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ var GetTileAt = require('./GetTileAt'); var GetTilesWithin = require('./GetTilesWithin'); /** * Calculates interesting faces within the rectangular area specified (in tile coordinates) of the * layer. Interesting faces are used internally for optimizing collisions against tiles. This method * is mostly used internally. * * @function Phaser.Tilemaps.Components.CalculateFacesWithin * @private * @since 3.0.0 * * @param {integer} tileX - The left most tile index (in tile coordinates) to use as the origin of the area. * @param {integer} tileY - The top most tile index (in tile coordinates) to use as the origin of the area. * @param {integer} width - How many tiles wide from the `tileX` index the area will be. * @param {integer} height - How many tiles tall from the `tileY` index the area will be. * @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon. */ var CalculateFacesWithin = function (tileX, tileY, width, height, layer) { var above = null; var below = null; var left = null; var right = null; var tiles = GetTilesWithin(tileX, tileY, width, height, null, layer); for (var i = 0; i < tiles.length; i++) { var tile = tiles[i]; if (tile) { if (tile.collides) { above = GetTileAt(tile.x, tile.y - 1, true, layer); below = GetTileAt(tile.x, tile.y + 1, true, layer); left = GetTileAt(tile.x - 1, tile.y, true, layer); right = GetTileAt(tile.x + 1, tile.y, true, layer); tile.faceTop = (above && above.collides) ? false : true; tile.faceBottom = (below && below.collides) ? false : true; tile.faceLeft = (left && left.collides) ? false : true; tile.faceRight = (right && right.collides) ? false : true; } else { tile.resetFaces(); } } } }; module.exports = CalculateFacesWithin;
var loopback = require('loopback'); var boot = require('loopback-boot'); var app = module.exports = loopback(); // boot scripts mount components like REST API boot(app, __dirname); app.start = function() { // start the web server return app.listen(process.env.PORT || 3000, function() { app.emit('started'); var baseUrl = app.get('url').replace(/\/$/, ''); console.log('Web server listening at: %s', baseUrl); if (app.get('loopback-component-explorer')) { var explorerPath = app.get('loopback-component-explorer').mountPath; console.log('Browse your REST API at %s%s', baseUrl, explorerPath); } }); }; // start the server if `$ node server.js` if (require.main === module) { app.start(); }
'use strict'; var sockjs = require('sockjs') , http = require('http') , SockJS = require('./'); // // Setup a Sockjs server so we can listen for incoming connections and regular // HTTP server to listen for incoming requests. // var realtime = sockjs.createServer() , server = http.createServer(); realtime.on('connection', function (socket) { socket.on('data', function echo(data) { socket.write(data); }); }); realtime.installHandlers(server, { prefix: '/test' }); // // Listen to the server. // server.listen(8123, function listening() { var socket = new SockJS('http://localhost:8123/test') , timeout; socket.onopen = function onopen() { socket.send('foo'); }; socket.onmessage = function onmessage(evt) { if ('foo' !== evt.data) throw new Error('Invalid message'); clearTimeout(timeout); socket.close(); server.close(); }; timeout = setTimeout(function timeout() { throw new Error('Timeout'); }, 1000); });
import React from "react"; import { ListGroupItem, ButtonToolbar, Button, Modal, Grid, Row, Col } from 'react-bootstrap'; class SearchListItem extends React.Component { constructor() { super() this.state = { showModal: false } } closeModal() { this.setState({ showModal: false }); } openModal() { this.setState({ showModal: true }); } render() { let jobDesc; if (this.props.job.description) { jobDesc = this.props.job.description.substr(0,5000) + "..."; } else { jobDesc = "No description provided. See the full posting at the link below." } return ( <ListGroupItem className="job-list-item"> <Grid> <Row> <Col md={6}> <h3>{this.props.job.title}</h3> <h4>{this.props.job.company}</h4> <h4>{this.props.job.location}</h4> </Col> <Col md={6}> <ButtonToolbar> <Button onClick={this.openModal.bind(this)} className="search-list-item-btns" > See Job Details </Button> <Button onClick={() => this.props.addJob(this.props.job)} className="search-list-item-btns" > Add Job To Interested List </Button> </ButtonToolbar> </Col> </Row> </Grid> <Modal show={this.state.showModal} bsSize="large" onHide={this.closeModal.bind(this)} className="job-modal" > <Modal.Header closeButton/> <Modal.Body className="modal-body"> <h3>{this.props.job.title}</h3> <h4>{this.props.job.company}</h4> <hr /> <h4>Job Description:</h4> <p>{jobDesc}</p> <hr /> <ButtonToolbar> <Button className="modal-btns" href={this.props.job.link} target="_blank" >See Posting on {this.props.job.api}</Button> <Button onClick={() => this.props.addJob(this.props.job)} className="modal-btns" > Add Job to Interested List </Button> </ButtonToolbar> </Modal.Body> </Modal> </ListGroupItem> ) } } export default SearchListItem
import { connect } from 'react-redux'; import { stopPresentation, previousSlide, nextSlide } from '../actions' import Presentation from '../components/Presentation'; const mapStateToProps = (state, ownProps) => { return { slide: state.slides.length > state.presentation.currentIndex ? state.slides[state.presentation.currentIndex] : null }; }; const mapDispatchToProps = (dispatch) => { return { onStopPresentation: () => { dispatch(stopPresentation()); }, onPreviousSlide: () => { dispatch(previousSlide()); }, onNextSlide: () => { dispatch(nextSlide()); } } } const PresentationContainer = connect( mapStateToProps, mapDispatchToProps )(Presentation); export default PresentationContainer;
'use strict'; var bodyParser = require('body-parser'); var csv = require('csv'); var DEFAULT_TYPE = 'text/csv'; module.exports = function (textOptions, csvOptions) { if (!textOptions) { textOptions = {}; } textOptions.type = textOptions.type || DEFAULT_TYPE; var textMiddleware = bodyParser.text(textOptions); var csvResponse = function csvResponse(content) { var _this = this; csv.stringify(content, function (err, stringified) { if (err) { return _this.status(500).send(err.message); } _this.set('Content-Type', 'text/csv').send(stringified); }); }; return function (req, res, next) { res.csv = csvResponse; textMiddleware(req, res, function (err) { if (err || Object.prototype.toString.call(req.body) !== '[object String]') { return next(err); } csv.parse(req.body, csvOptions || {}, function (err, parsed) { if (err) { return next(err); } req.body = parsed; next(); }); }); }; };
import React from 'react'; import PropTypes from 'prop-types'; import Badge from '@mui/material/Badge'; import { withStyles } from '@mui/styles'; import IconButton from '@mui/material/IconButton'; import ShoppingCartIcon from '@mui/icons-material/ShoppingCart'; const StyledBadge = withStyles((theme) => ({ badge: { right: -3, top: 13, border: `2px solid ${theme.palette.background.paper}`, padding: '0 4px', }, }))(Badge); export default function CartWithBadge({ num = 0 }) { return ( <StyledBadge badgeContent={num} color="secondary"> <ShoppingCartIcon /> </StyledBadge> ); } CartWithBadge.propTypes = { num: PropTypes.number, }; CartWithBadge.defaultProps = { num: 0, };
// call this from the developer console and you can control both instances var calendars = {}; $(document).ready( function() { // assuming you've got the appropriate language files, // clndr will respect whatever moment's language is set to. // moment.lang('ru'); // here's some magic to make sure the dates are happening this month. var thisMonth = moment().format('YYYY-MM'); var eventArray = [ { startDate: thisMonth + '-10', endDate: thisMonth + '-14', title: 'Multi-Day Event' }, { startDate: thisMonth + '-21', endDate: thisMonth + '-23', title: 'Another Multi-Day Event' } ]; // the order of the click handlers is predictable. // direct click action callbacks come first: click, nextMonth, previousMonth, nextYear, previousYear, or today. // then onMonthChange (if the month changed). // finally onYearChange (if the year changed). calendars.clndr1 = $('.cal1').clndr({ events: eventArray, // constraints: { // startDate: '2013-11-01', // endDate: '2013-11-15' // }, clickEvents: { click: function(target) { console.log(target); // if you turn the `constraints` option on, try this out: // if($(target.element).hasClass('inactive')) { // console.log('not a valid datepicker date.'); // } else { // console.log('VALID datepicker date.'); // } }, nextMonth: function() { console.log('next month.'); }, previousMonth: function() { console.log('previous month.'); }, onMonthChange: function() { console.log('month changed.'); }, nextYear: function() { console.log('next year.'); }, previousYear: function() { console.log('previous year.'); }, onYearChange: function() { console.log('year changed.'); } }, multiDayEvents: { startDate: 'startDate', endDate: 'endDate' }, showAdjacentMonths: true, adjacentDaysChangeMonth: false }); calendars.clndr2 = $('.cal2').clndr({ template: $('#template-calendar').html(), events: eventArray, multiDayEvents: { startDate: 'startDate', endDate: 'endDate' }, startWithMonth: moment().add(1, 'month'), clickEvents: { click: function(target) { console.log(target); } }, forceSixRows: true }); // bind both clndrs to the left and right arrow keys $(document).keydown( function(e) { if(e.keyCode == 37) { // left arrow calendars.clndr1.back(); calendars.clndr2.back(); } if(e.keyCode == 39) { // right arrow calendars.clndr1.forward(); calendars.clndr2.forward(); } }); });
'use strict'; import { cloneDeep, remove } from 'lodash'; const Sections = { TOP_FINANCIAL_CONTRIBUTORS: 'top-financial-contributors', CONNECTED_COLLECTIVES: 'connected-collectives', OUR_TEAM: 'our-team', GOALS: 'goals', UPDATES: 'updates', CONVERSATIONS: 'conversations', RECURRING_CONTRIBUTIONS: 'recurring-contributions', TICKETS: 'tickets', LOCATION: 'location', // Navigation v2 main sections // CONTRIBUTE/CONTRIBUTIONS CONTRIBUTE: 'contribute', CONTRIBUTIONS: 'contributions', // EVENTS/PROJECTS EVENTS: 'events', PROJECTS: 'projects', // BUDGET/TRANSACTIONS TRANSACTIONS: 'transactions', BUDGET: 'budget', // CONTRIBUTORS/PARTICIPANTS - is this a stand alone or in BUDGET as per Figma?? CONTRIBUTORS: 'contributors', PARTICIPANTS: 'participants', // ABOUT ABOUT: 'about', // EMPTY for new collectives/no data in any category sections EMPTY: 'empty', }; const NAVBAR_CATEGORIES = { ABOUT: 'ABOUT', BUDGET: 'BUDGET', CONNECT: 'CONNECT', CONTRIBUTE: 'CONTRIBUTE', CONTRIBUTIONS: 'CONTRIBUTIONS', EVENTS: 'EVENTS', // Events, projects, connected collectives }; /** * Map sections to their categories. Any section that's not in this object will be considered * as a "Widget" (aka. a section without navbar category). */ const SECTIONS_CATEGORIES = { // About [Sections.OUR_TEAM]: NAVBAR_CATEGORIES.ABOUT, [Sections.ABOUT]: NAVBAR_CATEGORIES.ABOUT, [Sections.LOCATION]: NAVBAR_CATEGORIES.ABOUT, // Connect [Sections.CONVERSATIONS]: NAVBAR_CATEGORIES.CONNECT, [Sections.UPDATES]: NAVBAR_CATEGORIES.CONNECT, // Contribute [Sections.TICKETS]: NAVBAR_CATEGORIES.CONTRIBUTE, [Sections.CONTRIBUTE]: NAVBAR_CATEGORIES.CONTRIBUTE, [Sections.CONTRIBUTORS]: NAVBAR_CATEGORIES.CONTRIBUTE, [Sections.TOP_FINANCIAL_CONTRIBUTORS]: NAVBAR_CATEGORIES.CONTRIBUTE, // Contributions [Sections.CONTRIBUTIONS]: NAVBAR_CATEGORIES.CONTRIBUTIONS, [Sections.RECURRING_CONTRIBUTIONS]: NAVBAR_CATEGORIES.CONTRIBUTIONS, // Budget [Sections.BUDGET]: NAVBAR_CATEGORIES.BUDGET, // Events/Projects [Sections.EVENTS]: NAVBAR_CATEGORIES.CONTRIBUTE, [Sections.PROJECTS]: NAVBAR_CATEGORIES.CONTRIBUTE, }; const normalizeLegacySection = section => { if (typeof section === 'string') { return { section, isEnabled: true }; } else { return section; } }; const convertSectionToNewFormat = ({ section, isEnabled, restrictedTo = null }) => ({ type: 'SECTION', name: section, isEnabled, restrictedTo, }); /** * Converts legacy sections to their new format */ const convertSectionsToNewFormat = (sections, collectiveType) => { const sectionsToConvert = sections.map(normalizeLegacySection); const convertedSections = []; if (!sectionsToConvert.length) { return []; } do { const section = sectionsToConvert[0]; const category = SECTIONS_CATEGORIES[section.section]; if (section.type) { // Already new format sectionsToConvert.shift(); } else if (!category) { // Simple case: section is a widget (not part of any category) convertedSections.push(convertSectionToNewFormat(section)); sectionsToConvert.shift(); } else { // If part of a category, create it and store all alike sections const allCategorySections = remove(sectionsToConvert, s => SECTIONS_CATEGORIES[s.section] === category); const convertedSubSections = allCategorySections.map(convertSectionToNewFormat); if (category === NAVBAR_CATEGORIES.CONTRIBUTE) { // We want to make sure TOP_FINANCIAL_CONTRIBUTORS and EVENTS are inserted at the right place const contributeSectionIdx = convertedSubSections.findIndex(s => s.name === Sections.CONTRIBUTE); if (contributeSectionIdx !== -1) { const sectionsToAdd = [Sections.TOP_FINANCIAL_CONTRIBUTORS]; if (collectiveType === 'COLLECTIVE') { sectionsToAdd.unshift(Sections.EVENTS, Sections.CONNECTED_COLLECTIVES); } remove(convertedSubSections, s => sectionsToAdd.includes(s.name)); const convertedSubSectionsToAdd = sectionsToAdd.map(name => ({ type: 'SECTION', isEnabled: true, name })); convertedSubSections.splice(contributeSectionIdx + 1, 0, ...convertedSubSectionsToAdd); } // Contributors is replaced by "Our team" for organizations. We can remove it safely if (collectiveType === 'ORGANIZATION') { const contributorsIdx = convertedSubSections.findIndex(s => s.name === Sections.CONTRIBUTORS); if (contributorsIdx !== -1) { convertedSubSections.splice(contributorsIdx, 1); } } } convertedSections.push({ type: 'CATEGORY', name: category || 'Other', sections: convertedSubSections, isEnabled: true, }); } } while (sectionsToConvert.length > 0); return convertedSections; }; /** * Migrate collective sections to the new format, saving a backup in `legacySectionsBackup` */ module.exports = { up: async queryInterface => { // Remove customization made so far with the new navbar to start from clean data (only affects staging & dev) await queryInterface.sequelize.query(` UPDATE "Collectives" SET settings = JSONB_SET( JSONB_SET(settings, '{collectivePage,sections}', 'null'), '{collectivePage,useNewSections}', 'false' ) WHERE settings -> 'collectivePage' -> 'sections' IS NOT NULL AND (settings -> 'collectivePage' ->> 'useNewSections')::boolean IS TRUE `); // Migrate all sections const [collectives] = await queryInterface.sequelize.query(` SELECT id, "type", settings FROM "Collectives" c WHERE settings -> 'collectivePage' -> 'sections' IS NOT NULL AND (settings -> 'collectivePage' ->> 'useNewSections')::boolean IS NOT TRUE `); for (const collective of collectives) { const settings = cloneDeep(collective.settings); if (!settings.collectivePage.sections) { continue; } settings.collectivePage.legacySectionsBackup = settings.collectivePage.sections; settings.collectivePage.sections = convertSectionsToNewFormat(settings.collectivePage.sections, collective.type); settings.collectivePage.useNewSections = true; await queryInterface.sequelize.query(`UPDATE "Collectives" SET settings = :settings WHERE id = :id`, { replacements: { settings: JSON.stringify(settings), id: collective.id }, }); } }, down: async queryInterface => { await queryInterface.sequelize.query(` UPDATE "Collectives" SET settings = JSONB_SET( JSONB_SET( settings, '{collectivePage,sections}', settings -> 'collectivePage' -> 'legacySectionsBackup' ), '{collectivePage,useNewSections}', 'false' ) WHERE settings -> 'collectivePage' -> 'sections' IS NOT NULL AND settings -> 'collectivePage' -> 'legacySectionsBackup' IS NOT NULL AND (settings -> 'collectivePage' ->> 'useNewSections')::boolean IS TRUE `); }, };
'use strict'; const config = require('../../config'); module.exports = function * (next) { const ua = this.request.headers['user-agent'] || ''; if (!config.useragent.pattern.test(ua)) { yield this.render('useragent/ban', { title: 'User agent', }); this.status = 503; return; } yield next; };
/* Example: _.module.define('ymaps', () => { return _.deal((resolve, reject) => { _.script('https://api-maps.yandex.ru/2.1/?lang=ru_RU').then(() => { ymaps.ready(() => resolve(ymaps)); }, reject); }); }); _.module('ymaps').then((ymaps) => { }); */ _.dependency('module', [ 'moduleProvider'], (name, moduleProvider) => { return moduleProvider(); }); _.dependency('moduleProvider', [ 'deal', 'EventEmitter', 'isFunction', 'isPlainObject'], (name, Deal, EventEmitter, isFunction, isPlainObject) => { return () => { var modules = {}; var providers = {}; var requires = {}; var em = new EventEmitter(); var __init = (name, provider) => { if(isFunction(provider))provider = provider(name); if(!provider)return; if(provider instanceof Promise){ modules[name] = provider; provider.on && provider.on('canceled', () => delete modules[name]); provider.then((instance) => { modules[name] = instance; em.emit(name, [ instance ]); return instance; }, (err) => { delete modules[name]; return err; }); return; } modules[name] = provider; em.emit(name, [ provider ]); }; var __once = (name) => { if(isPlainObject(name)){ var map = name; var promises = {}; for(name in map)promises[name] = __once(map[name]); return __deal.all(promises); } var module = modules[name]; var promise = Deal((resolve) => { var module = modules[name]; module ? resolve(module) : em.once(name, resolve); }); if(module){ if(module instanceof Promise){ module.then((module) => { em.emit(name, [ module ]); return module; }); }else{ em.emit(name, [ module ]); } }else{ var provider = providers[name]; if(provider){ __init(name, provider); }else{ requires[name] = true; } } return promise; }; function module(){ var l = arguments.length; var promises = new Array(l); for(;l--;)promises[l] = __once(arguments[l]); return Deal((resolve, reject) => { Deal.all(promises).then((modules) => { resolve.apply(null, modules); }, reject); }); } var define = module.define = (name, provider) => { providers[name] = provider; if(requires[name])__init(name, provider); return module; }; return module; } });
'use strict'; const declarationValueIndex = require('../../utils/declarationValueIndex'); const getDeclarationValue = require('../../utils/getDeclarationValue'); const isSingleLineString = require('../../utils/isSingleLineString'); const isStandardSyntaxFunction = require('../../utils/isStandardSyntaxFunction'); const report = require('../../utils/report'); const ruleMessages = require('../../utils/ruleMessages'); const setDeclarationValue = require('../../utils/setDeclarationValue'); const validateOptions = require('../../utils/validateOptions'); const valueParser = require('postcss-value-parser'); const ruleName = 'function-parentheses-space-inside'; const messages = ruleMessages(ruleName, { expectedOpening: 'Expected single space after "("', rejectedOpening: 'Unexpected whitespace after "("', expectedClosing: 'Expected single space before ")"', rejectedClosing: 'Unexpected whitespace before ")"', expectedOpeningSingleLine: 'Expected single space after "(" in a single-line function', rejectedOpeningSingleLine: 'Unexpected whitespace after "(" in a single-line function', expectedClosingSingleLine: 'Expected single space before ")" in a single-line function', rejectedClosingSingleLine: 'Unexpected whitespace before ")" in a single-line function', }); const meta = { url: 'https://stylelint.io/user-guide/rules/list/function-parentheses-space-inside', }; /** @type {import('stylelint').Rule} */ const rule = (primary, _secondaryOptions, context) => { return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual: primary, possible: ['always', 'never', 'always-single-line', 'never-single-line'], }); if (!validOptions) { return; } root.walkDecls((decl) => { if (!decl.value.includes('(')) { return; } let hasFixed = false; const declValue = getDeclarationValue(decl); const parsedValue = valueParser(declValue); parsedValue.walk((valueNode) => { if (valueNode.type !== 'function') { return; } if (!isStandardSyntaxFunction(valueNode)) { return; } // Ignore function without parameters if (!valueNode.nodes.length) { return; } const functionString = valueParser.stringify(valueNode); const isSingleLine = isSingleLineString(functionString); // Check opening ... const openingIndex = valueNode.sourceIndex + valueNode.value.length + 1; if (primary === 'always' && valueNode.before !== ' ') { if (context.fix) { hasFixed = true; valueNode.before = ' '; } else { complain(messages.expectedOpening, openingIndex); } } if (primary === 'never' && valueNode.before !== '') { if (context.fix) { hasFixed = true; valueNode.before = ''; } else { complain(messages.rejectedOpening, openingIndex); } } if (isSingleLine && primary === 'always-single-line' && valueNode.before !== ' ') { if (context.fix) { hasFixed = true; valueNode.before = ' '; } else { complain(messages.expectedOpeningSingleLine, openingIndex); } } if (isSingleLine && primary === 'never-single-line' && valueNode.before !== '') { if (context.fix) { hasFixed = true; valueNode.before = ''; } else { complain(messages.rejectedOpeningSingleLine, openingIndex); } } // Check closing ... const closingIndex = valueNode.sourceIndex + functionString.length - 2; if (primary === 'always' && valueNode.after !== ' ') { if (context.fix) { hasFixed = true; valueNode.after = ' '; } else { complain(messages.expectedClosing, closingIndex); } } if (primary === 'never' && valueNode.after !== '') { if (context.fix) { hasFixed = true; valueNode.after = ''; } else { complain(messages.rejectedClosing, closingIndex); } } if (isSingleLine && primary === 'always-single-line' && valueNode.after !== ' ') { if (context.fix) { hasFixed = true; valueNode.after = ' '; } else { complain(messages.expectedClosingSingleLine, closingIndex); } } if (isSingleLine && primary === 'never-single-line' && valueNode.after !== '') { if (context.fix) { hasFixed = true; valueNode.after = ''; } else { complain(messages.rejectedClosingSingleLine, closingIndex); } } }); if (hasFixed) { setDeclarationValue(decl, parsedValue.toString()); } /** * @param {string} message * @param {number} offset */ function complain(message, offset) { report({ ruleName, result, message, node: decl, index: declarationValueIndex(decl) + offset, }); } }); }; }; rule.ruleName = ruleName; rule.messages = messages; rule.meta = meta; module.exports = rule;
Date.parseISO8601 = function(s){ var re = /(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(\.\d+)?(Z|([+-])(\d\d):(\d\d))?/; var d = []; d = s.match(re); if (!d) { throw "Couldn't parse ISO 8601 date string '" + s + "'"; } var a = [1, 2, 3, 4, 5, 6, 10, 11]; for (var i in a) { d[a[i]] = parseInt(d[a[i]], 10); } d[7] = parseFloat(d[7]); var ms = null; if(d[8]){ ms = Date.UTC(d[1], d[2] - 1, d[3], d[4], d[5], d[6]); if (d[8] != "Z" && d[10]) { var offset = d[10] * 60 * 60 * 1000; if (d[11]) { offset += d[11] * 60 * 1000; } if (d[9] == "-") { ms -= offset; } else { ms += offset; } } } else { ms = (new Date(d[1], d[2] - 1, d[3], d[4], d[5], d[6])).getTime(); } if (d[7] > 0) { ms += Math.round(d[7] * 1000); } return new Date(ms); };
// user authentication will allow users (regardless of client) // authenticated access to protected routes import Boom from 'boom'; import config from 'config'; // Declare internals const internals = {}; exports.register = (plugin, options, next) => { plugin.auth.scheme('user', internals.implementation); next(); }; exports.register.attributes = { name: 'User Authentication', version: '1.0.0' }; internals.implementation = () => { const scheme = { authenticate: (request, reply) => { const req = request.raw.req; const authorization = req.headers.authorization; if (!authorization) { return reply(Boom.unauthorized('Please log in to access this resource')); } return request.redis.get(`sess:${authorization}`, (rediserror, result) => { if (rediserror) { return reply(Boom.badRequest(rediserror)); } const sess = JSON.parse(result); if (!sess) { return reply(Boom.unauthorized('Please log in to access this resource')); } // refresh session exp request.redis.expire(`sess:${authorization}`, config.get('redis_expire')); const credentials = { Authorization: authorization, scope: sess.role }; return reply.continue({ credentials }); }); } }; return scheme; };
var Magazine = Backbone.Model.extend({ defaults: { title: '', pubDate: '1/1', image: '' }, initialize: function(){ console.log("The model has been initialize"); this.on("change:title", function(){ console.log("The model's data has been change"); }) } }); var MagazineCollection = Backbone.Collection.extend({ model: Magazine });
/* eslint-disable no-new, class-methods-use-this */ /* global Breakpoints */ /* global Cookies */ /* global Flash */ import Cookies from 'js-cookie'; import './breakpoints'; import './flash'; const PipelinesTable = require('./commit/pipelines/pipelines_table'); /* eslint-disable max-len */ // MergeRequestTabs // // Handles persisting and restoring the current tab selection and lazily-loading // content on the MergeRequests#show page. // // ### Example Markup // // <ul class="nav-links merge-request-tabs"> // <li class="notes-tab active"> // <a data-action="notes" data-target="#notes" data-toggle="tab" href="/foo/bar/merge_requests/1"> // Discussion // </a> // </li> // <li class="commits-tab"> // <a data-action="commits" data-target="#commits" data-toggle="tab" href="/foo/bar/merge_requests/1/commits"> // Commits // </a> // </li> // <li class="diffs-tab"> // <a data-action="diffs" data-target="#diffs" data-toggle="tab" href="/foo/bar/merge_requests/1/diffs"> // Diffs // </a> // </li> // </ul> // // <div class="tab-content"> // <div class="notes tab-pane active" id="notes"> // Notes Content // </div> // <div class="commits tab-pane" id="commits"> // Commits Content // </div> // <div class="diffs tab-pane" id="diffs"> // Diffs Content // </div> // </div> // // <div class="mr-loading-status"> // <div class="loading"> // Loading Animation // </div> // </div> // /* eslint-enable max-len */ (() => { // Store the `location` object, allowing for easier stubbing in tests let location = window.location; class MergeRequestTabs { constructor({ action, setUrl, stubLocation } = {}) { this.diffsLoaded = false; this.pipelinesLoaded = false; this.commitsLoaded = false; this.fixedLayoutPref = null; this.setUrl = setUrl !== undefined ? setUrl : true; this.setCurrentAction = this.setCurrentAction.bind(this); this.tabShown = this.tabShown.bind(this); this.showTab = this.showTab.bind(this); if (stubLocation) { location = stubLocation; } this.bindEvents(); this.activateTab(action); this.initAffix(); } bindEvents() { $(document) .on('shown.bs.tab', '.merge-request-tabs a[data-toggle="tab"]', this.tabShown) .on('click', '.js-show-tab', this.showTab); $('.merge-request-tabs a[data-toggle="tab"]') .on('click', this.clickTab); } unbindEvents() { $(document) .off('shown.bs.tab', '.merge-request-tabs a[data-toggle="tab"]', this.tabShown) .off('click', '.js-show-tab', this.showTab); $('.merge-request-tabs a[data-toggle="tab"]') .off('click', this.clickTab); } destroy() { this.unbindEvents(); if (this.commitPipelinesTable) { this.commitPipelinesTable.$destroy(); } } showTab(e) { e.preventDefault(); this.activateTab($(e.target).data('action')); } clickTab(e) { if (e.currentTarget && gl.utils.isMetaClick(e)) { const targetLink = e.currentTarget.getAttribute('href'); e.stopImmediatePropagation(); e.preventDefault(); window.open(targetLink, '_blank'); } } tabShown(e) { const $target = $(e.target); const action = $target.data('action'); if (action === 'commits') { this.loadCommits($target.attr('href')); this.expandView(); this.resetViewContainer(); } else if (this.isDiffAction(action)) { this.loadDiff($target.attr('href')); if (Breakpoints.get().getBreakpointSize() !== 'lg') { this.shrinkView(); } if (this.diffViewType() === 'parallel') { this.expandViewContainer(); } $.scrollTo('.merge-request-details .merge-request-tabs', { offset: 0, }); } else if (action === 'pipelines') { this.resetViewContainer(); this.loadPipelines(); } else { this.expandView(); this.resetViewContainer(); } if (this.setUrl) { this.setCurrentAction(action); } } scrollToElement(container) { if (location.hash) { const offset = -$('.js-tabs-affix').outerHeight(); const $el = $(`${container} ${location.hash}:not(.match)`); if ($el.length) { $.scrollTo($el[0], { offset }); } } } // Activate a tab based on the current action activateTab(action) { const activate = action === 'show' ? 'notes' : action; // important note: the .tab('show') method triggers 'shown.bs.tab' event itself $(`.merge-request-tabs a[data-action='${activate}']`).tab('show'); } // Replaces the current Merge Request-specific action in the URL with a new one // // If the action is "notes", the URL is reset to the standard // `MergeRequests#show` route. // // Examples: // // location.pathname # => "/namespace/project/merge_requests/1" // setCurrentAction('diffs') // location.pathname # => "/namespace/project/merge_requests/1/diffs" // // location.pathname # => "/namespace/project/merge_requests/1/diffs" // setCurrentAction('notes') // location.pathname # => "/namespace/project/merge_requests/1" // // location.pathname # => "/namespace/project/merge_requests/1/diffs" // setCurrentAction('commits') // location.pathname # => "/namespace/project/merge_requests/1/commits" // // Returns the new URL String setCurrentAction(action) { this.currentAction = action === 'show' ? 'notes' : action; // Remove a trailing '/commits' '/diffs' '/pipelines' '/new' '/new/diffs' let newState = location.pathname.replace(/\/(commits|diffs|pipelines|new|new\/diffs)(\.html)?\/?$/, ''); // Append the new action if we're on a tab other than 'notes' if (this.currentAction !== 'notes') { newState += `/${this.currentAction}`; } // Ensure parameters and hash come along for the ride newState += location.search + location.hash; // TODO: Consider refactoring in light of turbolinks removal. // Replace the current history state with the new one without breaking // Turbolinks' history. // // See https://github.com/rails/turbolinks/issues/363 window.history.replaceState({ url: newState, }, document.title, newState); return newState; } loadCommits(source) { if (this.commitsLoaded) { return; } this.ajaxGet({ url: `${source}.json`, success: (data) => { document.querySelector('div#commits').innerHTML = data.html; gl.utils.localTimeAgo($('.js-timeago', 'div#commits')); this.commitsLoaded = true; this.scrollToElement('#commits'); }, }); } loadPipelines() { if (this.pipelinesLoaded) { return; } const pipelineTableViewEl = document.querySelector('#commit-pipeline-table-view'); // Could already be mounted from the `pipelines_bundle` if (pipelineTableViewEl) { this.commitPipelinesTable = new PipelinesTable().$mount(pipelineTableViewEl); } this.pipelinesLoaded = true; } loadDiff(source) { if (this.diffsLoaded) { return; } // We extract pathname for the current Changes tab anchor href // some pages like MergeRequestsController#new has query parameters on that anchor const urlPathname = gl.utils.parseUrlPathname(source); this.ajaxGet({ url: `${urlPathname}.json${location.search}`, success: (data) => { $('#diffs').html(data.html); if (typeof gl.diffNotesCompileComponents !== 'undefined') { gl.diffNotesCompileComponents(); } gl.utils.localTimeAgo($('.js-timeago', 'div#diffs')); $('#diffs .js-syntax-highlight').syntaxHighlight(); if (this.diffViewType() === 'parallel' && this.isDiffAction(this.currentAction)) { this.expandViewContainer(); } this.diffsLoaded = true; new gl.Diff(); this.scrollToElement('#diffs'); }, }); } // Show or hide the loading spinner // // status - Boolean, true to show, false to hide toggleLoading(status) { $('.mr-loading-status .loading').toggle(status); } ajaxGet(options) { const defaults = { beforeSend: () => this.toggleLoading(true), error: () => new Flash('An error occurred while fetching this tab.', 'alert'), complete: () => this.toggleLoading(false), dataType: 'json', type: 'GET', }; $.ajax($.extend({}, defaults, options)); } diffViewType() { return $('.inline-parallel-buttons a.active').data('view-type'); } isDiffAction(action) { return action === 'diffs' || action === 'new/diffs'; } expandViewContainer() { const $wrapper = $('.content-wrapper .container-fluid'); if (this.fixedLayoutPref === null) { this.fixedLayoutPref = $wrapper.hasClass('container-limited'); } $wrapper.removeClass('container-limited'); } resetViewContainer() { if (this.fixedLayoutPref !== null) { $('.content-wrapper .container-fluid') .toggleClass('container-limited', this.fixedLayoutPref); } } shrinkView() { const $gutterIcon = $('.js-sidebar-toggle i:visible'); // Wait until listeners are set setTimeout(() => { // Only when sidebar is expanded if ($gutterIcon.is('.fa-angle-double-right')) { $gutterIcon.closest('a').trigger('click', [true]); } }, 0); } // Expand the issuable sidebar unless the user explicitly collapsed it expandView() { if (Cookies.get('collapsed_gutter') === 'true') { return; } const $gutterIcon = $('.js-sidebar-toggle i:visible'); // Wait until listeners are set setTimeout(() => { // Only when sidebar is collapsed if ($gutterIcon.is('.fa-angle-double-left')) { $gutterIcon.closest('a').trigger('click', [true]); } }, 0); } initAffix() { const $tabs = $('.js-tabs-affix'); // Screen space on small screens is usually very sparse // So we dont affix the tabs on these if (Breakpoints.get().getBreakpointSize() === 'xs' || !$tabs.length) return; const $diffTabs = $('#diff-notes-app'); $tabs.off('affix.bs.affix affix-top.bs.affix') .affix({ offset: { top: () => ( $diffTabs.offset().top - $tabs.height() ), }, }) .on('affix.bs.affix', () => $diffTabs.css({ marginTop: $tabs.height() })) .on('affix-top.bs.affix', () => $diffTabs.css({ marginTop: '' })); // Fix bug when reloading the page already scrolling if ($tabs.hasClass('affix')) { $tabs.trigger('affix.bs.affix'); } } } window.gl = window.gl || {}; window.gl.MergeRequestTabs = MergeRequestTabs; })();
/* ========================================================================== Internal variables & dependencies ========================================================================== */ // ... /* ========================================================================== Tests ========================================================================== */ describe('util.js', function() { var test, ctrllr, _interface; /* # # # # # # # # # # # # # # # # # # # # */ /* # # # # # # # # # # # # # # # # # # # # */ // initialize store instance before each test beforeEach(function() { // ... }); // delete store after each test afterEach(function() { // ... }); /* # # # # # # # # # # # # # # # # # # # # */ /* # # # # # # # # # # # # # # # # # # # # */ });
import PropTypes from 'prop-types'; import { connect } from 'react-redux'; // import { Advanced, Managers } from 'czechidm-core'; import { ProvisioningBreakRecipientManager } from '../../redux'; const manager = new ProvisioningBreakRecipientManager(); /** * System provisioning break config basic information (info card) * * @author Vít Švanda */ export class BreakConfigRecipientInfo extends Advanced.AbstractEntityInfo { getManager() { return manager; } showLink() { if (!super.showLink()) { return false; } if (!Managers.SecurityManager.hasAccess({ type: 'HAS_ANY_AUTHORITY', authorities: ['SYSTEM_READ'] })) { return false; } return true; } /** * Get link to detail (`url`). * * @return {string} */ getLink() { const entity = this.getEntity(); if (entity._embedded && entity._embedded.breakConfig) { const systemId = entity._embedded.breakConfig.system; return `/system/${encodeURIComponent(systemId)}/break-configs/${encodeURIComponent(entity.breakConfig)}/detail`; } return null; } /** * Returns entity icon (null by default - icon will not be rendered) * * @param {object} entity */ getEntityIcon() { return 'fa:stop-circle-o'; } /** * Returns popovers title * * @param {object} entity */ getPopoverTitle() { return this.i18n('acc:entity.ProvisioningBreakConfigRecipient._type'); } /** * Returns popover info content * * @param {array} table data */ getPopoverContent(entity) { // FIXME: no informations are here - add system, identity or role ... return [ { label: this.i18n('entity.name.label'), value: this.getManager().getNiceLabel(entity) } ]; } } BreakConfigRecipientInfo.propTypes = { ...Advanced.AbstractEntityInfo.propTypes, /** * Selected entity - has higher priority. */ entity: PropTypes.object, /** * Selected entity's id - entity will be loaded automatically. */ entityIdentifier: PropTypes.string, // _showLoading: PropTypes.bool }; BreakConfigRecipientInfo.defaultProps = { ...Advanced.AbstractEntityInfo.defaultProps, entity: null, face: 'link', _showLoading: true, }; function select(state, component) { return { _entity: manager.getEntity(state, component.entityIdentifier), _showLoading: manager.isShowLoading(state, null, component.entityIdentifier) }; } export default connect(select)(BreakConfigRecipientInfo);
var CommandParser = function() { var parse = function(str, lookForQuotes) { var args = []; var readingPart = false; var part = ""; for (var i = 0; i < str.length; i++) { if (str.charAt(i) === " " && !readingPart) { args.push(part); part = ""; } else { if (str.charAt(i) === '"' && lookForQuotes) { readingPart = !readingPart; } else { part += str.charAt(i); } } } args.push(part); return args; }; return { parse: parse }; }(); (function() { var brightness = 0, commandLine, commandInput, scanlines, commandHistory, typing; var escapeHTML = function(html) { var fn = function(tag) { var charsToReplace = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&#34;" }; return charsToReplace[tag] || tag; }; return html.replace(/[&<>"]/g, fn); }; var syncTyping = function() { var beforeSelection, selection, afterSelection; beforeSelection = this.value.slice(0, this.selectionStart); selection = this.value.slice(this.selectionStart, this.selectionEnd); afterSelection = this.value.slice(this.selectionEnd); typing.innerHTML = beforeSelection + (this.selectionStart === this.selectionEnd ? "<span id='cursor'></span>" : "") + "<span id='selection'>" + selection + "</span>" + afterSelection; }; var alterBrightness = function(delta) { brightness = Math.max(0, Math.min(1, brightness + delta)); this.scanlines.style.backgroundColor = "hsla(120, 100%, 32%, " + brightness * .6 + ")"; }; var setInputEnabled = function(enabled) { console.log(enabled); if (enabled) { commandInput.readOnly = false; commandLine.style.display = "block"; } else { commandInput.readOnly = true; commandInput.value = ""; typing.innerHTML = ""; commandLine.style.display = "none"; } }; var showResponse = function(response) { commandHistory.innerHTML += response + "\n"; setInputEnabled(true); }; var handleForm = function() { var val = this.command.value; setInputEnabled(false); commandHistory.innerHTML += "a&gt;" + escapeHTML(val) + "\n"; setTimeout(function() { showResponse("Command not found."); }, 500); return false; }; var init = function() { console.log("init"); commandLine = document.getElementById("commandLine"); commandInput = document.getElementById("command"); scanlines = document.getElementById("scanlines"); commandHistory = document.getElementById("history"); typing = document.getElementById("typing"); commandInput.value = ""; commandInput.oninput = syncTyping; commandInput.onkeydown = syncTyping; commandInput.onkeyup = syncTyping; commandInput.onselect = syncTyping; commandInput.onfocus = syncTyping; commandInput.focus(); document.body.onmousedown = function() { commandInput.focus(); return false; }; document.getElementById("knobup").onmousedown = function() { alterBrightness(1 / 6); }; document.getElementById("knobdown").onmousedown = function() { alterBrightness(-1 / 6); }; document.forms[0].onsubmit = handleForm; alterBrightness(-1); }; document.addEventListener("DOMContentLoaded", init); })();
var gulp = require('gulp'); var browserSync = require('browser-sync'); var cp = require('child_process'); /** * Build site with Jekyll */ gulp.task('jekyll-build', function(done) { browserSync.notify('building site'); return cp.spawn('rake', ['build_drafts'], {stdio: 'inherit'}) .on('close', done) }); /** * Rebuild site then reload */ gulp.task('jekyll-rebuild', ['jekyll-build'], function () { browserSync.reload(); }) /** * Init browsersync */ gulp.task('browser-sync', ['jekyll-build'], function() { browserSync({ server: { baseDir: '_site' }, port: 4000 // same port with Jekyll }) }); /** * Watching */ gulp.task('watch', function () { gulp.watch(['*.html', '_layouts/*.html', '_includes/*.html', '_posts/**/*', '_drafts/*'], ['jekyll-rebuild']); }); gulp.task('default', ['browser-sync', 'watch']);
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ function getProductoAjEntradaxID(){ $(document).on("click", "#invajentradaitemxidgetbtn", function(e) { var form = $(this).parents('form'); $(form).ajaxForm({ success: getRespNewProdAjEntradaDetalle, clearForm: true }); }); return false; } function getRespNewProdAjEntradaDetalle(data){ if($.trim(data)!=''){ $('#ajusteentrada_areadetallefact').append(data); calcularTotalNewAjEntrada(); }else{ alertaInfo('No se ha encontrado el producto que busca o se ha dado de baja', 'Agregar Producto'); } } function calcularTotalNewAjEntrada(){ var totalnewajuste = 0; $("input#invajentradacostototal").each(function(e) { var total = parseFloat($(this).val()); totalnewajuste+=total; }); $('#ajusteentrada_totalfact').val(totalnewajuste.toFixed(numdecimales)); } /******************************************************************************/ function quitarProductoDeAjEntrada(){ $(document).delegate('#quitarprodajentradabtn','click',function(){ $(this).parent("div").parent("div").remove(); calcularTotalNewAjEntrada() }); } /******************************************************************************/ /*Para archivar el ajuste de entrada*/ function agregarNewAjusteEntrada(){ var prefix = "ajusteentrada_"; $(document).on("keypress", 'form#'+prefix+'formnewajustentrada', function(e) { if (e.keyCode == 13) {e.preventDefault(); /* prevent native submit*/} }); // $(document).delegate("#"+prefix+"btnaddajustentrada",'click',function(){ // $('#'+prefix+'formnewajustentrada').ajaxForm({ // success: responseagregarNewAjusteEntrada // }); // }); return false; } //function responseagregarNewAjusteEntrada(data){ // if($.trim(data) != '-1'){ // $('#invajentradanewoutput').html(data); // $('#ajusteentrada_btnnewajustentrada').removeClass('hide'); // $('#ajusteentrada_btnaddajustentrada').addClass('hide'); // }else{ // alertaImportant('No se pudo agregar la factura de venta, verifique los datos', 'Nueva Venta'); // $('#ventasnewfactoutput').html('<div class="alert alert-warning">Verifique que los datos ingresados sean correctos</div>'); // } //} function findProductToAjustEntrada(){ var prefix = 'ajusteentrada_'; $(document).delegate('#'+prefix+'btnfinditems','click',function(){ var clavebusqueda = $.trim($("#"+prefix+"txtfinditems").val()); var arrdatosDatos = [], bValid=true; //se vacia el array /******************************************/ arrdatosDatos = {'clavebusqueda': clavebusqueda}; var areapresent = "#"+prefix+"outputitems"; var url = main_path+"/modules/inventario/controlador/ajustes/finditems.php"; loadUrlJson2(url, true, arrdatosDatos, null, "Buscar Productos", "Datos Encontrados", "Error", areapresent); /******************************************/ return false; }); return false; } /**********************/ function anularAjusteEntrada(){ var cod, objThis; $(document).delegate("#ajentrada_anularaj",'click',function(){ objThis = $(this); cod = objThis.attr('cod') var arrdatosDatos = [], bValid=true, url = main_path+'/modules/inventario/controlador/ajustes/ajustentradaanular.php'; arrdatosDatos = {'cod': cod}; var data = JSON.stringify(arrdatosDatos); $.ajax({url: url,type: "POST", cache: false,dataType: "json", data: data, success: function(data){ if(data.ok=='1'){ alertaExito('El ajuste de entrada ha sido anulado correctamente', 'Anulacion de Ajuste Entrada'); } objThis.parent('td').parent('tr').remove(); }, error: function(data){alertaError('Problema!! No se pudo anular el ajuste de entrada', 'Anulacion de Ajuste Entrada');}, contentType: "application/json" }); $( this ).dialog( "close" ); }); } /*********************/ function limpiarParaNuevoAjusteEntrada(){ $(document).on("click", '#ajusteentrada_btnnewajustentrada', function(e) { e.preventDefault(); var data = {'action': 'refresh'}, url = main_path+'/modules/inventario/vista/ajustes/ajusteentrada.php'; $.ajax({ type: "POST", url: url, data: data, success: function(html){$('#inventariosajentrada').html(html);}, error: function(html){alertaImportant('Ocurrio un problema!!', 'Cargar Nuevo Ajuste Entrada');}, dataType: 'html' }); }); } function changeInventariosSection(){ // $(document).delegate("#"+prefix+"btnnewpuntoventa",'click',function(){ $(document).delegate('#btninventariosreports','click',function(){ $('#inventariostittlesection').html($(this).attr('title')); $('.inventariosmodule').slideUp(700); $('#inventariosreportinven').slideDown(700) }).delegate('#btninventarioskardex','click',function(){ $('#inventariostittlesection').html($(this).attr('title')); $('.inventariosmodule').slideUp(700); $('#inventarioskardex').slideDown(700) }).delegate('#btnajusteentrada','click',function(){ $('#inventariostittlesection').html($(this).attr('title')); $('.inventariosmodule').slideUp(700); $('#inventariosajentrada').slideDown(700) }).delegate('#btn_ajentrlist','click',function(){ $('#inventariostittlesection').html($(this).attr('title')); $('.inventariosmodule').slideUp(700); $('#inventariosajentradalist').slideDown(700) }) } function calcularTotalXProdAjEntrada(clickelem){ $(document).delegate(clickelem,'keyup',function(){ var codprod = $(this).attr('codprod'), cant = parseFloat($('.invajentradacantidad'+codprod).val()), costounit = parseFloat($('.invajentradacostounit'+codprod).val()), newtotalxprod = cant * costounit; $('.invajentradacostototal'+codprod).val(newtotalxprod.toFixed(numdecimales)); calcularTotalNewAjEntrada() }) } function inventario(){ ejectSubmitFormsHtmlOutput("#inv_productsearchbtn", "#inv_productsearchoutput"); ejectSubmitFormsHtmlOutput("#inventario_reportesbtngetinventarioxbodega", "#inventario_reportesoutputinventarioxbodega"); ejectSubmitFormsHtmlOutput("#invkardexgetbtn", "#invkardexgetoutput"); ejectSubmitFormsHtmlOutput("#btnfindajentrlist", "#outputajentrlist"); limpiarParaNuevoAjusteEntrada() findProductToAjustEntrada(); agregarNewAjusteEntrada(); // verDetalleAjEntrada(); quitarProductoDeAjEntrada(); anularAjusteEntrada(); changeInventariosSection() getProductoAjEntradaxID() calcularTotalXProdAjEntrada('#invajentradacostounit') calcularTotalXProdAjEntrada('#invajentradacantidad') }
app.factory('watsonSpeechModelFactory', function() { console.log("Watson speech model factory!"); let fromController = function(watsonSpeechModelFactoryObject) { // phoneme from the controller, that the user clicked in the template targetLanguage = watsonSpeechModelFactoryObject.targetLanguage; setBroadband = watsonSpeechModelFactoryObject.setBroadband; setUSEnglish = watsonSpeechModelFactoryObject.setUSEnglish; }; // close fromController let toController = function() { // this function creates the output switch (true) { case targetLanguage === 'ar' && setBroadband: watsonSpeechModel = 'ar-AR_BroadbandModel'; console.log("Arabic broadband."); break; case targetLanguage === 'ar' && !setBroadband: watsonSpeechModel = 'ar-AR_NarrowbandModel'; console.log("Arabic narrowband."); break; case targetLanguage === 'en' && setBroadband && setUSEnglish: watsonSpeechModel = 'en-US_BroadbandModel'; console.log("US English broadband."); break; case targetLanguage === 'en' && setBroadband && !setUSEnglish: watsonSpeechModel = 'en-UK_BroadbandModel'; // or en-GB_BroadbandModel? console.log("UK English broadband."); break; case targetLanguage === 'en' && !setBroadband && setUSEnglish: watsonSpeechModel = 'en-US_NarrowbandModel'; console.log("US English narrowband."); break; case targetLanguage === 'en' && !setBroadband && !setUSEnglish: watsonSpeechModel = 'en-UK_NarrowbandModel'; // or en-GB_NarrowbandModel? console.log("UK English narrowband."); break; case targetLanguage === 'es' && setBroadband: watsonSpeechModel = 'es-ES_BroadbandModel'; console.log("Spanish broadband."); break; case targetLanguage === 'es' && !setBroadband: watsonSpeechModel = 'es-ES_NarrowbandModel'; console.log("Spanish narrowband."); break; case targetLanguage === 'fr' && setBroadband: watsonSpeechModel = 'fr-FR_BroadbandModel'; console.log("French broadband."); break; case targetLanguage === 'fr' && !setBroadband: watsonSpeechModel = 'fr-FR_NarrowbandModel'; console.log("French narrowband."); break; case targetLanguage === 'ja' && setBroadband: watsonSpeechModel = 'ja-JA_BroadbandModel'; console.log("Japanese broadband."); break; case targetLanguage === 'ja' && !setBroadband: watsonSpeechModel = 'ja-JA_NarrowbandModel'; console.log("Japanese narrowband."); break; case targetLanguage === 'pt' && setBroadband: watsonSpeechModel = 'pt-BR_BroadbandModel'; console.log("Brazilian Portuguese broadband."); break; case targetLanguage === 'pt' && !setBroadband: watsonSpeechModel = 'pt-BR_NarrowbandModel'; console.log("Brazilian Portuguese narrowband."); break; case targetLanguage === 'zh' && setBroadband: watsonSpeechModel = 'zh-CN_BroadbandModel'; console.log("Mandarin Chinese broadband."); break; case targetLanguage === 'zh' && !setBroadband: watsonSpeechModel = 'zh-CN_NarrowbandModel'; console.log("Mandarin Chinese narrowband."); break; default: console.log("Error: no Watson language model."); }; return watsonSpeechModel; // return the local variable to the controller }; // close toController return { fromController: fromController, // map local function to controller function toController: toController }; });
/*! * bespoke-oridomi v0.0.0 * https://github.com/ebow/bespoke-oridomi * * Copyright 2013, Tim Churchward * This content is released under the MIT license */ (function(bespoke) { bespoke.plugins.oridomi = function(deck, options) { var oridomi_options = { speed: 1200, // folding duration in ms ripple: 2, // backwards ripple effect when animating shadingIntesity: 0.5, // lessen the shading effect perspective: 800, // smaller values exaggerate 3D distortion maxAngle: 40, // keep the user's folds within a range of -40 to 40 degrees shading: 'soft' // change the shading type }; // override default values with incoming options if(options.hasOwnProperty('oridomi_options')) { for(var option in options.oridomi_options) { oridomi_options[option] = options.oridomi_options[option]; } } var oridomi_slides = deck.slides.map(function(slide) { return new OriDomi(slide, oridomi_options); }, oridomi_options); deck.on('activate', function(e) { console.log('Slide #' + e.index + ' was activated!', e.slide); // var current_slide_folder = oridomi_slides[e.index]; // current_slide_folder.unfold(); }); deck.on('deactivate', function(e) { console.log('Slide #' + e.index + ' was deactivated!', e.slide); }); deck.on('next', function(e) { console.log('The next slide is #' + (e.index + 1), deck.slides[e.index + 1]); console.log('folded: '+ e.folded); if(!e.folded) { var current_slide_folder = oridomi_slides[e.index]; current_slide_folder.foldUp(function(){deck.next({folded: true});}); return false; } }); deck.on('prev', function(e) { console.log('The previous slide is #' + (e.index - 1), deck.slides[e.index - 1]); // return false to cancel user interaction }); deck.on('slide', function(e) { console.log('The requested slide is #' + e.index, e.slide); // return false to cancel user interaction }); }; }(bespoke));
var gulp = require('gulp'); var minifyCSS = require('gulp-minify-css'); var less = require('gulp-less'); var sourcemaps = require('gulp-sourcemaps'); var rename = require('gulp-rename'); var jade = require('gulp-jade'); var livereload = require('gulp-livereload'); var distDest = 'dist/'; var cssDistDest = distDest + 'css/'; gulp.task('less', function () { var files = [ 'src/less/demeter-nr.less', 'src/less/demeter.less', 'src/less/animations.less', 'src/less/prettify.less' ]; gulp.src(files) .pipe(less()) .pipe(gulp.dest(cssDistDest)); gulp.src('tests/jade/tests.less') .pipe(less()) .pipe(gulp.dest('tests/html')); gulp.src(files) .pipe(sourcemaps.init()) .pipe(less()) .pipe(rename(function (path) { path.basename += "-min"; })) .pipe(minifyCSS()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest(cssDistDest)); }); gulp.task('jade', function () { var files = [ 'tests/jade/*.jade' ]; gulp.src(files) .pipe(jade({ pretty: true })) .pipe(gulp.dest('tests/html')); }); gulp.task('default', ['less', 'jade']); gulp.task('watch', function () { livereload.listen(); gulp.watch('src/less/*.less', ['less']); gulp.watch('tests/jade/*.jade', ['jade']); });
// 初始化iCheck function initiCheck() { if ($('.icheck-cat').length > 0) { $('input.icheck-cat').iCheck({ checkboxClass: 'icheckbox_square-grey', radioClass: 'iradio_square-grey', increaseArea: '20%' }); } } // 初始化下拉框插件 $('.selectpicker').selectpicker(); // 新增分类 function addCategory() { $("#category-add").removeClass("hide"); $("#category-info").addClass("hide"); resetAddInfo(); } // 保存新分类 function saveCategory() { var query = {}; if ($("#name").val()) { query.name = $("#name").val().trim(); } else { toastr.warning("请输入分类名称!"); return; } if ($("#desc").val()) { query.desc = $("#desc").val().trim(); } else { toastr.warning("请输入描述信息!"); return; } query.style = $("#style").selectpicker('val'); query.is_pub = $('input:radio:checked')[0].defaultValue; query.is_remove = $('input:radio:checked')[1].defaultValue; alert(query) $.ajax({ url: '/api/category', type: 'POST', data: query, success: function (data) { console.log(data) if (data.code == 1) { toastr.success("新增分类成功!"); $("#category-add").addClass("hide"); $("#category-info").removeClass("hide"); resetAddInfo(); getCategory(); } else { toastr.error("新增分类失败:" + data.msg + "!"); } } }); } // 取消保存新分类 function cancelSave() { $("#category-add").addClass("hide"); $("#category-info").removeClass("hide"); resetAddInfo(); } // 重置新增输入 function resetAddInfo() { $("#name").val(""); $("#desc").val(""); $("#style").selectpicker('val', 'default'); } // 获取分类 function getCategory() { $.ajax({ url: '/api/category', type: 'GET', success: function (rm) { if (rm.code == 1) { var data = rm.result; var str_panel = ''; data.map(function (index, key) { str_panel += '<div class="panel panel-' + index.style + ' ">' + '<div class="panel-heading">' + '<h3 class="panel-title">' + '<a class="block-collapse" data-parent="#accordion-' + key + '" data-toggle="collapse" href="#accordion-' + key + '-child-' + key + '">' + index.name + '<span class="right-content">' + '<span class="right-icon">' + '<i class="glyphicon glyphicon-plus icon-collapse"></i>' + '</span>' + '</span>' + '</a>' + '</h3>' + '</div>' + '<div id="accordion-' + key + '-child-' + key + '" class="collapse">' + '<div class="panel-body">' + '<span>' + index.desc + '</span>' + '<hr class="all-hr" />' + '<span title="修改" style="cursor:pointer" onclick="detailCategory(\'' + index._id + '\')"><i class="fa fa-edit"></i></span>&nbsp;&nbsp;' + '<span title="删除" style="cursor:pointer" onclick="detailCategory(\'' + index._id + '\')"><i class="fa fa-trash-o"></i></span>&nbsp;&nbsp;' + '<span title="详情" style="cursor:pointer" onclick="detailCategory(\'' + index._id + '\')"><i class="fa fa-list-alt"></i></span>' + '</div>' + '</div>' + '</div>'; }); $("#category-group").html(str_panel); initPanel(); } else { toastr.error("查询分类失败:" + rm.msg + "!"); } } }); } // 分类详情 function detailCategory(id) { toastr.success(id); } // 初始化panel点击 function initPanel() { $('.collapse').on('show.bs.collapse', function () { var id = $(this).attr('id'); $('a.block-collapse[href="#' + id + '"] span.right-icon').html('<i class="glyphicon glyphicon-minus icon-collapse"></i>'); }); $('.collapse').on('hide.bs.collapse', function () { var id = $(this).attr('id'); $('a.block-collapse[href="#' + id + '"] span.right-icon').html('<i class="glyphicon glyphicon-plus icon-collapse"></i>'); }); } // 页面加载执行 $(function () { $("#add-category").on("click", function () { addCategory(); }); $("#save").on("click", function () { saveCategory(); }); $("#cancel").on("click", function () { cancelSave(); }); getCategory(); initiCheck(); })
import ffi from 'ffi'; import ref from 'ref'; const { bool, uint8, uint32 } = ref.types; const voidPtr = ref.refType(ref.types.void); const BLP = voidPtr; const FILE = voidPtr; export default new ffi.Library('libblp', { blp_convert: [voidPtr, [FILE, BLP, uint8]], blp_height: [uint32, [BLP, uint8]], blp_nbMipLevels: [uint32, [BLP]], blp_processFile: [BLP, [FILE]], blp_release: [bool, [BLP]], blp_version: [uint8, [BLP]], blp_width: [uint32, [BLP, uint8]], });
(function () { 'use strict'; angular .module('openSenseMapApp') .controller('EditBoxExtensionsController', EditBoxExtensionsController); EditBoxExtensionsController.$inject = ['notifications', 'boxData', 'AccountService']; function EditBoxExtensionsController (notifications, boxData, AccountService) { var vm = this; vm.save = save; vm.extensions = { feinstaub: { id: '', disabled: false } }; activate(); //// function activate () { if (boxData.model.includes('Feinstaub')) { vm.extensions.feinstaub.id = 'feinstaub'; vm.extensions.feinstaub.disabled = true; } } function save () { var data = { 'addons': { 'add': vm.extensions.feinstaub.id } }; return AccountService.updateBox(boxData._id, data) .then(function (response) { angular.copy(response.data, boxData); notifications.addAlert('info', 'NOTIFICATION_BOX_UPDATE_SUCCESS'); }) .catch(function () { notifications.addAlert('danger', 'NOTIFICATION_BOX_UPDATE_FAILED'); }); } } })();
#!/usr/bin/env node /* ------------------------------------------------------------------ * node-gotapi - index.js * * Copyright (c) 2017-2018, Futomi Hatano, All rights reserved. * Released under the MIT license * Date: 2018-11-17 * ---------------------------------------------------------------- */ 'use strict'; process.chdir(__dirname); let mPath = require('path'); let mFs = require('fs-extra'); let mHttp = require('http'); // Command line options let enable_debug = false; let disable_auth = false; let disable_monitor = false; if(process.argv.length > 2) { for(let i=2; i<process.argv.length; i++) { let opt = process.argv[i]; if(opt === '--enable-debug') { enable_debug = true; } else if(opt === '--disable-auth') { disable_auth = true; } else if(opt === '--disable-monitor') { disable_monitor = true; } else { console.log('Unknow option: ' + opt); process.exit(); } } } if(enable_debug === false) { disable_auth = false; disable_monitor = true; } if(!_isExistFile('./config.js')) { try { mFs.copySync('./config-default.js', './config.js'); } catch(e) { _errorExit('Failed to copy `config-default.js` to `config.js`: ' + e.message); } } if(!_isExistFile('./html')) { try { mFs.copySync('./html-default', './html'); } catch(e) { _errorExit('Failed to copy `html-default` to `html`: ' + e.message); } } if(!_isExistFile('./plugins')) { try { mFs.copySync('./plugins-default', './plugins'); } catch(e) { _errorExit('Failed to copy `plugins-default` to `plugins`: ' + e.message); } } try { mFs.ensureDirSync('./ssl'); } catch(e) { _errorExit('Failed to make a directory `ssl`: ' + e.message); } let config = null; try { config = require('./config.js'); } catch(error) { _errorExit('Failed to load `config.js`: ' + error.message); } ['plugin_root_path', 'http_server_document_root'].forEach((k) => { config[k] = mPath.resolve(mPath.join(__dirname, config[k])); }); if(config['ssl_engine'] === true) { if(config['ssl_key_file'] && config['ssl_crt_file']) { let key_res = _loadSSLFile(config['ssl_key_file']); let crt_res = _loadSSLFile(config['ssl_crt_file']); if(key_res['error']) { _errorExit('Failed to load the `ssl_key_file`: ' + key_res['error'].message); } else if(crt_res['error']) { _errorExit('Failed to load the `ssl_crt_file`: ' + crt_res['error'].message); } else { config['ssl_key_data'] = key_res['data']; config['ssl_crt_data'] = crt_res['data']; } if(config['ssl_ca_file_path']) { let ca_res = _loadSSLFile(config['ssl_ca_file']); if(ca_res['error']) { _errorExit('Failed to load the `ssl_ca_file`: ' + ca_res['error'].message); } else { config['ssl_ca_data'] = ca_res['data']; } } startServer(); } else { let key_file = mPath.resolve(mPath.join(__dirname, './ssl/server.key')); let crt_file = mPath.resolve(mPath.join(__dirname, './ssl/server.crt'));; let key_res = _loadSSLFile(key_file); let crt_res = _loadSSLFile(crt_file); if(!key_res['error'] && !crt_res['error']) { config['ssl_key_data'] = key_res['data']; config['ssl_crt_data'] = crt_res['data']; startServer(); } else { let pem = null; try { pem = require('pem'); } catch(err) { _errorExit(err.message); } pem.createCertificate({days:3650, selfSigned:true}, (err, keys) => { if(err) { _errorExit(err.message); } else { config['ssl_key_data'] = keys.serviceKey; config['ssl_crt_data'] = keys.certificate; try { mFs.writeFileSync(key_file, keys.serviceKey, 'ascii'); mFs.writeFileSync(crt_file, keys.certificate, 'ascii'); } catch(error) { _errorExit(error.message); } startServer(); } }); } } } else { startServer(); } function startServer() { let GotapiServer = require('./lib/gotapi-server.js'); let gotapi_server = new GotapiServer(config); if(disable_monitor === false) { gotapi_server.oncommunication = (m) => { console.log('----------------------------------------------'); // The direction of the message and the GotAPI Interface if(m['dir'] === 1) { // incoming message console.log('>> IF-' + m['type']); } else if(m['dir'] === 2) { // outgoing message console.log('<< IF-' + m['type']); } console.log(''); // The contents of the message if(m['type'] === 1) { // GotAPI-Interface-1/2 (HTTP) if(m['dir'] === 1) { // incoming console.log(m['method'] + ' ' + m['url']); } else if(m['dir'] === 2) { // outgoing console.log(m['code'] + ' ' + mHttp.STATUS_CODES[m['code']]); console.log(''); console.log(JSON.stringify(m['data'], null, ' ')); } } else if(m['type'] === 5) { // GotAPI-Interface-5 (WebSocket) console.log(JSON.stringify(m['data'], null, ' ')); } else if(m['type'] === 4) { // GotAPI-Interface-4 (Plug-In) console.log(JSON.stringify(m['data'], null, ' ')); } console.log(''); }; } gotapi_server.start({ enable_console: enable_debug, disable_auth: disable_auth }, () => { // For debug /* if(global.gc) { setInterval(() => { global.gc(); console.log(process.memoryUsage()); }, 60000); } */ }); } function _errorExit(message) { console.log('[ERROR] ' + message); process.exit(1); } function _loadSSLFile(path) { let res = {data: null, error: null}; if(_isExistFile(path)) { try { res['data'] = mFs.readFileSync(path, 'ascii'); } catch(e) { res['error'] = e; } } else { res['error'] = new Error('Not found `' + path + '`.'); } return res; } function _isExistFile(f) { let exist = false; try { mFs.statSync(f); exist = true; } catch(e) { exist = false; } return exist; }
/** * Copyright (c) 2014, 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ "use strict"; define(["ojs/ojcore","jquery","ojs/ojcomponentcore"],function(a,g){function c(a,c,e,f,g,k,l,m){this.Nd=a;this.kIa=c;this.UA=e;this.KL=f;g&&(g.xSa&&(this.DIa=g.xSa),g.gSa&&(this.THa=g.gSa),g.ypa&&(this.EIa=g.ypa),g.fpa&&(this.UHa=g.fpa),g.xpa&&(this.CIa=g.xpa),g.epa&&(this.SHa=g.epa));k&&(k.Xpa&&(this.Aia=k.Xpa),k.nPa&&(this.kX=k.nPa),k.hOa&&(this.kx=k.hOa),k.bm&&(this.BL=k.bm),k.Gn&&(this.MO=k.Gn),k.eI&&(this.Bi=k.eI),k.wJ&&(this.bh=k.wJ),k.Gna&&(this.IN=k.Gna),k.Wla&&(this.ZW=k.Wla),k.ig&&(this.mC= k.ig),k.hf&&(this.lC=k.hf));l&&(l.ppa&&(this.bha=l.ppa),l.ula&&(this.oaa=l.ula),l.eoa&&(this.Zx=l.eoa),l.Jna&&(this.zB=l.Jna));this.IL=!0;this.iB=0;m&&(this.Q9=m.browserVersion);a=navigator.userAgent.toLowerCase();if(-1!==a.indexOf("gecko/"))this.Swa=!0;else if(-1!==a.indexOf("opera"))this.Twa=!0;else if(m&&"safari"===m.browser)this.b$=!0;else if(-1!==a.indexOf("applewebkit")||-1!==a.indexOf("safari"))this.Uwa=!0}c.prototype.vt=function(a){var d=this;if(a){this.Iya();this.Uya(this.DIa,this.EIa,this.CIa); this.Lya(this.THa,this.UHa,this.SHa);var e=this.Hk;this.q$=e.offsetWidth;this.p$=e.offsetHeight;this.PN();this.NN();this.OG=function(a){d.KEa(a)};c.Ai(this.Nd,"mousewheel",this.OG);c.Ai(this.Nd,"wheel",this.OG);this.X0=function(a){d.gZ(a)};c.Ai(this.$g,"touchstart",this.X0);this.W0=function(a){d.fZ(a)};c.Ai(this.$g,"touchmove",this.W0);this.TH=function(a){d.dZ(a)};c.Ai(this.$g,"touchend",this.TH);c.Ai(this.$g,"touchcancel",this.TH);this.m_=0}else this.Nha();this.XV();this.L9(a);this.Ji(!0);a&&(this.BL&& (this.Dk=function(){d.Ji(!1)},this.BL.call(this.kx,this.Nd,this.Dk),this.BL.call(this.kx,this.Ql,this.Dk)),this.lC&&this.lC(this.Ql))};c.prototype.destroy=function(){var a=this.Nd;c.yg(a,"mousewheel",this.OG);c.yg(a,"wheel",this.OG);c.yg(this.$g,"touchstart",this.X0);c.yg(this.$g,"touchmove",this.W0);c.yg(this.$g,"touchend",this.TH);c.yg(this.$g,"touchcancel",this.TH);c.yg(this.$g,"scroll",this.$_);this.$_=this.TH=this.W0=this.X0=this.OG=null;this.MO&&this.Dk&&(this.MO.call(this.kx,a,this.Dk),this.MO.call(this.kx, this.Ql,this.Dk));this.Dk=null;this.fKa(this.Ql,a);a.removeChild(this.$g);a.removeChild(this.Hk);a.removeChild(this.be);this.Ql=this.$g=this.be=this.Hk=null;this.XV();this.UA=this.kx=this.lC=this.mC=this.ZW=this.IN=this.bh=this.Bi=this.MO=this.BL=this.kX=this.Aia=this.Nd=null};c.prototype.CI=function(){this.Ji(!1)};c.prototype.BTa=function(a){this.wy(a,!0)};c.prototype.VPa=function(){return this.Bj()};c.prototype.gKa=function(a,c){for(var e=a.childNodes;0<e.length;){var f=e[0];this.mC&&this.mC(f); c.appendChild(f);1===f.nodeType&&this.Zx&&this.Bi(f,this.Zx)}};c.prototype.fKa=function(a,c){if(a)for(var e=a.childNodes;0<e.length;){var f=e[0];c.appendChild(f);1===f.nodeType&&this.Zx&&this.bh(f,this.Zx)}};c.RF=function(a){var c=a.ownerDocument.defaultView,e=null;return e=c?c.getComputedStyle(a,null):a.currentStyle};c.CBa=function(a){a=c.RF(a);return c.Aj(a.width)};c.BBa=function(a){a=c.RF(a);return c.Aj(a.height)};c.Aj=function(a){return 0<a.length&&"auto"!=a?(a=parseInt(a,10),isNaN(a)&&(a=0), a):0};c.Ai=function(a,c,e){a.addEventListener?a.addEventListener(c,e,!1):a.attachEvent&&a.attachEvent("on"+c,e)};c.yg=function(a,c,e){a.removeEventListener?a.removeEventListener(c,e,!1):a.detachEvent&&a.detachEvent("on"+c,e)};c.ZCa=function(a){var c=0;return c=null!=a.wheelDelta?a.wheelDelta:null!=a.deltaY?-a.deltaY:-a.detail};c.YUa=function(){var a=document.createElement("div");a.style.display="table";return a};c.ZUa=function(){var a=document.createElement("div");a.style.display="table-row";return a}; c.XUa=function(){var a=document.createElement("div");a.style.display="table-cell";return a};c.PVa=function(a,c,e,f){var g=document.createElement("div"),k=g.style;k.display="inline-block";g.appendChild(a);c.appendChild(g);e&&(k.maxWidth=g.offsetWidth+"px");f&&(k.maxHeight=g.offsetHeight+"px");return g};c.prototype.ae=function(){return"horizontal"===this.kIa};c.prototype.uGa=function(){return!this.pca().hasChildNodes()};c.prototype.Nha=function(){this.m_=this.Bj();this.q0(0);this.PN();this.NN()};c.prototype.XV= function(){this.gP=this.zg=null};c.prototype.Ji=function(a){a||this.Nha();this.XV();this.zg&&this.gP||(this.zg=this.Aga());a||this.L9(!1);this.wwa()};c.prototype.wwa=function(){var a=this.Hk.style,c=this.be.style,e=this.Ql,f=this.zg;this.ae()?(e=.5*(f.$k-e.offsetHeight),a.top=e+"px",c.top=e+"px"):(e=.5*(f.ij-e.offsetWidth),this.KL&&(e=-e),a.left=e+"px",c.left=e+"px")};c.prototype.L9=function(a){var d=this.Ql,e=this.ae(),f=e?c.CBa(this.Nd):c.BBa(this.Nd);this.MG=0;this.JG=e?d.offsetWidth-f+this.q$: d.offsetHeight-f+this.p$;0>this.JG&&(this.JG=0);this.PN();this.NN();this.wy(a?this.MG:this.m_,!0);this.m_=0};c.prototype.Iya=function(){var a=this,d=this.Nd,e=document.createElement("div");this.$g=e;this.bha&&this.Bi(e,this.bha);var f=document.createElement("div");this.Ql=f;this.oaa&&this.Bi(f,this.oaa);this.gKa(d,f);d.appendChild(e);e.appendChild(f);this.$_=function(){a.WEa()};c.Ai(e,"scroll",this.$_)};c.prototype.oBa=function(){for(var a=[],c=this.UA?this.UA:this.Ql,e=c.children,f=e.length,g=0;g< f;g++){var k=e[g];1===k.nodeType&&a.push(k)}this.ZW&&(g=this.ZW,a=g(a));if(c===this.Ql&&this.Zx)for(g=0;g<a.length;g++)c=a[g],this.IN(c,this.Zx)||this.Bi(c,this.Zx);return a};c.prototype.Uya=function(a,d,e){var f=this,g=document.createElement("div");this.be=g;a&&g.setAttribute("id",a);g.setAttribute("class",d);g.setAttribute("aria-hidden","true");c.Ai(g,"click",function(){f.Cia()});e&&g.appendChild(e);this.Nd.insertBefore(g,this.$g)};c.prototype.Lya=function(a,d,e){var f=this,g=document.createElement("div"); this.Hk=g;a&&g.setAttribute("id",a);g.setAttribute("class",d);g.setAttribute("aria-hidden","true");c.Ai(g,"click",function(){f.Bia()});e&&g.appendChild(e);this.Nd.appendChild(g)};c.prototype.pca=function(){var a=this.UA;a||(a=this.Ql);return a};c.prototype.Aga=function(){var a=this.pca(),c=this.oBa(),e={ij:0,$k:0},f=[];if(a.hasChildNodes()&&c&&0<c.length)for(var a=this.ae(),g=0,g=this.Ql.offsetWidth,k=0,l=null,m=0;m<c.length;m++){var p=c[m];if(1===p.nodeType){var t=p.offsetWidth,r=p.offsetHeight, n={ij:t,$k:r,id:p.id};if(a){var s=p.offsetLeft;this.UA||0!==s||(p=p.parentNode,s=p.offsetLeft);n.start=this.KL?g-(s+t):s;0===m&&(k=n.start);n.start-=k;e.ij=n.start+t;e.$k=Math.max(e.$k,r);n.end=e.ij-1}else s=p.offsetTop,this.UA||0!==s||(p=p.parentNode,s=p.offsetTop),n.start=s,e.ij=Math.max(e.ij,t),e.$k=n.start+r,n.end=e.$k-1;l&&l.end>=n.start&&(t=l.end-(n.start-1),l.end-=t,a?l.ij-=t:l.$k-=t);f.push(n);l=n}}this.gP=f;return e};c.prototype.xB=function(){if(!this.gP){var a=this.Aga();this.zg||(this.zg= a)}return this.gP};c.prototype.bMa=function(){this.bh(this.Hk,this.zB)};c.prototype.cMa=function(){this.bh(this.be,this.zB)};c.prototype.NN=function(){this.Bi(this.Hk,this.zB)};c.prototype.PN=function(){this.Bi(this.be,this.zB)};c.prototype.HB=function(){return!this.IN(this.Hk,this.zB)};c.prototype.AG=function(){return!this.IN(this.be,this.zB)};c.prototype.sX=function(){return this.ae()?this.q$:this.p$};c.prototype.bNa=function(a){var c=this.sX(),e=this.Bj(),f=this.vO();a<=this.MG?(this.AG()&&(e-= c),this.PN()):f&&(this.AG()||(e+=c),this.cMa());a>=this.JG?(this.HB(),this.NN()):f&&(this.HB(),this.bMa());this.q0(e)};c.prototype.q0=function(a){var c=this.$g;this.ae()?c.scrollLeft=this.iW(a):c.scrollTop=a};c.prototype.UF=function(){var a=this.$g;return this.ae()?a.offsetWidth:a.offsetHeight};c.prototype.wy=function(a,c){this.au||(this.IL=!1,this.Oia(a,c))};c.prototype.Oia=function(a,d){if(!this.uGa()){this.au=!0;a=this.iya(a);this.bNa(a);var e=this.Aia;if(d||!e||a===this.Bj())this.Uga(this.IL? this.Bj():a);else{var f=this;e.call(this.kx,this.$g,this.iW(a),Math.abs(this.Bj()-a)/c.Pua,function(){f.Uga(a)})}}};c.prototype.Bj=function(){var a=this.$g;return this.ae()?this.pya(a.scrollLeft):a.scrollTop};c.prototype.vO=function(){var a=this.Ql,c=this.$g;return this.ae()?a.offsetWidth>c.offsetWidth:a.offsetHeight>c.offsetHeight};c.prototype.iya=function(a){!this.vO()||a<this.MG?a=this.MG:a>this.JG&&(a=this.JG);return a};c.prototype.KEa=function(a){var d=this.au;if(this.vO()&&!this.au){var e=c.ZCa(a); 0>e&&this.HB()?(d=!0,this.Bia()):0<e&&this.AG()&&(d=!0,this.Cia())}d&&(a.preventDefault(),a.stopPropagation())};c.prototype.gZ=function(a){a=a.touches;this.vO()&&!this.au&&1===a.length&&(this.Km=!0,a=a[0],this.lP=this.ae()?a.pageX:a.pageY,this.Y0=this.Bj(),this.KMa=this.y$(),this.LMa=this.z$(),this.nka=this.HB(),this.oka=this.AG())};c.prototype.fZ=function(a){var d=this.ae(),e=a.touches[0],e=(d?e.pageX:e.pageY)-this.lP,f=d&&this.KL?0<e:0>e,g=f&&this.nka||!f&&this.oka;if(this.Km&&g){g=this.$g;if(Math.abs(e)< c.fva*(d?g.offsetWidth:g.offsetHeight)){if(this.wy(this.Y0-e,!0),this.nka&&!this.HB()||this.oka&&!this.AG())this.Km=!1}else this.wy(f?this.KMa:this.LMa,!1),this.Km=!1;this.vy=!0}this.vy&&(a.preventDefault(),a.stopPropagation())};c.prototype.dZ=function(){this.Km&&this.wy(this.Y0,!1);this.vy=this.Km=!1};c.prototype.WEa=function(){this.IL&&!this.au&&this.Oia(this.Bj(),!0)};c.prototype.Uga=function(a){this.q0(a);this.IL=!0;this.au=!1;if(this.kX){this.iB=this.w$();a=this.x$();var c=this.xB(),e=c[this.iB]; this.iB!==a&&this.Bj()>e.start&&this.iB<c.length-2&&(this.iB++,e=c[this.iB]);this.KAa=e.id;this.kX.call(this.kx,this.KAa)}};c.prototype.Bia=function(){this.au||this.wy(this.y$(),!1)};c.prototype.Cia=function(){this.au||this.wy(this.z$(),!1)};c.prototype.y$=function(){var a=this.nxa(),c=0;return c=a===this.w$()?this.Bj()+this.UF():this.pxa(a)};c.prototype.z$=function(){var a=this.oxa(),c=0,c=a===this.x$()?this.Bj()-this.UF():this.mxa(a);this.HB()||(c+=this.sX());c<this.sX()&&(c=this.MG);return c}; c.prototype.pxa=function(a){return this.xB()[a].start};c.prototype.mxa=function(a){return this.xB()[a].end-this.UF()+1};c.prototype.w$=function(){var a=this.RL(this.Bj());return 0>a?0:a};c.prototype.x$=function(){var a=this.RL(this.Bj()+this.UF()-1),c=this.xB();return 0>a?c.length-1:a};c.prototype.oxa=function(){var a=this.RL(this.Bj()-1);return 0>a?0:a};c.prototype.nxa=function(){var a=this.RL(this.Bj()+this.UF()),c=this.xB();return 0>a?c.length-1:a};c.prototype.RL=function(a){for(var c=this.xB(), e=0;e<c.length;e++)if(a<=c[e].end)return e;return-1};c.prototype.iW=function(a){var c=a;if(this.KL&&this.ae())if(this.Swa||this.b$&&10<=this.Q9)c=-a;else if(this.Uwa||this.Twa||this.b$&&10>this.Q9)c=this.Ql.offsetWidth-this.$g.offsetWidth-a;return c};c.prototype.pya=function(a){return this.iW(a)};c.Pua=1.1;c.fva=.33;(function(){a.ab("oj.ojConveyorBelt",g.oj.baseComponent,{defaultElement:"\x3cdiv\x3e",widgetEventPrefix:"oj",options:{orientation:"horizontal",contentParent:null},_ComponentCreate:function(){this._super(); this.element.addClass("oj-conveyorbelt oj-component");this.options.disabled&&a.F.warn(b);this.hb(!0)},refresh:function(){this._super();var a="rtl"===this.rd(),a=this.Di!=a,b;a||(b=this.du.VPa());this.DW();this.hb(!0);a||this.du.BTa(b)},Ap:function(){this._super();this.rf?this.hb(this.rf[0]):this.du&&this.du.CI()},$n:function(){this._super();this.rf&&this.hb(this.rf[0])},hb:function(b){var e=this,f=this.element,h=this.options,k=h.orientation;"vertical"===k?f.addClass("oj-conveyorbelt-vertical"):f.removeClass("oj-conveyorbelt-vertical"); if(this.hF()){this.rf=null;this.Di="rtl"===this.rd();if(b&&!this.du){var l=null,m=null,p=null,t=null,r=null;"vertical"!==k?(l="oj-enabled oj-conveyorbelt-overflow-indicator oj-start oj-default",m="oj-enabled oj-conveyorbelt-overflow-indicator oj-end oj-default",p=this.fM("oj-conveyorbelt-overflow-icon oj-start"),t=this.fM("oj-conveyorbelt-overflow-icon oj-end"),r=this.Awa):(l="oj-enabled oj-conveyorbelt-overflow-indicator oj-top oj-default",m="oj-enabled oj-conveyorbelt-overflow-indicator oj-bottom oj-default", p=this.fM("oj-conveyorbelt-overflow-icon oj-top"),t=this.fM("oj-conveyorbelt-overflow-icon oj-bottom"),r=this.Bwa);var n={};n.ypa=l;n.fpa=m;n.xpa=p;n.epa=t;l={};l.bm=a.Q.bm;l.Gn=a.Q.Gn;l.eI=this.jwa;l.wJ=this.QJa;l.Gna=this.jZ;l.Wla=function(a){return e.EAa(a)};l.ig=a.Components.ig;l.hf=a.Components.hf;"enabled"!==a.qa.D2()&&(l.Xpa=r);r=null;h.contentParent&&(r=g(h.contentParent)[0]);h=a.Sa.en(navigator.userAgent);this.du=new c(f[0],k,r,this.Di,n,l,{ppa:"oj-conveyorbelt-overflow-container",ula:"oj-conveyorbelt-content-container", eoa:"oj-conveyorbelt-item",Jna:"oj-helper-hidden"},h)}this.du.vt(b);if(b)for(b=f.find(".oj-conveyorbelt-overflow-indicator"),f=0;f<b.length;f++)this.PLa(g(b[f]))}else f=!1,this.rf&&(f=this.rf[0]),this.rf=[b||f]},_destroy:function(){this.DW();this.element.removeClass("oj-conveyorbelt oj-component oj-conveyorbelt-vertical");this._super()},_setOption:function(c,e,f){var g=!1,k=this.options;switch(c){case "containerParent":case "orientation":g=k.orientation!=e;break;case "disabled":a.F.warn(b)}g&&this.DW(); this._super(c,e,f);g&&this.hb(!0)},DW:function(){var a=this.du;a&&(this.element.find(".oj-conveyorbelt-overflow-indicator").off(this.eventNamespace),a.destroy());this.du=null},hF:function(){var a=document.createElement("div"),b=a.style;b.width="10px";b.height="10px";b["-webkit-flex"]="0 0 auto";b.flex="0 0 auto";b=this.element[0];b.appendChild(a);var c=!1;try{c=0<a.offsetWidth&&0<a.offsetHeight}catch(g){}b.removeChild(a);return c},PLa:function(a){this.Uf({element:a,afterToggle:function(b){"mouseenter"=== b?a.removeClass("oj-default"):"mouseleave"===b&&a.addClass("oj-default")}});this.nk({element:a,afterToggle:function(b){"mousedown"===b||"touchstart"===b||"mouseenter"===b?a.removeClass("oj-default"):"mouseup"!==b&&"touchend"!==b&&"touchcancel"!==b&&"mouseleave"!==b||a.addClass("oj-default")}})},fM:function(a){var b=document.createElement("span");b.setAttribute("class","oj-component-icon "+a);return b},Awa:function(a,b,c,h){var k={};k.scrollLeft=b;g(a).animate(k,c,"swing",h)},Bwa:function(a,b,c,h){var k= {};k.scrollTop=b;g(a).animate(k,c,"swing",h)},jwa:function(a,b){g(a).addClass(b)},QJa:function(a,b){g(a).removeClass(b)},jZ:function(a,b){return g(a).hasClass(b)},EAa:function(a){for(var b=[],c=0;c<a.length;c++){var g=a[c];this.jZ(g,"oj-helper-detect-expansion")||this.jZ(g,"oj-helper-detect-contraction")||b.push(g)}return b},getNodeBySubId:function(a){if(null==a)return this.element?this.element[0]:null;a=a.subId;return"oj-conveyorbelt-start-overflow-indicator"===a?this.widget().find(".oj-conveyorbelt-overflow-indicator.oj-start")[0]: "oj-conveyorbelt-end-overflow-indicator"===a?this.widget().find(".oj-conveyorbelt-overflow-indicator.oj-end")[0]:"oj-conveyorbelt-top-overflow-indicator"===a?this.widget().find(".oj-conveyorbelt-overflow-indicator.oj-top")[0]:"oj-conveyorbelt-bottom-overflow-indicator"===a?this.widget().find(".oj-conveyorbelt-overflow-indicator.oj-bottom")[0]:null},getSubIdByNode:function(a){for(var b=this.getNodeBySubId({subId:"oj-conveyorbelt-start-overflow-indicator"}),c=this.getNodeBySubId({subId:"oj-conveyorbelt-end-overflow-indicator"}), g=this.getNodeBySubId({subId:"oj-conveyorbelt-top-overflow-indicator"}),k=this.getNodeBySubId({subId:"oj-conveyorbelt-bottom-overflow-indicator"}),l=this.element[0];a&&a!=l;){if(a===b)return{subId:"oj-conveyorbelt-start-overflow-indicator"};if(a===c)return{subId:"oj-conveyorbelt-end-overflow-indicator"};if(a===g)return{subId:"oj-conveyorbelt-top-overflow-indicator"};if(a===k)return{subId:"oj-conveyorbelt-bottom-overflow-indicator"};a=a.parentElement}return null}});var b="JET ConveyorBelt: 'disabled' option not supported"})(); a.U.ob("oj-conveyor-belt","baseComponent",{properties:{contentParent:{type:"string"},orientation:{type:"string",enumValues:["horizontal","vertical"]}},extension:{mb:"ojConveyorBelt"}});a.U.register("oj-conveyor-belt",{metadata:a.U.getMetadata("oj-conveyor-belt")})});
//= require ./groceries // todos
module.exports = function(grunt) { // Project configuration 'use strict'; grunt.loadNpmTasks('grunt-contrib-requirejs'); grunt.loadNpmTasks('grunt-regex-replace'); grunt.loadNpmTasks('grunt-contrib-uglify-es'); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // Compile the requirejs stuff into a single, uglified file. // the options below are taken verbatim from a standard build.js file // used for r.js (if we were doing this outside of a grunt build) requirejs: { compile: { options: { name: 'narrative_paths', baseUrl: 'kbase-extension/static', include: [ 'narrativeMain', 'buildTools/loadAppWidgets' ], mainConfigFile: 'kbase-extension/static/narrative_paths.js', findNestedDependencies: true, optimize: 'none', generateSourceMaps: true, preserveLicenseComments: false, out: 'kbase-extension/static/kbase-narrative.js', paths: { jqueryui: 'empty:', bootstrap: 'empty:', 'jquery-ui': 'empty:', narrativeConfig: 'empty:', 'base/js/utils': 'empty:', 'base/js/namespace': 'empty:', bootstraptour: 'empty:', 'services/kernels/comm': 'empty:', 'common/ui': 'empty:', 'notebook/js/celltoolbar': 'empty:', 'base/js/events': 'empty:', 'base/js/keyboard': 'empty:', 'base/js/dialog': 'empty:', 'notebook/js/notebook': 'empty:', 'notebook/js/main': 'empty:', 'custom/custom': 'empty:' }, inlineText: false, buildCSS: false, optimizeAllPluginResources: false, done: function(done, output) { console.log(output); done(); } } } }, uglify: { dist: { options: { sourceMap: true }, files: { 'kbase-extension/static/kbase-narrative-min.js': ['kbase-extension/static/kbase-narrative.js'] } } }, // Once we have a revved file, this inserts that reference into page.html at // the right spot (near the top, the narrative_paths reference) 'regex-replace': { dist: { src: ['kbase-extension/kbase_templates/notebook.html'], actions: [ { name: 'requirejs-onefile', // search: 'narrativeMain', search: 'narrativeMain.js', replace: function() { return 'kbase-narrative-min.js'; }, flags: '' } ] } }, }); grunt.registerTask('minify', [ 'requirejs', 'uglify', 'regex-replace' ]); grunt.registerTask('build', [ 'requirejs', 'regex-replace' ]); };
/* * token manager */ import request from './request'; const API_BASE = 'http://localhost'; // let globalStore; export function injectStoreToken(store) { // globalStore = store; console.log(store); } export function watchNRefreshToken() { // refresh token in 5 hours if (global.window.localStorage.refresh_token) { setInterval(refreshToken, 18000000); } } export function refreshToken() { const localStorage = global.window.localStorage; const options = { method: 'POST', body: JSON.stringify({ refresh_token: localStorage.refresh_token, }), }; return request(`${API_BASE}/auth/refresh_token`, options) .then((body) => { localStorage.access_token = body.data.access_token; localStorage.expires_in = Date.now() + (body.data.expires_in * 1000); localStorage.refresh_token = body.data.refresh_token; return true; }); } export function clearToken() { const localStorage = global.window.localStorage; localStorage.access_token = ''; localStorage.refresh_token = ''; localStorage.expires_in = ''; }
$(function() { $( "#accordion_data, #accordion_usage, #accordion_server" ).accordion( { active: false, collapsible: true } ); $("#clean_compress_json_data_button").click(function() { $("#results_compress_json_data").html(""); return false; }); $("#compress_json_data_1_button").click(function(event) { var compressedJSON = JSONC.compress( obj ); var stringCompressedJSON = JSON.stringify(compressedJSON); $("#results_compress_json_data").html( "<div class='size'>" + stringCompressedJSON.length + " bytes.</div> <div>" + stringCompressedJSON + "</div>"); return false; }); $("#compress_json_data_2_button").click(function(event) { var compressedJSON = JSONC.compress( obj2 ); var stringCompressedJSON = JSON.stringify(compressedJSON); $("#results_compress_json_data").html( "<div class='size'>" + stringCompressedJSON.length + " bytes.</div> <div>" + stringCompressedJSON + "</div>" ); return false; }); $("#clean_pack_json_data_button").click(function() { $("#results_pack_json_data").html(""); return false; }); $("#pack_json_data_1_button").click(function(event) { var stringCompressedJSON = JSONC.pack( obj ); $("#results_pack_json_data").html( "<div class='size'>" + stringCompressedJSON.length + " bytes.</div> <div>" + stringCompressedJSON + "</div>"); return false; }); $("#pack_json_data_2_button").click(function(event) { var stringCompressedJSON = JSONC.pack( obj2 ); $("#results_pack_json_data").html( "<div class='size'>" + stringCompressedJSON.length + " bytes.</div> <div>" + stringCompressedJSON + "</div>" ); return false; }); $("#clean_pack_compress_json_data_button").click(function() { $("#results_pack_compress_json_data").html(""); return false; }); $("#pack_compress_json_data_1_button").click(function(event) { var stringCompressedJSON = JSONC.pack( obj, true ); $("#results_pack_compress_json_data").html( "<div class='size'>" + stringCompressedJSON.length + " bytes.</div> <div>" + stringCompressedJSON + "</div>"); return false; }); $("#pack_compress_json_data_2_button").click(function(event) { var stringCompressedJSON = JSONC.pack( obj2, true ); $("#results_pack_compress_json_data").html( "<div class='size'>" + stringCompressedJSON.length + " bytes.</div> <div>" + stringCompressedJSON + "</div>" ); return false; }); $("#clean_decompress_json_data_button").click(function() { $("#results_decompress_json_data").html(""); return false; }); $("#decompress_json_data_1_button").click(function(event) { var oComp = JSONC.compress( obj ); var stringCompressedJSON = JSON.stringify( JSONC.decompress( oComp ) ); $("#results_decompress_json_data").html( "<div class='size'>" + stringCompressedJSON.length + " bytes.</div> <div>" + stringCompressedJSON + "</div>"); return false; }); $("#decompress_json_data_2_button").click(function(event) { var oComp = JSONC.compress( obj2 ); var stringCompressedJSON = JSON.stringify( JSONC.decompress( oComp ) ); $("#results_decompress_json_data").html( "<div class='size'>" + stringCompressedJSON.length + " bytes.</div> <div>" + stringCompressedJSON + "</div>" ); return false; }); $("#clean_unpack_json_data_button").click(function() { $("#results_unpack_json_data").html(""); return false; }); $("#unpack_json_data_1_button").click(function(event) { var gzipped = JSONC.pack( obj ); var stringCompressedJSON = JSON.stringify( JSONC.unpack( gzipped ) ); $("#results_unpack_json_data").html( "<div class='size'>" + stringCompressedJSON.length + " bytes.</div> <div>" + stringCompressedJSON + "</div>"); return false; }); $("#unpack_json_data_2_button").click(function(event) { var gzipped = JSONC.pack( obj2 ); var stringCompressedJSON = JSON.stringify( JSONC.unpack( gzipped ) ); $("#results_unpack_json_data").html( "<div class='size'>" + stringCompressedJSON.length + " bytes.</div> <div>" + stringCompressedJSON + "</div>" ); return false; }); $("#clean_unpack_compress_json_data_button").click(function() { $("#results_unpack_compressed_json_data").html(""); return false; }); $("#unpack_compress_json_data_1_button").click(function(event) { var gzipped = JSONC.pack( obj, true ); var stringCompressedJSON = JSON.stringify( JSONC.unpack( gzipped, true ) ); $("#results_unpack_compressed_json_data").html( "<div class='size'>" + stringCompressedJSON.length + " bytes.</div> <div>" + stringCompressedJSON + "</div>"); return false; }); $("#unpack_compress_json_data_2_button").click(function(event) { var gzipped = JSONC.pack( obj2, true ); var stringCompressedJSON = JSON.stringify( JSONC.unpack( gzipped, true ) ); $("#results_unpack_compressed_json_data").html( "<div class='size'>" + stringCompressedJSON.length + " bytes.</div> <div>" + stringCompressedJSON + "</div>" ); return false; }); }); $("form").submit(function(event) { var sObj, nLenObjStr, sZipped, nLenZipped; sObj = JSON.stringify( obj ); nLenObjStr = sObj.length; sZipped = JSONC.pack( obj ); //sZipped = JSONC.pack( obj, true ); //version compact nLenZipped = sZipped.length; console.log( 'Original:', sObj, sObj.length ); console.log( 'Send:', sZipped, sZipped.length ); $.ajax({ url: "/obj/demo_pack_gzip_without_base64/alo.php", type: "POST", data: { json: nLenObjStr > nLenZipped ? sZipped : sObj }, dataType: 'json', success: function( data ) { document.getElementById('info_server').innerHTML = 'Press F12 to open developer tools and check the console tab'; //data = JSONC.decompress( data ); //version compact console.log('Data:', data, JSON.stringify(data).length); }, error: function() { console.log.apply(console, arguments); } }); event.preventDefault(); });
var a = 1, b = 2, c =3; (function firstFunction(){ var b= 5, c = 6; (function secondFunction(){ var b = 8; console.log("a: "+a+", b: "+b+",c: "+c); (function thirdFunction(){ var a = 7, c = 9; (function fourthFunction() { var a = 1, c = 9; })(); })(); })(); })();
var http = require('http'); var path = require('path'); var express = require('express'); var router = express(); var server = http.createServer(router); var bodyParser = require('body-parser'); // Routes for commands router.use(bodyParser.json()); router.use(bodyParser.urlencoded({ extended: true })); router.post('/cmd', function(req, res) { res.contentType('application/json'); processCommands(req.body, function(objResult) { res.writeHead(200); res.write(JSON.stringify(objResult)); res.end(); }); }); //router.get('/cmd*', function(req, res) { }); // Not implemented yet // Routes for static files router.get('/simplex.js', function (req, res) { res.sendFile(path.resolve(__dirname, '../simplex.js')); }); router.use(express.static(path.resolve(__dirname, 'web'))); router.use('/lib', express.static(path.resolve(__dirname, 'lib'))); // Initial test data used in commands var users = [ { name: 'Richard', balance: 1000 }, { name: 'Jona', balance: 2000 } ]; var commands = { getUser: function (params, callback) { if(params.id > users.length || params.id < 0) { return { error: 'user does not exist.' }; } callback(users[params.id]); }, addUser: function (params, callback) { users.push(params); callback( { success: true } ); } }; // Commands helper functions function processCommands(input, callback) { var cmd, cmdName, res = {}, len = 0, complete = 0, completeFn = function(cmdName, cmdRes) { complete += 1; res[cmdName] = cmdRes; if(len === complete) { callback(res); } }; for(cmdName in input) { if (!input.hasOwnProperty(cmdName)) { continue; } len += 1; cmd = commands[cmdName]; if(!cmd) { res[cmdName] = { error: true, message: 'Command not found.' }; complete += 1; } else { runCommand(cmd, cmdName, input[cmdName], completeFn); } } if(len === complete) { callback(res); } } function runCommand(cmd, cmdName, params, callback) { cmd(params, function(cmdRes) { callback(cmdName, cmdRes); }); } server.listen(80, '0.0.0.0', function(){ console.log('Simplex Framework Test\n => http://localhost:80 /\nCTRL + C to shutdown'); });
import Emitter from "component-emitter"; import expect from "expect.js"; import ReconnectingProxy from "../src/reconnecting-proxy"; import sinon from "sinon"; class FakeClient extends Emitter { open() { return this; } close() { return this; } } describe("ReconnectingProxy", () => { beforeEach(function() { this.fakeClient = new FakeClient(); }); describe("when an `error` event is emitted from the client", () => { it("should close client", function() { var proxy = new ReconnectingProxy(this.fakeClient); var spy = sinon.spy(this.fakeClient, "close"); proxy.open(); this.fakeClient.emit("error", "abc"); expect(spy.called).to.be.ok(); }); }); });
function fruitLandings(house, trees, numOfFruits, ap, org) { var applesLanded = 0; var orangesLanded = 0; var apples = ap.map(function(val){ var apple = parseInt(trees[0]) + parseInt(val) if ( apple >= house[0] && apple <= house[1] ) { applesLanded++; } }); var oranges = org.map(function(val){ var orange = parseInt(trees[1]) + parseInt(val) if ( orange >= house[0] && orange <= house[1] ) { orangesLanded++; } }); return applesLanded + '\n' + orangesLanded; } function main() { var s_temp = readLine().split(' '); var s = parseInt(s_temp[0]); var t = parseInt(s_temp[1]); var a_temp = readLine().split(' '); var a = parseInt(a_temp[0]); var b = parseInt(a_temp[1]); var m_temp = readLine().split(' '); var m = parseInt(m_temp[0]); var n = parseInt(m_temp[1]); apple = readLine().split(' '); apple = apple.map(Number); orange = readLine().split(' '); orange = orange.map(Number); var res = fruitLandings(s_temp, a_temp, m_temp, apple, orange ); console.log(res); }
var validator = require("validator"); var exports = module.exports = {}; exports.sanitize = function(data) { var newData = []; for (var key in data) { newData[key] = sanitizeString(data[key]); } return newData; } var sanitizeString = exports.sanitizeString = function(data) { data = data.toString().trim(); data = validator.escape(data); return data; } var sanitizeStringStrict = exports.sanitizeStringStrict = function(data) { data = data.toString().trim(); data = validator.escape(data); data = validator.whitelist(data, 'a-zA-Z0-9-_ !?&\u00c4\u00e4\u00d6\u00f6\u00dc\u00fc\u00df'); return data; } exports.validateImageURL = function(data) { if (data == null) { return false; } else { return validator.isURL(data.toString(), { protocols: ["https"], require_tld: true, require_protocol: true, require_host: true, require_valid_protocol: true, allow_underscores: false, host_whitelist: false, host_blacklist: false, allow_trailing_dot: false, allow_protocl_relative_urls: false }); } } exports.checkValidDate = function(date) { return validator.isNumeric(date.toString());; } exports.sanitizeNumber = function(data) { data = data.toString().trim(); data = validator.escape(data); data = validator.whitelist(data, '0-9'); return parseInt(data); } exports.checkValidNumber = function(number) { return validator.isNumeric(number.toString()); } exports.toObject = function(arr) { return arr.reduce(function(acc, cur, i) { acc[i] = cur; return acc; }, {}); } exports.checkValidString = function(string, canBeNull, minLength, maxLength) { if (string == null) { if (canBeNull) { return true; } else { return false; } } else { if (!validator.isLength(string, { min: minLength, max: maxLength })) { return false; } } return true; } exports.validateEmail = function(email) { return validator.isEmail(email); }
import moment from 'moment'; function selectedData(get) { const selectedDate = moment(get('container.selectedDate')).format('DD-MM-YYYY'); return get(`container.data.data.${selectedDate}`); } export default selectedData;
"use strict"; let datafire = require('datafire'); let openapi = require('./openapi.json'); module.exports = datafire.Integration.fromOpenAPI(openapi, "roaring");
angular.module('queup.queue_list', []) // Queue List Controller // --------------------- // Monitors current queue state, and manages socket interaction between teacher and server .controller('Queue_listController', function($state, $scope, socket, teacherData, sinch){ var currentClass = teacherData.get('currentClass'); // If there is no current class, redirect to class list // so things don't break due to undefined currentClass if( currentClass.id === null) { $state.go('q.before_session.class_list'); return; } // Emit event to register class id with socket id on server (for routing socket messages from students to teacher) socket.emit('classReady', {classID: currentClass.classID}); // Get current class info to display, and for sending on server reqs $scope.currentClass = {id: currentClass.classID, name: currentClass.name}; $scope.queue = []; $scope.hasQuestions = true; $scope.noQuestions = false; $scope.modal = { name: "", fbPicture: "", email: "", timer: 0 }; // Call on student, send id and index in the queue so it can be returned/confirmed as received $scope.handleClick = function(student, index) { $scope.modal = { name: student.name, fbPicture: student.fbPicture, email: student.email, timer: student.timer }; clearInterval(student.timerID); socket.emit('callOnStudent', {email: student.email, index: index, classID: currentClass.classID}); $('#aModal').modal('show'); sinch.call(student.email) }; var removeFromQueue = function(student) { $scope.queue.splice(student.index,1); $('.questions').html($scope.queue.length); if($scope.queue.length === 0) { $scope.hasQuestions = false; $scope.noQuestions = true; } $('#aModal').modal('hide'); }; var addStudentToList = function(data) { data.timer = 0; data.timerID = setInterval(function ($scope) { var self = this $scope.$apply(function () { self.timer++; }); }.bind(data, $scope), 60000); $scope.queue.push(data); $('.questions').html($scope.queue.length); // send confirmation to student that they were added to list socket.emit('studentAddedToQueue', data) $scope.hasQuestions = true; $scope.noQuestions = false; }; // Listen for queue updates from server socket.on('studentRaisedHand', addStudentToList); // If server confims student receieved call, remove from queue socket.on('studentConfirmation', removeFromQueue); // Ask for queue of current class from server when view gets instantiated socket.emit('queueRequest', {classID: $scope.currentClass.classID, data: 'give me the queue'}); // Remove listeners to avoid memory leak when user leaves view and comes back $scope.$on('$destroy', function() { socket.off('studentRaisedHand', addStudentToList); socket.off('studentReceivedCall', removeFromQueue); }); });
/** This object represents a point in the canvas.. author: Houman Kamran **/ var Point = function(x, y) { this.x = x; this.y = y; };
(function () { 'use strict'; const highlightClass = 'playing'; const keys = document.querySelectorAll('.key'); const sounds = document.querySelectorAll('audio'); const clearTransition = (event) => { if (event.propertyName !== 'transform') { return; } event.target.classList.remove(highlightClass); }; const playSound = (event) => { const keyCode = event.keyCode.toString(); keys.forEach(k => k.dataset.key === keyCode && k.classList.add(highlightClass)); sounds.forEach(s => { if (s.dataset.key !== keyCode) { return; } s.currentTime = 0; return s.play(); }); }; keys.forEach(k => k.addEventListener('transitionend', clearTransition)); document.addEventListener('keyup', playSound); }());
import * as productsPartials from '@/store/partials/products'; import {RecipeModel} from '@/models'; import Delta from 'quill-delta'; export const INIT_MODEL = new RecipeModel(); export const createState = () => ({ model : INIT_MODEL, placeholder : null, uploading : false, imageProcessingUUID : null, loaded : false, loading : false, editing : false, preparationOut : new Delta(), preparationIn : new Delta(), ingredientsInShoppingList : {}, ingredients : productsPartials.createState() });
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow strict-local * @emails oncall+relay */ // flowlint ambiguous-object-type:error 'use strict'; const { MultiActorEnvironment, getActorIdentifier, } = require('../../multi-actor-environment'); const RelayNetwork = require('../../network/RelayNetwork'); const {graphql} = require('../../query/GraphQLTag'); const RelayModernEnvironment = require('../RelayModernEnvironment'); const { createOperationDescriptor, } = require('../RelayModernOperationDescriptor'); const {createReaderSelector} = require('../RelayModernSelector'); const RelayModernStore = require('../RelayModernStore'); const RelayRecordSource = require('../RelayRecordSource'); const { disallowWarnings, expectWarningWillFire, } = require('relay-test-utils-internal'); disallowWarnings(); const ActorQuery = graphql` query RelayModernEnvironmentCommitPayloadTestActorQuery { me { name } } `; describe.each(['RelayModernEnvironment', 'MultiActorEnvironment'])( 'CommitPayload', environmentType => { let environment; let operation; let source; let store; describe(environmentType, () => { beforeEach(() => { operation = createOperationDescriptor(ActorQuery, {}); source = RelayRecordSource.create(); store = new RelayModernStore(source); // $FlowFixMe[method-unbinding] added when improving typing for this parameters (store: $FlowFixMe).notify = jest.fn(store.notify.bind(store)); // $FlowFixMe[method-unbinding] added when improving typing for this parameters (store: $FlowFixMe).publish = jest.fn(store.publish.bind(store)); const fetch = jest.fn(); const multiActorEnvironment = new MultiActorEnvironment({ createNetworkForActor: _actorID => RelayNetwork.create(fetch), createStoreForActor: _actorID => store, }); environment = environmentType === 'MultiActorEnvironment' ? multiActorEnvironment.forActor(getActorIdentifier('actor:1234')) : new RelayModernEnvironment({ network: RelayNetwork.create(fetch), store, }); }); it('applies server updates', () => { const callback = jest.fn(); const snapshot = environment.lookup(operation.fragment); environment.subscribe(snapshot, callback); environment.commitPayload(operation, { me: { id: '4', __typename: 'User', name: 'Zuck', }, }); expect(callback.mock.calls.length).toBe(1); expect(callback.mock.calls[0][0].data).toEqual({ me: { name: 'Zuck', }, }); }); it('does not fill missing fields from server updates with null when treatMissingFieldsAsNull is disabled (default)', () => { const query = graphql` query RelayModernEnvironmentCommitPayloadTest2ActorQuery { me { name birthdate { day month year } } } `; operation = createOperationDescriptor(query, {}); const callback = jest.fn(); const snapshot = environment.lookup(operation.fragment); environment.subscribe(snapshot, callback); expectWarningWillFire( 'RelayResponseNormalizer: Payload did not contain a value for field `birthdate: birthdate`. Check that you are parsing with the same query that was used to fetch the payload.', ); environment.commitPayload(operation, { me: { id: '4', __typename: 'User', name: 'Zuck', // birthdate is missing in this response }, }); expect(callback.mock.calls.length).toBe(1); expect(callback.mock.calls[0][0].data).toEqual({ me: { name: 'Zuck', birthdate: undefined, // with treatMissingFieldsAsNull disabled this is left missing }, }); // and thus the snapshot has missing data expect(callback.mock.calls[0][0].isMissingData).toEqual(true); }); it('fills missing fields from server updates with null when treatMissingFieldsAsNull is enabled', () => { environment = new RelayModernEnvironment({ network: RelayNetwork.create(jest.fn()), store, treatMissingFieldsAsNull: true, }); const query = graphql` query RelayModernEnvironmentCommitPayloadTest3ActorQuery { me { name birthdate { day month year } } } `; operation = createOperationDescriptor(query, {}); const callback = jest.fn(); const snapshot = environment.lookup(operation.fragment); environment.subscribe(snapshot, callback); environment.commitPayload(operation, { me: { id: '4', __typename: 'User', name: 'Zuck', // birthdate is missing in this response }, }); expect(callback.mock.calls.length).toBe(1); expect(callback.mock.calls[0][0].data).toEqual({ me: { name: 'Zuck', birthdate: null, // with treatMissingFieldsAsNull enabled this is filled with null }, }); // and thus the snapshot does not have missing data expect(callback.mock.calls[0][0].isMissingData).toEqual(false); }); it('rebases optimistic updates', () => { const callback = jest.fn(); const snapshot = environment.lookup(operation.fragment); environment.subscribe(snapshot, callback); environment.applyUpdate({ storeUpdater: proxyStore => { const zuck = proxyStore.get('4'); if (zuck) { const name = zuck.getValue('name'); if (typeof name !== 'string') { throw new Error('Expected zuck.name to be defined'); } zuck.setValue(name.toUpperCase(), 'name'); } }, }); environment.commitPayload(operation, { me: { id: '4', __typename: 'User', name: 'Zuck', }, }); expect(callback.mock.calls.length).toBe(1); expect(callback.mock.calls[0][0].data).toEqual({ me: { name: 'ZUCK', }, }); }); it('applies payload on @defer fragments', () => { const id = '4'; const query = graphql` query RelayModernEnvironmentCommitPayloadTest4ActorQuery { me { name ...RelayModernEnvironmentCommitPayloadTest4UserFragment @defer } } `; const fragment = graphql` fragment RelayModernEnvironmentCommitPayloadTest4UserFragment on User { username } `; operation = createOperationDescriptor(query, {}); const selector = createReaderSelector( fragment, id, {}, operation.request, ); const queryCallback = jest.fn(); const fragmentCallback = jest.fn(); const querySnapshot = environment.lookup(operation.fragment); const fragmentSnapshot = environment.lookup(selector); environment.subscribe(querySnapshot, queryCallback); environment.subscribe(fragmentSnapshot, fragmentCallback); expect(queryCallback.mock.calls.length).toBe(0); expect(fragmentCallback.mock.calls.length).toBe(0); environment.commitPayload(operation, { me: { id, __typename: 'User', name: 'Zuck', username: 'Zucc', }, }); expect(queryCallback.mock.calls.length).toBe(1); expect(queryCallback.mock.calls[0][0].data).toEqual({ me: { name: 'Zuck', __id: id, __fragments: { RelayModernEnvironmentCommitPayloadTest4UserFragment: {}, }, __fragmentOwner: operation.request, __isWithinUnmatchedTypeRefinement: false, }, }); expect(fragmentCallback.mock.calls.length).toBe(1); expect(fragmentCallback.mock.calls[0][0].data).toEqual({ username: 'Zucc', }); }); it('applies payload on @defer fragments in a query with modules', () => { const id = '4'; const query = graphql` query RelayModernEnvironmentCommitPayloadTest6ActorQuery { me { name nameRenderer { ...RelayModernEnvironmentCommitPayloadTest6MarkdownUserNameRenderer_name @module(name: "MarkdownUserNameRenderer.react") } ...RelayModernEnvironmentCommitPayloadTest6UserFragment @defer } } `; const nameFragmentNormalizationNode = require('./__generated__/RelayModernEnvironmentCommitPayloadTest6MarkdownUserNameRenderer_name$normalization.graphql'); graphql` fragment RelayModernEnvironmentCommitPayloadTest6MarkdownUserNameRenderer_name on MarkdownUserNameRenderer { __typename markdown } `; const userFragment = graphql` fragment RelayModernEnvironmentCommitPayloadTest6UserFragment on User { username } `; environment = new RelayModernEnvironment({ network: RelayNetwork.create(jest.fn()), store, operationLoader: { get: () => { return nameFragmentNormalizationNode; }, load: jest.fn(), }, }); operation = createOperationDescriptor(query, {}); const selector = createReaderSelector( userFragment, id, {}, operation.request, ); const queryCallback = jest.fn(); const fragmentCallback = jest.fn(); const querySnapshot = environment.lookup(operation.fragment); const fragmentSnapshot = environment.lookup(selector); environment.subscribe(querySnapshot, queryCallback); environment.subscribe(fragmentSnapshot, fragmentCallback); expect(queryCallback.mock.calls.length).toBe(0); expect(fragmentCallback.mock.calls.length).toBe(0); environment.commitPayload(operation, { me: { id, __typename: 'User', nameRenderer: { __typename: 'MarkdownUserNameRenderer', __module_component_RelayModernEnvironmentCommitPayloadTest6ActorQuery: 'MarkdownUserNameRenderer.react', __module_operation_RelayModernEnvironmentCommitPayloadTest6ActorQuery: 'RelayModernEnvironmentCommitPayloadTest6MarkdownUserNameRenderer_name$normalization.graphql', markdown: 'markdown payload', }, name: 'Zuck', username: 'Zucc', }, }); expect(queryCallback.mock.calls.length).toBe(1); expect(fragmentCallback.mock.calls.length).toBe(1); expect(fragmentCallback.mock.calls[0][0].data).toEqual({ username: 'Zucc', }); }); describe('when using a scheduler', () => { let taskID; let tasks; let scheduler; let runTask; beforeEach(() => { taskID = 0; tasks = new Map(); scheduler = { cancel: (id: string) => { tasks.delete(id); }, schedule: (task: () => void) => { const id = String(taskID++); tasks.set(id, task); return id; }, }; runTask = () => { for (const [id, task] of tasks) { tasks.delete(id); task(); break; } }; environment = new RelayModernEnvironment({ network: RelayNetwork.create(jest.fn()), scheduler, store, }); }); it('applies server updates', () => { const callback = jest.fn(); const snapshot = environment.lookup(operation.fragment); environment.subscribe(snapshot, callback); environment.commitPayload(operation, { me: { id: '4', __typename: 'User', name: 'Zuck', }, }); // Verify task was scheduled and run it expect(tasks.size).toBe(1); runTask(); expect(callback.mock.calls.length).toBe(1); expect(callback.mock.calls[0][0].data).toEqual({ me: { name: 'Zuck', }, }); }); }); }); }, );
'use babel' import {CompositeDisposable} from 'atom' class RenameDialog { constructor (identifier, callback) { this.identifier = identifier this.callback = callback this.element = document.createElement('div') this.element.classList.add('gorename') this.subscriptions = new CompositeDisposable() this.subscriptions.add(atom.commands.add(this.element, 'core:cancel', () => { this.cancel() })) this.subscriptions.add(atom.commands.add(this.element, 'core:confirm', () => { this.confirm() })) this.oncancel = null let message = document.createElement('div') message.textContent = `Rename ${identifier} to:` message.style.padding = '1em' this.element.appendChild(message) this.input = document.createElement('atom-text-editor') this.input.setAttribute('mini', true) this.element.appendChild(this.input) } attach () { this.panel = atom.workspace.addModalPanel({ item: this.element }) this.input.model.setText(this.identifier) this.input.model.selectAll() this.input.focus() } onCancelled (callback) { this.oncancel = callback } cancel () { this.close() if (this.oncancel) { this.oncancel() this.oncancel = null } } confirm () { let newName = this.input.getModel().getText() this.close() this.callback(newName) this.callback = null } close () { this.subscriptions.dispose() if (this.element) { this.element.remove() } this.element = null if (this.panel) { this.panel.destroy() } this.panel = null } } export {RenameDialog}
var path = require('path'); module.exports = { devtool: 'source-map', entry: './app/app.ts', output: { path: path.join(__dirname, 'app'), filename: 'app.js' }, resolve: { extensions: ['', '.js', '.ts'] }, module: { loaders: [{ test: /\.ts$/, loader: 'ts', include: [path.join(__dirname, 'src'), path.join(__dirname, 'app')] }] }, ts: { compilerOptions: { noImplicitAny: true } } };
/** * Created by jjohnson on 12/13/13. */ var should = require("should"); var OomnitzaNode = require("../lib/oomnitza-node.js"); var oom = new OomnitzaNode("domain", "user", "pass"); var checking = function(str) { process.stdout.write("Checking " + str + "() "); } var log = function(str) { process.stdout.write(str + "\n"); } var ok = function() { process.stdout.write("OK!" + "\n"); } log("Starting test suite..."); var now = new Date().valueOf(); var newUserId, newLocationId; var newProfile = { user: "tmcgee", password: "superPass1", first_name: "Timothy", last_name: "McGee", email: "tmcgee@ncis.navy.mil", phone: "123-456-7890", address: "6 Navy Yard, Washington DC", position: "Field Agent", permissions_id: 30 }; var newLocation = { location_id: "T" + now, label: "Test Label " + now, "781D57E806F311E39B9C525400385B84": "California", asset_total: 100 } function main() { oom.addUser(newProfile, function(d) { checking("addUser"); d.should.have.property("success", true); ok(); newUserId = d.resp.id; doStuffWithNewUser(); }); oom.addLocation(newLocation, function(d) { checking("addLocation"); d.should.have.property("success", true); var resp = d.resp; resp.should.have.property("id"); ok(); newLocationId = d.resp.id; doStuffWithLocation(); }); oom.getLocationFields(function(d) { checking("getLocationFields"); d.should.have.property("success", true); d.should.have.property("resp").with.property("info").instanceof(Array); ok(); }); oom.getPerms(function(d) { checking("getPerms"); d.should.have.property("success", true); d.should.have.property("resp").with.property("rows"); ok(); }); oom.getUsers(function(d) { checking("getUsers"); d.should.have.property("success", true); d.should.have.property("resp").instanceof(Array); ok(); }); } function doStuffWithNewUser() { oom.getUser(newUserId, function(d) { checking("getUser"); d.should.have.property("success", true); ok(); }); } function doStuffWithLocation() { oom.getLocation(newLocationId, function(d) { checking("getLocation"); d.should.have.property("success", true); d.should.have.property("resp").with.property("info").instanceof(Array); ok(); }); } function deleteEverything() { oom.delLocation(newLocationId, function(d) { checking("delLocation"); d.should.have.property("success", true); ok(); }); oom.delUser(newUserId, function(d) { checking("delUser"); d.should.have.property("success", true); ok(); }); } oom.on("initialized", function() { main(); }); setTimeout(deleteEverything, 5000);
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Pagination from '../src/Pagination'; describe('Pagination', () => { it('Should have class', () => { let instance = ReactTestUtils.renderIntoDocument( <Pagination>Item content</Pagination> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'pagination')); }); it('Should show the correct active button', () => { let instance = ReactTestUtils.renderIntoDocument( <Pagination items={5} activePage={3} /> ); let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); assert.equal(pageButtons.length, 5); pageButtons[2].className.should.match(/\bactive\b/); }); it('Should call onSelect when page button is selected', (done) => { function onSelect(event, selectedEvent) { assert.equal(selectedEvent.eventKey, 2); done(); } let instance = ReactTestUtils.renderIntoDocument( <Pagination items={5} onSelect={onSelect} /> ); ReactTestUtils.Simulate.click( ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'a')[1] ); }); it('Should only show part of buttons and active button in the middle of buttons when given maxButtons', () => { let instance = ReactTestUtils.renderIntoDocument( <Pagination items={30} activePage={10} maxButtons={9} /> ); let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); // 9 visible page buttons and 1 ellipsis button assert.equal(pageButtons.length, 10); // active button is the second one assert.equal(pageButtons[0].firstChild.innerText, '6'); pageButtons[4].className.should.match(/\bactive\b/); }); it('Should show the ellipsis, boundaryLinks, first, last, prev and next button with default labels', () => { let instance = ReactTestUtils.renderIntoDocument( <Pagination first={true} last={true} prev={true} next={true} ellipsis={true} maxButtons={3} activePage={10} items={20} /> ); let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); // add first, last, prev, next and ellipsis button assert.equal(pageButtons.length, 8); assert.equal(pageButtons[0].innerText, '«'); assert.equal(pageButtons[1].innerText, '‹'); assert.equal(pageButtons[5].innerText, '...'); assert.equal(pageButtons[6].innerText, '›'); assert.equal(pageButtons[7].innerText, '»'); }); it('Should show the boundaryLinks, first, last, prev and next button', () => { let instance = ReactTestUtils.renderIntoDocument( <Pagination first={true} last={true} prev={true} next={true} ellipsis={true} boundaryLinks={true} maxButtons={3} activePage={10} items={20} /> ); let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); // add first, last, prev, next and ellipsis button assert.equal(pageButtons[2].innerText, '1'); assert.equal(pageButtons[3].innerText, '...'); assert.equal(pageButtons[7].innerText, '...'); assert.equal(pageButtons[8].innerText, '20'); }); it('Should show the ellipsis, first, last, prev and next button with custom labels', () => { let instance = ReactTestUtils.renderIntoDocument( <Pagination first='first' last='last' prev='prev' next='next' ellipsis='more' maxButtons={3} activePage={10} items={20} /> ); let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); // add first, last, prev, next and ellipsis button assert.equal(pageButtons.length, 8); assert.equal(pageButtons[0].innerText, 'first'); assert.equal(pageButtons[1].innerText, 'prev'); assert.equal(pageButtons[5].innerText, 'more'); assert.equal(pageButtons[6].innerText, 'next'); assert.equal(pageButtons[7].innerText, 'last'); }); it('Should enumerate pagenums correctly when ellipsis=true', () => { const instance = ReactTestUtils.renderIntoDocument( <Pagination first last prev next ellipsis maxButtons={5} activePage={1} items={1} /> ); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); assert.equal(pageButtons[0].innerText, '«'); assert.equal(pageButtons[1].innerText, '‹'); assert.equal(pageButtons[2].innerText, '1'); assert.equal(pageButtons[3].innerText, '›'); assert.equal(pageButtons[4].innerText, '»'); }); it('Should render next and last buttons as disabled when items=0 and ellipsis=true', () => { const instance = ReactTestUtils.renderIntoDocument( <Pagination last next ellipsis maxButtons={1} activePage={1} items={0} /> ); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); assert.equal(pageButtons[0].innerText, '›'); assert.equal(pageButtons[1].innerText, '»'); assert.include(pageButtons[0].className, 'disabled'); assert.include(pageButtons[1].className, 'disabled'); }); it('Should wrap buttons in SafeAnchor when no buttonComponentClass prop is supplied', () => { let instance = ReactTestUtils.renderIntoDocument( <Pagination maxButtons={2} activePage={1} items={2} /> ); let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); let tagName = 'A'; assert.equal(pageButtons[0].children[0].tagName, tagName); assert.equal(pageButtons[1].children[0].tagName, tagName); assert.equal(pageButtons[0].children[0].getAttribute('href'), ''); assert.equal(pageButtons[1].children[0].getAttribute('href'), ''); }); it('Should wrap each button in a buttonComponentClass when it is present', () => { class DummyElement extends React.Component { render() { return <div {...this.props}/>; } } let instance = ReactTestUtils.renderIntoDocument( <Pagination maxButtons={2} activePage={1} items={2} buttonComponentClass={DummyElement} /> ); let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); let tagName = 'DIV'; assert.equal(pageButtons[0].children[0].tagName, tagName); assert.equal(pageButtons[1].children[0].tagName, tagName); }); it('Should call onSelect with custom buttonComponentClass', (done) => { class DummyElement extends React.Component { render() { return <div {...this.props}/>; } } function onSelect(event, selectedEvent) { assert.equal(selectedEvent.eventKey, 3); done(); } let instance = ReactTestUtils.renderIntoDocument( <Pagination items={5} onSelect={onSelect} buttonComponentClass={DummyElement}/> ); ReactTestUtils.Simulate.click( ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'div')[2] ); }); it('should not fire "onSelect" event on disabled buttons', () => { function onSelect() { throw Error('this event should not happen'); } const instance = ReactTestUtils.renderIntoDocument( <Pagination onSelect={onSelect} last next ellipsis maxButtons={1} activePage={1} items={0} /> ); const liElements = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); // buttons are disabled assert.include(liElements[0].className, 'disabled'); assert.include(liElements[1].className, 'disabled'); const pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'a'); const nextButton = pageButtons[0]; const lastButton = pageButtons[1]; ReactTestUtils.Simulate.click( nextButton ); ReactTestUtils.Simulate.click( lastButton ); }); });
var mongoose = require('mongoose'); var uristring = 'mongodb://heroku_6tl56f0w:lpp8c3pu0t9n60vjee7da52l8s@ds141108.mlab.com:41108/heroku_6tl56f0w'; mongoose.connect(uristring, function(err) { if(err) { console.log('Error: Connection Failed!'); } else { console.log('Connection established'); } });
version https://git-lfs.github.com/spec/v1 oid sha256:21edeb54c32a6da198ec3296b4297a596e86c7fac2e2898f6b24527c83ee4420 size 115671
App.service('Sensor', /*@ngInject*/ function($http, $rootScope, Cache) { function clearCache() { Cache.clear('^/sensors/'); } $rootScope.$on('sensor.value', function(event, data) { clearCache(); $rootScope.$broadcast('sensor.update', data.sensorVo); }); return { getAll: () => $http.get('/sensors/'), getCachedData () { return $http .get('/sensors/', {cache: Cache}) .then(result => result.data); }, getValues (sensorsIds, parameters = '') { return $http.get(`/sensors/load/${sensorsIds}/${parameters}`); }, getSensorData (sensorId, cached) { return $http.get(`/sensors/${sensorId}/value/`, {cache: cached && Cache}); }, deleteSensor (sensorId) { clearCache(); return $http.delete(`/sensors/${sensorId}/`); }, deleteValue (sensorId, values) { clearCache(); return $http.delete(`/sensors/${sensorId}/values/${values}/`); }, addValue (sensorId, value) { clearCache(); return $http.post(`/sensors/${sensorId}/value/`, {value}); }, forceReadValue (sensorId) { clearCache(); return $http.post(`/sensors/${sensorId}/force/`, {}); }, edit (sensor) { clearCache(); return $http.put(`/sensors/${sensor.sensorId}/`, sensor); }, add (sensor) { clearCache(); return $http.post('/sensors/', sensor); }, parameters (sensorType) { return $http.get(`/sensors/${sensorType}/parameters/`, {cache: Cache}); } }; });
'use strict'; var expect = require('chai').expect; var spawns = require('../'); var node_path = require('path'); var fs = require('fs'); var mix = require('mix2'); describe("spawns", function() { it("normal", function(done) { spawns(['ls', 'ls'], { stdio: 'inherit' }).on('close', function(code) { expect(code).to.equal(0); done(); }); }); it("exit event", function(done){ spawns(['ls', 'ls'], { stdio: 'inherit' }).on('exit', function(code) { expect(code).to.equal(0); done(); }); }); }); describe("cross-platform compatibility", function(){ it("spawn a custom command", function(done){ var path = node_path.join(__dirname, './fixtures/command.js'); prepare_cmd(path, function (err, file, dir) { expect(err).to.equal(null); var env = {}; mix(env, process.env); env._CWD = dir; spawns([ file + ' --arg "a b c d"' ], { env: env }).on('close', function (code) { expect(code).not.to.equal(0); var file = node_path.join(dir, 'arg.tmp') var content = fs.readFileSync(file); expect(content.toString()).to.equal('a b c d'); done(); }); }); }); it("spawn with arguments", function(done){ var path = node_path.join(__dirname, './fixtures/command.js'); prepare_cmd(path, function (err, file, dir) { expect(err).to.equal(null); var env = {}; mix(env, process.env); env._CWD = dir; spawns(file, ['--arg', 'a b c d'], { stdio: 'inherit', env: env }) .on('close', function (code) { expect(code).not.to.equal(0); var file = node_path.join(dir, 'arg.tmp'); var content = fs.readFileSync(file); expect(content.toString()).to.equal('a b c d'); done(); }); }); }); }); var shim = require('cmd-shim'); var tmp = require('tmp-sync'); var is_windows = process.platform === 'win32'; function prepare_cmd (path, callback) { var dir = tmp.in(__dirname); var to = node_path.join(dir, 'command'); if (is_windows) { return shim(path, to, function (err) { if (err) { return callback(err); } callback(null, to); }); } fs.symlinkSync(path, to); // var content = fs.readFileSync(path).toString(); // console.log(content, to) // fs.writeFileSync(to, content); // fs.chmodSync(to, 755); callback(null, to, dir); };
'use strict'; // jshint node:true module.exports = function(grunt) { var files = [ 'src/load-dependency.js', 'src/ui-sortable-loader.js' ]; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), 'uglify': { 'options': { 'banner': '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, 'build': { 'src': files, 'dest': 'build/ui-sortable-loader.min.js' } }, 'concat': { 'options': { separator: '\n', }, 'build': { src: files, dest: 'build/ui-sortable-loader.js', } }, 'gh-pages': { 'options': { 'base': 'build' }, 'deploy': { 'src': ['index.html', 'ui-sortable-loader.js', 'ui-sortable-loader.min.js'] } }, 'jshint': { 'options': { 'jshintrc': true, 'reporter': require('jshint-stylish') }, 'src': { 'files': { 'src': ['*.js', '!*.min.js'] } } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-gh-pages'); grunt.registerTask('default', ['jshint:src', 'concat:build', 'uglify:build']); grunt.registerTask('deploy', ['default', 'gh-pages:deploy']); };
$(function() { $('li#three').removeClass('hot'); $('li.hot').addClass('favorite'); $('ul').attr('id', 'group'); });
(function() { window.Locomotive = { mounted_on: window.Locomotive.mounted_on, Views: { Sessions: {}, Registrations: {}, Passwords: {}, CustomFields: {} }, Flags: {} }; }).call(this); (function() { var View; View = Backbone.View; Backbone.View = View.extend({ constructor: function(options) { this.options = options || {}; return View.apply(this, arguments); }, replace: function($new_el) { var _view; $(this.el).hide(); $new_el.insertAfter($(this.el)); _view = new this.constructor({ el: $new_el }); _view.render(); this.remove(); return _view; } }); }).call(this); (function() { String.prototype.trim = function() { return this.replace(/^\s+/g, '').replace(/\s+$/g, ''); } String.prototype.repeat = function(num) { for (var i = 0, buf = ""; i < num; i++) buf += this; return buf; } String.prototype.truncate = function(length) { if (this.length > length) { return this.slice(0, length - 3) + '...'; } else { return this; } } String.prototype.slugify = function(sep) { if (typeof sep == 'undefined') sep = '_'; var alphaNumRegexp = new RegExp('[^\\w\\' + sep + ']', 'g'); var avoidDuplicateRegexp = new RegExp('[\\' + sep + ']{2,}', 'g'); return this.replace(/\s/g, sep).replace(alphaNumRegexp, '').replace(avoidDuplicateRegexp, sep).toLowerCase(); } window.addParameterToURL = function(key, value, context) { // code from http://stackoverflow.com/questions/486896/adding-a-parameter-to-the-url-with-javascript if (typeof context == 'undefined') context = document; key = encodeURIComponent(key); value = encodeURIComponent(value); var kvp = context.location.search.substr(1).split('&'); var i = kvp.length; var x; while(i--) { x = kvp[i].split('='); if (x[0] == key) { x[1] = value; kvp[i] = x.join('='); break; } } if (i < 0) { kvp[kvp.length] = [key,value].join('='); } //this will reload the page, it's likely better to store this until finished context.location.search = kvp.join('&'); } window.addJavascript = function(doc, src, options) { var script = doc.createElement('script'); script.type = 'text/javascript'; script.src = src; if (options && options.onload) { script.onload = options.onload; delete(options.onload); } for (var key in options) { script.setAttribute(key, options[key]); } doc.body.appendChild(script); } window.addStylesheet = function(doc, src) { var stylesheet = doc.createElement('link'); stylesheet.style = 'text/css'; stylesheet.href = src; stylesheet.media = 'screen'; stylesheet.rel = 'stylesheet'; doc.head.appendChild(stylesheet); } $.ui.dialog.prototype.overlayEl = function() { return this.overlay.$el; } window.absolute_url = function(url) { if (url.indexOf('http') == 0) return url; http = location.protocol; slashes = http.concat("//"); return slashes.concat(window.location.host).concat(url); } })(); (function() { (function() { window.remote_file_to_base64 = function(url, callback) { var xhr; xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'blob'; xhr.onload = function(event) { var blob, reader; if (this.status === 200) { blob = this.response; reader = new window.FileReader(); reader.readAsDataURL(blob); return reader.onloadend = function() { return callback(reader.result); }; } else { return callback(null); } }; xhr.onerror = function(event) { return callback(null); }; return xhr.send(); }; return window.resize_image = function(image, format, callback) { var data, xhr; if (format == null) { callback(image); return; } data = new FormData(); data.append('image', image); data.append('format', format); xhr = new XMLHttpRequest(); xhr.open('POST', '/locomotive/_image_thumbnail', true); xhr.onload = function(event) { if (this.status === 200) { return callback(this.response); } else { return callback(image); } }; xhr.onerror = function(event) { return callback(image); }; return xhr.send(data); }; })(); }).call(this); (function() { $(function() { jQuery.fn.equalize = function() { var items, max; items = this; max = -1; this.find_max = function() { return $(items).each(function() { var h; h = $(this).height(); return max = Math.max(h, max); }); }; this.apply_max = function() { return $(items).css({ 'min-height': max }); }; this.find_max(); this.apply_max(); return this; }; return $('section.main > *').equalize(); }); }).call(this); (function() { Locomotive.notify = function(message, type) { var icon; icon = type === 'danger' ? 'exclamation-triangle' : type === 'success' ? 'check' : 'exclamation-circle'; return $.notify({ message: message, icon: "fa fa-" + icon }, { type: type, placement: { from: 'bottom', align: 'right' } }); }; }).call(this); (function() { var parent; parent = $('.content').size() > 0 ? '.content' : '.wrapper'; if ($(parent).size() > 0) { NProgress.configure({ showSpinner: false, ease: 'ease', speed: 500, parent: parent }); } }).call(this); (function() { $.rails.safe_confirm = function(question) { return prompt(question.question) === question.answer; }; $.rails.allowAction = function(element) { var answer, callback, message, question; message = element.data('confirm'); question = element.data('safe-confirm'); answer = false; callback = null; if (!message && !question) { return true; } if ($.rails.fire(element, 'confirm')) { if (message) { answer = $.rails.confirm(message); } else if (question) { answer = $.rails.safe_confirm(question); } callback = $.rails.fire(element, 'confirm:complete', [answer]); } return answer && callback; }; $.rails.ajax = function(options) { if (_.isArray(options.data)) { return $.ajax(_.extend(options, { contentType: false })); } else { return $.ajax(options); } }; $(function() { $('body').delegate($.rails.formSubmitSelector, 'ajax:beforeSend', function(event, xhr, settings) { return xhr.setRequestHeader('X-Flash', true); }); $('body').delegate($.rails.formSubmitSelector, 'ajax:complete', function(event, xhr, status) { var message, type; $(this).find('button[type=submit], input[type=submit]').button('reset'); if (message = xhr.getResponseHeader('X-Message')) { type = status === 'success' ? 'success' : 'error'; return Locomotive.notify(decodeURIComponent($.parseJSON(message)), type); } }); $('body').delegate($.rails.formSubmitSelector, 'ajax:aborted:file', function(element) { $.rails.handleRemote($(this)); return false; }); return $('body').delegate($.rails.formSubmitSelector, 'ajax:beforeSend', function(event, xhr, settings) { settings.data = new FormData($(this)[0]); $(this).find('input[type=file]').each(function() { return settings.data.append($(this).attr('name'), this.files[0]); }); return true; }); }); }).call(this); (function() { window.Select2Helpers = (function() { var build_results, default_build_options; default_build_options = function(input) { return { minimumInputLength: 1, quietMillis: 100, formatNoMatches: input.data('no-matches'), formatSearching: input.data('searching'), formatInputTooShort: input.data('too-short'), ajax: { url: input.data('list-url'), dataType: 'json', data: function(params) { return { q: params.term, page: params.page }; }, processResults: function(data, params) { return { results: build_results(data, input.data('label-method'), input.data('group-by')), pagination: { more: data.length === input.data('per-page') } }; } } }; }; build_results = function(raw_data, label_method, group_by) { return _.tap([], (function(_this) { return function(list) { return _.each(raw_data, function(data) { var group, group_name; if ((_this.collection == null) || (_this.collection.get(data._id) == null)) { data.text = data[label_method]; if (group_by != null) { group_name = _.result(data, group_by); group = _.find(list, function(_group) { return _group.text === group_name; }); if (group == null) { group = { text: group_name, children: [] }; list.push(group); } return group.children.push(data); } else { return list.push(data); } } }); }; })(this)); }; return { build: function(input, options) { var _options; options || (options = {}); _options = _.extend(default_build_options(input), options); return input.select2(_options); } }; })(); }).call(this); (function() { (function(wysihtml5) { return wysihtml5.commands.strike = { exec: function(composer, command) { return wysihtml5.commands.formatInline.exec(composer, command, 'STRIKE'); }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, 'STRIKE', null, null); } }; })(wysihtml5); (function(wysihtml5) { var buildBody, buildHeader; buildHeader = function(cols) { var col, html, i, ref; html = '<thead><tr>'; for (col = i = 0, ref = cols; 0 <= ref ? i < ref : i > ref; col = 0 <= ref ? ++i : --i) { html += '<th><br></th>'; } return html + '</tr></thead>'; }; buildBody = function(cols, rows) { var col, html, i, j, ref, ref1, row; html = '<tbody>'; for (row = i = 0, ref = rows; 0 <= ref ? i < ref : i > ref; row = 0 <= ref ? ++i : --i) { html += '<tr>'; for (col = j = 0, ref1 = cols; 0 <= ref1 ? j < ref1 : j > ref1; col = 0 <= ref1 ? ++j : --j) { html += '<td><br></td>'; } html += '</tr>'; } return html += '</tbody>'; }; return wysihtml5.commands.createTable = { exec: function(composer, command, options) { var cols, html, rows; options = _.extend({ cols: 3, rows: 3, class_name: '', head: true }, options); cols = parseInt(options.cols, 10); rows = parseInt(options.rows, 10); html = "<table class='" + options.class_name + "'>"; if (options.head) { html += buildHeader(cols); } html += buildBody(cols, rows); html += '</table>'; return composer.commands.exec('insertHTML', html); }, state: function(composer, command) { return false; } }; })(wysihtml5); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Shared || (base.Shared = {}); Locomotive.Views.Shared.FormView = (function(superClass) { extend(FormView, superClass); function FormView() { return FormView.__super__.constructor.apply(this, arguments); } FormView.prototype.el = '.main'; FormView.prototype.namespace = null; FormView.prototype.events = { 'submit form': 'save', 'ajax:aborted:required': 'show_empty_form_message', 'keyup input, textarea': 'modifying' }; FormView.prototype.render = function() { this.inputs = []; this.display_active_nav(); this.register_unsaved_content(); this.enable_hover(); this.enable_simple_image_inputs(); this.enable_image_inputs(); this.enable_file_inputs(); this.enable_array_inputs(); this.enable_toggle_inputs(); this.enable_datetime_inputs(); this.enable_text_inputs(); this.enable_rte_inputs(); this.enable_markdown_inputs(); this.enable_tags_inputs(); this.enable_document_picker_inputs(); this.enable_select_inputs(); this.enable_color_inputs(); return this; }; FormView.prototype.register_unsaved_content = function() { window.unsaved_content = false; return this.tokens = [ PubSub.subscribe('inputs.text_changed', (function(_this) { return function() { return _this.modifying(); }; })(this)) ]; }; FormView.prototype.display_active_nav = function() { var name, url; url = document.location.toString(); if (url.match('#')) { name = url.split('#')[1]; return this.$(".nav-tabs a[href='#" + name + "']").tab('show'); } }; FormView.prototype.record_active_tab = function() { var tab_name; if ($('form .nav-tabs li.active a').size() > 0) { tab_name = $('form .nav-tabs li.active a').attr('href').replace('#', ''); return this.$('#active_tab').val(tab_name); } }; FormView.prototype.change_state = function() { return this.$('form button[type=submit], form input[type=submit]').button('loading'); }; FormView.prototype.reset_state = function() { return this.$('form button[type=submit], form input[type=submit]').button('reset'); }; FormView.prototype.save = function(event) { window.unsaved_content = false; this.change_state(); return this.record_active_tab(); }; FormView.prototype.show_empty_form_message = function(event) { var message; message = this.$('form').data('blank-required-fields-message'); if (message != null) { Locomotive.notify(message, 'error'); } return this.reset_state(); }; FormView.prototype.enable_hover = function() { return $('.form-group.input').hover(function() { return $(this).addClass('hovered'); }, function() { return $(this).removeClass('hovered'); }); }; FormView.prototype.enable_simple_image_inputs = function() { var self; self = this; return this.$('.input.simple_image').each(function() { var view; view = new Locomotive.Views.Inputs.SimpleImageView({ el: $(this) }); view.render(); return self.inputs.push(view); }); }; FormView.prototype.enable_image_inputs = function() { var self; self = this; return this.$('.input.image').each(function() { var view; view = new Locomotive.Views.Inputs.ImageView({ el: $(this) }); view.render(); return self.inputs.push(view); }); }; FormView.prototype.enable_file_inputs = function() { var self; self = this; return this.$('.input.file').each(function() { var view; view = new Locomotive.Views.Inputs.FileView({ el: $(this) }); view.render(); return self.inputs.push(view); }); }; FormView.prototype.enable_array_inputs = function() { var self; self = this; return this.$('.input.array').each(function() { var view; view = new Locomotive.Views.Inputs.ArrayView({ el: $(this) }); view.render(); return self.inputs.push(view); }); }; FormView.prototype.enable_toggle_inputs = function() { return this.$('.input.toggle input[type=checkbox]').each(function() { var $toggle; $toggle = $(this); $toggle.data('label-text', ($toggle.is(':checked') ? $toggle.data('off-text') : $toggle.data('on-text'))); return $toggle.bootstrapSwitch({ onSwitchChange: function(event, state) { return $toggle.data('bootstrap-switch').labelText((state ? $toggle.data('off-text') : $toggle.data('on-text'))); } }); }); }; FormView.prototype.enable_datetime_inputs = function() { return this.$('.input.date input[type=text], .input.date-time input[type=text]').each(function() { var datetime, format; format = $(this).data('format'); datetime = moment($(this).attr('value'), format); if (!datetime.isValid()) { datetime = null; } return $(this).removeAttr('value').datetimepicker({ locale: window.locale, widgetParent: $(this).parents('.form-wrapper'), format: format, defaultDate: datetime }); }); }; FormView.prototype.enable_text_inputs = function() { var self; self = this; return this.$('.input.text').each(function() { var view; view = new Locomotive.Views.Inputs.TextView({ el: $(this) }); view.render(); return self.inputs.push(view); }); }; FormView.prototype.enable_rte_inputs = function() { var self; self = this; return this.$('.input.rte').each(function() { var view; view = new Locomotive.Views.Inputs.RteView({ el: $(this) }); view.render(); return self.inputs.push(view); }); }; FormView.prototype.enable_markdown_inputs = function() { var self; self = this; return this.$('.input.markdown').each(function() { var view; view = new Locomotive.Views.Inputs.MarkdownView({ el: $(this) }); view.render(); return self.inputs.push(view); }); }; FormView.prototype.enable_color_inputs = function() { return this.$('.input.color .input-group').colorpicker({ container: false, align: 'right' }); }; FormView.prototype.enable_tags_inputs = function() { return this.$('.input.tags input[type=text]').tagsinput(); }; FormView.prototype.enable_select_inputs = function() { return this.$('.input.select select:not(.disable-select2)').select2(); }; FormView.prototype.enable_document_picker_inputs = function() { var self; self = this; return this.$('.input.document_picker').each(function() { var view; view = new Locomotive.Views.Inputs.DocumentPickerView({ el: $(this) }); view.render(); return self.inputs.push(view); }); }; FormView.prototype.modifying = function(event) { return window.unsaved_content = true; }; FormView.prototype.remove = function() { _.each(this.inputs, function(view) { return view.remove(); }); _.each(this.tokens, function(token) { return PubSub.unsubscribe(token); }); this.$('.input.select select:not(.disable-select2)').select2('destroy'); this.$('.input.tags input[type=text]').tagsinput('destroy'); return this.$('.input.color .input-group').colorpicker('destroy'); }; FormView.prototype._stop_event = function(event) { return event.stopPropagation() & event.preventDefault(); }; return FormView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Accounts || (base.Accounts = {}); Locomotive.Views.Accounts.NewView = (function(superClass) { extend(NewView, superClass); function NewView() { return NewView.__super__.constructor.apply(this, arguments); } NewView.prototype.el = '.main'; return NewView; })(Locomotive.Views.Shared.FormView); }).call(this); (function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Locomotive.Views.SimpleView = (function(superClass) { extend(SimpleView, superClass); function SimpleView() { return SimpleView.__super__.constructor.apply(this, arguments); } SimpleView.prototype.el = 'body'; SimpleView.prototype.render = function() { this.render_flash_messages(this.options.flash); if (this.options.view != null) { this.view = new this.options.view(this.options.view_data || {}); this.view.render(); } return this; }; SimpleView.prototype.render_flash_messages = function(messages) { return _.each(messages, function(couple) { return Locomotive.notify(couple[1], couple[0]); }); }; return SimpleView; })(Backbone.View); }).call(this); (function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Locomotive.Views.ApplicationView = (function(superClass) { extend(ApplicationView, superClass); function ApplicationView() { return ApplicationView.__super__.constructor.apply(this, arguments); } ApplicationView.prototype.el = 'body'; ApplicationView.prototype.events = { 'click .navigation-app .navigation-trigger': 'toggle_sidebar' }; ApplicationView.prototype.initialize = function() { _.bindAll(this, 'toggle_sidebar'); this.header_view = new Locomotive.Views.Shared.HeaderView(); this.sidebar_view = new Locomotive.Views.Shared.SidebarView(); this.drawer_view = new Locomotive.Views.Shared.DrawerView(); this.tokens = [PubSub.subscribe('sidebar.close', this.toggle_sidebar)]; return window.unsaved_content = false; }; ApplicationView.prototype.render = function() { ApplicationView.__super__.render.apply(this, arguments); this.sidebar_view.render(); this.drawer_view.render(); this.set_max_height(); this.automatic_max_height(); return this.register_warning_if_unsaved_content(); }; ApplicationView.prototype.toggle_sidebar = function(event) { return this.sidebar_view.toggle_sidebar(); }; ApplicationView.prototype.automatic_max_height = function() { return $(window).on('resize', (function(_this) { return function() { var height; height = _this.set_max_height(); return PubSub.publish('application_view.resize', { height: height }); }; })(this)); }; ApplicationView.prototype.set_max_height = function() { var height, max_height; max_height = $(window).height(); height = max_height - this.header_view.height(); this.$('> .wrapper').height(height); return height; }; ApplicationView.prototype.register_warning_if_unsaved_content = function() { return $(window).bind('beforeunload', function() { if (window.unsaved_content) { return $('meta[name=unsaved-content-warning]').attr('content'); } }); }; ApplicationView.prototype.remove = function() { ApplicationView.__super__.remove.call(this); return _.each(this.tokens, function(token) { return PubSub.unsubscribe(token); }); }; return ApplicationView; })(Locomotive.Views.SimpleView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).ContentAssets || (base.ContentAssets = {}); Locomotive.Views.ContentAssets.DropzoneView = (function(superClass) { extend(DropzoneView, superClass); function DropzoneView() { return DropzoneView.__super__.constructor.apply(this, arguments); } DropzoneView.prototype.events = { 'click a.upload': 'open_file_browser', 'dragover': 'hover', 'dragleave': 'unhover', 'dragenter': '_stop_event', 'drop': 'drop_files', 'change input[type=file]': 'drop_files' }; DropzoneView.prototype.render = function() { return DropzoneView.__super__.render.apply(this, arguments); }; DropzoneView.prototype.hover = function(event) { this._stop_event(event); return $(this.el).addClass('hovered'); }; DropzoneView.prototype.unhover = function(event) { this._stop_event(event); return $(this.el).removeClass('hovered'); }; DropzoneView.prototype.show_progress = function(value) { return this.$('.progress').removeClass('hide').find('> .progress-bar').width(value + "%"); }; DropzoneView.prototype.reset_progress = function() { return setTimeout((function(_this) { return function() { return _this.$('.progress').addClass('hide').find('> .progress-bar').width('0%'); }; })(this), 400); }; DropzoneView.prototype.open_file_browser = function(event) { this._stop_event(event); return this.$('form input[type=file]').trigger('click'); }; DropzoneView.prototype.drop_files = function(event) { var form_data; this._stop_event(event) & this.unhover(event); form_data = new FormData(); _.each(event.target.files || event.originalEvent.dataTransfer.files, function(file, i) { return form_data.append("content_assets[][source]", file); }); return this.upload_files(form_data); }; DropzoneView.prototype.upload_files = function(data) { return $.ajax(this._ajax_options(data)).always((function(_this) { return function() { return _this.reset_progress(); }; })(this)).fail((function(_this) { return function() { return _this.$('.instructions').effect('shake'); }; })(this)).done((function(_this) { return function() { console.log('uploaded'); return _this._refresh(); }; })(this)); }; DropzoneView.prototype._refresh = function() { var $link; $link = this.$('a.refresh'); if ($link.data('remote')) { return $link.trigger('click'); } else { return $link[0].click(); } }; DropzoneView.prototype._ajax_options = function(data) { return { url: $(this.el).data('url'), type: 'POST', xhr: (function(_this) { return function() { return _this._build_xhr(); }; })(this), data: data, dataType: 'json', cache: false, contentType: false, processData: false }; }; DropzoneView.prototype._build_xhr = function() { return _.tap($.ajaxSettings.xhr(), (function(_this) { return function(xhr) { if (xhr.upload) { return xhr.upload.addEventListener('progress', function(progress) { return _this.show_progress(~~((progress.loaded / progress.total) * 100)); }); } }; })(this)); }; DropzoneView.prototype._stop_event = function(event) { event.stopPropagation() & event.preventDefault(); return true; }; return DropzoneView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).ContentAssets || (base.ContentAssets = {}); Locomotive.Views.ContentAssets.EditImageView = (function(superClass) { extend(EditImageView, superClass); function EditImageView() { return EditImageView.__super__.constructor.apply(this, arguments); } EditImageView.prototype.events = { 'click .apply-btn': 'apply', 'click .resize-btn': 'toggle_resize_modal', 'click .crop-btn': 'enable_crop' }; EditImageView.prototype.initialize = function() { _.bindAll(this, 'change_size', 'apply_resizing', 'cancel_resizing', 'update_cropper_label'); return EditImageView.__super__.initialize.apply(this, arguments); }; EditImageView.prototype.render = function() { this.filename = this.$('.image-container').data('filename'); this.width = parseInt(this.$('.image-container').data('width')); this.height = parseInt(this.$('.image-container').data('height')); this.ratio = this.width / this.height; this.create_cropper(); return this.create_resize_popover(); }; EditImageView.prototype.create_cropper = function() { this.$cropper = this.$('.image-container > img'); this.cropper_enabled = false; this.set_cropper_height(); return this.$cropper.cropper({ autoCrop: false, done: this.update_cropper_label }); }; EditImageView.prototype.create_resize_popover = function() { var container; this.$link = this.$('.resize-btn'); this.$content = this.$('.resize-form').show(); this.$content.find('input').on('keyup', this.change_size); this.$content.find('.apply-resizing-btn').on('click', this.apply_resizing); this.$content.find('.cancel-resizing-btn').on('click', this.cancel_resizing); container = $('.drawer').size() > 0 ? '.drawer' : '.main'; this.$link.popover({ container: container, placement: 'left', content: this.$content, html: true, template: '<div class="popover" role="tooltip"><div class="arrow"></div><form><div class="popover-content"></div></form></div>' }); return this.$link.data('bs.popover').setContent(); }; EditImageView.prototype.enable_crop = function(event) { this.cropper_enabled = true; this.$cropper.cropper('clear'); return this.$cropper.cropper('setDragMode', 'crop'); }; EditImageView.prototype.toggle_resize_modal = function(event) { var state; state = this.resize_modal_opened ? 'hide' : 'show'; this.$link.popover(state); return this.resize_modal_opened = !this.resize_modal_opened; }; EditImageView.prototype.change_size = function(event) { var $input, _value, value; $input = $(event.target); value = parseInt($input.val().replace(/\D+/, '')); if (_.isNaN(value)) { return; } $input.val(value); if ($input.attr('name') === 'image_resize_form[width]') { _value = Math.round(value / this.ratio); return this._resize_input_el('height').val(_value); } else { _value = Math.round(value * this.ratio); return this._resize_input_el('width').val(_value); } }; EditImageView.prototype.apply_resizing = function(event) { var $btn, height, width; event.stopPropagation() & event.preventDefault(); width = parseInt(this._resize_input_el('width').val()); height = parseInt(this._resize_input_el('height').val()); if (_.isNaN(width) || _.isNaN(height)) { return; } $btn = $(event.target).button('loading'); return window.resizeImageStep(this.$cropper[0], width, height).then((function(_this) { return function(image) { _this.width = width; _this.height = height; _this.cropper_enabled = true; _this.$cropper.cropper('replace', image.src); _this.set_cropper_height(); $btn.button('reset'); return _this.toggle_resize_modal(); }; })(this)); }; EditImageView.prototype.cancel_resizing = function(event) { event.stopPropagation() & event.preventDefault(); return this.toggle_resize_modal(); }; EditImageView.prototype.apply = function(event) { var $link, blob, form_data, image_url; event.stopPropagation() & event.preventDefault(); if (!this.cropper_enabled) { return; } $link = $(event.target).closest('.apply-btn'); image_url = this.$cropper.cropper('getDataURL') || this.$cropper.attr('src'); blob = window.dataURLtoBlob(image_url); form_data = new FormData(); form_data.append('xhr', true); form_data.append('content_asset[source]', blob, this.filename); return $.ajax({ url: $link.data('url'), type: 'POST', data: form_data, processData: false, contentType: false, success: (function(_this) { return function(data) { if (_this.options.on_apply_callback != null) { _this.options.on_apply_callback(data); } return _this.options.drawer.close(); }; })(this) }); }; EditImageView.prototype.set_cropper_height = function() { var container_height; container_height = this.$('.edit-assets-container').height(); if (this.height < 150) { return this.$('.image-container').css('max-height', this.height * 2); } else if (this.height < container_height) { return this.$('.image-container').css('max-height', this.height); } else { return this.$('.image-container').css('max-height', 'inherit'); } }; EditImageView.prototype.update_cropper_label = function(data) { var $dragger, $label, height, width; $dragger = this.$('.cropper-dragger'); width = Math.round(data.width); height = Math.round(data.height); $label = $dragger.find('> .cropper-label'); if ($label.size() === 0) { $label = $dragger.append('<span class="cropper-label"><span>').find('> .cropper-label'); } return $label.html(width + " x " + height); }; EditImageView.prototype._resize_input_el = function(property) { var name; name = "image_resize_form[" + property + "]"; return this.$content.find("input[name=\"" + name + "\"]"); }; EditImageView.prototype.remove = function() { console.log('[EditView] remove'); this.$cropper.cropper('destroy'); this.$link.popover('destroy'); return EditImageView.__super__.remove.apply(this, arguments); }; return EditImageView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).ContentAssets || (base.ContentAssets = {}); Locomotive.Views.ContentAssets.IndexView = (function(superClass) { extend(IndexView, superClass); function IndexView() { return IndexView.__super__.constructor.apply(this, arguments); } IndexView.prototype.el = '.main'; IndexView.prototype.events = { 'click .header-row a.upload': 'open_file_browser', 'click a.edit': 'open_edit_drawer' }; IndexView.prototype.initialize = function() { _.bindAll(this, 'set_sidebar_max_height'); this.refresh_url = this.$('.content-assets').data('refresh-url'); return this.dropzone = new Locomotive.Views.ContentAssets.DropzoneView({ el: this.$('.dropzone') }); }; IndexView.prototype.render = function() { this.dropzone.render(); this.automatic_sidebar_max_height(); this.set_sidebar_max_height(); return IndexView.__super__.render.apply(this, arguments); }; IndexView.prototype.open_edit_drawer = function(event) { var $link; event.stopPropagation() & event.preventDefault(); $link = $(event.target); return window.application_view.drawer_view.open($link.attr('href'), Locomotive.Views.ContentAssets.EditImageView, { on_apply_callback: (function(_this) { return function(data) { return window.location.href = _this.refresh_url; }; })(this) }); }; IndexView.prototype.hide_from_drawer = function(stack_size) { if (this.options.parent_view && stack_size === 0) { return this.options.parent_view.opened.picker = false; } }; IndexView.prototype.open_file_browser = function(event) { return this.dropzone.open_file_browser(event); }; IndexView.prototype.automatic_sidebar_max_height = function() { return $(window).on('resize', this.set_sidebar_max_height); }; IndexView.prototype.set_sidebar_max_height = function() { return setTimeout(((function(_this) { return function() { var main_height, max_height; main_height = $(_this.el).height(); max_height = _this.$('.content-assets').height(); if (main_height > max_height) { max_height = main_height; } console.log(main_height); return $(_this.dropzone.el).height(max_height); }; })(this)), 20); }; IndexView.prototype.remove = function() { $(window).off('resize', this.set_sidebar_max_height); return this.dropzone.remove(); }; return IndexView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).ContentAssets || (base.ContentAssets = {}); Locomotive.Views.ContentAssets.PickerView = (function(superClass) { extend(PickerView, superClass); function PickerView() { return PickerView.__super__.constructor.apply(this, arguments); } PickerView.prototype.events = { 'click a.select': 'select', 'click a.edit': 'open_edit_drawer' }; PickerView.prototype.ajaxified_elements = ['.nav-tabs a', '.pagination a', '.search-bar form', '.asset a.remove', 'a.refresh']; PickerView.prototype.render = function() { console.log('[PickerView] rendering'); this.ajaxify(); this.enable_dropzone(); return PickerView.__super__.render.apply(this, arguments); }; PickerView.prototype.ajaxify = function() { var i, len, ref, results, selector; ref = this.ajaxified_elements; results = []; for (i = 0, len = ref.length; i < len; i++) { selector = ref[i]; results.push($(this.el).on('ajax:success', selector, (function(_this) { return function(event, data, status, xhr) { return _this.$('.updatable').html($(data).find('.updatable').html()); }; })(this))); } return results; }; PickerView.prototype.unajaxify = function() { var i, len, ref, results, selector; ref = this.ajaxified_elements; results = []; for (i = 0, len = ref.length; i < len; i++) { selector = ref[i]; results.push($(this.el).off('ajax:success', selector)); } return results; }; PickerView.prototype.select = function(event) { var $link; console.log('[PickerView] select'); event.stopPropagation() & event.preventDefault(); $link = $(event.target); return PubSub.publish('file_picker.select', { parent_view: this.options.parent_view, image: $link.data('image'), title: $link.attr('title'), url: $link.attr('href'), filename: $link.attr('href').split(/[\\\/]/).pop() }); }; PickerView.prototype.open_edit_drawer = function(event) { var $link; console.log('[PickerView] open_edit_drawer'); event.stopPropagation() & event.preventDefault(); $link = $(event.target); return window.application_view.drawer_view.open($link.attr('href'), Locomotive.Views.ContentAssets.EditImageView); }; PickerView.prototype.enable_dropzone = function() { return this.dropzone = new Locomotive.Views.ContentAssets.DropzoneView({ el: this.$('.dropzone') }).render(); }; PickerView.prototype.hide_from_drawer = function(stack_size) { console.log('[PickerView] hide_from_drawer'); if (this.options.parent_view && this.options.parent_view.hide_from_picker) { return this.options.parent_view.hide_from_picker(stack_size); } }; PickerView.prototype.remove = function() { console.log('[PickerView] remove'); this.unajaxify(); this.dropzone.remove(); return PickerView.__super__.remove.apply(this, arguments); }; return PickerView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).ContentEntries || (base.ContentEntries = {}); Locomotive.Views.ContentEntries.EditView = (function(superClass) { extend(EditView, superClass); function EditView() { return EditView.__super__.constructor.apply(this, arguments); } return EditView; })(Locomotive.Views.Shared.FormView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).ContentEntries || (base.ContentEntries = {}); Locomotive.Views.ContentEntries.IndexView = (function(superClass) { extend(IndexView, superClass); function IndexView() { return IndexView.__super__.constructor.apply(this, arguments); } IndexView.prototype.el = '.main'; IndexView.prototype.initialize = function() { return this.list_view = new Locomotive.Views.Shared.ListView({ el: this.$('.big-list') }); }; IndexView.prototype.render = function() { return this.list_view.render(); }; IndexView.prototype.remove = function() { this.list_view.remove(); return IndexView.__super__.remove.call(this); }; return IndexView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).ContentEntries || (base.ContentEntries = {}); Locomotive.Views.ContentEntries.NewView = (function(superClass) { extend(NewView, superClass); function NewView() { return NewView.__super__.constructor.apply(this, arguments); } return NewView; })(Locomotive.Views.Shared.FormView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).CurrentSite || (base.CurrentSite = {}); Locomotive.Views.CurrentSite.EditView = (function(superClass) { extend(EditView, superClass); function EditView() { return EditView.__super__.constructor.apply(this, arguments); } EditView.prototype.el = '.main'; EditView.prototype.initialize = function() { this.attach_events_on_private_access_attribute(); return this.display_locale_picker_only_for_seo(); }; EditView.prototype.attach_events_on_private_access_attribute = function() { return this.$('#site_private_access').on('switchChange.bootstrapSwitch', function(event, state) { var $inputs; $inputs = $('.locomotive_site_password'); return $inputs.toggleClass('hide'); }); }; EditView.prototype.display_locale_picker_only_for_seo = function() { var $picker; $picker = this.$('.locale-picker-btn-group').css({ visibility: 'hidden' }); return this.$('a[data-toggle="tab"]').on('shown.bs.tab', function(event) { if ($(event.target).attr('href') === '#seo') { return $picker.css({ visibility: '' }); } else { return $picker.css({ visibility: 'hidden' }); } }); }; return EditView; })(Locomotive.Views.Shared.FormView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).CurrentSiteMetafields || (base.CurrentSiteMetafields = {}); Locomotive.Views.CurrentSiteMetafields.IndexView = (function(superClass) { extend(IndexView, superClass); function IndexView() { return IndexView.__super__.constructor.apply(this, arguments); } IndexView.prototype.el = '.main'; return IndexView; })(Locomotive.Views.Shared.FormView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views.CustomFields).SelectOptions || (base.SelectOptions = {}); Locomotive.Views.CustomFields.SelectOptions.EditView = (function(superClass) { extend(EditView, superClass); function EditView() { return EditView.__super__.constructor.apply(this, arguments); } EditView.prototype.el = '.main'; EditView.prototype.events = { 'click .buttons .edit': 'start_inline_editing', 'click .editable .apply': 'apply_inline_editing', 'click .editable .cancel': 'cancel_inline_editing' }; EditView.prototype.start_inline_editing = function(event) { var $button, $cancel_button, $input, $label, $row; this._stop_event(event); $row = $(event.target).parents('.inner-row'); $label = $row.find('.editable > span').addClass('hide'); $input = $label.next('input').removeClass('hide'); $button = $input.next('.btn').removeClass('hide'); $cancel_button = $button.next('.btn').removeClass('hide'); return $input.data('previous', $input.val()); }; EditView.prototype.apply_inline_editing = function(event) { var $button, $cancel_button, $input, $label; this._stop_event(event); $button = $(event.target).closest('.btn').addClass('hide'); $cancel_button = $button.next('.btn').addClass('hide'); $input = $button.prev('input').addClass('hide'); return $label = $input.prev('span').html($input.val()).removeClass('hide'); }; EditView.prototype.cancel_inline_editing = function(event) { var $button, $cancel_button, $input, $label; this._stop_event(event); $cancel_button = $(event.target).closest('.btn').addClass('hide'); $button = $cancel_button.prev('.btn').addClass('hide'); $input = $button.prev('input').addClass('hide'); $input.val($input.data('previous')); return $label = $input.prev('span').html($input.val()).removeClass('hide'); }; EditView.prototype.mark_as_destroyed = function(event) { var $destroy_input; $destroy_input = $(event.target).parents('.item').find('.mark-as-destroyed'); if ($destroy_input.size() > 0) { return $destroy_input.val('1'); } }; return EditView; })(Locomotive.Views.Shared.FormView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Dashboard || (base.Dashboard = {}); Locomotive.Views.Dashboard.ShowView = (function(superClass) { extend(ShowView, superClass); function ShowView() { return ShowView.__super__.constructor.apply(this, arguments); } ShowView.prototype.el = '.main'; ShowView.prototype.infinite_activity_button = 'a[data-behavior~=load-more]'; ShowView.prototype.events = { 'ajax:beforeSend a[data-behavior~=load-more]': 'loading_activity_feed', 'ajax:success a[data-behavior~=load-more]': 'refresh_activity_feed' }; ShowView.prototype.render = function() { ShowView.__super__.render.apply(this, arguments); return this.$('.assets img').error(function() { return $(this).parent().html($(this).attr('alt')); }); }; ShowView.prototype.loading_activity_feed = function(event) { return $(event.target).button('loading'); }; ShowView.prototype.refresh_activity_feed = function(event, data, status, xhr) { var $btn, $last, $new_btn, $response; $btn = $(event.target).button('reset'); $last = this.$('.activity-feed > li:last-child'); $response = $(data); $response.find('.activity-feed > li').appendTo(this.$('.activity-feed')); if (($new_btn = $response.find(this.infinite_activity_button)).size() > 0) { $btn.replaceWith($new_btn); } else { this.$(this.infinite_activity_button).hide(); } return $(this.el).parent().animate({ scrollTop: $last.offset().top + 'px' }, 2000); }; return ShowView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).DevelopersDocumentation || (base.DevelopersDocumentation = {}); Locomotive.Views.DevelopersDocumentation.ShowView = (function(superClass) { extend(ShowView, superClass); function ShowView() { return ShowView.__super__.constructor.apply(this, arguments); } ShowView.prototype.el = '.main'; ShowView.prototype.render = function() { ShowView.__super__.render.call(this); return hljs.initHighlightingOnLoad(); }; return ShowView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).EditableElements || (base.EditableElements = {}); Locomotive.Views.EditableElements.EditView = (function(superClass) { extend(EditView, superClass); function EditView() { return EditView.__super__.constructor.apply(this, arguments); } EditView.prototype.el = '.content-main > .actionbar .content'; EditView.prototype.events = _.extend({}, Locomotive.Views.Shared.FormView.prototype.events, { 'click .form-group.rte label': 'select_editable_text', 'click .form-group.text label': 'select_editable_text' }); EditView.prototype.initialize = function() { _.bindAll(this, 'highlight_form_group'); return this.tokens = [PubSub.subscribe('editable_elements.highlighted_text', this.highlight_form_group)]; }; EditView.prototype.render = function() { EditView.__super__.render.apply(this, arguments); $('form.edit_page').on('ajax:success', (function(_this) { return function(event, data, status, xhr) { if (_this.need_reload != null) { return window.location.reload(); } else { return _this.refresh_inputs($(data)); } }; })(this)); $('.info-row select[name=block]').select2().on('change', (function(_this) { return function(event) { PubSub.publish('editable_elements.block_selected', { name: $(event.target).val() }); return _this.filter_elements_by($(event.target).val()); }; })(this)); return $('.editable-elements .form-group.input.select select').select2().on('change', (function(_this) { return function(event) { return _this.need_reload = true; }; })(this)); }; EditView.prototype.select_editable_text = function(event) { var element_id; element_id = $(event.target).parents('.form-group').attr('id').replace('editable-text-', ''); return PubSub.publish('editable_elements.form_group_selected', { element_id: element_id }); }; EditView.prototype.highlight_form_group = function(msg, data) { var $form_group, $parent, highlight_effect, offset; $form_group = $(this.el).find("#editable-text-" + data.element_id); if ($form_group.size() === 0) { return false; } this.filter_elements_by(''); highlight_effect = (function(_this) { return function() { return $form_group.clearQueue().queue(function(next) { $(this).addClass('highlighted'); return next(); }).delay(200).queue(function(next) { $(this).removeClass('highlighted').find('input[type=text],textarea').trigger('highlight'); return next(); }); }; })(this); $parent = this.$('.scrollable'); offset = $form_group.position().top; if (offset === 0) { return $parent.animate({ scrollTop: 0 }, 500, 'swing', highlight_effect); } else if (offset < 0 || offset > $parent.height()) { if (offset < 0) { offset = $parent.scrollTop() + offset; } return $parent.animate({ scrollTop: offset }, 500, 'swing', highlight_effect); } else { return highlight_effect(); } }; EditView.prototype.refresh_inputs = function($html) { return this.inputs = _.map(this.inputs, (function(_this) { return function(view) { var $new_el, dom_id; if (view.need_refresh == null) { return view; } dom_id = $(view.el).attr('id'); $new_el = $html.find("#" + dom_id); view.replace($new_el); return view; }; })(this)); }; EditView.prototype.filter_elements_by = function(block) { return this.$('.editable-elements .form-group.input').each(function() { var $el; $el = $(this); if (block === '' || (block === '_unknown' && $el.data('block') === '') || $el.data('block') === block) { return $el.parent().show(); } else { return $el.parent().hide(); } }); }; EditView.prototype.remove = function() { EditView.__super__.remove.apply(this, arguments); return _.each(this.tokens, function(token) { return PubSub.unsubscribe(token); }); }; return EditView; })(Locomotive.Views.Shared.FormView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).EditableElements || (base.EditableElements = {}); Locomotive.Views.EditableElements.IframeView = (function(superClass) { extend(IframeView, superClass); function IframeView() { return IframeView.__super__.constructor.apply(this, arguments); } IframeView.prototype.el = '.preview iframe'; IframeView.prototype.startup = true; IframeView.prototype.initialize = function() { this.window = $(this.el)[0].contentWindow; return $(this.el).load((function(_this) { return function(event) { return _this.on_load(event); }; })(this)); }; IframeView.prototype.reload = function() { return $(this.el).attr('src', this.preview_url); }; IframeView.prototype.on_load = function(event) { var path; this.register_beforeunload(); if ((path = this.edit_view_path()) != null) { this.preview_url = this.window.document.location.href; if (!this.startup) { History.replaceState({ live_editing: true, url: this.preview_url }, '', path); this.options.parent_view.replace_edit_view(path); } else { this.startup = false; } } return this.build_and_render_page_view(); }; IframeView.prototype.edit_view_path = function() { var $document, e, error; try { $document = $(this.window.document); return $document.find('meta[name=locomotive-editable-elements-path]').attr('content'); } catch (error) { e = error; this.reload(); Locomotive.notify($(this.el).data('redirection-error'), 'warning'); return null; } }; IframeView.prototype.build_and_render_page_view = function() { if (this.page_view != null) { this.page_view.remove(); } this.page_view = new Locomotive.Views.EditableElements.PageView({ el: $(this.window.document), parent_view: this, button_labels: { edit: $(this.el).data('edit-label') } }); this.page_view.render(); return window.addStylesheet(this.window.document, $(this.el).data('style-path')); }; IframeView.prototype.register_beforeunload = function() { $(this.window).off('beforeunload', this.warn_if_unsaved_content); return $(this.window).on('beforeunload', this.warn_if_unsaved_content); }; IframeView.prototype.warn_if_unsaved_content = function() { if (window.unsaved_content) { return $('meta[name=unsaved-content-warning]').attr('content'); } }; IframeView.prototype.remove = function() { IframeView.__super__.remove.call(this); if (this.page_view != null) { this.page_view.remove(); } return _.each(this.tokens, function(token) { return PubSub.unsubscribe(token); }); }; return IframeView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).EditableElements || (base.EditableElements = {}); Locomotive.Views.EditableElements.IndexView = (function(superClass) { extend(IndexView, superClass); function IndexView() { return IndexView.__super__.constructor.apply(this, arguments); } IndexView.prototype.el = '.content-main'; IndexView.prototype.events = { 'click .actionbar .actionbar-trigger': 'toggle_preview', 'click .content-overlay': 'close_sidebar' }; IndexView.prototype.initialize = function() { var view_options; _.bindAll(this, 'shrink_preview', 'close_sidebar'); view_options = $('body').hasClass('live-editing') ? {} : { el: '.main' }; this.tokens = [PubSub.subscribe('editable_elements.highlighted_text', this.shrink_preview)]; return this.views = [ new Locomotive.Views.EditableElements.EditView(view_options), new Locomotive.Views.EditableElements.IframeView({ parent_view: this }) ]; }; IndexView.prototype.render = function() { IndexView.__super__.render.call(this); return _.invoke(this.views, 'render'); }; IndexView.prototype.toggle_preview = function(event) { return $(this.el).toggleClass('actionbar-closed'); }; IndexView.prototype.shrink_preview = function(event) { return $(this.el).removeClass('actionbar-closed'); }; IndexView.prototype.close_sidebar = function(event) { return PubSub.publish('sidebar.close'); }; IndexView.prototype.replace_edit_view = function(url) { this.views[0].remove(); return $(this.views[0].el).load(url, (function(_this) { return function() { return (_this.views[0] = new Locomotive.Views.EditableElements.EditView()).render(); }; })(this)); }; IndexView.prototype.remove = function() { IndexView.__super__.remove.call(this); _.each(this.tokens, function(token) { return PubSub.unsubscribe(token); }); return _.invoke(this.views, 'remove'); }; return IndexView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).EditableElements || (base.EditableElements = {}); Locomotive.Views.EditableElements.PageView = (function(superClass) { extend(PageView, superClass); function PageView() { return PageView.__super__.constructor.apply(this, arguments); } PageView.prototype.initialize = function() { _.bindAll(this, 'refresh_all', 'refresh_text', 'refresh_image', 'refresh_image_on_remove', 'scroll_to_block', 'scroll_to_element'); this.tokens = [PubSub.subscribe('editable_elements.block_selected', this.scroll_to_block), PubSub.subscribe('editable_elements.form_group_selected', this.scroll_to_element), PubSub.subscribe('inputs.text_changed', this.refresh_text, PubSub.subscribe('inputs.image_changed', this.refresh_image, PubSub.subscribe('inputs.image_removed', this.refresh_image_on_remove, PubSub.subscribe('pages.sorted', this.refresh_all))))]; this.mounted_on = this.$('meta[name=locomotive-mounted-on]').attr('content'); return this.views = [ new Locomotive.Views.EditableElements.TextHighLighterView({ el: this.$('body'), button_labels: this.options.button_labels }) ]; }; PageView.prototype.render = function() { return _.invoke(this.views, 'render'); }; PageView.prototype.scroll_to_block = function(msg, data) { return this._scroll_to(this.$("span.locomotive-block-anchor[data-element-id=\"" + data.name + "\"]")); }; PageView.prototype.scroll_to_element = function(msg, data) { return this._scroll_to(this.$("span.locomotive-editable-text[data-element-id=\"" + data.element_id + "\"]")); }; PageView.prototype._scroll_to = function(element) { if (element.size() === 0) { return false; } return this.$('body').animate({ scrollTop: element.offset().top }, 500); }; PageView.prototype.each_elements = function(view, callback) { var $form_view, element_id; $form_view = $(view.el).parent(); element_id = $form_view.find('input[name*="[id]"]').val(); return callback(this.$("*[data-element-id=" + element_id + "]"), element_id); }; PageView.prototype.refresh_all = function(msg, data) { return this.options.parent_view.reload(); }; PageView.prototype.refresh_text = function(msg, data) { return this.each_elements(data.view, function($elements) { return $elements.each(function() { return $(this).html(data.content); }); }); }; PageView.prototype.refresh_image_on_remove = function(msg, data) { data.url = $(data.view.el).parent().find('input[name*="[default_source_url]"]').val(); return this.refresh_image(msg, data); }; PageView.prototype.refresh_image = function(msg, data) { return this.each_elements(data.view, (function(_this) { return function($elements, element_id) { var current_image_url, image_url, resize_format; if ($elements.size() === 0) { $elements = _this.find_and_reference_images_identified_by_url(data.view.path, element_id); } if ($elements.size() === 0) { return; } resize_format = data.view.$('.row').data('resize-format'); current_image_url = data.view.$('input[name*="[content]"]').val(); image_url = data.url || current_image_url; return window.resize_image(image_url, resize_format, function(resized_image) { return _this.replace_images($elements, resized_image); }); }; })(this)); }; PageView.prototype.replace_images = function(images, new_image_url) { return images.each(function() { if (this.nodeName === 'IMG') { return $(this).attr('src', new_image_url); } else { return $(this).css("background-image", "url('" + new_image_url + "')"); } }); }; PageView.prototype.find_and_reference_images_identified_by_url = function(path, element_id) { return this.$("*[style*='" + path + "'],img[src*='" + path + "']").attr('data-element-id', element_id); }; PageView.prototype.remove = function() { PageView.__super__.remove.call(this); _.each(this.tokens, function(token) { return PubSub.unsubscribe(token); }); return _.invoke(this.views, 'remove'); }; return PageView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).EditableElements || (base.EditableElements = {}); Locomotive.Views.EditableElements.TextHighLighterView = (function(superClass) { extend(TextHighLighterView, superClass); function TextHighLighterView() { return TextHighLighterView.__super__.constructor.apply(this, arguments); } TextHighLighterView.prototype.events = { 'mouseenter .locomotive-editable-text': 'show', 'mouseleave .locomotive-editable-text': 'hide', 'mouseenter .locomotive-highlighter-text': 'clear_hiding_timeout', 'mouseleave .locomotive-highlighter-text': 'hide', 'click #locomotive-highlighter-actions a': 'edit' }; TextHighLighterView.prototype.initialize = function() { return this.build(); }; TextHighLighterView.prototype.render = function() { return this.adjust_height(); }; TextHighLighterView.prototype.edit = function(event) { event.stopPropagation() & event.preventDefault(); this.hide(); return PubSub.publish('editable_elements.highlighted_text', { element_id: this.highlighted_element_id }); }; TextHighLighterView.prototype.build = function() { var actions_html, bar_html; actions_html = '<div id="locomotive-highlighter-actions" class="locomotive-highlighter-text"><a href="#"><i class="locomotive-fa locomotive-fa-pencil"></i>' + this.localize('edit') + '</a></div>'; bar_html = '<div id="locomotive-highlighter-bar" class="locomotive-highlighter-text"></div>'; $(this.el).append(actions_html); $(this.el).append(bar_html); return this.$('.locomotive-highlighter-text').hide(); }; TextHighLighterView.prototype.show = function(event) { var $action, $bar, $highliter, offset; $highliter = this.$('.locomotive-highlighter-text'); offset = this.find_element_offset(event); this.clear_hiding_timeout(); $action = $highliter.first().show(); $action.offset({ 'top': parseInt(offset.top) - 32, 'left': parseInt(offset.left) - 10 }); $action.width(offset.width).show(); $bar = $highliter.last().show(); $bar.offset({ 'top': parseInt(offset.top), 'left': parseInt(offset.left) - 10 }); return $bar.height(offset.height).show(); }; TextHighLighterView.prototype.hide = function(event) { return this.hiding_timeout = setTimeout(((function(_this) { return function() { return _this._hide(); }; })(this)), 600); }; TextHighLighterView.prototype._hide = function() { return this.$('.locomotive-highlighter-text').hide(); }; TextHighLighterView.prototype.clear_hiding_timeout = function() { if (this.hiding_timeout != null) { return clearTimeout(this.hiding_timeout); } }; TextHighLighterView.prototype.adjust_height = function() { return this.$('.locomotive-editable-text').each(function() { var height; height = $(this).height(); if (height === 0) { return height = $(this).css('display', 'block').height(); } }); }; TextHighLighterView.prototype.find_element_offset = function(event) { var $el; $el = $(event.target); if (!$el.hasClass('locomotive-editable-text')) { $el = $el.parents('.locomotive-editable-text'); } this.highlighted_element_id = $el.data('element-id'); return _.extend($el.offset(), { height: $el.height(), width: $el.width() }); }; TextHighLighterView.prototype.localize = function(key) { return this.options.button_labels[key]; }; TextHighLighterView.prototype.remove = function() { TextHighLighterView.__super__.remove.apply(this, arguments); if (this.hiding_timeout != null) { return clearTimeout(this.hiding_timeout); } }; return TextHighLighterView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Inputs || (base.Inputs = {}); Locomotive.Views.Inputs.ArrayView = (function(superClass) { extend(ArrayView, superClass); function ArrayView() { return ArrayView.__super__.constructor.apply(this, arguments); } ArrayView.prototype.events = { 'click a.add': 'begin_add_item', 'keypress input[type=text]': 'begin_add_item_from_enter', 'click a.delete': 'delete_item' }; ArrayView.prototype.initialize = function() { this.$list = this.$('.list'); this.$new_input = this.$('.new-field .input'); this.$new_button = this.$('.new-field a'); return this.template_url = this.$new_button.attr('href'); }; ArrayView.prototype.render = function() { this.make_sortable(); this.make_selectable(); return this.hide_if_empty(); }; ArrayView.prototype.make_sortable = function() { return this.$list.sortable({ items: '> .item', handle: '.draggable', axis: 'y', placeholder: 'sortable-placeholder', cursor: 'move', start: function(e, ui) { return ui.placeholder.html('<div class="inner">&nbsp;</div>'); }, update: (function(_this) { return function(e, ui) { return _this.$list.find('> .item:not(".hide")').each(function(index) { return $(this).find('.position-in-list').val(index); }); }; })(this) }); }; ArrayView.prototype.make_selectable = function() { if (this.$new_input.prop('tagName') !== 'SELECT') { return; } if (this.$new_input.data('list-url') != null) { return this.make_remote_selectable(); } else { return this.make_simple_selectable(); } }; ArrayView.prototype.make_remote_selectable = function() { Select2Helpers.build(this.$new_input); return this.$new_input.on('change', (function(_this) { return function(e) { return _this.begin_add_item(e); }; })(this)); }; ArrayView.prototype.make_simple_selectable = function() { return this.$new_input.select2({ templateResult: this.format_select_result, templateSelection: this.format_select_result }); }; ArrayView.prototype.format_select_result = function(state) { var display; if (state.id == null) { return state.text; } display = $(state.element).data('display'); return $("<span>" + (display != null ? display : state.text) + "</span>"); }; ArrayView.prototype.begin_add_item_from_enter = function(event) { if (event.keyCode !== 13) { return; } return this.begin_add_item(event); }; ArrayView.prototype.begin_add_item = function(event) { var data; event.stopPropagation() & event.preventDefault(); if (!this.is_unique()) { return; } data = {}; data[this.$new_input.attr('name')] = this.$new_input.val(); return $.ajax({ url: this.template_url, data: data, success: (function(_this) { return function(response) { return _this.add_item(response); }; })(this) }); }; ArrayView.prototype.add_item = function(html) { this.$list.append(html); this.showEl(this.$list); return this.reset_input_field(); }; ArrayView.prototype.delete_item = function(event) { var $destroy_input, $item, $link; $link = $(event.target).closest('a'); if ($link.attr('href') !== '#') { return; } $item = $link.parents('.item'); $destroy_input = $item.find('.mark-as-destroyed'); if ($destroy_input.size() > 0) { $destroy_input.val('1'); $item.addClass('hide'); this.$list.find('> .item.last-child').removeClass('last-child'); this.$list.find('> .item:not(".hide"):last').addClass('last-child'); } else { $item.remove(); } return this.hide_if_empty(); }; ArrayView.prototype.hide_if_empty = function() { if (this.$list.find('> .item:not(".hide")').size() === 0) { this.hideEl(this.$list); if (this.$list.hasClass('new-input-disabled')) { return $(this.el).find('> .form-wrapper').hide(); } } }; ArrayView.prototype.is_unique = function() { return _.indexOf(this.get_ids(), this.$new_input.val()) === -1; }; ArrayView.prototype.get_ids = function() { return _.map(this.$list.find('> .item'), function(item, i) { return $(item).data('id'); }); }; ArrayView.prototype.reset_input_field = function() { return this.$new_input.val(null).trigger('change'); }; ArrayView.prototype.showEl = function(el) { return el.removeClass('hide'); }; ArrayView.prototype.hideEl = function(el) { return el.addClass('hide'); }; return ArrayView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Inputs || (base.Inputs = {}); Locomotive.Views.Inputs.DocumentPickerView = (function(superClass) { extend(DocumentPickerView, superClass); function DocumentPickerView() { return DocumentPickerView.__super__.constructor.apply(this, arguments); } DocumentPickerView.prototype.initialize = function() { DocumentPickerView.__super__.initialize.apply(this, arguments); this.$input = this.$('select'); return this.$link = this.$('a.edit'); }; DocumentPickerView.prototype.render = function() { var label; label = this.$input.data('label'); Select2Helpers.build(this.$input, { allowClear: true }); this.$input.data('select2').on('unselect', (function(_this) { return function(el) { _this.$link.addClass('hide'); return setTimeout((function() { return _this.$input.select2('close'); }), 1); }; })(this)); return this.$input.on('change', (function(_this) { return function(el) { return _this.$link.addClass('hide'); }; })(this)); }; DocumentPickerView.prototype.remove = function() { this.$input.select2('destroy'); return DocumentPickerView.__super__.remove.apply(this, arguments); }; return DocumentPickerView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Inputs || (base.Inputs = {}); Locomotive.Views.Inputs.FileView = (function(superClass) { extend(FileView, superClass); function FileView() { return FileView.__super__.constructor.apply(this, arguments); } FileView.prototype.events = { 'change input[type=file]': 'change_file', 'click a.choose': 'begin_choose_file', 'click a.change': 'begin_change_file', 'click a.content-assets': 'open_content_assets_drawer', 'click a.cancel': 'cancel_new_file', 'click a.delete': 'mark_file_as_deleted' }; FileView.prototype.initialize = function() { _.bindAll(this, 'use_content_asset'); this.$file = this.$('input[type=file]'); this.$remove_file = this.$('input[type=hidden].remove'); this.$remote_url = this.$('input[type=hidden].remote-url'); this.$current_file = this.$('.current-file'); this.$no_file = this.$('.no-file'); this.$new_file = this.$('.new-file'); this.$choose_btn = this.$('.buttons > .choose'); this.$change_btn = this.$('.buttons > .change'); this.$cancel_btn = this.$('.buttons .cancel'); this.$delete_btn = this.$('.buttons .delete'); this.persisted_file = this.$('.row').data('persisted-file'); this.path = $(this.el).data('path'); return this.pubsub_token = PubSub.subscribe('file_picker.select', this.use_content_asset); }; FileView.prototype.begin_change_file = function() { return this.$file.click(); }; FileView.prototype.begin_choose_file = function() { return this.$file.click(); }; FileView.prototype.open_content_assets_drawer = function(event) { event.stopPropagation() & event.preventDefault(); $(event.target).closest('.btn-group').removeClass('open'); return window.application_view.drawer_view.open($(event.target).attr('href'), Locomotive.Views.ContentAssets.PickerView, { parent_view: this }); }; FileView.prototype.use_content_asset = function(msg, data) { var url; if (data.parent_view.cid !== this.cid) { return; } window.application_view.drawer_view.close(); url = window.absolute_url(data.url); return window.remote_file_to_base64(url, (function(_this) { return function(base64) { if (base64) { _this.update_ui_on_changing_file(data.title); base64 = base64.replace(';base64,', ";" + data.filename + ";base64,"); _this.$remote_url.val(base64); if (data.image) { _this.$new_file.html("<img src='" + url + "' /> " + (_this.$new_file.html())); return PubSub.publish('inputs.image_changed', { view: _this, url: url }); } } else { return Locomotive.notify('Unable to load the asset', 'error'); } }; })(this)); }; FileView.prototype.change_file = function(event) { var file, text; file = event.target.files ? event.target.files[0] : null; text = file != null ? file.name : 'New file'; this.update_ui_on_changing_file(text); if (file.type.match('image.*')) { return this.image_to_base_64(file, (function(_this) { return function(base64) { _this.$new_file.html("<img src='" + base64 + "' /> " + (_this.$new_file.html())); return PubSub.publish('inputs.image_changed', { view: _this, url: base64, file: file }); }; })(this)); } }; FileView.prototype.update_ui_on_changing_file = function(text) { this.$new_file.html(text); this.showEl(this.$new_file) && this.hideEl(this.$current_file) && this.hideEl(this.$no_file); return this.hideEl(this.$change_btn) && this.hideEl(this.$delete_btn) && this.hideEl(this.$choose_btn) && this.showEl(this.$cancel_btn); }; FileView.prototype.cancel_new_file = function(event) { this.hideEl(this.$new_file); this.$remote_url.val(''); this.$file.wrap('<form>').closest('form').get(0).reset(); this.$file.unwrap(); $(this.el).removeClass('mark-as-removed'); this.$remove_file.val('0'); this.hideEl(this.$cancel_btn); if (this.persisted_file) { this.showEl(this.$current_file); this.showEl(this.$change_btn) && this.showEl(this.$delete_btn); } else { this.showEl(this.$no_file); this.showEl(this.$choose_btn); } return PubSub.publish('inputs.image_changed', { view: this }); }; FileView.prototype.mark_file_as_deleted = function(event) { this.$remove_file.val('1'); $(this.el).addClass('mark-as-removed'); this.hideEl(this.$change_btn) && this.hideEl(this.$delete_btn) && this.showEl(this.$cancel_btn); return PubSub.publish('inputs.image_removed', { view: this }); }; FileView.prototype.image_to_base_64 = function(file, callback) { var reader; reader = new FileReader(); reader.onload = function(e) { return callback(e.target.result); }; return reader.readAsDataURL(file); }; FileView.prototype.showEl = function(el) { return el.removeClass('hide'); }; FileView.prototype.hideEl = function(el) { return el.addClass('hide'); }; FileView.prototype.need_refresh = function() { return true; }; FileView.prototype.remove = function() { FileView.__super__.remove.apply(this, arguments); return PubSub.unsubscribe(this.pubsub_token); }; return FileView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Inputs || (base.Inputs = {}); Locomotive.Views.Inputs.ImageView = (function(superClass) { extend(ImageView, superClass); function ImageView() { return ImageView.__super__.constructor.apply(this, arguments); } ImageView.prototype.events = { 'click *[data-action=delete]': 'mark_file_as_deleted', 'click *[data-action=undo]': 'undo', 'click a.file-browse': 'open_content_assets_drawer' }; ImageView.prototype.initialize = function() { _.bindAll(this, 'change_file'); return this.pubsub_token = PubSub.subscribe('file_picker.select', this.change_file); }; ImageView.prototype.render = function() { this.$spinner = this.$('.file-wrapper .spinner'); this.urls = { "default": this.$('.file-wrapper').data('default-url'), current: this.$('.file-wrapper').data('url') }; this.initial_state = this.urls.current === '' ? 'no_file' : 'existing_file'; if (_.isEmpty(this.urls.current)) { this.urls.current = this.urls["default"]; } this.resize_format = this.$('.file-wrapper').data('resize'); return this.no_file_label = this.$('.file-wrapper').data('no-file-label'); }; ImageView.prototype.open_content_assets_drawer = function(event) { event.stopPropagation() & event.preventDefault(); return window.application_view.drawer_view.open($(event.target).attr('href'), Locomotive.Views.ContentAssets.PickerView, { parent_view: this }); }; ImageView.prototype.mark_file_as_deleted = function(event) { if (this.initial_state === 'existing_file') { this.current_filename = this.$('.file-name').html(); return this.update_ui(false, true, this.urls["default"], this.no_file_label); } }; ImageView.prototype.undo = function(event) { return this.update_ui(true, false, this.urls.current, this.current_filename || this.no_file_label); }; ImageView.prototype.change_file = function(msg, data) { var url; if (data.parent_view.cid !== this.cid) { return; } window.application_view.drawer_view.close(); url = window.absolute_url(data.url); this.set_file_url(url); this.current_filename || (this.current_filename = this.$('.file-name').html()); this.$spinner.show() & this.update_filename(data.filename); return window.resize_image(url, this.resize_format, (function(_this) { return function(resized_image) { _this.update_ui(true, true, resized_image, data.filename); return _this.$spinner.hide(); }; })(this)); }; ImageView.prototype.update_ui = function(with_file, undo_enabled, url, filename) { if (!with_file) { this.set_file_url(''); } if (undo_enabled) { this.$('*[data-action=delete]').hide(); this.$('*[data-action=undo]').show(); } else { this.$('*[data-action=undo]').hide(); if (this.initial_state !== 'no_file') { this.$('*[data-action=delete]').show(); } } this.$('.file-image img').attr('src', url); return this.update_filename(filename); }; ImageView.prototype.update_filename = function(name) { if (!_.isEmpty(name)) { return this.$('.file-name').html(name); } }; ImageView.prototype.set_file_url = function(url) { return this.$('.file input[type=text]').val(url); }; ImageView.prototype.remove = function() { ImageView.__super__.remove.apply(this, arguments); if (this.pubsub_token != null) { return PubSub.unsubscribe(this.pubsub_token); } }; return ImageView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Inputs || (base.Inputs = {}); Locomotive.Views.Inputs.TextView = (function(superClass) { extend(TextView, superClass); function TextView() { return TextView.__super__.constructor.apply(this, arguments); } TextView.prototype.events = { 'change input[type=text]': 'content_change', 'paste input[type=text]': 'content_change', 'keyup input[type=text]': 'content_change', 'highlight input[type=text]': 'highlight', 'change textarea': 'content_change', 'paste textarea': 'content_change', 'keyup textarea': 'content_change', 'highlight textarea': 'highlight' }; TextView.prototype.content_change = function(event) { PubSub.publish('inputs.text_changed', { view: this, content: this.text_value($(event.target)) }); return true; }; TextView.prototype.text_value = function(textarea) { return textarea.val(); }; TextView.prototype.highlight = function(event) { return $(event.target).focus(); }; return TextView; })(Backbone.View); }).call(this); (function() { var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Locomotive.Views.Inputs.MarkdownView = (function(superClass) { extend(MarkdownView, superClass); function MarkdownView() { return MarkdownView.__super__.constructor.apply(this, arguments); } MarkdownView.prototype.events = _.extend({}, Locomotive.Views.Inputs.TextView.prototype.events, { 'click a[data-markdown-command]': 'run_command' }); MarkdownView.prototype.opened_picker = false; MarkdownView.prototype.initialize = function() { MarkdownView.__super__.initialize.apply(this, arguments); _.bindAll(this, 'insert_file'); this.$textarea = this.$('textarea.markdown'); this.editor = CodeMirror.fromTextArea(this.$textarea[0], { mode: 'markdown', tabMode: 'indent', lineWrapping: true }); return this.pubsub_token = PubSub.subscribe('file_picker.select', this.insert_file); }; MarkdownView.prototype.run_command = function(event) { var $link, command; $link = $(event.target).closest('a'); command = $link.data('markdown-command'); switch (command) { case 'bold': this.apply_bold(); break; case 'italic': this.apply_italic(); break; case 'insertFile': this.open_file_picker($link.data('url')); break; default: console.log("[Markdown input] command not implemented: " + command); return; } return this.content_change_with_markdown(); }; MarkdownView.prototype.apply_bold = function() { var text; text = this.editor.getSelection(); if (!((text != null) && text.length > 0)) { text = 'Some text'; } return this.editor.replaceSelection("**" + text + "**"); }; MarkdownView.prototype.apply_italic = function() { var text; text = this.editor.getSelection(); if (!((text != null) && text.length > 0)) { text = 'Some text'; } return this.editor.replaceSelection("*" + text + "*"); }; MarkdownView.prototype.insert_file = function(msg, data) { var text; if (data.parent_view.cid !== this.cid) { return; } text = this.editor.getSelection(); if ((text == null) || text.length === 0) { text = data.title; } if (data.image) { this.editor.replaceSelection(" ![" + text + "](" + data.url + ") "); } else { this.editor.replaceSelection(" [" + text + "](" + data.url + ") "); } this.content_change_with_markdown(); return this.hide_file_picker(); }; MarkdownView.prototype.content_change_with_markdown = function() { var event; event = $.Event('change', { target: this.$textarea }); return this.content_change(event); }; MarkdownView.prototype.text_value = function(textarea) { return kramed(this.editor.getValue()); }; MarkdownView.prototype.open_file_picker = function(url) { if (this.opened_picker === false) { window.application_view.drawer_view.open(url, Locomotive.Views.ContentAssets.PickerView, { parent_view: this }); return this.opened_picker = true; } }; MarkdownView.prototype.hide_file_picker = function() { window.application_view.drawer_view.close(); return this.opened_picker = false; }; MarkdownView.prototype.remove = function() { PubSub.unsubscribe(this.pubsub_token); return MarkdownView.__super__.remove.apply(this, arguments); }; return MarkdownView; })(Locomotive.Views.Inputs.TextView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views.Inputs).Rte || (base.Rte = {}); Locomotive.Views.Inputs.Rte.EditTableView = (function(superClass) { extend(EditTableView, superClass); function EditTableView() { return EditTableView.__super__.constructor.apply(this, arguments); } EditTableView.prototype.initialize = function() { _.bindAll(this, 'hide'); this.$link = this.$('a[data-wysihtml5-hiddentools=table]'); this.$content = this.$link.next('.table-dialog-content'); return this.editor = this.options.editor; }; EditTableView.prototype.render = function() { if (this.$link.size() === 0) { return; } this.create_popover(); return this.attach_events(); }; EditTableView.prototype.create_popover = function() { return this.$link.popover({ placement: 'bottom', content: this.$content.html(), html: true, title: void 0 }); }; EditTableView.prototype.attach_events = function() { return this.editor.on('tableunselect:composer', this.hide); }; EditTableView.prototype.detach_events = function() { return this.editor.stopObserving('tableselect:composer', this.hide); }; EditTableView.prototype.hide = function() { return this.$link.popover('hide'); }; EditTableView.prototype.remove = function() { this.$link.popover('destroy'); return this.$('.popover').remove(); }; return EditTableView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views.Inputs).Rte || (base.Rte = {}); Locomotive.Views.Inputs.Rte.FileView = (function(superClass) { extend(FileView, superClass); function FileView() { return FileView.__super__.constructor.apply(this, arguments); } FileView.prototype.opened = { popover: false, picker: false }; FileView.prototype.container = { dataset: { showdialogonselection: true } }; FileView.prototype.initialize = function() { _.bindAll(this, 'change_image', 'insert_file', 'hide'); this.$link = this.$('a[data-wysihtml5-command=insertFile]'); this.editor = this.options.editor; this.$popover = this.$link.next('.image-dialog-content'); return this.pubsub_token = PubSub.subscribe('file_picker.select', this.insert_file); }; FileView.prototype.render = function() { this.attach_editor(); return this.create_popover(); }; FileView.prototype.attach_editor = function() { var command; command = this.editor.toolbar.commandMapping['insertFile:null']; return command.dialog = this; }; FileView.prototype.create_popover = function() { this.$popover.show(); this.$link.popover({ container: '.main', placement: 'left', content: this.$popover, html: true, template: '<div class="popover" role="tooltip"><div class="arrow"></div><form class="simple_form"><div class="popover-content"></div></form></div>' }); this.$link.data('bs.popover').setContent(); return this.attach_popover_events(); }; FileView.prototype.attach_popover_events = function() { this.$popover.parents('form').on('click', '.apply', this.change_image); this.$popover.on('click', '.apply', this.change_image); return this.$popover.on('click', '.cancel', this.hide); }; FileView.prototype.detach_popover_events = function() { this.$popover.parents('form').on('click', '.apply', this.change_image); this.$popover.on('click', '.apply', this.change_image); return this.$popover.on('click', '.cancel', this.hide); }; FileView.prototype.change_image = function(event) { this.editor.composer.commands.exec('insertImage', { src: this._input_el('src').val(), "class": this._input_el('alignment', 'select').val(), title: this._input_el('title').val() }); return this.hide(); }; FileView.prototype.insert_file = function(msg, data) { var html; if (data.parent_view.cid !== this.cid) { return; } if (data.image) { this.editor.composer.commands.exec('insertImage', { src: data.url, title: data.title }); } else { html = "<a href='" + data.url + "' title='" + data.title + "'>" + data.title + "</a>"; this.editor.composer.commands.exec('insertHTML', html); } this.editor.toolbar._preventInstantFocus(); return this.hide(); }; FileView.prototype.show = function(state) { var $image; this.editor.focus(); if (state === false) { this.hide_popover(); return this.show_picker(); } else { $image = $(state); this._input_el('src').val($image.attr('src')); this._input_el('alignment', 'select').val($image.attr('class')); this._input_el('title').val($image.attr('title')); return this.show_popover(); } }; FileView.prototype.show_picker = function() { if (this.opened.picker === false) { window.application_view.drawer_view.open(this.$link.data('url'), Locomotive.Views.ContentAssets.PickerView, { parent_view: this }); return this.opened.picker = true; } }; FileView.prototype.show_popover = function() { if (this.opened.popover === false) { this.$link.popover('show'); return this.opened.popover = true; } }; FileView.prototype.update = function(state) {}; FileView.prototype.hide = function() { if (this.opened.picker) { return this.hide_picker(); } else if (this.opened.popover) { return this.hide_popover(); } }; FileView.prototype.hide_picker = function() { window.application_view.drawer_view.close(); return this.opened.picker = false; }; FileView.prototype.hide_from_picker = function(stack_size) { if (stack_size === 0) { return this.opened.picker = false; } }; FileView.prototype.hide_popover = function() { this.$link.popover('hide'); return this.opened.popover = false; }; FileView.prototype._input_el = function(property, type) { var name; type || (type = 'input'); name = "rte_input_image_form[" + property + "]"; return this.$popover.find(type + "[name=\"" + name + "\"]"); }; FileView.prototype.remove = function() { this.detach_popover_events(); this.$link.popover('destroy'); this.$('.popover').remove(); PubSub.unsubscribe(this.pubsub_token); return FileView.__super__.remove.apply(this, arguments); }; return FileView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views.Inputs).Rte || (base.Rte = {}); Locomotive.Views.Inputs.Rte.ImageView = (function(superClass) { extend(ImageView, superClass); function ImageView() { return ImageView.__super__.constructor.apply(this, arguments); } ImageView.prototype.initialize = function() { ImageView.__super__.initialize.call(this); this.$link = this.$('a[data-wysihtml5-command=insertImage]'); return this.$popover = this.$link.next('.image-dialog-content'); }; ImageView.prototype.attach_editor = function() { var command; command = this.editor.toolbar.commandMapping['insertImage:null']; return command.dialog = this; }; return ImageView; })(Locomotive.Views.Inputs.Rte.FileView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views.Inputs).Rte || (base.Rte = {}); Locomotive.Views.Inputs.Rte.LinkView = (function(superClass) { extend(LinkView, superClass); function LinkView() { return LinkView.__super__.constructor.apply(this, arguments); } LinkView.prototype.isOpen = false; LinkView.prototype.container = { dataset: { showdialogonselection: false } }; LinkView.prototype.initialize = function() { _.bindAll(this, 'apply', 'show', 'hide'); this.$link = this.$('a[data-wysihtml5-command=createLink]'); this.editor = this.options.editor; this.$content = this.$link.next('.link-dialog-content'); return this.$content.find('.input.select select:not(.disable-select2)').data('select2').$dropdown.addClass('rte-select2-dropdown'); }; LinkView.prototype.render = function() { this.attach_editor(); this.create_popover(); return this.attach_events(); }; LinkView.prototype.create_popover = function() { this.$content.show(); this.$link.popover({ container: this.$link.parents('fieldset'), placement: 'right', content: this.$content, html: true, trigger: 'manual', template: '<div class="popover" role="tooltip"><div class="arrow"></div><form class="simple_form"><div class="popover-content"></div></form></div>' }); return this.$link.data('bs.popover').setContent(); }; LinkView.prototype.attach_events = function() { this.$content.on('click', '.apply', this.apply); return this.$content.on('click', '.cancel', this.hide); }; LinkView.prototype.detach_events = function() { this.$content.off('click', '.apply', this.apply); return this.$content.off('click', '.cancel', this.hide); }; LinkView.prototype.attach_editor = function() { var command; command = this.editor.toolbar.commandMapping['createLink:null']; return command.dialog = this; }; LinkView.prototype.apply = function(event) { var url; url = this._input_el('url').val(); if (!_.isEmpty(url)) { this.editor.composer.commands.exec('createLink', { href: url, target: this._input_el('target', 'select').val(), title: this._input_el('title').val(), rel: "nofollow" }); this.editor.toolbar._preventInstantFocus(); return this.hide(); } }; LinkView.prototype.show = function(state) { var $link; if (this.isOpen && state !== false) { return; } if (state === false) { this.$content.parents('form')[0].reset(); } else { $link = $(state); this._input_el('url').val($link.attr('href')); this._input_el('target', 'select').val($link.attr('target')); this._input_el('title').val($link.attr('title')); } this.$link.popover('toggle'); this._input_el('url').focus(); return this.isOpen = true; }; LinkView.prototype.update = function(state) {}; LinkView.prototype.hide = function() { this._input_el('target', 'select').select2('close'); this.$link.popover('hide'); return this.isOpen = false; }; LinkView.prototype._input_el = function(property, type) { var name; type || (type = 'input'); name = "rte_input_link_form[" + property + "]"; return this.$content.find(type + "[name=\"" + name + "\"]"); }; LinkView.prototype.remove = function() { this.detach_events(); this.$link.popover('destroy'); return this.$('.popover').remove(); }; return LinkView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views.Inputs).Rte || (base.Rte = {}); Locomotive.Views.Inputs.Rte.TableView = (function(superClass) { extend(TableView, superClass); function TableView() { return TableView.__super__.constructor.apply(this, arguments); } TableView.prototype.container = { dataset: [] }; TableView.prototype.initialize = function() { _.bindAll(this, 'apply', 'show', 'hide', 'show_link', 'hide_link'); this.$link = this.$('a[data-wysihtml5-command=createTable]'); this.editor = this.options.editor; return this.$content = this.$link.next('.table-dialog-content'); }; TableView.prototype.render = function() { if (this.$link.size() === 0) { return; } this.create_popover(); this.attach_events(); return this.attach_editor(); }; TableView.prototype.create_popover = function() { this.$content.show(); this.$link.popover({ container: this.$link.parents('fieldset'), placement: 'right', content: this.$content, html: true, trigger: 'manual', template: '<div class="popover" role="tooltip"><div class="arrow"></div><form class="simple_form"><div class="popover-content"></div></form></div>' }); return this.$link.data('bs.popover').setContent(); }; TableView.prototype.attach_events = function() { this.$content.on('click', '.apply', this.apply); this.$content.on('click', '.cancel', this.hide); this.editor.on('tableselect:composer', this.hide_link); return this.editor.on('tableunselect:composer', this.show_link); }; TableView.prototype.detach_events = function() { this.$content.off('click', '.apply', this.apply); this.$content.off('click', '.cancel', this.hide); this.editor.stopObserving('tableselect:composer', this.hide_link); return this.editor.stopObserving('tableunselect:composer', this.show_link); }; TableView.prototype.attach_editor = function() { var command; command = this.editor.toolbar.commandMapping['createTable:null']; return command.dialog = this; }; TableView.prototype.apply = function(event) { this.editor.composer.commands.exec('createTable', { cols: this._input_el('cols').val(), rows: this._input_el('rows').val(), class_name: this._input_el('class_name').val(), head: this._input_el('head').last().bootstrapSwitch('state') }); return this.hide(); }; TableView.prototype.show = function(state) { this.$link.popover('toggle'); return this.$content.parents('form')[0].reset(); }; TableView.prototype.update = function(state) {}; TableView.prototype.hide = function() { return this.$link.popover('hide'); }; TableView.prototype.show_link = function() { return this.$link.show(); }; TableView.prototype.hide_link = function() { return this.$link.hide(); }; TableView.prototype._input_el = function(property, type) { var name; type || (type = 'input'); name = "rte_input_table_form[" + property + "]"; return this.$content.find(type + "[name=\"" + name + "\"]"); }; TableView.prototype.remove = function() { this.detach_events(); this.$link.popover('destroy'); return this.$('.popover').remove(); }; return TableView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Inputs || (base.Inputs = {}); Locomotive.Views.Inputs.RteView = (function(superClass) { extend(RteView, superClass); function RteView() { return RteView.__super__.constructor.apply(this, arguments); } RteView.prototype.events = { 'click a.style': 'open_styles_dialog', 'click a.table': 'open_table_dialog', 'click a.expand': 'expand', 'highlight textarea': 'highlight' }; RteView.prototype.initialize = function() { _.bindAll(this, 'register_editor_events', 'on_content_change', 'resize'); this.tokens = [PubSub.subscribe('application_view.resize', this.resize)]; return this.build_editor(); }; RteView.prototype.render = function() { return this.render_views(); }; RteView.prototype.build_editor = function() { var $textarea; $textarea = this.$('textarea'); this.editor = new wysihtml5.Editor($textarea.attr('id'), { toolbar: "wysihtml5-toolbar-" + ($textarea.attr('id')), useLineBreaks: $textarea.data('inline'), parserRules: wysihtml5ParserRules, stylesheets: ['/assets/locomotive/wysihtml5_editor-fc9dd453168cc989b0d1e4df89ed54a330618916423c4a4ac4a804329cc4fb1a.css'], showToolbarDialogsOnSelection: false }); return this.editor.on('load', this.register_editor_events); }; RteView.prototype.render_views = function() { return this.editor.on('load', (function(_this) { return function() { _this.views = [_this.build_and_render_view(Locomotive.Views.Inputs.Rte.LinkView), _this.build_and_render_view(Locomotive.Views.Inputs.Rte.FileView), _this.build_and_render_view(Locomotive.Views.Inputs.Rte.ImageView), _this.build_and_render_view(Locomotive.Views.Inputs.Rte.TableView), _this.build_and_render_view(Locomotive.Views.Inputs.Rte.EditTableView)]; return console.log('[RTE] all views created and rendered'); }; })(this)); }; RteView.prototype.expand = function(event) { event.stopPropagation() & event.preventDefault(); $(this.el).parents('.simple_form').toggleClass('rte-expanded'); $(this.el).parents('.inputs').toggleClass('expanded'); $(this.el).toggleClass('expanded'); if (this.$style_popover != null) { this.$style_popover.popover('hide'); } return this.resize(); }; RteView.prototype.open_styles_dialog = function(event) { var $button, html; $button = $(event.target).closest('a'); html = $button.next('.style-dialog-content').html(); this.$style_popover = this.$style_popover || ($button.popover({ placement: 'top', content: html, html: true, title: void 0 })); this.$style_popover.data('bs.popover').options.content = html; return this.$style_popover.popover('show'); }; RteView.prototype.build_and_render_view = function(klass, command) { var view; view = new klass({ el: this.el, editor: this.editor }); view.render(); return view; }; RteView.prototype.register_editor_events = function() { this.$('.wysihtml5-sandbox').contents().find('body').on('keyup', (function(_this) { return function() { return _this.on_content_change(); }; })(this)); this.$('.wysihtml5-sandbox').contents().find('body').on('dblclick', (function(_this) { return function() { var link, selectedNode; selectedNode = _this.editor.composer.selection.getSelectedNode(); link = wysihtml5.dom.getParentElement(selectedNode, { query: 'a' }, 4); if (link) { return _this.editor.toolbar.commandMapping['createLink:null'].link.click(); } }; })(this)); this.editor.on('change', this.on_content_change); return this.editor.on('aftercommand:composer', this.on_content_change); }; RteView.prototype.on_content_change = function() { return PubSub.publish('inputs.text_changed', { view: this, content: this.editor.getValue() }); }; RteView.prototype.highlight = function(event) { return this.editor.focus(); }; RteView.prototype.resize = function() { var $iframe, $inputs, $wrapper, delta_height, height, wrapper_max_height; $iframe = this.$('.form-wrapper .wysihtml5-sandbox'); $inputs = $(this.el).parents('.inputs'); $wrapper = this.$('.form-wrapper'); if ($inputs.hasClass('expanded')) { delta_height = $wrapper.outerHeight() - $iframe.outerHeight(); wrapper_max_height = $(this.el).height() - ($wrapper.outerHeight() - $wrapper.height() + parseInt($wrapper.css('margin-top')) + parseInt($(this.el).css('padding-bottom'))); height = wrapper_max_height - delta_height; if ($iframe.data('height') == null) { $iframe.data('height', $iframe.css('height')); } return $iframe.css('min-height', height); } else { return $iframe.css('min-height', $iframe.data('height')); } }; RteView.prototype.remove = function() { _.invoke(this.views, 'remove'); _.each(this.tokens, function(token) { return PubSub.unsubscribe(token); }); this.editor.stopObserving('onLoad', this.register_keydown_event); this.editor.stopObserving('onChange', this.on_content_change); this.editor.destroy(); return RteView.__super__.remove.call(this); }; return RteView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Inputs || (base.Inputs = {}); Locomotive.Views.Inputs.SimpleImageView = (function(superClass) { extend(SimpleImageView, superClass); function SimpleImageView() { return SimpleImageView.__super__.constructor.apply(this, arguments); } SimpleImageView.prototype.events = _.extend({}, Locomotive.Views.Inputs.ImageView.prototype.events, { 'change input[type=file]': 'change_file' }); SimpleImageView.prototype.render = function() { SimpleImageView.__super__.render.apply(this, arguments); return this.$fields = { file: this.$('input[type=file]'), remove: this.$('input[type=hidden].remove') }; }; SimpleImageView.prototype.undo = function(event) { this.$fields.file.wrap('<form>').parent('form').trigger('reset'); this.$fields.file.unwrap(); return SimpleImageView.__super__.undo.apply(this, arguments); }; SimpleImageView.prototype.change_file = function(event) { var file; file = event.target.files ? event.target.files[0] : null; if ((file == null) || !file.type.match('image.*')) { return; } this.current_filename || (this.current_filename = this.$('.file-name').html()); this.$spinner.show() & this.update_filename(file.name); return this.image_to_base_64(file, (function(_this) { return function(base64) { return window.resize_image(base64, _this.resize_format, function(resized_image) { _this.update_ui(true, true, resized_image, file.name); return _this.$spinner.hide(); }); }; })(this)); }; SimpleImageView.prototype.update_ui = function(with_file, undo_enabled, url, filename) { var value; value = with_file ? '0' : '1'; this.$fields.remove.val(value); return SimpleImageView.__super__.update_ui.apply(this, arguments); }; SimpleImageView.prototype.image_to_base_64 = function(file, callback) { var reader; reader = new FileReader(); reader.onload = function(e) { return callback(e.target.result); }; return reader.readAsDataURL(file); }; return SimpleImageView; })(Locomotive.Views.Inputs.ImageView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Memberships || (base.Memberships = {}); Locomotive.Views.Memberships.EditView = (function(superClass) { extend(EditView, superClass); function EditView() { return EditView.__super__.constructor.apply(this, arguments); } EditView.prototype.el = '.main'; return EditView; })(Locomotive.Views.Shared.FormView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Memberships || (base.Memberships = {}); Locomotive.Views.Memberships.NewView = (function(superClass) { extend(NewView, superClass); function NewView() { return NewView.__super__.constructor.apply(this, arguments); } NewView.prototype.el = '.main'; return NewView; })(Locomotive.Views.Shared.FormView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).MyAccount || (base.MyAccount = {}); Locomotive.Views.MyAccount.EditView = (function(superClass) { extend(EditView, superClass); function EditView() { return EditView.__super__.constructor.apply(this, arguments); } EditView.prototype.el = '.public-box'; EditView.prototype.events = { 'click .api_key.input button': 'regenerate_api_key', 'submit form': 'save' }; EditView.prototype.regenerate_api_key = function(event) { var button; event.stopPropagation() & event.preventDefault(); button = $(event.target); if (confirm(button.data('confirm'))) { return $.rails.ajax({ url: button.data('url'), type: 'put', dataType: 'json', success: (function(_this) { return function(data) { return button.prev('code').html(data.api_key); }; })(this) }); } }; return EditView; })(Locomotive.Views.Shared.FormView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Pages || (base.Pages = {}); Locomotive.Views.Pages.FormView = (function(superClass) { extend(FormView, superClass); function FormView() { return FormView.__super__.constructor.apply(this, arguments); } FormView.prototype.el = '#content'; FormView.prototype.initialize = function() { return this.attach_events_on_redirect_attribute(); }; FormView.prototype.attach_events_on_redirect_attribute = function() { return this.$('#page_redirect').on('switchChange.bootstrapSwitch', function(event, state) { var $inputs; $inputs = $('.locomotive_page_redirect_url, .locomotive_page_redirect_type'); return $inputs.toggleClass('hide'); }); }; return FormView; })(Locomotive.Views.Shared.FormView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Pages || (base.Pages = {}); Locomotive.Views.Pages.EditView = (function(superClass) { extend(EditView, superClass); function EditView() { return EditView.__super__.constructor.apply(this, arguments); } EditView.prototype.el = '.main'; return EditView; })(Locomotive.Views.Pages.FormView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Pages || (base.Pages = {}); Locomotive.Views.Pages.ListView = (function(superClass) { extend(ListView, superClass); function ListView() { return ListView.__super__.constructor.apply(this, arguments); } ListView.prototype.el = '.pages-tree'; ListView.prototype.render = function() { this.make_foldable(); this.make_sortable(); this.make_hoverable(); return this; }; ListView.prototype.make_foldable = function() { var self; self = this; return this.$('ul .fold-unfold').each(function() { var $children, $toggler; $toggler = $(this); $children = $toggler.next('ul.leaves'); if ($toggler.hasClass('folded')) { return $children.hide(); } }).click(function(event) { var $children, $node, $toggler; $toggler = $(this); $node = $toggler.parents('li.node'); $children = $toggler.next('ul.leaves'); if ($toggler.hasClass('folded')) { return $children.slideDown('fast', function() { $toggler.removeClass('folded').addClass('unfolded'); return $.cookie($node.attr('id'), 'unfolded', { path: window.Locomotive.mounted_on }); }); } else { return $children.slideUp('fast', function() { $toggler.removeClass('unfolded').addClass('folded'); return $.cookie($node.attr('id'), 'folded', { path: window.Locomotive.mounted_on }); }); } }); }; ListView.prototype.make_sortable = function() { var self; self = this; return this.$('ul').sortable({ items: '> li.page', handle: '.draggable', axis: 'y', placeholder: 'sortable-placeholder', cursor: 'move', update: function(event, ui) { return self.call_sort($(this)); }, stop: function(event, ui) { var position; if ($(this).hasClass('root')) { position = ui.item.index(); if (position === 0 || position >= $(this).find('> li').size() - 2) { return $(this).sortable('cancel'); } } } }); }; ListView.prototype.make_hoverable = function() { return this.$('a').hover(function() { return $(this).prev('i.icon').addClass('on'); }, function() { return $(this).prev('i.icon').removeClass('on'); }); }; ListView.prototype.call_sort = function(folder) { return $.rails.ajax({ url: folder.data('url'), type: 'post', dataType: 'json', data: { children: _.map(folder.sortable('toArray'), function(el) { return el.replace('node-', ''); }), _method: 'put' }, success: this.on_successful_sort, error: this.on_failed_sort }); }; ListView.prototype.on_successful_sort = function(data, status, xhr) { Locomotive.notify(decodeURIComponent($.parseJSON(xhr.getResponseHeader('X-Message'))), 'success'); return PubSub.publish('pages.sorted'); }; ListView.prototype.on_failed_sort = function(data, status, xhr) { return Locomotive.notify(decodeURIComponent($.parseJSON(xhr.getResponseHeader('X-Message'))), 'error'); }; return ListView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Pages || (base.Pages = {}); Locomotive.Views.Pages.NewView = (function(superClass) { extend(NewView, superClass); function NewView() { return NewView.__super__.constructor.apply(this, arguments); } NewView.prototype.el = '.main'; return NewView; })(Locomotive.Views.Pages.FormView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).PublicSubmissionAccounts || (base.PublicSubmissionAccounts = {}); Locomotive.Views.PublicSubmissionAccounts.EditView = (function(superClass) { extend(EditView, superClass); function EditView() { return EditView.__super__.constructor.apply(this, arguments); } EditView.prototype.el = '.main'; return EditView; })(Locomotive.Views.Shared.FormView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Registrations || (base.Registrations = {}); Locomotive.Views.Registrations.NewView = (function(superClass) { extend(NewView, superClass); function NewView() { return NewView.__super__.constructor.apply(this, arguments); } NewView.prototype.el = '.public-box'; return NewView; })(Locomotive.Views.Shared.FormView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Shared || (base.Shared = {}); Locomotive.Views.Shared.DrawerView = (function(superClass) { extend(DrawerView, superClass); function DrawerView() { return DrawerView.__super__.constructor.apply(this, arguments); } DrawerView.prototype.el = '.content-main > .drawer'; DrawerView.prototype.delays = { fade: 50, remove: 200 }; DrawerView.prototype.events = { 'click .close-button': 'close' }; DrawerView.prototype.initialize = function() { this.stack = []; return DrawerView.__super__.initialize.apply(this, arguments); }; DrawerView.prototype.open = function(url, view_klass, options) { var entry; if (options == null) { options = {}; } console.log("[DrawerView] open, stack(" + this.stack.length + ") opened = " + ($(this.el).hasClass('drawer-open')) + ", " + url); entry = { url: url, view_klass: view_klass, options: options }; return this.push(entry); }; DrawerView.prototype.close = function() { console.log("[DrawerView] close, stack(" + this.stack.length + ")"); return this.pop(); }; DrawerView.prototype.push = function(entry) { this.hide(this.last_entry()); this.stack.push(entry); return this.show(entry); }; DrawerView.prototype.pop = function() { var entry; entry = this.stack.pop(); return this.hide(entry, (function(_this) { return function() { return _this.show(_this.last_entry()); }; })(this)); }; DrawerView.prototype.replace = function(entry) { var _container, last_entry; last_entry = this.stack.pop(); _container = this.container(true); this.stack.push(entry); if (entry.url != null) { return _container.load(entry.url, (function(_this) { return function() { if (last_entry) { last_entry.view.remove(); } return _this._show(entry, _container); }; })(this)); } else { return this._show(entry, _container); } }; DrawerView.prototype.show = function(entry) { var timeout; if (entry === null) { return; } timeout = this.stack.length === 1 ? 0 : this.delays.fade; return setTimeout((function(_this) { return function() { var _container; _container = _this.container(); if (entry.url != null) { return _container.load(entry.url, function() { return _this._show(entry, _container); }); } else { return _this._show(entry, _container); } }; })(this), timeout); }; DrawerView.prototype.hide = function(entry, callback) { if (this.stack.length === 0) { $(this.el).removeClass('drawer-open'); } else { if (entry != null) { entry.view.$el.addClass('fadeout'); } } return setTimeout((function(_this) { return function() { if (entry != null) { if (entry.view.hide_from_drawer != null) { entry.view.hide_from_drawer(_this.stack.length); } entry.view.remove(); } if (callback != null) { return callback(); } }; })(this), this.delays.remove); }; DrawerView.prototype.last_entry = function() { if (this.stack.length === 0) { return null; } else { return this.stack[this.stack.length - 1]; } }; DrawerView.prototype.container = function(preserve) { if ((preserve != null) && preserve) { return this.$('> .content-inner').find('> div'); } else { return this.$('> .content-inner').html('<div></div>').find('> div'); } }; DrawerView.prototype._show = function(entry, container) { var _klass, attributes; _klass = entry.view_klass; attributes = _.extend({ el: container, drawer: this }, entry.options); entry.view = new _klass(attributes); entry.view.render(); return $(this.el).addClass('drawer-open'); }; return DrawerView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Shared || (base.Shared = {}); Locomotive.Views.Shared.HeaderView = (function(superClass) { extend(HeaderView, superClass); function HeaderView() { return HeaderView.__super__.constructor.apply(this, arguments); } HeaderView.prototype.el = '.header'; HeaderView.prototype.initialize = function() {}; HeaderView.prototype.render = function() {}; HeaderView.prototype.height = function() { return $(this.el).outerHeight(true); }; return HeaderView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Shared || (base.Shared = {}); Locomotive.Views.Shared.ListItemView = (function(superClass) { extend(ListItemView, superClass); function ListItemView() { return ListItemView.__super__.constructor.apply(this, arguments); } ListItemView.prototype.tagName = 'li'; ListItemView.prototype.events = { 'click a.remove': 'remove_item' }; ListItemView.prototype.template = function() {}; ListItemView.prototype.render = function() { $(this.el).html(this.template()(this.model.toJSON())); return this; }; ListItemView.prototype.remove_item = function(event) { event.stopPropagation() & event.preventDefault(); if (confirm($(event.target).closest('a').data('confirm'))) { return this.model.destroy(); } }; return ListItemView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Shared || (base.Shared = {}); Locomotive.Views.Shared.ListView = (function(superClass) { extend(ListView, superClass); function ListView() { return ListView.__super__.constructor.apply(this, arguments); } ListView.prototype.initialize = function() { return this.sort_url = $(this.el).data('sort-url'); }; ListView.prototype.render = function() { if (this.sort_url != null) { return this.make_sortable(); } }; ListView.prototype.make_sortable = function() { var self; self = this; return $(this.el).sortable({ items: '> .item', handle: '.draggable', axis: 'y', placeholder: 'sortable-placeholder', cursor: 'move', start: function(e, ui) { return ui.placeholder.html('<div class="inner">&nbsp;</div>'); }, update: function(event, ui) { return self.call_sort(ui); } }); }; ListView.prototype.call_sort = function() { return $.rails.ajax({ url: this.sort_url, type: 'post', dataType: 'json', data: { entries: _.map($(this.el).find('> .item'), function(el) { return $(el).data('id'); }), _method: 'put' }, success: this.on_successful_sort, error: this.on_failed_sort }); }; ListView.prototype.on_successful_sort = function(data, status, xhr) { var message; message = xhr.getResponseHeader('X-Message'); return Locomotive.notify(decodeURIComponent($.parseJSON(message)), 'success'); }; ListView.prototype.on_failed_sort = function(data, status, xhr) { var message; message = _.isObject(xhr) ? $.parseJSON(xhr.getResponseHeader('X-Message')) : xhr; return Locomotive.notify(decodeURIComponent(message), 'danger'); }; return ListView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Shared || (base.Shared = {}); Locomotive.Views.Shared.SidebarView = (function(superClass) { extend(SidebarView, superClass); function SidebarView() { return SidebarView.__super__.constructor.apply(this, arguments); } SidebarView.prototype.el = 'body > .sidebar'; SidebarView.prototype.initialize = function() { _.bindAll(this, 'close_sidebar_on_mobile'); this.pages_view = new Locomotive.Views.Pages.ListView(); return this.tokens = [PubSub.subscribe('application_view.resize', this.close_sidebar_on_mobile)]; }; SidebarView.prototype.render = function() { this.pages_view.render(); this.collapse_in_sections(); this.close_sidebar_on_mobile(); return this.highlight_active_section(); }; SidebarView.prototype.highlight_active_section = function() { var section; if (section = $(this.el).data('current-section')) { return this.$(".sidebar-link." + section).addClass('is-active'); } }; SidebarView.prototype.toggle_sidebar = function(event) { if (this.is_sidebar_open()) { return this.close_sidebar(); } else { return this.show_sidebar(); } }; SidebarView.prototype.is_sidebar_open = function() { return $('body').hasClass('sidebar-open'); }; SidebarView.prototype.show_sidebar = function() { return $('body').removeClass('sidebar-closed').addClass('sidebar-open'); }; SidebarView.prototype.close_sidebar = function() { return $('body').removeClass('sidebar-open').addClass('sidebar-closed'); }; SidebarView.prototype.close_sidebar_on_mobile = function() { if (this.is_sidebar_open() && $(window).width() < 992) { return this.close_sidebar(); } }; SidebarView.prototype.collapse_in_sections = function() { return this.$('a[data-toggle="collapse"].is-active').each(function() { var target_id; target_id = $(this).attr('href'); return $(target_id).collapse('show'); }); }; return SidebarView; })(Backbone.View); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Sites || (base.Sites = {}); Locomotive.Views.Sites.NewView = (function(superClass) { extend(NewView, superClass); function NewView() { return NewView.__super__.constructor.apply(this, arguments); } return NewView; })(Locomotive.Views.Shared.FormView); }).call(this); (function() { var base, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; (base = Locomotive.Views).Translations || (base.Translations = {}); Locomotive.Views.Translations.IndexView = (function(superClass) { extend(IndexView, superClass); function IndexView() { return IndexView.__super__.constructor.apply(this, arguments); } IndexView.prototype.el = '.main'; return IndexView; })(Backbone.View); }).call(this);