<commit_before>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011-2013 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

module.exports = new function() {
	var finish,
		valueOf,
		checkCallbackMethod,
		reportError,
		Tizen;

	this.init = function(testUtils) {
		finish = testUtils.finish;
		valueOf = testUtils.valueOf;
		reportError = testUtils.reportError;
		checkCallbackMethod = checkCallbackMethodFunction;
		Tizen = require('tizen');
	}

	//Tests for Tizen Device API: SystemInfo Device API
	this.name = 'sysinfo';
	this.tests = [
		{name: 'checkSystemInfo'},
		// {name: 'allPropertiesSupported'},
		{name: 'getCpuProperty'},
		{name: 'getStorageProperty'},
		{name: 'getWifiNetworkProperty'},
		{name: 'getCellularNetworkProperty'},
		// {name: 'getEthernetNetworkProperty'},
		{name: 'getSimProperty'},
		{name: 'testListenersCpu'},
		{name: 'testListenersStorage'},
		// {name: 'testListenersDevice'},
		{name: 'testListenersSIM'},
		//{name: 'testListenersEthernetNetwork'},
		{name: 'testListenersCellularNetwork'},
		{name: 'testListenersWifiNetwork'}
	];

	this.checkSystemInfo  = function(testRun) {

		Ti.API.debug('Checking SystemInfo object availability.');
		valueOf(testRun, Tizen).shouldBeObject();
		valueOf(testRun, Tizen.SystemInfo).shouldBeObject();
		finish(testRun);
	}

	this.allPropertiesSupported = function(testRun) {
		// Test for Tizen Device API: do all documented properties are supported?
		// according to 'Tizen Web App Programming' => 'Programming Guide' => 'Device' => 'SystemInfo'
		// Basic Supported Properties are: Power, Cpu, Storage, Display, Device, WifiNetwork, CellularNetwork.
		// And 'Network', 'EthernetNetwork', 'SIM', 'DeviceOrientation' are NOT 'Basic Supported Properties' and depends on device
		var i = 0,
			current,
			isSupported,
			listOfAllProperties = [
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_BATTERY,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_CPU,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_STORAGE,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_DISPLAY,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_BUILD,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_NETWORK,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_WIFI_NETWORK,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_CELLULAR_NETWORK,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_SIM,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_DEVICE_ORIENTATION
			],
			len = listOfAllProperties.length;

		for (; i < len; i++) {
			current  = listOfAllProperties[i];
			try{
				isSupported = Tizen.SystemInfo.isSupported(current);
				valueOf(testRun, isSupported).shouldBeTrue(); // test passed only if all properties are supported!

				if (isSupported) {
					Ti.API.debug('"' + current + '" property is supported.');
				} else {
					Ti.API.debug('"' + current + '" property is not supported.');
				}
			}catch (e) {
				Ti.API.debug('"' + current + '" property cause exception: ' + e.message);
				reportError(testRun, JSON.stringify(e));
			}
		}
		finish(testRun);
	}

	this.getCpuProperty = function(testRun) {
		//Test for Tizen Device API: SystemInfoCpu
		function onSuccessCallback(cpuData) {
			Ti.API.debug('The power CPU load level is ' + cpuData.load);

			valueOf(testRun, cpuData.toString()).shouldBe('[object TizenSystemInfoSystemInfoCpu]');
			valueOf(testRun, cpuData.load).shouldBeNumber(); // double!
			finish(testRun);
		}

		function onErrorCallback(error) {
			Ti.API.info('An error occurred on Cpu property:' + error.message);

			valueOf(testRun, error.toString()).shouldBe('[object TizenWebAPIError]');
			finish(testRun);
		}

		valueOf(testRun, Tizen.SystemInfo.getPropertyValue).shouldBeFunction();
		Tizen.SystemInfo.getPropertyValue(Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_CPU, onSuccessCallback, onErrorCallback);
	}

	this.getStorageProperty = function(testRun) {
		//Test for Tizen Device API: SystemInfoStorage and SystemInfoStorageUnit
		function onSuccessCallback(systemInfoStorage) {
			Ti.API.debug('Storage info: ' + JSON.stringify(systemInfoStorage));

			valueOf(testRun, systemInfoStorage.toString()).shouldBe('[object TizenSystemInfoSystemInfoStorage]');

			if (systemInfoStorage.units) {
				var i = 0,
					len = systemInfoStorage.units.length,
					current;

				for (; i < len; i++) {
					current  = systemInfoStorage.units[i];

					Ti.API.debug('Storage info: ' + JSON.stringify(current));

					valueOf(testRun, current.toString()).shouldBe('[object TizenSystemInfoSystemInfoStorageUnit]');
				}
			}

			finish(testRun);
		}

		function onErrorCallback(error) {
			Ti.API.info('An error occurred on Storage property:' + error.message);
			valueOf(testRun, error.toString()).shouldBe('[object TizenWebAPIError]');
			finish(testRun);
		}

		valueOf(testRun, Tizen.SystemInfo.getPropertyValue).shouldBeFunction();
		Tizen.SystemInfo.getPropertyValue(Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_STORAGE, onSuccessCallback, onErrorCallback);
	}

	this.getWifiNetworkProperty = function(testRun) {
		// Test for Tizen Device API: SystemInfoWifiNetwork
		function onSuccessCallback(systemInfoWifiNetwork) {
			Ti.API.debug('Wifi network info: ' + JSON.stringify(systemInfoWifiNetwork));

			valueOf(testRun, systemInfoWifiNetwork).shouldBe('[object TizenSystemInfoSystemInfoWifiNetwork]');

			if (systemInfoWifiNetwork){
				valueOf(testRun, systemInfoWifiNetwork.status).shouldBeString();
				valueOf(testRun, systemInfoWifiNetwork.ssid).shouldBeString();
				valueOf(testRun, systemInfoWifiNetwork.ipAddress).shouldBeString();
				valueOf(testRun, systemInfoWifiNetwork.ipv6Address).shouldBeString();
				valueOf(testRun, systemInfoWifiNetwork.signalStrength).shouldBeNumber();
			}
			finish(testRun);
		}

		function onErrorCallback(error) {
			Ti.API.info('An error occurred on WifiNetwork property:' + error.message);
			valueOf(testRun, error).shouldBe('[object TizenWebAPIError]');
			finish(testRun);
		}

		valueOf(testRun, Tizen.SystemInfo.getPropertyValue).shouldBeFunction();
		Tizen.SystemInfo.getPropertyValue(Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_WIFI_NETWORK, onSuccessCallback, onErrorCallback);
	}

	this.getCellularNetworkProperty = function(testRun) {
	// Test for Tizen Device API: SystemInfoCellularNetwork
		function onSuccessCallback(systemInfoCellularNetwork) {
			Ti.API.debug('Cellular network info: ' + JSON.stringify(systemInfoCellularNetwork));

			valueOf(testRun, systemInfoCellularNetwork).shouldBe('[object TizenSystemInfoSystemInfoCellularNetwork]');

			if (systemInfoCellularNetwork){
				valueOf(testRun, systemInfoCellularNetwork.status).shouldBeString();
				valueOf(testRun, systemInfoCellularNetwork.apn).shouldBeString();
				valueOf(testRun, systemInfoCellularNetwork.ipAddress).shouldBeString();
				valueOf(testRun, systemInfoCellularNetwork.ipv6Address).shouldBeString();
				valueOf(testRun, systemInfoCellularNetwork.mcc).shouldBeNumber();
				valueOf(testRun, systemInfoCellularNetwork.mnc).shouldBeNumber();
				valueOf(testRun, systemInfoCellularNetwork.cellId).shouldBeNumber();
				valueOf(testRun, systemInfoCellularNetwork.lac).shouldBeNumber();
				valueOf(testRun, systemInfoCellularNetwork.isRoaming).shouldBeBoolean();
			}
			finish(testRun);
		}

		function onErrorCallback(error) {
			Ti.API.info('An error occurred on "CellularNetwork" property:' + error.message);
			valueOf(testRun, error).shouldBe('[object TizenWebAPIError]');
			finish(testRun);
		}

		valueOf(testRun, Tizen.SystemInfo.getPropertyValue).shouldBeFunction();
		Tizen.SystemInfo.getPropertyValue(Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_CELLULAR_NETWORK, onSuccessCallback, onErrorCallback);
	}

	this.getEthernetNetworkProperty = function(testRun) {
	// Test for Tizen Device API: SystemInfoEthernetNetwork
		function onSuccessCallback(systemInfoEthernetNetwork) {
			Ti.API.debug('Ethernet network info: ' + JSON.stringify(systemInfoEthernetNetwork));

			valueOf(testRun, systemInfoEthernetNetwork).shouldBe('[object TizenSystemInfoSystemInfoEthernetNetwork]');

			if (systemInfoEthernetNetwork){
				valueOf(testRun, systemInfoEthernetNetwork.status).shouldBeString();
				valueOf(testRun, systemInfoEthernetNetwork.ipAddress).shouldBeString();
				valueOf(testRun, systemInfoEthernetNetwork.ipv6Address).shouldBeString();
				valueOf(testRun, systemInfoEthernetNetwork.proxyAddress).shouldBeString();
				valueOf(testRun, systemInfoEthernetNetwork.macAddress).shouldBeString();
				valueOf(testRun, systemInfoEthernetNetwork.gateway).shouldBeString();
				valueOf(testRun, systemInfoEthernetNetwork.dns).shouldBeString();
				valueOf(testRun, systemInfoEthernetNetwork.subnetMask).shouldBeString();
			}
			finish(testRun);
		}

		function onErrorCallback(error) {
			Ti.API.info('An error occurred on EthernetNetwork property:' + error.message);
			valueOf(testRun, error).shouldBe('[object TizenWebAPIError]');
			finish(testRun);
		}

		valueOf(testRun, Tizen.SystemInfo.getPropertyValue).shouldBeFunction();
		Tizen.SystemInfo.getPropertyValue('EthernetNetwork', onSuccessCallback, onErrorCallback);
	}

	this.getSimProperty = function(testRun) {
	// Test for Tizen Device API: SystemInfoSIM
		function onSuccessCallback(systemInfoSIM) {
			Ti.API.debug('SIM info: ' + JSON.stringify(systemInfoSIM));

			valueOf(testRun, systemInfoSIM).shouldBe('[object TizenSystemInfoSystemInfoSIM]');

			if (systemInfoSIM){
				valueOf(testRun, systemInfoSIM.operatorName).shouldBeString();
				valueOf(testRun, systemInfoSIM.msisdn).shouldBeString();
				valueOf(testRun, systemInfoSIM.iccid).shouldBeString();
				valueOf(testRun, systemInfoSIM.msin).shouldBeString();
				valueOf(testRun, systemInfoSIM.spn).shouldBeString();
				valueOf(testRun, systemInfoSIM.mcc).shouldBeNumber();
				valueOf(testRun, systemInfoSIM.mnc).shouldBeNumber();
			}

			finish(testRun);
		}

		function onErrorCallback(error) {
			Ti.API.info('An error occurred on SIM property:' + error.message);
			valueOf(testRun, error).shouldBe('[object TizenWebAPIError]');
			finish(testRun);
		}

		valueOf(testRun, Tizen.SystemInfo.getPropertyValue).shouldBeFunction();
		Tizen.SystemInfo.getPropertyValue(Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_SIM, onSuccessCallback, onErrorCallback);
	}

	this.testListenersCpu = function(testRun) {
		checkCallbackMethod( {propertyName: Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_CPU, testRun: testRun, optionsParameter:{}} );
	}

	this.testListenersStorage = function(testRun) {
		checkCallbackMethod( {propertyName: Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_STORAGE, testRun: testRun, optionsParameter:{}} );
	}

	this.testListenersWifiNetwork = function(testRun) {
		checkCallbackMethod( {propertyName: Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_WIFI_NETWORK, testRun: testRun, optionsParameter:{} });
	}

	this.testListenersCellularNetwork = function(testRun) {
		checkCallbackMethod( {propertyName: Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_CELLULAR_NETWORK, testRun: testRun, optionsParameter:{} });
	}

	this.testListenersEthernetNetwork = function(testRun) {
		checkCallbackMethod( {propertyName: 'EthernetNetwork', testRun: testRun, optionsParameter:{} });
	}

	this.testListenersSIM = function(testRun) {
		checkCallbackMethod( {propertyName: Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_SIM, testRun: testRun, optionsParameter:{} });
	}

	// helper that allows to test addPropertyValueChangeListener, removePropertyValueChangeListener, SystemInfoOptions
	// will be completed in 2 sec in any case.
	function checkCallbackMethodFunction (data) {
		Ti.API.debug('Running listener check for: ' + (data?data.propertyName:'[Wrong parameter!]'));
		var id,
			testRun = data.testRun,
			waitTimeout;

		// removes current listener. Must be completed to accept valid test.
		function removeListener() {
			valueOf(testRun, id).shouldNotBeNull();
			Ti.API.debug('removing listener with ID: ' + id);
			if (id != null) {
				try{
					valueOf(testRun, Tizen.SystemInfo.removePropertyValueChangeListener).shouldBeFunction();
					Tizen.SystemInfo.removePropertyValueChangeListener(id);
				} catch(e) {
					reportError(testRun, JSON.stringify(e));
				}
			}
		}

		// If can accept test as on success callback as without it
		function onSuccessCallback(dataObject) {
			Ti.API.debug('Test completed by success callback with parameter: ' + JSON.stringify(dataObject|''));
			valueOf(testRun, dataObject).shouldBe('[object TizenSystemInfoSystemInfoProperty]');
			clearFakeTimeout();  // cancel fake timer call

			valueOf(testRun, dataObject).shouldNotBeNull();
			removeListener();
			finish(testRun);
		}

		// If called with not null - test failed!
		function onErrorCallback(error) {
			Ti.API.info('Test completed by error callback - ' + JSON.stringify(error));
			valueOf(testRun, error).shouldBe('[object TizenWebAPIError]');
			clearFakeTimeout(); // cancel fake timer call
			reportError(testRun, JSON.stringify(error));
		}

		//clears timeout if it was set before.
		function clearFakeTimeout() {
			if (waitTimeout) {
				// cancel fake call if any
				clearTimeout(waitTimeout);
			}
		}

		// we don't need to wait for real callbacks from device,
		// as generally we are testing that we can subscribe and unsubscribe
		waitTimeout=setTimeout(function() {
			Ti.API.debug('Test completed by timeout!');
			removeListener();
			finish(testRun);
		}, 2000);

		try {
			// According to documentation:
			// 'Tizen Web App Programming' => 'Programming Guide' => 'Device' => 'Obtain Details on Basic Supported Properties'
			// devices MAY not support all properties. Some properties vary from device to device
			valueOf(testRun, Tizen.SystemInfo.addPropertyValueChangeListener).shouldBeFunction();

			id = Tizen.SystemInfo.addPropertyValueChangeListener(data.propertyName, onSuccessCallback, onErrorCallback, data.optionsParameter);
			valueOf(testRun, id).shouldBeGreaterThanEqual(0);
			if (id < 0) {
				clearFakeTimeout();
				Ti.API.warn('Property ' + data.propertyName + ' did not accepted listener. This may depends on device.');
				finish(testRun);
			}
		} catch(e) {
			clearFakeTimeout();
			reportError(testRun, JSON.stringify(e));
		}
	}
}
<commit_msg>Remove Wifinetwork test from Anvil<commit_after>/*
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011-2013 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */

module.exports = new function() {
	var finish,
		valueOf,
		checkCallbackMethod,
		reportError,
		Tizen;

	this.init = function(testUtils) {
		finish = testUtils.finish;
		valueOf = testUtils.valueOf;
		reportError = testUtils.reportError;
		checkCallbackMethod = checkCallbackMethodFunction;
		Tizen = require('tizen');
	}

	//Tests for Tizen Device API: SystemInfo Device API
	this.name = 'sysinfo';
	this.tests = [
		{name: 'checkSystemInfo'},
		// {name: 'allPropertiesSupported'},
		{name: 'getCpuProperty'},
		{name: 'getStorageProperty'},
		{name: 'getCellularNetworkProperty'},
		// {name: 'getEthernetNetworkProperty'},
		{name: 'getSimProperty'},
		{name: 'testListenersCpu'},
		{name: 'testListenersStorage'},
		// {name: 'testListenersDevice'},
		{name: 'testListenersSIM'},
		//{name: 'testListenersEthernetNetwork'},
		{name: 'testListenersCellularNetwork'},
		{name: 'testListenersWifiNetwork'}
	];

	this.checkSystemInfo  = function(testRun) {

		Ti.API.debug('Checking SystemInfo object availability.');
		valueOf(testRun, Tizen).shouldBeObject();
		valueOf(testRun, Tizen.SystemInfo).shouldBeObject();
		finish(testRun);
	}

	this.allPropertiesSupported = function(testRun) {
		// Test for Tizen Device API: do all documented properties are supported?
		// according to 'Tizen Web App Programming' => 'Programming Guide' => 'Device' => 'SystemInfo'
		// Basic Supported Properties are: Power, Cpu, Storage, Display, Device, WifiNetwork, CellularNetwork.
		// And 'Network', 'EthernetNetwork', 'SIM', 'DeviceOrientation' are NOT 'Basic Supported Properties' and depends on device
		var i = 0,
			current,
			isSupported,
			listOfAllProperties = [
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_BATTERY,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_CPU,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_STORAGE,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_DISPLAY,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_BUILD,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_NETWORK,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_WIFI_NETWORK,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_CELLULAR_NETWORK,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_SIM,
				Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_DEVICE_ORIENTATION
			],
			len = listOfAllProperties.length;

		for (; i < len; i++) {
			current  = listOfAllProperties[i];
			try{
				isSupported = Tizen.SystemInfo.isSupported(current);
				valueOf(testRun, isSupported).shouldBeTrue(); // test passed only if all properties are supported!

				if (isSupported) {
					Ti.API.debug('"' + current + '" property is supported.');
				} else {
					Ti.API.debug('"' + current + '" property is not supported.');
				}
			}catch (e) {
				Ti.API.debug('"' + current + '" property cause exception: ' + e.message);
				reportError(testRun, JSON.stringify(e));
			}
		}
		finish(testRun);
	}

	this.getCpuProperty = function(testRun) {
		//Test for Tizen Device API: SystemInfoCpu
		function onSuccessCallback(cpuData) {
			Ti.API.debug('The power CPU load level is ' + cpuData.load);

			valueOf(testRun, cpuData.toString()).shouldBe('[object TizenSystemInfoSystemInfoCpu]');
			valueOf(testRun, cpuData.load).shouldBeNumber(); // double!
			finish(testRun);
		}

		function onErrorCallback(error) {
			Ti.API.info('An error occurred on Cpu property:' + error.message);

			valueOf(testRun, error.toString()).shouldBe('[object TizenWebAPIError]');
			finish(testRun);
		}

		valueOf(testRun, Tizen.SystemInfo.getPropertyValue).shouldBeFunction();
		Tizen.SystemInfo.getPropertyValue(Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_CPU, onSuccessCallback, onErrorCallback);
	}

	this.getStorageProperty = function(testRun) {
		//Test for Tizen Device API: SystemInfoStorage and SystemInfoStorageUnit
		function onSuccessCallback(systemInfoStorage) {
			Ti.API.debug('Storage info: ' + JSON.stringify(systemInfoStorage));

			valueOf(testRun, systemInfoStorage.toString()).shouldBe('[object TizenSystemInfoSystemInfoStorage]');

			if (systemInfoStorage.units) {
				var i = 0,
					len = systemInfoStorage.units.length,
					current;

				for (; i < len; i++) {
					current  = systemInfoStorage.units[i];

					Ti.API.debug('Storage info: ' + JSON.stringify(current));

					valueOf(testRun, current.toString()).shouldBe('[object TizenSystemInfoSystemInfoStorageUnit]');
				}
			}

			finish(testRun);
		}

		function onErrorCallback(error) {
			Ti.API.info('An error occurred on Storage property:' + error.message);
			valueOf(testRun, error.toString()).shouldBe('[object TizenWebAPIError]');
			finish(testRun);
		}

		valueOf(testRun, Tizen.SystemInfo.getPropertyValue).shouldBeFunction();
		Tizen.SystemInfo.getPropertyValue(Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_STORAGE, onSuccessCallback, onErrorCallback);
	}

	this.getCellularNetworkProperty = function(testRun) {
	// Test for Tizen Device API: SystemInfoCellularNetwork
		function onSuccessCallback(systemInfoCellularNetwork) {
			Ti.API.debug('Cellular network info: ' + JSON.stringify(systemInfoCellularNetwork));

			valueOf(testRun, systemInfoCellularNetwork).shouldBe('[object TizenSystemInfoSystemInfoCellularNetwork]');

			if (systemInfoCellularNetwork){
				valueOf(testRun, systemInfoCellularNetwork.status).shouldBeString();
				valueOf(testRun, systemInfoCellularNetwork.apn).shouldBeString();
				valueOf(testRun, systemInfoCellularNetwork.ipAddress).shouldBeString();
				valueOf(testRun, systemInfoCellularNetwork.ipv6Address).shouldBeString();
				valueOf(testRun, systemInfoCellularNetwork.mcc).shouldBeNumber();
				valueOf(testRun, systemInfoCellularNetwork.mnc).shouldBeNumber();
				valueOf(testRun, systemInfoCellularNetwork.cellId).shouldBeNumber();
				valueOf(testRun, systemInfoCellularNetwork.lac).shouldBeNumber();
				valueOf(testRun, systemInfoCellularNetwork.isRoaming).shouldBeBoolean();
			}
			finish(testRun);
		}

		function onErrorCallback(error) {
			Ti.API.info('An error occurred on "CellularNetwork" property:' + error.message);
			valueOf(testRun, error).shouldBe('[object TizenWebAPIError]');
			finish(testRun);
		}

		valueOf(testRun, Tizen.SystemInfo.getPropertyValue).shouldBeFunction();
		Tizen.SystemInfo.getPropertyValue(Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_CELLULAR_NETWORK, onSuccessCallback, onErrorCallback);
	}

	this.getEthernetNetworkProperty = function(testRun) {
	// Test for Tizen Device API: SystemInfoEthernetNetwork
		function onSuccessCallback(systemInfoEthernetNetwork) {
			Ti.API.debug('Ethernet network info: ' + JSON.stringify(systemInfoEthernetNetwork));

			valueOf(testRun, systemInfoEthernetNetwork).shouldBe('[object TizenSystemInfoSystemInfoEthernetNetwork]');

			if (systemInfoEthernetNetwork){
				valueOf(testRun, systemInfoEthernetNetwork.status).shouldBeString();
				valueOf(testRun, systemInfoEthernetNetwork.ipAddress).shouldBeString();
				valueOf(testRun, systemInfoEthernetNetwork.ipv6Address).shouldBeString();
				valueOf(testRun, systemInfoEthernetNetwork.proxyAddress).shouldBeString();
				valueOf(testRun, systemInfoEthernetNetwork.macAddress).shouldBeString();
				valueOf(testRun, systemInfoEthernetNetwork.gateway).shouldBeString();
				valueOf(testRun, systemInfoEthernetNetwork.dns).shouldBeString();
				valueOf(testRun, systemInfoEthernetNetwork.subnetMask).shouldBeString();
			}
			finish(testRun);
		}

		function onErrorCallback(error) {
			Ti.API.info('An error occurred on EthernetNetwork property:' + error.message);
			valueOf(testRun, error).shouldBe('[object TizenWebAPIError]');
			finish(testRun);
		}

		valueOf(testRun, Tizen.SystemInfo.getPropertyValue).shouldBeFunction();
		Tizen.SystemInfo.getPropertyValue('EthernetNetwork', onSuccessCallback, onErrorCallback);
	}

	this.getSimProperty = function(testRun) {
	// Test for Tizen Device API: SystemInfoSIM
		function onSuccessCallback(systemInfoSIM) {
			Ti.API.debug('SIM info: ' + JSON.stringify(systemInfoSIM));

			valueOf(testRun, systemInfoSIM).shouldBe('[object TizenSystemInfoSystemInfoSIM]');

			if (systemInfoSIM){
				valueOf(testRun, systemInfoSIM.operatorName).shouldBeString();
				valueOf(testRun, systemInfoSIM.msisdn).shouldBeString();
				valueOf(testRun, systemInfoSIM.iccid).shouldBeString();
				valueOf(testRun, systemInfoSIM.msin).shouldBeString();
				valueOf(testRun, systemInfoSIM.spn).shouldBeString();
				valueOf(testRun, systemInfoSIM.mcc).shouldBeNumber();
				valueOf(testRun, systemInfoSIM.mnc).shouldBeNumber();
			}

			finish(testRun);
		}

		function onErrorCallback(error) {
			Ti.API.info('An error occurred on SIM property:' + error.message);
			valueOf(testRun, error).shouldBe('[object TizenWebAPIError]');
			finish(testRun);
		}

		valueOf(testRun, Tizen.SystemInfo.getPropertyValue).shouldBeFunction();
		Tizen.SystemInfo.getPropertyValue(Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_SIM, onSuccessCallback, onErrorCallback);
	}

	this.testListenersCpu = function(testRun) {
		checkCallbackMethod( {propertyName: Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_CPU, testRun: testRun, optionsParameter:{}} );
	}

	this.testListenersStorage = function(testRun) {
		checkCallbackMethod( {propertyName: Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_STORAGE, testRun: testRun, optionsParameter:{}} );
	}

	this.testListenersWifiNetwork = function(testRun) {
		checkCallbackMethod( {propertyName: Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_WIFI_NETWORK, testRun: testRun, optionsParameter:{} });
	}

	this.testListenersCellularNetwork = function(testRun) {
		checkCallbackMethod( {propertyName: Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_CELLULAR_NETWORK, testRun: testRun, optionsParameter:{} });
	}

	this.testListenersEthernetNetwork = function(testRun) {
		checkCallbackMethod( {propertyName: 'EthernetNetwork', testRun: testRun, optionsParameter:{} });
	}

	this.testListenersSIM = function(testRun) {
		checkCallbackMethod( {propertyName: Tizen.SystemInfo.SYSTEM_INFO_PROPERTY_ID_SIM, testRun: testRun, optionsParameter:{} });
	}

	// helper that allows to test addPropertyValueChangeListener, removePropertyValueChangeListener, SystemInfoOptions
	// will be completed in 2 sec in any case.
	function checkCallbackMethodFunction (data) {
		Ti.API.debug('Running listener check for: ' + (data?data.propertyName:'[Wrong parameter!]'));
		var id,
			testRun = data.testRun,
			waitTimeout;

		// removes current listener. Must be completed to accept valid test.
		function removeListener() {
			valueOf(testRun, id).shouldNotBeNull();
			Ti.API.debug('removing listener with ID: ' + id);
			if (id != null) {
				try{
					valueOf(testRun, Tizen.SystemInfo.removePropertyValueChangeListener).shouldBeFunction();
					Tizen.SystemInfo.removePropertyValueChangeListener(id);
				} catch(e) {
					reportError(testRun, JSON.stringify(e));
				}
			}
		}

		// If can accept test as on success callback as without it
		function onSuccessCallback(dataObject) {
			Ti.API.debug('Test completed by success callback with parameter: ' + JSON.stringify(dataObject|''));
			valueOf(testRun, dataObject).shouldBe('[object TizenSystemInfoSystemInfoProperty]');
			clearFakeTimeout();  // cancel fake timer call

			valueOf(testRun, dataObject).shouldNotBeNull();
			removeListener();
			finish(testRun);
		}

		// If called with not null - test failed!
		function onErrorCallback(error) {
			Ti.API.info('Test completed by error callback - ' + JSON.stringify(error));
			valueOf(testRun, error).shouldBe('[object TizenWebAPIError]');
			clearFakeTimeout(); // cancel fake timer call
			reportError(testRun, JSON.stringify(error));
		}

		//clears timeout if it was set before.
		function clearFakeTimeout() {
			if (waitTimeout) {
				// cancel fake call if any
				clearTimeout(waitTimeout);
			}
		}

		// we don't need to wait for real callbacks from device,
		// as generally we are testing that we can subscribe and unsubscribe
		waitTimeout=setTimeout(function() {
			Ti.API.debug('Test completed by timeout!');
			removeListener();
			finish(testRun);
		}, 2000);

		try {
			// According to documentation:
			// 'Tizen Web App Programming' => 'Programming Guide' => 'Device' => 'Obtain Details on Basic Supported Properties'
			// devices MAY not support all properties. Some properties vary from device to device
			valueOf(testRun, Tizen.SystemInfo.addPropertyValueChangeListener).shouldBeFunction();

			id = Tizen.SystemInfo.addPropertyValueChangeListener(data.propertyName, onSuccessCallback, onErrorCallback, data.optionsParameter);
			valueOf(testRun, id).shouldBeGreaterThanEqual(0);
			if (id < 0) {
				clearFakeTimeout();
				Ti.API.warn('Property ' + data.propertyName + ' did not accepted listener. This may depends on device.');
				finish(testRun);
			}
		} catch(e) {
			clearFakeTimeout();
			reportError(testRun, JSON.stringify(e));
		}
	}
}
<|endoftext|>


