<commit_before>
function get(id) { return document.getElementById(id); }
function create(name) { return document.createElement(name); }
function show(e) { e.style.display='block'; }
function hide(e) { e.style.display='none'; }
function addClass(e, c) { e.classList.add(c); } //HTML5!
function removeClass(e, c) { e.classList.remove(c); }
function setText(id, txt) { get(id).innerHTML = txt; }
function inArray(item, array) { return array.indexOf(item) != -1; }

function split(str)
{
	if(typeof str != 'string')
		return [];
	var a = str.match(/[^\s]+/g);
	return (a ? a : []);
}

function uniq(arr)
{
  var obj = {};
  for(var i in arr) obj[arr[i]] = 0;
  return Object.keys(obj);
}

//remove an item from a string list
function removeItem(str, item)
{
	var array = split(str);
	for(var i in array)
		if(array[i] == item)
			array.splice(i, 1);
	return array.join(' ');
}

function addItem(str, item)
{
	var array = split(str);
	for(var i in array)
		if(array[i] == item)
			return str;
	array.push(item);
	return array.join(' ');
}

function replaceItem(str, old_item, new_item)
{
	var array = split(str);
	for(var i in array)
		if(array[i] == old_item)
			array[i] = new_item;
	return array.join(' ');
}

//to config file syntax
function toUCI(pkg_obj)
{
	var str = "\n";
	for(var sid in pkg_obj)
	{
		if(sid == "pchanged")
			continue;

		var options = pkg_obj[sid];
		var sname = (sid.substring(0, 3) != "cfg") ? (" '"+sid+"'") : "";
		str += "config "+options.stype+sname+"\n";
		for(var oname in options)
		{
			if(oname == "stype")
				continue;
			var value = options[oname];
			if(typeof value == 'object')
			{
				for(var i in value)
					str += "	list "+oname+" '"+value[i]+"'\n";
			}
			else
				str += "	option "+oname+" '"+value+"'\n";
		}
		str += "\n";
	}
	return str;
}

// parses output from one or multiple
// calls like "uci export -qn foo"
function fromUCI(pkgs_str)
{
	var pkg_objs = {};
	var pkg;
	var cfg;

	var lines = pkgs_str.split("\n");
	for(var i = 0; i < lines.length; ++i)
	{
		var line = lines[i];
		var items = split(line);
		if(items.length < 2) continue;
		switch(items[0])
		{
			case 'package':
				pkg = { pchanged : false };
				pkg_objs[items[1]] = pkg;
				break;
			case 'config':
				var val = (items.length == 3) ? line.match(/'(.*)'/)[1] : ("cfg"+(++gid));
				cfg = { stype : items[1] };
				pkg[val] = cfg;
				break;
			case 'option':
				var val = line.match(/'(.*)'/)[1];
				cfg[items[1]] = val;
				break;
			case 'list':
				var val = line.match(/'(.*)'/)[1];
				if(!(items[1] in cfg)) cfg[items[1]] = [];
				cfg[items[1]].push(val);
				break;
		}
	}
	return pkg_objs;
}

function firstSectionID(obj, stype)
{
	for(var id in obj)
		if(obj[id].stype == stype)
			return id;
}

function config_foreach(objs, stype, func)
{
	for(var key in objs)
	{
		var obj = objs[key];
		if(obj["stype"] == stype)
			func(key, obj);
	}
}

function params(obj)
{
	var str = "";
	for(var key in obj) {
		if(str.length) str += "&";
		else str += "?";
		str += encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]);
	}
	return str.replace(/%20/g, "+");
}

function send(url, obj, func)
{
	url += params(obj);
	jx.load(url, func, 'text');
}

function onDesc(e, tag, func)
{
	for(var i = 0; i < e.childNodes.length; ++i) {
		var c = e.childNodes[i];
		if(c.tagName == tag && func(c) == false) return;
		onDesc(c, tag, func);
	}
}

function onChilds(e, tag, func)
{
	for(var i = 0; i < e.childNodes.length; ++i) {
		var c = e.childNodes[i];
		if(c.tagName == tag && func(c) == false) return;
	}
}

function onParents(e, tag, func)
{
	while(e != document) {
		e = e.parentNode;
		if(e.tagName == tag && func(e) == false) return;
	}
}

function removeChilds(p)
{
	while(p.hasChildNodes())
		p.removeChild(p.firstChild);
}

function show_error(data)
{
	var is_error = (data.substr(0, 3) == "(E)");
	if(is_error)
		setText('msg', data);
	return is_error;
}

function checkName(name)
{
	if(/[\w_]{2,12}/.test(name))
		return true;
	alert("Name '"+name+"' ist ung\xfcltig.");
	return false;
}

function addInputCheck(input, regex, msg)
{
	var prev_value = input.value;
	input.onchange = function(e) {
		if(regex.test(input.value))
			return;
		alert(msg);
		input.value = prev_value;
		e.stopPropagation();
	};
}

function collect_inputs(p, obj)
{
	if(p.tagName == "SELECT")
		obj[p.name] = p.value;
	if(p.tagName == "INPUT")
		if(p.type == "text" || (p.type == "radio" && p.checked))
			obj[p.name] = p.value
		else if(p.type == "checkbox" && p.checked)
		{
			var v = obj[p.name];
			v = (typeof v == "undefined") ? p.value : (v + " " + p.value);
			obj[p.name] = v;
		}

	for(var i = 0; i < p.childNodes.length; ++i)
		collect_inputs(p.childNodes[i], obj);
}

function append(parent, tag, id)
{
	var e = create(tag);
	if(id) e.id = id;
	parent.appendChild(e);
	return e;
}

function append_section(parent, title, id)
{
	var fs = append(parent, "fieldset");
	var lg = create("legend");
	lg.innerHTML = title;
	if(id) fs.id = id;
	fs.appendChild(lg);
	return fs;
}

function append_button(parent, text, onclick)
{
	var button = append(parent, 'button');
	button.type = 'button';
	button.innerHTML = text;
	button.onclick = onclick;
	return button;
}

function append_label(parent, title, value)
{
	var div = append(parent, 'div');
	var label = append(div, 'label');
	label.innerHTML = title + ":";

	if(typeof value == 'string')
	{
		//div.className = "label_option";
		var span = append(div, 'span');
		span.innerHTML = value;
	}
	else
	{
		div.className = "list_option";
		var span = append(div, 'span');
		for(var i in value)
		{
			var d = append(span, 'div');
			d.innerHTML = value[i];
		}
	}
	return div;
}

function append_options(parent, name, selected, choices)
{
	var select = append(parent, 'select');
	select.style.minWidth = "5em";
	select.name = name;
	for(var i in choices)
	{
		var s = (typeof choices[i] != 'object');
		var choice_text = " " + (s ? choices[i] : choices[i][0]);
		var choice_value = "" + (s ? choices[i] : choices[i][1]);

		var option = append(select, 'option');
		option.value = choice_value;
		option.selected = (choice_value == selected) ? "selected" : "";
		option.innerHTML= choice_text;
	}
}

function append_selection(parent, title, name, selected, choices)
{
	var p = append(parent, 'div');
	var label = append(p, 'label');

	p.className = "select_option";
	label.innerHTML = title + ":";

	append_options(p, name, selected, choices);
	return p;
}

//append an input field
//e.g. append_input(parent, "Name", "name_string", "MyName")
function append_input(parent, title, name, value)
{
	var div = append(parent, 'div');
	var label = create('label');
	var input = create('input');

	label.innerHTML = title + ":";
	input.value = (typeof value == "undefined") ? "" : value;
	input.name = name;
	input.type = "text";

	div.appendChild(label);
	div.appendChild(input);

	return div;
}

//append a radio field
//e.g. append_radio(parent, "Enabled", "enabled", 0, [["Yes", 1], ["No", 0])
function append_radio(parent, title, name, selected, choices) {
	return _selection("radio", parent, title, name, [selected], choices);
}

//append a checkbox field
//e.g. append_check(parent, "Enabled", "enabled", ["grass"], [["Grass", "grass"], ["Butter", "butter"]])
function append_check(parent, title, name, selected, choices) {
	return _selection("checkbox", parent, title, name, selected, choices);
}

function _selection(type, parent, title, name, selected, choices)
{
	var p = append(parent, 'div');
	var label = append(p, 'label');
	var span = append(p, 'span');

	p.className = "radio_option";
	label.innerHTML = title + ":";

	for (var i in choices)
	{
		var s = (typeof choices[i] == 'string');
		var choice_text = "" + (s ? choices[i] : choices[i][0]);
		var choice_value = "" + (s ? choices[i] : choices[i][1]);

		var div = append(span, 'div');
		var input = append(div, 'input');
		var label = append(div, 'label');

		input.name = name;
		input.value = choice_value;
		input.type = type;
		if(inArray(choice_value, selected))
			input.checked = "checked"

		label.innerHTML = " " + choice_text;

		if(choice_text == "_")
			hide(div);
	}
	return p;
}

//from jx_compressed.js
jx={getHTTPObject:function(){var A=false;if(typeof ActiveXObject!="undefined"){try{A=new ActiveXObject("Msxml2.XMLHTTP")}catch(C){try{A=new ActiveXObject("Microsoft.XMLHTTP")}catch(B){A=false}}}else{if(window.XMLHttpRequest){try{A=new XMLHttpRequest()}catch(C){A=false}}}return A},load:function(url,callback,format){var http=this.init();if(!http||!url){return }if(http.overrideMimeType){http.overrideMimeType("text/xml")}if(!format){var format="text"}format=format.toLowerCase();var now="uid="+new Date().getTime();url+=(url.indexOf("?")+1)?"&":"?";url+=now;http.open("GET",url,true);http.onreadystatechange=function(){if(http.readyState==4){if(http.status==200){var result="";if(http.responseText){result=http.responseText}if(format.charAt(0)=="j"){result=result.replace(/[\n\r]/g,"");result=eval("("+result+")")}if(callback){callback(result)}}else{if(error){error(http.status)}}}};http.send(null)},init:function(){return this.getHTTPObject()}}
<commit_msg>add the ability for config_foreach to stop as soon the caller returns 1<commit_after>
function get(id) { return document.getElementById(id); }
function create(name) { return document.createElement(name); }
function show(e) { e.style.display='block'; }
function hide(e) { e.style.display='none'; }
function addClass(e, c) { e.classList.add(c); } //HTML5!
function removeClass(e, c) { e.classList.remove(c); }
function setText(id, txt) { get(id).innerHTML = txt; }
function inArray(item, array) { return array.indexOf(item) != -1; }

function split(str)
{
	if(typeof str != 'string')
		return [];
	var a = str.match(/[^\s]+/g);
	return (a ? a : []);
}

function uniq(arr)
{
  var obj = {};
  for(var i in arr) obj[arr[i]] = 0;
  return Object.keys(obj);
}

//remove an item from a string list
function removeItem(str, item)
{
	var array = split(str);
	for(var i in array)
		if(array[i] == item)
			array.splice(i, 1);
	return array.join(' ');
}

function addItem(str, item)
{
	var array = split(str);
	for(var i in array)
		if(array[i] == item)
			return str;
	array.push(item);
	return array.join(' ');
}

function replaceItem(str, old_item, new_item)
{
	var array = split(str);
	for(var i in array)
		if(array[i] == old_item)
			array[i] = new_item;
	return array.join(' ');
}

