<commit_before>//检测是否为手机登陆
if (! device.mobile()) {
	window.location.href = "./error.html";
}
// 创建数字列表
var numList = new Array();
for (var i = 1; i < 14; i ++) {
	numList.push(i);
	numList.push(i);
}

// 创建符号列表
var symbolList = new Array();
symbolList.push("(");
symbolList.push(")");
symbolList.push("+");
symbolList.push("-");
symbolList.push("×");
symbolList.push("÷");

// 创建数字列表
var numDivList = new Array();
var numInputList = new Array();

// 输入框
var divInputBox = null;

// 输入的内容
var inputs = new Array();

// 计时器控件
var timer = null;

// 产生列表
function generateRandomNum() {
	var existIndexs = new Array();
	for (var i = 0; i < numDivList.length; i ++) {
		var index = parseInt(Math.random() * 26);
		while (existIndexs.indexOf(index) != -1) {
			index = parseInt(Math.random() * 26);
		}
		existIndexs.push(index);
		numInputList[i] = numList[index];
		numDivList[i].innerHTML = numList[index];
	}
}

// 获取元素
function getElement(id) {
	return document.getElementById(id);
}

// 初始化符号
function initSymbol(index) {
	getElement("div_symbol" + (index + 1)).addEventListener("touchstart", function(event) {
		inputs.push(symbolList[index]);
		divInputBox.innerHTML += symbolList[index];
	}, true);
}

// 初始化数字控件
function initNum(index) {
	numDivList.push(getElement("div_num" + (index + 1)));
	numDivList[index].addEventListener("touchstart", function(event) {
		if (numDivList[index].innerHTML == "") {
			return;
		}

		// 判断前一个被点击的是否是数字
		if (inputs.length > 0
			&& inputs[inputs.length - 1] != symbolList[0]
			&& inputs[inputs.length - 1] != symbolList[1]
			&& inputs[inputs.length - 1] != symbolList[2]
			&& inputs[inputs.length - 1] != symbolList[3]
			&& inputs[inputs.length - 1] != symbolList[4]
			&& inputs[inputs.length - 1] != symbolList[5]) {
			timer.stop();
			new NotificationDialog("不能连续输入数字！", "继续", function() {
				timer.restart();
			}).show();
			return;
		}

		inputs.push(numDivList[index].innerHTML);
		divInputBox.innerHTML += numDivList[index].innerHTML;
		numDivList[index].innerHTML = "";
	}, true);
	generateRandomNum();
}

function refreashGame() {
	timer.stop();
	timer.start();
	divInputBox.innerHTML = "";
	inputs = new Array();
	generateRandomNum();
}

// 初始化游戏
function initGame() {
	for (var i = 0; i < 6; i ++) {
		initSymbol(i);
	}

	for (var i = 0; i < 4; i ++) {
		initNum(i);
	}

	divInputBox = getElement("div_input_box");

	getElement("div_next").addEventListener("touchstart", function(event) {
		refreashGame();
	}, true);

	getElement("div_sure").addEventListener("touchstart", function() {
		for (var i = 0; i < numDivList.length; i ++) {
			if (numDivList[i].innerHTML != "") {
				timer.stop();
				new NotificationDialog("所有的数字都要用到才行！", "继续", function() {
					timer.restart();
				}).show();
				return;
			}
		}
		try {
			var content = divInputBox.innerHTML.replace(new RegExp("×","gm"), "*").replace(new RegExp("÷","gm"), "/");
			var value = eval(content);
			if (parseInt(value) == 24) {
				var time = timer.stop();
				new NotificationDialog("恭喜你得到24！用时" + time, "下一轮", function() {
					refreashGame();
				}).show();
			} else {
				timer.stop();
				new NotificationDialog("结果不对~再试试！", "继续", function() {
					timer.restart();
				}).show();
			}
		} catch(e) {
			timer.stop();
			new NotificationDialog("结果不对~再试试！", "继续", function() {
				timer.restart();
			}).show();
		}
	}, true);

	getElement("div_delete").addEventListener("touchstart", function() {
		if (inputs.length == 0) {
			return;
		}

		var lastInput = inputs[inputs.length - 1];

		for (var i = 0; i < symbolList.length; i ++) {
			if (lastInput == symbolList[i]) {
				inputs.pop();
				divInputBox.innerHTML = inputs.toString().replace(new RegExp(",","gm"), "");
				return;
			}
		}

		for (var i = 0; i < numInputList.length; i ++) {
			if (lastInput == numInputList[i] && numDivList[i].innerHTML == "") {
				numDivList[i].innerHTML = lastInput;
				inputs.pop();
				divInputBox.innerHTML = inputs.toString().replace(new RegExp(",","gm"), "");
				return;
			}
		}
	}, true);

	timer = new Timer();
	timer.start();

}

// 页面加载完成后执行
window.onload = function() {
	var divDialog = getElement("div_dialog");
	var divBegin = getElement("div_begin");
	divBegin.addEventListener("touchstart", function(event) {
			divDialog.setAttribute("class", "hidden");
			setTimeout(function() {
				divDialog.style.display = "none";
				initGame();
			}, 300);
		}, true);
}<commit_msg>commit<commit_after>//检测是否为手机登陆
if (! device.mobile()) {
	window.location.href = "./error.html";
}
// 创建数字列表
var numList = new Array();
for (var i = 1; i < 14; i ++) {
	numList.push(i);
	numList.push(i);
}

// 创建符号列表
var symbolList = new Array();
symbolList.push("(");
symbolList.push(")");
symbolList.push("+");
symbolList.push("-");
symbolList.push("×");
symbolList.push("÷");

// 创建数字列表
var numDivList = new Array();
var numInputList = new Array();

// 输入框
var divInputBox = null;

// 输入的内容
var inputs = new Array();

// 计时器控件
var timer = null;

// 产生列表
function generateRandomNum() {
	var existIndexs = new Array();
	for (var i = 0; i < numDivList.length; i ++) {
		var index = parseInt(Math.random() * 26);
		while (existIndexs.indexOf(index) != -1) {
			index = parseInt(Math.random() * 26);
		}
		existIndexs.push(index);
		numInputList[i] = numList[index];
		numDivList[i].innerHTML = numList[index];
	}
}

// 获取元素
function getElement(id) {
	return document.getElementById(id);
}

// 初始化符号
function initSymbol(index) {
	getElement("div_symbol" + (index + 1)).addEventListener("touchstart", function(event) {
		inputs.push(symbolList[index]);
		divInputBox.innerHTML += symbolList[index];
	}, true);
}

// 初始化数字控件
function initNum(index) {
	numDivList.push(getElement("div_num" + (index + 1)));
	numDivList[index].addEventListener("touchstart", function(event) {
		if (numDivList[index].innerHTML == "") {
			return;
		}

		// 判断前一个被点击的是否是数字
		if (inputs.length > 0
			&& inputs[inputs.length - 1] != symbolList[0]
			&& inputs[inputs.length - 1] != symbolList[1]
			&& inputs[inputs.length - 1] != symbolList[2]
			&& inputs[inputs.length - 1] != symbolList[3]
			&& inputs[inputs.length - 1] != symbolList[4]
			&& inputs[inputs.length - 1] != symbolList[5]) {
			timer.stop();
			new NotificationDialog("不能连续输入数字！", "继续", function() {
				timer.restart();
			}).show();
			return;
		}

		inputs.push(numDivList[index].innerHTML);
		divInputBox.innerHTML += numDivList[index].innerHTML;
		numDivList[index].innerHTML = "";
	}, true);
	generateRandomNum();
}

function refreashGame() {
	timer.stop();
	timer.start();
	divInputBox.innerHTML = "";
	inputs = new Array();
	generateRandomNum();
}

// 初始化游戏
function initGame() {
	for (var i = 0; i < 6; i ++) {
		initSymbol(i);
	}

	for (var i = 0; i < 4; i ++) {
		initNum(i);
	}

	divInputBox = getElement("div_input_box");

	getElement("div_next").addEventListener("touchstart", function(event) {
		refreashGame();
	}, true);

	getElement("div_sure").addEventListener("touchstart", function() {
		for (var i = 0; i < numDivList.length; i ++) {
			if (numDivList[i].innerHTML != "") {
				timer.stop();
				new NotificationDialog("所有的数字都要用到才行！", "继续", function() {
					timer.restart();
				}).show();
				return;
			}
		}
		try {
			var content = divInputBox.innerHTML.replace(new RegExp("×","gm"), "*").replace(new RegExp("÷","gm"), "/");
			var value = eval(content);
			if (parseFloat(value) == 24) {
				var time = timer.stop();
				new NotificationDialog("恭喜你得到24！用时" + time, "下一轮", function() {
					refreashGame();
				}).show();
			} else {
				timer.stop();
				new NotificationDialog("结果不对~再试试！", "继续", function() {
					timer.restart();
				}).show();
			}
		} catch(e) {
			timer.stop();
			new NotificationDialog("结果不对~再试试！", "继续", function() {
				timer.restart();
			}).show();
		}
	}, true);

	getElement("div_delete").addEventListener("touchstart", function() {
		if (inputs.length == 0) {
			return;
		}

		var lastInput = inputs[inputs.length - 1];

		for (var i = 0; i < symbolList.length; i ++) {
			if (lastInput == symbolList[i]) {
				inputs.pop();
				divInputBox.innerHTML = inputs.toString().replace(new RegExp(",","gm"), "");
				return;
			}
		}

		for (var i = 0; i < numInputList.length; i ++) {
			if (lastInput == numInputList[i] && numDivList[i].innerHTML == "") {
				numDivList[i].innerHTML = lastInput;
				inputs.pop();
				divInputBox.innerHTML = inputs.toString().replace(new RegExp(",","gm"), "");
				return;
			}
		}
	}, true);

	timer = new Timer();
	timer.start();

}

