<commit_before>console.log("[BoomRevEXT] Background.js")

function returnStorage () {
	chrome.storage.local.get(null,function (obj){
		chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
			chrome.tabs.sendMessage(tabs[0].id, obj, function(response) {
			console.log(response.farewell);
			});
		});
	});
}

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
    var respMsg={}
    respMsg.freeting=request.state
    console.log(request)
    if( request.state == "update" ){

    	chrome.storage.local.get(null,function (chromeObject){
    		console.log(chromeObject)
    		console.log(request);
    		for( sku in chromeObject.fetch ){
    			if( chromeObject.fetch[sku].srcSku == request.srcSku && chromeObject.fetch[sku].dstSku == request.dstSku ){
    				chromeObject.fetch[sku].verdict = request.verdict;
    				break;
    			}
    		}
    		console.log(chromeObject)
		chrome.storage.local.set(chromeObject,function (){
			console.log("Storage Hogayo update")
			chrome.storage.local.get(null,function (fetchObject){
				console.log(fetchObject)
			});
		});
    	});

    }else if ( request.state == "updating_from_src" ){
    	respMsg.status = "updating from src to Chrome Storage"
	/*
		store in chrome,
		send to valid UI,
		send to ###dst### pair
	*/
	chrome.storage.local.get(null,function (chromeObject){
		console.log("[BoomRevEXT] Action:"+request.state+" GET: Chrome Storage !!!"+JSON.stringify(chromeObject) );
		console.log(chromeObject)
		console.log(request);
		for( sku in chromeObject.fetch ){
			if( chromeObject.fetch[sku].srcSku == request.srcSku && chromeObject.fetch[sku].dstSku == request.dstSku ){
				chromeObject.fetch[sku].verdict = request.verdict;
				break;
			}
		}
		console.log(chromeObject)
		chrome.storage.local.set(chromeObject,function (){
			var boomrevWindowName = "BoomRevUI"
			var currentWindowName = "src_#_"+request.srcSku+"_#_dst_#_"+request.dstSku
			var toSendWindowName = "dst_#_"+request.dstSku+"_#_src_#_"+request.srcSku
			/*
				store in chrome = Done
				send to valid UI,
				send to ###dst### pair
			*/
			console.log("[BoomRevEXT] Action:"+request.state+" SET: Chrome Storage !!!"+JSON.stringify(chromeObject) );
			chrome.storage.local.get(null,function (chromeObject){
				console.log("[BoomRevEXT] Action:"+request.state+" Confirm-GET: Chrome Storage !!!"+JSON.stringify(chromeObject) );
				chrome.tabs.query({}, function(allTabs) {
					for (var iterTabs=0; iterTabs<allTabs.length; ++iterTabs) {
						//send to Validation UI

						request.state = "update_boomrev_ui";
						chrome.tabs.sendMessage(allTabs[iterTabs].id, request, function(response) {
							console.log("[BoomRevEXT] update_boomrev_ui "+JSON.stringify(response) );
						});

						request.state = "update_dst_window";
						chrome.tabs.sendMessage(allTabs[iterTabs].id, request, function(response) {
							console.log("[BoomRevEXT] update_dst_window "+JSON.stringify(response) );
						});

						// var codeToWork = "window.name+'_#_tabID_#_"+iterTabs+"';"
						// chrome.tabs.executeScript( allTabs[iterTabs].id, {code: codeToWork }, function(codeResult){
						// 	if( codeResult != undefined ){
						// 		var reqWindowName = codeResult[0].split("_#_tabID_#_")[0]
						// 		var reqTabID = parseInt(codeResult[0].split("_#_tabID_#_")[1])
						// 		console.log("[BoomRevEXT] window object for "+codeResult[0]+", winName: "+reqWindowName+", tabID: "+reqTabID);
						// 		if( reqWindowName.indexOf( boomrevWindowName ) >=0 ){
						// 			var requestToBeSent = jQuery.extend(true, {}, request);
						// 			requestToBeSent.state = "update_boomrev_ui";
						// 			console.log("[BoomRevEXT] sending update_boomrev_ui msg");
						// 			console.log(requestToBeSent)

						// 				// store in chrome = Done
						// 				// send to valid UI = Done
						// 				// send to ###dst### pair

						// 			chrome.tabs.sendMessage(allTabs[reqTabID].id, requestToBeSent, function(response) {
						// 				console.log(response);
						// 			});

						// 		}else if ( reqWindowName.indexOf( toSendWindowName ) >=0 ){
						// 			var requestToBeSent = jQuery.extend(true, {}, request);
						// 			requestToBeSent.state = "update_dst_window";
						// 			console.log("[BoomRevEXT] sending update_dst_window msg");
						// 			console.log(requestToBeSent)

						// 				// store in chrome = Done
						// 				// send to valid UI = Done
						// 				// send to ###dst### pair = Done

						// 			chrome.tabs.sendMessage(allTabs[reqTabID].id, requestToBeSent, function(response) {
						// 				console.log(response);
						// 			});
						// 		}else{
						// 			console.log("[BoomRevUI] nai mila for "+codeResult[0]+", winName: "+reqWindowName+", tabID: "+reqTabID+", dst req: "+toSendWindowName)
						// 		}
						// 			console.log("[BoomRevUI] wasdone??? "+codeResult[0]+", winName: "+reqWindowName+", tabID: "+reqTabID+", dst req: "+toSendWindowName)
						// 	}
						// } );
						// chrome.tabs.get(allTabs[iterTabs].id, function(tab){
						// 	chrome.windows.get(tab.windowId, function(win){
						// 		console.log("[BoomRevEXT] window object for "+tab.url)
						// 		console.log(win);
						// 	});
						// });
					}
				});
				chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
					console.log("[BoomRevEXT] Action:"+request.state+" sending request to verdictFetch !!!"+JSON.stringify(tabs) );
					chrome.tabs.sendMessage(tabs[0].id, request, function(response) {
					console.log(response.farewell);
					});
				});
				console.log(chromeObject)
			});
		});
	});

    }else if ( request.state == "updating_from_dst" ){
    	//store in chrome, send to valid UI, send to ###src### pair

    }else if( request.state == "clear"){

	chrome.storage.local.clear(function (){
		console.log("Storage Hogayo")
	});
    }else if( request.state == "create" ){
    	respMsg.status = "saving to Chrome Storage"
	/*############## Clearing Chrome Storage ##############*/
	chrome.storage.local.clear(function (){
		console.log("[BoomRevEXT] Action:"+request.state+" Chrome Storage Cleared !!!");
		/*############## Getting Chrome Storage ##############*/
		chrome.storage.local.get(null,function (fetchObject){
			console.log("[BoomRevEXT] Action:"+request.state+" Chrome Storage GET: "+JSON.stringify(fetchObject) );
			fetchObject.fetch = JSON.parse(JSON.stringify(request.skus))
			// console.log(fetchObject)
			/*############## Setting Chrome Storage ##############*/
			chrome.storage.local.set(fetchObject,function (){
				console.log("[BoomRevEXT] Action:"+request.state+" Chrome Storage SET: "+JSON.stringify(fetchObject) );
				/*############## Confirm-Getting Chrome Storage ##############*/
				chrome.storage.local.get(null,function (fetchObject){
					console.log("[BoomRevEXT] Action:"+request.state+" Chrome Storage Confirm-SET: "+JSON.stringify(fetchObject) );
					// console.log(fetchObject)
				});
			});
		});
	});

	// chrome.storage.local.get(null,function (fetchObject){
	// 	if( fetchObject.fetch == undefined ){
	// 		fetchObject.fetch=[];
	// 	}
	// 	fetchObject.fetch = JSON.parse(JSON.stringify(request.skus))
	// 	console.log(fetchObject)
	// 	chrome.storage.local.set(fetchObject,function (){
	// 		console.log("Storage Hogayo create")
	// 		chrome.storage.local.get(null,function (fetchObject){
	// 			console.log(fetchObject)
	// 		});
	// 	});
	// });

    }

	// chrome.storage.local.get(null,function (obj){
	// 	console.log(JSON.stringify(obj));
	// 	console.log(obj);
	// 	if(obj.expressions == undefined){
	// 		obj.expressions = {};
	// 		obj.expressions.hi = "Local Chrome Storage, "
	// 	}

	// 	obj.expressions.hi +=request.greeting+", ";

	// 	chrome.storage.local.set(obj,function (){
	// 		console.log("Storage Hogayo");
	// 	});
	// });
	sendResponse( respMsg );
  });
<commit_msg>[BoomRev] src-ui-dst paiing all done<commit_after>console.log("[BoomRevEXT] Background.js")