//to config file syntax
function toUCI(pkg_obj)
{
	var str = "\n";
	for(var sid in pkg_obj)
	{
		if(sid == "pchanged")
			continue;

		var options = pkg_obj[sid];
		var sname = (sid.substring(0, 3) != "cfg") ? (" '"+sid+"'") : "";
		str += "config "+options.stype+sname+"\n";
		for(var oname in options)
		{
			if(oname == "stype")
				continue;
			var value = options[oname];
			if(typeof value == 'object')
			{
				for(var i in value)
					str += "	list "+oname+" '"+value[i]+"'\n";
			}
			else
				str += "	option "+oname+" '"+value+"'\n";
		}
		str += "\n";
	}
	return str;
}

// parses output from one or multiple
// calls like "uci export -qn foo"
function fromUCI(pkgs_str)
{
	var pkg_objs = {};
	var pkg;
	var cfg;

	var lines = pkgs_str.split("\n");
	for(var i = 0; i < lines.length; ++i)
	{
		var line = lines[i];
		var items = split(line);
		if(items.length < 2) continue;
		switch(items[0])
		{
			case 'package':
				pkg = { pchanged : false };
				pkg_objs[items[1]] = pkg;
				break;
			case 'config':
				var val = (items.length == 3) ? line.match(/'(.*)'/)[1] : ("cfg"+(++gid));
				cfg = { stype : items[1] };
				pkg[val] = cfg;
				break;
			case 'option':
				var val = line.match(/'(.*)'/)[1];
				cfg[items[1]] = val;
				break;
			case 'list':
				var val = line.match(/'(.*)'/)[1];
				if(!(items[1] in cfg)) cfg[items[1]] = [];
				cfg[items[1]].push(val);
				break;
		}
	}
	return pkg_objs;
}

function firstSectionID(obj, stype)
{
	for(var id in obj)
		if(obj[id].stype == stype)
			return id;
}

function config_foreach(objs, stype, func)
{
	for(var key in objs)
	{
		var obj = objs[key];
		if(obj["stype"] == stype && func(key, obj))
			return;
	}
}

function params(obj)
{
	var str = "";
	for(var key in obj) {
		if(str.length) str += "&";
		else str += "?";
		str += encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]);
	}
	return str.replace(/%20/g, "+");
}

function send(url, obj, func)
{
	url += params(obj);
	jx.load(url, func, 'text');
}

function onDesc(e, tag, func)
{
	for(var i = 0; i < e.childNodes.length; ++i) {
		var c = e.childNodes[i];
		if(c.tagName == tag && func(c) == false) return;
		onDesc(c, tag, func);
	}
}

function onChilds(e, tag, func)
{
	for(var i = 0; i < e.childNodes.length; ++i) {
		var c = e.childNodes[i];
		if(c.tagName == tag && func(c) == false) return;
	}
}

function onParents(e, tag, func)
{
	while(e != document) {
		e = e.parentNode;
		if(e.tagName == tag && func(e) == false) return;
	}
}

function removeChilds(p)
{
	while(p.hasChildNodes())
		p.removeChild(p.firstChild);
}

function show_error(data)
{
	var is_error = (data.substr(0, 3) == "(E)");
	if(is_error)
		setText('msg', data);
	return is_error;
}

function checkName(name)
{
	if(/[\w_]{2,12}/.test(name))
		return true;
	alert("Name '"+name+"' ist ung\xfcltig.");
	return false;
}

function addInputCheck(input, regex, msg)
{
	var prev_value = input.value;
	input.onchange = function(e) {
		if(regex.test(input.value))
			return;
		alert(msg);
		input.value = prev_value;
		e.stopPropagation();
	};
}

function collect_inputs(p, obj)
{
	if(p.tagName == "SELECT")
		obj[p.name] = p.value;
	if(p.tagName == "INPUT")
		if(p.type == "text" || (p.type == "radio" && p.checked))
			obj[p.name] = p.value
		else if(p.type == "checkbox" && p.checked)
		{
			var v = obj[p.name];
			v = (typeof v == "undefined") ? p.value : (v + " " + p.value);
			obj[p.name] = v;
		}

	for(var i = 0; i < p.childNodes.length; ++i)
		collect_inputs(p.childNodes[i], obj);
}

function append(parent, tag, id)
{
	var e = create(tag);
	if(id) e.id = id;
	parent.appendChild(e);
	return e;
}

function append_section(parent, title, id)
{
	var fs = append(parent, "fieldset");
	var lg = create("legend");
	lg.innerHTML = title;
	if(id) fs.id = id;
	fs.appendChild(lg);
	return fs;
}

function append_button(parent, text, onclick)
{
	var button = append(parent, 'button');
	button.type = 'button';
	button.innerHTML = text;
	button.onclick = onclick;
	return button;
}

function append_label(parent, title, value)
{
	var div = append(parent, 'div');
	var label = append(div, 'label');
	label.innerHTML = title + ":";

	if(typeof value == 'string')
	{
		//div.className = "label_option";
		var span = append(div, 'span');
		span.innerHTML = value;
	}
	else
	{
		div.className = "list_option";
		var span = append(div, 'span');
		for(var i in value)
		{
			var d = append(span, 'div');
			d.innerHTML = value[i];
		}
	}
	return div;
}

function append_options(parent, name, selected, choices)
{
	var select = append(parent, 'select');
	select.style.minWidth = "5em";
	select.name = name;
	for(var i in choices)
	{
		var s = (typeof choices[i] != 'object');
		var choice_text = " " + (s ? choices[i] : choices[i][0]);
		var choice_value = "" + (s ? choices[i] : choices[i][1]);

		var option = append(select, 'option');
		option.value = choice_value;
		option.selected = (choice_value == selected) ? "selected" : "";
		option.innerHTML= choice_text;
	}
}

function append_selection(parent, title, name, selected, choices)
{
	var p = append(parent, 'div');
	var label = append(p, 'label');

	p.className = "select_option";
	label.innerHTML = title + ":";

	append_options(p, name, selected, choices);
	return p;
}

//append an input field
//e.g. append_input(parent, "Name", "name_string", "MyName")
function append_input(parent, title, name, value)
{
	var div = append(parent, 'div');
	var label = create('label');
	var input = create('input');

	label.innerHTML = title + ":";
	input.value = (typeof value == "undefined") ? "" : value;
	input.name = name;
	input.type = "text";

	div.appendChild(label);
	div.appendChild(input);

	return div;
}

//append a radio field
//e.g. append_radio(parent, "Enabled", "enabled", 0, [["Yes", 1], ["No", 0])
function append_radio(parent, title, name, selected, choices) {
	return _selection("radio", parent, title, name, [selected], choices);
}

//append a checkbox field
//e.g. append_check(parent, "Enabled", "enabled", ["grass"], [["Grass", "grass"], ["Butter", "butter"]])
function append_check(parent, title, name, selected, choices) {
	return _selection("checkbox", parent, title, name, selected, choices);
}

function _selection(type, parent, title, name, selected, choices)
{
	var p = append(parent, 'div');
	var label = append(p, 'label');
	var span = append(p, 'span');

	p.className = "radio_option";
	label.innerHTML = title + ":";

	for (var i in choices)
	{
		var s = (typeof choices[i] == 'string');
		var choice_text = "" + (s ? choices[i] : choices[i][0]);
		var choice_value = "" + (s ? choices[i] : choices[i][1]);

		var div = append(span, 'div');
		var input = append(div, 'input');
		var label = append(div, 'label');

		input.name = name;
		input.value = choice_value;
		input.type = type;
		if(inArray(choice_value, selected))
			input.checked = "checked"

		label.innerHTML = " " + choice_text;

		if(choice_text == "_")
			hide(div);
	}
	return p;
}

//from jx_compressed.js
jx={getHTTPObject:function(){var A=false;if(typeof ActiveXObject!="undefined"){try{A=new ActiveXObject("Msxml2.XMLHTTP")}catch(C){try{A=new ActiveXObject("Microsoft.XMLHTTP")}catch(B){A=false}}}else{if(window.XMLHttpRequest){try{A=new XMLHttpRequest()}catch(C){A=false}}}return A},load:function(url,callback,format){var http=this.init();if(!http||!url){return }if(http.overrideMimeType){http.overrideMimeType("text/xml")}if(!format){var format="text"}format=format.toLowerCase();var now="uid="+new Date().getTime();url+=(url.indexOf("?")+1)?"&":"?";url+=now;http.open("GET",url,true);http.onreadystatechange=function(){if(http.readyState==4){if(http.status==200){var result="";if(http.responseText){result=http.responseText}if(format.charAt(0)=="j"){result=result.replace(/[\n\r]/g,"");result=eval("("+result+")")}if(callback){callback(result)}}else{if(error){error(http.status)}}}};http.send(null)},init:function(){return this.getHTTPObject()}}
<|endoftext|>


<commit_before>import React from 'react';
import styles from './styles.css';
import { getVisibleSelectionRect } from 'draft-js';

// TODO make toolbarHeight to be determined or a parameter
const toolbarHeight = 40;

export default class Toolbar extends React.Component {

  state = {
    isVisisble: false,
  }

  componentWillMount() {
    this.props.store.subscribeToItem('isVisible', this.onVisibilityChanged);
  }

  onVisibilityChanged = (isVisible) => {
    const selectionRect = isVisible ? getVisibleSelectionRect(window) : undefined;
    const position = selectionRect ? {
      top: selectionRect.top + window.scrollY - toolbarHeight,
      left: selectionRect.left + window.scrollX,
    } : {};
    this.setState({
      isVisible,
      position
    });
  }

  render() {
    // if (!this.state.isVisible) {
    //   return null;
    // }

    return (
      <div
        className={styles.toolbar}
        style={this.state.position}
      >
        {this.props.structure.map((Component, index) => (
          <Component
            key={index}
            getEditorState={this.props.store.getItem('getEditorState')}
            setEditorState={this.props.store.getItem('setEditorState')}
          />
        ))}
      </div>
    );
  }
}
<commit_msg>hide toolbar in case no text is selected<commit_after>import React from 'react';
import styles from './styles.css';
import { getVisibleSelectionRect } from 'draft-js';

// TODO make toolbarHeight to be determined or a parameter
const toolbarHeight = 40;

export default class Toolbar extends React.Component {

  state = {
    isVisisble: false,
  }

  componentWillMount() {
    this.props.store.subscribeToItem('isVisible', this.onVisibilityChanged);
  }

  onVisibilityChanged = (isVisible) => {
    const selectionRect = isVisible ? getVisibleSelectionRect(window) : undefined;
    const position = selectionRect ? {
      top: selectionRect.top + window.scrollY - toolbarHeight,
      left: selectionRect.left + window.scrollX,
    } : {};
    this.setState({
      isVisible,
      position
    });
  }

  render() {
    if (!this.state.isVisible) {
      return null;
    }

    return (
      <div
        className={styles.toolbar}
        style={this.state.position}
      >
        {this.props.structure.map((Component, index) => (
          <Component
            key={index}
            getEditorState={this.props.store.getItem('getEditorState')}
            setEditorState={this.props.store.getItem('setEditorState')}
          />
        ))}
      </div>
    );
  }
}
<|endoftext|>


<commit_before>/**
 * @class  	WebAlloy
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

/**
 * @property config
 * @property {String} [config.jsExt=".jslocal"] The extension to use for Javascript files
 */
exports.config = _.extend({
	jsExt: '.jslocal'
}, Alloy.CFG.T ? Alloy.CFG.T.weballoy : {});

var libDir = [];
var helpers = {};

function embedFile(f) {
	var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, f);
	if ( ! file.exists()) {
		Ti.API.debug('Weballoy: File not found (' + f + ')');
		return null;
	}

	return file;
}

function getFileText(f) {
	var file = embedFile(f);
	if (file == null) return '';
	return file.read().text;
}

function embedCSS(f) {
	var file = embedFile(f);
	if (file == null) return '';
	return '<link rel="stylesheet" href="' + file.nativePath + (ENV_DEVELOPMENT ? '?v='+Math.random() : '') + '" />';
}