// 页面加载完成后执行
window.onload = function() {
	var divDialog = getElement("div_dialog");
	var divBegin = getElement("div_begin");
	divBegin.addEventListener("touchstart", function(event) {
			divDialog.setAttribute("class", "hidden");
			setTimeout(function() {
				divDialog.style.display = "none";
				initGame();
			}, 300);
		}, true);
}<|endoftext|>


<commit_before>/* global setup:true, initSetup:true */

setup = {};

initSetup = function(){
   var simteconf = require('simteconf');
   var phiConf = simteconf('phido.conf', {
      skipNames: ['//', '#'],
      prefixGroups: [
         'AreaSep'
      ]
   });
   // Read GoldED settings:
   var encodingGED = phiConf.last('EncodingGoldED') || 'utf8';
   var confGED = simteconf(phiConf.last('ConfigGoldED'), {
      encoding: encodingGED,
      skipNames: ['//', '#', '-'+'-'],
      prefixGroups: [
         'AreaSep'
      ]
   });
   setup.UserName =
      phiConf.first('UserName') || confGED.first('UserName') || 'anonymous';
   setup.areaSeparators = phiConf.group('AreaSep');
   if( setup.areaSeparators.names().length < 1 ){
      setup.areaSeparators = confGED.group('AreaSep');
   }
   // Read HPT areas:
   var encodingHPT = phiConf.last('EncodingHPT') || 'utf8';
   setup.areas = simteconf(phiConf.last('AreasHPT'), {
      encoding: encodingHPT,
      skipNames: ['#'],
      lowercase: false,
      prefixGroups: [
         'NetmailArea',
         'BadArea',
         'DupeArea',
         'LocalArea',
         'EchoArea'
      ]
   });
};<commit_msg>completed reading a filtered sorted list of areatag separators<commit_after>/* global setup:true, initSetup:true */

setup = {};

initSetup = function(){
   var simteconf = require('simteconf');
   var phiConf = simteconf('phido.conf', {
      skipNames: ['//', '#']
   });
   // Read GoldED settings:
   var encodingGED = phiConf.last('EncodingGoldED') || 'utf8';
   var confGED = simteconf(phiConf.last('ConfigGoldED'), {
      encoding: encodingGED,
      skipNames: ['//', '#', '-'+'-']
   });
   setup.UserName =
      phiConf.first('UserName') || confGED.first('UserName') || 'anonymous';
   setup.areaSeparators = (
      phiConf.all('AreaSep') || confGED.all('AreaSep') || []
   ).filter(function(areaSep){
      var ok = /^\s*\S+\s+"[^"]+"\s+\d+\s+[Ee][Cc][Hh][Oo]\s*$/.test(areaSep);
      return ok;
   }).map(function(areaSep){
      var matches =
         /^\s*(\S+)\s+"([^"]+)"\s+\d+\s+[Ee][Cc][Hh][Oo]\s*$/.exec(areaSep);
      return {
         sepName: matches[1],
         sepDesc: matches[2]
      };
   }).sort(function(a, b){
      if( a.sepName < b.sepName ){
         return -1;
      } else if ( a.sepName > b.sepName ){
         return 1;
      } else return 0;
   });
   // Read HPT areas:
   var encodingHPT = phiConf.last('EncodingHPT') || 'utf8';
   setup.areas = simteconf(phiConf.last('AreasHPT'), {
      encoding: encodingHPT,
      skipNames: ['#'],
      lowercase: false,
      prefixGroups: [
         'NetmailArea',
         'BadArea',
         'DupeArea',
         'LocalArea',
         'EchoArea'
      ]
   });
};<|endoftext|>