function returnStorage () {
	chrome.storage.local.get(null,function (obj){
		chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
			chrome.tabs.sendMessage(tabs[0].id, obj, function(response) {
			console.log(response.farewell);
			});
		});
	});
}

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
    var respMsg={}
    respMsg.freeting=request.state
    console.log(request)
    if( request.state == "update" ){

    	chrome.storage.local.get(null,function (chromeObject){
    		console.log(chromeObject)
    		console.log(request);
    		for( sku in chromeObject.fetch ){
    			if( chromeObject.fetch[sku].srcSku == request.srcSku && chromeObject.fetch[sku].dstSku == request.dstSku ){
    				chromeObject.fetch[sku].verdict = request.verdict;
    				break;
    			}
    		}
    		console.log(chromeObject)
		chrome.storage.local.set(chromeObject,function (){
			console.log("Storage Hogayo update")
			chrome.storage.local.get(null,function (fetchObject){
				console.log(fetchObject)
			});
		});
    	});

    }else if ( request.state == "updating_from_src" ){
    	respMsg.status = "updating from src to Chrome Storage"
	/*
		store in chrome,
		send to valid UI,
		send to ###dst### pair
	*/
	chrome.storage.local.get(null,function (chromeObject){
		console.log("[BoomRevEXT] Action:"+request.state+" GET: Chrome Storage !!!"+JSON.stringify(chromeObject) );
		console.log(chromeObject)
		console.log(request);
		for( sku in chromeObject.fetch ){
			if( chromeObject.fetch[sku].srcSku == request.srcSku && chromeObject.fetch[sku].dstSku == request.dstSku ){
				chromeObject.fetch[sku].verdict = request.verdict;
				break;
			}
		}
		console.log(chromeObject)
		chrome.storage.local.set(chromeObject,function (){
			var boomrevWindowName = "BoomRevUI"
			var currentWindowName = "src_#_"+request.srcSku+"_#_dst_#_"+request.dstSku
			var toSendWindowName = "dst_#_"+request.dstSku+"_#_src_#_"+request.srcSku
			/*
				store in chrome = Done
				send to valid UI,
				send to ###dst### pair
			*/
			console.log("[BoomRevEXT] Action:"+request.state+" SET: Chrome Storage !!!"+JSON.stringify(chromeObject) );
			chrome.storage.local.get(null,function (chromeObject){
				console.log("[BoomRevEXT] Action:"+request.state+" Confirm-GET: Chrome Storage !!!"+JSON.stringify(chromeObject) );
				chrome.tabs.query({}, function(allTabs) {
					for (var iterTabs=0; iterTabs<allTabs.length; ++iterTabs) {
						//send to Validation UI
						/*
							store in chrome = Done
							send to valid UI = Done
							send to ###dst### pair
						*/
						request.state = "update_boomrev_ui";
						chrome.tabs.sendMessage(allTabs[iterTabs].id, request, function(response) {
							console.log("[BoomRevEXT] update_boomrev_ui "+JSON.stringify(response) );
						});
						/*
							store in chrome = Done
							send to valid UI = Done
							send to ###dst### pair = Done
						*/
						request.state = "update_dst_window";
						chrome.tabs.sendMessage(allTabs[iterTabs].id, request, function(response) {
							console.log("[BoomRevEXT] update_dst_window "+JSON.stringify(response) );
						});

						// var codeToWork = "window.name+'_#_tabID_#_"+iterTabs+"';"
						// chrome.tabs.executeScript( allTabs[iterTabs].id, {code: codeToWork }, function(codeResult){
						// 	if( codeResult != undefined ){
						// 		var reqWindowName = codeResult[0].split("_#_tabID_#_")[0]
						// 		var reqTabID = parseInt(codeResult[0].split("_#_tabID_#_")[1])
						// 		console.log("[BoomRevEXT] window object for "+codeResult[0]+", winName: "+reqWindowName+", tabID: "+reqTabID);
						// 		if( reqWindowName.indexOf( boomrevWindowName ) >=0 ){
						// 			var requestToBeSent = jQuery.extend(true, {}, request);
						// 			requestToBeSent.state = "update_boomrev_ui";
						// 			console.log("[BoomRevEXT] sending update_boomrev_ui msg");
						// 			console.log(requestToBeSent)

						// 				// store in chrome = Done
						// 				// send to valid UI = Done
						// 				// send to ###dst### pair

						// 			chrome.tabs.sendMessage(allTabs[reqTabID].id, requestToBeSent, function(response) {
						// 				console.log(response);
						// 			});

						// 		}else if ( reqWindowName.indexOf( toSendWindowName ) >=0 ){
						// 			var requestToBeSent = jQuery.extend(true, {}, request);
						// 			requestToBeSent.state = "update_dst_window";
						// 			console.log("[BoomRevEXT] sending update_dst_window msg");
						// 			console.log(requestToBeSent)

						// 				// store in chrome = Done
						// 				// send to valid UI = Done
						// 				// send to ###dst### pair = Done

						// 			chrome.tabs.sendMessage(allTabs[reqTabID].id, requestToBeSent, function(response) {
						// 				console.log(response);
						// 			});
						// 		}else{
						// 			console.log("[BoomRevUI] nai mila for "+codeResult[0]+", winName: "+reqWindowName+", tabID: "+reqTabID+", dst req: "+toSendWindowName)
						// 		}
						// 			console.log("[BoomRevUI] wasdone??? "+codeResult[0]+", winName: "+reqWindowName+", tabID: "+reqTabID+", dst req: "+toSendWindowName)
						// 	}
						// } );
						// chrome.tabs.get(allTabs[iterTabs].id, function(tab){
						// 	chrome.windows.get(tab.windowId, function(win){
						// 		console.log("[BoomRevEXT] window object for "+tab.url)
						// 		console.log(win);
						// 	});
						// });
					}
				});
				// chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
				// 	console.log("[BoomRevEXT] Action:"+request.state+" sending request to verdictFetch !!!"+JSON.stringify(tabs) );
				// 	chrome.tabs.sendMessage(tabs[0].id, request, function(response) {
				// 	console.log(response.farewell);
				// 	});
				// });
				console.log(chromeObject)
			});
		});
	});

    }else if ( request.state == "updating_from_dst" ){
    	//store in chrome, send to valid UI, send to ###src### pair
	respMsg.status = "updating from src to Chrome Storage"
	/*
		store in chrome,
		send to valid UI,
		send to ###dst### pair
	*/
	chrome.storage.local.get(null,function (chromeObject){
		console.log("[BoomRevEXT] Action:"+request.state+" GET: Chrome Storage !!!"+JSON.stringify(chromeObject) );
		console.log(chromeObject)
		console.log(request);
		for( sku in chromeObject.fetch ){
			if( chromeObject.fetch[sku].srcSku == request.srcSku && chromeObject.fetch[sku].dstSku == request.dstSku ){
				chromeObject.fetch[sku].verdict = request.verdict;
				break;
			}
		}
		console.log(chromeObject)
		chrome.storage.local.set(chromeObject,function (){
			var boomrevWindowName = "BoomRevUI"
			var toSendWindowName = "src_#_"+request.srcSku+"_#_dst_#_"+request.dstSku
			var currentWindowName = "dst_#_"+request.dstSku+"_#_src_#_"+request.srcSku
			/*
				store in chrome = Done
				send to valid UI,
				send to ###src### pair
			*/
			console.log("[BoomRevEXT] Action:"+request.state+" SET: Chrome Storage !!!"+JSON.stringify(chromeObject) );
			chrome.storage.local.get(null,function (chromeObject){
				console.log("[BoomRevEXT] Action:"+request.state+" Confirm-GET: Chrome Storage !!!"+JSON.stringify(chromeObject) );
				chrome.tabs.query({}, function(allTabs) {
					for (var iterTabs=0; iterTabs<allTabs.length; ++iterTabs) {
						//send to Validation UI
						/*
							store in chrome = Done
							send to valid UI = Done
							send to ###src### pair
						*/
						request.state = "update_boomrev_ui";
						chrome.tabs.sendMessage(allTabs[iterTabs].id, request, function(response) {
							console.log("[BoomRevEXT] update_boomrev_ui "+JSON.stringify(response) );
						});
						/*
							store in chrome = Done
							send to valid UI = Done
							send to ###src### pair = Done
						*/
						request.state = "update_src_window";
						chrome.tabs.sendMessage(allTabs[iterTabs].id, request, function(response) {
							console.log("[BoomRevEXT] update_dst_window "+JSON.stringify(response) );
						});
					}
				});
				console.log(chromeObject)
			});
		});
	});

    }else if( request.state == "clear"){

	chrome.storage.local.clear(function (){
		console.log("Storage Hogayo")
	});
    }else if( request.state == "create" ){
    	respMsg.status = "saving to Chrome Storage"
	/*############## Clearing Chrome Storage ##############*/
	chrome.storage.local.clear(function (){
		console.log("[BoomRevEXT] Action:"+request.state+" Chrome Storage Cleared !!!");
		/*############## Getting Chrome Storage ##############*/
		chrome.storage.local.get(null,function (fetchObject){
			console.log("[BoomRevEXT] Action:"+request.state+" Chrome Storage GET: "+JSON.stringify(fetchObject) );
			fetchObject.fetch = JSON.parse(JSON.stringify(request.skus))
			// console.log(fetchObject)
			/*############## Setting Chrome Storage ##############*/
			chrome.storage.local.set(fetchObject,function (){
				console.log("[BoomRevEXT] Action:"+request.state+" Chrome Storage SET: "+JSON.stringify(fetchObject) );
				/*############## Confirm-Getting Chrome Storage ##############*/
				chrome.storage.local.get(null,function (fetchObject){
					console.log("[BoomRevEXT] Action:"+request.state+" Chrome Storage Confirm-SET: "+JSON.stringify(fetchObject) );
					// console.log(fetchObject)
				});
			});
		});
	});

	// chrome.storage.local.get(null,function (fetchObject){
	// 	if( fetchObject.fetch == undefined ){
	// 		fetchObject.fetch=[];
	// 	}
	// 	fetchObject.fetch = JSON.parse(JSON.stringify(request.skus))
	// 	console.log(fetchObject)
	// 	chrome.storage.local.set(fetchObject,function (){
	// 		console.log("Storage Hogayo create")
	// 		chrome.storage.local.get(null,function (fetchObject){
	// 			console.log(fetchObject)
	// 		});
	// 	});
	// });

    }

	// chrome.storage.local.get(null,function (obj){
	// 	console.log(JSON.stringify(obj));
	// 	console.log(obj);
	// 	if(obj.expressions == undefined){
	// 		obj.expressions = {};
	// 		obj.expressions.hi = "Local Chrome Storage, "
	// 	}

	// 	obj.expressions.hi +=request.greeting+", ";

	// 	chrome.storage.local.set(obj,function (){
	// 		console.log("Storage Hogayo");
	// 	});
	// });
	sendResponse( respMsg );
  });
<|endoftext|>


<commit_before>'use strict';

var mano     = require('mano')
  , gm       = require('./gm')
  , path     = require('path')
  , unlink   = require('fs2/unlink')
  , contains = require('es5-ext/string/#/contains')
  , deferred = require('deferred')

  , resolve = path.resolve
  , extname = path.extname
  , uploadsPath = mano.uploadsPath;

module.exports = function (file) {
	var path        = uploadsPath
	  , previewPath = file.path
	  , processPath = file.path
	  , extension   = extname(file.path)
	  , thumbPath   = file.path.slice(0, -extension.length) + '.thumb' + extension
	  , thumb, preview, processFullPath, thumbFullPath, previewFullPath;

	if (file.type !== 'image/jpeg') {
		thumbPath += '.jpg';
		previewPath += '.jpg';
	}
	if (file.type === 'application/pdf') {
		processPath += '[0]';
	}

	processFullPath = resolve(path, processPath);
	thumbFullPath = resolve(path, thumbPath);
	thumb = gm(processFullPath).density(300, 300).resize(500, 500).writeP(thumbFullPath);

	if (file.path !== previewPath) {
		previewFullPath = resolve(path, previewPath);
		preview = gm(processFullPath).density(300, 300).resize(1500, 1500).writeP(previewFullPath);
	}

	return deferred(thumb, preview)(function () {
		if (!file.path) {
			return deferred(unlink(thumbFullPath), preview && unlink(previewFullPath));
		}

		file.thumb.path = thumbPath;
		if (preview) {
			file.generatedPreview.path = previewPath;
		} else {
			file.isPreviewGenerated = false;
		}
	}, function (e) {
		if (!file.path && contains.call(e.message, 'Unable to open file')) {
			return deferred(unlink(thumbFullPath), preview && unlink(previewFullPath))(null, false);
		}
		throw e;
	});
};
<commit_msg>Issue #640. Don't enlarge images for preview.<commit_after>'use strict';

var mano     = require('mano')
  , gm       = require('./gm')
  , path     = require('path')
  , unlink   = require('fs2/unlink')
  , contains = require('es5-ext/string/#/contains')
  , deferred = require('deferred')

  , resolve = path.resolve
  , extname = path.extname
  , uploadsPath = mano.uploadsPath;

module.exports = function (file) {
	var path        = uploadsPath
	  , previewPath = file.path
	  , processPath = file.path
	  , extension   = extname(file.path)
	  , thumbPath   = file.path.slice(0, -extension.length) + '.thumb' + extension
	  , thumb, preview, processFullPath, thumbFullPath, previewFullPath;

	if (file.type !== 'image/jpeg') {
		thumbPath += '.jpg';
		previewPath += '.jpg';
	}
	if (file.type === 'application/pdf') {
		processPath += '[0]';
	}

	processFullPath = resolve(path, processPath);
	thumbFullPath = resolve(path, thumbPath);
	thumb = gm(processFullPath).density(300, 300).resize(500, 500, '>').writeP(thumbFullPath);

	if (file.path !== previewPath) {
		previewFullPath = resolve(path, previewPath);
		preview = gm(processFullPath).density(300, 300).resize(1500, 1500, '>').writeP(previewFullPath);
	}

	return deferred(thumb, preview)(function () {
		if (!file.path) {
			return deferred(unlink(thumbFullPath), preview && unlink(previewFullPath));
		}

		file.thumb.path = thumbPath;
		if (preview) {
			file.generatedPreview.path = previewPath;
		} else {
			file.isPreviewGenerated = false;
		}
	}, function (e) {
		if (!file.path && contains.call(e.message, 'Unable to open file')) {
			return deferred(unlink(thumbFullPath), preview && unlink(previewFullPath))(null, false);
		}
		throw e;
	});
};
<|endoftext|>


<commit_before>import {Parser, Lexer, ChangeDetector} from 'change_detection/change_detection';

import {bootstrap, Component, Template, TemplateConfig, ViewPort, Compiler} from 'core/core';

import {CompilerCache} from 'core/compiler/compiler';
import {DirectiveMetadataReader} from 'core/compiler/directive_metadata_reader';
import {TemplateLoader} from 'core/compiler/template_loader';
import {LifeCycle} from 'core/life_cycle/life_cycle';

import {reflector} from 'reflection/reflection';
import {DOM, document, window, Element} from 'facade/dom';
import {isPresent} from 'facade/lang';

var MAX_DEPTH = 9;

function setupReflector() {
  // TODO: Put the general calls to reflector.register... in a shared file
  // as they are needed in all benchmarks...

  reflector.registerType(AppComponent, {
    'factory': () => new AppComponent(),
    'parameters': [],
    'annotations' : [new Component({
      selector: 'app',
      template: new TemplateConfig({
        directives: [TreeComponent],
        inline: `<tree [data]='initData'></tree>`
      })
    })]
  });

  reflector.registerType(TreeComponent, {
    'factory': () => new TreeComponent(),
    'parameters': [],
    'annotations' : [new Component({
      selector: 'tree',
      bind: {
        'data': 'data'
      },
      template: new TemplateConfig({
          directives: [TreeComponent, NgIf],
          inline: `
     {{data.value}}
       <tree [data]='data.left'></tree>
       <tree [data]='data.right'></tree>
    `
      })
    })]
  });

  reflector.registerType(NgIf, {
    'factory': (vp) => new NgIf(vp),
    'parameters': [[ViewPort]],
    'annotations' : [new Template({
      selector: '[ng-if]',
      bind: {
        'ng-if': 'ngIf'
      }
    })]
  });

  reflector.registerType(Compiler, {
    'factory': (templateLoader, reader, parser, compilerCache) => new Compiler(templateLoader, reader, parser, compilerCache),
    'parameters': [[TemplateLoader], [DirectiveMetadataReader], [Parser], [CompilerCache]],
    'annotations': []
  });

  reflector.registerType(CompilerCache, {
    'factory': () => new CompilerCache(),
    'parameters': [],
    'annotations': []
  });

  reflector.registerType(Parser, {
    'factory': (lexer) => new Parser(lexer),
    'parameters': [[Lexer]],
    'annotations': []
  });

  reflector.registerType(TemplateLoader, {
    'factory': () => new TemplateLoader(),
    'parameters': [],
    'annotations': []
  });

  reflector.registerType(DirectiveMetadataReader, {
    'factory': () => new DirectiveMetadataReader(),
    'parameters': [],
    'annotations': []
  });

  reflector.registerType(Lexer, {
    'factory': () => new Lexer(),
    'parameters': [],
    'annotations': []
  });

  reflector.registerType(LifeCycle, {
    "factory": (cd) => new LifeCycle(cd),
    "parameters": [[ChangeDetector]],
    "annotations": []
  });

  reflector.registerGetters({
    'value': (a) => a.value,
    'left': (a) => a.left,
    'right': (a) => a.right,
    'initData': (a) => a.initData,
    'data': (a) => a.data
  });

  reflector.registerSetters({
    'value': (a,v) => a.value = v,
    'left': (a,v) => a.left = v,
    'right': (a,v) => a.right = v,
    'initData': (a,v) => a.initData = v,
    'data': (a,v) => a.data = v,
    'ngIf': (a,v) => a.ngIf = v
  });
}

export function main() {
  setupReflector();

  var app;
  var changeDetector;
  var baselineRootTreeComponent;
  var count = 0;

  function ng2DestroyDom(_) {
    // TODO: We need an initial value as otherwise the getter for data.value will fail
    // --> this should be already caught in change detection!
    app.initData = new TreeNode('', null, null);
    changeDetector.detectChanges();
  }

  function profile(create, destroy, name) {
    return function(_) {
      window.console.profile(name);
      var duration = 0;
      var downCount = 200;
      var count = 0;
      while(downCount--) {
        var start = window.performance.now();
        create(_);
        duration += window.performance.now() - start;
        destroy(_);
        count++;
      }
      window.console.profileEnd(name);
      window.console.log(`Iterations: ${count}; time: ${duration / count} ms / iteration`);
    };
  }

  function ng2CreateDom(_) {
    var values = count++ % 2 == 0 ?
      ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*'] :
      ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', '-'];

    app.initData = buildTree(MAX_DEPTH, values, 0);
    changeDetector.detectChanges();
  }

  function noop() {}

  function initNg2() {
    bootstrap(AppComponent).then((injector) => {
      changeDetector = injector.get(ChangeDetector);
      app = injector.get(AppComponent);
      DOM.on(DOM.querySelector(document, '#ng2DestroyDom'), 'click', ng2DestroyDom);
      DOM.on(DOM.querySelector(document, '#ng2CreateDom'), 'click', ng2CreateDom);
      DOM.on(DOM.querySelector(document, '#ng2UpdateDomProfile'), 'click', profile(ng2CreateDom, noop, 'ng2-update'));
      DOM.on(DOM.querySelector(document, '#ng2CreateDomProfile'), 'click', profile(ng2CreateDom, ng2DestroyDom, 'ng2-create'));
    });
  }

  function baselineDestroyDom(_) {
    baselineRootTreeComponent.update(new TreeNode('', null, null));
  }

  function baselineCreateDom(_) {
    var values = count++ % 2 == 0 ?
      ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*'] :
      ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', '-'];

    baselineRootTreeComponent.update(buildTree(MAX_DEPTH, values, 0));
  }

  function initBaseline() {
    baselineRootTreeComponent = new BaseLineTreeComponent();
    DOM.appendChild(DOM.querySelector(document, 'baseline'), baselineRootTreeComponent.element);
    DOM.on(DOM.querySelector(document, '#baselineDestroyDom'), 'click', baselineDestroyDom);
    DOM.on(DOM.querySelector(document, '#baselineCreateDom'), 'click', baselineCreateDom);
    DOM.on(DOM.querySelector(document, '#baselineUpdateDomProfile'), 'click', profile(baselineCreateDom, noop, 'baseline-update'));
    DOM.on(DOM.querySelector(document, '#baselineCreateDomProfile'), 'click', profile(baselineCreateDom, baselineDestroyDom, 'baseline-create'));
  }

  initNg2();
  initBaseline();
}

class TreeNode {
  value:string;
  left:TreeNode;
  right:TreeNode;
  constructor(value, left, right) {
    this.value = value;
    this.left = left;
    this.right = right;
  }
}

function buildTree(maxDepth, values, curDepth) {
  if (maxDepth === curDepth) return new TreeNode('', null, null);
  return new TreeNode(
      values[curDepth],
      buildTree(maxDepth, values, curDepth+1),
      buildTree(maxDepth, values, curDepth+1));
}

var BASELINE_TEMPLATE = DOM.createTemplate(
    '_<template class="ng-binding"></template><template class="ng-binding"></template>');
// http://jsperf.com/nextsibling-vs-childnodes

class BaseLineTreeComponent {
  element:Element;
  value:BaseLineInterpolation;
  left:BaseLineIf;
  right:BaseLineIf;
  constructor() {
    this.element = DOM.createElement('span');
    var clone = DOM.clone(BASELINE_TEMPLATE.content.firstChild);
    var shadowRoot = this.element.createShadowRoot();
    DOM.appendChild(shadowRoot, clone);

    var child = clone.firstChild;
    this.value = new BaseLineInterpolation(child);
    child = DOM.nextSibling(child);
    this.left = new BaseLineIf(child);
    child = DOM.nextSibling(child);
    this.right = new BaseLineIf(child);
  }
  update(value:TreeNode) {
    this.value.update(value.value);
    this.left.update(value.left);
    this.right.update(value.right);
  }
}

class BaseLineInterpolation {
  value:string;
  textNode;
  constructor(textNode) {
    this.value = null;
    this.textNode = textNode;
  }
  update(value:string) {
    if (this.value !== value) {
      this.value = value;
      DOM.setText(this.textNode, value + ' ');
    }
  }
}

class BaseLineIf {
  condition:boolean;
  component:BaseLineTreeComponent;
  anchor:Element;
  constructor(anchor) {
    this.anchor = anchor;
    this.condition = false;
    this.component = null;
  }
  update(value:TreeNode) {
    var newCondition = isPresent(value);
    if (this.condition !== newCondition) {
      this.condition = newCondition;
      if (isPresent(this.component)) {
        this.component.element.remove();
        this.component = null;
      }
      if (this.condition) {
        this.component = new BaseLineTreeComponent();
        this.anchor.parentNode.insertBefore(this.component.element, this.anchor);
      }
    }
    if (isPresent(this.component)) {
      this.component.update(value);
    }
  }
}

class AppComponent {
  initData:TreeNode;
  constructor() {
    // TODO: We need an initial value as otherwise the getter for data.value will fail
    // --> this should be already caught in change detection!
    this.initData = new TreeNode('', null, null);
  }
}

// TODO: Move this into a reusable directive in the 'core' module!
class NgIf {
  _viewPort:ViewPort;
  constructor(viewPort:ViewPort) {
    this._viewPort = viewPort;
  }
  set ngIf(value:boolean) {
    if (this._viewPort.length > 0) {
      this._viewPort.remove(0);
    }
    if (value) {
      this._viewPort.create();
    }
  }
}

class TreeComponent {
  data:TreeNode;
}

<commit_msg>perf: Change baseline benchmark to be more consistent with the Angular<commit_after>import {Parser, Lexer, ChangeDetector} from 'change_detection/change_detection';

import {bootstrap, Component, Template, TemplateConfig, ViewPort, Compiler} from 'core/core';

import {CompilerCache} from 'core/compiler/compiler';
import {DirectiveMetadataReader} from 'core/compiler/directive_metadata_reader';
import {TemplateLoader} from 'core/compiler/template_loader';
import {LifeCycle} from 'core/life_cycle/life_cycle';

import {reflector} from 'reflection/reflection';
import {DOM, document, window, Element} from 'facade/dom';
import {isPresent} from 'facade/lang';

var MAX_DEPTH = 9;

function setupReflector() {
  // TODO: Put the general calls to reflector.register... in a shared file
  // as they are needed in all benchmarks...

  reflector.registerType(AppComponent, {
    'factory': () => new AppComponent(),
    'parameters': [],
    'annotations' : [new Component({
      selector: 'app',
      template: new TemplateConfig({
        directives: [TreeComponent],
        inline: `<tree [data]='initData'></tree>`
      })
    })]
  });

  reflector.registerType(TreeComponent, {
    'factory': () => new TreeComponent(),
    'parameters': [],
    'annotations' : [new Component({
      selector: 'tree',
      bind: {
        'data': 'data'
      },
      template: new TemplateConfig({
          directives: [TreeComponent, NgIf],
          inline: `
     {{data.value}}
       <tree [data]='data.right'></tree>
       <tree [data]='data.left'></tree>
    `
      })
    })]
  });

  reflector.registerType(NgIf, {
    'factory': (vp) => new NgIf(vp),
    'parameters': [[ViewPort]],
    'annotations' : [new Template({
      selector: '[ng-if]',
      bind: {
        'ng-if': 'ngIf'
      }
    })]
  });

  reflector.registerType(Compiler, {
    'factory': (templateLoader, reader, parser, compilerCache) => new Compiler(templateLoader, reader, parser, compilerCache),
    'parameters': [[TemplateLoader], [DirectiveMetadataReader], [Parser], [CompilerCache]],
    'annotations': []
  });

  reflector.registerType(CompilerCache, {
    'factory': () => new CompilerCache(),
    'parameters': [],
    'annotations': []
  });

  reflector.registerType(Parser, {
    'factory': (lexer) => new Parser(lexer),
    'parameters': [[Lexer]],
    'annotations': []
  });

  reflector.registerType(TemplateLoader, {
    'factory': () => new TemplateLoader(),
    'parameters': [],
    'annotations': []
  });

  reflector.registerType(DirectiveMetadataReader, {
    'factory': () => new DirectiveMetadataReader(),
    'parameters': [],
    'annotations': []
  });

  reflector.registerType(Lexer, {
    'factory': () => new Lexer(),
    'parameters': [],
    'annotations': []
  });

  reflector.registerType(LifeCycle, {
    "factory": (cd) => new LifeCycle(cd),
    "parameters": [[ChangeDetector]],
    "annotations": []
  });

  reflector.registerGetters({
    'value': (a) => a.value,
    'left': (a) => a.left,
    'right': (a) => a.right,
    'initData': (a) => a.initData,
    'data': (a) => a.data
  });

  reflector.registerSetters({
    'value': (a,v) => a.value = v,
    'left': (a,v) => a.left = v,
    'right': (a,v) => a.right = v,
    'initData': (a,v) => a.initData = v,
    'data': (a,v) => a.data = v,
    'ngIf': (a,v) => a.ngIf = v
  });
}

export function main() {
  setupReflector();

  var app;
  var changeDetector;
  var baselineRootTreeComponent;
  var count = 0;

  function ng2DestroyDom(_) {
    // TODO: We need an initial value as otherwise the getter for data.value will fail
    // --> this should be already caught in change detection!
    app.initData = new TreeNode('', null, null);
    changeDetector.detectChanges();
  }

  function profile(create, destroy, name) {
    return function(_) {
      window.console.profile(name);
      var duration = 0;
      var downCount = 200;
      var count = 0;
      while(downCount--) {
        var start = window.performance.now();
        create(_);
        duration += window.performance.now() - start;
        destroy(_);
        count++;
      }
      window.console.profileEnd(name);
      window.console.log(`Iterations: ${count}; time: ${duration / count} ms / iteration`);
    };
  }

  function ng2CreateDom(_) {
    var values = count++ % 2 == 0 ?
      ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*'] :
      ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', '-'];

    app.initData = buildTree(MAX_DEPTH, values, 0);
    changeDetector.detectChanges();
  }

  function noop() {}

  function initNg2() {
    bootstrap(AppComponent).then((injector) => {
      changeDetector = injector.get(ChangeDetector);
      app = injector.get(AppComponent);
      DOM.on(DOM.querySelector(document, '#ng2DestroyDom'), 'click', ng2DestroyDom);
      DOM.on(DOM.querySelector(document, '#ng2CreateDom'), 'click', ng2CreateDom);
      DOM.on(DOM.querySelector(document, '#ng2UpdateDomProfile'), 'click', profile(ng2CreateDom, noop, 'ng2-update'));
      DOM.on(DOM.querySelector(document, '#ng2CreateDomProfile'), 'click', profile(ng2CreateDom, ng2DestroyDom, 'ng2-create'));
    });
  }

  function baselineDestroyDom(_) {
    baselineRootTreeComponent.update(new TreeNode('', null, null));
  }

  function baselineCreateDom(_) {
    var values = count++ % 2 == 0 ?
      ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '*'] :
      ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', '-'];

    baselineRootTreeComponent.update(buildTree(MAX_DEPTH, values, 0));
  }

  function initBaseline() {
    var tree = DOM.createElement('tree');
    DOM.appendChild(DOM.querySelector(document, 'baseline'), tree);
    baselineRootTreeComponent = new BaseLineTreeComponent(tree);
    DOM.on(DOM.querySelector(document, '#baselineDestroyDom'), 'click', baselineDestroyDom);
    DOM.on(DOM.querySelector(document, '#baselineCreateDom'), 'click', baselineCreateDom);
    DOM.on(DOM.querySelector(document, '#baselineUpdateDomProfile'), 'click', profile(baselineCreateDom, noop, 'baseline-update'));
    DOM.on(DOM.querySelector(document, '#baselineCreateDomProfile'), 'click', profile(baselineCreateDom, baselineDestroyDom, 'baseline-create'));
  }

  initNg2();
  initBaseline();
}