function embedJS(f) {
	var file = embedFile(f);
	if (file == null) return '';
	return '';
}

function getHTML(opt) {
	var tpl_data = _.extend({}, helpers, opt.webdata);

	// Include head (styles)
	var html = '<!DOCTYPE html><meta charset="utf-8" />';
	html += '<meta name="viewport" content="width=device-width; initial-scale=1; minimum-scale=1; maximum-scale=1; user-scalable=no;" />';

	// Install the global event handler for this specific WebView
	html += '';

	// Include global css
	html += embedCSS('web/app.css');
	if (opt.name) {
		html += embedCSS('web/styles/' + opt.name + '.css');
	}

	html += '';

	html += _.template(getFileText('web/app.tpl'))(tpl_data);

	// Include template
	html += '
';

	if (opt.content) {
		html += _.template(opt.content)(tpl_data);
	} else if (opt.name) {
		html += _.template(getFileText('web/views/' + opt.name + '.tpl'))(tpl_data);
	}

	html += '
';

	// Include libs
	_.each(libDir, function(js) {
		html += embedJS(js);
	});

	// Include footer
	html += embedJS('web/app' + exports.config.jsExt);
	if (opt.name) {
		html += embedJS('web/controllers/' + opt.name + exports.config.jsExt);
	}

	html += '';

	tpl = null;
	return html;
}

/**
 * Add an helper for the WebView
 * @param {String} 		name   The name of the helper
 * @param {Function} 	method The callback
 */
exports.addHelper = function(name, method) {
	helpers[name] = method;
};

/**
 * @method createView
 * @param  {Object} args Arguments for the view.
 * @return {Ti.UI.WebView}
 */
exports.createView = function(args) {
	args = args || {};
	args.uniqid = _.uniqueId();

	var $ui = Ti.UI.createWebView(_.extend({
		disableBounce: true,
		enableZoomControls: false,
		hideLoadIndicator: true,
		scalesPageToFit: false,
		backgroundColor: 'transparent',
		html: getHTML(args)
	}, args));

	$ui.addEventListener('load', function() {
		if (args.autoHeight) {
			$ui.height = Math.floor( $ui.evalJS('document.documentElement.offsetHeight') );
		}
		if (_.isFunction(args.onLoad)) {
			args.onLoad.call($ui);
		}
	});

	$ui._ = function(js) {
		return $ui.evalJS(js);
	};

	$ui.call = function() {
		var args = _.map(Array.prototype.slice.call(arguments, 1), function(a) { return JSON.stringify(a); });
		return $ui._( arguments[0] + '(' + args.join(',') + ')' );
	};

	$ui.$ = function(selector) {
		return {
			call: function() {
				var args = _.map(Array.prototype.slice.call(arguments, 1), function(a) { return JSON.stringify(a); });
				return $ui._( 'document.querySelector("' + selector + '").' + arguments[0] + '(' + args.join(',') + ')' );
			},
			get: function(name) {
				return $ui._( 'document.querySelector("' + selector + '").' + name );
			},
			set: function(name, value) {
				return $ui._( 'document.querySelector("' + selector + '").' + name + ' = ' + JSON.stringify(value) );
			}
		};
	};

	$ui.render = function(data) {
		$ui.$('#main').set('innerHTML', $ui.tpl(_.extend({}, helpers, data)));
	};

	// Install the API listener
	if (args.webapi != null) {

		var webapiListener = function(event) {
			if (!_.isFunction(args.webapi[event.name])) return;
			args.webapi[event.name].call($ui, event.data);
		};

		Ti.App.addEventListener('__weballoy_' + args.uniqid, webapiListener);
		$ui.webapiUnbind = function() {
			Ti.App.removeEventListener('__weballoy_' + args.uniqid, webapiListener);
		};
	}

	return $ui;
};

/*
Init
*/

var jsFiles = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'web/lib').getDirectoryListing();
_.each(jsFiles, function(js) {
	libDir.push('web/lib/'+js);
});
<commit_msg>Solved bug<commit_after>/**
 * @class  	WebAlloy
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

/**
 * @property config
 * @property {String} [config.jsExt=".jslocal"] The extension to use for Javascript files
 */
exports.config = _.extend({
	jsExt: '.jslocal'
}, Alloy.CFG.T ? Alloy.CFG.T.weballoy : {});

var libDir = [];
var helpers = {};

function embedFile(f) {
	var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, f);
	if ( ! file.exists()) {
		Ti.API.debug('Weballoy: File not found (' + f + ')');
		return null;
	}

	return file;
}

function getFileText(f) {
	var file = embedFile(f);
	if (file == null) return '';
	return file.read().text;
}

function embedCSS(f) {
	var file = embedFile(f);
	if (file == null) return '';
	return '<link rel="stylesheet" href="' + file.nativePath + (ENV_DEVELOPMENT ? '?v='+Math.random() : '') + '" />';
}

function embedJS(f) {
	var file = embedFile(f);
	if (file == null) return '';
	return '';
}

function getHTML(opt) {
	var tpl_data = _.extend({}, helpers, opt.webdata);

	// Include head (styles)
	var html = '<!DOCTYPE html><meta charset="utf-8" />';
	html += '<meta name="viewport" content="width=device-width; initial-scale=1; minimum-scale=1; maximum-scale=1; user-scalable=no;" />';
	html += ''; //iOS auto expand font BUG

	// Install the global event handler for this specific WebView
	html += '';

	// Include global css
	html += embedCSS('web/app.css');
	if (opt.name) {
		html += embedCSS('web/styles/' + opt.name + '.css');
	}

	html += '';

	html += _.template(getFileText('web/app.tpl'))(tpl_data);

	// Include template
	html += '
';

	if (opt.content) {
		html += _.template(opt.content)(tpl_data);
	} else if (opt.name) {
		html += _.template(getFileText('web/views/' + opt.name + '.tpl'))(tpl_data);
	}

	html += '
';

	// Include libs
	_.each(libDir, function(js) {
		html += embedJS(js);
	});

	// Include footer
	html += embedJS('web/app' + exports.config.jsExt);
	if (opt.name) {
		html += embedJS('web/controllers/' + opt.name + exports.config.jsExt);
	}

	html += '';

	tpl = null;
	return html;
}

/**
 * Add an helper for the WebView
 * @param {String} 		name   The name of the helper
 * @param {Function} 	method The callback
 */
exports.addHelper = function(name, method) {
	helpers[name] = method;
};

/**
 * @method createView
 * @param  {Object} args Arguments for the view.
 * @return {Ti.UI.WebView}
 */
exports.createView = function(args) {
	args = args || {};
	args.uniqid = _.uniqueId();

	var $ui = Ti.UI.createWebView(_.extend({
		disableBounce: true,
		enableZoomControls: false,
		hideLoadIndicator: true,
		scalesPageToFit: false,
		backgroundColor: 'transparent',
		html: getHTML(args)
	}, args));

	$ui.addEventListener('load', function() {
		if (args.autoHeight) {
			$ui.height = Math.floor( $ui.evalJS('document.documentElement.offsetHeight') );
		}
		if (_.isFunction(args.onLoad)) {
			args.onLoad.call($ui);
		}
	});

	$ui._ = function(js) {
		return $ui.evalJS(js);
	};

	$ui.call = function() {
		var args = _.map(Array.prototype.slice.call(arguments, 1), function(a) { return JSON.stringify(a); });
		return $ui._( arguments[0] + '(' + args.join(',') + ')' );
	};

	$ui.$ = function(selector) {
		return {
			call: function() {
				var args = _.map(Array.prototype.slice.call(arguments, 1), function(a) { return JSON.stringify(a); });
				return $ui._( 'document.querySelector("' + selector + '").' + arguments[0] + '(' + args.join(',') + ')' );
			},
			get: function(name) {
				return $ui._( 'document.querySelector("' + selector + '").' + name );
			},
			set: function(name, value) {
				return $ui._( 'document.querySelector("' + selector + '").' + name + ' = ' + JSON.stringify(value) );
			}
		};
	};

	$ui.render = function(data) {
		$ui.$('#main').set('innerHTML', $ui.tpl(_.extend({}, helpers, data)));
	};

	// Install the API listener
	if (args.webapi != null) {

		var webapiListener = function(event) {
			if (!_.isFunction(args.webapi[event.name])) return;
			args.webapi[event.name].call($ui, event.data);
		};

		Ti.App.addEventListener('__weballoy_' + args.uniqid, webapiListener);
		$ui.webapiUnbind = function() {
			Ti.App.removeEventListener('__weballoy_' + args.uniqid, webapiListener);
		};
	}

	return $ui;
};

/*
Init
*/

var jsFiles = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, 'web/lib').getDirectoryListing();
_.each(jsFiles, function(js) {
	libDir.push('web/lib/'+js);
});
<|endoftext|>


<commit_before>document.getElementById("ayuda").setAttribute("aria-current", "page");

var aside = document.getElementById("complementario");
var h = document.createElement("H5");
var t = document.createTextNode("Formulario para obtener información sobre complementos en GitHub");
h.appendChild(t);
aside.appendChild(h);
var form = document.createElement("FORM");
form.setAttribute("role", "form");
var p = document.createElement("P");
var label = document.createElement("LABEL");
label.setAttribute("for", "repo");
t = document.createTextNode("cuenta/repositorio de GitHub");
label.appendChild(t);
var input = document.createElement("INPUT");
input.setAttribute("type", "text");
input.setAttribute("id", "repo");
input.setAttribute("name", "repo");
input.setAttribute("placeholder", "Ejemplo: nvdaes/emoticons");
label.appendChild(input);
var submit = document.createElement("INPUT");
submit.setAttribute("id", "submit");
submit.setAttribute("type", "button");
submit.setAttribute("value", "Consultar descargas de última versión");
p.appendChild(label);
form.appendChild(p);
form.appendChild(submit);
aside.appendChild(form);

$(document).ready(function () {
	$("#submit").click(function () {
		$.getJSON("https://api.github.com/repos/" + input.value + "/releases/latest", function(json) {
			if (json == null) {
				alert("Repositorio no encontrado");
			} else {}
				var assetName = json.assets[0].name;
				var downloadCount = json.assets[0].download_count;
				alert(assetName + " " + downloadCount);
			}
		});
	});
});

<commit_msg>Remove symbol<commit_after>document.getElementById("ayuda").setAttribute("aria-current", "page");

var aside = document.getElementById("complementario");
var h = document.createElement("H5");
var t = document.createTextNode("Formulario para obtener información sobre complementos en GitHub");
h.appendChild(t);
aside.appendChild(h);
var form = document.createElement("FORM");
form.setAttribute("role", "form");
var p = document.createElement("P");
var label = document.createElement("LABEL");
label.setAttribute("for", "repo");
t = document.createTextNode("cuenta/repositorio de GitHub");
label.appendChild(t);
var input = document.createElement("INPUT");
input.setAttribute("type", "text");
input.setAttribute("id", "repo");
input.setAttribute("name", "repo");
input.setAttribute("placeholder", "Ejemplo: nvdaes/emoticons");
label.appendChild(input);
var submit = document.createElement("INPUT");
submit.setAttribute("id", "submit");
submit.setAttribute("type", "button");
submit.setAttribute("value", "Consultar descargas de última versión");
p.appendChild(label);
form.appendChild(p);
form.appendChild(submit);
aside.appendChild(form);

$(document).ready(function () {
	$("#submit").click(function () {
		$.getJSON("https://api.github.com/repos/" + input.value + "/releases/latest", function(json) {
			if (json == null) {
				alert("Repositorio no encontrado");
			} else {
				var assetName = json.assets[0].name;
				var downloadCount = json.assets[0].download_count;
				alert(assetName + " " + downloadCount);
			}
		});
	});
});