<commit_before>$(function() {
	'use strict';

	// set of default options with zero fade time for faster testing
	var zeroTimeOpts = $.extend({}, $.fn.powerTip.defaults, { fadeInTime: 0, fadeOutTime: 0 });

	QUnit.module('Tooltip Controller');

	QUnit.test('expose methods', function(assert) {
		var tc = new TooltipController($.fn.powerTip.defaults);
		assert.strictEqual(typeof tc.showTip, 'function', 'showTip method is defined');
		assert.strictEqual(typeof tc.hideTip, 'function', 'hideTip method is defined');
		assert.strictEqual(typeof tc.resetPosition, 'function', 'resetPosition method is defined');
	});

	QUnit.test('custom PowerTip events fire', function(assert) {
		var done = assert.async(),
			element = $('<span />').data(DATA_POWERTIP, 'This is the tooltip text.'),
			tc = new TooltipController(zeroTimeOpts),
			tipElem = $('#' + $.fn.powerTip.defaults.popupId);

		assert.expect(9);

		element.on({
			powerTipPreRender: function() {
				assert.ok(true, 'powerTipPreRender fired');
				assert.notStrictEqual(tipElem.text(), 'This is the tooltip text.', 'tooltip content has not been inserted yet');
			},
			powerTipRender: function() {
				assert.ok(true, 'powerTipRender fired');
				assert.strictEqual(tipElem.text(), 'This is the tooltip text.', 'tooltip content has been inserted');
			},
			powerTipOpen: function() {
				assert.ok(true, 'powerTipClose fired');
				assert.strictEqual(tipElem.css('opacity'), '1', 'tooltip is faded in');
				tc.hideTip(element);
			},
			powerTipClose: function() {
				assert.ok(true, 'powerTipClose fired');
				assert.strictEqual(tipElem.text(), 'This is the tooltip text.', 'tooltip content still exists');
				assert.strictEqual(tipElem.css('display'), 'none', 'display set to none');
				done();
			}
		});

		tc.showTip(element);
	});

	QUnit.test('showTip opens tooltip and hideTip closes it', function(assert) {
		var done = assert.async(),
			element = $('<span />').data(DATA_POWERTIP, 'This is the tooltip text.'),
			tc = new TooltipController(zeroTimeOpts),
			tipElem = $('#' + $.fn.powerTip.defaults.popupId);

		assert.expect(2);

		element.on({
			powerTipOpen: function() {
				assert.strictEqual(tipElem.css('opacity'), '1', 'tooltip is faded in');
				tc.hideTip(element);
			},
			powerTipClose: function() {
				assert.strictEqual(tipElem.css('display'), 'none', 'display set to none');
				done();
			}
		});

		tc.showTip(element);
	});

	QUnit.test('TooltipController uses custom id', function(assert) {
		// let the TooltipController create the element
		var tc = new TooltipController($.extend({}, zeroTimeOpts, { popupId: 'popupId' }));

		assert.strictEqual($('#popupId').length, 1, 'custom id element created');

		// clean up
		$('#popupId').remove();

		// this is solely to make the linter happy
		tc.foo = 0;
	});

	QUnit.test('TooltipController adds placement classes', function(assert) {
		var done = assert.async(),
			placementList = [],
			tipElem;

		assert.expect(Object.keys($.fn.powerTip.smartPlacementLists).length);

		// function that actually runs a test
		function testPlacementClass(placement) {
			var element = $('<span />').data(DATA_POWERTIP, 'This is the tooltip text.'),
				opts = $.extend({}, zeroTimeOpts, { placement: placement }),
				tc = new TooltipController(opts);

			// the element wont exist until it's built by a TooltipController,
			// so we must grab it here
			if (!tipElem) {
				tipElem = $('#' + $.fn.powerTip.defaults.popupId);
			}

			element.on({
				powerTipOpen: function() {
					assert.strictEqual(tipElem.hasClass(placement), true, placement + ' placement class added');
					tc.hideTip(element);
				},
				powerTipClose: function() {
					runNextTest();
				}
			});

			tc.showTip(element);
		}

		// function to run the next test in the placementList queue
		function runNextTest() {
			var nextPlacement = placementList.shift();
			if (nextPlacement) {
				testPlacementClass(nextPlacement);
			} else {
				done();
			}
		}

		// populate placement list
		$.each($.fn.powerTip.smartPlacementLists, function(key) {
			placementList.push(key);
		});

		// start the tests
		runNextTest();
	});

	QUnit.test('resetPosition removes old placement classes', function(assert) {
		var placement = 'se',
			element = $('<span />').data(DATA_POWERTIP, 'This is the tooltip text.'),
			tc = new TooltipController($.extend({}, zeroTimeOpts, { placement: placement })),
			tipElem = $('#' + $.fn.powerTip.defaults.popupId),
			allClasses = Object.keys($.fn.powerTip.smartPlacementLists),
			key;

		assert.expect(allClasses.length - 1);

		tipElem.addClass(allClasses.join(' '));
		tc.resetPosition(element);

		for (key in $.fn.powerTip.smartPlacementLists) {
			if (key !== placement) {
				assert.strictEqual(tipElem.hasClass(key), false, 'tooltip element does not have class: ' + key);
			}
		}
	});

	QUnit.test('TooltipController adds custom classes', function(assert) {
		var done = assert.async(),
			element = $('<span />').data(DATA_POWERTIP, 'This is the tooltip text.'),
			tc = new TooltipController($.extend({}, zeroTimeOpts, { popupClass: 'customClass' })),
			tipElem = $('#' + $.fn.powerTip.defaults.popupId);

		assert.expect(1);

		element.on({
			powerTipOpen: function() {
				assert.strictEqual(tipElem.hasClass('customClass'), true, 'custom class added');
				tc.hideTip(element);
			},
			powerTipClose: function() {
				done();
			}
		});

		tc.showTip(element);
	});
});
<commit_msg>Added test assertions to verify lifecycle events happen in order<commit_after>$(function() {
	'use strict';

	// set of default options with zero fade time for faster testing
	var zeroTimeOpts = $.extend({}, $.fn.powerTip.defaults, { fadeInTime: 0, fadeOutTime: 0 });

	QUnit.module('Tooltip Controller');

	QUnit.test('expose methods', function(assert) {
		var tc = new TooltipController($.fn.powerTip.defaults);
		assert.strictEqual(typeof tc.showTip, 'function', 'showTip method is defined');
		assert.strictEqual(typeof tc.hideTip, 'function', 'hideTip method is defined');
		assert.strictEqual(typeof tc.resetPosition, 'function', 'resetPosition method is defined');
	});

	QUnit.test('custom PowerTip events fire', function(assert) {
		var done = assert.async(),
			element = $('<span />').data(DATA_POWERTIP, 'This is the tooltip text.'),
			tc = new TooltipController(zeroTimeOpts),
			tipElem = $('#' + $.fn.powerTip.defaults.popupId);

		assert.expect(14);

		element.on({
			powerTipPreRender: function() {
				assert.step('powerTipPreRender');
				assert.ok(true, 'powerTipPreRender fired');
				assert.notStrictEqual(tipElem.text(), 'This is the tooltip text.', 'tooltip content has not been inserted yet');
			},
			powerTipRender: function() {
				assert.step('powerTipRender');
				assert.ok(true, 'powerTipRender fired');
				assert.strictEqual(tipElem.text(), 'This is the tooltip text.', 'tooltip content has been inserted');
			},
			powerTipOpen: function() {
				assert.step('powerTipOpen');
				assert.ok(true, 'powerTipClose fired');
				assert.strictEqual(tipElem.css('opacity'), '1', 'tooltip is faded in');
				tc.hideTip(element);
			},
			powerTipClose: function() {
				assert.step('powerTipClose');
				assert.ok(true, 'powerTipClose fired');
				assert.strictEqual(tipElem.text(), 'This is the tooltip text.', 'tooltip content still exists');
				assert.strictEqual(tipElem.css('display'), 'none', 'display set to none');
				assert.verifySteps([ 'powerTipPreRender', 'powerTipRender', 'powerTipOpen', 'powerTipClose' ]);
				done();
			}
		});

		tc.showTip(element);
	});

	QUnit.test('showTip opens tooltip and hideTip closes it', function(assert) {
		var done = assert.async(),
			element = $('<span />').data(DATA_POWERTIP, 'This is the tooltip text.'),
			tc = new TooltipController(zeroTimeOpts),
			tipElem = $('#' + $.fn.powerTip.defaults.popupId);

		assert.expect(2);

		element.on({
			powerTipOpen: function() {
				assert.strictEqual(tipElem.css('opacity'), '1', 'tooltip is faded in');
				tc.hideTip(element);
			},
			powerTipClose: function() {
				assert.strictEqual(tipElem.css('display'), 'none', 'display set to none');
				done();
			}
		});

		tc.showTip(element);
	});

	QUnit.test('TooltipController uses custom id', function(assert) {
		// let the TooltipController create the element
		var tc = new TooltipController($.extend({}, zeroTimeOpts, { popupId: 'popupId' }));

		assert.strictEqual($('#popupId').length, 1, 'custom id element created');

		// clean up
		$('#popupId').remove();

		// this is solely to make the linter happy
		tc.foo = 0;
	});

	QUnit.test('TooltipController adds placement classes', function(assert) {
		var done = assert.async(),
			placementList = [],
			tipElem;

		assert.expect(Object.keys($.fn.powerTip.smartPlacementLists).length);

		// function that actually runs a test
		function testPlacementClass(placement) {
			var element = $('<span />').data(DATA_POWERTIP, 'This is the tooltip text.'),
				opts = $.extend({}, zeroTimeOpts, { placement: placement }),
				tc = new TooltipController(opts);

			// the element wont exist until it's built by a TooltipController,
			// so we must grab it here
			if (!tipElem) {
				tipElem = $('#' + $.fn.powerTip.defaults.popupId);
			}

			element.on({
				powerTipOpen: function() {
					assert.strictEqual(tipElem.hasClass(placement), true, placement + ' placement class added');
					tc.hideTip(element);
				},
				powerTipClose: function() {
					runNextTest();
				}
			});

			tc.showTip(element);
		}

		// function to run the next test in the placementList queue
		function runNextTest() {
			var nextPlacement = placementList.shift();
			if (nextPlacement) {
				testPlacementClass(nextPlacement);
			} else {
				done();
			}
		}

		// populate placement list
		$.each($.fn.powerTip.smartPlacementLists, function(key) {
			placementList.push(key);
		});

		// start the tests
		runNextTest();
	});

	QUnit.test('resetPosition removes old placement classes', function(assert) {
		var placement = 'se',
			element = $('<span />').data(DATA_POWERTIP, 'This is the tooltip text.'),
			tc = new TooltipController($.extend({}, zeroTimeOpts, { placement: placement })),
			tipElem = $('#' + $.fn.powerTip.defaults.popupId),
			allClasses = Object.keys($.fn.powerTip.smartPlacementLists),
			key;

		assert.expect(allClasses.length - 1);

		tipElem.addClass(allClasses.join(' '));
		tc.resetPosition(element);

		for (key in $.fn.powerTip.smartPlacementLists) {
			if (key !== placement) {
				assert.strictEqual(tipElem.hasClass(key), false, 'tooltip element does not have class: ' + key);
			}
		}
	});

	QUnit.test('TooltipController adds custom classes', function(assert) {
		var done = assert.async(),
			element = $('<span />').data(DATA_POWERTIP, 'This is the tooltip text.'),
			tc = new TooltipController($.extend({}, zeroTimeOpts, { popupClass: 'customClass' })),
			tipElem = $('#' + $.fn.powerTip.defaults.popupId);

		assert.expect(1);

		element.on({
			powerTipOpen: function() {
				assert.strictEqual(tipElem.hasClass('customClass'), true, 'custom class added');
				tc.hideTip(element);
			},
			powerTipClose: function() {
				done();
			}
		});

		tc.showTip(element);
	});
});
<|endoftext|>


<commit_before>const { authenticate } = require('@feathersjs/authentication');
const { iff, keepQuery, isProvider, disallow } = require('feathers-hooks-common');

const { populateCurrentSchool } = require('../../../hooks');
const fillDefaultValues = require('./fillDefaultValues');
const restrictToSchoolSystems = require('../../ldap/hooks/restrictToSchoolSystems');

module.exports = {
	before: {
		all: [authenticate('jwt')],
		get: [iff(isProvider('external'), keepQuery([]))],
		create: [
			// only allow external calls (the service needs a user)
			iff(!isProvider('external'), disallow()),
			keepQuery('activate', 'verifyOnly'),
			populateCurrentSchool,
			fillDefaultValues,
		],
		patch: [
			// only allow external calls (the service needs a user)
			iff(!isProvider('external'), disallow()),
			keepQuery('activate', 'verifyOnly'),
			populateCurrentSchool,
			restrictToSchoolSystems,
			fillDefaultValues,
		],
		update: [disallow()],
		remove: [disallow()],
	},
	after: {
		all: [],
	},
};
<commit_msg>Fix hook params<commit_after>const { authenticate } = require('@feathersjs/authentication');
const { iff, keepQuery, isProvider, disallow } = require('feathers-hooks-common');

const { populateCurrentSchool } = require('../../../hooks');
const fillDefaultValues = require('./fillDefaultValues');
const restrictToSchoolSystems = require('../../ldap/hooks/restrictToSchoolSystems');

module.exports = {
	before: {
		all: [authenticate('jwt')],
		get: [iff(isProvider('external'), keepQuery())],
		create: [
			// only allow external calls (the service needs a user)
			iff(!isProvider('external'), disallow()),
			keepQuery('activate', 'verifyOnly'),
			populateCurrentSchool,
			fillDefaultValues,
		],
		patch: [
			// only allow external calls (the service needs a user)
			iff(!isProvider('external'), disallow()),
			keepQuery('activate', 'verifyOnly'),
			populateCurrentSchool,
			restrictToSchoolSystems,
			fillDefaultValues,
		],
		update: [disallow()],
		remove: [disallow()],
	},
	after: {
		all: [],
	},
};
<|endoftext|>


<commit_before>module('tl.enchant.js', {
    setup: function() {
        enchant();
        var game = new Game();
        var sprite = new Sprite(32, 32);
        sprite.moveTo(0, 0);
        game.rootScene.addChild(sprite);
    },
    teardown: function() {

    }
});

test('tl.delay.then', function() {
    var sprite = enchant.Game.instance.rootScene.childNodes[0];
    var then = false;
    sprite.tl.delay(30).then(function() {
        then = true;
    });
    ok(!then);

    var enterframe = new enchant.Event('enterframe');
    for (var i = 0; i < 30 - 1; i++) {
        sprite.dispatchEvent(enterframe);
    }

    ok(!then);
    sprite.dispatchEvent(enterframe);
    ok(then);

    sprite.tl.clear();
});

test('tl.tween', function() {
    var sprite = enchant.Game.instance.rootScene.childNodes[0];
    sprite.tl.moveTo(320, 320, 30);
    equal(sprite.x, 0);
    equal(sprite.y, 0);
    for (var i = 0; i < 30 - 1; i++) {
        var enterframe = new enchant.Event('enterframe');
        sprite.dispatchEvent(enterframe);
    }
    notEqual(Math.round(sprite.x, 5), 320);
    notEqual(Math.round(sprite.y, 5), 320);

    sprite.dispatchEvent(enterframe);
    equal(Math.round(sprite.x, 5), 320);
    equal(Math.round(sprite.y, 5), 320);
});