<commit_before>'use strict'
const debug = require('debug')('netcat:server')
const net = require('net')
const Stream = require('stream')

class Server {

  constructor (opts) {
    opts = opts || {}
    this._protocol = opts.protocol || 'tcp'
    this._address = opts.address || '0.0.0.0'
    this._port = opts.port || null
    this._keepalive = false
    this.passThrough = new Stream.PassThrough()
  }

  protocol (p) {
    this._protocol = p
    debug('Protocol is', this._protocol)
    return this /* chainable method */
  }

  address (a) {
    this._address = a
    return this /* chainable method */
  }

  addr (a) {
    /* address alias */
    return this.address(a)
  }

  port (p) {
    if (!Number.isInteger(p)) throw Error('Port should be a positive number!')
    this._port = p
    debug('Port set to', this._port)
    return this /* chainable method */
  }

  udp () {
    return this.protocol('udp') /* chainable method */
  }

  tcp () {
    return this.protocol('tcp') /* chainable method */
  }

  keepalive (bool) {
    this._keepalive = typeof bool !== 'undefined' ? bool : true
    debug('Keepalive connection.')
    return this /* chainable method */
  }

  k (bool) { /* keepalive alias */
    this.keepalive(bool)
    return this /* chainable method */
  }

  close (cb) {
    debug('Closing socket.')
    this.server.close(cb)
    return this
  }

  _createServer () {
    var self = this
    this.server = net.createServer(function (socket) {
      debug('New connection!')

      /* outcoming */
      if (self._serveStream){
        debug('Serving a stream to the current client.')
        self._serveStream.pipe(socket)
      }
      /* incoming */
      socket.pipe(self.passThrough, { end: !self._keepalive })

      //socket.on('data', function (data) {
      //  self.stdout.write(data)
      //})

      socket.on('end', function () {
        debug('Connection end.')
        if (!self._keepalive) self.close()
      })

      socket.on('timeout', function () {
        debug('Connection timed out')
      })

      socket.on('close', function (hadError) {
        debug('Connection closed', hadError ? 'because of a conn. error' : 'by client')
      })

    })
  }

  listen () {
    this._createServer()
    this.server.listen(this._port, this._address)
    debug('Server TCP listening on port', this._port, 'addr', this._address)
    return this /* chainable method */
  }

  pipe (outputStream) {
    debug('Pipe method called')
    this.passThrough.pipe(outputStream, { end: !this._keepalive })
    return this
  }

  serve (inputStream) {
    debug('Serving a stream to the clients...')
    this._serveStream = inputStream
    return this /* chainable method */
  }

  q () {
    // TODO

  }

}

module.exports = Server

if (!module.parent){
  const fs = require('fs')
  const nc = new Server()
  nc.port(2389).k().listen().pipe(fs.createWriteStream('output.txt'))
}
<commit_msg>verbose mode<commit_after>'use strict'
var debug = require('debug')('netcat:server')
const net = require('net')
const Stream = require('stream')

class Server {

  constructor (opts) {
    opts = opts || {}
    debug = opts.verbose ? function(){
      var args = Array.prototype.slice.call(arguments)
      process.stderr.write(args.join(' ') + '\n')
    } : debug
    this._protocol = opts.protocol || 'tcp'
    this._address = opts.address || '0.0.0.0'
    this._port = opts.port || null
    this._keepalive = false
    this.passThrough = new Stream.PassThrough()
  }

  protocol (p) {
    this._protocol = p
    debug('Protocol is', this._protocol)
    return this /* chainable method */
  }

  address (a) {
    this._address = a
    return this /* chainable method */
  }

  addr (a) {
    /* address alias */
    return this.address(a)
  }

  port (p) {
    if (!Number.isInteger(p)) throw Error('Port should be a positive number!')
    this._port = p
    debug('Port set to', this._port)
    return this /* chainable method */
  }

  udp () {
    return this.protocol('udp') /* chainable method */
  }

  tcp () {
    return this.protocol('tcp') /* chainable method */
  }

  keepalive (bool) {
    this._keepalive = typeof bool !== 'undefined' ? bool : true
    debug('Keepalive connection.')
    return this /* chainable method */
  }

  k (bool) { /* keepalive alias */
    this.keepalive(bool)
    return this /* chainable method */
  }

  close (cb) {
    debug('Closing socket.')
    this.server.close(cb)
    return this
  }

  _createServer () {
    var self = this
    this.server = net.createServer(function (socket) {
      debug('New connection!')

      /* outcoming */
      if (self._serveStream){
        debug('Serving a stream to the current client.')
        self._serveStream.pipe(socket)
      }
      /* incoming */
      socket.pipe(self.passThrough, { end: !self._keepalive })

      //socket.on('data', function (data) {
      //  self.stdout.write(data)
      //})

      socket.on('end', function () {
        debug('Connection end.')
        if (!self._keepalive) self.close()
      })

      socket.on('timeout', function () {
        debug('Connection timed out')
      })

      socket.on('close', function (hadError) {
        debug('Connection closed', hadError ? 'because of a conn. error' : 'by client')
      })

    })
  }

  listen () {
    this._createServer()
    this.server.listen(this._port, this._address)
    debug('Server TCP listening on port', this._port, 'addr', this._address)
    return this /* chainable method */
  }

  pipe (outputStream) {
    debug('Pipe method called')
    this.passThrough.pipe(outputStream, { end: !this._keepalive })
    return this
  }

  serve (inputStream) {
    debug('Serving a stream to the clients...')
    this._serveStream = inputStream
    return this /* chainable method */
  }

  q () {
    // TODO

  }

}

module.exports = Server

if (!module.parent){
  const fs = require('fs')
  const nc = new Server()
  nc.port(2389).k().listen().pipe(fs.createWriteStream('output.txt'))
}
<|endoftext|>


<commit_before>/**
 * Created by sghaida on 5/13/2017.
 */

var express         = require('express'),
    router          = express.Router(),
    passport        = require('passport'),
    auth            = require('connect-ensure-login'),
    Announcement    = require('../models/announcement'),
    Department      = require('../models/department'),
    Tag             = require('../models/tag'),
    async           = require('async');

/* View all announcements  */
router.get('/',auth.ensureLoggedIn('/login'), function (req,res, next) {
    Announcement.find().populate('department tags').exec(function (err, announcements) {
        if(err){
            console.log(err);
        }else {
            res.render('announcements/view', {announcements: announcements});
        }
    });

});

/* Submits new announcement */
router.post('/', auth.ensureLoggedIn('/login'), function (req, res, next) {
    Announcement.create(req.body.announcement, function (err, announcement) {
        if(err){
            console.log(err);
        } else {
            announcement.author.id = req.user._id;
            announcement.author.name = req.user.name;
            announcement.tags =req.body.announcement.tags

            announcement.department = req.body.announcement.department
            announcement.save();

            if(req.body['new-announcement'] === 'on') {
                res.redirect('/announcements/new')
            } else {
                res.redirect('/announcements');
            }

        }
    });
})

/* shows the new announcement form */
router.get('/new', auth.ensureLoggedIn('/login'), function (req,res, next) {
   async.parallel([
           function (cb) {
               Tag.find({},cb);
           },
           function (cb) {
               Department.find({},cb);
           }
       ],function (err, result) {
            if(err) {
                console.log('fuckin error' + err)
            }else {
                console.log(result);
                console.log('fuck');
                res.render('announcements/new', {tags: result[0], departments: result[1]});
            }
   });

});

module.exports = router;

<commit_msg>add get by department and get by tag functionality<commit_after>/**
 * Created by sghaida on 5/13/2017.
 */

var express         = require('express'),
    router          = express.Router(),
    passport        = require('passport'),
    auth            = require('connect-ensure-login'),
    Announcement    = require('../models/announcement'),
    Department      = require('../models/department'),
    Tag             = require('../models/tag'),
    async           = require('async');

/* View all announcements  */
router.get('/',auth.ensureLoggedIn('/login'), function (req,res, next) {
    Announcement.find().populate('department tags').exec(function (err, announcements) {
        if(err){
            console.log(err);
        }else {
            res.render('announcements/view', {announcements: announcements});
        }
    });

});

/* Submits new announcement */
router.post('/', auth.ensureLoggedIn('/login'), function (req, res, next) {
    Announcement.create(req.body.announcement, function (err, announcement) {
        if(err){
            console.log(err);
        } else {
            announcement.author.id = req.user._id;
            announcement.author.name = req.user.name;
            announcement.tags =req.body.announcement.tags

            announcement.department = req.body.announcement.department
            announcement.save();

            if(req.body['new-announcement'] === 'on') {
                res.redirect('/announcements/new')
            } else {
                res.redirect('/announcements');
            }

        }
    });
})

/* shows the new announcement form */
router.get('/new', auth.ensureLoggedIn('/login'), function (req,res, next) {
   async.parallel([
           function (cb) {
               Tag.find({},cb);
           },
           function (cb) {
               Department.find({},cb);
           }
       ],function (err, result) {
            if(err) {
                console.log('fuckin error' + err)
            }else {
                console.log(result);
                console.log('fuck');
                res.render('announcements/new', {tags: result[0], departments: result[1]});
            }
   });

});

/* get by tag refrence*/
router.get('/tag/:id', auth.ensureLoggedIn('/login'), function (req, res, next) {
   Announcement.find({'tags': Object(req.params.id)}).populate('department tags').exec(function (err, announcements) {
       if(err){
           console.log(err);
       }else {
           res.render('announcements/view', {announcements: announcements});
       }
   });
});

/* get by department refrence*/
router.get('/department/:id', auth.ensureLoggedIn('/login'), function (req, res, next) {
    Announcement.find({'department': Object(req.params.id)}).populate('department tags').exec(function (err, announcements) {
        if(err){
            console.log(err);
        }else {
            res.render('announcements/view', {announcements: announcements});
        }
    });
});

module.exports = router;

<|endoftext|>


<commit_before>console.log('outside');

openerp.kinesis_athletics_x = function(instance) {

var _t = instance.web._t,
    _lt = instance.web._lt;
var QWeb = instance.web.qweb;

var color_map = {'alert': '#ff3333', 'superior': '#33ccff', 'ideal': '#66ff66'}

instance.web_kanban.KinesisMetricWidget = instance.web_kanban.AbstractField.extend({
    className: "kinesis_metric",

    start: function() {
        var self = this;
        var parent = this.getParent();

        var value = this.field.raw_value;
        var test_name = this.getParent().record['test_id'].value;

        var rating_below_minimum_color = color_map['alert'];
        var rating_in_between_color = color_map['ideal'];
        var rating_over_maximum_color = color_map['superior'];

        if (this.getParent().record['rating_below_minimum'] != null) {
            rating_below_minimum_color = color_map[this.getParent().record['rating_below_minimum'].raw_value];
        }
        if (this.getParent().record['rating_over_maximum'] != null) {
            rating_over_maximum_color = color_map[this.getParent().record['rating_over_maximum'].raw_value];
        }

        var tickPositions = [];

        // Set plotband information.
        var plotband_ext_min = 0;
        var plotband_val_min = null;
        var plotband_val_max = null;
        var plotband_ext_max = 200;

        if (this.getParent().record['plotband_ext_min'] != null) {
            plotband_ext_min = this.getParent().record['plotband_ext_min'].raw_value;
        }
        tickPositions.push(plotband_ext_min);
        if (this.getParent().record['plotband_val_min'] != null) {
            plotband_val_min = this.getParent().record['plotband_val_min'].raw_value;
            tickPositions.push(plotband_val_min);
        }
        if (this.getParent().record['plotband_val_max'] != null) {
            plotband_val_max = this.getParent().record['plotband_val_max'].raw_value;
            tickPositions.push(plotband_val_max);
        }
        if (this.getParent().record['plotband_ext_max'] != null) {
            plotband_ext_max = this.getParent().record['plotband_ext_max'].raw_value;
        }
        tickPositions.push(plotband_ext_max);

        var plotBands = []

        if (plotband_ext_min != null && plotband_val_min != null) {
            plotBands.push({
                from: plotband_ext_min,
                to: plotband_val_min,
                color: rating_below_minimum_color,
                innerRadius: '100%',
                outerRadius: '110%',
            });
        }

        if (plotband_val_min != null && plotband_val_max != null) {
            plotBands.push({
                from: plotband_val_min,
                to: plotband_val_max,
                color: rating_in_between_color,
                innerRadius: '100%',
                outerRadius: '110%'
            });
        }

        if (plotband_val_max != null && plotband_ext_max != null) {
            plotBands.push({
                from: plotband_val_max,
                to: plotband_ext_max,
                color: rating_over_maximum_color,
                innerRadius: '100%',
                outerRadius: '110%'
            });
        }

        // Create the series with the value of the test.
        var series = [{
            data: [value],
            yAxis: 0
        }]

        // If the age_avg field is not null add this value to the series.
        if (this.getParent().record['age_avg'] != null) {
            series.push({
                data: [this.getParent().record['age_avg'].raw_value],
                backgroundColor: '#ffffff',
                dial: {
                    radius: '105%',
                    backgroundColor: '#999'
                },
                yAxis: 0
            });
        }

        this.$el.highcharts({
            chart: {
                renderTo: 'container',
                type: 'gauge',
                height: 130,
                width: 390
            },

            title: {
                text: test_name
            },

            pane: [{
                startAngle: -35,
                endAngle: 35,
                background: null,
                center: ['50%', '320%'],
                size: 380
            }],

            yAxis: [{
                min: plotband_ext_min,
                max: plotband_ext_max,
                lineColor: '#666',
                tickColor: '#666',
                minorTickColor: '#666',
                minorTickPosition: 'outside',
                tickPosition: 'outside',
                lineWidth: 1,
                tickLength: 19,
                tickWidth: 1,
                tickPositions: tickPositions,
                endOnTick: false,

                labels: {
                    rotation: 'auto',
                    distance: 25,
                    style: {
                        color: '#000',
                    },
                },
                plotBands: plotBands,
                pane: 0,
            }],

            plotOptions: {
                gauge: {
                    dataLabels: {
                        enabled: false
                    },
                    dial: {
                        radius: '105%'
                    }
                }
            },

            series: series
        });
    }
});

instance.web_kanban.KinesisStateWidget = instance.web_kanban.AbstractField.extend({
    className: "kinesis_state",
    template: 'KinesisState',
});

instance.web_kanban.fields_registry.add("kinesis_metric", "instance.web_kanban.KinesisMetricWidget");
instance.web_kanban.fields_registry.add("kinesis_state", "instance.web_kanban.KinesisStateWidget");

};
<commit_msg>Add additional controls to gauge widget not to display badly visualized graphs if errors with intervals ext_min, val_min, val_max, ext_max<commit_after>console.log('outside');

openerp.kinesis_athletics_x = function(instance) {

var _t = instance.web._t,
    _lt = instance.web._lt;
var QWeb = instance.web.qweb;

var color_map = {'alert': '#ff3333', 'superior': '#33ccff', 'ideal': '#66ff66'}

instance.web_kanban.KinesisMetricWidget = instance.web_kanban.AbstractField.extend({
    className: "kinesis_metric",

    start: function() {
        var self = this;
        var parent = this.getParent();

        var value = this.field.raw_value;
        var test_name = this.getParent().record['test_id'].value;

        var rating_below_minimum_color = color_map['alert'];
        var rating_in_between_color = color_map['ideal'];
        var rating_over_maximum_color = color_map['superior'];

        if (this.getParent().record['rating_below_minimum'] != null) {
            rating_below_minimum_color = color_map[this.getParent().record['rating_below_minimum'].raw_value];
        }
        if (this.getParent().record['rating_over_maximum'] != null) {
            rating_over_maximum_color = color_map[this.getParent().record['rating_over_maximum'].raw_value];
        }

        var tickPositions = [];

        // Set plotband information.
        var plotband_ext_min = 0;
        var plotband_val_min = null;
        var plotband_val_max = null;
        var plotband_ext_max = 200;

        if (this.getParent().record['plotband_ext_min'] != null) {
            plotband_ext_min = this.getParent().record['plotband_ext_min'].raw_value;
        }
        tickPositions.push(plotband_ext_min);

        if (this.getParent().record['plotband_val_min'] != null) {
            plotband_val_min = this.getParent().record['plotband_val_min'].raw_value;
            if (plotband_val_min < plotband_ext_min) {
                plotband_val_min = null;
            } else {
                tickPositions.push(plotband_val_min);
            }
        }

        if (this.getParent().record['plotband_ext_max'] != null) {
            plotband_ext_max = this.getParent().record['plotband_ext_max'].raw_value;
        }

        if (this.getParent().record['plotband_val_max'] != null) {
            plotband_val_max = this.getParent().record['plotband_val_max'].raw_value;
            if (plotband_val_max > plotband_ext_max) {
                plotband_val_max = null;
            } else {
                tickPositions.push(plotband_val_max);
            }
        }

        tickPositions.push(plotband_ext_max);

        var plotBands = []

        if (plotband_ext_min != null && plotband_val_min != null) {
            plotBands.push({
                from: plotband_ext_min,
                to: plotband_val_min,
                color: rating_below_minimum_color,
                innerRadius: '100%',
                outerRadius: '110%',
            });
        }

        if (plotband_val_min != null && plotband_val_max != null) {
            plotBands.push({
                from: plotband_val_min,
                to: plotband_val_max,
                color: rating_in_between_color,
                innerRadius: '100%',
                outerRadius: '110%'
            });
        }

        if (plotband_val_max != null && plotband_ext_max != null) {
            plotBands.push({
                from: plotband_val_max,
                to: plotband_ext_max,
                color: rating_over_maximum_color,
                innerRadius: '100%',
                outerRadius: '110%'
            });
        }

        // Create the series with the value of the test.
        var series = [{
            data: [value],
            yAxis: 0
        }]

        // If the age_avg field is not null add this value to the series.
        if (this.getParent().record['age_avg'] != null) {
            series.push({
                data: [this.getParent().record['age_avg'].raw_value],
                backgroundColor: '#ffffff',
                dial: {
                    radius: '105%',
                    backgroundColor: '#999'
                },
                yAxis: 0
            });
        }

        this.$el.highcharts({
            chart: {
                renderTo: 'container',
                type: 'gauge',
                height: 130,
                width: 390
            },

            title: {
                text: test_name
            },

            pane: [{
                startAngle: -35,
                endAngle: 35,
                background: null,
                center: ['50%', '320%'],
                size: 380
            }],

            yAxis: [{
                min: plotband_ext_min,
                max: plotband_ext_max,
                lineColor: '#666',
                tickColor: '#666',
                minorTickColor: '#666',
                minorTickPosition: 'outside',
                tickPosition: 'outside',
                lineWidth: 1,
                tickLength: 19,
                tickWidth: 1,
                tickPositions: tickPositions,
                endOnTick: false,

                labels: {
                    rotation: 'auto',
                    distance: 25,
                    style: {
                        color: '#000',
                    },
                },
                plotBands: plotBands,
                pane: 0,
            }],

            plotOptions: {
                gauge: {
                    dataLabels: {
                        enabled: false
                    },
                    dial: {
                        radius: '105%'
                    }
                }
            },

            series: series
        });
    }
});

instance.web_kanban.KinesisStateWidget = instance.web_kanban.AbstractField.extend({
    className: "kinesis_state",
    template: 'KinesisState',
});

instance.web_kanban.fields_registry.add("kinesis_metric", "instance.web_kanban.KinesisMetricWidget");
instance.web_kanban.fields_registry.add("kinesis_state", "instance.web_kanban.KinesisStateWidget");

};
<|endoftext|>


<commit_before>const Discord = require('discord.js');
module.exports = (message) => {
    let me = message.embeds.shift();
    const embed = new Discord.RichEmbed();
    embed.setAuthor(message.author.toString(),message.author.avatarURL)
    embed.setTitle(message.channel.toString() +" in "+message.guild.name)
    if(!message.content =="")
        embed.setDescription(message.content);
    else
        embed.setDescription("**"+me.author.name+" : "+me.title+"**\n	"+(me.description||"")+((me.footer)?("\n*At "+me.footer.text+"*"):""));
    embed.setFooter(message.createdAt)
    //embed.setTitle("Quote");
    return embed;
}
<commit_msg>fix the quote<commit_after>const Discord = require('discord.js');
module.exports = (message) => {
    let me = message.embeds.shift();
    const embed = new Discord.RichEmbed();
    embed.setAuthor(message.author.username,message.author.avatarURL)
    embed.setTitle(message.channel.name +" in "+message.guild.name)
    if(!message.content =="")
        embed.setDescription(message.content);
    else
        embed.setDescription("**"+me.author.name+" : "+me.title+"**\n	"+(me.description||"")+((me.footer)?("\n*At "+me.footer.text+"*"):""));
    embed.setFooter(message.createdAt)
    //embed.setTitle("Quote");
    return embed;
}
<|endoftext|>


<commit_before>const http = require("http");
const https = require("https");
const http2 = require("http2");
const domain = require("domain");
const url = require("url");
const fs = require("fs");
const querystring = require("querystring");

const ResponseWrapper = require("./ResponseWrapper.js");
const ResponseCodeMessage = require("./ResponseCodeMessage.js");
const Router = require("./Router.js");
const NullCache = require("./Cache/NullCache.js");
const Helper = require("./Helper.js");
const RequestHandler = require("./RequestHandler.js");

const config = require("../Config.js");
const log = require("./LogHandler.js");

class Server {
	constructor() {
		this.cache = new NullCache();
		this.router = new Router(null);
		this.port = config.Server.Port;
		this.onErrRes = new ResponseWrapper(null);
		this.httpServerToUse = "http";
		this.requestHandlersMappings = [];
		this.requestHandler = new RequestHandler(this);

		/** @type {https.ServerOptions} */
		this.httpsOptions = {
			key: config.Https.Key,
			cert: config.Https.Cert
		};
	}

	/**
	 * @public
	 */
	start() {
		if (config.EnableHttp2 && config.Https.Enabled) {
			log.info("Start server with https AND h2 enabled");
			this.httpServerToUse = "http2";
		} else if (config.Https.Enabled) {
			log.info("Start server with https enabled");
			this.httpServerToUse = "https";
		} else {
			log.info("Start server with http");
			this.httpServerToUse = "http";
		}

		if (config.DevMode) {
			log.info("Starting Server on port: " + this.port);
			let _this = this;

			switch (this.httpServerToUse) {
				case "http":
					http.createServer((request, response) => {
						_this._onRequest(_this, request, response);
					}).listen(this.port);
					break;
				case "https":
					https.createServer(this.httpsOptions, (request, response) => {
						_this._onRequest(_this, request, response);
					}).listen(this.port);
					break;
				case "http2":
					http2.createServer(this.httpsOptions, (request, response) => {
						_this._onRequest(_this, request, response);
					}).listen(this.port);
					break;
			}
		} else {
			const currentDomain = domain.create();
			let _this = this;
			currentDomain.on("error", (error) => {
				_this._onError(_this, error);
			});
			currentDomain.run(() => {
				_this._onDomainRun(_this);
			});
		}

		log.info("Init done, waiting for clients...");
	}

	/**
	 * @public
	 * @param {Array} handlerList
	 */
	setRequestHandlers(handlerList) {
		this.requestHandlersMappings = handlerList;
		this.router = new Router(this.requestHandlersMappings);
	}

	/**
	 * @public
	 * @param {NullCache} cacheModule
	 */
	setCacheModule(cacheModule) {
		this.cache = cacheModule;
	}

	/**
	 * @private
	 * @param {Server} server
	 * @param {http.IncomingMessage} request
	 * @param {http.ServerResponse} response
	 */
	_onRequest(server, request, response) {
		log.debug(`request: HTTP ${request.httpVersion} ${request.method} ${request.url}`);
		const res = new ResponseWrapper(response);

		if (!config.DevMode) {
			this.onErrRes = res;
		}

		server._processRequest(server, request, res);
	}

	_onDomainRun() {
		log.info(`Starting Server on port: ${this.port}`);
		let _this = this;

		switch (this.httpServerToUse) {
			case "http":
				http.createServer((request, response) => {
					_this._onRequest(_this, request, response);
				}).listen(this.port);
				break;
			case "https":
				https.createServer(this.httpsOptions, (request, response) => {
					_this._onRequest(_this, request, response);
				}).listen(this.port);
				break;
			case "http2":
				http2.createServer(this.httpsOptions, (request, response) => {
					_this._onRequest(_this, request, response);
				}).listen(this.port);
				break;
		}
	}

	/**
	 * @private
	 * @param {Server} server
	 * @param {Error} error
	 */
	_onError(server, error) {
		log.error("Internal Server Error", error);

		if (!config.DevMode) {
			server.onErrRes.setResponseCode(500);
			server.onErrRes.setContent("");
			server.onErrRes = new ResponseCodeMessage(server.onErrRes).prepareAndGetResponse(true);
			server.onErrRes.send();
		}

		process.exit(1);
	}

	// TODO give the return value more meaning / sense or remove it
	/**
	 * @private
	 * @param {Server} server
	 * @param {http.ClientRequest} request
	 * @param {ResponseWrapper} response
	 * @returns {boolean} whether the requested content could be send or not
	 */
	_processRequest(server, request, response) {
		const queryPath = url.parse(request.url).path;
		const queryString = url.parse(request.url).query;

		if (!server.router.routeExists(queryPath)) {
			log.info(`404: ${queryPath}`);
			response.setResponseCode(404);
			response = new ResponseCodeMessage(response).prepareAndGetResponse(true);
			response.send();
			return false;
		}

		if (server.router.getRoute(queryPath).handler === server.requestHandler.get("Static") && (request.headers["cache-control"] !== "no-cache")) {
			/** @type {string} */
			const filePath = Helper.replaceAll("/", Helper.GetFsDelimiter(), config.staticContentPath);

			/** @type {Date} */
			let lastModified;

			if (queryPath === "/favicon.ico") {
				lastModified = new Date(fs.statSync(`${filePath}${Helper.GetFsDelimiter()}favicon.ico`).mtime).toUTCString();
			} else if (queryPath === "/worker-html.js") {
				lastModified = new Date(fs.statSync(`${filePath}${Helper.GetFsDelimiter()}worker-html.js`).mtime).toUTCString();
			} else {
				/** @type {string} */
				const file = filePath + Helper.GetFsDelimiter() + querystring.parse(queryString).f;

				try {
					fs.accessSync(file, fs.constants.F_OK);
					lastModified = new Date(fs.statSync(file).mtime).toUTCString(); // TODO fix this
				} catch (error) {
					response.setResponseCode(404);
					response = new ResponseCodeMessage(response).prepareAndGetResponse(true);
					response.send();
					return false;
				}
			}

			if (lastModified === request.headers["if-modified-since"]) {
				response.setResponseCode(304);
				response.setLastModified(lastModified);
				response.send();
			}
		}

		const cacheLastModified = server.cache.getLastModified(request);
		const cacheHasRequest = server.cache.has(request);

		if (cacheHasRequest && request.headers["if-modified-since"] === cacheLastModified) {
			log.debug("304 not modified since: " + cacheLastModified);
			response.setResponseCode(304);
			response.setLastModified(cacheLastModified);
			response.send();
		} else {
			const deliverCache = !(config.HandleClientCacheControl && request.headers["cache-control"] === "no-cache");
			const writeCache = server.router.routeGetCacheEnabled(queryPath);

			if (deliverCache && cacheHasRequest) {
				server.cache.send(request, response);
				return false;
			}

			let data = server.router.route(queryPath, request);

			if (request.method === "POST") {
				let body = "";

				// TODO test the behavior of "this" at the anonymus delegate level!
				request.on("data", (postData) => {
					// reading http POST body
					if (body.length + postData.length < config.MaxHttpPOSTSize) {
						body += postData;
					} else {
						// Request entity too large
						response.setResponseCode(413);
						response = new ResponseCodeMessage(response).prepareAndGetResponse(true);
						response.send();
						return false;
					}

					return true;
				});

				request.on("end", () => {
					// after reading the http POST body, call the callback function "data()" returned from the request handler
					server._sendData(data(server.router.getRoute(queryPath).handler, body, request), request, response, writeCache);
				});
			} else if (request.method === "GET") {
				if (!server._sendData(data, request, response, writeCache)) {
					return false;
				}
			} else {
				// unknown http method
				response.setResponseCode(501);
				response = new ResponseCodeMessage(response).prepareAndGetResponse(true);
				response.send();
				return false;
			}
		}

		return true;
	}

	/**
	 * @private
	 * "data.type" MUST be set to a valid http status code (default: 500 "Internal Server Error") returns false if response has been send
	 * @param {Object} data
	 * @param {http.ClientRequest} request
	 * @param {ResponseWrapper} response
	 * @param {boolean} writeCache
	 * @returns {boolean} whether the requested content could be send or not
	 */
	_sendData(data, request, response, writeCache) {
		if (!data || !data.type) {
			response = new ResponseCodeMessage(response).prepareAndGetResponse(true);
			response.send();
			return false;
		}

		if (data.mimetype) {
			response.setContentType(data.mimetype);
		}

		if (data.code) {
			response.setResponseCode(data.code);
		}

		if (data.type === "file" && data.content) {
			response.setResponseCode(data.code || 200);
			response.setLastModified(new Date(fs.statSync(data.content).mtime).toUTCString());
			response.contentLength = fs.statSync(data.content).size;
			response.sendFileStream(fs.createReadStream(data.content));
			return false;
		}

		if (data.content) {
			response.setContent(data.content);
		}

		response = new ResponseCodeMessage(response).prepareAndGetResponse(true);

		if (writeCache && (data.code > 99 && data.code < 300)) {
			this.cache.add(request, data.content, data.mimetype, data.code);
			response.setLastModified(this.cache.getLastModified(request));
		}

		if (config.EnableHttp2 && config.Https.Enabled && data.push) {
			// TODO test the behavior of "this" at the anonymus delegate level!
			data.push.forEach((element) => {
				response.addHttp2PushEntity(element.path, element.data, element.httpCode, element.header);
			}, this);
		}

		response.send();
		return true;
	}
}

module.exports = Server;
<commit_msg>handle "if-modified-since" for static content<commit_after>const http = require("http");
const https = require("https");
const http2 = require("http2");
const domain = require("domain");
const url = require("url");
const fs = require("fs-extra");
const querystring = require("querystring");

const ResponseWrapper = require("./ResponseWrapper.js");
const ResponseCodeMessage = require("./ResponseCodeMessage.js");
const Router = require("./Router.js");
const NullCache = require("./Cache/NullCache.js");
const Helper = require("./Helper.js");
const RequestHandler = require("./RequestHandler.js");

const config = require("../Config.js");
const log = require("./LogHandler.js");

class Server {
	constructor() {
		this.cache = new NullCache();
		this.router = new Router(null);
		this.port = config.Server.Port;
		this.onErrRes = new ResponseWrapper(null);
		this.httpServerToUse = "http";
		this.requestHandlersMappings = [];
		this.requestHandler = new RequestHandler(this);

		/** @type {https.ServerOptions} */
		this.httpsOptions = {
			key: config.Https.Key,
			cert: config.Https.Cert
		};
	}

	/**
	 * @public
	 */
	start() {
		if (config.EnableHttp2 && config.Https.Enabled) {
			log.info("Start server with https AND h2 enabled");
			this.httpServerToUse = "http2";
		} else if (config.Https.Enabled) {
			log.info("Start server with https enabled");
			this.httpServerToUse = "https";
		} else {
			log.info("Start server with http");
			this.httpServerToUse = "http";
		}

		if (config.DevMode) {
			log.info("Starting Server on port: " + this.port);
			let _this = this;

			switch (this.httpServerToUse) {
				case "http":
					http.createServer((request, response) => {
						_this._onRequest(_this, request, response);
					}).listen(this.port);
					break;
				case "https":
					https.createServer(this.httpsOptions, (request, response) => {
						_this._onRequest(_this, request, response);
					}).listen(this.port);
					break;
				case "http2":
					http2.createServer(this.httpsOptions, (request, response) => {
						_this._onRequest(_this, request, response);
					}).listen(this.port);
					break;
			}
		} else {
			const currentDomain = domain.create();
			let _this = this;
			currentDomain.on("error", (error) => {
				_this._onError(_this, error);
			});
			currentDomain.run(() => {
				_this._onDomainRun(_this);
			});
		}

		log.info("Init done, waiting for clients...");
	}

	/**
	 * @public
	 * @param {Array} handlerList
	 */
	setRequestHandlers(handlerList) {
		this.requestHandlersMappings = handlerList;
		this.router = new Router(this.requestHandlersMappings);
	}

	/**
	 * @public
	 * @param {NullCache} cacheModule
	 */
	setCacheModule(cacheModule) {
		this.cache = cacheModule;
	}

	/**
	 * @private
	 * @param {Server} server
	 * @param {http.IncomingMessage} request
	 * @param {http.ServerResponse} response
	 */
	_onRequest(server, request, response) {
		log.debug(`request: HTTP ${request.httpVersion} ${request.method} ${request.url}`);
		const res = new ResponseWrapper(response);

		if (!config.DevMode) {
			this.onErrRes = res;
		}

		server._processRequest(server, request, res);
	}

	_onDomainRun() {
		log.info(`Starting Server on port: ${this.port}`);
		let _this = this;

		switch (this.httpServerToUse) {
			case "http":
				http.createServer((request, response) => {
					_this._onRequest(_this, request, response);
				}).listen(this.port);
				break;
			case "https":
				https.createServer(this.httpsOptions, (request, response) => {
					_this._onRequest(_this, request, response);
				}).listen(this.port);
				break;
			case "http2":
				http2.createServer(this.httpsOptions, (request, response) => {
					_this._onRequest(_this, request, response);
				}).listen(this.port);
				break;
		}
	}

	/**
	 * @private
	 * @param {Server} server
	 * @param {Error} error
	 */
	_onError(server, error) {
		log.error("Internal Server Error", error);

		if (!config.DevMode) {
			server.onErrRes.setResponseCode(500);
			server.onErrRes.setContent("");
			server.onErrRes = new ResponseCodeMessage(server.onErrRes).prepareAndGetResponse(true);
			server.onErrRes.send();
		}

		process.exit(1);
	}

	// TODO give the return value more meaning / sense or remove it
	/**
	 * @private
	 * @param {Server} server
	 * @param {http.ClientRequest} request
	 * @param {ResponseWrapper} response
	 * @returns {boolean} whether the requested content could be send or not
	 */
	_processRequest(server, request, response) {
		const queryPath = url.parse(request.url).path;
		const queryString = url.parse(request.url).query;

		if (!server.router.routeExists(queryPath)) {
			log.info(`404: ${queryPath}`);
			response.setResponseCode(404);
			response = new ResponseCodeMessage(response).prepareAndGetResponse(true);
			response.send();
			return false;
		}

		if (server.router.getRoute(queryPath).handler === server.requestHandler.get("Static") && (request.headers["cache-control"] !== "no-cache")) {
			/** @type {string} */
			const filePath = Helper.replaceAll("/", Helper.GetFsDelimiter(), config.staticContentPath);

			/** @type {Date} */
			let lastModified;

			if (queryPath === "/favicon.ico") {
				lastModified = new Date(fs.statSync(`${filePath}${Helper.GetFsDelimiter()}favicon.ico`).mtime).toUTCString();
			} else if (queryPath === "/worker-html.js") {
				lastModified = new Date(fs.statSync(`${filePath}${Helper.GetFsDelimiter()}worker-html.js`).mtime).toUTCString();
			} else {
				/** @type {string} */
				const file = filePath + Helper.GetFsDelimiter() + querystring.parse(queryString).f;

				try {
					fs.accessSync(file, fs.constants.F_OK);
					lastModified = new Date(fs.statSync(file).mtime).toUTCString(); // TODO fix this
				} catch (error) {
					response.setResponseCode(404);
					response = new ResponseCodeMessage(response).prepareAndGetResponse(true);
					response.send();
					return false;
				}
			}

			if (lastModified === request.headers["if-modified-since"]) {
				response.setResponseCode(304);
				response.setLastModified(lastModified);
				response.send();
			}
		}

		const cacheLastModified = server.cache.getLastModified(request);
		const cacheHasRequest = server.cache.has(request);

		if (cacheHasRequest && request.headers["if-modified-since"] === cacheLastModified) {
			log.debug("304 not modified since: " + cacheLastModified);
			response.setResponseCode(304);
			response.setLastModified(cacheLastModified);
			response.send();
		} else {
			const deliverCache = !(config.HandleClientCacheControl && request.headers["cache-control"] === "no-cache");
			const writeCache = server.router.routeGetCacheEnabled(queryPath);

			if (deliverCache && cacheHasRequest) {
				server.cache.send(request, response);
				return false;
			}

			let data = server.router.route(queryPath, request);

			if (request.method === "POST") {
				let body = "";

				// TODO test the behavior of "this" at the anonymus delegate level!
				request.on("data", (postData) => {
					// reading http POST body
					if (body.length + postData.length < config.MaxHttpPOSTSize) {
						body += postData;
					} else {
						// Request entity too large
						response.setResponseCode(413);
						response = new ResponseCodeMessage(response).prepareAndGetResponse(true);
						response.send();
						return false;
					}

					return true;
				});

				request.on("end", () => {
					// after reading the http POST body, call the callback function "data()" returned from the request handler
					server._sendData(data(server.router.getRoute(queryPath).handler, body, request), request, response, writeCache);
				});
			} else if (request.method === "GET") {
				if (!server._sendData(data, request, response, writeCache)) {
					return false;
				}
			} else {
				// unknown http method
				response.setResponseCode(501);
				response = new ResponseCodeMessage(response).prepareAndGetResponse(true);
				response.send();
				return false;
			}
		}

		return true;
	}

	/**
	 * @private
	 * "data.type" MUST be set to a valid http status code (default: 500 "Internal Server Error") returns false if response has been send
	 * @param {Object} data
	 * @param {http.ClientRequest} request
	 * @param {ResponseWrapper} response
	 * @param {boolean} writeCache
	 * @returns {boolean} whether the requested content could be send or not
	 */
	_sendData(data, request, response, writeCache) {
		if (!data || !data.type) {
			response = new ResponseCodeMessage(response).prepareAndGetResponse(true);
			response.send();
			return false;
		}

		if (data.mimetype) {
			response.setContentType(data.mimetype);
		}

		if (data.code) {
			response.setResponseCode(data.code);
		}

		if (data.type === "file" && data.content) {
			let lastModified = new Date(fs.statSync(data.content).mtime).toUTCString();
			response.setLastModified(lastModified);
			response.contentLength = fs.statSync(data.content).size;

			if (request.headers["if-modified-since"] === lastModified) {
				response.setResponseCode(304);
				response.send();
				return true;
			} else {
				response.setResponseCode(data.code || 200);
			}

			response.sendFileStream(fs.createReadStream(data.content));
			return false;
		}

		if (data.content) {
			response.setContent(data.content);
		}

		response = new ResponseCodeMessage(response).prepareAndGetResponse(true);

		if (writeCache && (data.code > 99 && data.code < 300)) {
			this.cache.add(request, data.content, data.mimetype, data.code);
			response.setLastModified(this.cache.getLastModified(request));
		}

		if (config.EnableHttp2 && config.Https.Enabled && data.push) {
			// TODO test the behavior of "this" at the anonymus delegate level!
			data.push.forEach((element) => {
				response.addHttp2PushEntity(element.path, element.data, element.httpCode, element.header);
			}, this);
		}

		response.send();
		return true;
	}
}

module.exports = Server;
<|endoftext|>


<commit_before>/*
 * 不枝雀
 * 2017-3-18 16:16:20
 */
//main
var body = document.body;
var onbacks = [];
var target_hash, exit_ing;
var window_history = window.history;
var window_history_length = window_history.length;
var load_count = "__zimoli_load_times";
var loadTime = +sessionStorage.getItem(load_count) || 0;
if (!loadTime) {
    location.replace("#reload");
}
loadTime++;
sessionStorage.setItem(load_count, loadTime);