<|endoftext|>


<commit_before>document.getElementById("ayuda").setAttribute("aria-current", "page");

var aside = document.getElementById("complementario");
var button = document.createElement("BUTTON");
button.setAttribute("id", "button");
var buttonText = document.createTextNode("Información sobre complementos de nvdaes");
button.appendChild(buttonText);
aside.appendChild(button);

addons = [
	"clipContentsDesigner",
	"emoticons",
	"eMule",
	"placeMarkers",
	"readFeeds",
	"reportSymbols",
]

var addonsLength = addons.length;

$(document).ready(function () {
	/*$("#addonsButton").click(function () {
		for (var i = 0; i < addonsLength; i++) {
			var details = document.createElement("DETAILS");
			var summary = document.createElement("SUMMARY");
			var t = document.createTextNode(addons[i]);
			summary.appendChild(t);
			details.appendChild(summary);
			$.getJSON("https://api.github.com/repos/nvdaes/" + addons[i] + "/releases/latest", function(json) {
				var name = json.name;
				var ul = document.createElement("UL");
				var li = document.createElement("LI");
				var t = document.createTextNode(name);
				li.appendChild(t);
				ul.appendChild(li);")
				details.appendChild(ul);
				aside.appendChild(details);
			});
		}
	});*/
});
<commit_msg>Update script<commit_after>document.getElementById("ayuda").setAttribute("aria-current", "page");

var aside = document.getElementById("complementario");
var button = document.createElement("BUTTON");
button.setAttribute("id", "addonsButton");
var buttonText = document.createTextNode("Información sobre complementos de nvdaes");
button.appendChild(buttonText);
aside.appendChild(button);

addons = [
	"clipContentsDesigner",
	"emoticons",
	"eMule",
	"placeMarkers",
	"readFeeds",
	"reportSymbols",
]

var addonsLength = addons.length;

$(document).ready(function () {
	$("#addonsButton").click(function () {
		for (var i = 0; i < addonsLength; i++) {
			var details = document.createElement("DETAILS");
			var summary = document.createElement("SUMMARY");
			var t = document.createTextNode(addons[i]);
			summary.appendChild(t);
			details.appendChild(summary);
			$.getJSON("https://api.github.com/repos/nvdaes/" + addons[i] + "/releases/latest", function(json) {
				var name = json.name;
				var ul = document.createElement("UL");
				var li = document.createElement("LI");
				var t = document.createTextNode(name);
				li.appendChild(t);
				ul.appendChild(li);")
				details.appendChild(ul);
				aside.appendChild(details);
			});
		}
	});
});
<|endoftext|>


<commit_before>class Board {
    // Creates a new board object
    // This is the stuff that should be coming from the view
    constructor(width, height, gameWidth, gameHeight, inputs, outputs, pieces){
        this.layout = new Array(gameWidth);
        for(var i = 0; i < gameWidth; i++){
            this.layout[i] = new Array(gameHeight);
        }
        this.wireStyle = new Array(gameWidth);
        for(var i = 0; i < gameWidth; i++){
            this.wireStyle[i] = new Array(gameHeight);
        }
        this.answer = new Array(gameWidth);
        for(var i = 0; i < gameWidth; i++){
            this.answer[i] = new Array(gameHeight);
        }
        this.inputs = inputs;
        this.outputs = outputs;
        this.pieces = pieces;
        this.width = width;
        this.height = height;
        this.state = 0;
    }

    // Uses "private" vars so we also calc dim unit size
    set width(width) {
        this._width = width;
        this.updateBoardDim();
    }
    get width() {
        return this._width;
    }
    set height(height) {
        this._height = height;
        this.updateBoardDim();
    }
    get height() {
        return this._height;
    }

    // Dinamicaly set the unit scale of pieces based on the new width and height
    updateBoardDim() {
        // Find a scale unit on the board
        // This is the number of pixels a square takes up
        var unitWidth = Math.trunc((this.width - 20) / this.gameWidth);
        var unitHeight = Math.trunc((this.height - 30) / (this.gameHeight + 1));
        if (unitWidth < unitHeight) {
            this._unit = unitWidth;
        } else {
            this._unit = unitHeight;
        }
        this._inputLocations = new Array(this.inputs.length);
        var seperation = Math.trunc(this.gameHeight / this.inputs.length);
        var start = Math.trunc(seperation / 2);
        this._inputLocations[0] = start;
        for (var i = 1; i < this.inputs.length; i++) {
            this._inputLocations[i] = start + (i * seperation);
        }
        this._outputLocations = new Array(this.inputs.length);
        seperation = Math.trunc(this.gameHeight / this.outputs.length);
        start = Math.trunc(seperation / 2);
        this._outputLocations[0] = start;
        for (var i = 1; i < this.outputs.length; i++) {
            this._outputLocations[i] = start + (i * seperation);
        }
    }

    // Returns the private unit calculation
    get unit() {
        return this._unit;
    }

    // Commom values that are needed in a lot of places so can be got
    // as if they were variables themselves
    get gameWidth() { return this.layout.length; }
    get gameHeight() { return this.layout[0].length; }
    get boardWidth() { return this.unit * this.gameWidth; }
    get boardHeight() { return this.unit * this.gameHeight; }
    get boardX() { return Math.trunc((this.width - this.boardWidth) / 2); }
    get boardY() { return Math.trunc((this.height - this.boardHeight - this.unit) / 2) - 5; }
    get inputLocations() { return this._inputLocations }
    get outputLocations() { return this._outputLocations }

    // These are common calculations that require extra bits of info such as x and y cords
    getBoardX(x) { return Math.trunc((x - this.boardX) / this.unit); }
    getBoardY(y) { return Math.trunc((y - this.boardY) / this.unit); }
    onBoard(x, y) { return 0 <= y && 0 <= x && y < this.gameHeight && x < this.gameWidth}

    /**
     * Returns a piece from the board and removes it from the board
     * based on x and y cordanate location
     *
     * @param x corordanate on the canvas that was drawn to
     * @param y corordanate on the canvas that was drawn to
     * @return game piece
     */
    getPiece(x, y) {
        // Start by seeing if the piece is in the y height of the dock
        var tmp = (y - this.boardY - this.boardHeight - 10);
        if (tmp > 0 && tmp < this.unit) {
            // Then check to see if there is a piece there for it
            tmp = this.getBoardX(x);
            if (0 <= tmp && tmp < this.pieces.length){
                // If there is remove the piece from the list and return it
                return this.pieces.splice(tmp, 1)[0];
            }
        } else {
            // Start by seing if the x, y is on the board
            var cx = this.getBoardX(x);
            var cy = this.getBoardY(y);
            if (this.onBoard(cx, cy)) {
                // If it is remove it and return it
                tmp = this.layout[cx][cy];
                this.layout[cx][cy] = undefined;
                this._updateWire(cx, cy);
                return tmp;
            }
        }
        return null;
    }

    /**
     * This sets a piece on the board based on screen cords to a piece id that is passed in
     *
     * @param x corodanate on the canvas that is drawn to
     * @param y corodanate on the canvas that is drawn to
     * @param p an id identifying what piece to place
     */
    setPiece(x, y, p) {
        // Make sure there is a piece and its not wire
        if (![0, null, undefined].includes(p)) {
            var cx = this.getBoardX(x);
            var cy = this.getBoardY(y);
            // Check to see if the location is on the board and the board doesn't already have a piece there
            if (this.onBoard(cx, cy) && [0, null, undefined].includes(this.layout[cx][cy])) {
                // If its good add it to the locaiton
                this.layout[cx][cy] = p;
                this._updateWire(cx, cy);
            } else {
                // The spot was invalid so we should add it to the end of the palate so we don't loose it
                this.pieces.push(p);
            }
        }
    }

    /**
     * This is for the drawing of wires on the board
     *
     * @param x corodanate on the canvas that is drawn to
     * @param y corodanate on the canvas that is drawn to
     * @param p an id identifying what piece was last clicked on
     */
    toogleWire(x, y, piece) {
        // If the piece that was given is a wire or nothing
        if ([0, null, undefined].includes(piece)) {
            var cx = this.getBoardX(x);
            var cy = this.getBoardY(y);
            // If the spot was on the board and not a piece
            if (this.onBoard(cx, cy) && [0, null, undefined].includes(this.layout[cx][cy])) {
                // Then set it to the oposite of the piece given
                this.layout[cx][cy] = (piece == 0) ? undefined : 0;
                this._updateWire(cx, cy);
            }
        }
    }

    // Only update the wires around the new one
    _updateWire(x, y) {
        this._setWire(x, y);
        if (x > 0) this._setWire(x - 1, y);
        if (x < this.gameWidth - 1) this._setWire(x + 1,  y);
        if (y > 0) this._setWire(x, y - 1);
        if (y < this.gameHeight - 1) this._setWire(x,  y + 1);
        this.calculate();
    }
    _setWire(x , y) {
        // console.log(x + " " + y);
        if(this.layout[x][y] != null) {
            var sides = new Array(4);
            // Left
            sides[0] = [0, 3].includes(this.layout[x][y])
                && ((x == 0 && this.inputLocations.includes(y))
                || (x > 0 && [0, 1, 2, 3].includes(this.layout[x - 1][y])));
            // Right
            sides[1] = (x == (this.gameWidth - 1) && this.outputLocations.includes(y))
                || (x < this.gameWidth - 1 && [0, 3].includes(this.layout[x + 1][y]));
            // Top
            if (this.layout[x][y] != 3) {
                sides[2] = (y > 0 && [0, 1, 2].includes(this.layout[x][y - 1]));
                // Bottom
                sides[3] = (y < this.gameHeight - 1 && [0, 1, 2].includes(this.layout[x][y + 1]));
            } else {
                sides[2] = sides[3] = false;
            }

            var num = 0
            sides.forEach(function(element, index, array){
                if (element) num = num | Math.pow(2, array.length - 1 - index);
            });
            this.wireStyle[x][y] = num;
        } else {
            this.wireStyle[x][y] = null;
        }
        // console.log(this.wireStyle);
    }

    calculate() {
        this.answer = new Array(this.gameWidth);
        for(var i = 0; i < this.gameWidth; i++){
            this.answer[i] = new Array(this.gameHeight);
        }

        // Create new queue
        this.queue = [];

        { // Set the starts to the input states
            var board = this;
            board.inputLocations.forEach(
                function(element, index){
                    board.answer[0][element] = (board.inputs[index][board.state] == 1)
                    board.queue.push([0, element]);
                }
            );
        }

        var num = 0;
        while (this.queue.length > 0) {
            var loc = this.queue.shift();
            if (this.queue.length < num ||
                ([0, 3].includes(this.layout[loc[0]][loc[1]])) ||
                    (
                        [1, 2].includes(this.layout[loc[0]][loc[1]]) &&
                            (loc[1] - 1 < 0 || this.answer[loc[0]][loc[1] - 1] != undefined) &&
                            (loc[1] + 1 >= this.gameHeight || this.answer[loc[0]][loc[1] + 1] != undefined)
                    )
            ) {
                // calulate from that spot
                this.visited = new Array(this.gameWidth);
                for(var i = 0; i < this.gameWidth; i++){
                    this.visited[i] = new Array(this.gameHeight);
                }
                this.visited[loc[0]][loc[1]] = true;
                // Switch the thing we are on every component calculates differently
                switch (this.layout[loc[0]][loc[1]]) {
                    case 0:
                        // Wire
                        this.visited[loc[0]][loc[1]] = false;
                        this.calcWire(loc[0] + 1, loc[1]);
                        this.calcWire(loc[0], loc[1] + 1);
                        this.calcWire(loc[0], loc[1] - 1);
                        break;
                    case 1:
                        // And
                        this.calcAnd(loc[0], loc[1]);
                        break;
                    case 2:
                        // Or
                        this.calcOr(loc[0], loc[1]);
                        break;
                    case 3:
                        // Not
                        this.calcNot(loc[0], loc[1]);
                        break;
                }
                num = 0;
            } else if (!(
                [1, 2].includes(this.layout[loc[0]][loc[1]]) &&
                    this.answer[loc[0]][loc[1]] != null
            )) {
                this.queue.push(loc);
                num += 1;
            }
        }
        console.log(this.answer);
    }

    calcWire(x, y) {
        // This is so we don't get stuck in an infinite loop
        // Only wires check for running loops
        if (!this.onBoard(x, y) || this.visited[x][y]) return;
        this.visited[x][y] = true;
        if ([1, 2].includes(this.layout[x][y])) {
            this.queue.push([x, y]);
        } else if (this.layout[x][y] == 3) {
            this.calcNot(x, y);
        } else if (this.layout[x][y] == 0) {
            // If any of the surrounding are true that the wire is true
            // only calculate the up and down if it is a wire
            this.answer[x][y] = (
                (this.onBoard(x + 1, y) && this.answer[x + 1][y]) ||
                    (this.onBoard(x - 1, y) && this.answer[x - 1][y]) ||
                    (this.onBoard(x, y + 1) && this.layout[x][y + 1] == 0 && this.answer[x][y + 1]) ||
                    (this.onBoard(x, y - 1) && this.layout[x][y - 1] == 0 && this.answer[x][y - 1])
            );

            // Only wires are omnidirectional
            this.calcWire(x, y + 1);
            this.calcWire(x, y - 1);
            this.calcWire(x + 1, y);
            this.calcWire(x - 1, y);
        }
    }
    calcAnd(x, y) {
        // TODO calc
        this.answer[x][y] = (
            (this.onBoard(x, y + 1) && this.layout[x][y + 1] == 0 && this.answer[x][y + 1]) &&
                (this.onBoard(x, y - 1) && this.layout[x][y - 1] == 0 && this.answer[x][y - 1])
        );
        this.calcWire(x + 1, y);
    }
    calcOr(x, y) {
        // TODO calc
        this.answer[x][y] = (
            (this.onBoard(x, y + 1) && this.layout[x][y + 1] == 0 && this.answer[x][y + 1]) ||
            (this.onBoard(x, y - 1) && this.layout[x][y - 1] == 0 && this.answer[x][y - 1])
        );
        this.calcWire(x + 1, y);
    }
    calcNot(x, y) {
        // TODO calc
        this.answer[x][y] = !(
            (this.onBoard(x - 1, y) && this.answer[x - 1][y])
        );
        this.calcWire(x + 1, y);
    }
}
<commit_msg>IT F***ING WORKSgit push<commit_after>class Board {
    // Creates a new board object
    // This is the stuff that should be coming from the view
    constructor(width, height, gameWidth, gameHeight, inputs, outputs, pieces){
        this.layout = new Array(gameWidth);
        for(var i = 0; i < gameWidth; i++){
            this.layout[i] = new Array(gameHeight);
        }
        this.wireStyle = new Array(gameWidth);
        for(var i = 0; i < gameWidth; i++){
            this.wireStyle[i] = new Array(gameHeight);
        }
        this.answer = new Array(gameWidth);
        for(var i = 0; i < gameWidth; i++){
            this.answer[i] = new Array(gameHeight);
        }
        this.inputs = inputs;
        this.outputs = outputs;
        this.pieces = pieces;
        this.width = width;
        this.height = height;
        this.state = 0;
    }

    // Uses "private" vars so we also calc dim unit size
    set width(width) {
        this._width = width;
        this.updateBoardDim();
    }
    get width() {
        return this._width;
    }
    set height(height) {
        this._height = height;
        this.updateBoardDim();
    }
    get height() {
        return this._height;
    }

    // Dinamicaly set the unit scale of pieces based on the new width and height
    updateBoardDim() {
        // Find a scale unit on the board
        // This is the number of pixels a square takes up
        var unitWidth = Math.trunc((this.width - 20) / this.gameWidth);
        var unitHeight = Math.trunc((this.height - 30) / (this.gameHeight + 1));
        if (unitWidth < unitHeight) {
            this._unit = unitWidth;
        } else {
            this._unit = unitHeight;
        }
        this._inputLocations = new Array(this.inputs.length);
        var seperation = Math.trunc(this.gameHeight / this.inputs.length);
        var start = Math.trunc(seperation / 2);
        this._inputLocations[0] = start;
        for (var i = 1; i < this.inputs.length; i++) {
            this._inputLocations[i] = start + (i * seperation);
        }
        this._outputLocations = new Array(this.inputs.length);
        seperation = Math.trunc(this.gameHeight / this.outputs.length);
        start = Math.trunc(seperation / 2);
        this._outputLocations[0] = start;
        for (var i = 1; i < this.outputs.length; i++) {
            this._outputLocations[i] = start + (i * seperation);
        }
    }

    // Returns the private unit calculation
    get unit() {
        return this._unit;
    }

    // Commom values that are needed in a lot of places so can be got
    // as if they were variables themselves
    get gameWidth() { return this.layout.length; }
    get gameHeight() { return this.layout[0].length; }
    get boardWidth() { return this.unit * this.gameWidth; }
    get boardHeight() { return this.unit * this.gameHeight; }
    get boardX() { return Math.trunc((this.width - this.boardWidth) / 2); }
    get boardY() { return Math.trunc((this.height - this.boardHeight - this.unit) / 2) - 5; }
    get inputLocations() { return this._inputLocations }
    get outputLocations() { return this._outputLocations }

    // These are common calculations that require extra bits of info such as x and y cords
    getBoardX(x) { return Math.trunc((x - this.boardX) / this.unit); }
    getBoardY(y) { return Math.trunc((y - this.boardY) / this.unit); }
    onBoard(x, y) { return 0 <= y && 0 <= x && y < this.gameHeight && x < this.gameWidth}

    /**
     * Returns a piece from the board and removes it from the board
     * based on x and y cordanate location
     *
     * @param x corordanate on the canvas that was drawn to
     * @param y corordanate on the canvas that was drawn to
     * @return game piece
     */
    getPiece(x, y) {
        // Start by seeing if the piece is in the y height of the dock
        var tmp = (y - this.boardY - this.boardHeight - 10);
        if (tmp > 0 && tmp < this.unit) {
            // Then check to see if there is a piece there for it
            tmp = this.getBoardX(x);
            if (0 <= tmp && tmp < this.pieces.length){
                // If there is remove the piece from the list and return it
                return this.pieces.splice(tmp, 1)[0];
            }
        } else {
            // Start by seing if the x, y is on the board
            var cx = this.getBoardX(x);
            var cy = this.getBoardY(y);
            if (this.onBoard(cx, cy)) {
                // If it is remove it and return it
                tmp = this.layout[cx][cy];
                this.layout[cx][cy] = undefined;
                this._updateWire(cx, cy);
                return tmp;
            }
        }
        return null;
    }

    /**
     * This sets a piece on the board based on screen cords to a piece id that is passed in
     *
     * @param x corodanate on the canvas that is drawn to
     * @param y corodanate on the canvas that is drawn to
     * @param p an id identifying what piece to place
     */
    setPiece(x, y, p) {
        // Make sure there is a piece and its not wire
        if (![0, null, undefined].includes(p)) {
            var cx = this.getBoardX(x);
            var cy = this.getBoardY(y);
            // Check to see if the location is on the board and the board doesn't already have a piece there
            if (this.onBoard(cx, cy) && [0, null, undefined].includes(this.layout[cx][cy])) {
                // If its good add it to the locaiton
                this.layout[cx][cy] = p;
                this._updateWire(cx, cy);
            } else {
                // The spot was invalid so we should add it to the end of the palate so we don't loose it
                this.pieces.push(p);
            }
        }
    }

    /**
     * This is for the drawing of wires on the board
     *
     * @param x corodanate on the canvas that is drawn to
     * @param y corodanate on the canvas that is drawn to
     * @param p an id identifying what piece was last clicked on
     */
    toogleWire(x, y, piece) {
        // If the piece that was given is a wire or nothing
        if ([0, null, undefined].includes(piece)) {
            var cx = this.getBoardX(x);
            var cy = this.getBoardY(y);
            // If the spot was on the board and not a piece
            if (this.onBoard(cx, cy) && [0, null, undefined].includes(this.layout[cx][cy])) {
                // Then set it to the oposite of the piece given
                this.layout[cx][cy] = (piece == 0) ? undefined : 0;
                this._updateWire(cx, cy);
            }
        }
    }

    // Only update the wires around the new one
    _updateWire(x, y) {
        this._setWire(x, y);
        if (x > 0) this._setWire(x - 1, y);
        if (x < this.gameWidth - 1) this._setWire(x + 1,  y);
        if (y > 0) this._setWire(x, y - 1);
        if (y < this.gameHeight - 1) this._setWire(x,  y + 1);
        this.calculate();
    }
    _setWire(x , y) {
        // console.log(x + " " + y);
        if(this.layout[x][y] != null) {
            var sides = new Array(4);
            // Left
            sides[0] = [0, 3].includes(this.layout[x][y])
                && ((x == 0 && this.inputLocations.includes(y))
                || (x > 0 && [0, 1, 2, 3].includes(this.layout[x - 1][y])));
            // Right
            sides[1] = (x == (this.gameWidth - 1) && this.outputLocations.includes(y))
                || (x < this.gameWidth - 1 && [0, 3].includes(this.layout[x + 1][y]));
            // Top
            if (this.layout[x][y] != 3) {
                sides[2] = (y > 0 && [0, 1, 2].includes(this.layout[x][y - 1]));
                // Bottom
                sides[3] = (y < this.gameHeight - 1 && [0, 1, 2].includes(this.layout[x][y + 1]));
            } else {
                sides[2] = sides[3] = false;
            }

            var num = 0
            sides.forEach(function(element, index, array){
                if (element) num = num | Math.pow(2, array.length - 1 - index);
            });
            this.wireStyle[x][y] = num;
        } else {
            this.wireStyle[x][y] = null;
        }
        // console.log(this.wireStyle);
    }

    calculate() {
        this.answer = new Array(this.gameWidth);
        for(var i = 0; i < this.gameWidth; i++){
            this.answer[i] = new Array(this.gameHeight);
        }

        // Create new queue
        this.queue = [];

        { // Set the starts to the input states
            var board = this;
            board.inputLocations.forEach(
                function(element, index){
                    board.answer[0][element] = (board.inputs[index][board.state] == 1)
                    board.queue.push([0, element]);
                }
            );
        }

        var num = 0;
        while (this.queue.length > 0) {
            var loc = this.queue.shift();
            if (!(
                [1, 2].includes(this.layout[loc[0]][loc[1]]) &&
                    this.answer[loc[0]][loc[1]] != null
            )) {
                if (this.queue.length < num ||
                    ([0, 3].includes(this.layout[loc[0]][loc[1]])) ||
                        (
                            [1, 2].includes(this.layout[loc[0]][loc[1]]) &&
                                (loc[1] - 1 < 0 || this.answer[loc[0]][loc[1] - 1] != undefined) &&
                                (loc[1] + 1 >= this.gameHeight || this.answer[loc[0]][loc[1] + 1] != undefined)
                        )
                ) {
                    // calulate from that spot
                    this.visited = new Array(this.gameWidth);
                    for(var i = 0; i < this.gameWidth; i++){
                        this.visited[i] = new Array(this.gameHeight);
                    }
                    this.visited[loc[0]][loc[1]] = true;
                    // Switch the thing we are on every component calculates differently
                    switch (this.layout[loc[0]][loc[1]]) {
                        case 0:
                            // Starting wire only
                            this.visited[loc[0]][loc[1]] = false;
                            this.calcWire(loc[0] + 1, loc[1]);
                            this.calcWire(loc[0], loc[1] + 1);
                            this.calcWire(loc[0], loc[1] - 1);
                            break;
                        case 1:
                            // And
                            this.calcAnd(loc[0], loc[1]);
                            break;
                        case 2:
                            // Or
                            this.calcOr(loc[0], loc[1]);
                            break;
                        case 3:
                            // Not
                            this.calcNot(loc[0], loc[1]);
                            break;
                    }
                    num = 0;
                } else {
                    this.queue.push(loc);
                    num += 1;
                }
            }
        }
        console.log(this.answer);
    }

    calcWire(x, y) {
        // This is so we don't get stuck in an infinite loop
        // Only wires check for running loops
        if (!this.onBoard(x, y) || this.visited[x][y]) return;
        this.visited[x][y] = true;
        if ([1, 2].includes(this.layout[x][y])) {
            this.queue.push([x, y]);
        } else if (this.layout[x][y] == 3) {
            this.calcNot(x, y);
        } else if (this.layout[x][y] == 0) {
            // If any of the surrounding are true that the wire is true
            // only calculate the up and down if it is a wire
            this.answer[x][y] = (
                (this.onBoard(x + 1, y) && this.answer[x + 1][y]) ||
                    (this.onBoard(x - 1, y) && this.answer[x - 1][y]) ||
                    (this.onBoard(x, y + 1) && this.layout[x][y + 1] == 0 && this.answer[x][y + 1]) ||
                    (this.onBoard(x, y - 1) && this.layout[x][y - 1] == 0 && this.answer[x][y - 1])
            );

            // Only wires are omnidirectional
            this.calcWire(x, y + 1);
            this.calcWire(x, y - 1);
            this.calcWire(x + 1, y);
            this.calcWire(x - 1, y);
        }
    }
    calcAnd(x, y) {
        // TODO calc
        this.answer[x][y] = (
            (this.onBoard(x, y + 1) && this.layout[x][y + 1] == 0 && this.answer[x][y + 1]) &&
                (this.onBoard(x, y - 1) && this.layout[x][y - 1] == 0 && this.answer[x][y - 1])
        );
        this.calcWire(x + 1, y);
    }
    calcOr(x, y) {
        // TODO calc
        this.answer[x][y] = (
            (this.onBoard(x, y + 1) && this.layout[x][y + 1] == 0 && this.answer[x][y + 1]) ||
            (this.onBoard(x, y - 1) && this.layout[x][y - 1] == 0 && this.answer[x][y - 1])
        );
        this.calcWire(x + 1, y);
    }
    calcNot(x, y) {
        // TODO calc
        this.answer[x][y] = !(
            (this.onBoard(x - 1, y) && this.answer[x - 1][y])
        );
        this.calcWire(x + 1, y);
    }
}
<|endoftext|>