test('tl.tween', function() {
    var sprite = enchant.Game.instance.rootScene.childNodes[0];
    sprite.tl.moveTo(320, 320, 30);
    equal(sprite.x, 0);
    equal(sprite.y, 0);
    for (var i = 0; i < 30 - 1; i++) {
        var enterframe = new enchant.Event('enterframe');
        sprite.dispatchEvent(enterframe);
    }
    notEqual(Math.round(sprite.x, 5), 320);
    notEqual(Math.round(sprite.y, 5), 320);

    sprite.dispatchEvent(enterframe);
    equal(Math.round(sprite.x, 5), 320);
    equal(Math.round(sprite.y, 5), 320);
});

test('tl.tween (minus)', function() {
    var sprite = enchant.Game.instance.rootScene.childNodes[0];

    sprite.moveTo(200, 0);
    sprite.tl.moveBy(-200, 0, 8);
    equal(sprite.x, 200);

    for (var i = 0; i < 8; i++) {
        var enterframe = new enchant.Event('enterframe');
        sprite.dispatchEvent(enterframe);
    }
    equal(sprite.x, 0);
});

test('tl.fadeOut', function() {
    var sprite = enchant.Game.instance.rootScene.childNodes[0];
    sprite.tl.fadeOut(10);
    equal(sprite.opacity, 1);
    for (var i = 0; i < 10 - 1; i++) {
        var enterframe = new enchant.Event('enterframe');
        sprite.dispatchEvent(enterframe);
    }
    notEqual(sprite.opacity, 0);

    sprite.dispatchEvent(enterframe);
    equal(sprite.opacity, 0);
});

<commit_msg>added time based animation test cases<commit_after>module('tl.enchant.js', {
	setup: function() {
		enchant();
		var game = new Game();
		var sprite = new Sprite(32, 32);
		sprite.moveTo(0, 0);
		game.rootScene.addChild(sprite);
	},
	teardown: function() {

	}
});

test('tl.frameBased', function() {
	var sprite = enchant.Game.instance.rootScene.childNodes[0];
	ok(sprite.tl.isFrameBased);
	sprite.tl.setFrameBased();
	ok(sprite.tl.isFrameBased);
	sprite.tl.setTimeBased();
	ok(!sprite.tl.isFrameBased);
	sprite.tl.setFrameBased();
	ok(sprite.tl.isFrameBased);
});

test('tl.delay.then', function() {
	var sprite = enchant.Game.instance.rootScene.childNodes[0];
	var then = false;
	sprite.tl.delay(30).then(function() {
		then = true;
	});
	ok(!then);

	var enterframe = new enchant.Event('enterframe');
	for (var i = 0; i < 30 - 1; i++) {
		sprite.dispatchEvent(enterframe);
	}

	ok(!then);
	sprite.dispatchEvent(enterframe);
	ok(then);

	sprite.tl.clear();
});

test('tl.tween', function() {
	var sprite = enchant.Game.instance.rootScene.childNodes[0];
	sprite.tl.moveTo(320, 320, 30);
	equal(sprite.x, 0);
	equal(sprite.y, 0);
	for (var i = 0; i < 30 - 1; i++) {
		var enterframe = new enchant.Event('enterframe');
		sprite.dispatchEvent(enterframe);
	}
	notEqual(Math.round(sprite.x, 5), 320);
	notEqual(Math.round(sprite.y, 5), 320);

	sprite.dispatchEvent(enterframe);
	equal(Math.round(sprite.x, 5), 320);
	equal(Math.round(sprite.y, 5), 320);
});

test('tl.tween', function() {
	var sprite = enchant.Game.instance.rootScene.childNodes[0];
	sprite.tl.moveTo(320, 320, 30);
	equal(sprite.x, 0);
	equal(sprite.y, 0);
	for (var i = 0; i < 30 - 1; i++) {
		var enterframe = new enchant.Event('enterframe');
		sprite.dispatchEvent(enterframe);
	}
	notEqual(Math.round(sprite.x, 5), 320);
	notEqual(Math.round(sprite.y, 5), 320);

	sprite.dispatchEvent(enterframe);
	equal(Math.round(sprite.x, 5), 320);
	equal(Math.round(sprite.y, 5), 320);
});

test('tl.tween (minus)', function() {
	var sprite = enchant.Game.instance.rootScene.childNodes[0];

	sprite.moveTo(200, 0);
	sprite.tl.moveBy(-200, 0, 8);
	equal(sprite.x, 200);

	for (var i = 0; i < 8; i++) {
		var enterframe = new enchant.Event('enterframe');
		sprite.dispatchEvent(enterframe);
	}
	equal(sprite.x, 0);
});

test('tl.fadeOut', function() {
	var sprite = enchant.Game.instance.rootScene.childNodes[0];
	sprite.tl.fadeOut(10);
	equal(sprite.opacity, 1);
	for (var i = 0; i < 10 - 1; i++) {
		var enterframe = new enchant.Event('enterframe');
		sprite.dispatchEvent(enterframe);
	}
	notEqual(sprite.opacity, 0);

	sprite.dispatchEvent(enterframe);
	equal(sprite.opacity, 0);
});

/* time based testing */

test('tl.timebased.delay.then', function() {
	var sprite = enchant.Game.instance.rootScene.childNodes[0];
	sprite.tl.setTimeBased();
	var then = false;
	sprite.tl.delay(1000).then(function() {
		then = true;
	});
	ok(!then);

	var enterframe = new enchant.Event('enterframe');
	enterframe.elapsed = 33;
	var time = 0;
	for (var i = 0; i < 30; i++) {
		sprite.dispatchEvent(enterframe);
		time += enterframe.elapsed;
	}
	equal(time, 990);
	enterframe.elapsed = 10;
	ok(!then);
	sprite.dispatchEvent(enterframe);
	ok(then);

	sprite.tl.clear();
	sprite.tl.setFrameBased();
});

test('tl.timebased.tween', function() {
	var sprite = enchant.Game.instance.rootScene.childNodes[0];
	sprite.tl.setTimeBased();
	sprite.tl.moveTo(320, 320, 1000);
	equal(sprite.x, 0);
	equal(sprite.y, 0);
	var enterframe = new enchant.Event('enterframe');
	enterframe.elapsed = 6;
	var time = 0;
	for (var i = 0; i < 165; i++) {
		sprite.dispatchEvent(enterframe);
		time += enterframe.elapsed;
	}
	equal(time, 990);

	notEqual(Math.round(sprite.x, 5), 320);
	notEqual(Math.round(sprite.y, 5), 320);

	enterframe.elapsed = 10;
	sprite.dispatchEvent(enterframe);
	equal(Math.round(sprite.x, 5), 320);
	equal(Math.round(sprite.y, 5), 320);
	sprite.tl.setFrameBased();
	sprite.tl.clear();
});

test('tl.timebased.tween (minus)', function() {
	var sprite = enchant.Game.instance.rootScene.childNodes[0];
	sprite.tl.setTimeBased();
	sprite.moveTo(200, 0);
	sprite.tl.moveBy(-200, 0, 800);
	equal(sprite.x, 200);

	var enterframe = new enchant.Event('enterframe');
	enterframe.elapsed = 20;
	var time = 0;
	for (var i = 0; i < 40; i++) {
		sprite.dispatchEvent(enterframe);
		time += enterframe.elapsed;
	}
	equal(time, 800);
	equal(sprite.x, 0);
	sprite.tl.setFrameBased();
	sprite.tl.clear();
});

test('tl.timebased.fadeOut', function() {
	var sprite = enchant.Game.instance.rootScene.childNodes[0];
	sprite.tl.setTimeBased();
	sprite.tl.fadeOut(100);
	equal(sprite.opacity, 1);
	var enterframe = new enchant.Event('enterframe');
	enterframe.elapsed = 7;
	var time = 0;
	for (var i = 0; i < 14; i++) {
		sprite.dispatchEvent(enterframe);
		time += enterframe.elapsed;
	}
	equal(time, 98);
	notEqual(sprite.opacity, 0);

	enterframe.elapsed = 2;
	sprite.dispatchEvent(enterframe);
	equal(sprite.opacity, 0);
});

test('tl.timebased.tween (framebased with elapsed)', function() {
	var sprite = enchant.Game.instance.rootScene.childNodes[0];
	sprite.tl.moveTo(320, 320, 30);
	equal(sprite.x, 0);
	equal(sprite.y, 0);
	for (var i = 0; i < 30 - 1; i++) {
		var enterframe = new enchant.Event('enterframe');
		enterframe.elapsed = Math.round((Math.random()*100));
		sprite.dispatchEvent(enterframe);
	}
	notEqual(Math.round(sprite.x, 5), 320);
	notEqual(Math.round(sprite.y, 5), 320);

	enterframe.elapsed = (Math.random()*100).toFixed(0);
	sprite.dispatchEvent(enterframe);
	equal(Math.round(sprite.x, 5), 320);
	equal(Math.round(sprite.y, 5), 320);
});