if (/MSIE\s*[2-7]/.test(navigator.userAgent)) {
    window.onhistorychange = function (url) {
        if (exit_ing) return exit_ing = false, window_history.go(-1);
        if (exit_ing === void 0 ? onback && onback() === true : exit_ing = void 0) { }
    };
    onselectstart(body, function (e) {
        return e.preventDefault();
    });
    var frame = createElement("iframe");
    css(frame, "display:none");
    appendChild(body, frame);
    var doc = frame.contentWindow.document;
    var backman = function (isloaded) {
        doc.open();
        doc.write(isloaded !== false ? "" : "<script>result=parent.onhistorychange();onload=function(){history.forward()}</script>");
        doc.close();
    };
    backman(false);
    backman();
} else {
    onhashchange(window, function (event) {
        if (/#$/.test(event.newURL || event.actionURL || location.href)) return;
        if (exit_ing) return exit_ing = false, window_history.go(-1);
        event.preventDefault();
        if (exit_ing === void 0 ? onback() === true : exit_ing = void 0) { }
    });
}
// body
css(body, {
    width: "100%",
    height: "100%",
    border: "none",
    position: "absolute",
    margin: "0",
    padding: "0",
    overflow: "hidden",
    backgroundColor: "#f2f4f9"
});
var location_pathname = location.pathname;
var _zimoli_params_key = `_zimoli_parameters:${location_pathname}#`;
var _zimoli_state_prefix = `_zimoli_page_state:${location_pathname}#`;

function go(url, args, history_name) {
    if (isNumber(url)) {
        if (!history_name)
            history_name = current_history;
        if (isString(history_name)) {
            var _history = history[history_name] || [];
            url = _history[url < 1 ? _history.length + url - 1 : url];
        }
    }
    if (!url) return true;
    localStorage.setItem(_zimoli_params_key + url, JSON.stringify(args) || null);
    if (!page_generators[url]) {
        return zimoli(url, args, history_name);
    }
    if (isNode(history_name)) {
        if (history_name.activate === url) return;
        history_name.activate = url;
    }
    var pg = page_generators[url];
    var _with_elements = [].concat(pg.with);
    var _remove_listeners = [].concat(pg.onappend);
    var _append_listeners = [].concat(pg.onremove);
    var _pageback_listener = [].concat(pg.onback);
    var state = pg.state;
    state.onappend = function (handler) {
        isFunction(handler) && _append_listeners.push(handler);
    };
    state.onremove = function (handler) {
        isFunction(handler) && _remove_listeners.push(handler);
    };
    state.with = function (element) {
        element && _with_elements.push(element);
        return _with_elements;
    };
    state.onback = function (handler) {
        _pageback_listener = handler;
    };
    if (!args) args = {};
    var _page = pg.call(state, args);
    if (pg.className) _page.className = pg.className;
    _page.with = _with_elements;
    onappend(_page, _append_listeners);
    onremove(_page, _remove_listeners);
    addGlobal(_page, history_name);
    _page.onback = _pageback_listener;
    pushstate(url, history_name);
    return _page;
}
var page_generators = {};
/**
 * 加载一个页面到document.body
 * 如果args是一个字符串，那么当下次指定一个相同的字符串时，此对象被新对象代替
 * 如果args是bool值true，那么当执行history.back()时，此对象被清除
 */
function zimoli(page, args, history_name) {
    if (arguments.length === 0) {
        exit_ing = false;
        history_name = current_history;
        var _history = history[history_name] || [];
        page = _history[_history.length - 1] || "/main";
        try {
            args = JSON.parse(localStorage.getItem(_zimoli_params_key + page)) || {};
        } catch (e) {
            args = {};
        }
    }
    //只有把runtime绑定到对像才可以使用
    //    css(document.body,{
    //        backgroundColor:"rgba(0,0,0,1)"
    //    });
    //    var button=createElement(anniu);
    //    console.log(button)
    var _zimoli_state_key = _zimoli_state_prefix + page;
    var state = function state(condition) {
        if (arguments.length >= 1) {
            localStorage.setItem(_zimoli_state_key, JSON.stringify(condition) || null);
        }
        try {
            condition = JSON.parse(localStorage.getItem(_zimoli_state_key)) || {};
        } catch (e) {
            condition = {};
        }
        return condition;
    };
    if (page_generators[page]) return go(page, args, history_name);
    var _with_elements = [];
    state.with = function (element) {
        element && _with_elements.push(element);
        return _with_elements;
    };
    state.go = function (url, args, history_name) {
        if (isString(url) && /^[^\\\/]/.test(url)) {
            url = page.replace(/[^\/]*$/, url);
            return go(url, args, history_name);
        }
        return go(url, args, history_name);
    };

    var _remove_listeners = [];
    state.onremove = function (handler, _handler) {
        if (isFunction(handler)) _remove_listeners.push(handler);
        else onremove(handler, _handler);
    };
    var _append_listeners = [];
    state.onappend = function (handler, _handler) {
        if (isFunction(handler)) _remove_listeners.push(handler);
        else onappend(handler, _handler);
    };
    var _pageback_listener = [];
    var onback = state.onback = state.onrelease = state.ondestroy = function (handler) {
        //只能在page上使用
        _pageback_listener = handler;
    };

    return init(page, function (pg) {
        console.log(page);
        if (!pg) return;
        pg.with = _with_elements;
        pg.onremove = _remove_listeners;
        pg.onappend = _append_listeners;
        pg.state = state;
        pg.onback = _pageback_listener;
        page_generators[page] = pg;
        return go(page, args, history_name);
    }, {
            state: state,
            titlebar: function () {
                return getTitleBar(state, arguments);
            },
            zimoli: state.go,
            go: state.go,
            onremove: function () {
                return getRemoveFn(state, arguments);
            },
            onappend: function () {
                return getAppendFn(state, arguments);
            },
            onback: onback,
            ondestroy: onback,
            onrelease: onback
        });
}
var getRemoveFn = function (state, args) {
    return state.onremove.apply(null, args);
};
var getAppendFn = function (state, args) {
    return state.onappend.apply(null, args);
};
var getTitleBar = function (state, args) {
    var realTitleBar = titlebar.apply(null, args);
    state.with(realTitleBar);
    return realTitleBar;
};
var alertslist = zimoli.alertslist = [];
var global = {};
var history = {};
var current_history = "default";
history[current_history] = [];
var history_session_object_key = `_zimoli_history_key:${location_pathname}`;
try {
    history = JSON.parse(localStorage.getItem(history_session_object_key)) || history;
} catch (e) {
}
var pushstate = function (path_name, history_name) {
    if (!history_name) {
        history_name = current_history;
    }
    if (!isString(history_name)) return;
    if (!history[history_name]) {
        history[history_name] = [path_name];
    } else {
        var _history = history[history_name];
        for (var cx = 0, dx = _history.length; cx < dx; cx++) {
            if (_history[cx] === path_name) {
                _history.splice(cx, dx - cx);
                break;
            }
        }
        _history.push(path_name);
        if (_history.length > 1) fixurl();
    }
    localStorage.setItem(history_session_object_key, JSON.stringify(history) || null);
};
var fixurl = function () {
    setTimeout(function () {
        exit_ing = void 0;
        if (!/#$/.test(location.href)) location.href = "#";
    }, 0);
}
var onback = function () {
    if (alertslist.length) {
        fixurl();
        remove(alertslist.pop());
        return;
    }
    var current_page = global[current_history];
    var onback = current_page && current_page.onback;
    if (isFunction(onback)) {
        onback = current_page.onback();
    }
    if (onback === false) {
        return;
    }
    if (isString(onback)) {
        return go(onback);
    }
    if (go(-1, onback) === true) {
        try {
            navigator.app.exitApp();
        } catch (e) {
            if (window_history.length > 2) exit_ing = true, window_history.go(-1);
        };
    } else { };
};

function addGlobal(element, name) {
    if (!name) {
        name = current_history;
    }
    if (isString(name)) {
        if (global[name]) {
            remove(global[name]);
        }
        appendChild(body, element);
        global[name] = element;
    } else if (isNode(name)) {
        appendChild(name, element);
    } else if (isFunction(name)) {
        name(element);
    } else {
        onremove(element, cleanup);
        appendChild(body, element);
        alertslist.push(element);
        fixurl();
    }
}
var cleanup = new Cleanup(alertslist);
var _switch = zimoli.switch = function (history_name) {
    if (history_name)
        current_history = history_name;
};
zimoli.global = addGlobal;
window.modules = modules;<commit_msg>把go和zimli区别开<commit_after>/*
 * 不枝雀
 * 2017-3-18 16:16:20
 */
//main
var body = document.body;
var onbacks = [];
var target_hash, exit_ing;
var window_history = window.history;
var window_history_length = window_history.length;
var load_count = "__zimoli_load_times";
var loadTime = +sessionStorage.getItem(load_count) || 0;
if (!loadTime) {
    location.replace("#reload");
}
loadTime++;
sessionStorage.setItem(load_count, loadTime);

if (/MSIE\s*[2-7]/.test(navigator.userAgent)) {
    window.onhistorychange = function (url) {
        if (exit_ing) return exit_ing = false, window_history.go(-1);
        if (exit_ing === void 0 ? onback && onback() === true : exit_ing = void 0) { }
    };
    onselectstart(body, function (e) {
        return e.preventDefault();
    });
    var frame = createElement("iframe");
    css(frame, "display:none");
    appendChild(body, frame);
    var doc = frame.contentWindow.document;
    var backman = function (isloaded) {
        doc.open();
        doc.write(isloaded !== false ? "" : "<script>result=parent.onhistorychange();onload=function(){history.forward()}</script>");
        doc.close();
    };
    backman(false);
    backman();
} else {
    onhashchange(window, function (event) {
        if (/#$/.test(event.newURL || event.actionURL || location.href)) return;
        if (exit_ing) return exit_ing = false, window_history.go(-1);
        event.preventDefault();
        if (exit_ing === void 0 ? onback() === true : exit_ing = void 0) { }
    });
}
// body
css(body, {
    width: "100%",
    height: "100%",
    border: "none",
    position: "absolute",
    margin: "0",
    padding: "0",
    overflow: "hidden",
    backgroundColor: "#f2f4f9"
});
var location_pathname = location.pathname;
var _zimoli_params_key = `_zimoli_parameters:${location_pathname}#`;
var _zimoli_state_prefix = `_zimoli_page_state:${location_pathname}#`;

function go(url, args, history_name) {
    if (isNumber(url)) {
        if (!history_name)
            history_name = current_history;
        if (isString(history_name)) {
            var _history = history[history_name] || [];
            url = _history[url < 1 ? _history.length + url - 1 : url];
        }
    }
    if (!url) return true;
    localStorage.setItem(_zimoli_params_key + url, JSON.stringify(args) || null);
    if (!page_generators[url]) {
        return zimoli(url, args, history_name);
    }
    if (isNode(history_name)) {
        if (history_name.activate === url) return;
        history_name.activate = url;
    }
    var pg = page_generators[url];
    var _with_elements = [].concat(pg.with);
    var _remove_listeners = [].concat(pg.onappend);
    var _append_listeners = [].concat(pg.onremove);
    var _pageback_listener = [].concat(pg.onback);
    var state = pg.state;
    state.onappend = function (handler) {
        isFunction(handler) && _append_listeners.push(handler);
    };
    state.onremove = function (handler) {
        isFunction(handler) && _remove_listeners.push(handler);
    };
    state.with = function (element) {
        element && _with_elements.push(element);
        return _with_elements;
    };
    state.onback = function (handler) {
        _pageback_listener = handler;
    };
    if (!args) args = {};
    var _page = pg.call(state, args);
    if (pg.className) _page.className = pg.className;
    _page.with = _with_elements;
    onappend(_page, _append_listeners);
    onremove(_page, _remove_listeners);
    addGlobal(_page, history_name);
    _page.onback = _pageback_listener;
    pushstate(url, history_name);
    return _page;
}
var page_generators = {};
/**
 * 加载一个页面到document.body
 * 如果args是一个字符串，那么当下次指定一个相同的字符串时，此对象被新对象代替
 * 如果args是bool值true，那么当执行history.back()时，此对象被清除
 */
function zimoli(page, args, history_name) {
    if (arguments.length === 0) {
        exit_ing = false;
        history_name = current_history;
        var _history = history[history_name] || [];
        page = _history[_history.length - 1] || "/main";
        try {
            args = JSON.parse(localStorage.getItem(_zimoli_params_key + page)) || {};
        } catch (e) {
            args = {};
        }
    }
    //只有把runtime绑定到对像才可以使用
    //    css(document.body,{
    //        backgroundColor:"rgba(0,0,0,1)"
    //    });
    //    var button=createElement(anniu);
    //    console.log(button)
    var _zimoli_state_key = _zimoli_state_prefix + page;
    var state = function state(condition) {
        if (arguments.length >= 1) {
            localStorage.setItem(_zimoli_state_key, JSON.stringify(condition) || null);
        }
        try {
            condition = JSON.parse(localStorage.getItem(_zimoli_state_key)) || {};
        } catch (e) {
            condition = {};
        }
        return condition;
    };
    if (page_generators[page]) return go(page, args, history_name);
    var _with_elements = [];
    state.with = function (element) {
        element && _with_elements.push(element);
        return _with_elements;
    };
    state.go = function (url, args, history_name) {
        if (isString(url) && /^[^\\\/]/.test(url)) {
            url = page.replace(/[^\/]*$/, url);
            return go(url, args, history_name);
        }
        return go(url, args, history_name);
    };

    var _remove_listeners = [];
    state.onremove = function (handler, _handler) {
        if (isFunction(handler)) _remove_listeners.push(handler);
        else onremove(handler, _handler);
    };
    var _append_listeners = [];
    state.onappend = function (handler, _handler) {
        if (isFunction(handler)) _remove_listeners.push(handler);
        else onappend(handler, _handler);
    };
    var _pageback_listener = [];
    var onback = state.onback = state.onrelease = state.ondestroy = function (handler) {
        //只能在page上使用
        _pageback_listener = handler;
    };

    return init(page, function (pg) {
        console.log(page);
        if (!pg) return;
        pg.with = _with_elements;
        pg.onremove = _remove_listeners;
        pg.onappend = _append_listeners;
        pg.state = state;
        pg.onback = _pageback_listener;
        page_generators[page] = pg;
        return go(page, args, history_name);
    }, {
            state: state,
            titlebar: function () {
                return getTitleBar(state, arguments);
            },
            go: state.go,
            onremove: function () {
                return getRemoveFn(state, arguments);
            },
            onappend: function () {
                return getAppendFn(state, arguments);
            },
            onback: onback,
            ondestroy: onback,
            onrelease: onback
        });
}
var getRemoveFn = function (state, args) {
    return state.onremove.apply(null, args);
};
var getAppendFn = function (state, args) {
    return state.onappend.apply(null, args);
};
var getTitleBar = function (state, args) {
    var realTitleBar = titlebar.apply(null, args);
    state.with(realTitleBar);
    return realTitleBar;
};
var alertslist = zimoli.alertslist = [];
var global = {};
var history = {};
var current_history = "default";
history[current_history] = [];
var history_session_object_key = `_zimoli_history_key:${location_pathname}`;
try {
    history = JSON.parse(localStorage.getItem(history_session_object_key)) || history;
} catch (e) {
}
var pushstate = function (path_name, history_name) {
    if (!history_name) {
        history_name = current_history;
    }
    if (!isString(history_name)) return;
    if (!history[history_name]) {
        history[history_name] = [path_name];
    } else {
        var _history = history[history_name];
        for (var cx = 0, dx = _history.length; cx < dx; cx++) {
            if (_history[cx] === path_name) {
                _history.splice(cx, dx - cx);
                break;
            }
        }
        _history.push(path_name);
        if (_history.length > 1) fixurl();
    }
    localStorage.setItem(history_session_object_key, JSON.stringify(history) || null);
};
var fixurl = function () {
    setTimeout(function () {
        exit_ing = void 0;
        if (!/#$/.test(location.href)) location.href = "#";
    }, 0);
}
var onback = function () {
    if (alertslist.length) {
        fixurl();
        remove(alertslist.pop());
        return;
    }
    var current_page = global[current_history];
    var onback = current_page && current_page.onback;
    if (isFunction(onback)) {
        onback = current_page.onback();
    }
    if (onback === false) {
        return;
    }
    if (isString(onback)) {
        return go(onback);
    }
    if (go(-1, onback) === true) {
        try {
            navigator.app.exitApp();
        } catch (e) {
            if (window_history.length > 2) exit_ing = true, window_history.go(-1);
        };
    } else { };
};

function addGlobal(element, name) {
    if (!name) {
        name = current_history;
    }
    if (isString(name)) {
        if (global[name]) {
            remove(global[name]);
        }
        appendChild(body, element);
        global[name] = element;
    } else if (isNode(name)) {
        appendChild(name, element);
    } else if (isFunction(name)) {
        name(element);
    } else {
        onremove(element, cleanup);
        appendChild(body, element);
        alertslist.push(element);
        fixurl();
    }
}
var cleanup = new Cleanup(alertslist);
var _switch = zimoli.switch = function (history_name) {
    if (history_name)
        current_history = history_name;
};
zimoli.global = addGlobal;
window.modules = modules;<|endoftext|>


<commit_before>window.cls || (window.cls = {});

/**
  * @constructor
  * @extends ViewBase
  */

cls.CSSInspectorView = function(id, name, container_class)
{
  var self = this;

  this.createView = function(container)
  {
    container.innerHTML ='';
    var cats = elementStyle.getCategories(), cat_key = '', cat = null, i = 0;
    container.render(templates.cssInspector(cats));
    for( ; cat = cats[i]; i++)
    {
      cat_key += cat.is_unfolded() ? '1' : '0';
    }
    this.updateCategories({}, cat_key);

    var quick_find = this.getToolbarControl( container, 'css-inspector-text-search');
    if( quick_find && elementStyle.getSearchTerm() )
    {
      quick_find.value = elementStyle.getSearchTerm();
      quick_find.previousElementSibling.textContent = "";
    }
  }

  this.updateCategories = function(ev, cats)
  {
    if( self.isvisible() )
    {
      if(ev.__call_count && ev.__call_count > 2  )
      {
        opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
          'failed updateCategories, missing indexMap, views-css-inspector')
        return;
      }
      var containers = self.getAllContainers(), c = null , i = 0;
      var styles = null, s_c = null , cat_index = 0, data = null;
      var search_active = elementStyle.getSearchActive();
      for( ; c = containers[i]; i++)
      {
        styles = c.getElementsByTagName('styles');
        if( !styles.length )
        {
          this.createView(c);
          return;
        }
        for( cat_index = 0; cat_index < 2; cat_index++ )
        {
          if( cats[cat_index] == '1' )
          {

            // TODO update depending from the category
            data = elementStyle.getCategoryData(cat_index);
            if( data )
            {
              // stylesheets.prettyPrintCat call will also ensure
              // that all style sheets for the given runtime and the index map
              // will be avaible, that means the call will not return any data
              // before this datas are avaible
              styles[cat_index].innerHTML =
                stylesheets.prettyPrintCat(cat_index, data, arguments, search_active);
              styles[cat_index].setAttribute('rt-id', data.rt_id);
            }
          }
        }
      }
    }
  }
  this.init(id, name, container_class);
}

cls.CSSInspectorView.create_ui_widgets = function()
{

  new Settings
  (
    // id
    'css-inspector',
    // key-value map
    {
      'computedStyle': false,
      'css': true,
      'hide-initial-values': true,
      'hide-shorthands': true
    },
    // key-label map
    {
      'hide-initial-values': ui_strings.S_SWITCH_SHOW_INITIAL_VALUES,
      'hide-shorthands': ui_strings.S_SWITCH_SHOW_SHORTHANDS
    },
    // settings map
    {
      checkboxes:
      [
        'hide-initial-values',
        'hide-shorthands',
      ]
    }
  );

  new ToolbarConfig
  (
    'css-inspector',
    null,
    [
      {
        handler: 'css-inspector-text-search',
        title: 'text search',
        label: ui_strings.S_INPUT_DEFAULT_TEXT_FILTER
      }
    ]
  );

  new Switches
  (
    'css-inspector',
    [
      'hide-initial-values',
      'hide-shorthands',
    ]
  );

}

<commit_msg>Close the color picker on destroying the css inspector view.<commit_after>window.cls || (window.cls = {});

/**
  * @constructor
  * @extends ViewBase
  */

cls.CSSInspectorView = function(id, name, container_class)
{
  var self = this;

  this.createView = function(container)
  {
    container.innerHTML ='';
    var cats = elementStyle.getCategories(), cat_key = '', cat = null, i = 0;
    container.render(templates.cssInspector(cats));
    for( ; cat = cats[i]; i++)
    {
      cat_key += cat.is_unfolded() ? '1' : '0';
    }
    this.updateCategories({}, cat_key);

    var quick_find = this.getToolbarControl( container, 'css-inspector-text-search');
    if( quick_find && elementStyle.getSearchTerm() )
    {
      quick_find.value = elementStyle.getSearchTerm();
      quick_find.previousElementSibling.textContent = "";
    }
  }

  this.updateCategories = function(ev, cats)
  {
    if( self.isvisible() )
    {
      if(ev.__call_count && ev.__call_count > 2  )
      {
        opera.postError(ui_strings.DRAGONFLY_INFO_MESSAGE +
          'failed updateCategories, missing indexMap, views-css-inspector')
        return;
      }
      var containers = self.getAllContainers(), c = null , i = 0;
      var styles = null, s_c = null , cat_index = 0, data = null;
      var search_active = elementStyle.getSearchActive();
      for( ; c = containers[i]; i++)
      {
        styles = c.getElementsByTagName('styles');
        if( !styles.length )
        {
          this.createView(c);
          return;
        }
        for( cat_index = 0; cat_index < 2; cat_index++ )
        {
          if( cats[cat_index] == '1' )
          {

            // TODO update depending from the category
            data = elementStyle.getCategoryData(cat_index);
            if( data )
            {
              // stylesheets.prettyPrintCat call will also ensure
              // that all style sheets for the given runtime and the index map
              // will be avaible, that means the call will not return any data
              // before this datas are avaible
              styles[cat_index].innerHTML =
                stylesheets.prettyPrintCat(cat_index, data, arguments, search_active);
              styles[cat_index].setAttribute('rt-id', data.rt_id);
            }
          }
        }
      }
    }
  }

  this.ondestroy = function()
  {
    UIWindowBase.closeWindow('color-selector');
  }

  this.init(id, name, container_class);
}

cls.CSSInspectorView.create_ui_widgets = function()
{

  new Settings
  (
    // id
    'css-inspector',
    // key-value map
    {
      'computedStyle': false,
      'css': true,
      'hide-initial-values': true,
      'hide-shorthands': true
    },
    // key-label map
    {
      'hide-initial-values': ui_strings.S_SWITCH_SHOW_INITIAL_VALUES,
      'hide-shorthands': ui_strings.S_SWITCH_SHOW_SHORTHANDS
    },
    // settings map
    {
      checkboxes:
      [
        'hide-initial-values',
        'hide-shorthands',
      ]
    }
  );

  new ToolbarConfig
  (
    'css-inspector',
    null,
    [
      {
        handler: 'css-inspector-text-search',
        title: 'text search',
        label: ui_strings.S_INPUT_DEFAULT_TEXT_FILTER
      }
    ]
  );

  new Switches
  (
    'css-inspector',
    [
      'hide-initial-values',
      'hide-shorthands',
    ]
  );

}

<|endoftext|>