class TreeNode {
  value:string;
  left:TreeNode;
  right:TreeNode;
  constructor(value, left, right) {
    this.value = value;
    this.left = left;
    this.right = right;
  }
}

function buildTree(maxDepth, values, curDepth) {
  if (maxDepth === curDepth) return new TreeNode('', null, null);
  return new TreeNode(
      values[curDepth],
      buildTree(maxDepth, values, curDepth+1),
      buildTree(maxDepth, values, curDepth+1));
}

var BASELINE_TREE_TEMPLATE = DOM.createTemplate(
    '_<template class="ng-binding"></template><template class="ng-binding"></template>');
var BASELINE_IF_TEMPLATE = DOM.createTemplate(
    '<tree></tree>');
// http://jsperf.com/nextsibling-vs-childnodes

class BaseLineTreeComponent {
  value:BaseLineInterpolation;
  left:BaseLineIf;
  right:BaseLineIf;
  constructor(element) {
    this.element = element;
    var clone = DOM.clone(BASELINE_TREE_TEMPLATE.content.firstChild);
    var shadowRoot = this.element.createShadowRoot();
    DOM.appendChild(shadowRoot, clone);

    var child = clone.firstChild;
    this.value = new BaseLineInterpolation(child);
    child = DOM.nextSibling(child);
    this.left = new BaseLineIf(child);
    child = DOM.nextSibling(child);
    this.right = new BaseLineIf(child);
  }
  update(value:TreeNode) {
    this.value.update(value.value);
    this.left.update(value.left);
    this.right.update(value.right);
  }
}

class BaseLineInterpolation {
  value:string;
  textNode;
  constructor(textNode) {
    this.value = null;
    this.textNode = textNode;
  }
  update(value:string) {
    if (this.value !== value) {
      this.value = value;
      DOM.setText(this.textNode, value + ' ');
    }
  }
}

class BaseLineIf {
  condition:boolean;
  component:BaseLineTreeComponent;
  anchor:Element;
  constructor(anchor) {
    this.anchor = anchor;
    this.condition = false;
    this.component = null;
  }
  update(value:TreeNode) {
    var newCondition = isPresent(value);
    if (this.condition !== newCondition) {
      this.condition = newCondition;
      if (isPresent(this.component)) {
        this.component.element.remove();
        this.component = null;
      }
      if (this.condition) {
        var element = DOM.clone(BASELINE_IF_TEMPLATE).content.firstChild;
        this.anchor.parentNode.insertBefore(element, this.anchor.nextSibling);
        this.component = new BaseLineTreeComponent(element.firstChild);
      }
    }
    if (isPresent(this.component)) {
      this.component.update(value);
    }
  }
}

class AppComponent {
  initData:TreeNode;
  constructor() {
    // TODO: We need an initial value as otherwise the getter for data.value will fail
    // --> this should be already caught in change detection!
    this.initData = new TreeNode('', null, null);
  }
}

// TODO: Move this into a reusable directive in the 'core' module!
class NgIf {
  _viewPort:ViewPort;
  constructor(viewPort:ViewPort) {
    this._viewPort = viewPort;
  }
  set ngIf(value:boolean) {
    if (this._viewPort.length > 0) {
      this._viewPort.remove(0);
    }
    if (value) {
      this._viewPort.create();
    }
  }
}

class TreeComponent {
  data:TreeNode;
}

<|endoftext|>


<commit_before>var backgroundObject = (function() {
	var maxConstant = 100;
	var colorMethod = 0;
	var twoColors, color, greenTints, greenScale, blueTints, blueScale, orangeTints, orangeScale, grayTints, grayScale;
	var firstRatioBegin, firstRatioEnd, SecondRatioBegin, SecondRatioEnd, ThirdRatioBegin, ThirdRatioEnd, firstEdgeBegin, firstEdgeEnd, SecondEdgeBegin, SecondEdgeEnd, ThridEdgeBegin, ThirdEdgeEnd;
	reloadColorScale();

	function reloadColorScale(){
		twoColors = [d3.rgb(colours.lightGreen()), d3.rgb(colours.darkRed())];
		color = d3.scale.linear().domain([0, maxConstant]).interpolate(d3.interpolateHcl).range(twoColors);
		greenTints = [d3.rgb(colours.lightGreen()), d3.rgb(colours.darkGreen())];
		greenScale = d3.scale.linear().domain([0, maxConstant]).interpolate(d3.interpolateHcl).range(greenTints);
		blueTints = [d3.rgb(colours.lightBlue()), d3.rgb(colours.darkBlue())];
		blueScale = d3.scale.linear().domain([0, maxConstant]).interpolate(d3.interpolateHcl).range(blueTints);
		orangeTints = [d3.rgb(colours.lightOrange()), d3.rgb(colours.darkOrange())];
		orangeScale = d3.scale.linear().domain([0, maxConstant]).interpolate(d3.interpolateHcl).range(orangeTints);
		grayTints = [d3.rgb(colours.grey()), d3.rgb(colours.grey())];
		grayScale =  d3.scale.linear().domain([0, 0]).interpolate(d3.interpolateHcl).range(grayTints);
	}
	/*
	 * Calculates the worst case of #warnings/loc
	 */
	function getRelativeWarnings() {
		var worstRatio = 0;
		for(var p =0; p < inputData.length; p++){
			var package = inputData[p];
			var classesArray = package.classes;
			for (i = 0; i < classesArray.length; i++) {
				classObjectJson = classesArray[i];
				var numberOfWarnings = 0;
				for (j = 0; j < classObjectJson.warningList.length; j++) {
					numberOfWarnings++;
		  		}
		  		var curRatio = numberOfWarnings / classObjectJson.loc;
		  		if(curRatio > worstRatio) {
		  			worstRatio = curRatio;
		  		}
			}
		}
		return (worstRatio * 100);
	}
	function getNormalColors() {
			return d3.scale.linear().domain([0, maxConstant]).interpolate(d3.interpolateHcl).range(twoColors);
	}
	function setToPercentages() {
		firstEdgeBegin = firstRatioBegin + "%";
		firstEdgeEnd = firstRatioEnd + "%";
		SecondEdgeBegin = SecondRatioBegin + "%";
		SecondEdgeEnd = SecondRatioEnd + "%";
		ThridEdgeBegin = ThridRatioBegin + "%";
		ThirdEdgeEnd = ThirdRatioEnd + "%";
	}
	function setGreenScale(gradient, start, end, weight) {
		gradient.append("stop")
			.attr("offset", start)
			.attr("stop-color", greenScale(weight*100))
			.attr("stop-opacity", 1);
		gradient.append("stop")
			.attr("offset", end)
			.attr("stop-color", greenScale(weight*100))
			.attr("stop-opacity", 1);
	}
	function setRedScale(gradient, start, end, weight) {
		gradient.append("stop")
			.attr("offset", start)
			.attr("stop-color", orangeScale(weight*100))
			.attr("stop-opacity", 1);
		gradient.append("stop")
			.attr("offset", end)
			.attr("stop-color", orangeScale(weight*100))
			.attr("stop-opacity", 1);
	}
	function setBlueScale(gradient, start, end, weight) {
		gradient.append("stop")
			.attr("offset", start)
			.attr("stop-color", blueScale(weight*100))
			.attr("stop-opacity", 1);
		gradient.append("stop")
			.attr("offset", end)
			.attr("stop-color", blueScale(weight*100))
			.attr("stop-opacity", 1);
	}
	function createGradientColours(gradient, onlyOneColour, whichOne, weight, ratioArray) {
		if(onlyOneColour) {
			switch(whichOne) {
				case 0:
					setGreenScale(gradient, "0%", "100%", weight);
					return gradient;
				case 1:
					setRedScale(gradient, "0%", "100%", weight);
					return gradient;
				case 2:
					setBlueScale(gradient, "0%", "100%", weight);
					return gradient;
				default:
					return gradient;
			}
		} else {
			if(ratioArray[0] == 0 && ratioArray[1] != 0 && ratioArray[2] != 0) {
				setRedScale(gradient, "0%", SecondEdgeEnd, weight);
				ThridEdgeBegin = (SecondRatioEnd + 0.01) + "%";
				setBlueScale(gradient, ThridEdgeBegin, "100%", weight);
			} else if(ratioArray[1] == 0 && ratioArray[0] != 0 && ratioArray[2] != 0) {
				setGreenScale(gradient, "0%", firstEdgeEnd, weight);
				ThridEdgeBegin = (firstRatioEnd + 0.01) + "%";
				setBlueScale(gradient, ThridEdgeBegin, "100%", weight);
			} else if(ratioArray[2] == 0 && ratioArray[1] != 0 && ratioArray[0] != 0) {
				setGreenScale(gradient, "0%", firstEdgeEnd, weight);
				SecondEdgeBegin = (firstRatioEnd + 0.01) + "%";
				setRedScale(gradient, SecondEdgeBegin, "100%", weight);
			} else {
				setGreenScale(gradient, "0%", firstEdgeEnd, weight)
				setRedScale(gradient, SecondEdgeBegin, SecondEdgeEnd, weight);
				setBlueScale(gradient, ThridEdgeBegin, "100%", weight);
			}
			return gradient;
		}
	}
	function calculateBackgroundGradient(svg,ratioArray,weight, id,x,y){
		var total = ratioArray[0] + ratioArray[1] + ratioArray[2];

		var tuple = gradientCalculator.calculate(x,y, ratioArray[0], ratioArray[1], ratioArray[2]);
		var tupleAngle = gradientCalculator.get45Angle(x,y);

		firstRatioBegin = 0;
		firstRatioEnd = tuple[0];
		SecondRatioBegin = firstRatioEnd + 0.01;
		SecondRatioEnd = tuple[1]
		ThridRatioBegin = SecondRatioEnd + 0.01;
		ThirdRatioEnd = 100;

		if(total == 0) {
			var gradient = svg.append("defs")
				.append("linearGradient")
				.attr("id", "gradient" + id)
				.attr("x1", "0%")
				.attr("y1", "0%")
				.attr("x2", "100%")
				.attr("y2", "0%")
				.attr("spreadMethod", "pad");
			gradient.append("stop")
				.attr("offset", "0%")
				.attr("stop-color", grayScale(0))
				.attr("stop-opacity", 1);
			gradient.append("stop")
				.attr("offset", "100%")
				.attr("stop-color",  grayScale(0))
				.attr("stop-opacity", 1);
			return gradient;
		} else {
			var gradient = svg.append("defs")
			  	.append("linearGradient")
				.attr("id", "gradient" + id)
				.attr("x1", "0%")
				.attr("y1", "0%")
				.attr("x2", "100%")
				.attr("y2", "100%")
				.attr("spreadMethod", "pad");
			if(ratioArray[0] == 100) {
				setToPercentages();
				return createGradientColours(gradient, true, 0, weight, ratioArray);
			} else if(ratioArray[1] == 100) {
				setToPercentages();
				return createGradientColours(gradient, true, 1, weight, ratioArray);
			} else if(ratioArray[2] == 100) {
				setToPercentages();
				return createGradientColours(gradient, true, 2, weight, ratioArray);
			} else {
				setToPercentages();
				return createGradientColours(gradient, false, -1, weight, ratioArray);
			}
		}
	}
	function checkIfNot0(number) {
		if(number == 0) {
			return 0.1;
		} else {
			return number;
		}
	}
	function calculateBackground(svg, weight, id){
		var currentColorScale = getNormalColors();
		var gradient = svg.append("defs")
			.append("linearGradient")
			.attr("id", "gradient" + id)
			.attr("x1", "0%")
			.attr("y1", "0%")
			.attr("x2", "100%")
			.attr("y2", "0%")
			.attr("spreadMethod", "pad");
		gradient.append("stop")
			.attr("offset", "0%")
			.attr("stop-color", currentColorScale(weight*100))
			.attr("stop-opacity", 1);
		return gradient;
	}
	return {
        getBackground: function(svg,ratioTuple,weight, id,x,y) {
			if ( weight > 1 ){ weight = 1;}
			switch(colorMethod) {
				case 0:
					return calculateBackground(svg, weight, id);
					break;
				case 1:
					return calculateBackgroundGradient(svg,ratioTuple[0],weight, id,x,y);
					break;
				case 2:
					return calculateBackgroundGradient(svg,ratioTuple[1],weight, id,x,y);
					break;
			}
		},
		setColorsRelative: function(){
			maxConstant = getRelativeWarnings();
			reloadColorScale();
		},
		setColorsAbsolute: function(){
			maxConstant = 100;
			reloadColorScale();
		},
		setColorMethod: function(index){
			colorMethod = index;
		},
		getRatios: function(d){
			ratioArrayASAT = [];
			var constant = 100;
			var warningsTotal = checkIfNot0(d.warnings);

            var ratioCheckStyle = Math.round(constant * d.warningsCheckStyle / warningsTotal);
			ratioArrayASAT.push(ratioCheckStyle);

            var ratiowarningsPMD = Math.round(constant * d.warningsPMD / warningsTotal);
			ratioArrayASAT.push(ratiowarningsPMD);

            var ratioFindBugs = Math.round(constant * d.warningsFindBugs / warningsTotal);
			ratioArrayASAT.push(ratioFindBugs);

			ratioArrayCategory = [];

            var ratioMaintainabilityDefects = Math.round(constant * d.warningsMaintainabilityDefects / warningsTotal);
			ratioArrayCategory.push(ratioMaintainabilityDefects);

            var ratioOtherDefects = Math.round(constant * d.warningsOtherDefects / warningsTotal);
			ratioArrayCategory.push(ratioOtherDefects);

			var ratioFunctionalDefects = Math.round(constant * d.warningsFunctionalDefects / warningsTotal);
			ratioArrayCategory.push(ratioFunctionalDefects);

			return [ratioArrayASAT,ratioArrayCategory]
		}
    }

}());<commit_msg>Refactored backgroundGradient.js<commit_after>var backgroundObject = (function() {
	var maxConstant = 100;
	var colorMethod = 0;
	var twoColors, color, greenTints, greenScale, blueTints, blueScale, orangeTints, orangeScale, grayTints, grayScale;
	var firstRatioBegin, firstRatioEnd, SecondRatioBegin, SecondRatioEnd, ThirdRatioBegin, ThirdRatioEnd, firstEdgeBegin, firstEdgeEnd, SecondEdgeBegin, SecondEdgeEnd, ThridEdgeBegin, ThirdEdgeEnd;
	reloadColorScale();

	/*
	 * Defines all different colour scales
	 */
	function reloadColorScale() {
		twoColors = [d3.rgb(colours.lightGreen()), d3.rgb(colours.darkRed())];
		color = d3.scale.linear().domain([0, maxConstant]).interpolate(d3.interpolateHcl).range(twoColors);
		greenTints = [d3.rgb(colours.lightGreen()), d3.rgb(colours.darkGreen())];
		greenScale = d3.scale.linear().domain([0, maxConstant]).interpolate(d3.interpolateHcl).range(greenTints);
		blueTints = [d3.rgb(colours.lightBlue()), d3.rgb(colours.darkBlue())];
		blueScale = d3.scale.linear().domain([0, maxConstant]).interpolate(d3.interpolateHcl).range(blueTints);
		orangeTints = [d3.rgb(colours.lightOrange()), d3.rgb(colours.darkOrange())];
		orangeScale = d3.scale.linear().domain([0, maxConstant]).interpolate(d3.interpolateHcl).range(orangeTints);
		grayTints = [d3.rgb(colours.grey()), d3.rgb(colours.grey())];
		grayScale =  d3.scale.linear().domain([0, 0]).interpolate(d3.interpolateHcl).range(grayTints);
	}
	/*
	 * Calculates the worst case of #warnings/loc
	 */
	function getRelativeWarnings() {
		var worstRatio = 0;
		for(var p =0; p < inputData.length; p++){
			var package = inputData[p];
			var classesArray = package.classes;
			for (i = 0; i < classesArray.length; i++) {
				classObjectJson = classesArray[i];
				var numberOfWarnings = 0;
				for (j = 0; j < classObjectJson.warningList.length; j++) {
					numberOfWarnings++;
		  		}
		  		var curRatio = numberOfWarnings / classObjectJson.loc;
		  		if(curRatio > worstRatio) {
		  			worstRatio = curRatio;
		  		}
			}
		}
		return (worstRatio * 100);
	}
	function getNormalColors() {
			return d3.scale.linear().domain([0, maxConstant]).interpolate(d3.interpolateHcl).range(twoColors);
	}
	function setToPercentages() {
		firstEdgeBegin = firstRatioBegin + "%";
		firstEdgeEnd = firstRatioEnd + "%";
		SecondEdgeBegin = SecondRatioBegin + "%";
		SecondEdgeEnd = SecondRatioEnd + "%";
		ThridEdgeBegin = ThridRatioBegin + "%";
		ThirdEdgeEnd = ThirdRatioEnd + "%";
	}
	function setGreenScale(gradient, start, end, weight) {
		gradient.append("stop")
			.attr("offset", start)
			.attr("stop-color", greenScale(weight*100))
			.attr("stop-opacity", 1);
		gradient.append("stop")
			.attr("offset", end)
			.attr("stop-color", greenScale(weight*100))
			.attr("stop-opacity", 1);
	}
	function setOrangeScale(gradient, start, end, weight) {
		gradient.append("stop")
			.attr("offset", start)
			.attr("stop-color", orangeScale(weight*100))
			.attr("stop-opacity", 1);
		gradient.append("stop")
			.attr("offset", end)
			.attr("stop-color", orangeScale(weight*100))
			.attr("stop-opacity", 1);
	}
	function setBlueScale(gradient, start, end, weight) {
		gradient.append("stop")
			.attr("offset", start)
			.attr("stop-color", blueScale(weight*100))
			.attr("stop-opacity", 1);
		gradient.append("stop")
			.attr("offset", end)
			.attr("stop-color", blueScale(weight*100))
			.attr("stop-opacity", 1);
	}
	function setNormalScale(gradient) {
		gradient.append("stop")
				.attr("offset", "0%")
				.attr("stop-color", grayScale(0))
				.attr("stop-opacity", 1);
			gradient.append("stop")
				.attr("offset", "100%")
				.attr("stop-color",  grayScale(0))
				.attr("stop-opacity", 1);
	}
	function createGradientColours(gradient, onlyOneColour, whichOne, weight, ratioArray) {
		if(onlyOneColour) {
			switch(whichOne) {
				case 0:
					setGreenScale(gradient, "0%", "100%", weight);
					return gradient;
				case 1:
					setOrangeScale(gradient, "0%", "100%", weight);
					return gradient;
				case 2:
					setBlueScale(gradient, "0%", "100%", weight);
					return gradient;
				default:
					return gradient;
			}
		} else {
			if(ratioArray[0] == 0 && ratioArray[1] != 0 && ratioArray[2] != 0) {
				setOrangeScale(gradient, "0%", SecondEdgeEnd, weight);
				ThridEdgeBegin = (SecondRatioEnd + 0.01) + "%";
				setBlueScale(gradient, ThridEdgeBegin, "100%", weight);
			} else if(ratioArray[1] == 0 && ratioArray[0] != 0 && ratioArray[2] != 0) {
				setGreenScale(gradient, "0%", firstEdgeEnd, weight);
				ThridEdgeBegin = (firstRatioEnd + 0.01) + "%";
				setBlueScale(gradient, ThridEdgeBegin, "100%", weight);
			} else if(ratioArray[2] == 0 && ratioArray[1] != 0 && ratioArray[0] != 0) {
				setGreenScale(gradient, "0%", firstEdgeEnd, weight);
				SecondEdgeBegin = (firstRatioEnd + 0.01) + "%";
				setOrangeScale(gradient, SecondEdgeBegin, "100%", weight);
			} else {
				setGreenScale(gradient, "0%", firstEdgeEnd, weight)
				setOrangeScale(gradient, SecondEdgeBegin, SecondEdgeEnd, weight);
				setBlueScale(gradient, ThridEdgeBegin, "100%", weight);
			}
			return gradient;
		}
	}
	function calculateBackgroundGradient(svg,ratioArray,weight, id,x,y) {
		var total = ratioArray[0] + ratioArray[1] + ratioArray[2];
		var tuple = gradientCalculator.calculate(x,y, ratioArray[0], ratioArray[1], ratioArray[2]);
		var tupleAngle = gradientCalculator.get45Angle(x,y);

		firstRatioBegin = 0;
		firstRatioEnd = tuple[0];
		SecondRatioBegin = firstRatioEnd + 0.01;
		SecondRatioEnd = tuple[1]
		ThridRatioBegin = SecondRatioEnd + 0.01;
		ThirdRatioEnd = 100;

		var y2 = "100%";
		if(total == 0) {
			y2 = "0%";
		}
		var gradient = svg.append("defs")
				.append("linearGradient")
				.attr("id", "gradient" + id)
				.attr("x1", "0%")
				.attr("y1", "0%")
				.attr("x2", "100%")
				.attr("y2", y2)
				.attr("spreadMethod", "pad");

		if(total == 0) {
			setNormalScale(gradient);
			return gradient;
		} else {
			setToPercentages();
			if(ratioArray[0] == 100) {
				return createGradientColours(gradient, true, 0, weight, ratioArray);
			} else if(ratioArray[1] == 100) {
				return createGradientColours(gradient, true, 1, weight, ratioArray);
			} else if(ratioArray[2] == 100) {
				return createGradientColours(gradient, true, 2, weight, ratioArray);
			} else {
				return createGradientColours(gradient, false, -1, weight, ratioArray);
			}
		}
	}
	function checkIfNotZero(number) {
		if(number == 0) {
			return 0.1;
		} else {
			return number;
		}
	}
	function calculateBackground(svg, weight, id) {
		var currentColorScale = getNormalColors();
		var gradient = svg.append("defs")
			.append("linearGradient")
			.attr("id", "gradient" + id)
			.attr("x1", "0%")
			.attr("y1", "0%")
			.attr("x2", "100%")
			.attr("y2", "0%")
			.attr("spreadMethod", "pad");
		gradient.append("stop")
			.attr("offset", "0%")
			.attr("stop-color", currentColorScale(weight*100))
			.attr("stop-opacity", 1);
		return gradient;
	}
	return {
        getBackground: function(svg,ratioTuple,weight, id,x,y) {
			if ( weight > 1 ){ weight = 1;}
			switch(colorMethod) {
				case 0:
					return calculateBackground(svg, weight, id);
					break;
				case 1:
					return calculateBackgroundGradient(svg,ratioTuple[0],weight, id,x,y);
					break;
				case 2:
					return calculateBackgroundGradient(svg,ratioTuple[1],weight, id,x,y);
					break;
			}
		},
		setColorsRelative: function() {
			maxConstant = getRelativeWarnings();
			reloadColorScale();
		},
		setColorsAbsolute: function() {
			maxConstant = 100;
			reloadColorScale();
		},
		setColorMethod: function(index) {
			colorMethod = index;
		},
		getRatios: function(d) {
			var constant = 100;
			var warningsTotal = checkIfNotZero(d.warnings);

			ratioArrayASAT = [];
            var ratioCheckStyle = Math.round(constant * d.warningsCheckStyle / warningsTotal);
			ratioArrayASAT.push(ratioCheckStyle);
            var ratiowarningsPMD = Math.round(constant * d.warningsPMD / warningsTotal);
			ratioArrayASAT.push(ratiowarningsPMD);
            var ratioFindBugs = Math.round(constant * d.warningsFindBugs / warningsTotal);
			ratioArrayASAT.push(ratioFindBugs);

			ratioArrayCategory = [];
            var ratioMaintainabilityDefects = Math.round(constant * d.warningsMaintainabilityDefects / warningsTotal);
			ratioArrayCategory.push(ratioMaintainabilityDefects);
            var ratioOtherDefects = Math.round(constant * d.warningsOtherDefects / warningsTotal);
			ratioArrayCategory.push(ratioOtherDefects);
			var ratioFunctionalDefects = Math.round(constant * d.warningsFunctionalDefects / warningsTotal);
			ratioArrayCategory.push(ratioFunctionalDefects);

			return [ratioArrayASAT,ratioArrayCategory]
		}
    }

}());<|endoftext|>


<commit_before>/**
 * Good Question
 * @flow
 */

import React, { AppRegistry } from 'react-native'

// Model
import Store from './js/data/Store'
import { connectToParseServer } from './js/api/ParseServer'

// Router
import SharedNavigator from './js/router/SharedNavigator'

/* iOS App */
const GoodQuestion = React.createClass ({
  /* Life Cycle */
  getInitialState() {
    return {
      store: Store
    }
  },

  /* Render */
  render() {
    return ( <SharedNavigator /> )
  }
})

AppRegistry.registerComponent('GoodQuestion', () => GoodQuestion)
<commit_msg>Re-adds ignoredYellowBox for iOS<commit_after>/**
 * Good Question
 * @flow
 */

import React, { AppRegistry } from 'react-native'

// Model
import Store from './js/data/Store'
import { connectToParseServer } from './js/api/ParseServer'