test('tl.timebased.parallel (random time)', function() {
	var sprite = enchant.Game.instance.rootScene.childNodes[0];
	sprite.tl.moveTo(320, 320, 2000).and().scaleTo(100, 2000);
	sprite.tl.setTimeBased();
	equal(sprite.x, 0);
	equal(sprite.y, 0);
	equal(sprite._scaleX, 1);
	equal(sprite._scaleY, 1);
	var time = 0;
	while(time < 2000) {
		notEqual(Math.round(sprite.x, 5), 320);
		notEqual(Math.round(sprite.y, 5), 320);
		notEqual(Math.round(sprite._scaleX, 5), 100);
		notEqual(Math.round(sprite._scaleY, 5), 100);
		var enterframe = new enchant.Event('enterframe');
		enterframe.elapsed = Math.round((Math.random()*100));
		sprite.dispatchEvent(enterframe);
		time += enterframe.elapsed;
	}

	equal(Math.round(sprite.x, 5), 320);
	equal(Math.round(sprite.y, 5), 320);
	equal(Math.round(sprite._scaleX, 5), 100);
	equal(Math.round(sprite._scaleY, 5), 100);
});

test('tl.parallel (random time)', function() {
	var sprite = enchant.Game.instance.rootScene.childNodes[0];
	sprite.tl.moveTo(100, 100, 20).and().scaleTo(100, 20);
	equal(sprite.x, 0);
	equal(sprite.y, 0);
	equal(sprite._scaleX, 1);
	equal(sprite._scaleY, 1);
	var time = 0;
	while(time < 20) {
		notEqual(Math.round(sprite.x, 5), 100);
		notEqual(Math.round(sprite.y, 5), 100);
		notEqual(Math.round(sprite._scaleX, 5), 100);
		notEqual(Math.round(sprite._scaleY, 5), 100);
		var enterframe = new enchant.Event('enterframe');
		enterframe.elapsed = Math.round((Math.random()*100));
		sprite.dispatchEvent(enterframe);
		time += 1;
	}

	equal(Math.round(sprite.x, 5), 100);
	equal(Math.round(sprite.y, 5), 100);
	equal(Math.round(sprite._scaleX, 5), 100);
	equal(Math.round(sprite._scaleY, 5), 100);
});<|endoftext|>


<commit_before>window.onload = function()
{
    var cities =
    [
        {name : "London", x : 0.5023, y : 0.2141},
        {name : "Moscow", x: 0.5992, y: 0.2146},
        {name : "Beijing", x: 0.8031, y: 0.3147},
        {name : "Los Angeles", x: 0.1720, y: 0.2927},
        {name : "Vancouver", x: 0.1659, y: 0.2219},
        {name : "Mexico", x: 0.2452, y: 0.4026},
        {name : "Bogota", x: 0.3112, y: 0.4929},
        {name : "Moscow", x: 0.5992, y: 0.2146},
        {name : "Valparaiso", x: 0.3112, y: 0.6514},
        {name : "Punta Arenas", x: 0.3026, y: 0.7908},
        {name : "Madrid", x: 0.4869, y: 0.2805},
        {name : "Bombay", x: 0.7091, y: 0.4172},
        {name : "Cairo", x: 0.5944, y: 0.3342},
        {name : "Dakar", x: 0.4564, y: 0.3879},
        {name : "Singapour", x: 0.7860, y: 0.4856},
        {name : "Sydney", x: 0.9191, y: 0.6907},
        {name : "New York", x: 0.2904, y: 0.2854},
        {name : "Lima", x: 0.2806, y: 0.5491},
        {name : "Sao Paulo", x: 0.3698, y: 0.6296},
        {name : "Johannesburg", x: 0.5858, y: 0.6614},
        {name : "Manille", x: 0.8355, y: 0.4124}
    ];

    var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    var audio = create_sound(audioCtx,0,0,0);
	//create a WebGL renderer, a camera, and a scene
    var renderer = new THREE.WebGLRenderer();
    renderer.setSize( 800, 500 );
    var container = $("#WebGL");

    var scene = new THREE.Scene();

    var camera = new THREE.PerspectiveCamera( 75, 800/500, 0.1, 2100 );
    //var camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, 0.001, 1000 );
    scene.add(camera);

    var skydome = new Skydome(THREE.ImageUtils.loadTexture('textures/skydome.jpg'));
    scene.add(skydome);
    var vector = new THREE.Vector3();
    var raycaster = new THREE.Raycaster();

	camera.position.z = 1000;
	camera.lookAt(new THREE.Vector3(0,0,0));

    //create a new mesh with sphere geometry
    var sphereMaterial = new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture('textures/earth.jpg'), transparent : true, opacity : 1.0 } );
	var radius = 300;
    var earth = new THREE.Mesh(new THREE.SphereGeometry(radius, 64, 64), sphereMaterial);
	scene.add(earth);

    var area1 = new Area(0.5, 0.26, "cool");
    var area2 = new Area(0.914, 0.705, "crisis");
    earth.add(area1);
    earth.add(area2);

    var geometrySpline = new THREE.Geometry();
    var i = 0;
    var count = 64.0;
    for(;i < count; ++i)
        geometrySpline.vertices[i] = new THREE.Vector3(area1.position.x * (1-i/count) + area2.position.x * (i/count),
                                                       area1.position.y * (1-i/count) + area2.position.y * (i/count),
                                                       area1.position.z * (1-i/count) + area2.position.z * (i/count)).normalize().multiplyScalar(310);

    geometrySpline.computeLineDistances();
    var object = new THREE.Line(geometrySpline, new THREE.LineBasicMaterial( { color: 0xffffff } ), THREE.LineStrip);
    earth.add(object);

    window.addEventListener('mousemove', onMouseMove, false);
	//window.addEventListener('resize', onWindowResize, false);

    var controls = new THREE.OrbitControls(camera);
	controls.target.set(0, 0, 0);
	controls.rotateSpeed = 0.4;
	controls.zoomSpeed   = 1.2;
	controls.panSpeed    = 0.3;
	controls.noRotate    = false;
	controls.noZoom      = false;
	controls.noPan       = true;
	controls.minDistance = 500;
	controls.maxDistance = 1200;

    var mouse = {x:0.0, y:0.0};
	function onMouseMove(e)
    {
        mouse.x = ( e.clientX / window.innerWidth ) * 2 - 1;
        mouse.y = - ( e.clientY / window.innerHeight ) * 2 + 1;
    };

    function onWindowResize(e)
    {
		containerWidth = window.innerWidth;
		containerHeight = window.innerHeight;
		renderer.setSize(containerWidth, containerHeight);
		camera.aspect = containerWidth / containerHeight;
		camera.updateProjectionMatrix();
	}

    earth.rotateY(1.5);

    var lastTime = (new Date()).getTime();

    var render = function()
    {
        // Compute time
        var time = (new Date()).getTime();
        var dt = (time - lastTime) / 1000.0;
        lastTime = time;

        requestAnimationFrame(render);
        update_sound(audio.osc, audio.gain, 440, audio.pan, (area2.position.x-camera.position.x)/200,(area2.position.y-camera.position.y)/200,(area2.position.z-camera.position.z)/200);

        vector.set(mouse.x, mouse.y, 0.1).unproject(camera);
        raycaster.ray.set(camera.position, vector.sub(camera.position).normalize());
        var intersections = raycaster.intersectObjects(scene.children, true);
        for(i = 0; i < intersections.length; ++i)
        {
            if(intersections[i].object.hover != null)
                intersections[i].object.hover();
        }

    	controls.update();

        area1.update(dt);
        area2.update(dt);

       	renderer.render(scene, camera);
    };

    render();

    container.append(renderer.domElement);
};<commit_msg>Coded a random node generator function, complete with node availability checking and generation reroll.<commit_after>window.onload = function()
{
    var cities =
    [
        {name : "London", x : 0.5023, y : 0.2141},
        {name : "Moscow", x: 0.5992, y: 0.2146},
        {name : "Beijing", x: 0.8031, y: 0.3147},
        {name : "Los Angeles", x: 0.1720, y: 0.2927},
        {name : "Vancouver", x: 0.1659, y: 0.2219},
        {name : "Mexico", x: 0.2452, y: 0.4026},
        {name : "Bogota", x: 0.3112, y: 0.4929},
        {name : "Moscow", x: 0.5992, y: 0.2146},
        {name : "Valparaiso", x: 0.3112, y: 0.6514},
        {name : "Punta Arenas", x: 0.3026, y: 0.7908},
        {name : "Madrid", x: 0.4869, y: 0.2805},
        {name : "Bombay", x: 0.7091, y: 0.4172},
        {name : "Cairo", x: 0.5944, y: 0.3342},
        {name : "Dakar", x: 0.4564, y: 0.3879},
        {name : "Singapour", x: 0.7860, y: 0.4856},
        {name : "Sydney", x: 0.9191, y: 0.6907},
        {name : "New York", x: 0.2904, y: 0.2854},
        {name : "Lima", x: 0.2806, y: 0.5491},
        {name : "Sao Paulo", x: 0.3698, y: 0.6296},
        {name : "Johannesburg", x: 0.5858, y: 0.6614},
        {name : "Manille", x: 0.8355, y: 0.4124}
    ];

    var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    var audio = create_sound(audioCtx,0,0,0);
	//create a WebGL renderer, a camera, and a scene
    var renderer = new THREE.WebGLRenderer();
    renderer.setSize( 800, 500 );
    var container = $("#WebGL");

    var scene = new THREE.Scene();

    var camera = new THREE.PerspectiveCamera( 75, 800/500, 0.1, 2100 );
    //var camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, 0.001, 1000 );
    scene.add(camera);

    var skydome = new Skydome(THREE.ImageUtils.loadTexture('textures/skydome.jpg'));
    scene.add(skydome);
    var vector = new THREE.Vector3();
    var raycaster = new THREE.Raycaster();

	camera.position.z = 1000;
	camera.lookAt(new THREE.Vector3(0,0,0));

    //create a new mesh with sphere geometry
    var sphereMaterial = new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture('textures/earth.jpg'), transparent : true, opacity : 1.0 } );
	var radius = 300;
    var earth = new THREE.Mesh(new THREE.SphereGeometry(radius, 64, 64), sphereMaterial);
	scene.add(earth);

	var randomAreaInfos = generateAreas();
	var area3 = new Area(cities[randomAreaInfos.id].x, cities[randomAreaInfos.id].y, randomAreaInfos.crisisOrCool);
	while(areaUnavailable(area3)){
		area3 = rerollArea;
	}

    var area1 = new Area(0.5, 0.26, "cool");
    var area2 = new Area(0.914, 0.705, "crisis");
    earth.add(area1);
    earth.add(area2);
    earth.add(area3);

    var geometrySpline = new THREE.Geometry();
    var i = 0;
    var count = 64.0;
    for(;i < count; ++i)
        geometrySpline.vertices[i] = new THREE.Vector3(area1.position.x * (1-i/count) + area2.position.x * (i/count),
                                                       area1.position.y * (1-i/count) + area2.position.y * (i/count),
                                                       area1.position.z * (1-i/count) + area2.position.z * (i/count)).normalize().multiplyScalar(310);

    geometrySpline.computeLineDistances();
    var object = new THREE.Line(geometrySpline, new THREE.LineBasicMaterial( { color: 0xffffff } ), THREE.LineStrip);
    earth.add(object);

    window.addEventListener('mousemove', onMouseMove, false);
	//window.addEventListener('resize', onWindowResize, false);

    var controls = new THREE.OrbitControls(camera);
	controls.target.set(0, 0, 0);
	controls.rotateSpeed = 0.4;
	controls.zoomSpeed   = 1.2;
	controls.panSpeed    = 0.3;
	controls.noRotate    = false;
	controls.noZoom      = false;
	controls.noPan       = true;
	controls.minDistance = 500;
	controls.maxDistance = 1200;

    var mouse = {x:0.0, y:0.0};

	function generateAreas(){
		var ret;
		var id = Math.floor((Math.random() * 10) + 0);
		var crisisOrCool = Math.floor((Math.random()*100)+0);
		if(crisisOrCool >= 65)
			crisisOrCool = "cool";
		else crisisOrCool = "crisis";

		return ret = {id : id, crisisOrCool : crisisOrCool};
	}

	function areaUnavailable(area){
		var randomAreaInfos = generateAreas();
		newArea = new Area(cities[randomAreaInfos.id].x, cities[randomAreaInfos.id].y, randomAreaInfos.crisisOrCool);
		console.log("area is already a node. rerolling");
	}

	function rerollArea(area){
		var newArea;
		earth.children.forEach(function(entry){
		   		if(entry.name == area.name){
		   			return false;
				}
			});
		return true;

		return newArea;
	}

	function onMouseMove(e)
    {
        mouse.x = ( e.clientX / window.innerWidth ) * 2 - 1;
        mouse.y = - ( e.clientY / window.innerHeight ) * 2 + 1;
    };

    function onWindowResize(e)
    {
		containerWidth = window.innerWidth;
		containerHeight = window.innerHeight;
		renderer.setSize(containerWidth, containerHeight);
		camera.aspect = containerWidth / containerHeight;
		camera.updateProjectionMatrix();
	}

    earth.rotateY(1.5);

    var lastTime = (new Date()).getTime();

    var render = function()
    {
        // Compute time
        var time = (new Date()).getTime();
        var dt = (time - lastTime) / 1000.0;
        lastTime = time;

        requestAnimationFrame(render);
        update_sound(audio.osc, audio.gain, 440, audio.pan, (area2.position.x-camera.position.x)/200,(area2.position.y-camera.position.y)/200,(area2.position.z-camera.position.z)/200);

        vector.set(mouse.x, mouse.y, 0.1).unproject(camera);
        raycaster.ray.set(camera.position, vector.sub(camera.position).normalize());
        var intersections = raycaster.intersectObjects(scene.children, true);
        for(i = 0; i < intersections.length; ++i)
        {
            if(intersections[i].object.hover != null)
                intersections[i].object.hover();
        }

    	controls.update();

	   	earth.children.forEach(function(entry){
	   		if(entry.update != null)
	   			entry.update(dt);
		});

       	renderer.render(scene, camera);
    };

    render();

    container.append(renderer.domElement);
};

