How to use getCurrentSessionData method in Cypress

Best JavaScript code snippet using cypress

test.js

Source:test.js Github

copy

Full Screen

...385 livereLoggedIn: function() {386 return widget.sidebar.getLoginData()387 },388 cityLoggedIn: function() {389 return widget.sidebar.getCurrentSessionData()390 }391 },392 popup: {393 image: function(a, b) {394 return widget.sidebar.image(b)395 }396 }397 };398 return addEventListener("message", function(b) {399 if (b.data && "string" == typeof b.data && b.data.match(/^{.*}$/g)) {400 var c = JSON.parse(b.data),401 d = a[c.caller];402 return !!d && d[c.e](c.caller, c.params)403 }404 })405 }, livere.load = function(a) {406 var b = get("common");407 if (!(!a instanceof Array))408 for (var c = 0; c < a.length; c++) widget[a[c]] && widget[a[c]].draw(template(a[c], b))409 }, widget.check = function() {410 var a = {};411 return a.draw = function(a) {412 if (console.log(a), a) {413 var b = serial("lv-check");414 a.style.cssText = "min-width:100%;width:100px;*width:100%;height:250px;overflow:hidden;border:0;z-index:124212;", a.id = b, document.getElementById("lv-container").appendChild(a)415 }416 }, a417 }(), widget.comment = function() {418 var a = {};419 return a.state = function() {420 var a = get("lv_comment");421 if (a) return postMessage(a.contentWindow, {422 e: "state"423 })424 }, a.updateBlock = function(a) {425 return postMessage(get("lv_comment").contentWindow, {426 e: "updateBlock",427 params: a428 })429 }, a.highlight = function(a, b) {430 var c = get("lv_comment").offsetTop;431 return window.scrollTo(0, c + b)432 }, a.parentHeight = function(a) {433 var b = offset() - getCommentOffset().top + 30,434 c = document.documentElement.clientHeight,435 d = c / 2;436 return postMessage(get("lv_comment").contentWindow, {437 e: "position",438 params: {439 top: b > 0 ? b : 0,440 center: b > 0 ? b + d : d,441 bottom: c + offset() - 100442 }443 })444 }, a.draw = function(a) {445 function b(a) {446 return set("lv_comment", document.getElementById(a))447 }448 if (a) {449 var c = serial("lv-comment");450 return a.style.cssText = "min-width:100%;width:100px;*width:100%;height:500px;overflow:hidden;border:0;z-index:124212;", a.id = c, document.getElementById("lv-container").appendChild(a), b(c)451 }452 }, a.resize = function(a, b) {453 var c = window.livereOptions,454 d = c && void 0 !== c.bottomMargin && !isNaN(Number(c.bottomMargin)) && c.bottomMargin >= 0 ? c.bottomMargin : 40;455 return get("lv_comment").style.height = b + d + "px"456 }, a.updateParams = function() {457 var a = document.querySelector('meta[property="og:description"]');458 if (a && a.content) return postMessage(get("lv_comment").contentWindow, {459 e: "updateParams",460 params: {461 description: a.content462 }463 })464 }, a.sendCustomLivereOption = function() {465 var a = window.livereOptions;466 return postMessage(get("lv_comment").contentWindow, {467 e: "getCustomLivereOption",468 params: {469 options: a470 }471 })472 }, a.insertTaboola = function(a) {473 if (a && void 0 !== a.status && !a.status) {474 var b = "taboola-livere";475 window._taboola = window._taboola || [], _taboola.push({476 article: "auto"477 }),478 function(a, b, c, d) {479 document.getElementById(d) || (a.async = 1, a.src = c, a.id = d, b.parentNode.insertBefore(a, b))480 }(document.createElement("script"), document.getElementsByTagName("script")[0], "//cdn.taboola.com/libtrc/" + a.accountId + "/loader.js", "tb_loader_script"), window.performance && "function" == typeof window.performance.mark && window.performance.mark("tbl_ic");481 var c = document,482 d = c.querySelector("#lv-container"),483 e = c.createElement("div");484 e.id = b, d.parentNode.insertBefore(e, d.nextSibling), window._taboola = window._taboola || [], _taboola.push({485 mode: "thumbnails-a",486 container: b,487 placement: a.placement,488 target_type: "mix"489 }), window._taboola = window._taboola || [], _taboola.push({490 flush: !0491 })492 }493 }, a.updateBlock = function(a) {494 return postMessage(get("lv_comment").contentWindow, {495 e: "updateBlock",496 params: a497 })498 }, a.requestAction = function(a) {499 return postMessage(get("lv_comment").contentWindow, {500 e: "requestAction",501 params: a502 })503 }, a.requestDeleteReply = function(a) {504 return postMessage(get("lv_comment").contentWindow, {505 e: "requestDeleteReply",506 params: a507 })508 }, a.modifyReplyInformation = function(a) {509 return postMessage(get("lv_comment").contentWindow, {510 e: "modifyReplyInformation",511 params: a512 })513 }, a.removeReply = function(a) {514 return postMessage(get("lv_comment").contentWindow, {515 e: "removeReply",516 params: a517 })518 }, a.emitPositionEvent = function(a) {519 var b = get("lv_comment");520 if (b) {521 var c = getPosition(b);522 return postMessage(b.contentWindow, {523 e: "scroll",524 params: {525 relativeX: c.x,526 relativeY: c.y,527 screenHeight: window.innerHeight528 }529 })530 }531 }, a532 }(), widget.sidebar = function() {533 var a = {};534 return a.open = function(a) {535 function b(a) {536 var b = get("lv_utils");537 if (b) return b.style.height = "100%", b.style.display = "block", postMessage(b.contentWindow, {538 e: "open",539 params: a540 })541 }542 function c(a) {543 var b = get("common.id"),544 c = "https://was.livere.me/sidebar/" + b;545 if (!a) return top.location.href = c;546 var d = concatURI(c, {547 uid: a.uid,548 member_group_seq: a.member_group_seq,549 path: a.path550 }, !0);551 return top.location.href = d552 }553 return (get("mobile") ? c : b).call(this, a)554 }, a.image = function(a) {555 var b = get("lv_utils");556 if (b) return b.style.display = "block", postMessage(b.contentWindow, {557 e: "image",558 params: a559 })560 }, a.draw = function(b) {561 function c(a) {562 return set("lv_utils", document.getElementById(a))563 }564 if (b) {565 var d = serial("lv-utils");566 return b.style.cssText = "width:100%;overflow:hidden;border:0;position:fixed;left:0;top:0;z-index:2147483647;display:none", b.style.height = document.documentElement.clientHeight + "px", b.id = d, document.getElementsByTagName("body")[0].appendChild(b), a.attachEvent(), c(d)567 }568 }, a.openCardReplyPopup = function(a) {569 var b = get("lv_utils");570 return b.style.display = "block", postMessage(b.contentWindow, {571 e: "openCardReplyPopup",572 params: a573 })574 }, a.closeCardReplyPopup = function(a) {575 get("lv_utils").style.display = "none"576 }, a.actionSuccess = function(a) {577 return postMessage(get("lv_utils").contentWindow, {578 e: "actionSuccess",579 params: a580 })581 }, a.deleteSuccess = function(a) {582 var b = get("lv_utils");583 return b.style.display = "none", postMessage(b.contentWindow, {584 e: "deleteSuccess",585 params: a586 })587 }, a.attachEvent = function() {588 addEventListener("resize", widget.sidebar.resize)589 }, a.resize = function() {590 var a = get("lv_utils"),591 b = document.documentElement.clientHeight;592 a.style.height = b + "px", postMessage(a.contentWindow, {593 e: "resize",594 params: {595 height: b596 }597 })598 }, a.close = function() {599 return get("lv_utils").style.display = "none", removeEventListener("resize", widget.sidebar.resize)600 }, a.getLoginData = function() {601 return postMessage(get("lv_utils").contentWindow, {602 e: "loginData"603 })604 }, a.getCurrentSessionData = function() {605 return postMessage(get("lv_utils").contentWindow, {606 e: "sessionData"607 })608 }, a609 }(), widget.oauth = function() {610 ! function(a, b) {611 var c, d = a.getElementsByTagName(b)[0];612 c = a.createElement(b), c.src = "https://api-city.livere.com/smartlogin", c.async = !0, d.parentNode.insertBefore(c, d)613 }(document, "script")614 }, config.previousVersion = function() {615 Array.prototype.indexOf || (Array.prototype.indexOf = function(a, b) {616 for (var c = b || 0, d = this.length; c < d; c++)617 if (this[c] === a) return c;618 return -1619 }),620 function() {621 var a = document.createStyleSheet(),622 b = function(b, c) {623 var d, e = document.all,624 f = e.length,625 g = [];626 for (a.addRule(b, "foo:bar"), d = 0; d < f && !("bar" === e[d].currentStyle.foo && (g.push(e[d]), g.length > c)); d += 1);627 return a.removeRule(0), g628 };629 document.querySelectorAll || document.querySelector || (document.querySelectorAll = function(a) {630 return b(a, 1 / 0)631 }, document.querySelector = function(a) {632 return b(a, 1)[0] || null633 })634 }(), "object" != typeof JSON && (JSON = {}),635 function() {636 function f(a) {637 return a < 10 ? "0" + a : a638 }639 function this_value() {640 return this.valueOf()641 }642 function quote(a) {643 return escapable.lastIndex = 0, escapable.test(a) ? '"' + a.replace(escapable, function(a) {644 var b = meta[a];645 return "string" == typeof b ? b : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)646 }) + '"' : '"' + a + '"'647 }648 function str(a, b) {649 var c, d, e, f, g, h = gap,650 i = b[a];651 switch (i && "object" == typeof i && "function" == typeof i.toJSON && (i = i.toJSON(a)), "function" == typeof rep && (i = rep.call(b, a, i)), typeof i) {652 case "string":653 return quote(i);654 case "number":655 return isFinite(i) ? String(i) : "null";656 case "boolean":657 case "null":658 return String(i);659 case "object":660 if (!i) return "null";661 if (gap += indent, g = [], "[object Array]" === Object.prototype.toString.apply(i)) {662 for (f = i.length, c = 0; c < f; c += 1) g[c] = str(c, i) || "null";663 return e = 0 === g.length ? "[]" : gap ? "[\n" + gap + g.join(",\n" + gap) + "\n" + h + "]" : "[" + g.join(",") + "]", gap = h, e664 }665 if (rep && "object" == typeof rep)666 for (f = rep.length, c = 0; c < f; c += 1) "string" == typeof rep[c] && (d = rep[c], (e = str(d, i)) && g.push(quote(d) + (gap ? ": " : ":") + e));667 else668 for (d in i) Object.prototype.hasOwnProperty.call(i, d) && (e = str(d, i)) && g.push(quote(d) + (gap ? ": " : ":") + e);669 return e = 0 === g.length ? "{}" : gap ? "{\n" + gap + g.join(",\n" + gap) + "\n" + h + "}" : "{" + g.join(",") + "}", gap = h, e670 }671 }672 "function" != typeof Date.prototype.toJSON && (Date.prototype.toJSON = function() {673 return isFinite(this.valueOf()) ? this.getUTCFullYear() + "-" + f(this.getUTCMonth() + 1) + "-" + f(this.getUTCDate()) + "T" + f(this.getUTCHours()) + ":" + f(this.getUTCMinutes()) + ":" + f(this.getUTCSeconds()) + "Z" : null674 }, Boolean.prototype.toJSON = this_value, Number.prototype.toJSON = this_value, String.prototype.toJSON = this_value);675 var cx, escapable, gap, indent, meta, rep;676 "function" != typeof JSON.stringify && (escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, meta = {677 "\b": "\\b",678 "\t": "\\t",679 "\n": "\\n",680 "\f": "\\f",681 "\r": "\\r",682 '"': '\\"',683 "\\": "\\\\"684 }, JSON.stringify = function(a, b, c) {685 var d;686 if (gap = "", indent = "", "number" == typeof c)687 for (d = 0; d < c; d += 1) indent += " ";688 else "string" == typeof c && (indent = c);689 if (rep = b, b && "function" != typeof b && ("object" != typeof b || "number" != typeof b.length)) throw new Error("JSON.stringify");690 return str("", {691 "": a692 })693 }), "function" != typeof JSON.parse && (cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, JSON.parse = function(text, reviver) {694 function walk(a, b) {695 var c, d, e = a[b];696 if (e && "object" == typeof e)697 for (c in e) Object.prototype.hasOwnProperty.call(e, c) && (d = walk(e, c), void 0 !== d ? e[c] = d : delete e[c]);698 return reviver.call(a, b, e)699 }700 var j;701 if (text = String(text), cx.lastIndex = 0, cx.test(text) && (text = text.replace(cx, function(a) {702 return "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)703 })), /^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) return j = eval("(" + text + ")"), "function" == typeof reviver ? walk({704 "": j705 }, "") : j;706 throw new SyntaxError("JSON.parse")707 })708 }(), window.atob = function(a) {709 a = String(a);710 var b, c = 0,711 d = [],712 e = 0,713 f = 0;714 if (a = a.replace(/\s/g, ""), a.length % 4 == 0 && (a = a.replace(/=+$/, "")), a.length % 4 == 1) throw Error("InvalidCharacterError");715 if (/[^+\/0-9A-Za-z]/.test(a)) throw Error("InvalidCharacterError");716 for (; c < a.length;) b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(c)), e = e << 6 | b, f += 6, 24 === f && (d.push(String.fromCharCode(e >> 16 & 255)), d.push(String.fromCharCode(e >> 8 & 255)), d.push(String.fromCharCode(255 & e)), f = 0, e = 0), c += 1;717 return 12 === f ? (e >>= 4, d.push(String.fromCharCode(255 & e))) : 18 === f && (e >>= 2, d.push(String.fromCharCode(e >> 8 & 255)), d.push(String.fromCharCode(255 & e))), d.join("")718 }, Object.keys || (Object.keys = function(a) {719 if (a !== Object(a)) throw new TypeError("Object.keys called on a non-object");720 var b, c = [];721 for (b in a) Object.prototype.hasOwnProperty.call(a, b) && c.push(b);722 return c723 })724 }, config.parse = function() {725 var a = document,726 b = a.querySelector("#lv-container"),727 c = window.livereOptions || {};728 if (b) {729 var d = a.querySelector('meta[property="og:image"]'),730 e = a.querySelector('meta[property="og:title"]'),731 f = a.querySelector('meta[property="og:url"]'),732 g = location.hash,733 h = g.match(/#highlight-comment=([0-9]{1,})/),734 i = {735 id: b.getAttribute("data-id"),736 refer: c.refer || window.refer || location.host + location.pathname737 };738 if (~location.host.indexOf("tistory.com") && hasProtocol(i.refer) && (i.refer = i.refer.replace(new RegExp("^https?://", "i"), "http://")), !isObjectPropertiesNull(i)) {739 i.uid = b.getAttribute("data-uid") || null, i.site = c.site || (f ? f.getAttribute("content") : location.href);740 var j = (e ? e.getAttribute("content") : document.title) || "Welcome to the black parade";741 return i.title = encodeURIComponent(escape(j)), i.titleLength = j.length, i.logo = d ? d.getAttribute("content") : null, i.highlightSeq = h ? h[h.length - 1] : null, i.redirectOrigin = c.redirectOrigin || null, i.preview = !!c.preview && c.preview, c.facebookPageId && c.facebookUploadUrl && (i.facebookPageId = c.facebookPageId, i.facebookUploadUrl = c.facebookUploadUrl), i742 }743 }744 };745 var options = window.livereOptions || {},746 scrollEventTarget = document.querySelector(options.scrollEventTargetSelector);747 return addEventListener("scroll", widget.comment.emitPositionEvent, scrollEventTarget), livere.reload = function() {748 var a, b, c = Object.keys(bound);749 for (a = 0; a < c.length; a++) {750 var d = c[a],751 e = bound[d];752 for (b = 0; b < e.length; b++) removeEventListener(d, e[b]);753 delete bound[d]754 }755 var f = document.querySelector("#lv-container"),756 g = get("lv_comment"),757 h = get("lv_utils");758 if (f && (g && f.removeChild(g), h && document.body.removeChild(h)), variables = {}, bound = {}, (window.livereOptions || {}).eagerLoading) return location.search.indexOf("redirectOrigin=true") > -1 ? widget.oauth.call(this) : livere.start.call(this);759 livere.loading.call(this)760 }, livere.get = get, livere.set = set, livere.refresh = function() {761 return widget.comment.state()762 }, livere.common = {763 utils: {764 open: function() {765 return widget.sidebar.open()766 },767 getLoginData: function() {768 return widget.sidebar.getLoginData()769 },770 getCurrentSessionData: function() {771 return widget.sidebar.getCurrentSessionData()772 }773 }774 }, livere775}();...

Full Screen

Full Screen

embed.dist.js

Source:embed.dist.js Github

copy

Full Screen

...497 livereLoggedIn: function() {498 return widget.sidebar.getLoginData()499 },500 cityLoggedIn: function() {501 return widget.sidebar.getCurrentSessionData()502 }503 },504 popup: {505 image: function(a, b) {506 return widget.sidebar.image(b)507 }508 },509 ad: {510 resize: function(a, b) {511 return widget.ad.resize(a, b.height)512 }513 }514 };515 return addEventListener("message", function(b) {516 if (b.data && "string" == typeof b.data && b.data.match(/^{.*}$/g)) {517 var c = JSON.parse(b.data),518 d = a[c.caller];519 return !!d && d[c.e](c.caller, c.params)520 }521 })522 }, livere.load = function(a) {523 var b = get("common");524 if (!(!a instanceof Array))525 for (var c = 0; c < a.length; c++) widget[a[c]] && widget[a[c]].draw(template(a[c], b))526 }, widget.check = function() {527 var a = {};528 return a.draw = function(a) {529 if (a) {530 var b = serial("lv-check");531 a.style.cssText = "min-width:100%;width:100px;*width:100%;height:250px;overflow:hidden;border:0;z-index:124212;",532 a.id = b, document.getElementById("lv-container").appendChild(a)533 }534 }, a535 }(), widget.comment = function() {536 var a = {};537 return a.state = function() {538 var a = get("lv_comment");539 if (a) return postMessage(a.contentWindow, {540 e: "state"541 })542 }, a.updateBlock = function(a) {543 return postMessage(get("lv_comment").contentWindow, {544 e: "updateBlock",545 params: a546 })547 }, a.highlight = function(a, b) {548 var c = get("lv_comment").offsetTop;549 return window.scrollTo(0, c + b)550 }, a.parentHeight = function(a) {551 var b = offset() - getCommentOffset().top + 30,552 c = document.documentElement.clientHeight,553 d = c / 2;554 return postMessage(get("lv_comment").contentWindow, {555 e: "position",556 params: {557 top: b > 0 ? b : 0,558 center: b > 0 ? b + d : d,559 bottom: c + offset() - 100560 }561 })562 }, a.draw = function(a) {563 function b(a) {564 return set("lv_comment", document.getElementById(a))565 }566 if (a) {567 var c = serial("lv-comment");568 return a.style.cssText =569 "min-width:100%;width:100px;*width:100%;height:500px;overflow:hidden;border:0;z-index:124212;", a.id = c,570 document.getElementById("lv-container").appendChild(a), b(c)571 }572 }, a.resize = function(a, b) {573 var c = window.livereOptions,574 d = c && void 0 !== c.bottomMargin && !isNaN(Number(c.bottomMargin)) && c.bottomMargin >= 0 ? c.bottomMargin :575 40;576 return get("lv_comment").style.height = b + d + "px"577 }, a.updateParams = function() {578 var a = document.querySelector('meta[property="og:description"]');579 if (a && a.content) return postMessage(get("lv_comment").contentWindow, {580 e: "updateParams",581 params: {582 description: a.content583 }584 })585 }, a.sendCustomLivereOption = function() {586 var a = window.livereOptions;587 return postMessage(get("lv_comment").contentWindow, {588 e: "getCustomLivereOption",589 params: {590 options: a591 }592 })593 }, a.insertTaboola = function(a) {594 if (a && void 0 !== a.status && !a.status) {595 var b = "taboola-livere";596 window._taboola = window._taboola || [], _taboola.push({597 article: "auto"598 }),599 function(a, b, c, d) {600 document.getElementById(d) || (a.async = 1, a.src = c, a.id = d, b.parentNode.insertBefore(a, b))601 }(document.createElement("script"), document.getElementsByTagName("script")[0], "//cdn.taboola.com/libtrc/" + a602 .accountId + "/loader.js", "tb_loader_script"), window.performance && "function" == typeof window.performance.mark &&603 window.performance.mark("tbl_ic");604 var c = document,605 d = c.querySelector("#lv-container"),606 e = c.createElement("div");607 e.id = b, d.parentNode.insertBefore(e, d.nextSibling), window._taboola = window._taboola || [], _taboola.push({608 mode: "thumbnails-a",609 container: b,610 placement: a.placement,611 target_type: "mix"612 }), window._taboola = window._taboola || [], _taboola.push({613 flush: !0614 })615 }616 }, a.updateBlock = function(a) {617 return postMessage(get("lv_comment").contentWindow, {618 e: "updateBlock",619 params: a620 })621 }, a.requestAction = function(a) {622 return postMessage(get("lv_comment").contentWindow, {623 e: "requestAction",624 params: a625 })626 }, a.requestDeleteReply = function(a) {627 return postMessage(get("lv_comment").contentWindow, {628 e: "requestDeleteReply",629 params: a630 })631 }, a.modifyReplyInformation = function(a) {632 return postMessage(get("lv_comment").contentWindow, {633 e: "modifyReplyInformation",634 params: a635 })636 }, a.removeReply = function(a) {637 return postMessage(get("lv_comment").contentWindow, {638 e: "removeReply",639 params: a640 })641 }, a.emitPositionEvent = function(a) {642 var b = get("lv_comment");643 if (b) {644 var c = getPosition(b);645 return postMessage(b.contentWindow, {646 e: "scroll",647 params: {648 relativeX: c.x,649 relativeY: c.y,650 screenHeight: window.innerHeight651 }652 })653 }654 }, a655 }(), widget.sidebar = function() {656 var a = {};657 return a.open = function(a) {658 function b(a) {659 var b = get("lv_utils");660 if (b) return b.style.height = "100%", b.style.display = "block", postMessage(b.contentWindow, {661 e: "open",662 params: a663 })664 }665666 function c(a) {667 var b = get("common.id"),668 c = LIVEREMEURL + "sidebar/" + b;669 if (!a) return top.location.href = c;670 var d = concatURI(c, {671 uid: a.uid,672 code: a.code,673 member_group_seq: a.member_group_seq,674 path: a.path,675 memberGroupSeq: a.member_group_seq,676 refer: window.livereOptions && window.livereOptions.refer || window.refer || location.host + location.pathname,677 mode: "mobile",678 type: a.target,679 uuid: uuid680 }, !0);681 return top.location.href = d682 }683 return (get("mobile") ? c : b).call(this, a)684 }, a.image = function(a) {685 var b = get("lv_utils");686 if (b) return b.style.display = "block", postMessage(b.contentWindow, {687 e: "image",688 params: a689 })690 }, a.draw = function(b) {691 function c(a) {692 return set("lv_utils", document.getElementById(a))693 }694 if (b) {695 var d = serial("lv-utils");696 return b.style.cssText =697 "width:100%;overflow:hidden;border:0;position:fixed;left:0;top:0;z-index:2147483647;display:none", b.style.height =698 document.documentElement.clientHeight + "px", b.id = d, document.getElementsByTagName("body")[0].appendChild(b),699 a.attachEvent(), c(d)700 }701 }, a.openCardReplyPopup = function(a) {702 var b = get("lv_utils");703 return b.style.display = "block", postMessage(b.contentWindow, {704 e: "openCardReplyPopup",705 params: a706 })707 }, a.closeCardReplyPopup = function(a) {708 get("lv_utils").style.display = "none"709 }, a.actionSuccess = function(a) {710 return postMessage(get("lv_utils").contentWindow, {711 e: "actionSuccess",712 params: a713 })714 }, a.deleteSuccess = function(a) {715 var b = get("lv_utils");716 return b.style.display = "none", postMessage(b.contentWindow, {717 e: "deleteSuccess",718 params: a719 })720 }, a.attachEvent = function() {721 addEventListener("resize", widget.sidebar.resize)722 }, a.resize = function() {723 var a = get("lv_utils"),724 b = document.documentElement.clientHeight;725 a.style.height = b + "px", postMessage(a.contentWindow, {726 e: "resize",727 params: {728 height: b729 }730 })731 }, a.close = function() {732 return get("lv_utils").style.display = "none", removeEventListener("resize", widget.sidebar.resize), postMessage(733 get("lv_comment").contentWindow, {734 e: "setCurrentFocus"735 })736 }, a.getLoginData = function() {737 return postMessage(get("lv_utils").contentWindow, {738 e: "loginData"739 })740 }, a.getCurrentSessionData = function() {741 return postMessage(get("lv_utils").contentWindow, {742 e: "sessionData"743 })744 }, a.notifyCountUpdate = function() {745 return postMessage(get("lv_comment").contentWindow, {746 e: "notifyCountUpdate"747 })748 }, a749 }(), widget.ad = function() {750 var a = {};751 return a.draw = function(a) {752 function b(a) {753 return set("lv_ad", document.getElementById(a))754 }755 if (a) {756 var c = serial("lv-ad");757 return a.style.cssText = "min-width:100%;width:100px;height:0px;overflow:visible;border:0;z-index:124212;", a.id =758 c, document.getElementById("lv-container").appendChild(a), b(c)759 }760 }, a.load = function() {761 var a = config.parse(),762 b = atob(a.uid).split("/"),763 c = +b[0],764 d = +b[1],765 e = document.querySelector('meta[property="og:url"]'),766 f = options.site || (e ? e.getAttribute("content") : location.href);767 widget.ad.draw(widget.ad.template("ad", {768 consumerSeq: c,769 livereSeq: d,770 isMobile: isMobile(),771 site: f772 }))773 }, a.template = function(a, b) {774 var c = document.createElement("iframe"),775 d = LIVEREMEURL + a;776 return c.title = "livereAd", c.scrolling = "no", c.async = !0, c.frameBorder = 0, c.allowTransparency = "true", c777 .src = d + "?consumerSeq=" + b.consumerSeq + "&livereSeq=" + b.livereSeq + "&isMobile=" + b.isMobile + "&site=" +778 b.site + "&uuid=" + uuid, c779 }, a.resize = function(a, b) {780 return get("lv_ad").style.height = b + "px"781 }, a782 }(), widget.oauth = function() {783 ! function(a, b) {784 var c, d = a.getElementsByTagName(b)[0];785 c = a.createElement(b), c.src = "https://api-city.livere.com/smartlogin", c.async = !0, d.parentNode.insertBefore(786 c, d)787 }(document, "script")788 }, config.previousVersion = function() {789 Array.prototype.indexOf || (Array.prototype.indexOf = function(a, b) {790 for (var c = b || 0, d = this.length; c < d; c++)791 if (this[c] === a) return c;792 return -1793 }),794 function() {795 var a = document.createStyleSheet(),796 b = function(b, c) {797 var d, e = document.all,798 f = e.length,799 g = [];800 for (a.addRule(b, "foo:bar"), d = 0; d < f && !("bar" === e[d].currentStyle.foo && (g.push(e[d]), g.length > c)); d +=801 1);802 return a.removeRule(0), g803 };804 document.querySelectorAll || document.querySelector || (document.querySelectorAll = function(a) {805 return b(a, 1 / 0)806 }, document.querySelector = function(a) {807 return b(a, 1)[0] || null808 })809 }(), "object" != typeof JSON && (JSON = {}),810 function() {811 function f(a) {812 return a < 10 ? "0" + a : a813 }814815 function this_value() {816 return this.valueOf()817 }818819 function quote(a) {820 return escapable.lastIndex = 0, escapable.test(a) ? '"' + a.replace(escapable, function(a) {821 var b = meta[a];822 return "string" == typeof b ? b : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)823 }) + '"' : '"' + a + '"'824 }825826 function str(a, b) {827 var c, d, e, f, g, h = gap,828 i = b[a];829 switch (i && "object" == typeof i && "function" == typeof i.toJSON && (i = i.toJSON(a)), "function" == typeof rep &&830 (i = rep.call(b, a, i)), typeof i) {831 case "string":832 return quote(i);833 case "number":834 return isFinite(i) ? String(i) : "null";835 case "boolean":836 case "null":837 return String(i);838 case "object":839 if (!i) return "null";840 if (gap += indent, g = [], "[object Array]" === Object.prototype.toString.apply(i)) {841 for (f = i.length, c = 0; c < f; c += 1) g[c] = str(c, i) || "null";842 return e = 0 === g.length ? "[]" : gap ? "[\n" + gap + g.join(",\n" + gap) + "\n" + h + "]" : "[" + g.join(843 ",") + "]", gap = h, e844 }845 if (rep && "object" == typeof rep)846 for (f = rep.length, c = 0; c < f; c += 1) "string" == typeof rep[c] && (d = rep[c], (e = str(d, i)) && g.push(847 quote(d) + (gap ? ": " : ":") + e));848 else849 for (d in i) Object.prototype.hasOwnProperty.call(i, d) && (e = str(d, i)) && g.push(quote(d) + (gap ? ": " :850 ":") + e);851 return e = 0 === g.length ? "{}" : gap ? "{\n" + gap + g.join(",\n" + gap) + "\n" + h + "}" : "{" + g.join(",") +852 "}", gap = h, e853 }854 }855 "function" != typeof Date.prototype.toJSON && (Date.prototype.toJSON = function() {856 return isFinite(this.valueOf()) ? this.getUTCFullYear() + "-" + f(this.getUTCMonth() + 1) + "-" + f(this.getUTCDate()) +857 "T" + f(this.getUTCHours()) + ":" + f(this.getUTCMinutes()) + ":" + f(this.getUTCSeconds()) + "Z" : null858 }, Boolean.prototype.toJSON = this_value, Number.prototype.toJSON = this_value, String.prototype.toJSON =859 this_value);860 var cx, escapable, gap, indent, meta, rep;861 "function" != typeof JSON.stringify && (escapable =862 /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,863 meta = {864 "\b": "\\b",865 "\t": "\\t",866 "\n": "\\n",867 "\f": "\\f",868 "\r": "\\r",869 '"': '\\"',870 "\\": "\\\\"871 }, JSON.stringify = function(a, b, c) {872 var d;873 if (gap = "", indent = "", "number" == typeof c)874 for (d = 0; d < c; d += 1) indent += " ";875 else "string" == typeof c && (indent = c);876 if (rep = b, b && "function" != typeof b && ("object" != typeof b || "number" != typeof b.length)) throw new Error(877 "JSON.stringify");878 return str("", {879 "": a880 })881 }), "function" != typeof JSON.parse && (cx =882 /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,883 JSON.parse = function(text, reviver) {884 function walk(a, b) {885 var c, d, e = a[b];886 if (e && "object" == typeof e)887 for (c in e) Object.prototype.hasOwnProperty.call(e, c) && (d = walk(e, c), void 0 !== d ? e[c] = d : delete e[888 c]);889 return reviver.call(a, b, e)890 }891 var j;892 if (text = String(text), cx.lastIndex = 0, cx.test(text) && (text = text.replace(cx, function(a) {893 return "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)894 })), /^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").replace(895 /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, "")))896 return j = eval("(" + text + ")"), "function" == typeof reviver ? walk({897 "": j898 }, "") : j;899 throw new SyntaxError("JSON.parse")900 })901 }(), window.atob = function(a) {902 a = String(a);903 var b, c = 0,904 d = [],905 e = 0,906 f = 0;907 if (a = a.replace(/\s/g, ""), a.length % 4 == 0 && (a = a.replace(/=+$/, "")), a.length % 4 == 1) throw Error(908 "InvalidCharacterError");909 if (/[^+\/0-9A-Za-z]/.test(a)) throw Error("InvalidCharacterError");910 for (; c < a.length;) b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(c)),911 e = e << 6 | b, f += 6, 24 === f && (d.push(String.fromCharCode(e >> 16 & 255)), d.push(String.fromCharCode(e >>912 8 & 255)), d.push(String.fromCharCode(255 & e)), f = 0, e = 0), c += 1;913 return 12 === f ? (e >>= 4, d.push(String.fromCharCode(255 & e))) : 18 === f && (e >>= 2, d.push(String.fromCharCode(914 e >> 8 & 255)), d.push(String.fromCharCode(255 & e))), d.join("")915 }, Object.keys || (Object.keys = function(a) {916 if (a !== Object(a)) throw new TypeError("Object.keys called on a non-object");917 var b, c = [];918 for (b in a) Object.prototype.hasOwnProperty.call(a, b) && c.push(b);919 return c920 })921 }, config.parse = function() {922 var a = document,923 b = a.querySelector("#lv-container"),924 c = window.livereOptions || {};925 if (b) {926 var d = a.querySelector('meta[property="og:image"]'),927 e = a.querySelector('meta[property="og:title"]'),928 f = a.querySelector('meta[property="og:url"]'),929 g = location.hash,930 h = g.match(/#highlight-comment=([0-9]{1,})/),931 i = {932 id: b.getAttribute("data-id"),933 refer: c.refer || window.refer || location.host + location.pathname934 };935 if (~location.host.indexOf("tistory.com") && hasProtocol(i.refer) && (i.refer = i.refer.replace(new RegExp(936 "^https?://", "i"), "http://")), !isObjectPropertiesNull(i)) {937 i.uid = b.getAttribute("data-uid") || null, i.site = c.site || (f ? f.getAttribute("content") : location.href);938 var j = (e ? e.getAttribute("content") : document.title) || "Welcome to the black parade";939 return i.title = encodeURIComponent(escape(j)), i.titleLength = j.length, i.logo = d ? d.getAttribute("content") :940 null, i.highlightSeq = h ? h[h.length - 1] : null, i.redirectOrigin = c.redirectOrigin || null, i.preview = !!c.preview &&941 c.preview, i942 }943 }944 };945 var options = window.livereOptions || {},946 scrollEventTarget = document.querySelector(options.scrollEventTargetSelector);947 return addEventListener("scroll", widget.comment.emitPositionEvent, scrollEventTarget), livere.reload = function() {948 var a, b, c = Object.keys(bound);949 for (a = 0; a < c.length; a++) {950 var d = c[a],951 e = bound[d];952 for (b = 0; b < e.length; b++) removeEventListener(d, e[b]);953 delete bound[d]954 }955 var f = document.querySelector("#lv-container"),956 g = get("lv_comment"),957 h = get("lv_utils");958 if (f && (g && f.removeChild(g), h && document.body.removeChild(h)), variables = {}, bound = {}, (window.livereOptions ||959 {}).eagerLoading) return location.search.indexOf("redirectOrigin=true") > -1 ? widget.oauth.call(this) : livere.start960 .call(this);961 livere.loading.call(this)962 }, livere.get = get, livere.set = set, livere.refresh = function() {963 return widget.comment.state()964 }, livere.common = {965 utils: {966 open: function() {967 return widget.sidebar.open()968 },969 getLoginData: function() {970 return widget.sidebar.getLoginData()971 },972 getCurrentSessionData: function() {973 return widget.sidebar.getCurrentSessionData()974 }975 }976 }, livere977}(); ...

Full Screen

Full Screen

emb.js

Source:emb.js Github

copy

Full Screen

...497 livereLoggedIn: function() {498 return widget.sidebar.getLoginData()499 },500 cityLoggedIn: function() {501 return widget.sidebar.getCurrentSessionData()502 }503 },504 popup: {505 image: function(a, b) {506 return widget.sidebar.image(b)507 }508 },509 ad: {510 resize: function(a, b) {511 return widget.ad.resize(a, b.height)512 }513 }514 };515 return addEventListener("message", function(b) {516 if (b.data && "string" == typeof b.data && b.data.match(/^{.*}$/g)) {517 var c = JSON.parse(b.data),518 d = a[c.caller];519 return !!d && d[c.e](c.caller, c.params)520 }521 })522 }, livere.load = function(a) {523 var b = get("common");524 if (!(!a instanceof Array))525 for (var c = 0; c < a.length; c++) widget[a[c]] && widget[a[c]].draw(template(a[c], b))526 }, widget.check = function() {527 var a = {};528 return a.draw = function(a) {529 if (a) {530 var b = serial("lv-check");531 a.style.cssText = "min-width:100%;width:100px;*width:100%;height:250px;overflow:hidden;border:0;z-index:124212;",532 a.id = b, document.getElementById("lv-container").appendChild(a)533 }534 }, a535 }(), widget.comment = function() {536 var a = {};537 return a.state = function() {538 var a = get("lv_comment");539 if (a) return postMessage(a.contentWindow, {540 e: "state"541 })542 }, a.updateBlock = function(a) {543 return postMessage(get("lv_comment").contentWindow, {544 e: "updateBlock",545 params: a546 })547 }, a.highlight = function(a, b) {548 var c = get("lv_comment").offsetTop;549 return window.scrollTo(0, c + b)550 }, a.parentHeight = function(a) {551 var b = offset() - getCommentOffset().top + 30,552 c = document.documentElement.clientHeight,553 d = c / 2;554 return postMessage(get("lv_comment").contentWindow, {555 e: "position",556 params: {557 top: b > 0 ? b : 0,558 center: b > 0 ? b + d : d,559 bottom: c + offset() - 100560 }561 })562 }, a.draw = function(a) {563 function b(a) {564 return set("lv_comment", document.getElementById(a))565 }566 if (a) {567 var c = serial("lv-comment");568 return a.style.cssText =569 "min-width:100%;width:100px;*width:100%;height:500px;overflow:hidden;border:0;z-index:124212;", a.id = c,570 document.getElementById("lv-container").appendChild(a), b(c)571 }572 }, a.resize = function(a, b) {573 var c = window.livereOptions,574 d = c && void 0 !== c.bottomMargin && !isNaN(Number(c.bottomMargin)) && c.bottomMargin >= 0 ? c.bottomMargin :575 40;576 return get("lv_comment").style.height = b + d + "px"577 }, a.updateParams = function() {578 var a = document.querySelector('meta[property="og:description"]');579 if (a && a.content) return postMessage(get("lv_comment").contentWindow, {580 e: "updateParams",581 params: {582 description: a.content583 }584 })585 }, a.sendCustomLivereOption = function() {586 var a = window.livereOptions;587 return postMessage(get("lv_comment").contentWindow, {588 e: "getCustomLivereOption",589 params: {590 options: a591 }592 })593 }, a.insertTaboola = function(a) {594 if (a && void 0 !== a.status && !a.status) {595 var b = "taboola-livere";596 window._taboola = window._taboola || [], _taboola.push({597 article: "auto"598 }),599 function(a, b, c, d) {600 document.getElementById(d) || (a.async = 1, a.src = c, a.id = d, b.parentNode.insertBefore(a, b))601 }(document.createElement("script"), document.getElementsByTagName("script")[0], "//cdn.taboola.com/libtrc/" + a602 .accountId + "/loader.js", "tb_loader_script"), window.performance && "function" == typeof window.performance.mark &&603 window.performance.mark("tbl_ic");604 var c = document,605 d = c.querySelector("#lv-container"),606 e = c.createElement("div");607 e.id = b, d.parentNode.insertBefore(e, d.nextSibling), window._taboola = window._taboola || [], _taboola.push({608 mode: "thumbnails-a",609 container: b,610 placement: a.placement,611 target_type: "mix"612 }), window._taboola = window._taboola || [], _taboola.push({613 flush: !0614 })615 }616 }, a.updateBlock = function(a) {617 return postMessage(get("lv_comment").contentWindow, {618 e: "updateBlock",619 params: a620 })621 }, a.requestAction = function(a) {622 return postMessage(get("lv_comment").contentWindow, {623 e: "requestAction",624 params: a625 })626 }, a.requestDeleteReply = function(a) {627 return postMessage(get("lv_comment").contentWindow, {628 e: "requestDeleteReply",629 params: a630 })631 }, a.modifyReplyInformation = function(a) {632 return postMessage(get("lv_comment").contentWindow, {633 e: "modifyReplyInformation",634 params: a635 })636 }, a.removeReply = function(a) {637 return postMessage(get("lv_comment").contentWindow, {638 e: "removeReply",639 params: a640 })641 }, a.emitPositionEvent = function(a) {642 var b = get("lv_comment");643 if (b) {644 var c = getPosition(b);645 return postMessage(b.contentWindow, {646 e: "scroll",647 params: {648 relativeX: c.x,649 relativeY: c.y,650 screenHeight: window.innerHeight651 }652 })653 }654 }, a655 }(), widget.sidebar = function() {656 var a = {};657 return a.open = function(a) {658 function b(a) {659 var b = get("lv_utils");660 if (b) return b.style.height = "100%", b.style.display = "block", postMessage(b.contentWindow, {661 e: "open",662 params: a663 })664 }665666 function c(a) {667 var b = get("common.id"),668 c = LIVEREMEURL + "sidebar/" + b;669 if (!a) return top.location.href = c;670 var d = concatURI(c, {671 uid: a.uid,672 code: a.code,673 member_group_seq: a.member_group_seq,674 path: a.path,675 memberGroupSeq: a.member_group_seq,676 refer: window.livereOptions && window.livereOptions.refer || window.refer || location.host + location.pathname,677 mode: "mobile",678 type: a.target,679 uuid: uuid680 }, !0);681 return top.location.href = d682 }683 return (get("mobile") ? c : b).call(this, a)684 }, a.image = function(a) {685 var b = get("lv_utils");686 if (b) return b.style.display = "block", postMessage(b.contentWindow, {687 e: "image",688 params: a689 })690 }, a.draw = function(b) {691 function c(a) {692 return set("lv_utils", document.getElementById(a))693 }694 if (b) {695 var d = serial("lv-utils");696 return b.style.cssText =697 "width:100%;overflow:hidden;border:0;position:fixed;left:0;top:0;z-index:2147483647;display:none", b.style.height =698 document.documentElement.clientHeight + "px", b.id = d, document.getElementsByTagName("body")[0].appendChild(b),699 a.attachEvent(), c(d)700 }701 }, a.openCardReplyPopup = function(a) {702 var b = get("lv_utils");703 return b.style.display = "block", postMessage(b.contentWindow, {704 e: "openCardReplyPopup",705 params: a706 })707 }, a.closeCardReplyPopup = function(a) {708 get("lv_utils").style.display = "none"709 }, a.actionSuccess = function(a) {710 return postMessage(get("lv_utils").contentWindow, {711 e: "actionSuccess",712 params: a713 })714 }, a.deleteSuccess = function(a) {715 var b = get("lv_utils");716 return b.style.display = "none", postMessage(b.contentWindow, {717 e: "deleteSuccess",718 params: a719 })720 }, a.attachEvent = function() {721 addEventListener("resize", widget.sidebar.resize)722 }, a.resize = function() {723 var a = get("lv_utils"),724 b = document.documentElement.clientHeight;725 a.style.height = b + "px", postMessage(a.contentWindow, {726 e: "resize",727 params: {728 height: b729 }730 })731 }, a.close = function() {732 return get("lv_utils").style.display = "none", removeEventListener("resize", widget.sidebar.resize), postMessage(733 get("lv_comment").contentWindow, {734 e: "setCurrentFocus"735 })736 }, a.getLoginData = function() {737 return postMessage(get("lv_utils").contentWindow, {738 e: "loginData"739 })740 }, a.getCurrentSessionData = function() {741 return postMessage(get("lv_utils").contentWindow, {742 e: "sessionData"743 })744 }, a.notifyCountUpdate = function() {745 return postMessage(get("lv_comment").contentWindow, {746 e: "notifyCountUpdate"747 })748 }, a749 }(), widget.ad = function() {750 var a = {};751 return a.draw = function(a) {752 function b(a) {753 return set("lv_ad", document.getElementById(a))754 }755 if (a) {756 var c = serial("lv-ad");757 return a.style.cssText = "min-width:100%;width:100px;height:0px;overflow:visible;border:0;z-index:124212;", a.id =758 c, document.getElementById("lv-container").appendChild(a), b(c)759 }760 }, a.load = function() {761 var a = config.parse(),762 b = atob(a.uid).split("/"),763 c = +b[0],764 d = +b[1],765 e = document.querySelector('meta[property="og:url"]'),766 f = options.site || (e ? e.getAttribute("content") : location.href);767 widget.ad.draw(widget.ad.template("ad", {768 consumerSeq: c,769 livereSeq: d,770 isMobile: isMobile(),771 site: f772 }))773 }, a.template = function(a, b) {774 var c = document.createElement("iframe"),775 d = LIVEREMEURL + a;776 return c.title = "livereAd", c.scrolling = "no", c.async = !0, c.frameBorder = 0, c.allowTransparency = "true", c777 .src = d + "?consumerSeq=" + b.consumerSeq + "&livereSeq=" + b.livereSeq + "&isMobile=" + b.isMobile + "&site=" +778 b.site + "&uuid=" + uuid, c779 }, a.resize = function(a, b) {780 return get("lv_ad").style.height = b + "px"781 }, a782 }(), widget.oauth = function() {783 ! function(a, b) {784 var c, d = a.getElementsByTagName(b)[0];785 c = a.createElement(b), c.src = "https://api-city.livere.com/smartlogin", c.async = !0, d.parentNode.insertBefore(786 c, d)787 }(document, "script")788 }, config.previousVersion = function() {789 Array.prototype.indexOf || (Array.prototype.indexOf = function(a, b) {790 for (var c = b || 0, d = this.length; c < d; c++)791 if (this[c] === a) return c;792 return -1793 }),794 function() {795 var a = document.createStyleSheet(),796 b = function(b, c) {797 var d, e = document.all,798 f = e.length,799 g = [];800 for (a.addRule(b, "foo:bar"), d = 0; d < f && !("bar" === e[d].currentStyle.foo && (g.push(e[d]), g.length > c)); d +=801 1);802 return a.removeRule(0), g803 };804 document.querySelectorAll || document.querySelector || (document.querySelectorAll = function(a) {805 return b(a, 1 / 0)806 }, document.querySelector = function(a) {807 return b(a, 1)[0] || null808 })809 }(), "object" != typeof JSON && (JSON = {}),810 function() {811 function f(a) {812 return a < 10 ? "0" + a : a813 }814815 function this_value() {816 return this.valueOf()817 }818819 function quote(a) {820 return escapable.lastIndex = 0, escapable.test(a) ? '"' + a.replace(escapable, function(a) {821 var b = meta[a];822 return "string" == typeof b ? b : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)823 }) + '"' : '"' + a + '"'824 }825826 function str(a, b) {827 var c, d, e, f, g, h = gap,828 i = b[a];829 switch (i && "object" == typeof i && "function" == typeof i.toJSON && (i = i.toJSON(a)), "function" == typeof rep &&830 (i = rep.call(b, a, i)), typeof i) {831 case "string":832 return quote(i);833 case "number":834 return isFinite(i) ? String(i) : "null";835 case "boolean":836 case "null":837 return String(i);838 case "object":839 if (!i) return "null";840 if (gap += indent, g = [], "[object Array]" === Object.prototype.toString.apply(i)) {841 for (f = i.length, c = 0; c < f; c += 1) g[c] = str(c, i) || "null";842 return e = 0 === g.length ? "[]" : gap ? "[\n" + gap + g.join(",\n" + gap) + "\n" + h + "]" : "[" + g.join(843 ",") + "]", gap = h, e844 }845 if (rep && "object" == typeof rep)846 for (f = rep.length, c = 0; c < f; c += 1) "string" == typeof rep[c] && (d = rep[c], (e = str(d, i)) && g.push(847 quote(d) + (gap ? ": " : ":") + e));848 else849 for (d in i) Object.prototype.hasOwnProperty.call(i, d) && (e = str(d, i)) && g.push(quote(d) + (gap ? ": " :850 ":") + e);851 return e = 0 === g.length ? "{}" : gap ? "{\n" + gap + g.join(",\n" + gap) + "\n" + h + "}" : "{" + g.join(",") +852 "}", gap = h, e853 }854 }855 "function" != typeof Date.prototype.toJSON && (Date.prototype.toJSON = function() {856 return isFinite(this.valueOf()) ? this.getUTCFullYear() + "-" + f(this.getUTCMonth() + 1) + "-" + f(this.getUTCDate()) +857 "T" + f(this.getUTCHours()) + ":" + f(this.getUTCMinutes()) + ":" + f(this.getUTCSeconds()) + "Z" : null858 }, Boolean.prototype.toJSON = this_value, Number.prototype.toJSON = this_value, String.prototype.toJSON =859 this_value);860 var cx, escapable, gap, indent, meta, rep;861 "function" != typeof JSON.stringify && (escapable =862 /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,863 meta = {864 "\b": "\\b",865 "\t": "\\t",866 "\n": "\\n",867 "\f": "\\f",868 "\r": "\\r",869 '"': '\\"',870 "\\": "\\\\"871 }, JSON.stringify = function(a, b, c) {872 var d;873 if (gap = "", indent = "", "number" == typeof c)874 for (d = 0; d < c; d += 1) indent += " ";875 else "string" == typeof c && (indent = c);876 if (rep = b, b && "function" != typeof b && ("object" != typeof b || "number" != typeof b.length)) throw new Error(877 "JSON.stringify");878 return str("", {879 "": a880 })881 }), "function" != typeof JSON.parse && (cx =882 /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,883 JSON.parse = function(text, reviver) {884 function walk(a, b) {885 var c, d, e = a[b];886 if (e && "object" == typeof e)887 for (c in e) Object.prototype.hasOwnProperty.call(e, c) && (d = walk(e, c), void 0 !== d ? e[c] = d : delete e[888 c]);889 return reviver.call(a, b, e)890 }891 var j;892 if (text = String(text), cx.lastIndex = 0, cx.test(text) && (text = text.replace(cx, function(a) {893 return "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)894 })), /^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").replace(895 /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, "")))896 return j = eval("(" + text + ")"), "function" == typeof reviver ? walk({897 "": j898 }, "") : j;899 throw new SyntaxError("JSON.parse")900 })901 }(), window.atob = function(a) {902 a = String(a);903 var b, c = 0,904 d = [],905 e = 0,906 f = 0;907 if (a = a.replace(/\s/g, ""), a.length % 4 == 0 && (a = a.replace(/=+$/, "")), a.length % 4 == 1) throw Error(908 "InvalidCharacterError");909 if (/[^+\/0-9A-Za-z]/.test(a)) throw Error("InvalidCharacterError");910 for (; c < a.length;) b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(c)),911 e = e << 6 | b, f += 6, 24 === f && (d.push(String.fromCharCode(e >> 16 & 255)), d.push(String.fromCharCode(e >>912 8 & 255)), d.push(String.fromCharCode(255 & e)), f = 0, e = 0), c += 1;913 return 12 === f ? (e >>= 4, d.push(String.fromCharCode(255 & e))) : 18 === f && (e >>= 2, d.push(String.fromCharCode(914 e >> 8 & 255)), d.push(String.fromCharCode(255 & e))), d.join("")915 }, Object.keys || (Object.keys = function(a) {916 if (a !== Object(a)) throw new TypeError("Object.keys called on a non-object");917 var b, c = [];918 for (b in a) Object.prototype.hasOwnProperty.call(a, b) && c.push(b);919 return c920 })921 }, config.parse = function() {922 var a = document,923 b = a.querySelector("#lv-container"),924 c = window.livereOptions || {};925 if (b) {926 var d = a.querySelector('meta[property="og:image"]'),927 e = a.querySelector('meta[property="og:title"]'),928 f = a.querySelector('meta[property="og:url"]'),929 g = location.hash,930 h = g.match(/#highlight-comment=([0-9]{1,})/),931 i = {932 id: b.getAttribute("data-id"),933 refer: c.refer || window.refer || location.host + location.pathname934 };935 if (~location.host.indexOf("tistory.com") && hasProtocol(i.refer) && (i.refer = i.refer.replace(new RegExp(936 "^https?://", "i"), "http://")), !isObjectPropertiesNull(i)) {937 i.uid = b.getAttribute("data-uid") || null, i.site = c.site || (f ? f.getAttribute("content") : location.href);938 var j = (e ? e.getAttribute("content") : document.title) || "Welcome to the black parade";939 return i.title = encodeURIComponent(escape(j)), i.titleLength = j.length, i.logo = d ? d.getAttribute("content") :940 null, i.highlightSeq = h ? h[h.length - 1] : null, i.redirectOrigin = c.redirectOrigin || null, i.preview = !!c.preview &&941 c.preview, i942 }943 }944 };945 var options = window.livereOptions || {},946 scrollEventTarget = document.querySelector(options.scrollEventTargetSelector);947 return addEventListener("scroll", widget.comment.emitPositionEvent, scrollEventTarget), livere.reload = function() {948 var a, b, c = Object.keys(bound);949 for (a = 0; a < c.length; a++) {950 var d = c[a],951 e = bound[d];952 for (b = 0; b < e.length; b++) removeEventListener(d, e[b]);953 delete bound[d]954 }955 var f = document.querySelector("#lv-container"),956 g = get("lv_comment"),957 h = get("lv_utils");958 if (f && (g && f.removeChild(g), h && document.body.removeChild(h)), variables = {}, bound = {}, (window.livereOptions ||959 {}).eagerLoading) return location.search.indexOf("redirectOrigin=true") > -1 ? widget.oauth.call(this) : livere.start960 .call(this);961 livere.loading.call(this)962 }, livere.get = get, livere.set = set, livere.refresh = function() {963 return widget.comment.state()964 }, livere.common = {965 utils: {966 open: function() {967 return widget.sidebar.open()968 },969 getLoginData: function() {970 return widget.sidebar.getLoginData()971 },972 getCurrentSessionData: function() {973 return widget.sidebar.getCurrentSessionData()974 }975 }976 }, livere977}(); ...

Full Screen

Full Screen

code.js

Source:code.js Github

copy

Full Screen

...171}172function getCurrentGraphData() {173 return getCurrentState().graph;174}175function getCurrentSessionData() {176 return window.appdata.sessionData;177}178function getNodeData(node_id) {179 return window.appdata.nodeData[getStorageValue("state_id")][node_id];180}181function updateStyle() {182 cy.style()183 .selector('node')184 .css({185 'height': getStorageValue('cy-node-height'),186 'width': getStorageValue('cy-node-width'),187 'font-size': getStorageValue('cy-font-size'),188 'content': function (n) {189 var data = n.data()190 return `${data.label}(${data.id})`191 },192 'shape': 'square',193 })194 .selector(getStorageValue('nonParamNodeSelector'))195 .css({196 197 'height': 200,198 'width': 200,199 'shape': 'diamond',200 })201 .selector('node[label="OUTPUT"]')202 .css({203 'height': 200,204 'width': 200,205 'shape': 'round-octagon',206 }).update();207 cy.nodes().leaves().style({208 'border-width': 20,209 'border-color': '#F00'210 });211 cy.nodes().roots().style({212 'border-width': 20,213 'border-color': '#0F0'214 });215}216const loadImage = (img) =>217 new Promise(resolve => {218 img.onload = () => resolve(img);219 img.onerror = () => resolve(img);220 });221function makeImage(src) {222 let img = new Image();223 img.src = src;224 return img;225}226//Preloading so we can get images sizes before rendering graph as well as cache node images227const buildNodeInfo = async (node, state) => {228 let promise_list = [];229 let ndata = node.data230 let component_ids = ndata.component_ids;231 var image_info = {}232 var component_info = {};233 var dgt_data = {}234 //Gather info on components235 getStorageValue('image_types').forEach(236 function (img_type) {237 image_info[img_type] = {};238 });239 for (i = 0; i < component_ids.length; i++) {240 if (component_ids[i] in state['data']) {241 comp = component_ids[i];242 comp_data = state['data'][comp];243 component_info[comp] = comp_data;244 dgt = comp_data['data_group_type']245 if (!(dgt in dgt_data)) {246 dgt_data[dgt] = [];247 }248 dgt_data[dgt].push(comp_data)249 }250 }251 //CREATES/LOAD NODE IMAGES252 getStorageValue('valid_data_group_types').forEach(function (item, index) {253 let dgt = item[0]254 let vt = item[1]255 if (dgt in dgt_data) {256 var compList = dgt_data[dgt]257 //GEN GRAPHS258 getStorageValue('image_types').forEach(function (image_type, index2) {259 let statsList = []260 compList.forEach(function (comp) {261 let stat_info = {262 data_group_type: comp['data_group_type'],263 component: comp.id,264 stats: comp['value'][`${vt}__stats`]265 };266 statsList.push(stat_info);267 });268 //FOR DIST IMAGE269 //TODO Fix repeat code270 if (image_type == 'dist') {271 var plot_stats = []272 for (let i = 0; i < statsList.length; i++) {273 plot_stat = { ...statsList[i].stats }274 plot_stat['xlabel'] = `${statsList[i].component} - ${vt}`;275 plot_stats.push(plot_stat)276 }277 let plotCan = plotNormDistMulti(plot_stats,278 Width = getStorageValue('cy-node-width'),279 Height = getStorageValue('cy-node-height'));280 image_info[image_type][[dgt, vt]] = {281 src: plotCan.node().toDataURL(),282 height: plotCan.height,283 width: plotCan.width284 }285 }286 else if (image_type == 'hist') {287 var plot_stats = []288 for (let i = 0; i < statsList.length; i++) {289 plot_stat = { ...statsList[i].stats }290 plot_stat['xlabel'] = `${statsList[i].component} - ${vt}`;291 plot_stats.push(plot_stat)292 }293 let plotCan = plotMultiHist(plot_stats,294 Width = getStorageValue('cy-node-width'),295 Height = getStorageValue('cy-node-height'));296 image_info[image_type][[dgt, vt]] = {297 src: plotCan.node().toDataURL(),298 height: plotCan.height,299 width: plotCan.width300 }301 }302 else if (image_type == 'session_stats') {303 let comps = []304 let labels = []305 for (let i = 0; i < statsList.length; i++) {306 comps.push(statsList[i].component)307 labels.push(`${statsList[i].component} - ${vt}`)308 }309 let valueName = `${vt}__stats`310 let plotCan = plotMultiStatsOverTime(311 labels,312 comps,313 valueName,314 window.appdata.stateData,315 getStorageValue('state_id'),316 Width = getStorageValue('cy-node-width'),317 Height = getStorageValue('cy-node-height'));318 image_info[image_type][[dgt, vt]] = {319 src: plotCan.node().toDataURL(),320 height: plotCan.height,321 width: plotCan.width322 }323 }324 });325 //INPUTS GET IMAGE326 if (dgt == 'INPUT') {327 image_info['heatmap'] = {}328 compList.forEach(function (comp) {329 var image_path = `${getSessionPath()}/${state.id}/images/${comp.id}_${vt}__image.jpg`330 var img = makeImage(image_path)331 image_info['heatmap'][[dgt, vt]] = img332 promise_list.push(loadImage(img))333 })334 }335 }336 });337 //Gather results before proceeding to update global data338 var results = await Promise.all(promise_list)339 window.appdata['nodeData'][state.id][ndata.id] = {340 'component_info': component_info,341 'image_info': image_info342 }343 return results344}345const buildAllNodes = async (stateData) => {346 await Promise.all(stateData.graph.nodes.map(347 async function (node) {348 return await buildNodeInfo(node, stateData)349 }));350}351async function renderNodeImages() {352 let stateData = getCurrentState()353 if (getStorageValue('node_render_type') == 'fixed') {354 updateStyle();355 }356 let current_image_type = getStorageValue('current_image_type');357 let current_data_group = getStorageValue('current_data_group');358 function updateBackground(stateData) {359 return Promise.all(cy.nodes().map(async function (node) {360 let ndata = node.data();361 if (!(ndata.id in window.appdata['nodeData'][stateData.id])) {362 console.log(window.appdata['nodeData'][stateData.id].length)363 return364 }365 let nodeData = getNodeData(ndata.id);366 if (typeof (nodeData) == 'undefined') {367 return368 }369 let image_info = getNodeData(ndata.id).image_info;370 let node_data_group = current_data_group371 let node_image_type = current_image_type372 if (ndata.label == 'INPUT') {373 node_image_type = 'heatmap'374 node_data_group = ['INPUT', 'tensor']375 }376 if (node_image_type in image_info377 && node_data_group in image_info[node_image_type]) {378 var img = image_info[node_image_type][node_data_group]379 style_update = {};380 if (getStorageValue('node_render_type') == 'fit') {381 style_update['height'] = img.height;382 style_update['width'] = img.width;383 }384 style_update['background-image'] = img.src385 node.style(style_update);386 }387 }));388 }389 if (stateData.id in window.appdata['nodeData']) {390 await updateBackground(stateData);391 } else {392 window.appdata['nodeData'][stateData.id] = {}393 await buildAllNodes(stateData);394 await updateBackground(stateData);395 }396}397// Removes intermediate node and 398// adds edge between the nodes source and target node399const skipNode = (node) => {400 try {401 sources = node.incomers().sources();402 targets = node.outgoers().targets();403 //TODO: consider cy.move instead404 new_edges = [];405 for (i = 0; i < sources.size(); i++) {406 for (j = 0; j < targets.size(); j++) {407 sid = sources[i].data().id;408 tid = targets[j].data().id409 new_edges.push({410 'group': 'edges', 'data': {411 'id': "" + sid + "_" + tid,412 'source': sid,413 'target': tid414 }415 });416 }417 }418 cy.add(new_edges);419 node.remove();420 } catch (e) {421 console.log("Node skipping issues found for " + node + " ");422 console.log(e)423 }424}425const removeNonParams = () => {426 var vals = getStorageValue('nonParamNodeSelector').split(',');427 for (var i in vals){428 cy.nodes(vals[i]).forEach(function (node) { skipNode(node); });429 }430}431const restoreElements = async () => {432 cy.elements().remove();433 cy.add(cy.orig_elements);434}435const backupInitState = () => {436 cy.orig_elements = cy.elements().clone();437}438function updateRadioButtons(eleData, currVal) {439 for (let [elName, elValue] of Object.entries(eleData)) {440 if (currVal == elValue) {441 document.getElementById(elName).checked = true;442 }443 }444}445function playImages(comp,typ){446 let stateIds = getCurrentSessionData()['state_ids'];447 var totalImages = stateIds.length;448 let canvasId = 'playerCanvas';449 let canvas = document.getElementById('playerCanvas');450 let ctx = canvas.getContext('2d');451 let first = true;452 const imageList= [];453 let imagesReady = 0454 for (let stateId of stateIds){455 456 const image = new Image();457 var image_path = `${getStatePathFor(stateId)}/images/${comp}_${typ}__image.jpg`;458 imageList.push(image);459 function prepimage(){460 if (first){461 first=false;462 canvas.width = image.naturalWidth;463 canvas.height = image.naturalHeight;464 }465 imagesReady++;466 }467 image.onload = prepimage;468 image.src = image_path;469 }470 471 var intervalms = Math.round((5/totalImages)*1000);472 document.getElementById('stateValue').max = totalImages-1473 var loaded =false;474 function drawImages(canvasId){475 if (!loaded && imagesReady>=totalImages){476 loaded = true;477 if(document.getElementById("playValue").value === "true"){478 document.getElementById("playButton").innerHTML="Stop";479 }480 else{481 document.getElementById("playButton").innerHTML="Play";482 }483 484 } else {485 let currentIdx =document.getElementById('stateValue').value;486 let img = imageList[currentIdx];487 ctx.drawImage(img,0,0);488 ctx.fillText("State Id: " + stateIds[currentIdx], 5, 15); 489 if (document.getElementById('playValue').value === "true"){490 currentIdx++;491 currentIdx = currentIdx % totalImages;492 }493 document.getElementById('stateValue').value = currentIdx494 }495 }496 497 498 let intervalId = setInterval(function() {499 drawImages(canvasId)},500 intervalms);501 return intervalId502}503function loadPlayer(comp,typ){504 $('#playerModal').modal('show');505 $('#stateRange').value = 0506 document.getElementById("playButton").innerHTML="Loading";507 document.getElementById("playValue").value = false;508 let intervalId = playImages(comp,typ);509 $('#playerModal').on('hidden.bs.modal', function (e) {510 clearInterval(intervalId) 511 })512}513function updateSideBar() {514 /*515 on node click update node info516 */517 // var node_data = this.data()518 var node_id = getStorageValue('selected_node_id')519 var node_label = getStorageValue('selected_node_label')520 if (node_id == -1){521 return 522 }523 var node_info = getNodeData(node_id)524 var component_info = node_info.component_info;525 var html_list = [];526 html_list.push(`<div class="row"><div class="col">`)527 html_list.push(`<h3>Node: ${node_label}(${node_id})</h3>`);528 head_html = `529 <table class="table table-sm">530 <tr><td>Operation: ${node_label}</td></tr>531 <tr><td>Components: <a title="click to stat details for components" type="button" data-toggle="collapse" data-target=".table-stats" aria-expanded="false"><u>${Object.keys(component_info).join(", ")}</u></a> </td></tr>532 </table>`;533 html_list.push(head_html);534 html_list.push('</div></div>')535 html_list.push(`<div class="row"><div class="col">`)536 var actionList = []537 for (let comp in component_info) {538 let stats = component_info[comp]['value']['tensor__stats']539 let component_html = [`540 <h4>${comp}: ${component_info[comp].data_group_type}</h4>541 <table class="table table-sm collapse table-stats">542 <tr><td>Type: </td><td><b>${component_info[comp].data_group_type}</b></td></tr>543 <tr><td>Shape: </td><td> (${component_info[comp].shape})</td></tr>`];544 component_html.push(`<ul>`);545 for (const stat in stats) {546 if (stat != 'histogram') {547 component_html.push(`<tr><td>${stat}:</td><td>${stats[stat]}</td></tr>`);548 }549 }550 component_html.push("</table>")551 // html_list.push('</div></div>')552 // html_list.push(`<div class="row"><div class="col">`)553 html_list.push(component_html.join("\n"));554 var image_path = `${getStatePath()}/images/${comp}_tensor__image.jpg`555 556 html_list.push(`<div class="image_holder link_div" id="play_${comp}_tensor"> <img class="side_data" src="${image_path}"/><p class="image_caption">Heatmap</p></div>`);557 558 actionList.push(function () { 559 document.getElementById(`play_${comp}_tensor`).addEventListener("click", function() {560 loadPlayer(comp,"tensor");561 });562 }) 563// Disabled for now 564 if (node_label != 'INPUT')565 {566 var image_path = `${getStatePath()}/images/${comp}_first_delta__image.jpg`567 html_list.push(`<div class="image_holder link_div" id="play_${comp}_first_delta"><img class="side_data" src="${image_path}"/><p class="image_caption">Delta Heatmap (total change in parameters)</p></div>`);568 actionList.push(function () { 569 document.getElementById(`play_${comp}_first_delta`).addEventListener("click", function() {570 loadPlayer(comp,"first_delta");571 });572 }); 573 }574 html_list.push(`<div class="image_holder"><div id="${comp}Canvas1"></div><p class="image_caption">Histogram of current state</p></div>`);575 html_list.push(`<div class="image_holder"><div id="${comp}StatsOverSessionCanvas1"></div><p class="image_caption" >Mean/Variance across session</p></div>`);576 actionList.push(function () {577 var Width = 500;578 var Height = 400;579 let canvas = plotHist(comp, stats, Width, Height);580 document.getElementById(`${comp}Canvas1`).appendChild(canvas.node());581 let valueName = 'tensor__stats'582 let canvas2 = plotStatsOverTime(583 `${comp} - ${valueName}`,584 comp,585 valueName,586 window.appdata.stateData,587 getStorageValue('state_id'),588 Width,589 Height)590 document.getElementById(`${comp}StatsOverSessionCanvas1`).appendChild(canvas2.node());591 })592 // html_list.push('</div></div>')593 // html_list.push(`<div class="row"><div class="col">`)594 if (component_info[comp].data_group_type == 'PARAM') {595 let stats = component_info[comp]['value']['grad__stats']596 let component_html = [`597 <h4>${comp}: PARAM Gradient</h4>598 <table class="table table-sm collapse table-stats">599 <tr><td>Type: </td><td><b>PARAM Gradient</b></td></tr>600 <tr><td>Shape:</td><td> (${component_info[comp].shape})</td></tr>`];601 component_html.push(`<ul>`);602 for (const stat in stats) {603 if (stat != 'histogram') {604 component_html.push(`<tr><td>${stat}:</td><td>${stats[stat]}</td></tr>`);605 }606 }607 component_html.push("</table>")608 html_list.push(component_html.join("\n"));609 html_list.push('</div></div>')610 html_list.push(`<div class="row"><div class="col">`)611 var image_path = `${getStatePath()}/images/${comp}_grad__image.jpg`612 html_list.push(`<div class="image_holder link_div" id="play_${comp}_grad"><div><img class="side_data" src="${image_path}"/></div><p class="image_caption">Heatmap</p></div>`);613 actionList.push(function () { 614 document.getElementById(`play_${comp}_grad`).addEventListener("click", function() {615 loadPlayer(comp,"grad");616 });617 }) 618 html_list.push(`<div class="image_holder"><div id="${comp}Canvas2"></div><p class="image_caption">Histogram of current state</p></div>`);619 html_list.push(`<div class="image_holder"><div id="${comp}StatsOverSessionCanvas2"></div><p class="image_caption">Mean/Variance across session</p></div>`);620 actionList.push(function () {621 var Width = 500;622 var Height = 400;623 let canvas = plotHist(comp, stats, Width, Height);624 document.getElementById(`${comp}Canvas2`).appendChild(canvas.node());625 let valueName = 'grad__stats'626 let canvas2 = plotStatsOverTime(627 `${comp} - ${valueName}`,628 comp,629 valueName,630 window.appdata.stateData,631 getStorageValue('state_id'),632 Width,633 Height)634 document.getElementById(`${comp}StatsOverSessionCanvas2`).appendChild(canvas2.node());635 })636 }637 html_list.push(`<hr/>`)638 }639 html_list.push('</div></div>')640 document.getElementById("node_info").innerHTML = html_list.join("");641 actionList.forEach(f => f())642}643// CREATE GRAPH644const initGraph = async () => {645 var cy = window.cy = cytoscape({646 container: document.getElementById('cy'),647 boxSelectionEnabled: false,648 autounselectify: true,649 style: cytoscape.stylesheet()650 .selector('node')651 .css({652 'background-fit': 'contain',653 'height': getStorageValue('cy-node-height'),654 'width': getStorageValue('cy-node-width'),655 'font-size': getStorageValue('cy-font-size'),656 'border-color': '#444',657 'border-width': 5,658 'border-opacity': 0.5,659 'color': '#333',660 'content': 'data(label)',661 'shape': 'square',662 'background-color': '#FFF',663 })664 .selector('.selected_node')665 .css({666 'border-width': 20,667 'border-color': "skyblue",668 'font-weight': 'bolder',669 670 'border-opacity': 1,671 // 'background-color': '#FFD',672 })673 .selector('edge')674 .css({675 "curve-style": "unbundled-bezier",676 "control-point-step-size": 0,677 'width': getStorageValue('cy-edge-size'),678 'target-arrow-shape': 'triangle',679 'opacity': 0.5,680 'line-color': '#666666',681 'target-arrow-color': '#555555'682 }),683 elements: getCurrentGraphData(),684 layout: getLayoutConfig('grid')685 });686 setTimeout(resize, 0);687 cy.ready(() => {688 changeStateByIdx(0);689 backupInitState();690 updateStyle();691 updateRadioButtons(imageTypeElData, getStorageValue('current_image_type'));692 updateRadioButtons(dataViewElData, getStorageValue('current_data_group').join("_"));693 });694 cy.on('click', 'node', function(evt){695 var node_data = this.data()696 cy.elements().removeClass("selected_node")697 this.addClass("selected_node")698 setStorageValue('selected_node_id',node_data.id)699 setStorageValue('selected_node_label',node_data.label)700 updateSideBar()701 });702 return cy;703}704const changeStateById = async (stateId) => {705 if (!(stateId in window.appdata['stateIdxLookup'])) {706 console.log("Invalid stateId " + stateId)707 return708 }709 else {710 return changeStateByIdx(window.appdata['stateIdxLookup'][stateId])711 }712}713function renderAdditionalInfo(){714 let addInfo = getCurrentState()['additional_info'];715 var html_list = [];716 if ( Object.keys(addInfo).length > 0){717 718 html_list.push(`<table class="table table-sm table-stats">`)719 for (const [key, value] of Object.entries(addInfo)) {720 html_list.push(`<tr><td>${key}:</td><td>${value.value}</td></tr>`);721 }722 html_list.push("</table>")723 }724 document.getElementById("additional_info").innerHTML = html_list.join("\n");725}726const changeStateByIdx = async (stateIdx) => {727 let stateIds = getCurrentSessionData()['state_ids']728 if (stateIdx < 0 || stateIdx >= stateIds.length) {729 console.log("Invalid stateIdx " + stateIdx)730 return731 }732 let newStateId = stateIds[stateIdx]733 setStorageValue('state_id', newStateId);734 setStorageValue('state_idx', stateIdx)735 await renderNodeImages();736 window.updateGraphSelected(newStateId)737 document.getElementById("state_info").innerHTML = `State ID: ${newStateId}, Session ID: ${PARAMS.session_id}`738 renderAdditionalInfo()739}740const initSession = async () => {741 localStorage.clear();742 window.appdata = {}743 window.appdata['stateData'] = {}744 window.appdata['nodeData'] = {}745 window.appdata['metricIdxLookup'] = {}746 window.appdata['stateIdxLookup'] = {}747 // Load Session Data748 let sessionData = window.appdata['sessionData'] = await $.getJSON(`${getSessionPath()}/session.json`)749 .then(async function (sessionData) { return sessionData; });750 // Lookup maps751 sessionData.metric_ids.forEach(function (d, i) {752 window.appdata['metricIdxLookup'][d] = i753 })754 // state id to state idx755 sessionData.state_ids.forEach(function (d, i) {756 window.appdata['stateIdxLookup'][d] = i757 })758 // Load State Data759 let allStateData = await Promise.all(sessionData.state_ids760 .map(async function (state_id) {761 return $.getJSON(`${getSessionPath()}/${state_id}/state.json`)762 }));763 await buildHeadPlot(getCurrentSessionData(),"loss");764 allStateData.map(function (stateData) {765 window.appdata['stateData'][stateData.id] = stateData766 })767 await initGraph();768 // TEMPORARY FIX (TODO): this is currently used to ensure 769 // the graph layout is formatted properly when the page is loaded.770 await sleep(1)771 await updateLayout("grid");772 await runPlot();773}774initSession()775//REGISTER FORM HANDLERS ----------------------------776document.getElementById("font_plus_btn").addEventListener("click", () => {777 current_font_size = getStorageValue('cy-font-size');...

Full Screen

Full Screen

app.js

Source:app.js Github

copy

Full Screen

...14app.use(session({secret: "its a secret!",15 saveUninitialized: false,16 resave: false}));17app.use(express.static(path.join(__dirname, '/public')));18function getCurrentSessionData(req) {19 // common code separated in a function20 let username = req.session.username;21 let name = req.session.name;22 let cart = req.session.cart;23 if (!cart) {24 cart = [];25 }26 return {name, username, cart};27}28app.get("/", function (req, res) {29 // home page30 let sessionData = getCurrentSessionData(req);31 sessionData['shoeList'] = shoeService.getShoeList();32 res.render("home.ejs", sessionData);33} );34app.get("/sign-in", function (req, res) {35 let sessionData = getCurrentSessionData(req);36 if(sessionData['username']) {37 // if already signed-in (from other tab)38 let message = {type: 'success', data: `You are already logged in as ${sessionData['username']}`};39 sessionData['shoeList'] = shoeService.getShoeList();40 sessionData['message'] = message;41 res.render("home.ejs", sessionData);42 } else {43 // Show sign-in page44 res.render("signin.ejs", sessionData);45 }46} );47app.post("/sign-in", function (req, res) {48 // User submitted username/password from the sign-in page49 let {username, password} = req.body;50 let userInfo = userService.validateUser(username, password);51 let sessionData = getCurrentSessionData(req);52 if(userInfo) {53 // User is authenticated54 req.session.username = userInfo.username;55 req.session.name = userInfo.name;56 sessionData['username'] = userInfo.username;57 sessionData['name'] = userInfo.name;58 sessionData['shoeList'] = shoeService.getShoeList();59 res.render("home.ejs", sessionData);60 } else {61 // Incorrect username or password62 sessionData['message'] = {type: 'error', data: 'Invalid username or password!'};63 res.render("signin.ejs", sessionData);64 }65} );66app.get("/logout", function(req, res) {67 // destory the existing session and empty the cart68 req.session.destroy();69 let shoeList = shoeService.getShoeList();70 res.render("home.ejs", {shoeList, cart: []});71});72app.get ("/details/:id", function (req, res) {73 // Specific shoe details requested74 let shoeId = req.params.id;75 let sessionData = getCurrentSessionData(req);76 let shoeInfo = shoeService.getShoeInfo(shoeId);77 if(shoeInfo) {78 // Requested shoe details found79 sessionData['shoeInfo'] = shoeInfo;80 res.render("details.ejs", sessionData);81 } else {82 // Shoe details not found (by changing the id in url)83 sessionData['shoeList'] = shoeService.getShoeList();84 sessionData['message'] = {type: 'error', data : `Details for shoe id ${shoeId} not found`};85 res.render("home.ejs", sessionData);86 }87});88app.get('/cart', function (req, res){89 // Show cart when cart icon on navbar is clicked90 let sessionData = getCurrentSessionData(req);91 res.render("cart.ejs", sessionData);92});93app.post("/addtocart/", function (req, res) {94 // Add item to cart95 let shoeId = req.body.shoeId;96 let size = req.body.size;97 let count = req.body.count;98 //Retrieve shoe details from its id99 let shoeInfo = shoeService.getShoeInfo(shoeId);100 if(shoeInfo) {101 // Details of the shoe being added are found102 cartService.addItemToCart(req, shoeInfo, size, count);103 let sessionData = getCurrentSessionData(req);104 sessionData['shoeInfo'] = shoeInfo;105 sessionData['message'] = {type: 'success', data : `The ${shoeInfo.name} added to cart successfully!`};106 res.render("details.ejs", sessionData);107 } else {108 // Shoe details not found (protect against page refresh for item that went out of stock on the previous addToCart)109 let sessionData = getCurrentSessionData(req);110 sessionData['shoeList'] = shoeService.getShoeList();111 sessionData['message'] = {type: 'error', data : `Details for shoe id ${shoeId} not found`};112 res.render("home.ejs", sessionData);113 }114});115app.post("/checkout", function(req, res) {116 // Checkout the entire cart117 let sessionData = getCurrentSessionData(req);118 if(!sessionData['username']) {119 // User hasn't logged-in. Redirect to login120 let message = {type: 'warning', data: `Please sign-in and then click the cart to proceed to checkout!`};121 sessionData['message'] = message;122 res.render("signin.ejs", sessionData);123 } else {124 // Add order to the user's account125 orderService.checkoutCart(sessionData);126 let orders = orderService.getUserOrders(sessionData['username']);127 sessionData['orders'] = orders;128 // Empty cart now129 req.session.cart = [];130 sessionData['cart'] = [];131 res.render("orders.ejs", sessionData);132 }133})134app.get('/myorders/', function (req, res) {135 // When singed-in user clicks 'My Orders' on navbar136 let username = req.session.username;137 let sessionData = getCurrentSessionData(req);138 if(username) {139 // Retrieve the orders for the current user140 let orders = orderService.getUserOrders(username);141 sessionData['orders'] = orders;142 res.render("orders.ejs", sessionData);143 } else {144 // If user logs out from one tab and requests myorders from other145 let message = {type: 'warning', data: `Please sign-in to see your orders!`};146 sessionData['message'] = message;147 res.render("signin.ejs", sessionData);148 }149});150app.get('/category/:type', function(req, res) {151 // Specific category requested, e.g., men, women, kids152 let category = req.params.type;153 let sessionData = getCurrentSessionData(req);154 let itemList = shoeService.getShoeByCategory(category);155 if(itemList) {156 // If the requested category found157 sessionData['itemList'] = itemList;158 res.render("category.ejs", sessionData);159 } else {160 // If the non-existing category is selected161 sessionData['shoeList'] = shoeService.getShoeList();162 sessionData['message'] = {type: 'error', data : `Selected category '${category}' not found`};163 res.render("home.ejs", sessionData);164 }165});166app.get("/api/shoelist", (req, res) => {167 // To retrieve json...

Full Screen

Full Screen

session-service.js

Source:session-service.js Github

copy

Full Screen

1import { SessionData, User, Device, DeviceStatusInfo, PartialSessionData } from '../models';2import { SessionRepository, UserRepository, DeviceRepository } from '../repositories';3/** @class */4class SessionService {5 /** @type {SessionRepository} */ _sessionRepository;6 /** @type {UserRepository} */ _userRepository;7 /** @type {DeviceRepository} */ _deviceRepository;8 /** @type {User} */ _user;9 /** @type {Device} */ _device;10 /** @type {string} */ _deviceId;11 /** @property {string} DeviceId - Currently known device ID */12 get DeviceId() { return this._deviceId; }13 set DeviceId(val) { this._deviceId = val; }14 15 constructor() {16 this._sessionRepository = new SessionRepository();17 this._userRepository = new UserRepository();18 this._deviceRepository = new DeviceRepository();19 }20 /**21 * @returns {Promise<User>} - The currently logged in user22 */23 async GetCurrentUser() {24 const s = await this._sessionRepository.GetPartialSessionData();25 26 if (!this._lastUser || !this._lastUser.name == s.UserName) {27 try {28 const users = await this._userRepository.Get(s.UserName);29 if (users && users[0])30 this._lastUser = users[0];31 else {32 this._lastUser = null;33 }34 }35 catch(err) {36 console.log(err);37 this._lastUser = null;38 }39 }40 return this._lastUser;41 }42 /**43 * Fetch the current device in use by this user44 * @returns {Promise<Device>}45 */46 async GetCurrentDevice() {47 if (!this._device || this._device.id != this._deviceId) {48 if (!this._deviceId)49 return null;50 try {51 const devices = await this._deviceRepository.GetDevice(this._deviceId);52 if (devices && devices[0])53 this._device = devices[0];54 else return null;55 } catch (error) {56 console.log(error);57 return null;58 }59 }60 return this._device;61 }62 /**63 * Fetch the device info for the device currently in use by the user64 * @returns {Promise<DeviceStatusInfo>}65 */66 async GetCurrentDeviceStatusInfo() {67 const u = await this.GetCurrentUser();68 if (u && u.id) {69 try {70 const info = await this._deviceRepository.GetDeviceStatusInfoForUser(u.id);71 if (!info || !info[0])72 return null;73 74 if (info[0].device && info[0].device.id != this._deviceId)75 this._deviceId = info[0].device.id;76 return info[0];77 } catch (err) {78 console.log(err);79 }80 }81 return null;82 }83 /**84 * @returns {Promise<SessionData>}85 */86 async GetCurrentSessionData() {87 const session = await this._sessionRepository.GetPartialSessionData();88 const device = await this.GetCurrentDevice();89 if (session && device) {90 const retVal = new SessionData();91 retVal.ApiServer = session.ApiServer;92 retVal.Database = session.Database;93 retVal.DeviceId = device.id;94 retVal.DeviceName = device.name;95 retVal.VehicleIdentificationNumber = device.vehicleIdentificationNumber;96 retVal.SessionId = session.SessionId;97 retVal.UserName = session.UserName;98 return retVal;99 }100 return null;101 }102}...

Full Screen

Full Screen

motion-app-service.js

Source:motion-app-service.js Github

copy

Full Screen

1import { SessionServiceSingleton } from '../services';2import { SessionData } from '../models';3import { MessageBus, AppConstants } from '../shared';4import { MobileDevice } from '../platform/dependencies';5import { DrivingStatusChangeProducer, DrivingStatus, GeotabGeolocationProducer } from '../producers';6class MotionAppService {7 /** @type {MobileDevice} */ _mobileDevice;8 /** @type {boolean} */ _autoLaunched;9 constructor() {10 this._autoLaunched = false;11 this._mobileDevice = new MobileDevice();12 13 MessageBus.subscribe(AppConstants.Messages.Start, this, this.OnStartup); 14 MessageBus.subscribe(AppConstants.Messages.PageLoad, this, this.OnPageLoad);15 }16 /**17 * Handles the Start message18 * @param {object} data19 * @returns {Promise<void>}20 */21 async OnStartup(data) {22 MessageBus.subscribe(AppConstants.Messages.Vehicle.StartedDriving, this, this._onDrivingStatusChanged);23 DrivingStatusChangeProducer.Start();24 }25 async _onDrivingStatusChanged(newDrivingStatus) {26 if (newDrivingStatus == DrivingStatus.Driving) {27 DrivingStatusChangeProducer.Stop();28 await this.AutoLaunchMotion();29 }30 }31 /**32 * Handles the Focus (PageLoad event)33 * @param {object} sessionData 34 * @returns {Promise<void>}35 */36 async OnPageLoad(data) {37 await this.AutoLaunchMotion();38 }39 /**40 * Auto launches the motion app if it hasn't been launched already41 * @param {SessionData} sessionData 42 * @returns {Promise<boolean>}43 */44 async AutoLaunchMotion() {45 if (!this._autoLaunched) {46 return await this.LaunchMotion();47 }48 49 }50 /**51 * Launches the MOTION app52 * @param {SessionData} sessionData 53 * @returns {Promise<boolean>} - True if operation successful54 */55 async LaunchMotion() {56 GeotabGeolocationProducer.Start();57 let sessionData = await SessionServiceSingleton.GetCurrentSessionData();58 if (sessionData != null) {59 let autoLaunched = await this._mobileDevice.LaunchMotion(sessionData);60 if (autoLaunched) 61 this._autoLaunched = true; 62 return autoLaunched;63 }64 65 return false;66 }67 /**68 * Launches the MOTION app on Geofence Trigger69 * @param {SessionData} sessionData 70 * @returns {Promise<boolean>} - True if operation successful71 */72 async LaunchMotionOnGeofenceTrigger() {73 let sessionData = await SessionServiceSingleton.GetCurrentSessionData();74 if (sessionData != null) {75 let isSuccessful = await this._mobileDevice.LaunchMotionOnGeofenceTrigger(sessionData);76 return isSuccessful;77 } 78 return false;79 }80}...

Full Screen

Full Screen

requests.js

Source:requests.js Github

copy

Full Screen

1import { API } from "aws-amplify";2import getCurrentSessionData from "../../lib/Auth/getCurrentUser";3export async function getRequestWithAuth(path, data = {}) {4 // const tokens = await getCurrentSessionData();5 // const jwtToken = tokens.getIdToken().getJwtToken();6 // data.headers = {7 // Authorization: jwtToken,8 // };9 return API.get("CoderSpaceApi", path, data);10}11export async function postRequestWithAuth(path, data) {12 // const tokens = await getCurrentSessionData();13 // const jwtToken = tokens.getIdToken().getJwtToken();14 // data.headers = {15 // Authorization: jwtToken,16 // };17 return API.post("CoderSpaceApi", path, data);18}19export async function patchRequestWithAuth(path, data) {20 // const tokens = await getCurrentSessionData();21 // const jwtToken = tokens.getIdToken().getJwtToken();22 // data.headers = {23 // Authorization: jwtToken,24 // };25 // console.log("data: ", data);26 return API.patch("CoderSpaceApi", path, data);27}28export async function filePostRequestWithAuth(path, data) {29 // const tokens = await getCurrentSessionData();30 // const jwtToken = tokens.getIdToken().getJwtToken();31 data.headers = {32 "Access-Control-Allow-Origin": "*",33 "Access-Control-Allow-Methods": "*",34 "Content-Type": "multipart/form-data",35 };36 return API.post("CoderSpaceApi", path, data);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('getCurrentSessionData', () => {2 return cy.window().then((win) => {3 return win.sessionStorage.getItem('sessionData');4 });5});6Cypress.Commands.add('setCurrentSessionData', (sessionData) => {7 return cy.window().then((win) => {8 win.sessionStorage.setItem('sessionData', sessionData);9 });10});11Cypress.Commands.add('clearCurrentSessionData', () => {12 return cy.window().then((win) => {13 win.sessionStorage.removeItem('sessionData');14 });15});16Cypress.Commands.add('getCurrentSessionData', () => {17 return cy.window().then((win) => {18 return win.sessionStorage.getItem('sessionData');19 });20});21Cypress.Commands.add('setCurrentSessionData', (sessionData) => {22 return cy.window().then((win) => {23 win.sessionStorage.setItem('sessionData', sessionData);24 });25});26Cypress.Commands.add('clearCurrentSessionData', () => {27 return cy.window().then((win) => {28 win.sessionStorage.removeItem('sessionData');29 });30});31Cypress.Commands.add('getCurrentSessionData', () => {32 return cy.window().then((win) => {33 return win.sessionStorage.getItem('sessionData');34 });35});36Cypress.Commands.add('setCurrentSessionData', (sessionData) => {37 return cy.window().then((win) => {38 win.sessionStorage.setItem('sessionData', sessionData);39 });40});41Cypress.Commands.add('clearCurrentSessionData', () => {42 return cy.window().then((win) => {43 win.sessionStorage.removeItem('sessionData');44 });45});46Cypress.Commands.add('getCurrentSessionData', () => {47 return cy.window().then((win) => {48 return win.sessionStorage.getItem('sessionData');49 });50});51Cypress.Commands.add('setCurrentSessionData', (session

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.getCurrentSessionData().then((data) => {2});3Cypress.Commands.add('getCurrentSessionData', () => {4 return cy.window().then((win) => {5 return win.sessionStorage.getItem('currentSession');6 });7});

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.getCurrentSessionData().then((sessionData) => {2});3cy.setSessionData('key', 'value').then((sessionData) => {4});5cy.clearSessionData().then((sessionData) => {6});7cy.clearSessionDataByKey('key').then((sessionData) => {8});9cy.getSessionDataByKey('key').then((sessionData) => {10});11cy.clearSessionData().then((sessionData) => {12});13cy.clearSessionDataByKey('key').then((sessionData) => {14});15cy.getSessionDataByKey('key').then((sessionData) => {16});17cy.clearSessionData().then((sessionData) => {18});19cy.clearSessionDataByKey('key').then((sessionData) => {20});21cy.getSessionDataByKey('key').then((sessionData) => {22});23cy.clearSessionData().then((sessionData) => {24});25cy.clearSessionDataByKey('key').then((sessionData) => {26});27cy.getSessionDataByKey('key').then((sessionData) => {28});29cy.clearSessionData().then((sessionData) => {30});

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.getCurrentSessionData().then((data) => {2 console.log(data);3});4cy.setSessionData({5});6cy.clearSessionData();7cy.clearAllSessionData();8cy.getSessionData('key').then((data) => {9 console.log(data);10});11cy.getAllSessionData().then((data) => {12 console.log(data);13});

Full Screen

Using AI Code Generation

copy

Full Screen

1const cypress = require('cypress');2const fs = require('fs');3cypress.run({4 config: {5 reporterOptions: {6 }7 }8}).then((results) => {9 const currentSessionData = cypress.getCurrentSessionData();10 const currentSessionDataJson = JSON.stringify(currentSessionData);11 console.log(currentSessionDataJson);12 fs.writeFileSync('./cypress/results/currentSessionData.json', currentSessionDataJson);13 console.log(results);14 process.exit(results.totalFailed);15});16describe('Test', () => {17 it('Test', () => {18 cy.get('.action-email').type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', () => {2 it('Test', () => {3 .then(() => {4 cy.getCurrentSessionData().then((sessionData) => {5 cy.log(sessionData);6 });7 });8 });9});10Cypress.Commands.add('getCurrentSessionData', () => {11 return cy.window().then((win) => {12 return win.sessionStorage.getItem('data');13 });14});15{16 "env": {17 }18}

Full Screen

Using AI Code Generation

copy

Full Screen

1var currentSessionData = Cypress.automation('getCurrentSessionData');2console.log(currentSessionData);3var currentSessionData = Cypress.automation('setCurrentSessionData', {foo: 'bar'});4console.log(currentSessionData);5var currentSessionData = Cypress.automation('clearCurrentSessionData');6console.log(currentSessionData);7var currentSessionData = Cypress.automation('clearCurrentSessionData');8console.log(currentSessionData);9var currentSessionData = Cypress.automation('clearCurrentSessionData');10console.log(currentSessionData);11var currentSessionData = Cypress.automation('clearCurrentSessionData');12console.log(currentSessionData);13var currentSessionData = Cypress.automation('clearCurrentSessionData');14console.log(currentSessionData);15var currentSessionData = Cypress.automation('clearCurrentSessionData');16console.log(currentSessionData);17var currentSessionData = Cypress.automation('clearCurrentSessionData');18console.log(currentSessionData);19var currentSessionData = Cypress.automation('clearCurrentSessionData');20console.log(currentSessionData);21var currentSessionData = Cypress.automation('clearCurrentSessionData');22console.log(currentSessionData);

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful