<commit_before>// if registerModule is defined call that. if not then check if this this has
// been loaded as a node.js module and the code can execute right away.
(typeof registerModule=='function' ? registerModule : function (fn){fn(module, require);}).call(this, function (module, require){
	var exports=module.exports;

var isNodeJS = !(typeof window=='object');

/**
 * This code intercepts calls to the QUnit testing library to allow tests written for that library to run in BrowserDriver.
 */

exports.initialize=function (){

	var extend, sendMessage, onMessage;

	var sourceFilesQueue=[]
		processingSourceFile=false;

	function nextTick(cb){
		isNodeJS ? process.nextTick(cb) : setTimeout(cb, 0);
	}

	function processSourceFilesQueue(){
		if(!processingSourceFile && sourceFilesQueue.length){
			processingSourceFile=true;
			currentModule=undefined;
			function fileProcessed(){
				processingSourceFile=false;
				var file=sourceFilesQueue.shift();
				sendMessage({
					id:'allTestsRead',
					fileName:file.fileName
				});
				nextTick(processSourceFilesQueue);
			}
			if(isNodeJS){
				var vm = require("vm"),
					fs = require("fs");

				fs.readFile(sourceFilesQueue[0].filePath, function (err, fileData){
					if(err)
						console.log('ERR: processSourceFilesQueue failed loading "'+sourceFilesQueue[0].filePath+'": '+err)
					else{
//						console.log('runInThisContext '+sourceFilesQueue[0])
						vm.runInThisContext(fileData, sourceFilesQueue[0].filePath);
					}
					fileProcessed();
				});
			}else{
				attachScript(sourceFilesQueue[0].filePath, function (){
					fileProcessed();
				});
			}
		}
	}
	/**
	 * Loads a test source file so tests in it are registered in the environment and ready (but not scheduled) to be run. All loaded tests
	 * are added to the testCache
	 * @param	{String}	src	The path of the test file.
	 */
	function loadTestsSource(file){
//		console.log('loadTestsSource '+path)
		if(file instanceof Array)
			sourceFilesQueue.push.apply(sourceFilesQueue, file);
		else
			sourceFilesQueue.push(file);
		processSourceFilesQueue();
	}

	var currentModule=undefined,
		testCache={};
//		currentFileName='';
	function addToTestCache(test){
		var obj=testCache[test.fileName];
		if(!obj)
			obj=testCache[test.fileName]={};
		obj[test.name]=test;
	}

	var testsQueue=[],
		runningTest;
	function processTestsQueue(){
		if(!runningTest && testsQueue.length){
			var test=testsQueue.shift(),
				cacheObj=testCache[test.fileName];
			if(cacheObj)
				extend(test, cacheObj[test.name]);
			runningTest=new Test(test);
			runningTest.run();
		}
	}

	function Test(cfg){
		extend(this, cfg);
	}
	function onTestRead(test){
//		console.log('testRead', test.name, 'in', test.fileName)
		addToTestCache(test);
		sendMessage({
			id:'testRead',
			test:test
		});
//		console.log('runningTest', runningTest, runningTest&&(runningTest.module==test.module))
		if(runningTest && runningTest.paused
						&& runningTest.fileName==test.fileName
						&& (!(runningTest.module&&test.module) || (runningTest.module.name==test.module.name))
						&& runningTest.name==test.name){
//			console.log('resuming test ...');
			extend(runningTest, test);
			runningTest.resume();
		}
	}
	function Module(){
		this.initialize.apply(this, arguments);
	}

	function setup(QUnit){
		extend(Test.prototype, {
			run:function (){
				if(!this.paused){
					if(this.fn){
						this.reset();
						if(this.module && (typeof this.module.setup=='function'))
							this.module.setup.call(this.testEnvironment);
						this.fn.call(this.environment);
					}else{
						this.pause();
						console.log('waiting for test function ...');
						loadTestsSource(this);
					}
				}
			},
			end:function (){
				if(this.module && (typeof this.module.teardown=='function'))
					this.module.teardown.call(this.testEnvironment);
			},
			pause:function (){
				this.paused=true;
			},
			resume:function (){
				this.paused=false;
				this.run();
			},
			reset:function (){
				this.testEnvironment={
					__testInst:this
				};
			}
		});
		extend(Module.prototype, {
			initialize:function (name, lifecycle){
				this.name=name;
				if(lifecycle)
					extend(this, lifecycle);
			}
		});

		QUnit.testStart(function (data){
			sendMessage(extend({
				id:'testStart',
				name:runningTest.name,
				module:runningTest.module?runningTest.module.name:'',
				fileName:runningTest.fileName
			}, data));
		});
		QUnit.testDone(function (data){
			runningTest.end();
			var msg=extend({
				id:'testDone',
				name:runningTest.name,
				module:runningTest.module?runningTest.module.name:'',
				fileName:runningTest.fileName
			}, data);
			runningTest=null;
			sendMessage(msg);
			processTestsQueue();
		});
		QUnit.log(function (data){
			if(runningTest){
				sendMessage(extend({
					id:'assertion',
					name:runningTest.name,
					module:runningTest.module?runningTest.module.name:'',
					fileName:runningTest.fileName
				}, data));
			}
		});

		// add the test methods to global
		extend(function() {return this;}.call(), QUnit.assert, {
			start:QUnit.start,
			stop:QUnit.stop,
			test:function (testName, expected, callback){
//				console.log('test')
				var mod=currentModule,
					args=Array.prototype.slice.call(arguments, 0);
				if(args.length === 2){
					args[2]=args[1]; // callback = expected;
					args[1]=1; // expected = 1;
					expected=1;
				}
				var fn=args[2];
				args[2]=function (){
					fn.call(runningTest.testEnvironment);  // set scope to runningTest because QUnit will set it to its test environment object
				};
				var test={
					module:mod,
					fileName:sourceFilesQueue[0].fileName, //currentFileName,
					name:testName,
					fn:function (){
						if(mod)
							QUnit.module(mod.name);
						else
							QUnit.module('');
						QUnit.test.apply(QUnit, args);
					},
					expect:expected
				};
				onTestRead(test);
			},
			asyncTest:function (testName, expected, callback){
				var mod=currentModule,
					args=Array.prototype.slice.call(arguments, 0);
				if(args.length === 2){
					args[2]=args[1]; // callback = expected;
					args[1]=1; // expected = 1;
					expected=1;
				}
				var fn=args[2];
				args[2]=function (){
					fn.call(runningTest.testEnvironment);  // set scope to runningTest because QUnit will set it to its test environment object
				};
				var test={
					module:mod,
					fileName:sourceFilesQueue[0].fileName, //currentFileName,
					name:testName,
					fn:function (){
						if(mod)
							QUnit.module(mod.name);
						else
							QUnit.module('');
						QUnit.asyncTest.apply(QUnit, args);
					},
					expect:expected
				};
				onTestRead(test);
			},
			module:function (name, lifecycle){
				currentModule=new Module(name, lifecycle);
			}
		});
	}
	// load the QUnit library
	if(isNodeJS){
		extend=require('jquery.extend');
		sendMessage=function (msg){
//			console.log('sendMessage '+msg.id)
			process.send(msg);
		};
		onMessage=function (fn){
			process.on('message', fn);
		};
		setup(require('../qunit'));
		sendMessage({
			id:'adaptorInitialized'
		});
	}else{
		sendMessage=function (msg){
			window.__adaptorSendMessage(msg);
		};
		(function (){
			var listeners=[];
			window.__adaptorOnMessage=function (msg){
				for(var i=0; i<listeners.length; i++)
					listeners[i](msg);
			};
			onMessage=function (fn){
				listeners.push(fn);
			};
		}());
		attachScript(module.url.replace(/[^\/]*$/, '')+'../qunit.js', function (){
			extend=$.extend;
			// do this because for now the lib is not loaded in a standard document wich to fire "load"
			//QUnit.config.blocking=false;
			QUnit.init();
			QUnit.config.autorun=true;
			QUnit.config.semaphore=0;

			setup(QUnit);
			sendMessage({
				id:'adaptorInitialized'
			});

//			function initQUnit(){
//				QUnit.init();
//				QUnit.config.autorun=true;
//			}
//			driver.on('reset', initQUnit);
//			initQUnit();
		});
	}
	onMessage(function (msg){
//		console.log('testInstance received message '+msg.id);
		switch(msg.id){
			case 'loadTestsSource':
					loadTestsSource(msg);
				break;
			case 'runTest':
					if(msg.test instanceof Array)
						testsQueue.push.apply(testsQueue, msg.test);
					else
						testsQueue.push(msg.test);
					processTestsQueue();
				break;
		}
	});
};

function attachScript(src, cb, doc){
	if(!doc)
		doc=document;
	var script=doc.createElement('SCRIPT'),
		head=doc.getElementsByTagName('head')[0];
	script.src=src;
	script.type='text/javascript';

	if($.browser.msie) // no load event in IE so wait for readyState
		script.onreadystatechange=function(){
			if(script.readyState == 'complete' || script.readyState == 'loaded'){
				script.onreadystatechange=null;
				head.removeChild(script);
				if(cb)
					cb();
			}
		};
	else
		$(script).one('load', function (){
			head.removeChild(script);
			if(cb)
				cb()
		});

	head.appendChild(script);

	return script;
}
exports.createTestingInstance=function (cfg){
	var inst={};
	if(isNodeJS){
		var cp = require('child_process');
		inst.child=cp.fork(__dirname + '/../../node.js/testing-instance.js', ['adaptor='+__filename], {env: process.env});
		inst.onMessage=function (fn){
			this.child.on('message', fn);
		};
		inst.sendMessage=function (msg){
			this.child.send(msg);
		};
		inst.disconnect=function (){
			this.child.disconnect();
			delete this.child;
		};
	}else{
		inst.listeners=[];
		inst.el=document.createElement('iframe');
		inst.el.className='testing-instance';
		document.body.appendChild(inst.el);
//		$(inst.el).bind('load', function (){
			inst.el.contentWindow.__adaptorSendMessage=function (msg){
				for(var i=0; i<inst.listeners.length; i++)
					inst.listeners[i](msg);
			};
			/**
			 * TO-DO: try to use asyncFlow instead of nesting callbacks
			 */
			var doc=inst.el.contentWindow.document;
			attachScript(cfg.serverUrl+'/lib/jquery-1.7.1.min.js', function (){
					attachScript(cfg.serverUrl+'/lib/modules.js', function (){
							inst.el.contentWindow.registerModule.loadFromAbsPath(cfg.serverUrl+'/lib/adaptors/qunit', function (exports){
								exports.initialize();
							});
						}, doc);
				}, doc);
//		});
		inst.onMessage=function (fn){
			this.listeners.push(fn);
		};
		inst.sendMessage=function (msg){
			this.el.contentWindow.__adaptorOnMessage(msg);
		};
		inst.disconnect=function (){
			$(this.el).remove();
			delete this.el;
			this.listeners.splice(0, this.listeners.length);
		};
	}
	return inst;
};

/**
 *
 */
exports.getTestsInfoList=function (requirePath, cb){
//	console.log('getTestsInfoList ', requirePath);
	var inst=exports.createTestingInstance();
	if(isNodeJS){
		/**
		 * TO-DO: try to reuse the forked process
		 */
		if(requirePath instanceof Array){
			var sources=requirePath.slice(0),	// copy the list
				allTests=[],
				currentTestsList=[];
			inst.onMessage(function sourceComplete(msg){
				if(msg.id=='testRead'){
					currentTestsList.push({
						module:msg.test.module?msg.test.module.name:'',
						fileName:msg.test.fileName,
						name:msg.test.name,
						expect:msg.test.expect
					});

				}else if(msg.id=='allTestsRead'){
					allTests.push({
						fileName:sources.shift(),
						tests:currentTestsList
					});
					processNextSource();
				}
			});
			function processNextSource(){
				if(sources.length){
					currentTestsList=[];
					inst.sendMessage({
						id:'loadTestsSource',
						fileName:sources[0],
						filePath:sources[0]
					});
				}else{
					cb && cb(null, allTests);
					inst.disconnect();
				}
			}
			processNextSource();
		}else{
			var currentTestsList=[];
			inst.onMessage(function (msg){
				if(msg.id=='testRead'){
					currentTestsList.push({
						module:msg.test.module?msg.test.module.name:'',
						fileName:msg.test.fileName,
						name:msg.test.name,
						expect:msg.test.expect
					});

				}else if(msg.id=='allTestsRead'){
					cb && cb(null, currentTestsList);
					inst.disconnect();
				}
			});
			inst.sendMessage({
				id:'loadTestsSource',
				fileName:requirePath,
				filePath:requirePath
			});
		}
	}else{
		/**
		 * not needed for now
		 */
//		driverObj.doLoadTestSource(requirePath);
	}
};

}, typeof module=='object'?module:null);

<commit_msg>added require() to the Test object to let tests include library modules or whatever shared code they may need<commit_after>// if registerModule is defined call that. if not then check if this this has
// been loaded as a node.js module and the code can execute right away.
(typeof registerModule=='function' ? registerModule : function (fn){fn(module, require);}).call(this, function (module, require){
	var exports=module.exports;

var isNodeJS = !(typeof window=='object');

/**
 * This code intercepts calls to the QUnit testing library to allow tests written for that library to run in BrowserDriver.
 */

exports.initialize=function (){

	var extend, sendMessage, onMessage;

	var sourceFilesQueue=[]
		processingSourceFile=false;

	function nextTick(cb){
		isNodeJS ? process.nextTick(cb) : setTimeout(cb, 0);
	}

	function processSourceFilesQueue(){
		if(!processingSourceFile && sourceFilesQueue.length){
			processingSourceFile=true;
			currentModule=undefined;
			function fileProcessed(){
				processingSourceFile=false;
				var file=sourceFilesQueue.shift();
				sendMessage({
					id:'allTestsRead',
					fileName:file.fileName
				});
				nextTick(processSourceFilesQueue);
			}
			if(isNodeJS){
				var vm = require("vm"),
					fs = require("fs");

				fs.readFile(sourceFilesQueue[0].filePath, function (err, fileData){
					if(err)
						console.log('ERR: processSourceFilesQueue failed loading "'+sourceFilesQueue[0].filePath+'": '+err)
					else{
//						console.log('runInThisContext '+sourceFilesQueue[0])
						vm.runInThisContext(fileData, sourceFilesQueue[0].filePath);
					}
					fileProcessed();
				});
			}else{
				attachScript(sourceFilesQueue[0].filePath, function (){
					fileProcessed();
				});
			}
		}
	}
	/**
	 * Loads a test source file so tests in it are registered in the environment and ready (but not scheduled) to be run. All loaded tests
	 * are added to the testCache
	 * @param	{String}	src	The path of the test file.
	 */
	function loadTestsSource(file){
//		console.log('loadTestsSource '+path)
		if(file instanceof Array)
			sourceFilesQueue.push.apply(sourceFilesQueue, file);
		else
			sourceFilesQueue.push(file);
		processSourceFilesQueue();
	}

	var currentModule=undefined,
		testCache={};
//		currentFileName='';
	function addToTestCache(test){
		var obj=testCache[test.fileName];
		if(!obj)
			obj=testCache[test.fileName]={};
		obj[test.name]=test;
	}

	var testsQueue=[],
		runningTest;
	function processTestsQueue(){
		if(!runningTest && testsQueue.length){
			var test=testsQueue.shift(),
				cacheObj=testCache[test.fileName];
			if(cacheObj)
				extend(test, cacheObj[test.name]);
			runningTest=new Test(test);
			runningTest.run();
		}
	}

	function Test(cfg){
		extend(this, cfg);
	}
	function onTestRead(test){
//		console.log('testRead', test.name, 'in', test.fileName)
		addToTestCache(test);
		sendMessage({
			id:'testRead',
			test:test
		});
//		console.log('runningTest', runningTest, runningTest&&(runningTest.module==test.module))
		if(runningTest && runningTest.paused
						&& runningTest.fileName==test.fileName
						&& (!(runningTest.module&&test.module) || (runningTest.module.name==test.module.name))
						&& runningTest.name==test.name){
//			console.log('resuming test ...');
			extend(runningTest, test);
			runningTest.resume();
		}
	}
	function Module(){
		this.initialize.apply(this, arguments);
	}

	function setup(QUnit){
		extend(Test.prototype, {
			run:function (){
				if(!this.paused && !this.setupCount){
					if(this.fn){
						this.reset();
						if(this.module && (typeof this.module.setup=='function')){
							this.setupCount++;
							this.module.setup.call(this.testEnvironment);
							this.setupCount--;
						}
						this.doRun();
					}else{
						this.pause();
						console.log('waiting for test function ...');
						loadTestsSource(this);
					}
				}
			},
			doRun:function (){
				if(!this.setupCount)
					this.fn.call(this.environment);
			},
			end:function (){
				if(this.module && (typeof this.module.teardown=='function'))
					this.module.teardown.call(this.testEnvironment);
			},
			pause:function (){
				this.paused=true;
			},
			resume:function (){
				this.paused=false;
				this.run();
			},
			reset:function (){
				this.setupCount=0;
				this.testEnvironment={
					__testInst:this
				};
			},
			require:function (src, cb){
				this.setupCount++;
				var test=this;
				require(src, function (exports){
					cb&&cb(exports);
					test.setupCount--;
					test.doRun();
				});
			}
		});
		extend(Module.prototype, {
			initialize:function (name, lifecycle){
				this.name=name;
				if(lifecycle)
					extend(this, lifecycle);
			}
		});

		QUnit.testStart(function (data){
			sendMessage(extend({
				id:'testStart',
				name:runningTest.name,
				module:runningTest.module?runningTest.module.name:'',
				fileName:runningTest.fileName
			}, data));
		});
		QUnit.testDone(function (data){
			runningTest.end();
			var msg=extend({
				id:'testDone',
				name:runningTest.name,
				module:runningTest.module?runningTest.module.name:'',
				fileName:runningTest.fileName
			}, data);
			runningTest=null;
			sendMessage(msg);
			processTestsQueue();
		});
		QUnit.log(function (data){
			if(runningTest){
				sendMessage(extend({
					id:'assertion',
					name:runningTest.name,
					module:runningTest.module?runningTest.module.name:'',
					fileName:runningTest.fileName
				}, data));
			}
		});

		// add the test methods to global
		extend(function() {return this;}.call(), QUnit.assert, {
			start:QUnit.start,
			stop:QUnit.stop,
			test:function (testName, expected, callback){
//				console.log('test')
				var mod=currentModule,
					args=Array.prototype.slice.call(arguments, 0);
				if(args.length === 2){
					args[2]=args[1]; // callback = expected;
					args[1]=1; // expected = 1;
					expected=1;
				}
				var fn=args[2];
				args[2]=function (){
					fn.call(runningTest.testEnvironment);  // set scope to runningTest because QUnit will set it to its test environment object
				};
				var test={
					module:mod,
					fileName:sourceFilesQueue[0].fileName, //currentFileName,
					name:testName,
					fn:function (){
						if(mod)
							QUnit.module(mod.name);
						else
							QUnit.module('');
						QUnit.test.apply(QUnit, args);
					},
					expect:expected
				};
				onTestRead(test);
			},
			asyncTest:function (testName, expected, callback){
				var mod=currentModule,
					args=Array.prototype.slice.call(arguments, 0);
				if(args.length === 2){
					args[2]=args[1]; // callback = expected;
					args[1]=1; // expected = 1;
					expected=1;
				}
				var fn=args[2];
				args[2]=function (){
					fn.call(runningTest.testEnvironment);  // set scope to runningTest because QUnit will set it to its test environment object
				};
				var test={
					module:mod,
					fileName:sourceFilesQueue[0].fileName, //currentFileName,
					name:testName,
					fn:function (){
						if(mod)
							QUnit.module(mod.name);
						else
							QUnit.module('');
						QUnit.asyncTest.apply(QUnit, args);
					},
					expect:expected
				};
				onTestRead(test);
			},
			module:function (name, lifecycle){
				currentModule=new Module(name, lifecycle);
			}
		});
	}
	// load the QUnit library
	if(isNodeJS){
		extend=require('jquery.extend');
		sendMessage=function (msg){
//			console.log('sendMessage '+msg.id)
			process.send(msg);
		};
		onMessage=function (fn){
			process.on('message', fn);
		};
		setup(require('../qunit'));
		sendMessage({
			id:'adaptorInitialized'
		});
	}else{
		sendMessage=function (msg){
			window.__adaptorSendMessage(msg);
		};
		(function (){
			var listeners=[];
			window.__adaptorOnMessage=function (msg){
				for(var i=0; i<listeners.length; i++)
					listeners[i](msg);
			};
			onMessage=function (fn){
				listeners.push(fn);
			};
		}());
		attachScript(module.url.replace(/[^\/]*$/, '')+'../qunit.js', function (){
			extend=$.extend;
			// do this because for now the lib is not loaded in a standard document wich to fire "load"
			//QUnit.config.blocking=false;
			QUnit.init();
			QUnit.config.autorun=true;
			QUnit.config.semaphore=0;

			setup(QUnit);
			sendMessage({
				id:'adaptorInitialized'
			});

//			function initQUnit(){
//				QUnit.init();
//				QUnit.config.autorun=true;
//			}
//			driver.on('reset', initQUnit);
//			initQUnit();
		});
	}
	onMessage(function (msg){
//		console.log('testInstance received message '+msg.id);
		switch(msg.id){
			case 'loadTestsSource':
					loadTestsSource(msg);
				break;
			case 'runTest':
					if(msg.test instanceof Array)
						testsQueue.push.apply(testsQueue, msg.test);
					else
						testsQueue.push(msg.test);
					processTestsQueue();
				break;
		}
	});
};

function attachScript(src, cb, doc){
	if(!doc)
		doc=document;
	var script=doc.createElement('SCRIPT'),
		head=doc.getElementsByTagName('head')[0];
	script.src=src;
	script.type='text/javascript';

	if($.browser.msie) // no load event in IE so wait for readyState
		script.onreadystatechange=function(){
			if(script.readyState == 'complete' || script.readyState == 'loaded'){
				script.onreadystatechange=null;
				head.removeChild(script);
				if(cb)
					cb();
			}
		};
	else
		$(script).one('load', function (){
			head.removeChild(script);
			if(cb)
				cb()
		});

	head.appendChild(script);

	return script;
}
exports.createTestingInstance=function (cfg){
	var inst={};
	if(isNodeJS){
		var cp = require('child_process');
		inst.child=cp.fork(__dirname + '/../../node.js/testing-instance.js', ['adaptor='+__filename], {env: process.env});
		inst.onMessage=function (fn){
			this.child.on('message', fn);
		};
		inst.sendMessage=function (msg){
			this.child.send(msg);
		};
		inst.disconnect=function (){
			this.child.disconnect();
			delete this.child;
		};
	}else{
		inst.listeners=[];
		inst.el=document.createElement('iframe');
		inst.el.className='testing-instance';
		document.body.appendChild(inst.el);
//		$(inst.el).bind('load', function (){
			inst.el.contentWindow.__adaptorSendMessage=function (msg){
				for(var i=0; i<inst.listeners.length; i++)
					inst.listeners[i](msg);
			};
			/**
			 * TO-DO: try to use asyncFlow instead of nesting callbacks
			 */
			var doc=inst.el.contentWindow.document;
			attachScript(cfg.serverUrl+'/lib/jquery-1.7.1.min.js', function (){
					attachScript(cfg.serverUrl+'/lib/modules.js', function (){
							inst.el.contentWindow.registerModule.loadFromAbsPath(cfg.serverUrl+'/lib/adaptors/qunit', function (exports){
								exports.initialize();
							});
						}, doc);
				}, doc);
//		});
		inst.onMessage=function (fn){
			this.listeners.push(fn);
		};
		inst.sendMessage=function (msg){
			this.el.contentWindow.__adaptorOnMessage(msg);
		};
		inst.disconnect=function (){
			$(this.el).remove();
			delete this.el;
			this.listeners.splice(0, this.listeners.length);
		};
	}
	return inst;
};

/**
 *
 */
exports.getTestsInfoList=function (requirePath, cb){
//	console.log('getTestsInfoList ', requirePath);
	var inst=exports.createTestingInstance();
	if(isNodeJS){
		/**
		 * TO-DO: try to reuse the forked process
		 */
		if(requirePath instanceof Array){
			var sources=requirePath.slice(0),	// copy the list
				allTests=[],
				currentTestsList=[];
			inst.onMessage(function sourceComplete(msg){
				if(msg.id=='testRead'){
					currentTestsList.push({
						module:msg.test.module?msg.test.module.name:'',
						fileName:msg.test.fileName,
						name:msg.test.name,
						expect:msg.test.expect
					});

				}else if(msg.id=='allTestsRead'){
					allTests.push({
						fileName:sources.shift(),
						tests:currentTestsList
					});
					processNextSource();
				}
			});
			function processNextSource(){
				if(sources.length){
					currentTestsList=[];
					inst.sendMessage({
						id:'loadTestsSource',
						fileName:sources[0],
						filePath:sources[0]
					});
				}else{
					cb && cb(null, allTests);
					inst.disconnect();
				}
			}
			processNextSource();
		}else{
			var currentTestsList=[];
			inst.onMessage(function (msg){
				if(msg.id=='testRead'){
					currentTestsList.push({
						module:msg.test.module?msg.test.module.name:'',
						fileName:msg.test.fileName,
						name:msg.test.name,
						expect:msg.test.expect
					});

				}else if(msg.id=='allTestsRead'){
					cb && cb(null, currentTestsList);
					inst.disconnect();
				}
			});
			inst.sendMessage({
				id:'loadTestsSource',
				fileName:requirePath,
				filePath:requirePath
			});
		}
	}else{
		/**
		 * not needed for now
		 */
//		driverObj.doLoadTestSource(requirePath);
	}
};

}, typeof module=='object'?module:null);

<|endoftext|>


<commit_before>var utils = require('../utils/utils.js'),
    util = require('util');

var url = utils.serviceURL + '/net2/oauth2/getaccesstoken.ashx?';

module.exports = {
  send: function(options) {
    var tempURL = util.format('%s?refresh_token=%s&client_id=%s&client_secret=%s',
        url,
        options.refreshToken,
        options.client_id,
        options.client_secret);
    options.resourceURL = tempURL;
    return utils.send(options);
  }
};

/*
 GET https://www.concursolutions.com/net2/oauth2/getaccesstoken.ashx
 ?refresh_token={Refresh Token}
 &client_id={Consumer Key}&client_secret={Consumer Secret}
 */<commit_msg>Fixes double '?' in URL for refreshToken method<commit_after>var utils = require('../utils/utils.js'),
    util = require('util');

var url = utils.serviceURL + '/net2/oauth2/getaccesstoken.ashx';

module.exports = {
  send: function(options) {
    var tempURL = util.format('%s?refresh_token=%s&client_id=%s&client_secret=%s',
        url,
        options.refreshToken,
        options.client_id,
        options.client_secret);
    options.resourceURL = tempURL;
    return utils.send(options);
  }
};

/*
 GET https://www.concursolutions.com/net2/oauth2/getaccesstoken.ashx
 ?refresh_token={Refresh Token}
 &client_id={Consumer Key}&client_secret={Consumer Secret}
 */
<|endoftext|>


<commit_before>const bot = require('./bot.js');
const settings = require('./../settings.json');
const modules = require('./modules.js');
const commands = require('./commands');
let lock = false;
bot.on('error', (err) => {
    /**
     * Catch errors here
     */
    console.log("Stack Trace: " + err.stack);
})
process.on('unhandledRejection',(err)=>console.log("UNHANDLED REJECTION AT "+err.stack));
process.on('uncaughtException',(err)=>console.log("UNHANDLED EXCEPTION AT "+err.stack));
bot.on('message', (message) => {
    /**
     * if locked, reject everything except dm
     */
    if (lock) {
        if (!settings.owners.includes(message.author.id))
            if (message.channel.guild)
                return;//not DM
    }
    /**
     * Listen to messages and convert into params
     */
    if (message.content.startsWith(settings.identifier)) {
        /**Extracting params */
        let params = message.content.substring(settings.identifier.length).trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift().trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else if (message.isMentioned(bot.user)) {
        /**remove mentions and then get params */
        let params = message.cleancontent.trim().replace(bot.user.toString(), "").trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift.trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else {
        //ignore because normal message
    }
});
bot.on('lock', () => { lock = true; });
bot.on('unlock', () => { lock = false; });
bot.on("guildMemberAdd", (member) => {
    var user = member.user;
    if (member.guild.name.toLowerCase().includes('revive')) {
        user.sendMessage("Welcome to the Revive Network");
        refresh(user);
    }
});
bot.on('disconnect', function(event) {
    if (event.code === 0) return console.error(event);
    bot.destroy().then(() => bot.login());
});
<commit_msg>Force restart of bot on disconnect<commit_after>const bot = require('./bot.js');
const settings = require('./../settings.json');
const modules = require('./modules.js');
const commands = require('./commands');
let lock = false;
bot.on('error', (err) => {
    /**
     * Catch errors here
     */
    console.log("Stack Trace: " + err.stack);
})
process.on('unhandledRejection',(err)=>{
    console.log("UNHANDLED REJECTION AT "+err.stack);
    if(err.toString().includes('Request to use token, but token was unavailable to the client'))
        process.exit();//restart
});
process.on('uncaughtException',(err)=>console.log("UNHANDLED EXCEPTION AT "+err.stack));
bot.on('message', (message) => {
    /**
     * if locked, reject everything except dm
     */
    if (lock) {
        if (!settings.owners.includes(message.author.id))
            if (message.channel.guild)
                return;//not DM
    }
    /**
     * Listen to messages and convert into params
     */
    if (message.content.startsWith(settings.identifier)) {
        /**Extracting params */
        let params = message.content.substring(settings.identifier.length).trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift().trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else if (message.isMentioned(bot.user)) {
        /**remove mentions and then get params */
        let params = message.cleancontent.trim().replace(bot.user.toString(), "").trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift.trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else {
        //ignore because normal message
    }
});
bot.on('lock', () => { lock = true; });
bot.on('unlock', () => { lock = false; });
bot.on("guildMemberAdd", (member) => {
    var user = member.user;
    if (member.guild.name.toLowerCase().includes('revive')) {
        user.sendMessage("Welcome to the Revive Network");
        refresh(user);
    }
});
bot.on('disconnect', function(event) {
    if (event.code === 0) return console.error(event);
    process.exit();//force restart
});
<|endoftext|>


<commit_before>const bot = require('./bot.js');
const settings = require('./../settings.json');
const modules = require('./modules.js');
const commands = require('./commands');
let lock = false;
bot.on('error', (err) => {
    /**
     * Catch errors here
     */
    console.log(new Date.now() + " - Error: " + err);
    console.log("Stack Trace: " + err.stack);
})
bot.on('message', (message) => {
    /**
     * if locked, reject everything except dm
     */
    if (lock) {
        if (!settings.owners.includes(message.author))
            if (message.channel.guild)
                return;//not DM
    }
    /**
     * Listen to messages and convert into params
     */
    if (message.content.startsWith(settings.identifier)) {
        /**Extracting params */
        let params = message.content.substring(settings.identifier.length).trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift().trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else if (message.isMentioned(bot.user)) {
        /**remove mentions and then get params */
        let params = message.cleancontent.trim().replace(bot.user.toString(), "").trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift.trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else {
        //ignore because normal message
    }
});
bot.on('lock', () => { lock = true; });
bot.on('unlock', () => { lock = false; });
bot.on("guildMemberAdd", (member) => {
    var user = member.user;
    if (member.guild.name.toLowerCase().includes('revive')) {
        user.sendMessage("Welcome to the Revive Network");
        refresh(user);
    }
});<commit_msg>Fix lock probably<commit_after>const bot = require('./bot.js');
const settings = require('./../settings.json');
const modules = require('./modules.js');
const commands = require('./commands');
let lock = false;
bot.on('error', (err) => {
    /**
     * Catch errors here
     */
    console.log(new Date.now() + " - Error: " + err);
    console.log("Stack Trace: " + err.stack);
})
bot.on('message', (message) => {
    /**
     * if locked, reject everything except dm
     */
    if (lock) {
        if (!settings.owners.includes(message.author.id))
            if (message.channel.guild)
                return;//not DM
    }
    /**
     * Listen to messages and convert into params
     */
    if (message.content.startsWith(settings.identifier)) {
        /**Extracting params */
        let params = message.content.substring(settings.identifier.length).trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift().trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else if (message.isMentioned(bot.user)) {
        /**remove mentions and then get params */
        let params = message.cleancontent.trim().replace(bot.user.toString(), "").trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift.trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else {
        //ignore because normal message
    }
});
bot.on('lock', () => { lock = true; });
bot.on('unlock', () => { lock = false; });
bot.on("guildMemberAdd", (member) => {
    var user = member.user;
    if (member.guild.name.toLowerCase().includes('revive')) {
        user.sendMessage("Welcome to the Revive Network");
        refresh(user);
    }
});<|endoftext|>


<commit_before>import React from 'react';
// Components
import { BrowserRouter as Router, Route } from 'react-router-dom';
import HomeContainer from '../containers/HomeContainer';
import LoginContainer from '../containers/LoginContainer';
import DashboardContainer from '../containers/DashboardContainer';
// Styles
import './App.css';

const App = () => {
  return (
    <Router>
      <div>
        <Route exact path="/" component={HomeContainer} />
        <Route path="/login" component={LoginContainer} />
        <Route path="/dashboard" component={DashboardContainer} />
      </div>
    </Router>
  );
}

export default App;
<commit_msg>make 404 page actually show<commit_after>import React from 'react';
// Components
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import HomeContainer from '../containers/HomeContainer';
import LoginContainer from '../containers/LoginContainer';
import DashboardContainer from '../containers/DashboardContainer';
import NotFound from './NotFound';
// Styles
import './App.css';

const App = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={HomeContainer} />
        <Route path="/login" component={LoginContainer} />
        <Route path="/dashboard" component={DashboardContainer} />
        <Route component={NotFound} />
      </Switch>
    </Router>
  );
}

export default App;
<|endoftext|>


<commit_before>var fs = require('fs');
var separator = '############################################################################\n';
var respId = 0;
var variables = require('./variables');
var feedback_chatId = variables['feedback_chatId'];

function processOnText(msg, match) {
    var resp = null;
    var timestamp = new Date();
    var messagesToSend = [];
    var openingh = require('./openingh');
    var chatId = msg.chat.id;

    //Mensas, die Abendessen Haben
    var dinner_dict = {
        "poly" : "Mensa Polyterrasse",
        "pizzapasta" : "food market - pizza pasta"
    }

    //Übersetzt den einfacheren Befehl zum komplizierteren Mensanamen im JSON
    var dict = {
                "cliff" : "Clausiusbar",
                "haoyi" : "Woka",
                "poly" : "Mensa Polyterrasse",
                "foodlab" : "foodLAB",
                "clausiusbar" : "Clausiusbar",
                "asia" : "Clausiusbar",
                "fusion" : "FUSION meal",
                "woka" : "Woka",
                "tannenbar" : "Tannenbar",
                "trailer" : "Foodtrailer ETZ",
                "dozentenfoyer" : "Dozentenfoyer",
                "grill" : "food market - grill bbQ",
                "pizzapasta" : "food market - pizza pasta",
                "green" : "food market - green day",
        };

    console.log(msg);
    console.log(JSON.stringify(match));
    fs.appendFile('logs/requests.log', separator + timestamp + '\n\n' + JSON.stringify(msg) + '\n' + separator, function (err) {
        console.log(err);
    });
    //Feedback
    if(match[0].indexOf('/feedback') != -1 || match[0].indexOf('/respond') != -1) {
        if (match[0] === '/feedback'){
            resp = '*Feedback für Dummies:*\n/feedback <Deine Nachricht>';

        }else if(match[0].indexOf('/feedback')!=-1){
            respId=chatId;
            fs.appendFile('logs/feedback.log', separator + '\n\n' + timestamp + '\n\n' + JSON.stringify(msg) + '\n\n', function (err) {
                console.log(err);
            });
            resp = 'Vielen Dank für Dein Feedback!';

            messagesToSend.push({chatId:-106064170, message:'New feedback:\n\n' + JSON.stringify(msg)});
        }else if(match[0].indexOf('/respond') != -1){

            resp = match[0].split('respond');
            resp = resp[1];

            chatId = respId;
        }
    }else{
        //Chopping '@...' from the command if needed
        var command = match[1].split('@');
        command = command[0];
        //Nicht ideal weil ja nicht ein Strang, aber funktioniert so weit ganz gut (denke ich):
        //Checking whether a cafeteria has dinner and if its late enough to display the dinner menu
        if (command in dinner_dict && timestamp.getHours() >= 14){
            command = dinner_dict[command];
            var mensas = require('./mensas_abig.json');
            var t = 1;
        //Checking whether its a known cafeteria
        }else if (command in dict){
            command = dict[command];
            var mensas = require('./mensas.json');
            var t = 0;
        //...help/start, opening hours
        }

        if(command in openingh){
            resp = openingh[command];
        //Mensa
        }else if(command in mensas){

            //Weekend?
            if(timestamp.getDay() === 6 || timestamp.getDay() === 0){
                resp = "Heute haben leider alle Mensen geschlossen, sorry!";
            //If weekday, wanted information is formatted as follows:
            }else{
                resp = "*" + command + "*\n_Essen von " + mensas[command].hours.mealtime[t]["from"] +" bis " +mensas[command].hours.mealtime[t]["to"] + " Uhr_\n\n";
                for (var meal in mensas[command]["meals"]){
                    var description = "";
                    for (i in mensas[command]["meals"][meal]["description"]){
                        description += mensas[command]["meals"][meal]["description"][i]+ " " ;
                        if (i === "0"){
                            description += "\n";
                        }
                    }
                    resp += "*" +mensas[command]["meals"][meal]["label"] + " (" + mensas[command]["meals"][meal]["prices"]["student"]+ "/" +mensas[command]["meals"][meal]["prices"]["staff"] +  "/" + mensas[command]["meals"][meal]["prices"]["extern"]+"):*\n" + description + "\n";
                }
            }
        }
}

    messagesToSend.push({chatId:chatId, message:resp, options:{parse_mode: 'Markdown'}});

    fs.appendFile('logs/handled_requests.log', separator + timestamp + '\n\n' + JSON.stringify(msg,null,2) + '\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\nRESPONSE:\n\n' + resp + '\n', function (err) {
        console.log(err);
    });

    return messagesToSend;
}
module.exports.processOnText = processOnText;
<commit_msg>added case no menu<commit_after>var fs = require('fs');
var separator = '############################################################################\n';
var respId = 0;
var variables = require('./variables');
var feedback_chatId = variables['feedback_chatId'];

function processOnText(msg, match) {
    var resp = null;
    var timestamp = new Date();
    var messagesToSend = [];
    var openingh = require('./openingh');
    var chatId = msg.chat.id;

    //Mensas, die Abendessen Haben
    var dinner_dict = {
        "poly" : "Mensa Polyterrasse",
        "pizzapasta" : "food market - pizza pasta"
    }

    //Übersetzt den einfacheren Befehl zum komplizierteren Mensanamen im JSON
    var dict = {
                "cliff" : "Clausiusbar",
                "haoyi" : "Woka",
                "poly" : "Mensa Polyterrasse",
                "foodlab" : "foodLAB",
                "clausiusbar" : "Clausiusbar",
                "asia" : "Clausiusbar",
                "fusion" : "FUSION meal",
                "woka" : "Woka",
                "tannenbar" : "Tannenbar",
                "trailer" : "Foodtrailer ETZ",
                "dozentenfoyer" : "Dozentenfoyer",
                "grill" : "food market - grill bbQ",
                "pizzapasta" : "food market - pizza pasta",
                "green" : "food market - green day",
        };

    console.log(msg);
    console.log(JSON.stringify(match));
    fs.appendFile('logs/requests.log', separator + timestamp + '\n\n' + JSON.stringify(msg) + '\n' + separator, function (err) {
        console.log(err);
    });
    //Feedback
    if(match[0].indexOf('/feedback') != -1 || match[0].indexOf('/respond') != -1) {
        if (match[0] === '/feedback'){
            resp = '*Feedback für Dummies:*\n/feedback <Deine Nachricht>';

        }else if(match[0].indexOf('/feedback')!=-1){
            respId=chatId;
            fs.appendFile('logs/feedback.log', separator + '\n\n' + timestamp + '\n\n' + JSON.stringify(msg) + '\n\n', function (err) {
                console.log(err);
            });
            resp = 'Vielen Dank für Dein Feedback!';

            messagesToSend.push({chatId:-106064170, message:'New feedback:\n\n' + JSON.stringify(msg)});
        }else if(match[0].indexOf('/respond') != -1){

            resp = match[0].split('respond');
            resp = resp[1];

            chatId = respId;
        }
    }else{
        //Chopping '@...' from the command if needed
        var command = match[1].split('@');
        command = command[0];
        //Nicht ideal weil ja nicht ein Strang, aber funktioniert so weit ganz gut (denke ich):
        //Checking whether a cafeteria has dinner and if its late enough to display the dinner menu
        if (command in dinner_dict && timestamp.getHours() >= 14){
            command = dinner_dict[command];
            var mensas = require('./mensas_abig.json');
            var t = 1;
        //Checking whether its a known cafeteria
        }else if (command in dict){
            command = dict[command];
            var mensas = require('./mensas.json');
            var t = 0;
        //...help/start, opening hours
        }

        if(command in openingh){
            resp = openingh[command];
        //Mensa
        }else if(command in mensas){

            //Weekend?
            if(timestamp.getDay() === 6 || timestamp.getDay() === 0){
                resp = "Heute haben leider alle Mensen geschlossen, sorry!";
            //If weekday, wanted information is formatted as follows:
            }else{
                if (mensas[command] != undefined){
                    resp = "*" + command + "*\n_Essen von " + mensas[command].hours.mealtime[t]["from"] +" bis " +mensas[command].hours.mealtime[t]["to"] + " Uhr_\n\n";
                    for (var meal in mensas[command]["meals"]){
                        var description = "";
                        for (i in mensas[command]["meals"][meal]["description"]){
                            description += mensas[command]["meals"][meal]["description"][i]+ " " ;
                            if (i === "0"){
                                description += "\n";
                            }
                        }
                        resp += "*" +mensas[command]["meals"][meal]["label"] + " (" + mensas[command]["meals"][meal]["prices"]["student"]+ "/" +mensas[command]["meals"][meal]["prices"]["staff"] +  "/" + mensas[command]["meals"][meal]["prices"]["extern"]+"):*\n" + description + "\n";
                    }
                }else{
                    resp = "Tut mir Leid, für diese Mensa ist momentan leider kein Menü verfügbar :(";
                }
            }
        }
}

    messagesToSend.push({chatId:chatId, message:resp, options:{parse_mode: 'Markdown'}});

    fs.appendFile('logs/handled_requests.log', separator + timestamp + '\n\n' + JSON.stringify(msg,null,2) + '\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\nRESPONSE:\n\n' + resp + '\n', function (err) {
        console.log(err);
    });

    return messagesToSend;
}
module.exports.processOnText = processOnText;
<|endoftext|>


<commit_before>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 */
var utils = require('../utils'),
	openTags = require('../parsers/open-tags'),
	strictTags = /span|script|meta/,
	Context = require('../context'),
	Template = require('../template');

// String Output Descriptor
function SOD() {
	this.attributes = '';
	this.classes = '';
	this.children = '';
	this.style = '';
}

function tagOutput(descriptor, innerDescriptor, name) {
	var out = '<' + name + innerDescriptor.attributes;
	if (innerDescriptor.style)
		out += ' style="' + innerDescriptor.style + '"';
	if (innerDescriptor.classes)
		out += ' class="' + innerDescriptor.classes + '"';
	if (innerDescriptor.children)
		descriptor.children += out + '>' + innerDescriptor.children + '</' + name + '>';
	else if (openTags.test(name))
		descriptor.children += out + '>';
	else if (strictTags.test(name))
		descriptor.children += out + '></' + name + '>';
	else
		descriptor.children += out + '/>';
}
utils.tagOutput = tagOutput;

var methods = {
	SOD: SOD,
	//_________________________________ local context management
	newContext: function(context, descriptor, args) {
		var data = args[0],
			parent = args[1] || context,
			path = args[2];
		descriptor.context = new Context(data, parent, path);
	},
	//_________________________________________ EACH
	each: function(context, descriptor, args) {
		var path = args[0],
			values = (typeof path === 'string') ? context.get(path) : path;
		if (values && values.length) {
			var template = args[1];
			for (var i = 0, len = values.length; i < len; ++i)
				template.toHTMLString(new Context(values[i], context), descriptor);
		} else if (args[2])
			args[2].toHTMLString(context, descriptor);
	},
	eachTemplates: function(context, descriptor, args) {
		var templates = args[0],
			handler = args[1];
		templates.forEach(function(templ) {
			(handler ? handler(templ) : templ).toHTMLString(context, descriptor);
		});
	},
	// ____________________________________ WITH
	with: function(context, descriptor, args) {
		var path = args[0],
			template = args[1];
		var ctx = new Context(typeof path === 'string' ? context.get(path) : path, context, path);
		template.toHTMLString(ctx, descriptor, container);
	},
	//______________________________________________
	mountIf: function(context, descriptor, args) {
		var ok, condition = args[0],
			successTempl = args[1],
			failTempl = args[2];
		if (condition && condition.__interpolable__)
			ok = condition.output(context);
		else if (typeof condition === 'function')
			ok = condition.call(this, context);
		var sod = new SOD();
		if (ok)
			successTempl.toHTMLString(context, sod);
		else if (failTempl)
			failTempl.toHTMLString(context, sod);
		if (sod.children)
			descriptor.children += sod.children;
	},
	//______________________________________________
	if: function(context, descriptor, args) {
		var ok, condition = args[0],
			successTempl = args[1],
			failTempl = args[2];
		if (condition && condition.__interpolable__)
			ok = condition.output(context);
		else if (typeof condition === 'function')
			ok = condition.call(this, context);
		if (ok)
			successTempl.toHTMLString(context, descriptor);
		else if (failTempl)
			failTempl.toHTMLString(context, descriptor);
	},
	switch: function(context, descriptor, args) {
		var xpr = args[0],
			dico = args[1],
			value = xpr.output(context),
			templ = dico[value] || dico['default'];
		if (templ) {
			var sod = new SOD();
			templ.toHTMLString(context, sod);
			if (sod.children)
				descriptor.children += sod.children;
		}
	},
	//________________________________ TAGS
	tag: function(context, descriptor, originalArgs) {
		var name = originalArgs[0],
			template = originalArgs[1];
		var newDescriptor = new SOD();
		template.toHTMLString(context, newDescriptor);
		tagOutput(descriptor, newDescriptor, name);
	},
	text: function(context, descriptor, args) {
		var value = args[0];
		descriptor.children += value.__interpolable__ ? value.output(context) : value;
	},
	br: function(context, descriptor) {
		descriptor.children += '
';
	},
	//______________________________________________ ATTRIBUTES
	attr: function(context, descriptor, args) {
		var name = args[0],
			value = args[1];
		descriptor.attributes += ' ' + name + (value ? descriptor.attributes += '="' + (value.__interpolable__ ? value.output(context) : value) + '"' : '');
	},
	disabled: function(context, descriptor, args) {
		var value = args[0];
		if (value === undefined || context.get(value))
			descriptor.attributes += ' disabled';
	},
	val: function(context, descriptor, args) {
		var path = args[0],
			value = args[1];
		descriptor.attributes += ' value="' + (value.__interpolable__ ? value.output(context) : value) + '"';
	},
	contentEditable: function(context, descriptor, args) {
		var value = args[1];
		descriptor.attributes += ' contenteditable';
		descriptor.children = value.output(context);
	},
	setClass: function(context, descriptor, args) {
		var name = args[0],
			flag = args[1];
		if ((flag.__interpolable__ && flag.output(context)) || flag)
			descriptor.classes += ' ' + (name.__interpolable__ ? name.output(context) : name);
	},
	css: function(context, descriptor, args) {
		var prop = args[0],
			value = args[1];
		descriptor.style += prop + ':' + (value.__interpolable__ ? value.output(context) : value);
	},
	visible: function(context, descriptor, args) {
		var flag = args[0],
			val = flag.__interpolable__ ? flag.output(context) : flag;
		if (!val)
			descriptor.style += 'display:none;';
	},
	//_________________________________ EVENTS
	on: function() {},
	once: function() {},
	off: function() {},
	//_________________________________ CLIENT/SERVER
	client: function(context, descriptor, args) {
		if (context.env.data.isServer)
			return;
		args[0].toHTMLString(context, descriptor);
	},
	server: function(context, descriptor, args) {
		if (!context.env.data.isServer)
			return;
		args[0].toHTMLString(context, descriptor);
	},
	//_______________________________ SUSPEND RENDER
	suspendUntil: function(context, descriptor, args) {
		var xpr = args[0],
			index = args[1],
			templ = args[2],
			val = xpr.__interpolable__ ? xpr.output(context) : xpr,
			rest = new Template(templ._queue.slice(index));
		if (val)
			rest.toHTMLString(context, descriptor);
	},
	container: function(context, descriptor, args) {
		var sod = new SOD();
		args[0].toHTMLString(context, sod);
		descriptor.children += sod.children;
	}
};

View.prototype.toHTMLString = function(context, descriptor) {
	var sod = new SOD();
	Template.prototype.toHTMLString.call(this, context, sod);
	descriptor.children += sod.children;
	return descriptor.children;
};

Template.prototype.toHTMLString = function(context, descriptor) {
	context = context || new Context();
	descriptor = descriptor ||  new SOD();
	var handler = this._queue[0],
		index = 0,
		f;
	while (handler) {
		f = null;
		switch (handler.type) {
			case '*':
				f = methods[handler.handler];
				break;
			case 'string':
			case 'context':
				f = handler.handler;
				break;
			case 'custom':
				f = handler.handler.string;
				break;
		}
		if (!f) {
			handler = this._queue[++index];
			continue;
		}
		f(descriptor.context || context, descriptor, handler.args);
		if (handler.suspendAfter)
			break;
		handler = this._queue[++index];
	}
	return descriptor.children;
};

module.exports = methods;
<commit_msg>String output : remove View.toHTMLString<commit_after>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 */
var utils = require('../utils'),
	openTags = require('../parsers/open-tags'),
	strictTags = /span|script|meta/,
	Context = require('../context'),
	Template = require('../template');

// String Output Descriptor
function SOD() {
	this.attributes = '';
	this.classes = '';
	this.children = '';
	this.style = '';
}

function tagOutput(descriptor, innerDescriptor, name) {
	var out = '<' + name + innerDescriptor.attributes;
	if (innerDescriptor.style)
		out += ' style="' + innerDescriptor.style + '"';
	if (innerDescriptor.classes)
		out += ' class="' + innerDescriptor.classes + '"';
	if (innerDescriptor.children)
		descriptor.children += out + '>' + innerDescriptor.children + '</' + name + '>';
	else if (openTags.test(name))
		descriptor.children += out + '>';
	else if (strictTags.test(name))
		descriptor.children += out + '></' + name + '>';
	else
		descriptor.children += out + '/>';
}
utils.tagOutput = tagOutput;

var methods = {
	SOD: SOD,
	//_________________________________ local context management
	newContext: function(context, descriptor, args) {
		var data = args[0],
			parent = args[1] || context,
			path = args[2];
		descriptor.context = new Context(data, parent, path);
	},
	//_________________________________________ EACH
	each: function(context, descriptor, args) {
		var path = args[0],
			values = (typeof path === 'string') ? context.get(path) : path;
		if (values && values.length) {
			var template = args[1];
			for (var i = 0, len = values.length; i < len; ++i)
				template.toHTMLString(new Context(values[i], context), descriptor);
		} else if (args[2])
			args[2].toHTMLString(context, descriptor);
	},
	eachTemplates: function(context, descriptor, args) {
		var templates = args[0],
			handler = args[1];
		templates.forEach(function(templ) {
			(handler ? handler(templ) : templ).toHTMLString(context, descriptor);
		});
	},
	// ____________________________________ WITH
	with: function(context, descriptor, args) {
		var path = args[0],
			template = args[1];
		var ctx = new Context(typeof path === 'string' ? context.get(path) : path, context, path);
		template.toHTMLString(ctx, descriptor, container);
	},
	//______________________________________________
	mountIf: function(context, descriptor, args) {
		var ok, condition = args[0],
			successTempl = args[1],
			failTempl = args[2];
		if (condition && condition.__interpolable__)
			ok = condition.output(context);
		else if (typeof condition === 'function')
			ok = condition.call(this, context);
		var sod = new SOD();
		if (ok)
			successTempl.toHTMLString(context, sod);
		else if (failTempl)
			failTempl.toHTMLString(context, sod);
		if (sod.children)
			descriptor.children += sod.children;
	},
	//______________________________________________
	if: function(context, descriptor, args) {
		var ok, condition = args[0],
			successTempl = args[1],
			failTempl = args[2];
		if (condition && condition.__interpolable__)
			ok = condition.output(context);
		else if (typeof condition === 'function')
			ok = condition.call(this, context);
		if (ok)
			successTempl.toHTMLString(context, descriptor);
		else if (failTempl)
			failTempl.toHTMLString(context, descriptor);
	},
	switch: function(context, descriptor, args) {
		var xpr = args[0],
			dico = args[1],
			value = xpr.output(context),
			templ = dico[value] || dico['default'];
		if (templ) {
			var sod = new SOD();
			templ.toHTMLString(context, sod);
			if (sod.children)
				descriptor.children += sod.children;
		}
	},
	//________________________________ TAGS
	tag: function(context, descriptor, originalArgs) {
		var name = originalArgs[0],
			template = originalArgs[1];
		var newDescriptor = new SOD();
		template.toHTMLString(context, newDescriptor);
		tagOutput(descriptor, newDescriptor, name);
	},
	text: function(context, descriptor, args) {
		var value = args[0];
		descriptor.children += value.__interpolable__ ? value.output(context) : value;
	},
	br: function(context, descriptor) {
		descriptor.children += '
';
	},
	//______________________________________________ ATTRIBUTES
	attr: function(context, descriptor, args) {
		var name = args[0],
			value = args[1];
		descriptor.attributes += ' ' + name + (value ? descriptor.attributes += '="' + (value.__interpolable__ ? value.output(context) : value) + '"' : '');
	},
	disabled: function(context, descriptor, args) {
		var value = args[0];
		if (value === undefined || context.get(value))
			descriptor.attributes += ' disabled';
	},
	val: function(context, descriptor, args) {
		var path = args[0],
			value = args[1];
		descriptor.attributes += ' value="' + (value.__interpolable__ ? value.output(context) : value) + '"';
	},
	contentEditable: function(context, descriptor, args) {
		var value = args[1];
		descriptor.attributes += ' contenteditable';
		descriptor.children = value.output(context);
	},
	setClass: function(context, descriptor, args) {
		var name = args[0],
			flag = args[1];
		if ((flag.__interpolable__ && flag.output(context)) || flag)
			descriptor.classes += ' ' + (name.__interpolable__ ? name.output(context) : name);
	},
	css: function(context, descriptor, args) {
		var prop = args[0],
			value = args[1];
		descriptor.style += prop + ':' + (value.__interpolable__ ? value.output(context) : value);
	},
	visible: function(context, descriptor, args) {
		var flag = args[0],
			val = flag.__interpolable__ ? flag.output(context) : flag;
		if (!val)
			descriptor.style += 'display:none;';
	},
	//_________________________________ EVENTS
	on: function() {},
	once: function() {},
	off: function() {},
	//_________________________________ CLIENT/SERVER
	client: function(context, descriptor, args) {
		if (context.env.data.isServer)
			return;
		args[0].toHTMLString(context, descriptor);
	},
	server: function(context, descriptor, args) {
		if (!context.env.data.isServer)
			return;
		args[0].toHTMLString(context, descriptor);
	},
	//_______________________________ SUSPEND RENDER
	suspendUntil: function(context, descriptor, args) {
		var xpr = args[0],
			index = args[1],
			templ = args[2],
			val = xpr.__interpolable__ ? xpr.output(context) : xpr,
			rest = new Template(templ._queue.slice(index));
		if (val)
			rest.toHTMLString(context, descriptor);
	},
	container: function(context, descriptor, args) {
		var sod = new SOD();
		args[0].toHTMLString(context, sod);
		descriptor.children += sod.children;
	}
};

Template.prototype.toHTMLString = function(context, descriptor) {
	context = context || new Context();
	descriptor = descriptor ||  new SOD();
	var handler = this._queue[0],
		index = 0,
		f;
	while (handler) {
		f = null;
		switch (handler.type) {
			case '*':
				f = methods[handler.handler];
				break;
			case 'string':
			case 'context':
				f = handler.handler;
				break;
			case 'custom':
				f = handler.handler.string;
				break;
		}
		if (!f) {
			handler = this._queue[++index];
			continue;
		}
		f(descriptor.context || context, descriptor, handler.args);
		if (handler.suspendAfter)
			break;
		handler = this._queue[++index];
	}
	return descriptor.children;
};

module.exports = methods;
<|endoftext|>


<commit_before>module.exports = () => require('yargs')
    .alias('a', 'adress')
    .demandOption('a')
    .boolean('c')
    .alias('c', 'copy')
    .describe('c', 'Copy files to target directory')
    .implies('c', 't')
    .boolean('r')
    .alias('r', 'remove')
    .describe('r', 'Remove source files')
    .implies('r', 't')
    .boolean('l')
    .alias('l', 'links')
    .describe('l', 'Create links in place of source files')
    .implies('l', 't')
    .boolean('u')
    .alias('u', 'update')
    .describe('u', 'Update mode - use database contents to scan for files missing on filesystem')
    .boolean('x')
    .alias('x', 'skip-scan')
    .describe('x', 'Disables scanning filesystem - usefull in conjunction with --update')
    .string('t')
    .alias('t', 'target')
    .describe('t', 'Target directory')
    .array('p')
    .alias('p', 'paths')
    .describe('p', 'Paths to scan')
    .demandOption('p')
    .help('h')
    .argv
<commit_msg>Added mime option<commit_after>module.exports = () => require('yargs')
  .alias('a', 'adress')
  .demandOption('a')
  .boolean('c')
  .alias('c', 'copy')
  .describe('c', 'Copy files to target directory')
  .implies('c', 't')
  .boolean('r')
  .alias('r', 'remove')
  .describe('r', 'Remove source files')
  .implies('r', 't')
  .boolean('l')
  .alias('l', 'links')
  .describe('l', 'Create links in place of source files')
  .implies('l', 't')
  .boolean('u')
  .alias('u', 'update')
  .describe('u', 'Update mode - use database contents to scan for files missing on filesystem')
  .boolean('x')
  .alias('x', 'skip-scan')
  .describe('x', 'Disables scanning filesystem - usefull in conjunction with --update')
  .string('t')
  .alias('t', 'target')
  .describe('t', 'Target directory')
  .array('m')
  .alias('m', 'mime')
  .describe('m', 'Mime types to process')
  .default('m', ['image/**'])
  .array('p')
  .alias('p', 'paths')
  .describe('p', 'Paths to scan')
  .demandOption('p')
  .help('h')
  .argv
<|endoftext|>


<commit_before>Ti.include('lib/TiDomParser.js');
Ti.include('workitemForm.js');
Ti.include('httpclient.js');

function stripNamespace(obj) {
	if( typeof obj != "object") {
		return;
	}
	for(var key in obj) {
		stripNamespace(obj[key]);
		var tokens = key.split(':');
		if(tokens.length == 2) {
			obj[tokens[1]] = obj[key];
			delete obj[key];
		}
	}
}

var workitemListParser = new com.hamasyou.XML.TiDOMParser();
workitemListParser.force_array = ['form-data','user-select','executing-role','process-data-definition-detail:item','ns2:item','qfile','ns2:sub-data-def'];
var formResultParser = new com.hamasyou.XML.TiDOMParser();
formResultParser.force_array = ['error'];

var win = Ti.UI.currentWindow;
Titanium.UI.setBackgroundColor('#fff');

var view = Ti.UI.createTableView({
	minRowHeight: 40
});

/* workitem-form オブジェクト */
var workitem = null;
/* 各データ項目毎の WorkitemForm インスタンスの配列 */
var formItems = null;
var dialog = null;
/* 各データ項目毎の TableViewRow インスタンス */
var rowData = [];
/* submit ボタン */
var submitButtons = [];
/* インジケータ */
var activityIndicator = Titanium.UI.createActivityIndicator({
	style: Titanium.UI.iPhone.ActivityIndicatorStyle.DARK
});
win.add(view);
win.add(activityIndicator);

function refreshView() {
	view.setData(rowData);
}

function updateTable(client) {
	var obj = workitemListParser.dom2Json(client.responseXML);
	stripNamespace(obj);
	workitem = obj['workitem-form'];
	rowData = [];
	formItems = [];
	var deferRendering = false;
	if(workitem['form-data']) {
		for(var i=0; i<workitem['form-data'].length; i++) {
			var formData = workitem['form-data'][i];
			var formItem = WorkitemForm.createForm(formData);
			var row = formItem.getRow();
			formItems.push(formItem);
			rowData.push(row);
			deferRendering |= formItem.deferRendering;
			if(formItem.deferRendering) {
				formItem.onRender = function() {
					refreshView();
				};
			}
		}
	}
	submitButtons = [];
	if(workitem['user-selects'] && workitem['user-selects']['user-select']) {
		var userselects = workitem['user-selects']['user-select'];
		for(var j=0; j<userselects.length; j++) {
			submitButtons.push(userselects[j]);
		}
	} else {
		submitButtons.push({name: 'タスク終了'});
	}
	view.setData(rowData);
	setTimeout(function(){
		view.setData(rowData);
	}, 100);
    activityIndicator.hide();
}

function update() {
	var contextRoot = Ti.App.Properties.getString('url');
    activityIndicator.show();
    HttpClient.send({
            url: contextRoot + 'API/PE/Workitem/Form/viewXml',
            parameters: [['workitemId', win.workitemId ]],
            success: updateTable,
            indicator: activityIndicator
    });
}

function showSubmitErrorDialog(result) {
	var message = '';
	var errors;
	if(result['process-data-validation-errors'] && result['process-data-validation-errors'].error) {
		errors = result['process-data-validation-errors'].error;
		for(var i=0; i<errors.length; i++) {
			for(var j=0; j<formItems.length; j++) {
				if(errors[i].key.indexOf(formItems[j].paramPrefix,0) == 0) {
					if(message != '') {
						message += '\n';
					}
					message += workitem['form-data'][j].name + ": " + errors[i].detail;
					break;
				}
			}
		}
	}
	if(result.errors && result.errors.error) {
		errors = result.errors.error;
		for(var i=0; i<errors.length; i++) {
			if(message != '') {
				message += '\n';
			}
			message += errors[i].key + ": " + errors[i].detail;
		}
	}
	Ti.UI.createAlertDialog({
        title: 'エラー',
        message: message
    }).show();
}

/**
 * submit のレスポンス処理
 * @param client
 */
function receiveSubmit(client) {
	try {
		var result = formResultParser.dom2Json(client.responseXML).result;
		if(result.success == 'true') {
            Ti.UI.createAlertDialog({
                title: '完了しました',
                message: ''
            }).show();
            win.updateWorkitemList();
            win.close();
		} else {
			showSubmitErrorDialog(result);
		}
	} catch (e) {
		Ti.API.info("receiveSubmit error: " + JSON.stringify(e));
        Ti.UI.createAlertDialog({
            title: '不明エラー',
            message: e + client.responseText
        }).show();
	}
};

/**
 * submit のリクエスト発行
 * @param saveOnly
 * @param buttonIndex
 */
function submit(/* boolean */saveOnly, buttonIndex) {
    activityIndicator.show();
	var parameters = [['workitemId', win.workitemId ]];
	if(saveOnly) {
		parameters.push(['saveOnly', 'true']);
	} else {
		if(submitButtons[buttonIndex]['flow-id']) {
			parameters.push(['flow', submitButtons[buttonIndex]['flow-id']]);
		}
	}
	if(workitem['executing-roles'] && workitem['executing-roles']['executing-role']) {
		/* 複数ロールが選択できる場合、プライマリグループを自動選択する */
		parameters.push(['qgroupId', workitem['executing-roles']['executing-role'][0]['qgroup-id']]);
	}
	for(var i=0; i<formItems.length; i++) {
		formItems[i].appendParameter(parameters);
	}
	var contextRoot = Ti.App.Properties.getString('url');
    HttpClient.send({
            url: contextRoot + 'API/PE/Workitem/Form/save',
            parameters: parameters,
            success: receiveSubmit,
            indicator: activityIndicator
    });
};

/** タスク終了 */
var doneButton = Titanium.UI.createButton({title:'完了'});
doneButton.addEventListener('click', function(){
	var options = [];
	for(var i=0; i<submitButtons.length; i++) {
		options.push(submitButtons[i].name);
	}
	options.push('保存のみ');
	options.push('キャンセル');
	dialog = Titanium.UI.createOptionDialog({
		options: options,
		cancel: options.length-1
	});
	dialog.addEventListener('click', function(e) {
		if(e.cancel == e.index) {
			return;
		} else {
			submit((e.cancel-1) == e.index, e.index); // true if saveOnly
		}
	});
	dialog.show();
});
Ti.UI.currentWindow.rightNavButton = doneButton;

/** 項目編集 */
function updateItem(/* number */ index, newValue) {
	var formItem = formItems[index];
	if(formItem.applyValue(newValue)) {
		rowData[index] = formItem.getRow();
		view.setData(rowData);
	}
};

view.addEventListener('click', function(e) {
	var formItem = formItems[e.index];
	if(formItem.isWritable()) {
		var editWin = Titanium.UI.createWindow({
			title: formItem.formData.name
		});
		editWin.add(formItem.getEditorView(editWin, updateItem, e.index));
		Titanium.UI.currentTab.open(editWin, {animated:true});
	}
});

update();
<commit_msg>タスク完了・保存時にバリデーションエラーが出た場合、Activity Indicator が消えず継続して操作できなくなる問題の修正。<commit_after>Ti.include('lib/TiDomParser.js');
Ti.include('workitemForm.js');
Ti.include('httpclient.js');

function stripNamespace(obj) {
	if( typeof obj != "object") {
		return;
	}
	for(var key in obj) {
		stripNamespace(obj[key]);
		var tokens = key.split(':');
		if(tokens.length == 2) {
			obj[tokens[1]] = obj[key];
			delete obj[key];
		}
	}
}

var workitemListParser = new com.hamasyou.XML.TiDOMParser();
workitemListParser.force_array = ['form-data','user-select','executing-role','process-data-definition-detail:item','ns2:item','qfile','ns2:sub-data-def'];
var formResultParser = new com.hamasyou.XML.TiDOMParser();
formResultParser.force_array = ['error'];

var win = Ti.UI.currentWindow;
Titanium.UI.setBackgroundColor('#fff');

var view = Ti.UI.createTableView({
	minRowHeight: 40
});

/* workitem-form オブジェクト */
var workitem = null;
/* 各データ項目毎の WorkitemForm インスタンスの配列 */
var formItems = null;
var dialog = null;
/* 各データ項目毎の TableViewRow インスタンス */
var rowData = [];
/* submit ボタン */
var submitButtons = [];
/* インジケータ */
var activityIndicator = Titanium.UI.createActivityIndicator({
	style: Titanium.UI.iPhone.ActivityIndicatorStyle.DARK
});
win.add(view);
win.add(activityIndicator);

function refreshView() {
	view.setData(rowData);
}

function updateTable(client) {
	var obj = workitemListParser.dom2Json(client.responseXML);
	stripNamespace(obj);
	workitem = obj['workitem-form'];
	rowData = [];
	formItems = [];
	var deferRendering = false;
	if(workitem['form-data']) {
		for(var i=0; i<workitem['form-data'].length; i++) {
			var formData = workitem['form-data'][i];
			var formItem = WorkitemForm.createForm(formData);
			var row = formItem.getRow();
			formItems.push(formItem);
			rowData.push(row);
			deferRendering |= formItem.deferRendering;
			if(formItem.deferRendering) {
				formItem.onRender = function() {
					refreshView();
				};
			}
		}
	}
	submitButtons = [];
	if(workitem['user-selects'] && workitem['user-selects']['user-select']) {
		var userselects = workitem['user-selects']['user-select'];
		for(var j=0; j<userselects.length; j++) {
			submitButtons.push(userselects[j]);
		}
	} else {
		submitButtons.push({name: 'タスク終了'});
	}
	view.setData(rowData);
	setTimeout(function(){
		view.setData(rowData);
	}, 100);
    activityIndicator.hide();
}

function update() {
	var contextRoot = Ti.App.Properties.getString('url');
    activityIndicator.show();
    HttpClient.send({
            url: contextRoot + 'API/PE/Workitem/Form/viewXml',
            parameters: [['workitemId', win.workitemId ]],
            success: updateTable,
            indicator: activityIndicator
    });
}

function showSubmitErrorDialog(result) {
	var message = '';
	var errors;
	if(result['process-data-validation-errors'] && result['process-data-validation-errors'].error) {
		errors = result['process-data-validation-errors'].error;
		for(var i=0; i<errors.length; i++) {
			for(var j=0; j<formItems.length; j++) {
				if(errors[i].key.indexOf(formItems[j].paramPrefix,0) == 0) {
					if(message != '') {
						message += '\n';
					}
					message += workitem['form-data'][j].name + ": " + errors[i].detail;
					break;
				}
			}
		}
	}
	if(result.errors && result.errors.error) {
		errors = result.errors.error;
		for(var i=0; i<errors.length; i++) {
			if(message != '') {
				message += '\n';
			}
			message += errors[i].key + ": " + errors[i].detail;
		}
	}
	Ti.UI.createAlertDialog({
        title: 'エラー',
        message: message
    }).show();
}

/**
 * submit のレスポンス処理
 * @param client
 */
function receiveSubmit(client) {
	activityIndicator.hide();
	try {
		var result = formResultParser.dom2Json(client.responseXML).result;
		if(result.success == 'true') {
            Ti.UI.createAlertDialog({
                title: '完了しました',
                message: ''
            }).show();
            win.updateWorkitemList();
            win.close();
		} else {
			showSubmitErrorDialog(result);
		}
	} catch (e) {
		Ti.API.info("receiveSubmit error: " + JSON.stringify(e));
        Ti.UI.createAlertDialog({
            title: '不明エラー',
            message: e + client.responseText
        }).show();
	}
};

/**
 * submit のリクエスト発行
 * @param saveOnly
 * @param buttonIndex
 */
function submit(/* boolean */saveOnly, buttonIndex) {
    activityIndicator.show();
	var parameters = [['workitemId', win.workitemId ]];
	if(saveOnly) {
		parameters.push(['saveOnly', 'true']);
	} else {
		if(submitButtons[buttonIndex]['flow-id']) {
			parameters.push(['flow', submitButtons[buttonIndex]['flow-id']]);
		}
	}
	if(workitem['executing-roles'] && workitem['executing-roles']['executing-role']) {
		/* 複数ロールが選択できる場合、プライマリグループを自動選択する */
		parameters.push(['qgroupId', workitem['executing-roles']['executing-role'][0]['qgroup-id']]);
	}
	for(var i=0; i<formItems.length; i++) {
		formItems[i].appendParameter(parameters);
	}
	var contextRoot = Ti.App.Properties.getString('url');
    HttpClient.send({
            url: contextRoot + 'API/PE/Workitem/Form/save',
            parameters: parameters,
            success: receiveSubmit,
            indicator: activityIndicator
    });
};

/** タスク終了 */
var doneButton = Titanium.UI.createButton({title:'完了'});
doneButton.addEventListener('click', function(){
	var options = [];
	for(var i=0; i<submitButtons.length; i++) {
		options.push(submitButtons[i].name);
	}
	options.push('保存のみ');
	options.push('キャンセル');
	dialog = Titanium.UI.createOptionDialog({
		options: options,
		cancel: options.length-1
	});
	dialog.addEventListener('click', function(e) {
		if(e.cancel == e.index) {
			return;
		} else {
			submit((e.cancel-1) == e.index, e.index); // true if saveOnly
		}
	});
	dialog.show();
});
Ti.UI.currentWindow.rightNavButton = doneButton;

/** 項目編集 */
function updateItem(/* number */ index, newValue) {
	var formItem = formItems[index];
	if(formItem.applyValue(newValue)) {
		rowData[index] = formItem.getRow();
		view.setData(rowData);
	}
};

view.addEventListener('click', function(e) {
	var formItem = formItems[e.index];
	if(formItem.isWritable()) {
		var editWin = Titanium.UI.createWindow({
			title: formItem.formData.name
		});
		editWin.add(formItem.getEditorView(editWin, updateItem, e.index));
		Titanium.UI.currentTab.open(editWin, {animated:true});
	}
});

update();
<|endoftext|>


<commit_before>import { Base } from "./base";
import { return_type, argument_list, unescape } from "./helpers";

export class CallbackFunction extends Base {
  /**
   * @param {import("../tokeniser.js").Tokeniser} tokeniser
   */
  static parse(tokeniser, base) {
    const tokens = { base };
    const ret = new CallbackFunction({ source: tokeniser.source, tokens });
    tokens.name = tokeniser.consume("identifier") || tokeniser.error("Callback lacks a name");
    tokeniser.current = ret;
    tokens.assign = tokeniser.consume("=") || tokeniser.error("Callback lacks an assignment");
    ret.idlType = return_type(tokeniser) || tokeniser.error("Callback lacks a return type");
    tokens.open = tokeniser.consume("(") || tokeniser.error("Callback lacks parentheses for arguments");
    ret.arguments = argument_list(tokeniser);
    tokens.close = tokeniser.consume(")") || tokeniser.error("Unterminated callback");
    tokens.termination = tokeniser.consume(";") || tokeniser.error("Unterminated callback, expected `;`");
    return ret;
  }

  get type() {
    return "callback";
  }
  get name() {
    return unescape(this.tokens.name.value);
  }
}
<commit_msg>fix: add missing file extensions (#377)<commit_after>import { Base } from "./base.js";
import { return_type, argument_list, unescape } from "./helpers.js";

export class CallbackFunction extends Base {
  /**
   * @param {import("../tokeniser.js").Tokeniser} tokeniser
   */
  static parse(tokeniser, base) {
    const tokens = { base };
    const ret = new CallbackFunction({ source: tokeniser.source, tokens });
    tokens.name = tokeniser.consume("identifier") || tokeniser.error("Callback lacks a name");
    tokeniser.current = ret;
    tokens.assign = tokeniser.consume("=") || tokeniser.error("Callback lacks an assignment");
    ret.idlType = return_type(tokeniser) || tokeniser.error("Callback lacks a return type");
    tokens.open = tokeniser.consume("(") || tokeniser.error("Callback lacks parentheses for arguments");
    ret.arguments = argument_list(tokeniser);
    tokens.close = tokeniser.consume(")") || tokeniser.error("Unterminated callback");
    tokens.termination = tokeniser.consume(";") || tokeniser.error("Unterminated callback, expected `;`");
    return ret;
  }

  get type() {
    return "callback";
  }
  get name() {
    return unescape(this.tokens.name.value);
  }
}
<|endoftext|>


<commit_before>const defaultConfig = require('./default-config')
const generateAssignedTo = require('./generate-assigned-to')
const { comment } = require('./templates')

// We already have an instance of handlebars from Probot's hbs dependency

module.exports = async context => {
  const { data: diff } = await context.github.pullRequests.get(context.issue({
    headers: { Accept: 'application/vnd.github.diff' }
  }))
  const config = await context.config('config.yml')
  const cfg = config && config.todo ? {...defaultConfig, ...config.todo} : defaultConfig

  const keywords = Array.isArray(cfg.keyword) ? cfg.keyword : [cfg.keyword]
  const reg = new RegExp(`^diff --git a/.+ b/(.+)[\\s\\S]+^@@ -?(\\d+).+[\\r\\n]([\\s\\S]+(^(\\+).*(${keywords.join('|')})(?:[:-\\s]+)?(.*))[\\s\\S]+)(^diff --git)?`, 'gm')

  let match
  while ((match = reg.exec(diff)) !== null) {
    context.log('Match found')
    const {
      1: filename,
      3: contents,
      4: matchedLine,
      5: prefix,
      6: keyword,
      7: title
    } = match

    // TODO: Check if comment already exists

    const lineNumber = parseInt(match[2])

    context.log({ filename, lineNumber, matchedLine, prefix, keyword, title })

    const split = contents.substring(0, contents.indexOf(matchedLine)).split(/(?:\r\n|\n)/g)
    const start = lineNumber + split.length

    const { sha, user } = context.payload.pull_request.head
    const { number } = context.payload.pull_request

    const assignedToString = generateAssignedTo(cfg.autoAssign, user.login, number)
    const body = comment(context.repo({
      title,
      sha,
      assignedToString,
      number,
      start,
      filename,
      keyword
    }))

    return context.github.issues.createComment(context.issue({ body }))
  }
}
<commit_msg>Check for existing comments<commit_after>const defaultConfig = require('./default-config')
const generateAssignedTo = require('./generate-assigned-to')
const { comment } = require('./templates')

module.exports = async context => {
  const { data: diff } = await context.github.pullRequests.get(context.issue({
    headers: { Accept: 'application/vnd.github.diff' }
  }))
  const config = await context.config('config.yml')
  const cfg = config && config.todo ? {...defaultConfig, ...config.todo} : defaultConfig

  const keywords = Array.isArray(cfg.keyword) ? cfg.keyword : [cfg.keyword]
  const reg = new RegExp(`^diff --git a/.+ b/(.+)[\\s\\S]+^@@ -?(\\d+).+[\\r\\n]([\\s\\S]+(^(\\+).*(${keywords.join('|')})(?:[:-\\s]+)?(.*))[\\s\\S]+)(^diff --git)?`, 'gm')

  const comments = await context.github.issues.getComments(context.issue({}))

  let match
  while ((match = reg.exec(diff)) !== null) {
    context.log('Match found')
    const {
      1: filename,
      3: contents,
      4: matchedLine,
      5: prefix,
      6: keyword,
      7: title
    } = match

    // This PR already has a comment for this item
    if (comments.data.some(c => c.body.startsWith(`## ${title}`))) {
      context.log(`Comment with title [${title}] already exists`)
      return
    }

    const lineNumber = parseInt(match[2])

    context.log({ filename, lineNumber, matchedLine, prefix, keyword, title })

    const split = contents.substring(0, contents.indexOf(matchedLine)).split(/(?:\r\n|\n)/g)
    const start = lineNumber + split.length

    const { sha, user } = context.payload.pull_request.head
    const { number } = context.payload.pull_request

    const assignedToString = generateAssignedTo(cfg.autoAssign, user.login, number)
    const body = comment(context.repo({
      title,
      sha,
      assignedToString,
      number,
      start,
      filename,
      keyword
    }))

    return context.github.issues.createComment(context.issue({ body }))
  }
}
<|endoftext|>


<commit_before>var fs = require("fs");
var PythonShell = require('python-shell');
var mongodb = require('../data/mongodb');
var method = require('../data/stock_method');
var methodSchema = method.Method;

exports.stockholm = function(req, res) {
	res.render('stockholm.ejs', {
		currPage : 'stock',
		host : req.protocol + '://' + req.get('host')
	});
}

exports.loadData = function(req, res) {
	var targetDate = null;
	var query = require('url').parse(req.url, true).query;
	if (query.targetDate != null && query.targetDate.length > 0) {
		targetDate = query.targetDate;
	}
	var dirname = getUserHome() + "/tmp/stockholm_export";
	var dateArray = [];
	fs.readdir(dirname, function(err, files) {
		if (files != null) {
			var isDateValid = false;
			files.forEach(function(file) {
				if (file.indexOf("result_") >= 0) {
					var date = file.substr(7, 10);
					dateArray.push(date);
					if (date == targetDate) {
						isDateValid = true;
					}
				}
			});
			if (targetDate == null || targetDate == "") {
				targetDate = dateArray[dateArray.length - 1];
				isDateValid = true;
			}
			var resultJSON = {
				"res" : [],
				"targetDate" : targetDate
			};
			if (isDateValid) {
				files.forEach(function(file) {
					if (file.indexOf(targetDate) >= 0) {
						var filepath = dirname + "/" + file;
						fs.readFile(filepath, function(error, fileData) {
							if (error) {
								console.log(error);
							}
							var data = JSON.parse(fileData);

							data.forEach(function(item, index) {
								if ("Data" in item && item.Data.length > 0) {
									for ( var key in item.Data[0]) {
										item[key] = item.Data[0][key];
									}
								}
								item["Date"] = targetDate;
							});

							resultJSON.res = data;
							res.send(resultJSON);
						});
					}
				});
			} else {
				res.send(resultJSON);
			}
		}
	});
}

exports.loadDates = function(req, res) {
	var dirname = getUserHome() + "/tmp/stockholm_export";
	var dateArray = [];
	fs.readdir(dirname, function(err, files) {
		if (files != null) {
			files.forEach(function(file) {
				if (file.indexOf("result_") >= 0) {
					var date = file.substr(7, 10);
					var dateObj = {};
					dateObj['date_str'] = date;
					dateArray.push(dateObj);
				}
			});
			var resultJSON = {
				"res" : dateArray
			};
			res.send(resultJSON);
		}
	});
}

exports.runTest = function(req, res) {
	var resultJSON = {
		"status" : "Successful",
		"msg" : "回测执行完毕..."
	};

	var options = {
		mode : 'text',
		pythonPath : 'python3.4',
		args : [ '--reload=N', '--portfolio=Y', '--testfile=mongodb', '--dbname=datanium' ],
		scriptPath : '/Users/Puffy/git/stockholm/stockholm'
	// scriptPath : '/opt/datanium/stockholm_codebase/stockholm'
	};
	// console.log(options);

	PythonShell.run('main.py', options, function(err, results) {
		if (err) {
			resultJSON = {
				"status" : "Failed",
				"msg" : "回测执行失败..."
			};
		}
		// console.log(results);
		console.log('script execution is completed...');
		res.send(resultJSON);
	});
}

exports.loadMethods = function(req, res) {
	var query = require('url').parse(req.url, true).query;
	var findObj = {};
	if (query.id != null && query.id.length > 0) {
		findObj = {
			"method_id" : query.id
		};
	}
	methodSchema.find(findObj, function(err, doc) {
		if (err) {
			console.log('Exception: ' + err);
		}
		var methodObjArray = [];
		doc.forEach(function(rec) {
			var methodObj = {
				'method_id' : rec.method_id,
				'name' : rec.name,
				'desc' : rec.desc,
				'method' : rec.method,
				'user_id' : rec.user_id,
				'user_name' : rec.user_name,
				'creation_date' : rec.creation_date,
				'modification_date' : rec.modification_date
			};
			methodObjArray.push(methodObj);
		});
		var resultJSON = {
			"status" : "Successful",
			"res" : methodObjArray
		};
		res.send(resultJSON);
	});
}

exports.saveMethod = function(req, res) {
	var query = require('url').parse(req.url, true).query;
	var methodObj = req.body;
	var date = new Date();
	if (methodObj.method_id != null && methodObj.method_id != '') {
		console.log('Update Method ' + methodObj.name);
		methodSchema.findOne({
			method_id : methodObj.method_id
		}, function(err, mtd) {
			if (err)
				throw err;
			methodSchema.update({
				method_id : methodObj.method_id
			}, {
				'name' : methodObj.name,
				'desc' : methodObj.desc,
				'method' : methodObj.method,
				'modification_date' : date
			}, function(err, doc) {
				if (err) {
					res.send({
						success : false,
						msg : "保存出错..."
					});
					throw err;
				}
				res.send({
					success : true,
					msg : "保存成功..."
				});
			});
		});
	} else {
		console.log('Save New Method');
		var newMethod = new methodSchema({
			'name' : methodObj.name,
			'desc' : methodObj.desc,
			'method' : methodObj.method,
			'user_id' : 'dtnium@gmail.com',
			'user_name' : 'Stockholm',
			'creation_date' : date,
			'modification_date' : date
		});
		newMethod.save(function(err, doc) {
			if (err) {
				res.send({
					success : false,
					msg : "保存出错..."
				});
				throw err;
			}
			res.send({
				success : true,
				msg : "保存成功..."
			});
		});

	}
}

exports.removeMethod = function(req, res) {
	var query = require('url').parse(req.url, true).query;
	var findObj = {};
	if (query.id != null && query.id.length > 0) {
		methodSchema.remove({
			"method_id" : query.id
		}, function(err, doc) {
			var resultJSON = {
				"status" : "Success"
			};
			if (err) {
				console.log('Exception: ' + err);
				resultJSON = {
					"status" : "Failed"
				};
			}
			res.send(resultJSON);
		});
	} else {
		res.send({
			"status" : "Failed"
		});
	}
}

var getUserHome = function() {
	return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
}
<commit_msg>print err msg<commit_after>var fs = require("fs");
var PythonShell = require('python-shell');
var mongodb = require('../data/mongodb');
var method = require('../data/stock_method');
var methodSchema = method.Method;

exports.stockholm = function(req, res) {
	res.render('stockholm.ejs', {
		currPage : 'stock',
		host : req.protocol + '://' + req.get('host')
	});
}

exports.loadData = function(req, res) {
	var targetDate = null;
	var query = require('url').parse(req.url, true).query;
	if (query.targetDate != null && query.targetDate.length > 0) {
		targetDate = query.targetDate;
	}
	var dirname = getUserHome() + "/tmp/stockholm_export";
	var dateArray = [];
	fs.readdir(dirname, function(err, files) {
		if (files != null) {
			var isDateValid = false;
			files.forEach(function(file) {
				if (file.indexOf("result_") >= 0) {
					var date = file.substr(7, 10);
					dateArray.push(date);
					if (date == targetDate) {
						isDateValid = true;
					}
				}
			});
			if (targetDate == null || targetDate == "") {
				targetDate = dateArray[dateArray.length - 1];
				isDateValid = true;
			}
			var resultJSON = {
				"res" : [],
				"targetDate" : targetDate
			};
			if (isDateValid) {
				files.forEach(function(file) {
					if (file.indexOf(targetDate) >= 0) {
						var filepath = dirname + "/" + file;
						fs.readFile(filepath, function(error, fileData) {
							if (error) {
								console.log(error);
							}
							var data = JSON.parse(fileData);

							data.forEach(function(item, index) {
								if ("Data" in item && item.Data.length > 0) {
									for ( var key in item.Data[0]) {
										item[key] = item.Data[0][key];
									}
								}
								item["Date"] = targetDate;
							});

							resultJSON.res = data;
							res.send(resultJSON);
						});
					}
				});
			} else {
				res.send(resultJSON);
			}
		}
	});
}

exports.loadDates = function(req, res) {
	var dirname = getUserHome() + "/tmp/stockholm_export";
	var dateArray = [];
	fs.readdir(dirname, function(err, files) {
		if (files != null) {
			files.forEach(function(file) {
				if (file.indexOf("result_") >= 0) {
					var date = file.substr(7, 10);
					var dateObj = {};
					dateObj['date_str'] = date;
					dateArray.push(dateObj);
				}
			});
			var resultJSON = {
				"res" : dateArray
			};
			res.send(resultJSON);
		}
	});
}

exports.runTest = function(req, res) {
	var resultJSON = {
		"status" : "Successful",
		"msg" : "回测执行完毕..."
	};

	var options = {
		mode : 'text',
		pythonPath : 'python3.4',
		args : [ '--reload=N', '--portfolio=Y', '--testfile=mongodb', '--dbname=datanium' ],
		scriptPath : '/Users/Puffy/git/stockholm/stockholm'
	// scriptPath : '/opt/datanium/stockholm_codebase/stockholm'
	};
	// console.log(options);

	PythonShell.run('main.py', options, function(err, results) {
		if (err) {
			resultJSON = {
				"status" : "Failed",
				"msg" : "回测执行失败..."
			};
			console.log(err);
		}
		// console.log(results);
		console.log('script execution is completed...');
		res.send(resultJSON);
	});
}

exports.loadMethods = function(req, res) {
	var query = require('url').parse(req.url, true).query;
	var findObj = {};
	if (query.id != null && query.id.length > 0) {
		findObj = {
			"method_id" : query.id
		};
	}
	methodSchema.find(findObj, function(err, doc) {
		if (err) {
			console.log('Exception: ' + err);
		}
		var methodObjArray = [];
		doc.forEach(function(rec) {
			var methodObj = {
				'method_id' : rec.method_id,
				'name' : rec.name,
				'desc' : rec.desc,
				'method' : rec.method,
				'user_id' : rec.user_id,
				'user_name' : rec.user_name,
				'creation_date' : rec.creation_date,
				'modification_date' : rec.modification_date
			};
			methodObjArray.push(methodObj);
		});
		var resultJSON = {
			"status" : "Successful",
			"res" : methodObjArray
		};
		res.send(resultJSON);
	});
}

exports.saveMethod = function(req, res) {
	var query = require('url').parse(req.url, true).query;
	var methodObj = req.body;
	var date = new Date();
	if (methodObj.method_id != null && methodObj.method_id != '') {
		console.log('Update Method ' + methodObj.name);
		methodSchema.findOne({
			method_id : methodObj.method_id
		}, function(err, mtd) {
			if (err)
				throw err;
			methodSchema.update({
				method_id : methodObj.method_id
			}, {
				'name' : methodObj.name,
				'desc' : methodObj.desc,
				'method' : methodObj.method,
				'modification_date' : date
			}, function(err, doc) {
				if (err) {
					res.send({
						success : false,
						msg : "保存出错..."
					});
					throw err;
				}
				res.send({
					success : true,
					msg : "保存成功..."
				});
			});
		});
	} else {
		console.log('Save New Method');
		var newMethod = new methodSchema({
			'name' : methodObj.name,
			'desc' : methodObj.desc,
			'method' : methodObj.method,
			'user_id' : 'dtnium@gmail.com',
			'user_name' : 'Stockholm',
			'creation_date' : date,
			'modification_date' : date
		});
		newMethod.save(function(err, doc) {
			if (err) {
				res.send({
					success : false,
					msg : "保存出错..."
				});
				throw err;
			}
			res.send({
				success : true,
				msg : "保存成功..."
			});
		});

	}
}

exports.removeMethod = function(req, res) {
	var query = require('url').parse(req.url, true).query;
	var findObj = {};
	if (query.id != null && query.id.length > 0) {
		methodSchema.remove({
			"method_id" : query.id
		}, function(err, doc) {
			var resultJSON = {
				"status" : "Success"
			};
			if (err) {
				console.log('Exception: ' + err);
				resultJSON = {
					"status" : "Failed"
				};
			}
			res.send(resultJSON);
		});
	} else {
		res.send({
			"status" : "Failed"
		});
	}
}

var getUserHome = function() {
	return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
}
<|endoftext|>