// Router
import SharedNavigator from './js/router/SharedNavigator'

// Due to a bug in React Native, we must temporarily ignore propType warnings for some iOS components to work.
// Affected component: DatePickerIOS
console.ignoredYellowBox = [
  'Warning: Failed propType',
]

/* iOS App */
const GoodQuestion = React.createClass ({
  /* Life Cycle */
  getInitialState() {
    return {
      store: Store
    }
  },

  /* Render */
  render() {
    return ( <SharedNavigator /> )
  }
})

AppRegistry.registerComponent('GoodQuestion', () => GoodQuestion)
<|endoftext|>


<commit_before>(function(global) {
  "use strict";

  global.app = global.app || {};

  //-------------------------
  // parameterManager module
  //-------------------------
  global.app.parameterManager = (function (global) {

    var default_value_moon_speed = 0.25, // [日/秒]
        default_value_moon_size;  // [px]

    var getDefaultValueMoonSize = function() {
      return default_value_moon_size;
    };

    /**
     * @param event
     * @param ui
     */
    var handlerOfMoonSpeed = function(event, ui) {

      $( "#amount-moon-speed" ).val( ui.value );

    };

    /**
     * @param event
     * @param ui
     */
    var handlerOfMoonSize = function(event, ui) {

      var moonManager = global.app.moonManager,
          renderer = moonManager.getRenderer(),
          camera = moonManager.getCamera(),
          size = ui.value;

      renderer.setSize(size, size);
      camera.aspect = size / size;
      camera.updateProjectionMatrix();

      $( "#amount-moon-size" ).val( size );

    };

    /**
     *
     */
    var setDefaultValues = function() {

      var containerElement = $('#moon-shape-container');

      default_value_moon_size = containerElement.width();
      console.log('default_value_moon_size', default_value_moon_size);

    };

    /**
     *
     */
    var setEventHandlers = function() {

      /* +++++ slider-moon-speed +++++ */
      $( "#slider-moon-speed" ).slider({
        orientation: "horizontal",
        range: "min",
        max: 10, // from 0
        step: 0.25,
        value: default_value_moon_speed, // default
        slide: handlerOfMoonSpeed,
        change: handlerOfMoonSpeed
      });
      $( "#amount-moon-speed" ).val( default_value_moon_speed );

      /* +++++ slider-moon-size +++++ */
      $( "#slider-moon-size" ).slider({
        orientation: "horizontal",
        range: "min",
        max: 500, // from 0
        step: 5,
        value: default_value_moon_size, // default
        slide: handlerOfMoonSize,
        change: handlerOfMoonSize
      });
      $( "#amount-moon-size" ).val( default_value_moon_size );

    };

    /**
     *
     */
    var init = function() {

      setDefaultValues();
      setEventHandlers();

    };

    return {
      init: init,
      getDefaultValueMoonSize: getDefaultValueMoonSize
    };

  })(global);

  //--------------------------------------------
  // moonDaysManager module （月齢管理モジュール）
  //--------------------------------------------
  global.app.moonDaysManager = (function (/*global*/) {

    /**
     * @param days
     */
    var update = function(days) {

      days = (Math.round(days * 100) % 2935) / 100;

      $('#moon-days').val(days);

    };

    return {
      update: update
    };

  })(global);

  //--------------------
  // moonManager module
  //--------------------
  global.app.moonManager = (function (global) {

    var renderer, camera, containerElement;

    var getRenderer = function() {
      return renderer;
    };

    var getCamera = function() {
      return camera;
    };

    var getContainerElement = function() {
      return containerElement;
    };

    /**
     * @param lightObj
     * @param baseTime
     * @param currentTime
     */
    var moveLight = function(lightObj, baseTime, currentTime) {

      var cycle_days = 29.53, // 月の周期[日]
          rad_per_day = (2 * Math.PI) / cycle_days, // 本来の速度[ラジアン/日]
          rate = $( "#amount-moon-speed" ).val(), // 1秒で何日進めるか（倍速機能）
          elapsed_days, x, y, z;

      elapsed_days = (currentTime - baseTime) / (1000 * 60 * 60 * 24); // 経過日数[日]
      elapsed_days = elapsed_days * (rate * (60 * 60 * 24)); // 表示用の値に変換する
      x = 4 * Math.sin( rad_per_day * elapsed_days );
      z = (-1) * 2 * Math.cos( rad_per_day * elapsed_days );
      y = 0.158;

      lightObj.position.set(x, y, z);

      global.app.moonDaysManager.update(elapsed_days);

    };

    /**
     *
     * Ref. 多彩な表現力のWebGLを扱いやすくする「Three.js」
     *      http://www.atmarkit.co.jp/ait/articles/1210/04/news142_5.html
     */
    var run = function() {

      if(!Detector.webgl) Detector.addGetWebGLMessage();

      var moon_size_default = global.app.parameterManager.getDefaultValueMoonSize();

      renderer = new THREE.WebGLRenderer({ antialias:true });
      renderer.setSize( moon_size_default, moon_size_default );
      document.getElementById('moon-shape-container').appendChild(renderer.domElement);

      var scene = new THREE.Scene();

      /* +++++ Camera +++++ */
      camera = new THREE.PerspectiveCamera(
        15, moon_size_default / moon_size_default);
      camera.position.set(0, 0, 8);
      camera.lookAt(new THREE.Vector3(0, 0, 0));
      scene.add(camera);

      /* +++++ Light +++++ */
      var light = new THREE.DirectionalLight(0x858585, 1.0);
      // set(x, y, z)
      light.position.set(0, 0, -4); // 新月
      var ambient = new THREE.AmbientLight(0x000000);
      scene.add(light);
      scene.add(ambient);

      /* +++++ 球体 +++++ */
      var geometry = new THREE.SphereGeometry(1, 32, 32);
      var material = new THREE.MeshPhongMaterial({
        color: 0xffffff,
        specular: 0xcccccc,
        shininess: 0,
        ambient: 0xffffff,
        map: THREE.ImageUtils.loadTexture('img/moon.jpg') });
      var mesh = new THREE.Mesh(geometry, material);
      // 球体の初期表示面を調整する
      var axis = new THREE.Vector3(0, 2.2, - 0.5).normalize();
      var q = new THREE.Quaternion();
      q.setFromAxisAngle(axis, - Math.PI/2);
      mesh.quaternion.copy(q);
      scene.add(mesh);

      /* +++++ Stats ( https://github.com/mrdoob/stats.js/ ) +++++ */
      var stats = new Stats();
      stats.setMode( 1 );
      stats.domElement.style.position = 'absolute';
      stats.domElement.style.right = '0px';
      stats.domElement.style.top = '0px';
      document.body.appendChild( stats.domElement );

      /* +++++ Loop +++++ */
      var baseTime = +new Date();
      function render() {

        stats.begin();

        moveLight(light, baseTime, +new Date());

        renderer.render(scene, camera);

        stats.end();

        requestAnimationFrame(render);
      }
      render();

    };

    return {
      run: run,
      getRenderer: getRenderer,
      getCamera: getCamera,
      getContainerElement: getContainerElement
    };

  })(global);

  //------------
  // Main
  //------------
  $(function(){

    global.app.parameterManager.init();
    global.app.moonManager.run();

  });

})((typeof window === 'object' && window) || global);
<commit_msg>Improve calculation of MoonDays<commit_after>(function(global) {
  "use strict";

  global.app = global.app || {};

  //-------------------------
  // parameterManager module
  //-------------------------
  global.app.parameterManager = (function (global) {

    var default_value_moon_speed = 0.25, // [日/秒]
        default_value_moon_size;  // [px]

    var getDefaultValueMoonSize = function() {
      return default_value_moon_size;
    };

    /**
     * @param event
     * @param ui
     */
    var handlerOfMoonSpeed = function(event, ui) {

      $( "#amount-moon-speed" ).val( ui.value );

    };

    /**
     * @param event
     * @param ui
     */
    var handlerOfMoonSize = function(event, ui) {

      var moonManager = global.app.moonManager,
          renderer = moonManager.getRenderer(),
          camera = moonManager.getCamera(),
          size = ui.value;

      renderer.setSize(size, size);
      camera.aspect = size / size;
      camera.updateProjectionMatrix();

      $( "#amount-moon-size" ).val( size );

    };

    /**
     *
     */
    var setDefaultValues = function() {

      var containerElement = $('#moon-shape-container');

      default_value_moon_size = containerElement.width();

    };

    /**
     *
     */
    var setEventHandlers = function() {

      /* +++++ slider-moon-speed +++++ */
      $( "#slider-moon-speed" ).slider({
        orientation: "horizontal",
        range: "min",
        max: 5, // from 0
        step: 0.125,
        value: default_value_moon_speed, // default
        slide: handlerOfMoonSpeed,
        change: handlerOfMoonSpeed
      });
      $( "#amount-moon-speed" ).val( default_value_moon_speed );

      /* +++++ slider-moon-size +++++ */
      $( "#slider-moon-size" ).slider({
        orientation: "horizontal",
        range: "min",
        max: 500, // from 0
        step: 5,
        value: default_value_moon_size, // default
        slide: handlerOfMoonSize,
        change: handlerOfMoonSize
      });
      $( "#amount-moon-size" ).val( default_value_moon_size );

    };

    /**
     *
     */
    var init = function() {

      setDefaultValues();
      setEventHandlers();

    };

    return {
      init: init,
      getDefaultValueMoonSize: getDefaultValueMoonSize
    };

  })(global);

  //--------------------------------------------
  // moonDaysManager module （月齢管理モジュール）
  //--------------------------------------------
  global.app.moonDaysManager = (function (/*global*/) {

    /**
     * @param days
     */
    var update = function(days) {

      $('#moon-days').val(days);

    };

    return {
      update: update
    };

  })(global);

  //--------------------
  // moonManager module
  //--------------------
  global.app.moonManager = (function (global) {

    var renderer, camera, containerElement;

    var getRenderer = function() {
      return renderer;
    };

    var getCamera = function() {
      return camera;
    };

    var getContainerElement = function() {
      return containerElement;
    };

    /**
     * @param lightObj
     * @param baseTime
     * @param currentTime
     */
    var moveLight = function(lightObj, baseTime, currentTime) {

      var cycle_days = 29.53, // 月の周期[日]
          rad_per_day = (2 * Math.PI) / cycle_days, // 本来の速度[ラジアン/日]
          rate = $( "#amount-moon-speed" ).val(), // 1秒で何日進めるか（倍速機能）
          elapsed_days, x, y, z;

      elapsed_days = (currentTime - baseTime) / (1000 * 60 * 60 * 24); // 経過日数[日]
      elapsed_days = elapsed_days * (rate * (60 * 60 * 24)); // 表示用の値に変換する
      elapsed_days = (Math.round(elapsed_days * 100) % (parseInt(cycle_days * 100))) / 100;

      x = 4 * Math.sin( rad_per_day * elapsed_days );
      z = (-1) * 2 * Math.cos( rad_per_day * elapsed_days );
      y = 0.158;

      lightObj.position.set(x, y, z);

      global.app.moonDaysManager.update(elapsed_days);

    };

    /**
     *
     * Ref. 多彩な表現力のWebGLを扱いやすくする「Three.js」
     *      http://www.atmarkit.co.jp/ait/articles/1210/04/news142_5.html
     */
    var run = function() {

      if(!Detector.webgl) Detector.addGetWebGLMessage();

      var moon_size_default = global.app.parameterManager.getDefaultValueMoonSize();

      renderer = new THREE.WebGLRenderer({ antialias:true });
      renderer.setSize( moon_size_default, moon_size_default );
      document.getElementById('moon-shape-container').appendChild(renderer.domElement);

      var scene = new THREE.Scene();

      /* +++++ Camera +++++ */
      camera = new THREE.PerspectiveCamera(
        15, moon_size_default / moon_size_default);
      camera.position.set(0, 0, 8);
      camera.lookAt(new THREE.Vector3(0, 0, 0));
      scene.add(camera);

      /* +++++ Light +++++ */
      var light = new THREE.DirectionalLight(0x858585, 1.0);
      // set(x, y, z)
      light.position.set(0, 0, -4); // 新月
      var ambient = new THREE.AmbientLight(0x000000);
      scene.add(light);
      scene.add(ambient);

      /* +++++ 球体 +++++ */
      var geometry = new THREE.SphereGeometry(1, 32, 32);
      var material = new THREE.MeshPhongMaterial({
        color: 0xffffff,
        specular: 0xcccccc,
        shininess: 0,
        ambient: 0xffffff,
        map: THREE.ImageUtils.loadTexture('img/moon.jpg') });
      var mesh = new THREE.Mesh(geometry, material);
      // 球体の初期表示面を調整する
      var axis = new THREE.Vector3(0, 2.2, - 0.5).normalize();
      var q = new THREE.Quaternion();
      q.setFromAxisAngle(axis, - Math.PI/2);
      mesh.quaternion.copy(q);
      scene.add(mesh);

      /* +++++ Stats ( https://github.com/mrdoob/stats.js/ ) +++++ */
      var stats = new Stats();
      stats.setMode( 1 );
      stats.domElement.style.position = 'absolute';
      stats.domElement.style.right = '0px';
      stats.domElement.style.top = '0px';
      document.body.appendChild( stats.domElement );

      /* +++++ Loop +++++ */
      var baseTime = +new Date();
      function render() {

        stats.begin();

        moveLight(light, baseTime, +new Date());

        renderer.render(scene, camera);

        stats.end();

        requestAnimationFrame(render);
      }
      render();

    };

    return {
      run: run,
      getRenderer: getRenderer,
      getCamera: getCamera,
      getContainerElement: getContainerElement
    };

  })(global);

  //------------
  // Main
  //------------
  $(function(){

    global.app.parameterManager.init();
    global.app.moonManager.run();

  });

})((typeof window === 'object' && window) || global);
<|endoftext|>


