<commit_before>/*global JsonFx, JsonML, JSON, jQuery */
/*
	JsonFx_Bindings.js
	dynamic behavior binding support

	Created: 2006-11-11-1759
	Modified: 2009-02-28-1047

	Copyright (c)2006-2009 Stephen M. McKamey
	Distributed under an open-source license: http://jsonfx.net/license
*/

/* namespace JsonFx */
if ("undefined" === typeof window.JsonFx) {
	window.JsonFx = {};
}
/* namespace JsonFx.UI */
if ("undefined" === typeof JsonFx.UI) {
	JsonFx.UI = {};
}

/* dependency checks --------------------------------------------*/

if ("undefined" === typeof window.JSON) {
	throw new Error("JsonFx_Bindings.js requires json2.js");
}

if ("undefined" === typeof JsonFx.jsonReviver) {
	/*object*/ JsonFx.jsonReviver = function(/*string*/ key, /*object*/ value) {
		var a;
		if ("string" === typeof value) {
			a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
			if (a) {
				return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
			}
		}
		return value;
	};
}

/* singleton JsonFx.Bindings */
JsonFx.Bindings = function() {

	/*object*/ var b = this;
	/*bool*/ var jQ = ("undefined" !== typeof jQuery);
	/*const string*/ var BIND = 1, UNBIND = 2;

	/*
		the structure of bindings and the implementation of add, bind, and unbind fork on presence of jQuery.
		if jQuery is present before JsonFx.Bindings, then the selector implementation is delegated to jQuery.
		otherwise a simple selector lookup structure is built to very specifically allow lookups without
		a lot of iterations.
	*/
	/*Dictionary<string,object>*/ var bindings = jQ ? [] : {};

	/*RegExp*/ var re = /^\s*([\w\-]*|[*])(?:#([\w\-]+)|\.([\w\-]+))?(?:#([\w\-]+)|\.([\w\-]+))?\s*$/;

	/*void*/ b.add = jQ ?
		// jQuery JsonFx.Bindings.add implementation
		function(/*string*/ selector, /*function(elem)*/ bind, /*function(elem)*/ unbind) {
			if (typeof bind !== "function") {
				bind = null;
			}
			if (typeof unbind !== "function") {
				unbind = null;
			}
			if (!selector || (!bind && !unbind)) {
				return;
			}

			var binding = { selector: selector };
			binding[BIND] = bind;
			binding[UNBIND] = unbind;
			bindings.push(binding);
		} :
		// simple JsonFx.Bindings.add implementation
		function(/*string*/ selector, /*function(elem)*/ bind, /*function(elem)*/ unbind) {
			if (typeof bind !== "function") {
				bind = null;
			}
			if (typeof unbind !== "function") {
				unbind = null;
			}
			if (!selector || (!bind && !unbind)) {
				return;
			}

			var s = selector instanceof Array ?
				selector :
				String(selector).split(',');
			while (s.length > 1) {
				b.add(s.shift(), bind, unbind);
			}
			selector = s.shift();

			s = re.exec(selector);
			if (!s) {
				// http://www.w3.org/TR/css3-selectors/#simple-selectors
				throw new Error("JsonFx.Bindings only supports simple tag, class, and id selectors. Selector: \""+selector+"\"");
			}

			s = {
				tag: (s[1]||"*").toLowerCase(),
				css: (s[3]||s[5]||"*"),
				id: (s[2]||s[4]||"")
			};

	// TODO: add ability to bind on ID, className, tagName or any combination
	// determine how to most efficiently store binding references for arbitrary combinations

			if (s.id) {
				throw new Error("JsonFx.Bindings does not yet support tag selectors. Selector: \""+selector+"\"");
			} else {
				if ("undefined" === typeof bindings[s.tag]) {
					/*object*/ bindings[s.tag] = {};
				} else if (bindings[s.tag][s.css]) {
					throw new Error("A binding for "+selector+" has already been registered.");
				}

				/*object*/ bindings[s.tag][s.css] = {};
				bindings[s.tag][s.css][BIND] = bind;
				bindings[s.tag][s.css][UNBIND] = unbind;
			}
		};

	/*deprecated*/
	/*void*/ b.register = function(/*string*/ tag, /*string*/ css, /*function(elem)*/ bind, /*function(elem)*/ unbind) {
		b.add(tag+'.'+css, bind, unbind);
	};

	/*DOM*/ var performOne = jQ ?
		// jQuery performOne implementation
		function(/*DOM*/ elem, /*actionKey*/ a) {
			for (var i=0; i<bindings.length; i++) {
				if (bindings[i][a]) {
					var action = bindings[i][a];
					jQuery(elem).filter(bindings[i].selector).each(
						function() {
							try {
								elem = action(this) || this;
							} catch (ex) {
								window.alert("Error binding "+bindings[i].selector+":\n\n\""+ex.message+"\"");
							}
						});
				}
			}
			return elem;
		} :
		// simple performOne implementation
		function(/*DOM*/ elem, /*actionKey*/ a) {

// TODO: add ability to bind on ID, className, tagName or any combination
// ultimately this means being able to grab an arbitrary element and determine
// which if any bindings need to be performed.

			function bindSet(/*object*/ binds, /*string*/ css) {
				if (binds && binds[css] && binds[css][a]) {
					try {
						// perform action on element and
						// allow binding to replace element
						elem = binds[css][a](elem) || elem;
					} catch (ex) {
						window.alert("Error binding "+elem.tagName+"."+css+":\n\n\""+ex.message+"\"");
					}
				}
			}

			if (elem && elem.tagName) {

				// only perform on registered tags
				var tag = elem.tagName.toLowerCase();
				var allBinds = bindings["*"];
				var tagBinds = bindings[tag];

				if (tagBinds || allBinds) {

					bindSet(tagBinds, "*");
					bindSet(allBinds, "*");

					if (elem.className) {
						// for each css class in elem
						var classes = elem.className.split(/\s+/);
						for (var i=0; i<classes.length; i++) {
							var css = classes[i];
							bindSet(tagBinds, css);
							bindSet(allBinds, css);
						}
					}
				}
			}
			return elem;
		};

	// perform a binding action on all child elements
	/*void*/ var perform = jQ ?
		// jQuery perform implementation
		function(/*DOM*/ root, /*actionKey*/ a) {
			root = jQuery(root);
			for (var i=0; i<bindings.length; i++) {
				if (bindings[i][a]) {
					var action = bindings[i][a];
					root.find(bindings[i].selector).each(
						function() {
							try {
								var elem = action(this) || this;
								if (elem !== this) {
									this.parentNode.replaceChild(elem, this);
								}
							} catch (ex) {
								window.alert("Error binding "+bindings[i].selector+":\n\n\""+ex.message+"\"");
							}
						});
				}
			}
		} :
		// simple perform implementation
		function(/*DOM*/ root, /*actionKey*/ a) {

	// TODO: add ability to bind on ID, className, tagName or any combination
	// determine how to most efficiently select the smallest set of eligible elements

			/*create a closure for replacement*/
			function queueReplacer(newer, older) {
				window.setTimeout(function() {
					if (older && older.parentNode) {
						older.parentNode.replaceChild(newer, older);
					}
					// free references
					newer = older = null;
				}, 0);
			}

			function bindTagSet(/*string*/ tag) {
				// for each element in root with tagName
				var elems = root.getElementsByTagName(tag);
				for (var i=0; i<elems.length; i++) {
					// perform action on element and
					// allow binding to replace element
					var replace = performOne(elems[i], a);
					if (replace !== elems[i] && elems[i].parentNode) {
						// queue up replacement at the end so as not to disrupt the list
						queueReplacer(replace, elems[i]);
					}
				}
			}

			if (root && root.getElementsByTagName) {
				if (bindings["*"]) {
					// if star rule, then must apply to all
					bindTagSet("*");
				} else {
					// only apply to tags with rules
					for (var tag in bindings) {
						if (tag !== "*" && bindings.hasOwnProperty(tag)) {
							bindTagSet(tag);
						}
					}
				}
			}
		};

	/*DOM*/ bindOne = function(/*DOM*/ elem) {
		return performOne(elem, BIND);
	};

	// use bindOne as the default JBST filter
	if ("undefined" !== typeof JsonML && JsonML.BST) {
		if ("function" !== typeof JsonML.BST.filter) {
			JsonML.BST.filter = bindOne;
		} else {
			JsonML.BST.filter = (function() {
				var jbstFilter = JsonML.BST.filter;
				return function(/*DOM*/ elem) {
					elem = jbstFilter(elem);
					return elem && bindOne(elem);
				};
			})();
		}
	}

	// bind
	/*void*/ b.bind = function(/*DOM*/ root) {
		if (!isFinite(root.nodeType)) {
			root = null;
		}

		perform(root || document.body, BIND);
	};

	// unbind
	/*void*/ b.unbind = function(/*DOM*/ root) {
		if (!isFinite(root.nodeType)) {
			root = null;
		}

		perform(root || document.body, UNBIND);
	};

	// register bind events
	if (typeof jQuery !== "undefined") {
		jQuery(b.bind);
		jQuery(window).bind("unload", b.unbind);
	} else if (window.addEventListener) {
		//DOM Level 2 model for binding events
		window.addEventListener("load", b.bind, false);
		window.addEventListener("unload", b.unbind, false);
	} else if (window.attachEvent) {
		//IE model for binding events
		window.attachEvent("onload", b.bind);
		window.attachEvent("onunload", b.unbind);
	} else {
		//DOM Level 0 model for binding events
		var onload = window.onload;
		window.onload =
			("function" === typeof onload) ?
			function(/*Event*/ evt) { b.bind(evt); return onload(evt); } :
			b.bind;

		var onunload = window.onunload;
		window.onunload =
			("function" === typeof onunload) ?
			function(/*Event*/ evt) { b.unbind(evt); return onunload(evt); } :
			b.unbind;
	}
};

// doing instead of anonymous fn for JSLint compatibility
// instantiate only one, destroying the constructor
JsonFx.Bindings = new JsonFx.Bindings();
<commit_msg>- removed dormant JSON code<commit_after>/*global JsonFx, JsonML, jQuery */
/*
	JsonFx_Bindings.js
	dynamic behavior binding support

	Created: 2006-11-11-1759
	Modified: 2009-02-28-1345

	Copyright (c)2006-2009 Stephen M. McKamey
	Distributed under an open-source license: http://jsonfx.net/license
*/

/* namespace JsonFx */
if ("undefined" === typeof window.JsonFx) {
	window.JsonFx = {};
}
/* namespace JsonFx.UI */
if ("undefined" === typeof JsonFx.UI) {
	JsonFx.UI = {};
}

/* dependency checks --------------------------------------------*/

/* singleton JsonFx.Bindings */
JsonFx.Bindings = function() {

	/*object*/ var b = this;
	/*bool*/ var jQ = ("undefined" !== typeof jQuery);
	/*const string*/ var BIND = 1, UNBIND = 2;

	/*
		the structure of bindings and the implementation of add, bind, and unbind fork on presence of jQuery.
		if jQuery is present before JsonFx.Bindings, then the selector implementation is delegated to jQuery.
		otherwise a simple selector lookup structure is built to very specifically allow lookups without
		a lot of iterations.
	*/
	/*Dictionary<string,object>*/ var bindings = jQ ? [] : {};

	/*RegExp*/ var re = /^\s*([\w\-]*|[*])(?:#([\w\-]+)|\.([\w\-]+))?(?:#([\w\-]+)|\.([\w\-]+))?\s*$/;

	/*void*/ b.add = jQ ?
		// jQuery JsonFx.Bindings.add implementation
		function(/*string*/ selector, /*function(elem)*/ bind, /*function(elem)*/ unbind) {
			if (typeof bind !== "function") {
				bind = null;
			}
			if (typeof unbind !== "function") {
				unbind = null;
			}
			if (!selector || (!bind && !unbind)) {
				return;
			}

			var binding = { selector: selector };
			binding[BIND] = bind;
			binding[UNBIND] = unbind;
			bindings.push(binding);
		} :
		// simple JsonFx.Bindings.add implementation
		function(/*string*/ selector, /*function(elem)*/ bind, /*function(elem)*/ unbind) {
			if (typeof bind !== "function") {
				bind = null;
			}
			if (typeof unbind !== "function") {
				unbind = null;
			}
			if (!selector || (!bind && !unbind)) {
				return;
			}

			var s = selector instanceof Array ?
				selector :
				String(selector).split(',');
			while (s.length > 1) {
				b.add(s.shift(), bind, unbind);
			}
			selector = s.shift();

			s = re.exec(selector);
			if (!s) {
				// http://www.w3.org/TR/css3-selectors/#simple-selectors
				throw new Error("JsonFx.Bindings only supports simple tag, class, and id selectors. Selector: \""+selector+"\"");
			}

			s = {
				tag: (s[1]||"*").toLowerCase(),
				css: (s[3]||s[5]||"*"),
				id: (s[2]||s[4]||"")
			};

	// TODO: add ability to bind on ID, className, tagName or any combination
	// determine how to most efficiently store binding references for arbitrary combinations

			if (s.id) {
				throw new Error("JsonFx.Bindings does not yet support tag selectors. Selector: \""+selector+"\"");
			} else {
				if ("undefined" === typeof bindings[s.tag]) {
					/*object*/ bindings[s.tag] = {};
				} else if (bindings[s.tag][s.css]) {
					throw new Error("A binding for "+selector+" has already been registered.");
				}

				/*object*/ bindings[s.tag][s.css] = {};
				bindings[s.tag][s.css][BIND] = bind;
				bindings[s.tag][s.css][UNBIND] = unbind;
			}
		};

	/*deprecated*/
	/*void*/ b.register = function(/*string*/ tag, /*string*/ css, /*function(elem)*/ bind, /*function(elem)*/ unbind) {
		b.add(tag+'.'+css, bind, unbind);
	};

	/*DOM*/ var performOne = jQ ?
		// jQuery performOne implementation
		function(/*DOM*/ elem, /*actionKey*/ a) {
			for (var i=0; i<bindings.length; i++) {
				if (bindings[i][a]) {
					var action = bindings[i][a];
					jQuery(elem).filter(bindings[i].selector).each(
						function() {
							try {
								elem = action(this) || this;
							} catch (ex) {
								window.alert("Error binding "+bindings[i].selector+":\n\n\""+ex.message+"\"");
							}
						});
				}
			}
			return elem;
		} :
		// simple performOne implementation
		function(/*DOM*/ elem, /*actionKey*/ a) {

// TODO: add ability to bind on ID, className, tagName or any combination
// ultimately this means being able to grab an arbitrary element and determine
// which if any bindings need to be performed.

			function bindSet(/*object*/ binds, /*string*/ css) {
				if (binds && binds[css] && binds[css][a]) {
					try {
						// perform action on element and
						// allow binding to replace element
						elem = binds[css][a](elem) || elem;
					} catch (ex) {
						window.alert("Error binding "+elem.tagName+"."+css+":\n\n\""+ex.message+"\"");
					}
				}
			}

			if (elem && elem.tagName) {

				// only perform on registered tags
				var tag = elem.tagName.toLowerCase();
				var allBinds = bindings["*"];
				var tagBinds = bindings[tag];

				if (tagBinds || allBinds) {

					bindSet(tagBinds, "*");
					bindSet(allBinds, "*");

					if (elem.className) {
						// for each css class in elem
						var classes = elem.className.split(/\s+/);
						for (var i=0; i<classes.length; i++) {
							var css = classes[i];
							bindSet(tagBinds, css);
							bindSet(allBinds, css);
						}
					}
				}
			}
			return elem;
		};

	// perform a binding action on all child elements
	/*void*/ var perform = jQ ?
		// jQuery perform implementation
		function(/*DOM*/ root, /*actionKey*/ a) {
			root = jQuery(root);
			for (var i=0; i<bindings.length; i++) {
				if (bindings[i][a]) {
					var action = bindings[i][a];
					root.find(bindings[i].selector).each(
						function() {
							try {
								var elem = action(this) || this;
								if (elem !== this) {
									this.parentNode.replaceChild(elem, this);
								}
							} catch (ex) {
								window.alert("Error binding "+bindings[i].selector+":\n\n\""+ex.message+"\"");
							}
						});
				}
			}
		} :
		// simple perform implementation
		function(/*DOM*/ root, /*actionKey*/ a) {

	// TODO: add ability to bind on ID, className, tagName or any combination
	// determine how to most efficiently select the smallest set of eligible elements

			/*create a closure for replacement*/
			function queueReplacer(newer, older) {
				window.setTimeout(function() {
					if (older && older.parentNode) {
						older.parentNode.replaceChild(newer, older);
					}
					// free references
					newer = older = null;
				}, 0);
			}

			function bindTagSet(/*string*/ tag) {
				// for each element in root with tagName
				var elems = root.getElementsByTagName(tag);
				for (var i=0; i<elems.length; i++) {
					// perform action on element and
					// allow binding to replace element
					var replace = performOne(elems[i], a);
					if (replace !== elems[i] && elems[i].parentNode) {
						// queue up replacement at the end so as not to disrupt the list
						queueReplacer(replace, elems[i]);
					}
				}
			}

			if (root && root.getElementsByTagName) {
				if (bindings["*"]) {
					// if star rule, then must apply to all
					bindTagSet("*");
				} else {
					// only apply to tags with rules
					for (var tag in bindings) {
						if (tag !== "*" && bindings.hasOwnProperty(tag)) {
							bindTagSet(tag);
						}
					}
				}
			}
		};

	/*DOM*/ bindOne = function(/*DOM*/ elem) {
		return performOne(elem, BIND);
	};

	// use bindOne as the default JBST filter
	if ("undefined" !== typeof JsonML && JsonML.BST) {
		if ("function" !== typeof JsonML.BST.filter) {
			JsonML.BST.filter = bindOne;
		} else {
			JsonML.BST.filter = (function() {
				var jbstFilter = JsonML.BST.filter;
				return function(/*DOM*/ elem) {
					elem = jbstFilter(elem);
					return elem && bindOne(elem);
				};
			})();
		}
	}

	// bind
	/*void*/ b.bind = function(/*DOM*/ root) {
		if (!isFinite(root.nodeType)) {
			root = null;
		}

		perform(root || document.body, BIND);
	};

	// unbind
	/*void*/ b.unbind = function(/*DOM*/ root) {
		if (!isFinite(root.nodeType)) {
			root = null;
		}

		perform(root || document.body, UNBIND);
	};

	// register bind events
	if (typeof jQuery !== "undefined") {
		jQuery(b.bind);
		jQuery(window).bind("unload", b.unbind);
	} else if (window.addEventListener) {
		//DOM Level 2 model for binding events
		window.addEventListener("load", b.bind, false);
		window.addEventListener("unload", b.unbind, false);
	} else if (window.attachEvent) {
		//IE model for binding events
		window.attachEvent("onload", b.bind);
		window.attachEvent("onunload", b.unbind);
	} else {
		//DOM Level 0 model for binding events
		var onload = window.onload;
		window.onload =
			("function" === typeof onload) ?
			function(/*Event*/ evt) { b.bind(evt); return onload(evt); } :
			b.bind;

		var onunload = window.onunload;
		window.onunload =
			("function" === typeof onunload) ?
			function(/*Event*/ evt) { b.unbind(evt); return onunload(evt); } :
			b.unbind;
	}
};

// doing instead of anonymous fn for JSLint compatibility
// instantiate only one, destroying the constructor
JsonFx.Bindings = new JsonFx.Bindings();
<|endoftext|>


<commit_before>import textures from 'textures'

export const colorTextures = {
  '#ffd300': () => {
    return textures.lines()
    .stroke('#f48335')
    .background('#f36d20')
  },
  '#f56d00': () => {
    return textures.lines()
    .stroke('#f48335')
    .background('#f36d20')
  },
  '#15c2e8': () => {
    return textures.lines()
    .stroke('#f48335')
    .background('#f36d20')
  },
  '#1d70b7': () => {
    return textures.lines()
    .stroke('#f48335')
    .background('#f36d20')
  },
  '#c792ca': () => {
    return textures.lines()
    .stroke('#f48335')
    .background('#f36d20')
  },
  '#ba4b7a': () => {
    return textures.lines()
    .stroke('#f48335')
    .background('#f36d20')
  },
}

export const colors = Object.keys(colorTextures)
<commit_msg>Make sure colors are in static order<commit_after>import textures from 'textures'

export const colors = ['#ffd300', '#f56d00', '#15c2e8', '#1d70b7', '#c792ca', '#ba4b7a']

export const colorTextures = {
  '#ffd300': () => {
    return textures.lines()
    .stroke('#f48335')
    .background('#f36d20')
  },
  '#f56d00': () => {
    return textures.lines()
    .stroke('#f48335')
    .background('#f36d20')
  },
  '#15c2e8': () => {
    return textures.lines()
    .stroke('#f48335')
    .background('#f36d20')
  },
  '#1d70b7': () => {
    return textures.lines()
    .stroke('#f48335')
    .background('#f36d20')
  },
  '#c792ca': () => {
    return textures.lines()
    .stroke('#f48335')
    .background('#f36d20')
  },
  '#ba4b7a': () => {
    return textures.lines()
    .stroke('#f48335')
    .background('#f36d20')
  },
}
<|endoftext|>


<commit_before>import '@ciscospark/plugin-logger';
import '@ciscospark/plugin-authorization';
import '@ciscospark/internal-plugin-mercury';
import '@ciscospark/plugin-people';
import '@ciscospark/internal-plugin-conversation';
import '@ciscospark/plugin-phone';
import '@ciscospark/internal-plugin-flag';
import '@ciscospark/internal-plugin-feature';
import '@ciscospark/internal-plugin-presence';
import '@ciscospark/internal-plugin-search';
import '@ciscospark/internal-plugin-team';
import Spark from '@ciscospark/spark-core';
import LocalForageStoreAdapter from '@ciscospark/storage-adapter-local-forage';

/**
 * Creates the default spark config for the widgets
 * @param {Object} [options={}]
 * @returns {Object}
 */
function defaultConfig(options = {}) {
  return {
    appName: 'spark-widgets',
    appVersion: process.env.REACT_CISCOSPARK_VERSION,
    device: {
      ephemeral: true
    },
    logger: {
      level: options.logLevel || process.env.NODE_ENV === 'production' ? 'silent' : 'trace'
    },
    conversation: {
      allowedInboundTags: {
        'spark-mention': ['data-object-type', 'data-object-id', 'data-object-url'],
        a: ['href'],
        b: [],
        blockquote: ['class'],
        strong: [],
        i: [],
        em: [],
        pre: [],
        code: [],
        br: [],
        hr: [],
        p: [],
        ul: [],
        ol: [],
        li: [],
        h1: [],
        h2: [],
        h3: []
      },
      allowedOutboundTags: {
        'spark-mention': ['data-object-type', 'data-object-id', 'data-object-url'],
        a: ['href'],
        b: [],
        blockquote: ['class'],
        strong: [],
        i: [],
        em: [],
        pre: [],
        code: [],
        br: [],
        hr: [],
        p: [],
        ul: [],
        ol: [],
        li: [],
        h1: [],
        h2: [],
        h3: []
      }
    },
    credentials: {
      client_id: process.env.CISCOSPARK_CLIENT_ID,
      federation: process.env.FEDERATION === 'true',
      scope: 'spark:all spark:kms'
    },
    // Added to help load blocking during decryption
    encryption: {
      kmsInitialTimeout: 10000
    },
    phone: {
      enableExperimentalGroupCallingSupport: true
    },
    storage: {
      unboundedAdapter: new LocalForageStoreAdapter('ciscospark-widgets')
    }
  };
}

/**
 * Creates a spark instance with the access token
 * @param {string} accessToken
 * @param {object} options
 * @returns {Promise<object>}
 */
function createSpark(accessToken, options = {}) {
  // Check if we already have a spark instance in memory
  let {ciscosparkInstance} = window;

  if (typeof ciscosparkInstance !== 'object') {
    const credentials = JSON.parse(localStorage.getItem('credentials') || false);

    ciscosparkInstance = new Spark({
      credentials: {
        authorization: {
          access_token: accessToken || credentials.access_token
        }
      },
      config: defaultConfig(options)
    });
    window.ciscosparkInstance = ciscosparkInstance;
  }

  return Promise.resolve(ciscosparkInstance);
}

/**
 * Creates a spark instance with the jwt token generated
 * by a guest issuer.
 * https://developer.ciscospark.com/guest-issuer.html
 *
 * @param {string} jwt
 * @param {object} options
 * @returns {Promise<object>}
 */
export function createSparkJwt(jwt, options = {}) {
  // Check if we already have a spark instance in memory
  let {ciscosparkInstance} = window;

  if (typeof ciscosparkInstance === 'object') {
    return Promise.resolve(ciscosparkInstance);
  }

  ciscosparkInstance = new Spark({
    config: defaultConfig(options)
  });
  window.ciscosparkInstance = ciscosparkInstance;

  return ciscosparkInstance.authorization.requestAccessTokenFromJwt({jwt}).then(() => ciscosparkInstance);
}

export default createSpark;
<commit_msg>feat(react-redux-spark): enable federation by default<commit_after>import '@ciscospark/plugin-logger';
import '@ciscospark/plugin-authorization';
import '@ciscospark/internal-plugin-mercury';
import '@ciscospark/plugin-people';
import '@ciscospark/internal-plugin-conversation';
import '@ciscospark/plugin-phone';
import '@ciscospark/internal-plugin-flag';
import '@ciscospark/internal-plugin-feature';
import '@ciscospark/internal-plugin-presence';
import '@ciscospark/internal-plugin-search';
import '@ciscospark/internal-plugin-team';
import Spark from '@ciscospark/spark-core';
import LocalForageStoreAdapter from '@ciscospark/storage-adapter-local-forage';

/**
 * Evaluates the federation environment variable so that
 * it can be used to configure federation.
 * @returns {boolean} whether to configure federation
 */
function configureFederation() {
  const fed = process.env.FEDERATION;

  if (fed && (fed === '0' || fed.toLowerCase() === 'false')) {
    return false;
  }

  // Federation is on by default.
  return true;
}

/**
 * Creates the default spark config for the widgets
 * @param {Object} [options={}]
 * @returns {Object}
 */
function defaultConfig(options = {}) {
  return {
    appName: 'spark-widgets',
    appVersion: process.env.REACT_CISCOSPARK_VERSION,
    device: {
      ephemeral: true
    },
    logger: {
      level: options.logLevel || process.env.NODE_ENV === 'production' ? 'silent' : 'trace'
    },
    conversation: {
      allowedInboundTags: {
        'spark-mention': ['data-object-type', 'data-object-id', 'data-object-url'],
        a: ['href'],
        b: [],
        blockquote: ['class'],
        strong: [],
        i: [],
        em: [],
        pre: [],
        code: [],
        br: [],
        hr: [],
        p: [],
        ul: [],
        ol: [],
        li: [],
        h1: [],
        h2: [],
        h3: []
      },
      allowedOutboundTags: {
        'spark-mention': ['data-object-type', 'data-object-id', 'data-object-url'],
        a: ['href'],
        b: [],
        blockquote: ['class'],
        strong: [],
        i: [],
        em: [],
        pre: [],
        code: [],
        br: [],
        hr: [],
        p: [],
        ul: [],
        ol: [],
        li: [],
        h1: [],
        h2: [],
        h3: []
      }
    },
    credentials: {
      client_id: process.env.CISCOSPARK_CLIENT_ID,
      federation: configureFederation(),
      scope: 'spark:all spark:kms'
    },
    // Added to help load blocking during decryption
    encryption: {
      kmsInitialTimeout: 10000
    },
    phone: {
      enableExperimentalGroupCallingSupport: true
    },
    storage: {
      unboundedAdapter: new LocalForageStoreAdapter('ciscospark-widgets')
    }
  };
}

/**
 * Creates a spark instance with the access token
 * @param {string} accessToken
 * @param {object} options
 * @returns {Promise<object>}
 */
function createSpark(accessToken, options = {}) {
  // Check if we already have a spark instance in memory
  let {ciscosparkInstance} = window;

  if (typeof ciscosparkInstance !== 'object') {
    const credentials = JSON.parse(localStorage.getItem('credentials') || false);

    ciscosparkInstance = new Spark({
      credentials: {
        authorization: {
          access_token: accessToken || credentials.access_token
        }
      },
      config: defaultConfig(options)
    });
    window.ciscosparkInstance = ciscosparkInstance;
  }

  return Promise.resolve(ciscosparkInstance);
}

/**
 * Creates a spark instance with the jwt token generated
 * by a guest issuer.
 * https://developer.ciscospark.com/guest-issuer.html
 *
 * @param {string} jwt
 * @param {object} options
 * @returns {Promise<object>}
 */
export function createSparkJwt(jwt, options = {}) {
  // Check if we already have a spark instance in memory
  let {ciscosparkInstance} = window;

  if (typeof ciscosparkInstance === 'object') {
    return Promise.resolve(ciscosparkInstance);
  }

  ciscosparkInstance = new Spark({
    config: defaultConfig(options)
  });
  window.ciscosparkInstance = ciscosparkInstance;

  return ciscosparkInstance.authorization.requestAccessTokenFromJwt({jwt}).then(() => ciscosparkInstance);
}

export default createSpark;
<|endoftext|>


<commit_before>test(
  'ADT Test',

  [
    'ephox.katamari.api.Adt',
    'ephox.katamari.api.Arr',
    'ephox.katamari.api.Fun',
    'ephox.katamari.api.Obj',
    'ephox.wrap.Jsc'
  ],

  function (Adt, Arr, Fun, Obj, Jsc) {

    var checkInvalid = function (message, f) {
      var error = false;
      try {
        f();
      } catch (e) {
        if (e === 'ADTWHOOPS') {
          console.log('die function incorrectly called');
        } else {
          error = true;
        }
      }

      if (!error) {
        throw 'Unexpected pass: ' + message;
      }
    };

    var checkInvalidGenerate = function (cases, message) {
      checkInvalid('generate() did not throw an error. Input: "' + message + "'", function () {
        Adt.generate(cases);
      });
    };

    checkInvalidGenerate({}, 'object instead of array');
    checkInvalidGenerate([], 'empty cases array');
    checkInvalidGenerate(['f'], 'array contains strings');
    checkInvalidGenerate([{}], 'empty case');
    checkInvalidGenerate([{'t': {}}], 'object case arguments');
    checkInvalidGenerate([{'cata': []}], 'case named cata');
    checkInvalidGenerate([{'a': []},{'a': []}], 'duplicate names');
    checkInvalidGenerate([
       {
        'one': [],
        'two': []
       }
      ], 'two cases in one');

    // A real Adt from the soldier project
    var soldierBlock = Adt.generate([
      { 'none':     [] },
      { 'root':     ['target', 'block'] },
      { 'created':  ['target', 'block'] },
      { 'actual':   ['target', 'block'] }
    ]);

    var none = function () {
      assert.eq(0, arguments.length);
    };

    var targetStr = 'target';
    var blockStr = 'block';

    var tag = function (target, block) {
      assert.eq(2, arguments.length);
      assert.eq(targetStr, target);
      assert.eq(blockStr, block);
    };

    var die = function () {
      // this is used when an error is expected, so we need to use fancy tricks
      // to actually fail
      throw 'ADTWHOOPS';
    };

    // double functions because that makes actual use better
    var adtNone = soldierBlock.none();
    var adtRoot = soldierBlock.root(targetStr, blockStr);
    var adtCreated = soldierBlock.created(targetStr, blockStr);
    var adtActual = soldierBlock.actual(targetStr, blockStr);

    checkInvalid('tag passed to none', function () {
      adtNone.fold(tag, die, die, die);
    });

    checkInvalid('none passed to root', function () {
      adtRoot.fold(die, none, die, die);
    });

    checkInvalid('none passed to created', function () {
      adtCreated.fold(die, die, none, die);
    });

    checkInvalid('none passed to actual', function () {
      adtActual.fold(die, die, die, none);
    });

    // valid checks, so we can redefine die to be sensible now
    die = Fun.die('Well that was unexpected');

    adtNone.fold(   none, die, die, die);
    adtRoot.fold(    die, tag, die, die);
    adtCreated.fold( die, die, tag, die);
    adtActual.fold(  die, die, die, tag);

    var cheese = Fun.constant('cheese');

    assert.eq('cheese', adtNone.fold(   cheese,    die,    die,    die));
    assert.eq('cheese', adtRoot.fold(      die, cheese,    die,    die));
    assert.eq('cheese', adtCreated.fold(   die,    die, cheese,    die));
    assert.eq('cheese', adtActual.fold(    die,    die,    die, cheese));

    var newAdt = Adt.generate([
      { nothing: [ ] },
      { unknown: [ 'guesses' ] },
      { exact: [ 'value', 'precision' ] }
    ]);

    var arbNothing = Jsc.constant(newAdt.nothing());

    var arbUnknown = Jsc.array(Jsc.string).smap(function (guesses) {
      return newAdt.unknown(guesses);
    }, function (r) {
      return r.match({
        nothing: Fun.die('not a nothing'),
        unknown: Fun.identity,
        exact: Fun.die('not an exact')
      });
    });

    var arbExact = Jsc.tuple(Jsc.number, Jsc.number).smap(function (arr) {
      return newAdt.exact(arr[0], arr[1]);
    }, function (r) {
      return r.match({
        nothing: Fun.die('not a nothing'),
        unknown: Fun.die('not an unknown'),
        exact: function (value, precision) { return [ value, precision ]; }
      });
    });

    var arbAdt = Jsc.oneof([
      arbNothing,
      arbUnknown,
      arbExact
    ]);

    // Fix with property-based testing
    var allKeys = [ 'nothing', 'unknown', 'exact' ];
    var arbKeys = Jsc.elements(allKeys);

    Jsc.property('Error is thrown if not all arguments are supplied', arbAdt, arbKeys, function (subject, key) {
      var original = Arr.filter(allKeys, function (k) {
        return k !== key;
      });

      assert.throws(function () {
        var branches = Obj.tupleMap(original, function (k, i) {
          return { key: k, value: function () { } };
        });
        subject.match(branches);
      });
      return false;
    });

/*
    assert.throws(function () {
      adtNone.match({
        none: cheese
      });
    });

    assert.throws(function () {
      adtNone.match({
        root: die,
        created: die,
        actual: die
      });
    });

    assert.eq('cheese', adtNone.match({
      none: cheese,
      root: die,
      created: die,
      actual: die
    }));

    assert.eq('cheese', adtRoot.match({
      none: die,
      root: cheese,
      created: die,
      actual: die
    }));

    assert.eq('cheese', adtCreated.match({
      none: die,
      root: die,
      created: cheese,
      actual: die
    }));

    assert.eq('cheese', adtActual.match({
      none: die,
      root: die,
      created: die,
      actual: cheese
    }));
  */
  }
);<commit_msg>VAN-39: property test for not enough arguments<commit_after>test(
  'ADT Test',

  [
    'ephox.katamari.api.Adt',
    'ephox.katamari.api.Arr',
    'ephox.katamari.api.Fun',
    'ephox.katamari.api.Obj',
    'ephox.wrap.Jsc'
  ],

  function (Adt, Arr, Fun, Obj, Jsc) {

    var checkInvalid = function (message, f) {
      var error = false;
      try {
        f();
      } catch (e) {
        if (e === 'ADTWHOOPS') {
          console.log('die function incorrectly called');
        } else {
          error = true;
        }
      }

      if (!error) {
        throw 'Unexpected pass: ' + message;
      }
    };

    var checkInvalidGenerate = function (cases, message) {
      checkInvalid('generate() did not throw an error. Input: "' + message + "'", function () {
        Adt.generate(cases);
      });
    };

    checkInvalidGenerate({}, 'object instead of array');
    checkInvalidGenerate([], 'empty cases array');
    checkInvalidGenerate(['f'], 'array contains strings');
    checkInvalidGenerate([{}], 'empty case');
    checkInvalidGenerate([{'t': {}}], 'object case arguments');
    checkInvalidGenerate([{'cata': []}], 'case named cata');
    checkInvalidGenerate([{'a': []},{'a': []}], 'duplicate names');
    checkInvalidGenerate([
       {
        'one': [],
        'two': []
       }
      ], 'two cases in one');

    // A real Adt from the soldier project
    var soldierBlock = Adt.generate([
      { 'none':     [] },
      { 'root':     ['target', 'block'] },
      { 'created':  ['target', 'block'] },
      { 'actual':   ['target', 'block'] }
    ]);

    var none = function () {
      assert.eq(0, arguments.length);
    };

    var targetStr = 'target';
    var blockStr = 'block';

    var tag = function (target, block) {
      assert.eq(2, arguments.length);
      assert.eq(targetStr, target);
      assert.eq(blockStr, block);
    };

    var die = function () {
      // this is used when an error is expected, so we need to use fancy tricks
      // to actually fail
      throw 'ADTWHOOPS';
    };

    // double functions because that makes actual use better
    var adtNone = soldierBlock.none();
    var adtRoot = soldierBlock.root(targetStr, blockStr);
    var adtCreated = soldierBlock.created(targetStr, blockStr);
    var adtActual = soldierBlock.actual(targetStr, blockStr);

    checkInvalid('tag passed to none', function () {
      adtNone.fold(tag, die, die, die);
    });

    checkInvalid('none passed to root', function () {
      adtRoot.fold(die, none, die, die);
    });

    checkInvalid('none passed to created', function () {
      adtCreated.fold(die, die, none, die);
    });

    checkInvalid('none passed to actual', function () {
      adtActual.fold(die, die, die, none);
    });

    // valid checks, so we can redefine die to be sensible now
    die = Fun.die('Well that was unexpected');

    adtNone.fold(   none, die, die, die);
    adtRoot.fold(    die, tag, die, die);
    adtCreated.fold( die, die, tag, die);
    adtActual.fold(  die, die, die, tag);

    var cheese = Fun.constant('cheese');

    assert.eq('cheese', adtNone.fold(   cheese,    die,    die,    die));
    assert.eq('cheese', adtRoot.fold(      die, cheese,    die,    die));
    assert.eq('cheese', adtCreated.fold(   die,    die, cheese,    die));
    assert.eq('cheese', adtActual.fold(    die,    die,    die, cheese));

    var newAdt = Adt.generate([
      { nothing: [ ] },
      { unknown: [ 'guesses' ] },
      { exact: [ 'value', 'precision' ] }
    ]);

    var arbNothing = Jsc.constant(newAdt.nothing());

    var arbUnknown = Jsc.array(Jsc.string).smap(function (guesses) {
      return newAdt.unknown(guesses);
    }, function (r) {
      return r.match({
        nothing: Fun.die('not a nothing'),
        unknown: Fun.identity,
        exact: Fun.die('not an exact')
      });
    });

    var arbExact = Jsc.tuple([Jsc.number, Jsc.number]).smap(function (arr) {
      return newAdt.exact(arr[0], arr[1]);
    }, function (r) {
      return r.match({
        nothing: Fun.die('not a nothing'),
        unknown: Fun.die('not an unknown'),
        exact: function (value, precision) { return [ value, precision ]; }
      });
    });

    var arbAdt = Jsc.oneof([
      arbNothing,
      arbUnknown,
      arbExact
    ]);

    // Fix with property-based testing
    var allKeys = [ 'nothing', 'unknown', 'exact' ];
    var arbKeys = Jsc.elements(allKeys);

    Jsc.property('Error is thrown if not all arguments are supplied', arbAdt, Jsc.nearray(arbKeys), function (subject, exclusions) {
      var original = Arr.filter(allKeys, function (k) {
        return !Arr.contains(exclusions, k);
      });

      try {
        var branches = Obj.tupleMap(original, function (k, i) {
          return { k: k, v: function () { } };
        });
        subject.match(branches);
        return false;
      } catch (err) {
        return true;
      }
    });

/*
    assert.throws(function () {
      adtNone.match({
        none: cheese
      });
    });

    assert.throws(function () {
      adtNone.match({
        root: die,
        created: die,
        actual: die
      });
    });

    assert.eq('cheese', adtNone.match({
      none: cheese,
      root: die,
      created: die,
      actual: die
    }));

    assert.eq('cheese', adtRoot.match({
      none: die,
      root: cheese,
      created: die,
      actual: die
    }));

    assert.eq('cheese', adtCreated.match({
      none: die,
      root: die,
      created: cheese,
      actual: die
    }));

    assert.eq('cheese', adtActual.match({
      none: die,
      root: die,
      created: die,
      actual: cheese
    }));
  */
  }
);<|endoftext|>


<commit_before>exports.version=1440808866
<commit_msg>update version for cursor fix<commit_after>exports.version=1440870245
<|endoftext|>


<commit_before>angular.module('feature.helloWorld')

.factory('SampleService', function($resource) {
    return {
        create: function() {
            return $resource("~/api/views/pessoa/?$orderby=nome", {}, {
                "update": {
                    method: "PUT"
                },
                'query': {
                    method: 'GET',
                    isArray: false,
                    cache: false
                }
            });
        }
    };
});
<commit_msg>Adicionando comentários de como chamar a VIEW.<commit_after>angular.module('feature.helloWorld')

/* O SampleService está realizando a chamada para a view -- GVMVW_PESSOA
   Caso queira excecutar outra view por exemplo -- GVMVWM_EXEMPLO a url passada para API deverá ser: "~/api/views/exemplo/"
*/

.factory('SampleService', function($resource) {
    return {
        create: function() {
            return $resource("~/api/views/pessoa/", {}, {
                "update": {
                    method: "PUT"
                },
                'query': {
                    method: 'GET',
                    isArray: false,
                    cache: false
                }
            });
        }
    };
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';

import style from './style.css';
import { makeFieldDisplayName } from '../../lib/searchHelpers';

class DetailList extends Component {
  render() {
    let d = this.props.data;
    let nodes = this.props.fields.map( (field) => {
      let valueNode;
      if (field === 'species') {
        valueNode = ;
      } else {
        valueNode = ;
      }
      return (
        <div className={style.detailLineContainer} key={`srField.${field}`}>
          {makeFieldDisplayName(field)}:
          {valueNode}

      );
    });
    return (

        {nodes}

    );
  }
}

DetailList.propTypes = {
  data: React.PropTypes.object,
  fields: React.PropTypes.array
};

export default DetailList;
<commit_msg>add space to array fields<commit_after>import React, { Component } from 'react';

import style from './style.css';
import { makeFieldDisplayName } from '../../lib/searchHelpers';

const JOIN_CHAR = ', ';

class DetailList extends Component {
  render() {
    let d = this.props.data;
    let nodes = this.props.fields.map( (field) => {
      let valueNode;
      let value = d[field];
      if (Array.isArray(value)) {
        value = value.join(JOIN_CHAR);
      }
      if (field === 'species') {
        valueNode = ;
      } else {
        valueNode = ;
      }
      return (
        <div className={style.detailLineContainer} key={`srField.${field}`}>
          {makeFieldDisplayName(field)}:
          {valueNode}

      );
    });
    return (

        {nodes}

    );
  }
}

DetailList.propTypes = {
  data: React.PropTypes.object,
  fields: React.PropTypes.array
};

export default DetailList;
<|endoftext|>


<commit_before>/*jshint worker: true*/

// Modules and dependencies to expose in the public Tangram module
import Utils from './utils/utils';

// The leaflet layer plugin is currently the primary public API
import {LeafletLayer, leafletLayer} from './leaflet_layer';

// The scene worker is only activated when a worker thread is instantiated, but must always be loaded
import {SceneWorker} from '../src/scene_worker';

// Additional modules are exposed for debugging
import log from 'loglevel';
import Geo from './geo';
import DataSource from './data_source';
import GLSL from './gl/glsl';
import ShaderProgram from './gl/shader_program';
import Texture from './gl/texture';
import Material from './material';
import Light from './light';
import WorkerBroker from './utils/worker_broker';
import {ruleCache} from './styles/rule';

import glMatrix from 'gl-matrix';

// Default to 64-bit because we need the extra precision when multiplying matrices w/mercator projected values
glMatrix.glMatrix.setMatrixArrayType(Float64Array);

// Make some modules accessible for debugging
var debug = {
    log,
    Utils,
    Geo,
    DataSource,
    GLSL,
    ShaderProgram,
    Texture,
    Material,
    Light,
    SceneWorker,
    WorkerBroker,
    ruleCache
};

// Window can only be set in main thread
if (Utils.isMainThread) {
    // Main thread objects that can be called from workers
    WorkerBroker.addTarget('Texture', Texture);

    window.Tangram = module.exports = {
        LeafletLayer,
        leafletLayer,
        debug
    };

}

if (Utils.isWorkerThread) {
    self.Tangram = {
        debug
    };
}

if (Utils.isMainThread) {
    Utils.requestAnimationFramePolyfill();
}
<commit_msg>add style manager + parser to debug<commit_after>/*jshint worker: true*/

// Modules and dependencies to expose in the public Tangram module
import Utils from './utils/utils';

// The leaflet layer plugin is currently the primary public API
import {LeafletLayer, leafletLayer} from './leaflet_layer';

// The scene worker is only activated when a worker thread is instantiated, but must always be loaded
import {SceneWorker} from '../src/scene_worker';

// Additional modules are exposed for debugging
import log from 'loglevel';
import Geo from './geo';
import DataSource from './data_source';
import GLSL from './gl/glsl';
import ShaderProgram from './gl/shader_program';
import Texture from './gl/texture';
import Material from './material';
import Light from './light';
import WorkerBroker from './utils/worker_broker';
import {ruleCache} from './styles/rule';
import {StyleParser} from './styles/style_parser';
import {StyleManager} from './styles/style_manager';

import glMatrix from 'gl-matrix';

// Default to 64-bit because we need the extra precision when multiplying matrices w/mercator projected values
glMatrix.glMatrix.setMatrixArrayType(Float64Array);

// Make some modules accessible for debugging
var debug = {
    log,
    Utils,
    Geo,
    DataSource,
    GLSL,
    ShaderProgram,
    Texture,
    Material,
    Light,
    SceneWorker,
    WorkerBroker,
    ruleCache,
    StyleParser,
    StyleManager
};

// Window can only be set in main thread
if (Utils.isMainThread) {
    // Main thread objects that can be called from workers
    WorkerBroker.addTarget('Texture', Texture);

    window.Tangram = module.exports = {
        LeafletLayer,
        leafletLayer,
        debug
    };

}

if (Utils.isWorkerThread) {
    self.Tangram = {
        debug
    };
}

if (Utils.isMainThread) {
    Utils.requestAnimationFramePolyfill();
}
<|endoftext|>


<commit_before>"use strict";

var sslaConfig = {
    openContentIn: "inline",
    autoLaunchFirstSco: true,
    setDataUrl: "/trackAllInOne/set",
    getDataUrl: "/trackAllInOne/get",
    returnToLastScoOnLaunch: false,
//    singleScoView: "HIDE_ALL",

    scoreAllowReduce: false,

//     statusAllowChangeAfterCompleted: false,
//     statusAllowChangeAfterFailed: false,
//     statusAllowChangeAfterPassed: false,
//
//     pluginLoadDetection: false,
//     pluginMode: "scorm",
//     scormManifestUseRawXml: true,
//     scormManifestRawXml: '<manifest identifier="CQFaceism" version="1.0" xmlns="http://www.imsproject.org/xsd/imscp_rootv1p1p2" xmlns:adlcp="http://www.adlnet.org/xsd/adlcp_rootv1p2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.imsproject.org/xsd/imscp_rootv1p1p2 imscp_rootv1p1p2.xsd\
//     http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd\
//     http://www.adlnet.org/xsd/adlcp_rootv1p2 adlcp_rootv1p2.xsd">\
// <metadata>\
// <schema>ADL SCORM</schema>\
// <schemaversion>1.2</schemaversion>\
// </metadata>\
// <organizations default="Tester">\
//     <organization identifier="Tester">\
//     <title>Tester</title>\
//     <item identifier="quiz1" identifierref="testerf" isvisible="true">\
//     <title>Tester</title>\
//     </item>\
// </organization>\
// </organizations>\
// <resources>\
// <resource adlcp:scormtype="sco" href="index3.htm" identifier="testerf" type="webcontent">\
//     </resource>\
//     </resources>\
//     </manifest>\
//     ',
};
<commit_msg>update config_override.js<commit_after>var sslaConfig = {
    autoLaunchFirstSco: true,
    setDataAjaxMethod: "POST",
    getDataAjaxMethod: "POST",
    setDataUrl: setDataURL,
    getDataUrl: getDataURL,
    setDataHeaders: dataHeaders,
    getDataHeaders: dataHeaders,
    openContentIn: openContentIn,
    popupWindowParams: popupWindowParams,
    courseId: courseId,
    courseDirectory: courseDirectory,
    studentId: studentId,
    studentName: studentName
};

var messageData = null;
var ssla_player_debug = false;

// we don't want alerts displaying in production
if (!(ssla_player_debug)) window.alert = function() {};

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event) {
  console.log("Receive Message:", event);
  var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
  /*
  if (origin !== "http://example.org:8080")
    return;
  */
  if (ssla_player_debug) alert('SSLA player received message!');
  messageData = event.data;
  ssla.ssla.start();
}

function dataHeaders() {
   try {
     return {"X-CSRFToken": messageData.csrftoken};
   }
   catch (e) {
     //fail on cross-domain security error...
     return {};
   }
}

function getDataURL() {
  console.log('calling getDataURL');
  try {
    return messageData.get_url;
  }
  catch (e){
    //fail on cross-domain security error...
    //we don't want preview from Studio to send get/set
    return "#";
  }
}

function setDataURL() {
  try {
    return messageData.set_url;
  }
  catch (e){
    //fail on cross-domain security error...
    //we don't want preview from Studio to send get/set
    return "#";
  }
}

function openContentIn() {
  try {
    return messageData.display_type.toLowerCase() == "iframe" ? "inline" : "popup";
  }
  catch (e){
    return "1";
  }
}

function popupWindowParams() {
  try {
    width = messageData.display_width;
    height = messageData.display_height;
    menubar = toolbar = status = scrollbar = "no";
    if (ssla_player_debug) {
      menubar = toolbar = status = scrollbar = "yes";
    }
    attrstr = "width="+width+",height="+height+",menubar="+menubar+",toolbar="+toolbar+",status="+status+",scrollbar="+scrollbar;
    return attrstr;
  }
  catch (e){
    return "";
  }
}

function courseId() {
  try {
    return messageData.course_id;
  }
  catch (e){
    return "";
  }
}

function courseDirectory() {
  try {
    //console.log('courseDirectory is '+messageData.course_location);
    return messageData.course_location;
  }
  catch (e){
    console.log(e)
    return "";
  }
}

function studentId() {
  try {
    return messageData.student_id;
  }
  catch (e){
    return "";
  }
}

function studentName() {
  try {
    return messageData.student_name;
  }
  catch (e){
    return "";
  }
}
<|endoftext|>


<commit_before>function displayAnimalGallery(animals) {
    var container = document.querySelector('.animal-gallery--animals');

    animals.map(animalDetails).forEach(function(element) {
        container.appendChild(element);
    }, container);
}

function displayFeaturedAnimal(animal) {
    var container = document.querySelector('.featured-animal--info');

    var name = container.querySelector('.featured-animal--name');
    name.appendChild(document.createTextNode(animal.name));

    var location = container.querySelector('.featured-animal--location');
    location.appendChild(document.createTextNode(animal.location));

    var age = container.querySelector('.featured-animal--age');
    age.appendChild(document.createTextNode(animal.age));

    var commonName = container.querySelector('.featured-animal--common-name');
    commonName.appendChild(document.createTextNode(animal.commonName));

    var imageContainer = container.querySelector('.featured-animal--image-container');

    var imageLink = document.createElement('a');
    imageLink.href = 'images/' + animal.image;
    var image = document.createElement('img');
    image.className = 'featured-animal--image';
    image.src = 'images/' + animal.image;
    imageLink.appendChild(image);

    imageContainer.appendChild(imageLink);
}

function displayAnimalAges(ages) {
    var container = document.querySelector('.animal-ages');
    var table = document.createElement('table');
    var headingRow = document.createElement('tr');

    var nameHeading = document.createElement('th');
    nameHeading.appendChild(document.createTextNode('Name'));
    headingRow.appendChild(nameHeading);

    var speciesHeading = document.createElement('th');
    speciesHeading.appendChild(document.createTextNode('Species'));
    headingRow.appendChild(speciesHeading);

    var ageHeading = document.createElement('th');
    ageHeading.appendChild(document.createTextNode('Age'));
    headingRow.appendChild(ageHeading);
    table.appendChild(headingRow);

    ages.map(ageDetails).forEach(function(details) {
        table.appendChild(details);
    });
    container.appendChild(table);

}

function animalDetails(animal) {
    var element = document.createElement('article');
    element.className = 'animal';
    element.appendChild(createElement('h3', 'animal--name', animal.name));

    var imageLink = document.createElement('a');
    imageLink.href = 'images/' + animal.image;
    var image = document.createElement('img');
    image.className = 'animal--image';
    image.src = 'images/' + animal.image;
    imageLink.appendChild(image);
    element.appendChild(imageLink);

    var details = createElement('div', 'animal--details');
    details.appendChild(createLabelAndValue('animal--common-name', 'Common name', animal.commonName));
    details.appendChild(createLabelAndValue('animal--species', 'Species', animal.species));
    details.appendChild(createLabelAndValue('animal--location', 'Location', animal.location));
    details.appendChild(createLabelAndValue('animal--age', 'Age', animal.age));
    element.appendChild(details);

    return element;
}

function ageDetails(animal) {
    var row = document.createElement('tr');

    row.appendChild(createElement('td', 'name', animal.name));
    row.appendChild(createElement('td', 'common-name', animal.commonName));
    row.appendChild(createElement('td', 'age', animal.age));

    return row;
}

function createLabelAndValue(className, label, text) {
    var element = createElement('div', className);
    element.appendChild(createLabel(label));
    element.appendChild(document.createTextNode(' '));
    element.appendChild(createElement('span', 'value', text));
    return element;
}

function createLabel(text) {
    return createElement('span', 'label', text);
}

function createElement(tagName, className, text) {
    var element = document.createElement(tagName);
    element.className = className;
    element.appendChild(document.createTextNode(text || ''));

    return element;
}
<commit_msg>Clean up DOM rendering code<commit_after>function displayAnimalGallery(animals) {
    var container = document.querySelector('.animal-gallery--animals');
    animals.map(animalDetails).forEach(container.appendChild, container);
}

function displayFeaturedAnimal(animal) {
    var container = document.querySelector('.featured-animal--info');

    container.querySelector('.featured-animal--name').appendChild(createTextNode(animal.name));
    container.querySelector('.featured-animal--location').appendChild(createTextNode(animal.location));
    container.querySelector('.featured-animal--age').appendChild(createTextNode(animal.age));
    container.querySelector('.featured-animal--common-name').appendChild(createTextNode(animal.commonName));

    var imageLink = createElement('a', 'featured-animal--link');
    imageLink.href = 'images/' + animal.image;

    var image = createElement('img', 'featured-animal--image');
    image.src = 'images/' + animal.image;
    imageLink.appendChild(image);

    container.querySelector('.featured-animal--image-container').appendChild(imageLink);
}

function displayAnimalAges(ages) {
    var container = document.querySelector('.animal-ages');
    var table = createElement('table', 'animal-ages--table');

    var thead = createElement('thead');
    table.appendChild(thead);

    var headingRow = createElement('tr');
    headingRow.appendChild(createElement('th', 'name', 'Name'));
    headingRow.appendChild(createElement('th', 'species', 'Species'));
    headingRow.appendChild(createElement('th', 'age', 'Age'));
    thead.appendChild(headingRow);

    var tbody = createElement('tbody');
    ages.map(ageDetails).forEach(tbody.appendChild, tbody);
    table.appendChild(tbody);

    container.appendChild(table);
}

function animalDetails(animal) {
    var element = createElement('article', 'animal');

    element.appendChild(createElement('h3', 'animal--name', animal.name));

    var imageLink = createElement('a', 'featured-animal--link');
    imageLink.href = 'images/' + animal.image;
    element.appendChild(imageLink);

    var image = createElement('img', 'animal--image');
    image.src = 'images/' + animal.image;
    imageLink.appendChild(image);

    var details = createElement('div', 'animal--details');
    details.appendChild(createLabelAndValue('animal--common-name', 'Common name', animal.commonName));
    details.appendChild(createLabelAndValue('animal--species', 'Species', animal.species));
    details.appendChild(createLabelAndValue('animal--location', 'Location', animal.location));
    details.appendChild(createLabelAndValue('animal--age', 'Age', animal.age));
    element.appendChild(details);

    return element;
}

function ageDetails(animal) {
    var row = document.createElement('tr');

    row.appendChild(createElement('td', 'name', animal.name));
    row.appendChild(createElement('td', 'species', animal.commonName));
    row.appendChild(createElement('td', 'age', animal.age));

    return row;
}

//
// Utilities
//

function createElement(tagName, className, text) {
    var element = document.createElement(tagName);
    if (className) element.className = className;
    if (text) element.appendChild(createTextNode(text));
    return element;
}

function createTextNode(text) {
    return document.createTextNode(text);
}

function createLabelAndValue(className, label, text) {
    var element = createElement('div', className);

    element.appendChild(createElement('span', 'label', label));
    element.appendChild(createTextNode(' ')); // add some whitespace
    element.appendChild(createElement('span', 'value', text));

    return element;
}<|endoftext|>


<commit_before>/**
 * @file menuTimerAnimated.js
 * @author Vladimir Deminenko
 * @date 24.08.2017
 */

'use strict';

/**
 * https://learn.javascript.ru/task/menu-timer-animated
 */
let AnimatingMenu = (function () {
    let STATE_ANIMATING = 2;

    return class AnimatingMenu extends Menu {
        constructor(state) {
            super(state);

            this._timer = null;
        }

        _stateAsString() {
            if (this._state === STATE_ANIMATING) {
                return 'анимация';
            }

            return Menu.prototype._stateAsString.call(this);
        }

        open() {
            this._state = STATE_ANIMATING;
            this._timer = setTimeout(() => Menu.prototype.open.call(this), 1000);
        }

        close() {
            clearInterval(this._timer);
            Menu.prototype.close.call(this);
        }
    }
})();
<commit_msg>homework-07<commit_after>/**
 * @file menuTimerAnimated.js
 * @author Vladimir Deminenko
 * @date 24.08.2017
 */

'use strict';

/**
 * https://learn.javascript.ru/task/menu-timer-animated
 */
let AnimatingMenu = (function () {
    let STATE_ANIMATING = 2;

    return class AnimatingMenu extends Menu {
        constructor(state) {
            super(state);

            this._timer = null;
        }

        _stateAsString() {
            if (this._state === STATE_ANIMATING) {
                return 'анимация';
            }

            return super._stateAsString.call(this);
        }

        open() {
            this._state = STATE_ANIMATING;
            this._timer = setTimeout(() => super.open.call(this), 1000);
        }

        close() {
            clearInterval(this._timer);
            super.close.call(this);
        }
    }
})();
<|endoftext|>


<commit_before>import React from 'react';

import { Abelito75 } from 'CONTRIBUTORS';
import retryingPromise from 'common/retryingPromise';
import SpellLink from 'common/SpellLink';
import SPELLS from 'common/SPELLS';
import SPECS from 'game/SPECS';
import { TooltipElement } from 'common/Tooltip';
import Warning from 'interface/common/Alert/Warning';

import CHANGELOG from './CHANGELOG';

export default {
  // The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion.
  contributors: [Abelito75],
  // The WoW client patch this spec was last updated to be fully compatible with.
  patchCompatibility: '8.0',
  // If set to  false`, the spec will show up as unsupported.
  isSupported: true,
  // Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more.
  // If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component.
  description: (
    <>
      <Warning>
        Hey there! Right now the Protection Warrior parser is a work in progress and  is nearing completion! More or less everything is in here but not fully tested. Use at your own risk... but if you do find a bug contact us on Discord.

      </Warning>
      <Warning>
        Because resets of <SpellLink id={SPELLS.SHIELD_SLAM.id} /> <TooltipElement content="The combatlog does not contain any events for random cooldown resets.">can't be tracked</TooltipElement> properly, any cooldown information of <SpellLink id={SPELLS.SHIELD_SLAM.id} /> should be treated as <TooltipElement content="Whenever Shield Slams would be cast before its cooldown would have expired normally, the cooldown expiry will be set back to the last possible trigger of Revenge, Devastate, Devastator or Thunder Clap. This may lead to higher times on cooldown than you actually experienced in-game.">educated guesses</TooltipElement>.
      </Warning>
    </>
  ),
  // A recent example report to see interesting parts of the spec. Will be shown on the homepage.
  exampleReport: '/report/fGx9M1rNZWX34ynk/18-Heroic+Grong+-+Kill+(5:21)/3-Areoss',

  // Don't change anything below this line;
  // The current spec identifier. This is the only place (in code) that specifies which spec this parser is about.
  spec: SPECS.PROTECTION_WARRIOR,
  // The contents of your changelog.
  changelog: CHANGELOG,
  // The CombatLogParser class for your spec.
  parser: () => retryingPromise(() => import('./CombatLogParser' /* webpackChunkName: "ProtectionWarrior" */).then(exports => exports.default)),
  // The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code.
  path: __dirname,
};
<commit_msg>support: false<commit_after>import React from 'react';

import { Abelito75 } from 'CONTRIBUTORS';
import retryingPromise from 'common/retryingPromise';
import SpellLink from 'common/SpellLink';
import SPELLS from 'common/SPELLS';
import SPECS from 'game/SPECS';
import { TooltipElement } from 'common/Tooltip';
import Warning from 'interface/common/Alert/Warning';

import CHANGELOG from './CHANGELOG';

export default {
  // The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion.
  contributors: [Abelito75],
  // The WoW client patch this spec was last updated to be fully compatible with.
  patchCompatibility: '8.0',
  // If set to  false`, the spec will show up as unsupported.
  isSupported: false,
  // Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more.
  // If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component.
  description: (
    <>
      <Warning>
        Hey there! Right now the Protection Warrior parser is a work in progress and  is nearing completion! More or less everything is in here but not fully tested. Use at your own risk... but if you do find a bug contact us on Discord.

      </Warning>
      <Warning>
        Because resets of <SpellLink id={SPELLS.SHIELD_SLAM.id} /> <TooltipElement content="The combatlog does not contain any events for random cooldown resets.">can't be tracked</TooltipElement> properly, any cooldown information of <SpellLink id={SPELLS.SHIELD_SLAM.id} /> should be treated as <TooltipElement content="Whenever Shield Slams would be cast before its cooldown would have expired normally, the cooldown expiry will be set back to the last possible trigger of Revenge, Devastate, Devastator or Thunder Clap. This may lead to higher times on cooldown than you actually experienced in-game.">educated guesses</TooltipElement>.
      </Warning>
    </>
  ),
  // A recent example report to see interesting parts of the spec. Will be shown on the homepage.
  exampleReport: '/report/fGx9M1rNZWX34ynk/18-Heroic+Grong+-+Kill+(5:21)/3-Areoss',

  // Don't change anything below this line;
  // The current spec identifier. This is the only place (in code) that specifies which spec this parser is about.
  spec: SPECS.PROTECTION_WARRIOR,
  // The contents of your changelog.
  changelog: CHANGELOG,
  // The CombatLogParser class for your spec.
  parser: () => retryingPromise(() => import('./CombatLogParser' /* webpackChunkName: "ProtectionWarrior" */).then(exports => exports.default)),
  // The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code.
  path: __dirname,
};
<|endoftext|>


<commit_before>export { init, testResultSame, testDifferentDisposeStrategy_All, disposeTensors };

import * as ValueMax from "../ValueMax.js";
import * as Embedding2d from "../Conv/Embedding2d.js";
import * as TensorTools from "../util/TensorTools.js";

/**
 * Test CNN Embedding2d.
 *
 * @see {@link }
 */

/**
 * A test set.
 */
class HeightWidthDepth {

  /**
   * @param {number} height            image height
   * @param {number} width             image width
   * @param {number} depth             image channel count
   * @param {number} channelMultiplier Every input channel expands into how many channels.
   */
  constructor( height, width, depth, channelMultiplier ) {

    this.disposeTensors();

    this.height = height;
    this.width = width;
    this.depth = depth;
    this.channelMultiplier = channelMultiplier;

    this.valueCount = height * width * depth;

    this.concatenatedShape = [ height, width, depth ];

    this.dataTensor3d = tf.tidy( () => {
      let dataTensor1d = tf.linspace( 0, this.valueCount - 1, this.valueCount );

      let dataTensor3d = dataTensor1d.reshape( [ height, width, depth ] );
      return dataTensor3d;
    });

    this.weightsFloat32Array = new Float32Array( [
      9, 8, 7, // Un-used

    ] );

    this.weightsByteOffsetBegin = 3; // Skip the un-used.
  }

  disposeTensors() {
    if ( this.dataTensor3d ) {
      this.dataTensor3d.dispose();
      this.dataTensor3d = null;
    }

    this.embedding2d_release();
  }

  ebedding2d_init() {
    this.embedding2d_release();

    this.embedding2d = new Embedding2d.Base();
    {
      let progress = new ValueMax.Percentage.Aggregate();
      let initer = embedding2d.initer( this.progress, this.weightsFloat32Array, this.weightsByteOffsetBegin, this.depth, this.channelMultiplier );
      let initerNext;
      while ( ! ( ( initerNext = initer.next() ).done ) ) {
        //initerNext.value; // progressRoot
      }
      //initerNext.value; // Initialize successfully or failed.
    }
  }

  embedding2d_release() {
    if ( this.embedding2d ) {
      this.embedding2d.disposeTensors();
      this.embedding2d = null;
    }
  }

  // Test concat-reshape-transpose-reshape-split
  test_ConcatReshapeTransposeReshapeSplit() {
    let shuffledArray = this.shuffleInfo.concatReshapeTransposeReshapeSplit( this.dataTensor3dArray );
    tf.dispose( shuffledArray );
  }

  // Test concat-gather (Unsorted)
  test_ConcatGatherUnsorted() {
    let shuffledArray = this.concatGatherUnsorted.concatGather( this.dataTensor3dArray );
    tf.dispose( shuffledArray );
  }

  // Test split-concat (Sorted Shared)
  test_SplitConcatSortedShared() {
    let shuffledArray = this.splitConcatSortedShared.splitConcat( this.dataTensor3dArray );
    tf.dispose( shuffledArray );
  }

  // Test concat-pointwise-convolution
  test_ConcatPointwiseConv() {
    let shuffledArray = this.concatPointwiseConv.concatGather( this.dataTensor3dArray );
    tf.dispose( shuffledArray );
  }

  // Testing whether the results of different implementation are the same.
  testResultSame() {
    tf.tidy( () => { // Test memory leakage of embedding2d.
      let memoryInfoPre = tf.memory();
      this.ebedding2d_init();
      this.ebedding2d_release();
      let memoryInfo = tf.memory();
      tf.util.assert( memoryInfoPre.numTensors == memoryInfo.numTensors, `Channel shufflers memory leak.`);
    });

    this.ebedding2d_init();  // (Should outside tidy() for preventing from tensors being disposed.

    tf.tidy( () => {
      let memoryInfo0 = tf.memory();

      let t1Array = this.shuffleInfo.concatReshapeTransposeReshapeSplit( this.dataTensor3dArray );
      let memoryInfo1 = tf.memory();
      tf.util.assert( memoryInfo1.numTensors == ( memoryInfo0.numTensors + t1Array.length ), `ConcatReshapeTransposeReshapeSplit() memory leak`);

      let t2Array = this.concatGatherUnsorted.concatGather( this.dataTensor3dArray );
      let memoryInfo2 = tf.memory();
      tf.util.assert( memoryInfo2.numTensors == ( memoryInfo1.numTensors + t2Array.length ), `ConcatGatherUnsorted() memory leak`);

      let t3Array = this.splitConcatSortedShared.splitConcat( this.dataTensor3dArray );
      let memoryInfo3 = tf.memory();
      tf.util.assert( memoryInfo3.numTensors == ( memoryInfo2.numTensors + t3Array.length ), `SplitConcatSortedShared() memory leak`);

      let t4Array = this.concatPointwiseConv.concatGather( this.dataTensor3dArray );
      let memoryInfo4 = tf.memory();
      tf.util.assert( memoryInfo4.numTensors == ( memoryInfo3.numTensors + t4Array.length ), `PointwiseConv() memory leak`);

      tf.util.assert(
        TensorTools.Comparator.isTensorArrayEqual( t1Array, t2Array ),
        `ConcatReshapeTransposeReshapeSplit() != ConcatGatherUnsorted()`);

//!!! Sorted never equal to Unsorted.
//       tf.util.assert(
//         ChannelShuffler.Layer.isTensorArrayEqual( t2Array, t3Array ),
//         `ConcatGatherUnsorted() != SplitConcatSortedShared()`);

      // Because the sorted will never equal to unsorted, try to compare their sum.
      // (Using average may be have some floating-point error.)
      tf.tidy( () => {
//         let t2MeanArray = t2Array.map( t => t.mean() );
//         let t3MeanArray = t3Array.map( t => t.mean() );
        let lastAxisId = t2Array[ 0 ].rank - 1;
        let t2SumArray = t2Array.map( t => t.sum( lastAxisId ) );
        let t3SumArray = t3Array.map( t => t.sum( lastAxisId ) );

        tf.util.assert(
          TensorTools.Comparator.isTensorArrayEqual( t2SumArray, t3SumArray ),
          `ConcatGatherUnsorted() != SplitConcatSortedShared()`);
      });

      tf.util.assert(
        TensorTools.Comparator.isTensorArrayEqual( t2Array, t4Array ),
        `ConcatGatherUnsorted() != PointwiseConv()`);
    });
  }

//   testDifferentDisposeStrategy_ConcatReshapeTransposeReshapeSplit() {
//     let functionTable = [
//     ];
//     this.testDifferentDisposeStrategy( functionTable, this.shuffleInfo );
//   }
//
//   testDifferentDisposeStrategy_All() {
//     this.testDifferentDisposeStrategy_ConcatReshapeTransposeReshapeSplit();
//   }
//
//   testDifferentDisposeStrategy( functionTable, thisArg ) {
//     tf.tidy( () => {
//       let funcPrev;
//       let tArrayPrev;
//
//       for ( let i = 0; i < functionTable.length; ++i ) {
//         let func = functionTable[ i ];
//
//         let memoryInfoPrev = tf.memory();
//         let tArray = func.call( thisArg, this.dataTensor3dArray );
//         let memoryInfo = tf.memory();
//
//         tf.util.assert( memoryInfo.numTensors == ( memoryInfoPrev.numTensors + tArray.length ), `${func.name}() memory leak`);
//
//         if ( tArrayPrev ) {
//           tf.util.assert(
//             TensorTools.Comparator.isTensorArrayEqual( tArrayPrev, tArray ),
//             `${funcPrev.name}() != ${func.name}()`);
//         }
//
//         tf.dispose( tArrayPrev );
//
//         funcPrev = func;
//         tArrayPrev = tArray;
//       }
//     });
//   }
// }

function init() {
  globalThis.testSet_110x110x24_cm8 = new HeightWidthDepth( 110, 110, 24, 8 ); // height, width, depth, channelMultiplier
  globalThis.testSet_110x110x24_cm4 = new HeightWidthDepth( 110, 110, 24, 4 );
  globalThis.testSet_110x110x24_cm3 = new HeightWidthDepth( 110, 110, 24, 3 );
  globalThis.testSet_110x110x24_cm2 = new HeightWidthDepth( 110, 110, 24, 2 );
  globalThis.testSet_110x110x24_cm1 = new HeightWidthDepth( 110, 110, 24, 1 );

  globalThis.testSet_110x110x24_All = [
    globalThis.testSet_110x110x24_cm8,
    globalThis.testSet_110x110x24_cm4,
    globalThis.testSet_110x110x24_cm3,
    globalThis.testSet_110x110x24_cm2,
    globalThis.testSet_110x110x24_cm1,
  ];
}

function testResultSame() {
  for ( let i = 0; i < globalThis.testSet_110x110x24_All.length; ++i ) {
    let testSet = globalThis.testSet_110x110x24_All[ i ];
    testSet.testResultSame();
  }
}

function testDifferentDisposeStrategy_All() {
  for ( let i = 0; i < globalThis.testSet_110x110x24_All.length; ++i ) {
    let testSet = globalThis.testSet_110x110x24_All[ i ];
    testSet.testDifferentDisposeStrategy_All();
  }
}

function disposeTensors() {
  for ( let i = 0; i < globalThis.testSet_110x110x24_All.length; ++i ) {
    let testSet = globalThis.testSet_110x110x24_All[ i ];
    testSet.disposeTensors();
  }

  globalThis.testSet_110x110x24_g8
    = globalThis.testSet_110x110x24_g4
    = globalThis.testSet_110x110x24_g3
    = globalThis.testSet_110x110x24_g2
    = globalThis.testSet_110x110x24_g1
    = null;
}
<commit_msg>Update jsPerf_Embedding2d.js<commit_after>export { init, testResultSame, testDifferentDisposeStrategy_All, disposeTensors };

import * as ValueMax from "../ValueMax.js";
import * as Embedding2d from "../Conv/Embedding2d.js";
import * as TensorTools from "../util/TensorTools.js";

/**
 * Test CNN Embedding2d.
 *
 * @see {@link }
 */

/**
 * A test set.
 */
class HeightWidthDepth {

  /**
   * @param {number} height            image height
   * @param {number} width             image width
   * @param {number} depth             image channel count
   * @param {number} channelMultiplier Every input channel expands into how many channels.
   */
  constructor( height, width, depth, channelMultiplier ) {

    this.disposeTensors();

    this.height = height;
    this.width = width;
    this.depth = depth;
    this.channelMultiplier = channelMultiplier;

    this.valueCount = height * width * depth;

    this.concatenatedShape = [ height, width, depth ];

    this.dataTensor3d = tf.tidy( () => {
      let dataTensor1d = tf.linspace( 0, this.valueCount - 1, this.valueCount );

      let dataTensor3d = dataTensor1d.reshape( [ height, width, depth ] );
      return dataTensor3d;
    });

    this.weightsByteOffsetBegin = 3; // Skip the un-used.
    this.vocabularyCountPerInputChannel = 256;
    this.bEmbedVocabularyId = true;
    this.bKeepInputTensor = false;

    let wieghtsArrayLength =
      this.weightsByteOffsetBegin // Skip the un-used.
        + ( depth * this.vocabularyCountPerInputChannel )
      ;

    this.weightsFloat32Array = new Float32Array( wieghtsArrayLength );
    {
      for ( let i = 0; i < this.weightsByteOffsetBegin; ++i ) { // Make-up the un-used weight values.
        this.weightsFloat32Array[ i ] = -i;
      }

      for ( let i = this.weightsByteOffsetBegin; i < wieghtsArrayLength; ++i ) { // Make-up the embedding weight values.
        this.weightsFloat32Array[ i ] = ( i - this.weightsByteOffsetBegin );
      }
    }
  }

  disposeTensors() {
    if ( this.dataTensor3d ) {
      this.dataTensor3d.dispose();
      this.dataTensor3d = null;
    }

    this.embedding2d_release();
  }

  ebedding2d_init() {
    this.embedding2d_release();

    this.embedding2d = new Embedding2d.Base();
    {
      let progress = new ValueMax.Percentage.Aggregate();
      let initer = this.embedding2d.initer(
        this.progress, this.weightsFloat32Array, this.weightsByteOffsetBegin, this.depth, this.channelMultiplier,
        this.vocabularyCountPerInputChannel,
        this.bEmbedVocabularyId,
        this.bKeepInputTensor
      );

      let initerNext;
      while ( ! ( ( initerNext = initer.next() ).done ) ) {
        //initerNext.value; // progressRoot
      }
      //initerNext.value; // Initialize successfully or failed.
    }
  }

  embedding2d_release() {
    if ( this.embedding2d ) {
      this.embedding2d.disposeTensors();
      this.embedding2d = null;
    }
  }

  // Test concat-reshape-transpose-reshape-split
  test_ConcatReshapeTransposeReshapeSplit() {
    let shuffledArray = this.shuffleInfo.concatReshapeTransposeReshapeSplit( this.dataTensor3dArray );
    tf.dispose( shuffledArray );
  }

  // Test concat-gather (Unsorted)
  test_ConcatGatherUnsorted() {
    let shuffledArray = this.concatGatherUnsorted.concatGather( this.dataTensor3dArray );
    tf.dispose( shuffledArray );
  }

  // Test split-concat (Sorted Shared)
  test_SplitConcatSortedShared() {
    let shuffledArray = this.splitConcatSortedShared.splitConcat( this.dataTensor3dArray );
    tf.dispose( shuffledArray );
  }

  // Test concat-pointwise-convolution
  test_ConcatPointwiseConv() {
    let shuffledArray = this.concatPointwiseConv.concatGather( this.dataTensor3dArray );
    tf.dispose( shuffledArray );
  }

  // Testing whether the results of different implementation are the same.
  testResultSame() {
    tf.tidy( () => { // Test memory leakage of embedding2d.
      let memoryInfoPre = tf.memory();
      this.ebedding2d_init();
      this.ebedding2d_release();
      let memoryInfo = tf.memory();
      tf.util.assert( memoryInfoPre.numTensors == memoryInfo.numTensors, `Channel shufflers memory leak.`);
    });

    this.ebedding2d_init();  // (Should outside tidy() for preventing from tensors being disposed.

    tf.tidy( () => {
      let memoryInfo0 = tf.memory();

      let t1Array = this.shuffleInfo.concatReshapeTransposeReshapeSplit( this.dataTensor3dArray );
      let memoryInfo1 = tf.memory();
      tf.util.assert( memoryInfo1.numTensors == ( memoryInfo0.numTensors + t1Array.length ), `ConcatReshapeTransposeReshapeSplit() memory leak`);

      let t2Array = this.concatGatherUnsorted.concatGather( this.dataTensor3dArray );
      let memoryInfo2 = tf.memory();
      tf.util.assert( memoryInfo2.numTensors == ( memoryInfo1.numTensors + t2Array.length ), `ConcatGatherUnsorted() memory leak`);

      let t3Array = this.splitConcatSortedShared.splitConcat( this.dataTensor3dArray );
      let memoryInfo3 = tf.memory();
      tf.util.assert( memoryInfo3.numTensors == ( memoryInfo2.numTensors + t3Array.length ), `SplitConcatSortedShared() memory leak`);

      let t4Array = this.concatPointwiseConv.concatGather( this.dataTensor3dArray );
      let memoryInfo4 = tf.memory();
      tf.util.assert( memoryInfo4.numTensors == ( memoryInfo3.numTensors + t4Array.length ), `PointwiseConv() memory leak`);

      tf.util.assert(
        TensorTools.Comparator.isTensorArrayEqual( t1Array, t2Array ),
        `ConcatReshapeTransposeReshapeSplit() != ConcatGatherUnsorted()`);

//!!! Sorted never equal to Unsorted.
//       tf.util.assert(
//         ChannelShuffler.Layer.isTensorArrayEqual( t2Array, t3Array ),
//         `ConcatGatherUnsorted() != SplitConcatSortedShared()`);

      // Because the sorted will never equal to unsorted, try to compare their sum.
      // (Using average may be have some floating-point error.)
      tf.tidy( () => {
//         let t2MeanArray = t2Array.map( t => t.mean() );
//         let t3MeanArray = t3Array.map( t => t.mean() );
        let lastAxisId = t2Array[ 0 ].rank - 1;
        let t2SumArray = t2Array.map( t => t.sum( lastAxisId ) );
        let t3SumArray = t3Array.map( t => t.sum( lastAxisId ) );

        tf.util.assert(
          TensorTools.Comparator.isTensorArrayEqual( t2SumArray, t3SumArray ),
          `ConcatGatherUnsorted() != SplitConcatSortedShared()`);
      });

      tf.util.assert(
        TensorTools.Comparator.isTensorArrayEqual( t2Array, t4Array ),
        `ConcatGatherUnsorted() != PointwiseConv()`);
    });
  }

//   testDifferentDisposeStrategy_ConcatReshapeTransposeReshapeSplit() {
//     let functionTable = [
//     ];
//     this.testDifferentDisposeStrategy( functionTable, this.shuffleInfo );
//   }

   testDifferentDisposeStrategy_All() {
//     this.testDifferentDisposeStrategy_ConcatReshapeTransposeReshapeSplit();
   }

//   testDifferentDisposeStrategy( functionTable, thisArg ) {
//     tf.tidy( () => {
//       let funcPrev;
//       let tArrayPrev;
//
//       for ( let i = 0; i < functionTable.length; ++i ) {
//         let func = functionTable[ i ];
//
//         let memoryInfoPrev = tf.memory();
//         let tArray = func.call( thisArg, this.dataTensor3dArray );
//         let memoryInfo = tf.memory();
//
//         tf.util.assert( memoryInfo.numTensors == ( memoryInfoPrev.numTensors + tArray.length ), `${func.name}() memory leak`);
//
//         if ( tArrayPrev ) {
//           tf.util.assert(
//             TensorTools.Comparator.isTensorArrayEqual( tArrayPrev, tArray ),
//             `${funcPrev.name}() != ${func.name}()`);
//         }
//
//         tf.dispose( tArrayPrev );
//
//         funcPrev = func;
//         tArrayPrev = tArray;
//       }
//     });
//   }
// }

function init() {
  globalThis.testSet_110x110x24_cm8 = new HeightWidthDepth( 110, 110, 24, 8 ); // height, width, depth, channelMultiplier
  globalThis.testSet_110x110x24_cm4 = new HeightWidthDepth( 110, 110, 24, 4 );
  globalThis.testSet_110x110x24_cm3 = new HeightWidthDepth( 110, 110, 24, 3 );
  globalThis.testSet_110x110x24_cm2 = new HeightWidthDepth( 110, 110, 24, 2 );
  globalThis.testSet_110x110x24_cm1 = new HeightWidthDepth( 110, 110, 24, 1 );

  globalThis.testSet_110x110x24_All = [
    globalThis.testSet_110x110x24_cm8,
    globalThis.testSet_110x110x24_cm4,
    globalThis.testSet_110x110x24_cm3,
    globalThis.testSet_110x110x24_cm2,
    globalThis.testSet_110x110x24_cm1,
  ];
}

function testResultSame() {
  for ( let i = 0; i < globalThis.testSet_110x110x24_All.length; ++i ) {
    let testSet = globalThis.testSet_110x110x24_All[ i ];
    testSet.testResultSame();
  }
}

function testDifferentDisposeStrategy_All() {
  for ( let i = 0; i < globalThis.testSet_110x110x24_All.length; ++i ) {
    let testSet = globalThis.testSet_110x110x24_All[ i ];
    testSet.testDifferentDisposeStrategy_All();
  }
}

function disposeTensors() {
  for ( let i = 0; i < globalThis.testSet_110x110x24_All.length; ++i ) {
    let testSet = globalThis.testSet_110x110x24_All[ i ];
    testSet.disposeTensors();
  }

  globalThis.testSet_110x110x24_g8
    = globalThis.testSet_110x110x24_g4
    = globalThis.testSet_110x110x24_g3
    = globalThis.testSet_110x110x24_g2
    = globalThis.testSet_110x110x24_g1
    = null;
}
<|endoftext|>