<commit_before>// BRAIN INFO //
const inputs = 3;
const outputs = 5 + memories;

const testInput = [];
for (let i = 0; i < inputs; i++) {
	testInput.push(seededNoise(-1, 1));
}

// Creature.prototype creates a neural network composed of layers and axons
Creature.prototype.createNeuralNetwork = function () {
	// VARIABLES //
	this.inputs = inputs + this.eyes.length * 2;

	let layers = [this.inputs + outputs, Math.ceil((this.inputs + outputs * 2) / 2), outputs];
	let forgetLayers = [this.inputs + outputs * 2, Math.ceil((this.inputs + outputs * 3) / 2), outputs];
	let decideLayers = [this.inputs + outputs, Math.ceil((this.inputs + outputs * 2) / 2), outputs];
	let modifyLayers = [this.inputs + outputs * 2, Math.ceil((this.inputs + outputs * 3) / 2), outputs];

	this.network = new Network(forgetLayers, decideLayers, modifyLayers, layers, this);

	this.initNeurons(); // Creature.prototype initializes the neurons, creating them, Neurons contain a value and are the connection point for axons
	this.initAxons(); // Axons are basically lines that connect Neurons, each one has a weight, and each neuron has a value, the axon takes the value and multiplies it by the weight
};

function Network(forget, decide, modify, main, par) {
	this.main = {
		layers: main
	};

	this.forget = {
		layers: forget
	};

	this.decide = {
		layers: decide
	};

	this.modify = {
		layers: modify
	};

	this.cellState = [];
	for (let i = 0; i < outputs; i++) this.cellState.push(0);

	this.output = [];
	for (let i = 0; i < outputs; i++) this.output.push(0);

	this.parent = par;
}

Creature.prototype.initNeurons = function () {
	for (let brain in this.network) {
		if (brain == "cellState") break;

		this.network[brain].neurons = [];

		let layers = this.network[brain].layers.length;

		for (let layer = 0; layer < layers; layer++) {
			this.network[brain].neurons.push([]);

			let neurons = this.network[brain].layers[layer];
			for (let neuron = 0; neuron < neurons; neuron++) {
				this.network[brain].neurons[layer].push(0);
			}
		}
	}
};

Creature.prototype.initAxons = function () {
	for (let brain in this.network) {
		if (brain == "cellState") break;

		this.network[brain].axons = [];

		this.network[brain].biasAxons = [];

		let layers = this.network[brain].layers.length - 1;
		for (let layer = 0; layer < layers; layer++) {
			let layerWeights = [];

			let neurons = this.network[brain].layers[layer];
			let neuronsInNextLayer = this.network[brain].layers[layer + 1];

			for (let neuron = 0; neuron < neurons; neuron++) {
				let neuronWeights = [];
				for (let axon = 0; axon < neuronsInNextLayer; axon++) {
					let weight = 0;

					if (seededNoise() < connectionDensity) {
						weight = seededNoise(-maxInitialAxonValue, maxInitialAxonValue) / neurons;
					}

					neuronWeights.push(weight);
				}
				layerWeights.push(neuronWeights);
			}

			this.network[brain].axons.push(layerWeights);

			layerWeights = [];

			for (let axon = 0; axon < neuronsInNextLayer; axon++) {
				let weight = 0;

				if (seededNoise() < connectionDensity) {
					weight = seededNoise(-maxInitialAxonValue, maxInitialAxonValue);
				}

				layerWeights.push(weight);
			}

			this.network[brain].biasAxons.push(layerWeights);
		}
	}
};

// Creature.prototype feeds the neuron values through the axons, and all the way to the end of the network.
Creature.prototype.feedForward = function (input) {
	let cellStateLength = this.network.cellState.length;
	for (let brain in this.network) {
		if (brain == "cellState") break;

		let nbrain = this.network[brain];

		for (let neuron = 0; neuron < this.inputs; neuron++) {
			nbrain.neurons[0][neuron] = input[neuron] || 0;
		}

		for (let op = 0; op < outputs; op++) {
			nbrain.neurons[0][this.inputs + op] = this.network.output[op] || 0;
		}

		if (brain == "forget" || brain == "modify") {
			for (let cs = 0; cs < cellStateLength; cs++) {
				nbrain.neurons[0][this.inputs + outputs + cs] = this.network.cellState[cs] || 0;
			}
		}

		let layers = nbrain.layers.length - 1;

		for (let layer = 0; layer < layers; layer++) {
			let neuronsInLayer = nbrain.layers[layer];
			let neuronsInNextLayer = nbrain.layers[layer + 1];

			for (let axon = 0; axon < neuronsInNextLayer; axon++) { // Loops through each axon
				let value = 0;

				for (let neuron = 0; neuron <= neuronsInLayer; neuron++) { // For each axon position (neuron in next layer) loop through all of the neurons in this layer
					if (neuron == neuronsInLayer) {
						value += nbrain.biasAxons[layer][axon] * bias; // add bias neuron (independent)
					} else {
						value += nbrain.axons[layer][neuron][axon] * nbrain.neurons[layer][neuron]; // add all neuron values times weight of their respective axon
					}

				}

				if (brain == "forget" || brain == "modify" || brain == "main") {
					nbrain.neurons[layer + 1][axon] = 1 / (1 + Math.exp(-value)); // set neuron in next layer value to sigmoid
				} else {
					nbrain.neurons[layer + 1][axon] = Math.tanh(value); // set neuron in next layer value to tanh
				}
			}
		}
	}

	for (let i = 0; i < cellStateLength; i++) {
		this.network.cellState[i] *= this.network.forget.neurons[this.network.forget.neurons.length - 1][i];
		this.network.cellState[i] += this.network.decide.neurons[this.network.decide.neurons.length - 1][i] * this.network.modify.neurons[this.network.modify.neurons.length - 1][i];
		this.network.main.neurons[this.network.main.neurons.length - 1][i] *= Math.tanh(this.network.cellState[i]);
	}

	this.network.output = this.network.main.neurons[this.network.main.neurons.length - 1];

	return this.network.output;
};

// Modifies weights of the axons
Creature.prototype.mutate = function () {
	let rand = seededNoise(0, 100);

	if (rand < this.mutability.children / 2) {
		this.children += 1;
		if (this.children < minChildren) this.children = minChildren;
	} else if (rand < this.mutability.children) {
		this.children -= 1;
		if (this.children > maxChildren) this.children = maxChildren;
	}

	rand = seededNoise(0, 100);

	if (rand < this.mutability.size / 2) {
		this.size /= 1.03;
		if (this.size < minCreatureSize) this.size = minCreatureSize;
	} else if (rand < this.mutability.size) {
		this.size *= 1.03;
		if (this.size > maxCreatureSize) this.size = maxCreatureSize;
	}

	rand = seededNoise(0, 100);

	if (rand < this.mutability.size / 10) {
		this.size /= 1.1;
		if (this.size < minCreatureSize) this.size = minCreatureSize;
	} else if (rand < this.mutability.size / 5) {
		this.size *= 1.1;
		if (this.size > maxCreatureSize) this.size = maxCreatureSize;
	}

	rand = seededNoise(0, 100);

	if (rand < this.mutability.childEnergy / 2) {
		this.childEnergy /= 1.03;
		if (this.childEnergy < minChildEnergy) this.childEnergy = minChildEnergy;
	} else if (rand < this.mutability.childEnergy) {
		this.childEnergy *= 1.03;
		if (this.childEnergy > maxChildEnergy) this.childEnergy = maxChildEnergy;
	}

	let eyes = this.eyes.length;
	for (let i = eyes - 1; i >= 0; i--) {
		rand = seededNoise(0, 100);
		if (rand < this.mutability.eyes.angle) {
			let eye = this.eyes[i];

			eye.angle += seededNoise(-maxEyeAngleChange, maxEyeAngleChange);
			if (eye.angle < 0) eye.angle = 0;
			else if (eye.angle > 2 * Math.PI) eye.angle = 2 * Math.PI;
		}

		rand = seededNoise(0, 100);

		if (rand < this.mutability.eyes.distance) {
			let eye = this.eyes[i];

			eye.distance += seededNoise(-maxEyeDistanceChange, maxEyeDistanceChange);
			if (eye.distance < minEyeDistance) eye.distance = minEyeDistance;
			else if (eye.distance > maxEyeDistance) eye.angle = maxEyeDistance;
		}

		rand = seededNoise(0, 100);

		if (rand < this.mutability.eyes.number / 2 && this.eyes.length < maxEyes) {
			this.eyes.push(new this.eye(this));
		} else if (rand < this.mutability.eyes.number && this.eyes.length > minEyes) {
			let eye = this.eyes[i];

			this.eyes.splice(this.eyes.indexOf(eye), 1);
		}
	}

	for (let property in this.mutability) {
		rand = seededNoise(0, 100);

		if (property == "eyes") {
			for (let sec in this.mutability[property]) {
				rand = seededNoise(0, 100);

				if (rand < this.mutability.mutability) {
					this.mutability[property][sec] += seededNoise(-maxMutabilityChange, maxMutabilityChange);

					if (this.mutability[property][sec] < minMutability[property][sec]) this.mutability[property][sec] = minMutability[property][sec];
					else if (this.mutability[property][sec] > maxMutability[property][sec]) this.mutability[property][sec] = maxMutability[property][sec];
				}
			}
		} else if (rand < this.mutability.mutability) {
			this.mutability[property] += seededNoise(-maxMutabilityChange, maxMutabilityChange);

			if (this.mutability[property] < minMutability[property]) this.mutability[property] = minMutability[property];
			else if (this.mutability[property] > maxMutability[property]) this.mutability[property] = maxMutability[property];
		}
	}
};