<commit_before>// Copyright (c) 2018, Livio, Inc.
const builder = require('nomad-helper');
const config = require('./config');
const coreSettings = require('./core-image-settings');
const hmiSettings = require('./hmi-image-settings');
const logger = config.logger;
const utils = require('../../../utils.js'); //contains useful functions for the job submission process

const randomString = require('randomatic');
const PATTERN = 'af09';
const PORTS_USED_THRESHOLD = .5;

//times to wait for healthy instances in milliseconds
const CORE_ALLOCATION_TIME = 5000;
const CORE_HEALTH_TIME = 8000;
const HMI_ALLOCATION_TIME = 5000;
const HMI_HEALTH_TIME = 8000;

const jobInfo = {
    core: {
        versions: ["6.0.0"], //ex. 5.0.1, master, develop
        builds: ["default"]
    },
    hmis: [{
        type: "generic",
        versions: ["minimal-0.7.2"] //ex. master, minimal-0.5.1
    }]
};

async function jobOptions () {
    return jobInfo;
}

/*
expected input:
{
    id: 1,
    core: {
        version: "master",
        build: "default"
    },
    hmi: {
        type: "generic",
        version: "minimal"
    }
}

expected output:
{
    body: {}, //if isValid is true, this body gets sent to manticore to be stored for future reference
    isValid: false, //determines whether manticore should approve of the request
    errorMessage: "" //if isValid is false, this message gets sent to the user with a 400 status code
}
*/
async function validate (body) {
    if (!body || !body.core || !body.hmi) {
        return createErrorResponse("Request body is invalid");
    }

    const coreVersionValid = jobInfo.core.versions.includes(body.core.version);
    const coreBuildValid = jobInfo.core.builds.includes(body.core.build);
    const hmiTypeIndex = jobInfo.hmis.findIndex(elem => {
        return elem.type === body.hmi.type;
    });
    const hmiVersionValid = hmiTypeIndex !== -1 && jobInfo.hmis[hmiTypeIndex].versions.includes(body.hmi.version);

    if (!coreVersionValid) {
        return createErrorResponse("Not a valid core version: " + body.core.version);
    }
    if (!coreBuildValid) {
        return createErrorResponse("Not a valid core build option: " + body.core.build);
    }
    if (hmiTypeIndex === -1) {
        return createErrorResponse("Not a valid hmi type: " + body.hmi.type);
    }
    else if (!hmiVersionValid) {
        return createErrorResponse("Not a valid hmi version: " + body.hmi.version);
    }

    //the response is valid at this point. clean the input
    return {
        body: { //response to store
            core: {
                version: body.core.version,
                build: body.core.build
            },
            hmi: {
                type: body.hmi.type,
                version: body.hmi.version
            }
        },
        isValid: true
    };
}

function createErrorResponse (message) {
    return {
        body: {},
        isValid: false,
        errorMessage: message
    }
}

//responsible for advancing the state of the job for a request
//can modify the context object passed in from manticore
async function advance (ctx) {
    //note: modify currentRequest as a shortcut to modifying waitingState
    const {currentRequest, waitingState} = ctx;
    const {id, request} = currentRequest;
    const {version: coreVersion, build} = request.core;
    const {version: hmiVersion, type} = request.hmi;

    const jobName = `core-hmi-${id}`;
    const coreTaskName = `core-task-${id}`;
    const hmiTaskName = `hmi-task-${id}`;

    //perform a different action depending on the current state
    if (currentRequest.state === "waiting") { //this stage causes a core job to run
        const job = coreSettings.generateJobFile(jobName, currentRequest);
        const jobFile = job.getJob().Job;

        await utils.autoHandleAll({
            ctx: ctx,
            job: jobFile,
            allocationTime: CORE_ALLOCATION_TIME,
            healthTime: CORE_HEALTH_TIME,
            stateChangeValue: "pending-1",
            servicesKey: "manticore"
        });

        return; //done
    }
    //this stage generates external core address values for haproxy mode and stores them for future use
    if (currentRequest.state === "pending-1") {
        //if haproxy is configured, generate the external addresses
        if (config.modes.haproxy) {
            //ensure that the tcp port numbers generated haven't been used before
            //make the string addresses long enough to be improbable for collisions to ever happen
            const usedTcpPorts = getUsedTcpPorts(waitingState);
            const coreTcpPort = await generateTcpPort(config.tcpPortStart, config.tcpPortEnd, usedTcpPorts);

            currentRequest.services.manticore[`core-broker-${id}-0`].external = randomString(PATTERN, 16);
            currentRequest.services.manticore[`core-broker-${id}-0`].isHttp = true;

            currentRequest.services.manticore[`core-file-${id}-0`].external = randomString(PATTERN, 16);
            currentRequest.services.manticore[`core-file-${id}-0`].isHttp = true;

            currentRequest.services.manticore[`core-log-${id}-0`].external = randomString(PATTERN, 16);
            currentRequest.services.manticore[`core-log-${id}-0`].isHttp = true;

            currentRequest.services.manticore[`core-policy-${id}-0`].external = randomString(PATTERN, 16);
            currentRequest.services.manticore[`core-policy-${id}-0`].isHttp = true;

            currentRequest.services.manticore[`core-tcp-${id}-0`].external = coreTcpPort;
            currentRequest.services.manticore[`core-tcp-${id}-0`].isHttp = false;

            currentRequest.state = "pending-2";
            ctx.updateStore = true;
            ctx.removeUser = false;
            return; //done. wait for the next cycle for the next phase
        }
        currentRequest.state = "pending-2";
        //immediately proceed to the next phase, as nothing needs to be stored here
    }
    if (currentRequest.state === "pending-2") { //this stage causes an hmi job to run
        const brokerAddress = currentRequest.services.manticore[`core-broker-${id}-0`].internal;
        const coreFileAddress = currentRequest.services.manticore[`core-file-${id}-0`].internal;

        let fullBrokerAddress = `ws:\\/\\/${brokerAddress}`; //internal address

        //if haproxy is configured, generate the external addresses
        if (config.modes.haproxy) {
            //domain addresses
            const externalBrokerAddress = currentRequest.services.manticore[`core-broker-${id}-0`].external;
            const brokerDomainAddress = `${externalBrokerAddress}.${config.haproxyDomain}`;

            //external address (HAProxy)
            fullBrokerAddress = `ws:\\/\\/${brokerDomainAddress}:${config.haproxyPort}`;

            if (config.modes.elb) { //external address (ELB)
                fullBrokerAddress = `ws:\\/\\/${brokerDomainAddress}:${config.wsPort}`;
            }

            if (config.modes.elbEncryptWs) { //secure external address (ELB)
                fullBrokerAddress = `wss:\\/\\/${brokerDomainAddress}:${config.wsPort}`;
            }
        }

        const envs = { //extract service addresses found from the previous stage
            brokerAddress: fullBrokerAddress,
            coreFileAddress: coreFileAddress,
        };

        let job = coreSettings.generateJobFile(jobName, currentRequest);
        //add the hmi task group
        job = hmiSettings.generateJobFile(job, currentRequest, envs);

        const jobFile = job.getJob().Job;

        await utils.autoHandleAll({
            ctx: ctx,
            job: jobFile,
            allocationTime: HMI_ALLOCATION_TIME,
            healthTime: HMI_HEALTH_TIME,
            stateChangeValue: "pending-3",
            servicesKey: "manticore"
        });

        return; //done
    }
    //this stage generates external hmi address values for haproxy mode and stores them for future use
    if (currentRequest.state === "pending-3") {
        //if haproxy is configured, generate the external addresses
        if (config.modes.haproxy && currentRequest.services.manticore) {
            currentRequest.services.manticore[`hmi-user-${id}-0`].external = randomString(PATTERN, 16);
            currentRequest.services.manticore[`hmi-user-${id}-0`].isHttp = true;

            currentRequest.state = "pending-4";
            ctx.updateStore = true;
            ctx.removeUser = false;
            return; //done. wait for the next cycle for the next phase
        }
        currentRequest.state = "pending-4";
        //immediately proceed to the next phase, as nothing needs to be stored here
    }
    //this additional phase ensures that modules listening on "post-waiting-job-advance" have the correct info
    //since it has been stored in the KV store
    if (currentRequest.state === "pending-4") {
        //all addresses have been finalized and the jobs are healthy. done
        currentRequest.state = "claimed";
        ctx.updateStore = true;
        ctx.removeUser = false;
        return;
    }

}

//given an id, return the full name of the job
async function idToJobName (id) {
    return `core-hmi-${id}`;
}

//use the waiting state to find all used tcp ports
function getUsedTcpPorts (waitingState) {
    let usedPorts = [];
    for (let id in waitingState) {
        const cond1 = waitingState[id].services !== undefined;
        const cond2 = cond1 && waitingState[id].services.manticore !== undefined;
        const cond3 = cond2 && waitingState[id].services.manticore[`core-tcp-${id}-0`].external !== undefined;
        if (cond3) {
            usedPorts.push(waitingState[id].services.manticore[`core-tcp-${id}-0`].external);
        }
    }
    return usedPorts;
}

//continue to create random numbers between min and max until one isn't in the blacklisted ports
//WARNING: will get much slower the greater the percentage of possible ports are taken. make sure
//the range is always large enough for your load!
async function generateTcpPort (min, max, blacklistedPorts) {
    //start printing warnings if a significant percentage of ports are already taken
    const range = max - min + 1;
    const portsTakenPercentage = blacklistedPorts.length / range;
    if (portsTakenPercentage >= PORTS_USED_THRESHOLD) {
        logger.warn(new Error("Port supply running low! Percentage used: " + portsTakenPercentage).stack);
    }
    let foundPort = false;
    let port;
    while (!foundPort) {
        port = Math.floor(Math.random() * range) + min;
        foundPort = !blacklistedPorts.includes(port);
    }

    return port;
}

//given a services object, formats the addresses in some friendly manner and returns them for a client
function formatAddresses (id, services) {
    return {
        "core-broker": utils.formatWsAddress(services.manticore[`core-broker-${id}-0`]),
        "core-tcp": utils.formatTcpAddress(services.manticore[`core-tcp-${id}-0`]),
        "core-file": utils.formatHttpAddress(services.manticore[`core-file-${id}-0`]),
        "core-log": utils.formatWsAddress(services.manticore[`core-log-${id}-0`]),
        "core-policy": utils.formatHttpAddress(services.manticore[`core-policy-${id}-0`]),
        "hmi-user": utils.formatHttpAddress(services.manticore[`hmi-user-${id}-0`]),
    };
}

//returns some valid job configuration that could be used as a request
function exampleJobOption () {
    return {
        core: {
            version: "6.0.0",
            build: "default"
        },
        hmi: {
            type: "generic",
            version: "minimal-0.7.2"
        }
    };
}

module.exports = {
    jobOptions: jobOptions,
    validate: validate,
    advance: advance,
    idToJobName: idToJobName,
    formatAddresses: formatAddresses,
    exampleJobOption: exampleJobOption
}
<commit_msg>Update core job version<commit_after>// Copyright (c) 2018, Livio, Inc.
const builder = require('nomad-helper');
const config = require('./config');
const coreSettings = require('./core-image-settings');
const hmiSettings = require('./hmi-image-settings');
const logger = config.logger;
const utils = require('../../../utils.js'); //contains useful functions for the job submission process

const randomString = require('randomatic');
const PATTERN = 'af09';
const PORTS_USED_THRESHOLD = .5;

//times to wait for healthy instances in milliseconds
const CORE_ALLOCATION_TIME = 5000;
const CORE_HEALTH_TIME = 8000;
const HMI_ALLOCATION_TIME = 5000;
const HMI_HEALTH_TIME = 8000;

const jobInfo = {
    core: {
        versions: ["6.0.1"], //ex. 5.0.1, master, develop
        builds: ["default"]
    },
    hmis: [{
        type: "generic",
        versions: ["minimal-0.7.2"] //ex. master, minimal-0.5.1
    }]
};