<|endoftext|>


<commit_before><commit_msg>properly calculate text width across browsers<commit_after><|endoftext|>


<commit_before>function(args) {
/*
is_app(true)
control_type("VB")
display_name("Data Window control")
description("This will return the data window control")
base_component_id("data_window_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:     "text",
            name:   "Text",
            type:   "String"
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    350,
            type:       "Number"
        }
        ,
        {
            id:     "limit",
            name:   "Limit",
            type:   "Number",
            default_expression: "(typeof $RETURNED_ROWS_LIMIT !== 'undefined')?eval('$RETURNED_ROWS_LIMIT'):100",
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    300,
            type:       "Number"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:     "changed_event",
            name:   "Changed event",
            type:   "Event"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "hide_children",
            name:       "Hide Children?",
            type:       "Boolean",
            default:    false,
            hidden:     true
        }
        ,
        {
            id:         "setData",
            snippet:    `setData([{a: 1, b: "c"},{a: 2, b: "d"}])`,
            name:       "setData",
            type:       "Action"
        }
        ,
        {
            id:         "resetColumns",
            snippet:    `resetColumns()`,
            name:       "resetColumns",
            type:       "Action"
        }
        ,
        {
            id:     "addColumn",
            name:   "addColumn",
            type:   "Action"
        }
        ,
        {
            id:     "source_type",
            name:   "Data Source Type",
            type:   "String",
            default: "postgres"
        }
        ,
        {
            id:     "sql",
            name:   "SQL",
            type:   "String",
            default: "SELECT * FROM pg_catalog.pg_tables;"
        }
        ,
        {
            id:      "user",
            name:    "USER",
            type:    "String",
            default_expression: "(typeof $POSTGRES_USER !== 'undefined')?eval('$POSTGRES_USER'):'postgres'"
        }
        ,
        {
            id:     "password",
            name:   "Password",
            type:   "String",
            default_expression: "(typeof $POSTGRES_PASSWORD !== 'undefined')?eval('$POSTGRES_PASSWORD'):'password'",
        }
        ,
        {
            id:     "database",
            name:   "Database",
            type:   "String",
            default_expression: "(typeof $POSTGRES_DATABASE !== 'undefined')?eval('$POSTGRES_DATABASE'):'postgres'",
        }
        ,
        {
            id:     "port",
            name:   "Port",
            type:   "Number",
            default_expression: "(typeof $POSTGRES_PORT !== 'undefined')?eval('$POSTGRES_PORT'):5432",
        }
        ,
        {
            id:     "host",
            name:   "Host",
            type:   "String",
            default_expression: "(typeof $POSTGRES_HOST !== 'undefined')?$POSTGRES_HOST:'localhost'",
        }

        ,
        {
            id:     "result",
            name:   "result",
            type:   "Array",
            default:    []
        }
        ,
        {
            id:         "executeSql",
            pre_snippet: `await `,
            snippet:    `executeSql()`,
            name:       "executeSql",
            type:       "Action",
            help:       `
Help text for
                            executeSql function

The SQL is store in the "sql" property

`
        }
        ]
)//properties
logo_url("/driver_icons/data_window.png")
*/

    Vue.component("data_window_control",{
      props: ["meta","name","args","refresh","design_mode"]
      ,
      template:
`

            SQL Builder

                    Data source connection

                Schema and tables

                Columns

                Where

            connection tab

           schema tab

            columns tab

            where tab

                     SQL:
                        {{args.sql}}

`
      ,

      data: function() {
       return {
         selected_index:     null
         ,
         columnDefinitions: [ ]
         ,
         data:              [ ]
         ,
         table:              null
         ,
         designDetailTab: "connection"
       }
     }
     ,

     watch: {
       // This would be called anytime the value of the input changes
       refresh: function(newValue, oldValue) {
           //console.log("refresh: " + this.args.text)
           if (isValidObject(this.args)) {
           }
       }
     }
     ,

     mounted: async function() {
         registerComponent(this)

         if (isValidObject(this.args)) {
         }

         if (this.design_mode == false) {
             this.table = new Tabulator(this.$refs.exampletable, {
                    width:                    this.args.width
                    ,
                    height:                    this.args.height
                    ,
                    tables:                    []
                    ,
                    data:                      this.data
                    ,
                	layout:                    "fitColumns"
                    ,
                	responsiveLayout:          "hide"
                    ,
                	tooltips:                   true
                    ,
                	addRowPos:                 "top"
                    ,
                	history:                    true
                    ,
                	pagination:                "local"
                    ,
                	paginationSize:             7
                    ,
                	movableColumns:             true
                    ,
                	resizableRows:              true
                    ,

                	initialSort:                [
                                            	]
                    ,

                	columns:                    this.columnDefinitions
                });
         }

         if (!this.design_mode) {

             var results = await this.executeSql()
             //alert(JSON.stringify(results,null,2))
             await this.setData(results.value)
         }

      }
      ,

      methods: {

            changedFn: function() {
                if (isValidObject(this.args)) {
                }
            }

            ,
            resetColumns: async function(data) {
                this.table.setColumns([])
            }
            ,
            addColumn: async function(colData) {
                this.table.addColumn(colData, true, "name");
            }
            ,

            runEventHandler: function() {
                this.$emit('send', {
                                                type:               "subcomponent_event",
                                                control_name:        this.args.name,
                                                sub_type:           "changed",
                                                code:                this.args.changed_event
                                            })
            }
            ,
            setData: async function(data) {
                this.data = data
                this.table.setData(data)

                var keysOfData = new Object()
                if ((this.columnDefinitions == null)  || (this.columnDefinitions.length == 0)) {
                    for (var rr = 0 ; rr < data.length; rr ++) {
                        var dfg = Object.keys(data[rr])
                        for (var qq = 0 ; qq < dfg.length; qq ++) {
                            keysOfData[dfg[qq]] = true
                        }
                    }
                }

                var dfg2 = Object.keys(keysOfData)
                for (var qq2 = 0 ; qq2 < dfg2.length; qq2 ++) {
                    this.addColumn({title:dfg2[qq2], field:dfg2[qq2]})
                }

            }
            ,

            executeSql: async function() {
                if (!this.design_mode) {
                    var result = await callFunction(
                                        {
                                            driver_name: "postgres_server",
                                            method_name: "postgres_sql"  }
                                            ,{
                                                sql:             this.args.sql,
                                                user:            this.args.user,
                                                password:        this.args.password,
                                                database:        this.args.database,
                                                host:            this.args.host,
                                                port:            this.args.port,
                                                limit:           this.args.limit
                                             })

                   //alert("executeSql: " + JSON.stringify(result,null,2))
                   console.log(JSON.stringify(result,null,2))
                   if (result.value) {
                        this.args.result = result.value.result

                        return result.value
                   }

               }
                this.args.result = []
                this.changedFn()
                return {}
            }

        }

    })
}
<commit_msg>Show different data source types<commit_after>function(args) {
/*
is_app(true)
control_type("VB")
display_name("Data Window control")
description("This will return the data window control")
base_component_id("data_window_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:     "text",
            name:   "Text",
            type:   "String"
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    350,
            type:       "Number"
        }
        ,
        {
            id:     "limit",
            name:   "Limit",
            type:   "Number",
            default_expression: "(typeof $RETURNED_ROWS_LIMIT !== 'undefined')?eval('$RETURNED_ROWS_LIMIT'):100",
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    300,
            type:       "Number"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:     "changed_event",
            name:   "Changed event",
            type:   "Event"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "hide_children",
            name:       "Hide Children?",
            type:       "Boolean",
            default:    false,
            hidden:     true
        }
        ,
        {
            id:         "setData",
            snippet:    `setData([{a: 1, b: "c"},{a: 2, b: "d"}])`,
            name:       "setData",
            type:       "Action"
        }
        ,
        {
            id:         "resetColumns",
            snippet:    `resetColumns()`,
            name:       "resetColumns",
            type:       "Action"
        }
        ,
        {
            id:     "addColumn",
            name:   "addColumn",
            type:   "Action"
        }
        ,
        {
            id:     "source_type",
            name:   "Data Source Type",
            type:   "String",
            default: "postgres"
        }
        ,
        {
            id:     "sql",
            name:   "SQL",
            type:   "String",
            default: "SELECT * FROM pg_catalog.pg_tables;"
        }
        ,
        {
            id:      "user",
            name:    "USER",
            type:    "String",
            default_expression: "(typeof $POSTGRES_USER !== 'undefined')?eval('$POSTGRES_USER'):'postgres'"
        }
        ,
        {
            id:     "password",
            name:   "Password",
            type:   "String",
            default_expression: "(typeof $POSTGRES_PASSWORD !== 'undefined')?eval('$POSTGRES_PASSWORD'):'password'",
        }
        ,
        {
            id:     "database",
            name:   "Database",
            type:   "String",
            default_expression: "(typeof $POSTGRES_DATABASE !== 'undefined')?eval('$POSTGRES_DATABASE'):'postgres'",
        }
        ,
        {
            id:     "port",
            name:   "Port",
            type:   "Number",
            default_expression: "(typeof $POSTGRES_PORT !== 'undefined')?eval('$POSTGRES_PORT'):5432",
        }
        ,
        {
            id:     "host",
            name:   "Host",
            type:   "String",
            default_expression: "(typeof $POSTGRES_HOST !== 'undefined')?$POSTGRES_HOST:'localhost'",
        }

        ,
        {
            id:     "result",
            name:   "result",
            type:   "Array",
            default:    []
        }
        ,
        {
            id:         "executeSql",
            pre_snippet: `await `,
            snippet:    `executeSql()`,
            name:       "executeSql",
            type:       "Action",
            help:       `
Help text for
                            executeSql function

The SQL is store in the "sql" property

`
        }
        ]
)//properties
logo_url("/driver_icons/data_window.png")
*/

    Vue.component("data_window_control",{
      props: ["meta","name","args","refresh","design_mode"]
      ,
      template:
`

            SQL Builder

                    Data source connection

                Schema and tables

                Columns

                Where

            connection tab

            <select  @change='alert($event)'>
                  <option   v-for='propVal in ["postgres","csv"]'
                            v-bind:value="propVal"
                            v-bind:selected='(propVal == "postgres")'>

                        {{propVal}}

                  </option>
            </select>

           schema tab

            columns tab

            where tab

                     SQL:
                        {{args.sql}}

`
      ,

      data: function() {
       return {
         selected_index:     null
         ,
         columnDefinitions: [ ]
         ,
         data:              [ ]
         ,
         table:              null
         ,
         designDetailTab: "connection"
       }
     }
     ,

     watch: {
       // This would be called anytime the value of the input changes
       refresh: function(newValue, oldValue) {
           //console.log("refresh: " + this.args.text)
           if (isValidObject(this.args)) {
           }
       }
     }
     ,

     mounted: async function() {
         registerComponent(this)

         if (isValidObject(this.args)) {
         }

         if (this.design_mode == false) {
             this.table = new Tabulator(this.$refs.exampletable, {
                    width:                    this.args.width
                    ,
                    height:                    this.args.height
                    ,
                    tables:                    []
                    ,
                    data:                      this.data
                    ,
                	layout:                    "fitColumns"
                    ,
                	responsiveLayout:          "hide"
                    ,
                	tooltips:                   true
                    ,
                	addRowPos:                 "top"
                    ,
                	history:                    true
                    ,
                	pagination:                "local"
                    ,
                	paginationSize:             7
                    ,
                	movableColumns:             true
                    ,
                	resizableRows:              true
                    ,

                	initialSort:                [
                                            	]
                    ,

                	columns:                    this.columnDefinitions
                });
         }

         if (!this.design_mode) {

             var results = await this.executeSql()
             //alert(JSON.stringify(results,null,2))
             await this.setData(results.value)
         }

      }
      ,

      methods: {

            changedFn: function() {
                if (isValidObject(this.args)) {
                }
            }

            ,
            resetColumns: async function(data) {
                this.table.setColumns([])
            }
            ,
            addColumn: async function(colData) {
                this.table.addColumn(colData, true, "name");
            }
            ,

            runEventHandler: function() {
                this.$emit('send', {
                                                type:               "subcomponent_event",
                                                control_name:        this.args.name,
                                                sub_type:           "changed",
                                                code:                this.args.changed_event
                                            })
            }
            ,
            setData: async function(data) {
                this.data = data
                this.table.setData(data)

                var keysOfData = new Object()
                if ((this.columnDefinitions == null)  || (this.columnDefinitions.length == 0)) {
                    for (var rr = 0 ; rr < data.length; rr ++) {
                        var dfg = Object.keys(data[rr])
                        for (var qq = 0 ; qq < dfg.length; qq ++) {
                            keysOfData[dfg[qq]] = true
                        }
                    }
                }

                var dfg2 = Object.keys(keysOfData)
                for (var qq2 = 0 ; qq2 < dfg2.length; qq2 ++) {
                    this.addColumn({title:dfg2[qq2], field:dfg2[qq2]})
                }

            }
            ,

            executeSql: async function() {
                if (!this.design_mode) {
                    var result = await callFunction(
                                        {
                                            driver_name: "postgres_server",
                                            method_name: "postgres_sql"  }
                                            ,{
                                                sql:             this.args.sql,
                                                user:            this.args.user,
                                                password:        this.args.password,
                                                database:        this.args.database,
                                                host:            this.args.host,
                                                port:            this.args.port,
                                                limit:           this.args.limit
                                             })

                   //alert("executeSql: " + JSON.stringify(result,null,2))
                   console.log(JSON.stringify(result,null,2))
                   if (result.value) {
                        this.args.result = result.value.result

                        return result.value
                   }

               }
                this.args.result = []
                this.changedFn()
                return {}
            }

        }

    })
}
<|endoftext|>