Network.prototype.mutate = function () {
	for (let brain in this) {
		if (brain == "cellState") break;
		for (let layer = 0; layer < this[brain].axons.length; layer++) {
			for (let neuron = 0; neuron < this[brain].axons[layer].length; neuron++) {
				for (let axon = 0; axon < this[brain].axons[layer][neuron].length; axon++) {
					let weight = this[brain].axons[layer][neuron][axon];
					let randomNumber = seededNoise(0, 100);

					if (randomNumber < this.parent.mutability.brain / 2) {
						weight += seededNoise(-stepAmount, stepAmount);
					} else if (randomNumber < this.parent.mutability.brain) {
						weight = 0;
					}

					this[brain].axons[layer][neuron][axon] = weight;
				}
			}
		}

		for (let layer = 0; layer < this[brain].biasAxons.length; layer++) {
			for (let axon = 0; axon < this[brain].biasAxons[layer].length; axon++) {
				let weight = this[brain].biasAxons[layer][axon];
				let randomNumber = seededNoise(0, 100);

				if (randomNumber < this.parent.mutability.brain / 2) {
					weight += seededNoise(-stepAmount, stepAmount);
				} else if (randomNumber < this.parent.mutability.brain) {
					weight = 0;
				}

				this[brain].biasAxons[layer][axon] = weight;
			}
		}
	}
}

Creature.prototype.copyNeuralNetwork = function (copy) {
	for (let brain in this.network) {
		if (brain == "cellState") break;
		let netw = copy.network[brain].layers[0] < this.network[brain].layers[0] ? copy.network[brain] : this.network[brain];

		for (let layer = 0; layer < netw.axons.length; layer++) {
			for (let neuron = 0; neuron < netw.axons[layer].length; neuron++) {
				for (let axon = 0; axon < netw.axons[layer][neuron].length; axon++) {
					this.network[brain].axons[layer][neuron][axon] = copy.network[brain].axons[layer][neuron][axon];
				}
			}
		}

		for (let layer = 0; layer < netw.biasAxons.length; layer++) {
			for (let axon = 0; axon < netw.biasAxons[layer].length; axon++) {
				this.network[brain].biasAxons[layer][axon] = copy.network[brain].biasAxons[layer][axon];
			}
		}
	}
};<commit_msg>another slight performance boost by storing variables<commit_after>// BRAIN INFO //
const inputs = 3;
const outputs = 5 + memories;

const testInput = [];
for (let i = 0; i < inputs; i++) {
	testInput.push(seededNoise(-1, 1));
}

// Creature.prototype creates a neural network composed of layers and axons
Creature.prototype.createNeuralNetwork = function () {
	// VARIABLES //
	this.inputs = inputs + this.eyes.length * 2;

	let layers = [this.inputs + outputs, Math.ceil((this.inputs + outputs * 2) / 2), outputs];
	let forgetLayers = [this.inputs + outputs * 2, Math.ceil((this.inputs + outputs * 3) / 2), outputs];
	let decideLayers = [this.inputs + outputs, Math.ceil((this.inputs + outputs * 2) / 2), outputs];
	let modifyLayers = [this.inputs + outputs * 2, Math.ceil((this.inputs + outputs * 3) / 2), outputs];

	this.network = new Network(forgetLayers, decideLayers, modifyLayers, layers, this);

	this.initNeurons(); // Creature.prototype initializes the neurons, creating them, Neurons contain a value and are the connection point for axons
	this.initAxons(); // Axons are basically lines that connect Neurons, each one has a weight, and each neuron has a value, the axon takes the value and multiplies it by the weight
};

function Network(forget, decide, modify, main, par) {
	this.main = {
		layers: main
	};

	this.forget = {
		layers: forget
	};

	this.decide = {
		layers: decide
	};

	this.modify = {
		layers: modify
	};

	this.cellState = [];
	for (let i = 0; i < outputs; i++) this.cellState.push(0);

	this.output = [];
	for (let i = 0; i < outputs; i++) this.output.push(0);

	this.parent = par;
}

Creature.prototype.initNeurons = function () {
	for (let brain in this.network) {
		if (brain == "cellState") break;

		this.network[brain].neurons = [];

		let layers = this.network[brain].layers.length;

		for (let layer = 0; layer < layers; layer++) {
			this.network[brain].neurons.push([]);

			let neurons = this.network[brain].layers[layer];
			for (let neuron = 0; neuron < neurons; neuron++) {
				this.network[brain].neurons[layer].push(0);
			}
		}
	}
};

Creature.prototype.initAxons = function () {
	for (let brain in this.network) {
		if (brain == "cellState") break;

		this.network[brain].axons = [];

		this.network[brain].biasAxons = [];

		let layers = this.network[brain].layers.length - 1;
		for (let layer = 0; layer < layers; layer++) {
			let layerWeights = [];

			let neurons = this.network[brain].layers[layer];
			let neuronsInNextLayer = this.network[brain].layers[layer + 1];

			for (let neuron = 0; neuron < neurons; neuron++) {
				let neuronWeights = [];
				for (let axon = 0; axon < neuronsInNextLayer; axon++) {
					let weight = 0;

					if (seededNoise() < connectionDensity) {
						weight = seededNoise(-maxInitialAxonValue, maxInitialAxonValue) / neurons;
					}

					neuronWeights.push(weight);
				}
				layerWeights.push(neuronWeights);
			}

			this.network[brain].axons.push(layerWeights);

			layerWeights = [];

			for (let axon = 0; axon < neuronsInNextLayer; axon++) {
				let weight = 0;

				if (seededNoise() < connectionDensity) {
					weight = seededNoise(-maxInitialAxonValue, maxInitialAxonValue);
				}

				layerWeights.push(weight);
			}

			this.network[brain].biasAxons.push(layerWeights);
		}
	}
};

// Creature.prototype feeds the neuron values through the axons, and all the way to the end of the network.
Creature.prototype.feedForward = function (input) {
	let network = this.network;
	let cellStateLength = network.cellState.length;

	for (let brain in network) {
		if (brain == "cellState") break;

		let nbrain = network[brain];

		for (let neuron = 0; neuron < this.inputs; neuron++) {
			nbrain.neurons[0][neuron] = input[neuron] || 0;
		}

		for (let op = 0; op < outputs; op++) {
			nbrain.neurons[0][this.inputs + op] = network.output[op] || 0;
		}

		if (brain == "forget" || brain == "modify") {
			for (let cs = 0; cs < cellStateLength; cs++) {
				nbrain.neurons[0][this.inputs + outputs + cs] = network.cellState[cs] || 0;
			}
		}

		let layers = nbrain.layers.length - 1;

		let neuronsInNextLayer;
		for (let layer = 0; layer < layers; layer++) {
			let neuronsInLayer = neuronsInNextLayer || nbrain.layers[layer];
			neuronsInNextLayer = nbrain.layers[layer + 1];

			for (let axon = 0; axon < neuronsInNextLayer; axon++) { // Loops through each axon
				let value = 0;

				for (let neuron = 0; neuron <= neuronsInLayer; neuron++) { // For each axon position (neuron in next layer) loop through all of the neurons in this layer
					if (neuron == neuronsInLayer) {
						value += nbrain.biasAxons[layer][axon] * bias; // add bias neuron (independent)
					} else {
						value += nbrain.axons[layer][neuron][axon] * nbrain.neurons[layer][neuron]; // add all neuron values times weight of their respective axon
					}
				}

				if (brain == "forget" || brain == "modify" || brain == "main") {
					nbrain.neurons[layer + 1][axon] = 1 / (1 + Math.exp(-value)); // set neuron in next layer value to sigmoid
				} else {
					nbrain.neurons[layer + 1][axon] = Math.tanh(value); // set neuron in next layer value to tanh
				}
			}
		}
	}

	let forgetOutput = network.forget.neurons[network.forget.neurons.length - 1];
	let decideOutput = network.decide.neurons[network.decide.neurons.length - 1];
	let modifyOutput = network.modify.neurons[network.modify.neurons.length - 1];
	network.output = network.main.neurons[network.main.neurons.length - 1];
	for (let i = 0; i < cellStateLength; i++) {
		network.cellState[i] *= forgetOutput[i];
		network.cellState[i] += decideOutput[i] * modifyOutput[i];
		network.output[i] *= Math.tanh(network.cellState[i]);
	}

	return network.output;
};

// Modifies weights of the axons
Creature.prototype.mutate = function () {
	let mutability = this.mutability;

	let rand = seededNoise(0, 100);

	if (rand < mutability.children / 2) {
		this.children += 1;
		if (this.children < minChildren) this.children = minChildren;
	} else if (rand < mutability.children) {
		this.children -= 1;
		if (this.children > maxChildren) this.children = maxChildren;
	}

	rand = seededNoise(0, 100);

	if (rand < mutability.size / 2) {
		this.size /= 1.03;
		if (this.size < minCreatureSize) this.size = minCreatureSize;
	} else if (rand < mutability.size) {
		this.size *= 1.03;
		if (this.size > maxCreatureSize) this.size = maxCreatureSize;
	}

	rand = seededNoise(0, 100);

	if (rand < mutability.size / 10) {
		this.size /= 1.1;
		if (this.size < minCreatureSize) this.size = minCreatureSize;
	} else if (rand < mutability.size / 5) {
		this.size *= 1.1;
		if (this.size > maxCreatureSize) this.size = maxCreatureSize;
	}

	rand = seededNoise(0, 100);

	if (rand < mutability.childEnergy / 2) {
		this.childEnergy /= 1.03;
		if (this.childEnergy < minChildEnergy) this.childEnergy = minChildEnergy;
	} else if (rand < mutability.childEnergy) {
		this.childEnergy *= 1.03;
		if (this.childEnergy > maxChildEnergy) this.childEnergy = maxChildEnergy;
	}

	let eyes = this.eyes.length;
	for (let i = eyes - 1; i >= 0; i--) {
		rand = seededNoise(0, 100);
		if (rand < mutability.eyes.angle) {
			let eye = this.eyes[i];

			eye.angle += seededNoise(-maxEyeAngleChange, maxEyeAngleChange);
			if (eye.angle < 0) eye.angle = 0;
			else if (eye.angle > 2 * Math.PI) eye.angle = 2 * Math.PI;
		}

		rand = seededNoise(0, 100);

		if (rand < mutability.eyes.distance) {
			let eye = this.eyes[i];

			eye.distance += seededNoise(-maxEyeDistanceChange, maxEyeDistanceChange);
			if (eye.distance < minEyeDistance) eye.distance = minEyeDistance;
			else if (eye.distance > maxEyeDistance) eye.angle = maxEyeDistance;
		}

		rand = seededNoise(0, 100);

		if (rand < mutability.eyes.number / 2 && this.eyes.length < maxEyes) {
			this.eyes.push(new this.eye(this));
		} else if (rand < mutability.eyes.number && this.eyes.length > minEyes) {
			let eye = this.eyes[i];

			this.eyes.splice(this.eyes.indexOf(eye), 1);
		}
	}

	for (let property in mutability) {
		rand = seededNoise(0, 100);

		if (property == "eyes") {
			for (let sec in mutability[property]) {
				rand = seededNoise(0, 100);

				if (rand < mutability.mutability) {
					mutability[property][sec] += seededNoise(-maxMutabilityChange, maxMutabilityChange);

					if (mutability[property][sec] < minMutability[property][sec]) mutability[property][sec] = minMutability[property][sec];
					else if (mutability[property][sec] > maxMutability[property][sec]) mutability[property][sec] = maxMutability[property][sec];
				}
			}
		} else if (rand < mutability.mutability) {
			mutability[property] += seededNoise(-maxMutabilityChange, maxMutabilityChange);

			if (mutability[property] < minMutability[property]) mutability[property] = minMutability[property];
			else if (mutability[property] > maxMutability[property]) mutability[property] = maxMutability[property];
		}
	}
};