async function jobOptions () {
    return jobInfo;
}

/*
expected input:
{
    id: 1,
    core: {
        version: "master",
        build: "default"
    },
    hmi: {
        type: "generic",
        version: "minimal"
    }
}

expected output:
{
    body: {}, //if isValid is true, this body gets sent to manticore to be stored for future reference
    isValid: false, //determines whether manticore should approve of the request
    errorMessage: "" //if isValid is false, this message gets sent to the user with a 400 status code
}
*/
async function validate (body) {
    if (!body || !body.core || !body.hmi) {
        return createErrorResponse("Request body is invalid");
    }

    const coreVersionValid = jobInfo.core.versions.includes(body.core.version);
    const coreBuildValid = jobInfo.core.builds.includes(body.core.build);
    const hmiTypeIndex = jobInfo.hmis.findIndex(elem => {
        return elem.type === body.hmi.type;
    });
    const hmiVersionValid = hmiTypeIndex !== -1 && jobInfo.hmis[hmiTypeIndex].versions.includes(body.hmi.version);

    if (!coreVersionValid) {
        return createErrorResponse("Not a valid core version: " + body.core.version);
    }
    if (!coreBuildValid) {
        return createErrorResponse("Not a valid core build option: " + body.core.build);
    }
    if (hmiTypeIndex === -1) {
        return createErrorResponse("Not a valid hmi type: " + body.hmi.type);
    }
    else if (!hmiVersionValid) {
        return createErrorResponse("Not a valid hmi version: " + body.hmi.version);
    }

    //the response is valid at this point. clean the input
    return {
        body: { //response to store
            core: {
                version: body.core.version,
                build: body.core.build
            },
            hmi: {
                type: body.hmi.type,
                version: body.hmi.version
            }
        },
        isValid: true
    };
}

function createErrorResponse (message) {
    return {
        body: {},
        isValid: false,
        errorMessage: message
    }
}

//responsible for advancing the state of the job for a request
//can modify the context object passed in from manticore
async function advance (ctx) {
    //note: modify currentRequest as a shortcut to modifying waitingState
    const {currentRequest, waitingState} = ctx;
    const {id, request} = currentRequest;
    const {version: coreVersion, build} = request.core;
    const {version: hmiVersion, type} = request.hmi;

    const jobName = `core-hmi-${id}`;
    const coreTaskName = `core-task-${id}`;
    const hmiTaskName = `hmi-task-${id}`;

    //perform a different action depending on the current state
    if (currentRequest.state === "waiting") { //this stage causes a core job to run
        const job = coreSettings.generateJobFile(jobName, currentRequest);
        const jobFile = job.getJob().Job;

        await utils.autoHandleAll({
            ctx: ctx,
            job: jobFile,
            allocationTime: CORE_ALLOCATION_TIME,
            healthTime: CORE_HEALTH_TIME,
            stateChangeValue: "pending-1",
            servicesKey: "manticore"
        });

        return; //done
    }
    //this stage generates external core address values for haproxy mode and stores them for future use
    if (currentRequest.state === "pending-1") {
        //if haproxy is configured, generate the external addresses
        if (config.modes.haproxy) {
            //ensure that the tcp port numbers generated haven't been used before
            //make the string addresses long enough to be improbable for collisions to ever happen
            const usedTcpPorts = getUsedTcpPorts(waitingState);
            const coreTcpPort = await generateTcpPort(config.tcpPortStart, config.tcpPortEnd, usedTcpPorts);

            currentRequest.services.manticore[`core-broker-${id}-0`].external = randomString(PATTERN, 16);
            currentRequest.services.manticore[`core-broker-${id}-0`].isHttp = true;

            currentRequest.services.manticore[`core-file-${id}-0`].external = randomString(PATTERN, 16);
            currentRequest.services.manticore[`core-file-${id}-0`].isHttp = true;

            currentRequest.services.manticore[`core-log-${id}-0`].external = randomString(PATTERN, 16);
            currentRequest.services.manticore[`core-log-${id}-0`].isHttp = true;

            currentRequest.services.manticore[`core-policy-${id}-0`].external = randomString(PATTERN, 16);
            currentRequest.services.manticore[`core-policy-${id}-0`].isHttp = true;

            currentRequest.services.manticore[`core-tcp-${id}-0`].external = coreTcpPort;
            currentRequest.services.manticore[`core-tcp-${id}-0`].isHttp = false;

            currentRequest.state = "pending-2";
            ctx.updateStore = true;
            ctx.removeUser = false;
            return; //done. wait for the next cycle for the next phase
        }
        currentRequest.state = "pending-2";
        //immediately proceed to the next phase, as nothing needs to be stored here
    }
    if (currentRequest.state === "pending-2") { //this stage causes an hmi job to run
        const brokerAddress = currentRequest.services.manticore[`core-broker-${id}-0`].internal;
        const coreFileAddress = currentRequest.services.manticore[`core-file-${id}-0`].internal;

        let fullBrokerAddress = `ws:\\/\\/${brokerAddress}`; //internal address

        //if haproxy is configured, generate the external addresses
        if (config.modes.haproxy) {
            //domain addresses
            const externalBrokerAddress = currentRequest.services.manticore[`core-broker-${id}-0`].external;
            const brokerDomainAddress = `${externalBrokerAddress}.${config.haproxyDomain}`;

            //external address (HAProxy)
            fullBrokerAddress = `ws:\\/\\/${brokerDomainAddress}:${config.haproxyPort}`;

            if (config.modes.elb) { //external address (ELB)
                fullBrokerAddress = `ws:\\/\\/${brokerDomainAddress}:${config.wsPort}`;
            }

            if (config.modes.elbEncryptWs) { //secure external address (ELB)
                fullBrokerAddress = `wss:\\/\\/${brokerDomainAddress}:${config.wsPort}`;
            }
        }

        const envs = { //extract service addresses found from the previous stage
            brokerAddress: fullBrokerAddress,
            coreFileAddress: coreFileAddress,
        };

        let job = coreSettings.generateJobFile(jobName, currentRequest);
        //add the hmi task group
        job = hmiSettings.generateJobFile(job, currentRequest, envs);

        const jobFile = job.getJob().Job;

        await utils.autoHandleAll({
            ctx: ctx,
            job: jobFile,
            allocationTime: HMI_ALLOCATION_TIME,
            healthTime: HMI_HEALTH_TIME,
            stateChangeValue: "pending-3",
            servicesKey: "manticore"
        });

        return; //done
    }
    //this stage generates external hmi address values for haproxy mode and stores them for future use
    if (currentRequest.state === "pending-3") {
        //if haproxy is configured, generate the external addresses
        if (config.modes.haproxy && currentRequest.services.manticore) {
            currentRequest.services.manticore[`hmi-user-${id}-0`].external = randomString(PATTERN, 16);
            currentRequest.services.manticore[`hmi-user-${id}-0`].isHttp = true;

            currentRequest.state = "pending-4";
            ctx.updateStore = true;
            ctx.removeUser = false;
            return; //done. wait for the next cycle for the next phase
        }
        currentRequest.state = "pending-4";
        //immediately proceed to the next phase, as nothing needs to be stored here
    }
    //this additional phase ensures that modules listening on "post-waiting-job-advance" have the correct info
    //since it has been stored in the KV store
    if (currentRequest.state === "pending-4") {
        //all addresses have been finalized and the jobs are healthy. done
        currentRequest.state = "claimed";
        ctx.updateStore = true;
        ctx.removeUser = false;
        return;
    }

}

//given an id, return the full name of the job
async function idToJobName (id) {
    return `core-hmi-${id}`;
}

//use the waiting state to find all used tcp ports
function getUsedTcpPorts (waitingState) {
    let usedPorts = [];
    for (let id in waitingState) {
        const cond1 = waitingState[id].services !== undefined;
        const cond2 = cond1 && waitingState[id].services.manticore !== undefined;
        const cond3 = cond2 && waitingState[id].services.manticore[`core-tcp-${id}-0`].external !== undefined;
        if (cond3) {
            usedPorts.push(waitingState[id].services.manticore[`core-tcp-${id}-0`].external);
        }
    }
    return usedPorts;
}

//continue to create random numbers between min and max until one isn't in the blacklisted ports
//WARNING: will get much slower the greater the percentage of possible ports are taken. make sure
//the range is always large enough for your load!
async function generateTcpPort (min, max, blacklistedPorts) {
    //start printing warnings if a significant percentage of ports are already taken
    const range = max - min + 1;
    const portsTakenPercentage = blacklistedPorts.length / range;
    if (portsTakenPercentage >= PORTS_USED_THRESHOLD) {
        logger.warn(new Error("Port supply running low! Percentage used: " + portsTakenPercentage).stack);
    }
    let foundPort = false;
    let port;
    while (!foundPort) {
        port = Math.floor(Math.random() * range) + min;
        foundPort = !blacklistedPorts.includes(port);
    }

    return port;
}

//given a services object, formats the addresses in some friendly manner and returns them for a client
function formatAddresses (id, services) {
    return {
        "core-broker": utils.formatWsAddress(services.manticore[`core-broker-${id}-0`]),
        "core-tcp": utils.formatTcpAddress(services.manticore[`core-tcp-${id}-0`]),
        "core-file": utils.formatHttpAddress(services.manticore[`core-file-${id}-0`]),
        "core-log": utils.formatWsAddress(services.manticore[`core-log-${id}-0`]),
        "core-policy": utils.formatHttpAddress(services.manticore[`core-policy-${id}-0`]),
        "hmi-user": utils.formatHttpAddress(services.manticore[`hmi-user-${id}-0`]),
    };
}

//returns some valid job configuration that could be used as a request
function exampleJobOption () {
    return {
        core: {
            version: "6.0.1",
            build: "default"
        },
        hmi: {
            type: "generic",
            version: "minimal-0.7.2"
        }
    };
}

module.exports = {
    jobOptions: jobOptions,
    validate: validate,
    advance: advance,
    idToJobName: idToJobName,
    formatAddresses: formatAddresses,
    exampleJobOption: exampleJobOption
}
<|endoftext|>


<commit_before>import React from 'react'
import {State, RouteHandler} from 'react-router'

import Sidebar from './sidebar'

let Student = React.createClass({
	mixins: [State],

	getInitialState: function() {
		return { student: null }
	},

	componentWillReceiveProps: function(nextProps) {
		let queryId = this.getParams().id
		let student = nextProps.students.get(queryId)
		console.info('student\'s student: ', student.toJS())

		window.stu = student
		this.setState({student})
	},

	componentWillMount() {
		this.componentWillReceiveProps(this.props)
	},

	// shouldComponentUpdate(nextProps, nextState) {
		// return nextState.student !== this.state.student
	// },

	render() {
		console.info('student render', this.props.students.toJS())

		if (!this.state.student)
			return React.createElement('img', {
				className: 'loading',
				src: 'images/loading.svg',
				alt: 'Gobbldygook is Loading',
			})

		return React.createElement('div',
			{className: 'student'},
			React.createElement(Sidebar, {student: this.state.student, settings: this.props.settings}),
			React.createElement(RouteHandler, {student: this.state.student, settings: this.props.settings}))
	},
})

export default Student
<commit_msg>Show a message when a student can't be found<commit_after>import React from 'react'
import {State, RouteHandler} from 'react-router'

import Sidebar from './sidebar'

let Student = React.createClass({
	mixins: [State],

	getInitialState: function() {
		let queryId = this.getParams().id
		return {
			student: null,
			message: `Loading Student ${queryId}`,
			messageClass: '',
		}
	},

	componentWillReceiveProps: function(nextProps) {
		let queryId = this.getParams().id
		let student = nextProps.students.get(queryId)

		if (student) {
			console.info('student\'s student: ', student.toJS())

			window.stu = student
			this.setState({student})
		}
		else {
			this.setState({message: `Could not find student "${queryId}"`, messageClass: 'error'})
			console.info('student is undefined at Student')
		}
	},

	componentWillMount() {
		this.componentWillReceiveProps(this.props)
	},

	// shouldComponentUpdate(nextProps, nextState) {
		// return nextState.student !== this.state.student
	// },

	render() {
		console.info('student render', this.props.students.toJS())

		if (!this.state.student)
			return React.createElement('figure', {className: 'loading'},
				React.createElement('img', {
					className: 'loading-spinner',
					src: 'images/loading.svg',
					alt: 'Gobbldygook is Loading',
				}),
				React.createElement('figcaption', {className: 'loading-message ' + this.state.messageClass}, this.state.message))

		return React.createElement('div',
			{className: 'student'},
			React.createElement(Sidebar, {student: this.state.student, settings: this.props.settings}),
			React.createElement(RouteHandler, {student: this.state.student, settings: this.props.settings}))
	},
})

export default Student
<|endoftext|>