<commit_before>function(args) {
/*
is_app(true)
control_type("VB")
display_name("Data Window control")
description("This will return the data window control")
base_component_id("data_window_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:     "text",
            name:   "Text",
            type:   "String"
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    350,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    300,
            type:       "Number"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,
        {
            id:         "items",
            name:       "Items",
            type:       "Array",
            default:    [],
            editor:     "detail_editor"
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:     "changed_event",
            name:   "Changed event",
            type:   "Event"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "hide_children",
            name:       "Hide Children?",
            type:       "Boolean",
            default:    false,
            hidden:     true
        }
        ,
        {
            id:         "setData",
            snippet:    `setData([{a: 1, b: "c"},{a: 2, b: "d"}])`,
            name:       "setData",
            type:       "Action"
        }
        ,
        {
            id:         "resetColumns",
            snippet:    `resetColumns()`,
            name:       "resetColumns",
            type:       "Action"
        }
        ,
        {
            id:     "addColumn",
            name:   "addColumn",
            type:   "Action"
        }
    ]
)//properties
logo_url("/driver_icons/data_window.png")
*/

    Vue.component("data_window_control",{
      props: ["args","refresh","design_mode"]
      ,
      template:
`

         <input v-model="new_value"></input>
         <input v-model="new_text"></input>

            Add

                         {{child_item.value}}:{{child_item.text}}

                 <div    class='btn btn-info'
                         v-bind:refresh='refresh'
                         v-on:click='var x = items[index];items.splice(index, 1);items.splice(index - 1, 0, x);changedFn();'
                         v-if='child_item'
                         v-bind:style='"box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;padding:0px; z-index: 21474836;opacity:1;"  +
                         "width: 60px; height: 20px; line-height:20px;text-align: center;vertical-align: middle;margin-left: 20px;"'>
                         UP

                 <div    class='btn btn-info'
                         v-bind:refresh='refresh'
                         v-on:click='var x = items[index];items.splice(index, 1);items.splice(index + 1, 0, x);changedFn();'
                         v-if='child_item'
                         v-bind:style='"box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;padding:0px; z-index: 21474836;opacity:1;"  +
                         "width: 60px; height: 20px; line-height:20px;text-align: center;vertical-align: middle;margin-left: 20px;"'>
                         DOWN

                         X

        <select
            v-on:change='changedFn();runEventHandler()'
            size="5"
            v-model='value'>

            <option v-for='opt in args.items'
                    v-bind:value='opt.value'>
                {{opt.text}}
            </option>
        </select>

`
      ,
      data: function() {
       return {
         value:             null,
         selected_index:    null,
         items:             [],
         new_value:         "",
         new_text:          ""
         ,
         columnDefinitions: [ ]
         ,
         data:              [ ]
         ,
         table:   null
       }
     }
     ,
     watch: {
       // This would be called anytime the value of the input changes
       refresh: function(newValue, oldValue) {
           //console.log("refresh: " + this.args.text)
           if (isValidObject(this.args)) {
               this.value = this.args.value
               this.items = this.args.items
           }
       }
     }
     ,
     mounted: function() {
         registerComponent(this)

         if (isValidObject(this.args)) {
             this.items = this.args.items
             if (isValidObject(this.args.value)) {
                this.value = this.args.value
             }
         }

          this.table = new Tabulator(this.$refs.exampletable, {
                 width:                    this.args.width
                 ,
                 height:                    this.args.height
                 ,
             	data:                       this.data
                 ,
             	layout:                    "fitColumns"
                 ,
             	responsiveLayout:          "hide"
                 ,
             	tooltips:                   true
                 ,
             	addRowPos:                 "top"
                 ,
             	history:                    true
                 ,
             	pagination:                "local"
                 ,
             	paginationSize:             7
                 ,
             	movableColumns:             true
                 ,
             	resizableRows:              true
                 ,

             	initialSort:                [
                                         	]
                 ,

             	columns:                    this.columnDefinitions
             });

      }
      ,
      methods: {
            changedFn: function() {
                if (isValidObject(this.args)) {
                    this.args.value = this.value
                    this.args.items = this.items
                }
            }
            ,
            resetColumns: async function(data) {
                this.table.setColumns([])
            }
            ,
            addColumn: async function(colData) {
                this.table.addColumn(colData, true, "name");
            }
            ,

            runEventHandler: function() {
                this.$emit('send', {
                                                type:               "subcomponent_event",
                                                control_name:        this.args.name,
                                                sub_type:           "changed",
                                                code:                this.args.changed_event
                                            })
            }
            ,
            setData: async function(data) {
                this.data = data
                this.table.setData(data)

                var keysOfData = new Object()
                if ((this.columnDefinitions == null)  || (this.columnDefinitions.length == 0)) {
                    for (var rr = 0 ; rr < data.length; rr ++) {
                        var dfg = Object.keys(data[rr])
                        for (var qq = 0 ; qq < dfg.length; qq ++) {
                            keysOfData[dfg[qq]] = true
                        }
                    }
                }

                var dfg2 = Object.keys(keysOfData)
                for (var qq2 = 0 ; qq2 < dfg2.length; qq2 ++) {
                    this.addColumn({title:dfg2[qq2], field:dfg2[qq2]})
                }

            }
        }

    })
}
<commit_msg>DataWindow control: we can now set data here with "setData"<commit_after>function(args) {
/*
is_app(true)
control_type("VB")
display_name("Data Window control")
description("This will return the data window control")
base_component_id("data_window_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:     "text",
            name:   "Text",
            type:   "String"
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    350,
            type:       "Number"
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    300,
            type:       "Number"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,
        {
            id:         "items",
            name:       "Items",
            type:       "Array",
            default:    [],
            editor:     "detail_editor"
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:     "changed_event",
            name:   "Changed event",
            type:   "Event"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "hide_children",
            name:       "Hide Children?",
            type:       "Boolean",
            default:    false,
            hidden:     true
        }
        ,
        {
            id:         "setData",
            snippet:    `setData([{a: 1, b: "c"},{a: 2, b: "d"}])`,
            name:       "setData",
            type:       "Action"
        }
        ,
        {
            id:         "resetColumns",
            snippet:    `resetColumns()`,
            name:       "resetColumns",
            type:       "Action"
        }
        ,
        {
            id:     "addColumn",
            name:   "addColumn",
            type:   "Action"
        }
    ]
)//properties
logo_url("/driver_icons/data_window.png")
*/

    Vue.component("data_window_control",{
      props: ["meta","name","args","refresh","design_mode"]
      ,
      template:
`

         <input v-model="new_value"></input>
         <input v-model="new_text"></input>

            Add

                         {{child_item.value}}:{{child_item.text}}

                 <div    class='btn btn-info'
                         v-bind:refresh='refresh'
                         v-on:click='var x = items[index];items.splice(index, 1);items.splice(index - 1, 0, x);changedFn();'
                         v-if='child_item'
                         v-bind:style='"box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;padding:0px; z-index: 21474836;opacity:1;"  +
                         "width: 60px; height: 20px; line-height:20px;text-align: center;vertical-align: middle;margin-left: 20px;"'>
                         UP

                 <div    class='btn btn-info'
                         v-bind:refresh='refresh'
                         v-on:click='var x = items[index];items.splice(index, 1);items.splice(index + 1, 0, x);changedFn();'
                         v-if='child_item'
                         v-bind:style='"box-shadow: rgba(0, 0, 0, 0.2) 0px 4px 8px 0px, rgba(0, 0, 0, 0.19) 0px 6px 20px 0px;padding:0px; z-index: 21474836;opacity:1;"  +
                         "width: 60px; height: 20px; line-height:20px;text-align: center;vertical-align: middle;margin-left: 20px;"'>
                         DOWN

                         X

        <select
            v-on:change='changedFn();runEventHandler()'
            size="5"
            v-model='value'>

            <option v-for='opt in args.items'
                    v-bind:value='opt.value'>
                {{opt.text}}
            </option>
        </select>

`
      ,

      data: function() {
       return {
         value:              null
         ,
         selected_index:     null
         ,
         items:             []
         ,
         new_value:          ""
         ,
         new_text:           ""
         ,
         columnDefinitions: [ ]
         ,
         data:              [ ]
         ,
         table:              null
       }
     }
     ,

     watch: {
       // This would be called anytime the value of the input changes
       refresh: function(newValue, oldValue) {
           //console.log("refresh: " + this.args.text)
           if (isValidObject(this.args)) {
               this.value = this.args.value
               this.items = this.args.items
           }
       }
     }
     ,

     mounted: function() {
         registerComponent(this)

         if (isValidObject(this.args)) {
             this.items = this.args.items
             if (isValidObject(this.args.value)) {
                this.value = this.args.value
             }
         }

          this.table = new Tabulator(this.$refs.exampletable, {
                 width:                    this.args.width
                 ,
                 height:                    this.args.height
                 ,
                 data:                      this.data
                 ,
             	layout:                    "fitColumns"
                 ,
             	responsiveLayout:          "hide"
                 ,
             	tooltips:                   true
                 ,
             	addRowPos:                 "top"
                 ,
             	history:                    true
                 ,
             	pagination:                "local"
                 ,
             	paginationSize:             7
                 ,
             	movableColumns:             true
                 ,
             	resizableRows:              true
                 ,

             	initialSort:                [
                                         	]
                 ,

             	columns:                    this.columnDefinitions
             });

      }
      ,

      methods: {

            changedFn: function() {
                if (isValidObject(this.args)) {
                    this.args.value = this.value
                    this.args.items = this.items
                }
            }

            ,
            resetColumns: async function(data) {
                this.table.setColumns([])
            }
            ,
            addColumn: async function(colData) {
                this.table.addColumn(colData, true, "name");
            }
            ,

            runEventHandler: function() {
                this.$emit('send', {
                                                type:               "subcomponent_event",
                                                control_name:        this.args.name,
                                                sub_type:           "changed",
                                                code:                this.args.changed_event
                                            })
            }
            ,
            setData: async function(data) {
                this.data = data
                this.table.setData(data)

                var keysOfData = new Object()
                if ((this.columnDefinitions == null)  || (this.columnDefinitions.length == 0)) {
                    for (var rr = 0 ; rr < data.length; rr ++) {
                        var dfg = Object.keys(data[rr])
                        for (var qq = 0 ; qq < dfg.length; qq ++) {
                            keysOfData[dfg[qq]] = true
                        }
                    }
                }

                var dfg2 = Object.keys(keysOfData)
                for (var qq2 = 0 ; qq2 < dfg2.length; qq2 ++) {
                    this.addColumn({title:dfg2[qq2], field:dfg2[qq2]})
                }

            }
        }

    })
}
<|endoftext|>