Network.prototype.mutate = function () {
	for (let brain in this) {
		if (brain == "cellState") break;
		let nbrain = this[brain];

		let layers = nbrain.layers.length - 1;
		for (let layer = 0; layer < layers; layer++) {
			let neurons = nbrain.layers[layer];
			let neuronsInNextLayer = nbrain.layers[layer + 1];

			for (let axon = 0; axon < neuronsInNextLayer; axon++) {
				for (let neuron = 0; neuron <= neurons; neuron++) {
					let randomNumber = seededNoise(0, 100);

					if (neuron == neurons) {
						if (randomNumber < this.parent.mutability.brain / 2) {
							nbrain.biasAxons[layer][axon] += seededNoise(-stepAmount, stepAmount);
						} else if (randomNumber < this.parent.mutability.brain) {
							nbrain.biasAxons[layer][axon] = 0;
						}
					} else {
						if (randomNumber < this.parent.mutability.brain / 2) {
							nbrain.axons[layer][neuron][axon] += seededNoise(-stepAmount, stepAmount);
						} else if (randomNumber < this.parent.mutability.brain) {
							nbrain.axons[layer][neuron][axon] = 0;
						}
					}
				}
			}
		}
	}
}

Creature.prototype.copyNeuralNetwork = function (copy) {
	for (let brain in this.network) {
		if (brain == "cellState") break;
		let netw = copy.network[brain].layers[0] < this.network[brain].layers[0] ? copy.network[brain] : this.network[brain];

		for (let layer = 0; layer < netw.axons.length; layer++) {
			for (let neuron = 0; neuron < netw.axons[layer].length; neuron++) {
				for (let axon = 0; axon < netw.axons[layer][neuron].length; axon++) {
					this.network[brain].axons[layer][neuron][axon] = copy.network[brain].axons[layer][neuron][axon];
				}
			}
		}

		for (let layer = 0; layer < netw.biasAxons.length; layer++) {
			for (let axon = 0; axon < netw.biasAxons[layer].length; axon++) {
				this.network[brain].biasAxons[layer][axon] = copy.network[brain].biasAxons[layer][axon];
			}
		}
	}
};<|endoftext|>


<commit_before>//Import dependencies
var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var header = require('gulp-header');
var sass = require('gulp-sass');

//Import configuration
var config = require('./config.js');

//Build the SCSS files
var buildCss = function()
{
  //Select all the SCSS files
  return gulp.src('scss/**/*.scss')

  //Build the scss files
  .pipe(sass().on('error', sass.logError))

  //Autoprefix
  .pipe(autoprefixer({ browsers: ['last 3 versions', 'IE 9'], cascade: false }))

  //Add the header
  .pipe(header(config.banner, { } ))

  //Save on the dist folder
  .pipe(gulp.dest(config.dist));
};

//Build the css files
buildCss();
<commit_msg>scripts/build.js: added minimize task<commit_after>//Import dependencies
var path = require('path');
var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var header = require('gulp-header');
var rename = require('gulp-rename');
var cleanCSS = require('gulp-clean-css');
var sass = require('gulp-sass');
var keue = require('keue');

//Import configuration
var config = require('./config.js');

//Initialize the new keue
var k = new keue(function(next)
{
  //Clean the output directory
  rmr.sync(config.dist);

  //Continue
  return next();
});

//Compile the css files
k.then(function(next)
{
  //Output stream
  var output = gulp.dest(config.dist);

  //Build task completed
  output.on('finish', function()
  {
    //Continue with the next task
    return next();
  });

  //Select all the SCSS files
  return gulp.src('scss/**/*.scss')

  //Build the scss files
  .pipe(sass().on('error', sass.logError))

  //Autoprefix
  .pipe(autoprefixer({ browsers: ['last 3 versions', 'IE 9'], cascade: false }))

  //Add the header
  .pipe(header(config.banner, { } ))

  //Save on the dist folder
  .pipe(output);
});

//Minimize the css files
k.then(function(next)
{
  //Output stream
  var output = gulp.dest(config.dist);

  //Build task completed
  output.on('finish', function()
  {
    //Continue with the next task
    return next();
  });

  //Set the source file
  return gulp.src(path.join(config.dist, './siimple-colors.css'))

  //Clean the css
  .pipe(cleanCSS({ compatibility: '*' }))

  //Rename the file
  .pipe(rename({ extname: '.min.css' }))

  //Add the header
  .pipe(header(config.banner, { } ))

  //Save on the dist folder
  .pipe(output);
});

//Queue finished
k.finish(function()
{
  //Display in console
  console.log('Build completed');
});

<|endoftext|>


<commit_before>// chrome.idle.setDetectionInterval(15*60)
// chrome.idle.onStateChanged.addListener((idleState) => {
//   chrome.ipcRenderer.send('dispatch-action', JSON.stringify({
//     actionType: 'app-idle-state-changed',
//     idleState
//   }))
// })
<commit_msg>Re-enable idle timer for ledger timer visits<commit_after>chrome.idle.setDetectionInterval(15 * 60)
chrome.idle.onStateChanged.addListener((idleState) => {
  chrome.ipcRenderer.send('dispatch-action', JSON.stringify({
    actionType: 'app-idle-state-changed',
    idleState
  }))
})
<|endoftext|>


<commit_before>'use strict';

<%= angularAppName %>.factory('<%= entityClass %>', ['$resource',
    function ($resource) {
        return $resource('app/rest/<%= entityInstance %>s/:id', {}, {
            'query': { method: 'GET', isArray: true},
            'get': { method: 'GET'}
        });
    }]);
<commit_msg>Let ng-annotate add dependency injection annotations for entity-service.js<commit_after>'use strict';

<%= angularAppName %>.factory('<%= entityClass %>', function ($resource) {
        return $resource('app/rest/<%= entityInstance %>s/:id', {}, {
            'query': { method: 'GET', isArray: true},
            'get': { method: 'GET'}
        });
    });
<|endoftext|>


<commit_before>import * as fs from 'fs';

import { terser } from 'rollup-plugin-terser';
import commonjs from '@rollup/plugin-commonjs';

import {
  addOnBundleConfig,
  baseBundleConfig,
  markAsBrowserBuild,
  nodeResolvePlugin,
  typescriptPluginES5,
} from '../../rollup.config';

const terserInstance = terser({
  mangle: {
    // captureExceptions and captureMessage are public API methods and they don't need to be listed here
    // as mangler doesn't touch user-facing thing, however sentryWrapped is not, and it would be mangled into a minified version.
    // We need those full names to correctly detect our internal frames for stripping.
    // I listed all of them here just for the clarity sake, as they are all used in the frames manipulation process.
    reserved: ['captureException', 'captureMessage', 'sentryWrapped'],
    properties: false,
  },
  output: {
    comments: false,
  },
});

const plugins = [
  typescriptPluginES5,
  // replace `__SENTRY_BROWSER_BUNDLE__` with `true` to enable treeshaking of non-browser code
  markAsBrowserBuild,
  nodeResolvePlugin,
  commonjs(),
];

function allIntegrations() {
  return fs.readdirSync('./src').filter(file => file != 'index.ts');
}

function loadAllIntegrations() {
  const builds = [];
  [
    {
      extension: '.js',
      plugins,
    },
    {
      extension: '.min.js',
      plugins: [...plugins, terserInstance],
    },
  ].forEach(build => {
    builds.push(
      ...allIntegrations().map(file => ({
        ...baseBundleConfig,
        input: `src/${file}`,
        output: {
          ...baseBundleConfig.output,
          ...addOnBundleConfig.output,
          file: `build/${file.replace('.ts', build.extension)}`,
        },
        plugins: build.plugins,
      })),
    );
  });
  return builds;
}

export default loadAllIntegrations();
<commit_msg>ref(build): Use standard regex for minifying integration bundles (#4651)<commit_after>import * as fs from 'fs';

import { terser } from 'rollup-plugin-terser';
import commonjs from '@rollup/plugin-commonjs';

import {
  addOnBundleConfig,
  baseBundleConfig,
  markAsBrowserBuild,
  nodeResolvePlugin,
  typescriptPluginES5,
} from '../../rollup.config';

const terserInstance = terser({
  mangle: {
    // captureExceptions and captureMessage are public API methods and they don't need to be listed here
    // as mangler doesn't touch user-facing thing, however sentryWrapped is not, and it would be mangled into a minified version.
    // We need those full names to correctly detect our internal frames for stripping.
    // I listed all of them here just for the clarity sake, as they are all used in the frames manipulation process.
    reserved: ['captureException', 'captureMessage', 'sentryWrapped'],
    properties: {
      regex: /^_[^_]/,
    },
  },
  output: {
    comments: false,
  },
});

const plugins = [
  typescriptPluginES5,
  // replace `__SENTRY_BROWSER_BUNDLE__` with `true` to enable treeshaking of non-browser code
  markAsBrowserBuild,
  nodeResolvePlugin,
  commonjs(),
];

function allIntegrations() {
  return fs.readdirSync('./src').filter(file => file != 'index.ts');
}

function loadAllIntegrations() {
  const builds = [];
  [
    {
      extension: '.js',
      plugins,
    },
    {
      extension: '.min.js',
      plugins: [...plugins, terserInstance],
    },
  ].forEach(build => {
    builds.push(
      ...allIntegrations().map(file => ({
        ...baseBundleConfig,
        input: `src/${file}`,
        output: {
          ...baseBundleConfig.output,
          ...addOnBundleConfig.output,
          file: `build/${file.replace('.ts', build.extension)}`,
        },
        plugins: build.plugins,
      })),
    );
  });
  return builds;
}

export default loadAllIntegrations();
<|endoftext|>


<commit_before>import React from 'react';
import request from 'superagent'

import Attributes from '../dist/server'
import '../playground/server'

request
  .get('http://localhost:9090/fixtures')
  .set('Accept', 'application/json')
  .end((err, res) => {
    res.body.forEach((element) => {
      const renderedElement = React.createElement(Attributes, {
        data: element
      });

      const htmlString = React.renderToString(renderedElement);
      console.log(htmlString);
    });

    process.exit(0);

  });

<commit_msg>Let's use mson zoo directly<commit_after>import React from 'react';
import request from 'superagent'
import mson_zoo from 'mson-zoo'

import Attributes from '../dist/server'

mson_zoo.samples.forEach((element) => {
  const renderedElement = React.createElement(Attributes, {
    data: element
  });

  const htmlString = React.renderToString(renderedElement);
  console.log(htmlString);
});

process.exit(0);
<|endoftext|>