<commit_before>define([
	'goo/entities/components/MeshDataComponent',
	'goo/entities/components/MeshRendererComponent',
	'goo/renderer/MeshData',
	'goo/renderer/Material',
	'goo/renderer/Shader',
	'goo/renderer/TextureCreator'
],
/** @lends */
function(
	MeshDataComponent,
	MeshRendererComponent,
	MeshData,
	Material,
	Shader,
	TextureCreator
) {
	"use strict";

	/**
	 * @class A terrain
	 */
	function Terrain(world) {
		var resourcePath = "../resources";
		var material = Material.createMaterial(terrainShaderDef);
		var texture = new TextureCreator().loadTexture2D(resourcePath + '/head_diffuse.jpg');
		material.setTexture('DIFFUSE_MAP', texture);
		var material2 = Material.createMaterial(terrainShaderDef);
		material2.setTexture('HEIGHT_MAP', texture);
		material2.wireframe = true;
		this.material = material;
		this.material2 = material2;

		var entity = world.createEntity();
		entity.addToWorld();
		for (var i = 0; i < 6; i++) {
			var level = this.createClipmapLevel(world, i, i === 0);
			entity.transformComponent.attachChild(level.transformComponent);
		}
	}

	Terrain.prototype.createClipmapLevel = function(world, scale, isInner) {
		var entity = world.createEntity();

		var size = Math.pow(2, scale);
		entity.transformComponent.transform.scale.set(size, size, 1);
		var move = (2 * Math.pow(-1, scale+1) + Math.pow(2, scale+1))/6;
		var diff = scale % 2 === 0 ? move : -move;
		entity.transformComponent.transform.translation.set(diff, -diff, 0);
		entity.addToWorld();

		// 0
		this.createQuadEntity(world, entity, 0, 0, 3, 3);
		this.createQuadEntity(world, entity, 3, 0, 3, 3);
		this.createQuadEntity(world, entity, 6, 0, 2, 3);
		this.createQuadEntity(world, entity, 8, 0, 3, 3);
		this.createQuadEntity(world, entity, 11, 0, 3, 3);

		// 1
		this.createQuadEntity(world, entity, 0, 3, 3, 3);
		this.createQuadEntity(world, entity, 11, 3, 3, 3);

		// 2
		this.createQuadEntity(world, entity, 0, 6, 3, 2);
		this.createQuadEntity(world, entity, 11, 6, 3, 2);

		// 3
		this.createQuadEntity(world, entity, 0, 8, 3, 3);
		this.createQuadEntity(world, entity, 11, 8, 3, 3);

		// 4
		this.createQuadEntity(world, entity, 0, 11, 3, 3);
		this.createQuadEntity(world, entity, 3, 11, 3, 3);
		this.createQuadEntity(world, entity, 6, 11, 2, 3);
		this.createQuadEntity(world, entity, 8, 11, 3, 3);
		this.createQuadEntity(world, entity, 11, 11, 3, 3);

		// interior
		// this.createQuadEntity(world, entity, 3, 3, 8, 1);
		// this.createQuadEntity(world, entity, 10, 4, 1, 7);

		// innermost level fill
		if (isInner) {
			this.createQuadEntity(world, entity, 3, 4, 7, 7);
		}

		return entity;
	};

	Terrain.prototype.createQuadEntity = function(world, parentEntity, x, y, w, h) {
		var meshData = this.createGrid(x, y, w, h);

		var entity = world.createEntity();
		parentEntity.transformComponent.attachChild(entity.transformComponent);
		var meshDataComponent = new MeshDataComponent(meshData);
		entity.setComponent(meshDataComponent);
		var meshRendererComponent = new MeshRendererComponent();
		// meshRendererComponent.materials.push(this.material);
		meshRendererComponent.materials.push(this.material2);
		entity.setComponent(meshRendererComponent);

		entity.addToWorld();

		return entity;
	};

	Terrain.prototype.createGrid = function(offsetX, offsetY, w, h) {
		var attributeMap = MeshData.defaultMap([MeshData.POSITION, MeshData.TEXCOORD0]);
		var meshData = new MeshData(attributeMap, (w + 1) * (h + 1), w * h * 6);

		var vertices = meshData.getAttributeBuffer(MeshData.POSITION);
		var uvs = meshData.getAttributeBuffer(MeshData.TEXCOORD0);
		var indices = meshData.getIndexBuffer();

		for (var x = 0; x < w + 1; x++) {
			for (var y = 0; y < h + 1; y++) {
				var index = y * (w + 1) + x;
				vertices[index * 3 + 0] = (x + offsetX - 7);
				vertices[index * 3 + 1] = (y + offsetY - 7);
				vertices[index * 3 + 2] = 0;

				uvs[index * 2 + 0] = (x + offsetX) / 15;
				uvs[index * 2 + 1] = (y + offsetY) / 15;
			}
		}

		for (var x = 0; x < w; x++) {
			for (var y = 0; y < h; y++) {
				var index = y * (w + 1) + x;
				var indicesIndex = y * w + x;
				indices[indicesIndex * 6 + 0] = index;
				indices[indicesIndex * 6 + 1] = index + 1;
				indices[indicesIndex * 6 + 2] = index + w + 1;
				indices[indicesIndex * 6 + 3] = index + 1;
				indices[indicesIndex * 6 + 4] = index + w + 1 + 1;
				indices[indicesIndex * 6 + 5] = index + w + 1;
			}
		}

		return meshData;
	};

	var terrainShaderDef = {
		attributes: {
			vertexPosition: MeshData.POSITION,
			vertexUV0: MeshData.TEXCOORD0
		},
		uniforms: {
			viewMatrix: Shader.VIEW_MATRIX,
			projectionMatrix: Shader.PROJECTION_MATRIX,
			worldMatrix: Shader.WORLD_MATRIX,
			diffuseMap: 'DIFFUSE_MAP',
			time: Shader.TIME
		},
		vshader: [ //
		'attribute vec3 vertexPosition;', //
		'attribute vec2 vertexUV0;', //

		'uniform mat4 viewMatrix;', //
		'uniform mat4 projectionMatrix;', //
		'uniform mat4 worldMatrix;', //

		'uniform float time;', //
		'uniform sampler2D diffuseMap;', //

		'varying vec4 texCol;', //

		'void main(void) {', //
		'	texCol = texture2D(diffuseMap, vertexUV0 + vec2(time*0.0));', //
		'	float height = length(texCol.rgb);', //
		'	gl_Position = projectionMatrix * viewMatrix * worldMatrix * ', //
		'		vec4(vertexPosition.x,vertexPosition.y,height*5.0, 1.0);', //
		'}' //
		].join('\n'),
		fshader: [ //
		'precision mediump float;', //

		'varying vec4 texCol;', //

		'void main(void)', //
		'{', //
		'	gl_FragColor = texCol;', //
		'}' //
		].join('\n')
	};

	return Terrain;
});<commit_msg>Iteraion 2 on clipmaps<commit_after>define([
	'goo/entities/components/MeshDataComponent',
	'goo/entities/components/MeshRendererComponent',
	'goo/math/MathUtils',
	'goo/renderer/MeshData',
	'goo/renderer/Material',
	'goo/renderer/Shader',
	'goo/renderer/TextureCreator'
],
/** @lends */
function(
	MeshDataComponent,
	MeshRendererComponent,
	MathUtils,
	MeshData,
	Material,
	Shader,
	TextureCreator
) {
	"use strict";

	/**
	 * @class A terrain
	 */
	function Terrain(world, texture) {
		// this.n = 8;
		this.n = 16;
		this.levels = 5;

		var material = Material.createMaterial(terrainShaderDef);
		material.setTexture('DIFFUSE_MAP', texture);
		// material.wireframe = true;
		material.uniforms.heightMul = 255;
		console.log(texture);
		// material.uniforms.resolution = [];
		this.material = material;

		this.material2 = Material.createMaterial(terrainShaderDefDebug);
		this.material2.setTexture('DIFFUSE_MAP', texture);
		this.material2.wireframe = true;
		this.material2.uniforms.col = [1, 0, 0];

		this.material3 = Material.createMaterial(terrainShaderDefDebug);
		this.material3.setTexture('DIFFUSE_MAP', texture);
		this.material3.wireframe = true;
		this.material3.uniforms.col = [0, 1, 0];

		var entity = world.createEntity();
		entity.addToWorld();
		this.clipmaps = [];
		for (var i = 0; i < this.levels; i++) {
			var clipmapEntity = this.createClipmapLevel(world, i === 0);
			// var clipmapEntity = this.createClipmapLevel(world, false);
			entity.attachChild(clipmapEntity);
			this.clipmaps[i] = {
				clipmapEntity: clipmapEntity,
				level: i,
				size: Math.pow(2, i),
				currentX: 100000,
				currentZ: 100000,
			};
		}

		var parentClipmap =  this.clipmaps[this.clipmaps.length-1];
		for (var i = this.clipmaps.length-2; i >= 0; i--) {
			var clipmap = this.clipmaps[i];
			clipmap.parentClipmap = parentClipmap;
			parentClipmap = clipmap;
		}
	}

	Terrain.prototype.update = function(pos) {
		var x = pos.x;
		var z = pos.z;

		for (var i = 0; i < this.clipmaps.length; i++) {
			var clipmap = this.clipmaps[i];

			var level = clipmap.level;

			var xx = Math.floor(x * 0.5 / clipmap.size);
			var zz = Math.floor(z * 0.5 / clipmap.size);

			if (xx === clipmap.currentX && zz === clipmap.currentZ) {
				continue;
			}

			var n = this.n;

			if (clipmap.parentClipmap) {
				var interior1 = clipmap.parentClipmap.clipmapEntity.interior1;
				var interior2 = clipmap.parentClipmap.clipmapEntity.interior2;

				var xxx = MathUtils.moduloPositive(xx+1, 2);
				var zzz = MathUtils.moduloPositive(zz+1, 2);
				var xmove = xxx % 2 === 0 ? -n : n+1;
				var zmove = zzz % 2 === 0 ? -n : n+1;
				interior1.setTranslation(-n, 0, zmove);
				zzz = MathUtils.moduloPositive(zz, 2);
				zmove = zzz % 2 === 0 ? -n : -n+1;
				interior2.setTranslation(xmove, 0, zmove);
			}

			// console.log(clipmap.level, 'new pos', xx, zz);

			clipmap.clipmapEntity.setTranslation(xx * clipmap.size * 2, 0, zz * clipmap.size * 2);
			clipmap.clipmapEntity.setScale(clipmap.size, 0, clipmap.size);

			clipmap.currentX = xx;
			clipmap.currentZ = zz;
		}
	};

	Terrain.prototype.createClipmapLevel = function(world, isInner) {
		var entity = world.createEntity('clipmap');
		entity.addToWorld();

		var n = this.n;

		// 0
		this.createQuadEntity(world, entity, -2*n, -2*n, n, n);
		this.createQuadEntity(world, entity, -1*n, -2*n, n, n);
		this.createQuadEntity(world, entity, 0*n, -2*n, 2, n);
		this.createQuadEntity(world, entity, 2, -2*n, n, n);
		this.createQuadEntity(world, entity, 2+1*n, -2*n, n, n);

		// 1
		this.createQuadEntity(world, entity, -2*n, -1*n, n, n);
		this.createQuadEntity(world, entity, 2+1*n, -1*n, n, n);

		// 2
		this.createQuadEntity(world, entity, -2*n, 0, n, 2);
		this.createQuadEntity(world, entity, 2+1*n, 0, n, 2);

		// 3
		this.createQuadEntity(world, entity, -2*n, 2, n, n);
		this.createQuadEntity(world, entity, 2+1*n, 2, n, n);

		// 4
		this.createQuadEntity(world, entity, -2*n, 2+1*n, n, n);
		this.createQuadEntity(world, entity, -1*n, 2+1*n, n, n);
		this.createQuadEntity(world, entity, 0, 2+1*n, 2, n);
		this.createQuadEntity(world, entity, 2, 2+1*n, n, n);
		this.createQuadEntity(world, entity, 2+1*n, 2+1*n, n, n);

		if (isInner) {
			// innermost level fill
			this.createQuadEntity(world, entity, -n, -n, n*2+2, n*2+2);
		} else {
			// interior
			entity.interior1 = this.createQuadEntity(world, entity, -n, -n, n*2+2, 1);
			entity.interior2 = this.createQuadEntity(world, entity, -n, -n, 1, n*2+1);
		}

		return entity;
	};

	Terrain.prototype.createQuadEntity = function(world, parentEntity, x, y, w, h, material) {
		material = material || this.material;

		var meshData = this.createGrid(w, h);
		var entity = world.createEntity(meshData, material);
		entity.meshRendererComponent.materials.push(this.material2);
		entity.setTranslation(x, 0, y);
		// entity.setTranslation(x * 1.01, 0, y * 1.01);
		parentEntity.attachChild(entity);
		entity.addToWorld();

		entity.meshRendererComponent.cullMode = 'Never';

		return entity;
	};

	var gridCache = {};

	Terrain.prototype.createGrid = function(w, h, ww, hh) {
		var key = w + '_' + h;
		if (gridCache[key]) {
			return gridCache[key];
		}

		var attributeMap = MeshData.defaultMap([MeshData.POSITION]);
		var meshData = new MeshData(attributeMap, (w + 1) * (h + 1), w * h * 6);
		gridCache[key] = meshData;

		var vertices = meshData.getAttributeBuffer(MeshData.POSITION);
		var uvs = meshData.getAttributeBuffer(MeshData.TEXCOORD0);
		var indices = meshData.getIndexBuffer();

		for (var x = 0; x < w + 1; x++) {
			for (var y = 0; y < h + 1; y++) {
				var index = y * (w + 1) + x;
				// vertices[index * 3 + 0] = x * ww / w;
				vertices[index * 3 + 0] = x;
				vertices[index * 3 + 1] = 0;
				// vertices[index * 3 + 2] = y * hh / h;
				vertices[index * 3 + 2] = y;
			}
		}

		for (var x = 0; x < w; x++) {
			for (var y = 0; y < h; y++) {
				var index = y * (w + 1) + x;
				var indicesIndex = y * w + x;
				indices[indicesIndex * 6 + 0] = index;
				indices[indicesIndex * 6 + 1] = index + w + 1;
				indices[indicesIndex * 6 + 2] = index + 1;
				indices[indicesIndex * 6 + 3] = index + 1;
				indices[indicesIndex * 6 + 4] = index + w + 1;
				indices[indicesIndex * 6 + 5] = index + w + 1 + 1;
			}
		}

		return meshData;
	};

	var terrainShaderDef = {
		attributes: {
			vertexPosition: MeshData.POSITION,
		},
		uniforms: {
			viewMatrix: Shader.VIEW_MATRIX,
			projectionMatrix: Shader.PROJECTION_MATRIX,
			worldMatrix: Shader.WORLD_MATRIX,
			diffuseMap: 'DIFFUSE_MAP',
			time: Shader.TIME,
			heightMul: 255,
			resolution: [1024, 1024],
			col: [0, 0, 0]
		},
		vshader: [
			'attribute vec3 vertexPosition;',

			'uniform mat4 viewMatrix;',
			'uniform mat4 projectionMatrix;',
			'uniform mat4 worldMatrix;',
			'uniform sampler2D diffuseMap;',
			'uniform float heightMul;',
			'uniform vec2 resolution;',

			'varying vec4 worldPos;',

			'void main(void) {',
				'worldPos = worldMatrix * vec4(vertexPosition, 1.0);',
				'worldPos.y = texture2D(diffuseMap, worldPos.xz / resolution).r * heightMul;',
				'gl_Position = projectionMatrix * viewMatrix * worldPos;',
			'}'
		].join('\n'),
		fshader: [
			'uniform vec3 col;',
			'uniform sampler2D diffuseMap;',
			'uniform vec2 resolution;',

			'varying vec4 worldPos;',

			'void main(void)',
			'{',
				'gl_FragColor = texture2D(diffuseMap, worldPos.xz / resolution);',
				// 'gl_FragColor = vec4(col, 1.0);',
			'}'
		].join('\n')
	};

	var terrainShaderDefDebug = {
		attributes: {
			vertexPosition: MeshData.POSITION,
		},
		uniforms: {
			viewMatrix: Shader.VIEW_MATRIX,
			projectionMatrix: Shader.PROJECTION_MATRIX,
			worldMatrix: Shader.WORLD_MATRIX,
			diffuseMap: 'DIFFUSE_MAP',
			time: Shader.TIME,
			heightMul: 255,
			resolution: [1024, 1024],
			col: [0, 0, 0]
		},
		vshader: [
			'attribute vec3 vertexPosition;',

			'uniform mat4 viewMatrix;',
			'uniform mat4 projectionMatrix;',
			'uniform mat4 worldMatrix;',
			'uniform sampler2D diffuseMap;',
			'uniform float heightMul;',
			'uniform vec2 resolution;',

			'varying vec4 worldPos;',

			'void main(void) {',
				'worldPos = worldMatrix * vec4(vertexPosition, 1.0);',
				'worldPos.y = texture2D(diffuseMap, worldPos.xz / resolution).r * heightMul;',
				'gl_Position = projectionMatrix * viewMatrix * worldPos;',
			'}'
		].join('\n'),
		fshader: [
			'uniform vec3 col;',
			'uniform sampler2D diffuseMap;',

			'varying vec4 worldPos;',

			'void main(void)',
			'{',
				'gl_FragColor = vec4(col, 1.0);',
			'}'
		].join('\n')
	};

	return Terrain;
});<|endoftext|>


<commit_before>'use strict'

const printChat = require('../core/printChat.js')
const impMetamodel = require('./impSchema.js')

module.exports = function overview (cy) {
  const networkArray = impMetamodel.network
  const securityArray = impMetamodel.security
  const socialArray = impMetamodel.social
  const sensingArray = impMetamodel.sensing

  let result = ''

  const totalNodes = cy.elements().nodes().length
  result = `• total nodes: ${totalNodes}\n\n`

  let networkNode = 0
  let securityNode = 0
  let socialNode = 0
  let sensingNode = 0

  cy.nodes().map(node => {
    const nodeConcept = node.data().info.concept
    if (networkArray.includes(nodeConcept) === true) {
      networkNode += 1
    } else if (securityArray.includes(nodeConcept) === true) {
      securityNode += 1
    } else if (socialArray.includes(nodeConcept) === true) {
      socialNode += 1
    } else if (sensingArray.includes(nodeConcept) === true) {
      sensingNode += 1
    }
  })
  result = `${result}• network nodes: ${networkNode}\n`
  result = `${result}• social nodes: ${socialNode}\n`
  result = `${result}• security nodes: ${securityNode}\n`
  result = `${result}• sensing nodes: ${sensingNode}\n\n`

  let deviceNode = 0
  let connectionNode = 0
  let micronetNode = 0
  let applicationNode = 0
  let netNode = 0
  let unidentifiedNode = 0
  let informationNode = 0
  let assetNode = 0
  let threatNode = 0
  let vulnNode = 0
  let mechNode = 0
  let constraintNode = 0
  let malActorNode = 0
  let actorNode = 0
  let eventSensorNode = 0
  let reportSensorNode = 0
  let controlSensorNode = 0

  cy.nodes().map(node => {
    const nodeConcept = node.data().info.concept
    if (nodeConcept === 'device') {
      deviceNode += 1
    } else if (nodeConcept === 'application') {
      applicationNode += 1
    } else if (nodeConcept === 'information') {
      informationNode += 1
    } else if (nodeConcept === 'network connection') {
      connectionNode += 1
    } else if (nodeConcept === 'micronet') {
      micronetNode += 1
    } else if (nodeConcept === 'net') {
      netNode += 1
    } else if (nodeConcept === 'unidentified node') {
      unidentifiedNode += 1
    } else if (nodeConcept === 'asset') {
      assetNode += 1
    } else if (nodeConcept === 'threat') {
      threatNode += 1
    } else if (nodeConcept === 'vulnerability') {
      vulnNode += 1
    } else if (nodeConcept === 'mechanism') {
      mechNode += 1
    } else if (nodeConcept === 'constraint') {
      constraintNode += 1
    } else if (nodeConcept === 'malicious actor') {
      malActorNode += 1
    } else if (nodeConcept === 'actor') {
      actorNode += 1
    } else if (nodeConcept === 'event sensor') {
      eventSensorNode += 1
    } else if (nodeConcept === 'report sensor') {
      reportSensorNode += 1
    } else if (nodeConcept === 'control sensor') {
      controlSensorNode += 1
    }
  })

  result = `${result}• device nodes: ${deviceNode}\n`
  result = `${result}• application nodes: ${applicationNode}\n`
  result = `${result}• network connection nodes: ${connectionNode}\n`
  result = `${result}• micronet nodes: ${micronetNode}\n`
  result = `${result}• net nodes: ${netNode}\n`
  result = `${result}• data nodes: ${informationNode}\n`
  result = `${result}• unidentified nodes: ${unidentifiedNode}\n`
  result = `${result}• asset nodes: ${assetNode}\n`
  result = `${result}• threat nodes: ${threatNode}\n`
  result = `${result}• vulnerability nodes: ${vulnNode}\n`
  result = `${result}• mechanism nodes: ${mechNode}\n`
  result = `${result}• constraint nodes: ${constraintNode}\n`
  result = `${result}• malicious actor nodes: ${malActorNode}\n`
  result = `${result}• actor nodes: ${actorNode}\n`
  result = `${result}• event sensor nodes: ${eventSensorNode}\n`
  result = `${result}• report sensor nodes: ${reportSensorNode}\n`
  result = `${result}• control sensor nodes: ${controlSensorNode}\n`

  printChat(result)
}
<commit_msg>data -> information<commit_after>'use strict'

const printChat = require('../core/printChat.js')
const impMetamodel = require('./impSchema.js')

module.exports = function overview (cy) {
  const networkArray = impMetamodel.network
  const securityArray = impMetamodel.security
  const socialArray = impMetamodel.social
  const sensingArray = impMetamodel.sensing

  let result = ''

  const totalNodes = cy.elements().nodes().length
  result = `• total nodes: ${totalNodes}\n\n`

  let networkNode = 0
  let securityNode = 0
  let socialNode = 0
  let sensingNode = 0

  cy.nodes().map(node => {
    const nodeConcept = node.data().info.concept
    if (networkArray.includes(nodeConcept) === true) {
      networkNode += 1
    } else if (securityArray.includes(nodeConcept) === true) {
      securityNode += 1
    } else if (socialArray.includes(nodeConcept) === true) {
      socialNode += 1
    } else if (sensingArray.includes(nodeConcept) === true) {
      sensingNode += 1
    }
  })
  result = `${result}• network nodes: ${networkNode}\n`
  result = `${result}• social nodes: ${socialNode}\n`
  result = `${result}• security nodes: ${securityNode}\n`
  result = `${result}• sensing nodes: ${sensingNode}\n\n`

  let deviceNode = 0
  let connectionNode = 0
  let micronetNode = 0
  let applicationNode = 0
  let netNode = 0
  let unidentifiedNode = 0
  let informationNode = 0
  let assetNode = 0
  let threatNode = 0
  let vulnNode = 0
  let mechNode = 0
  let constraintNode = 0
  let malActorNode = 0
  let actorNode = 0
  let eventSensorNode = 0
  let reportSensorNode = 0
  let controlSensorNode = 0

  cy.nodes().map(node => {
    const nodeConcept = node.data().info.concept
    if (nodeConcept === 'device') {
      deviceNode += 1
    } else if (nodeConcept === 'application') {
      applicationNode += 1
    } else if (nodeConcept === 'information') {
      informationNode += 1
    } else if (nodeConcept === 'network connection') {
      connectionNode += 1
    } else if (nodeConcept === 'micronet') {
      micronetNode += 1
    } else if (nodeConcept === 'net') {
      netNode += 1
    } else if (nodeConcept === 'unidentified node') {
      unidentifiedNode += 1
    } else if (nodeConcept === 'asset') {
      assetNode += 1
    } else if (nodeConcept === 'threat') {
      threatNode += 1
    } else if (nodeConcept === 'vulnerability') {
      vulnNode += 1
    } else if (nodeConcept === 'mechanism') {
      mechNode += 1
    } else if (nodeConcept === 'constraint') {
      constraintNode += 1
    } else if (nodeConcept === 'malicious actor') {
      malActorNode += 1
    } else if (nodeConcept === 'actor') {
      actorNode += 1
    } else if (nodeConcept === 'event sensor') {
      eventSensorNode += 1
    } else if (nodeConcept === 'report sensor') {
      reportSensorNode += 1
    } else if (nodeConcept === 'control sensor') {
      controlSensorNode += 1
    }
  })

  result = `${result}• device nodes: ${deviceNode}\n`
  result = `${result}• application nodes: ${applicationNode}\n`
  result = `${result}• network connection nodes: ${connectionNode}\n`
  result = `${result}• micronet nodes: ${micronetNode}\n`
  result = `${result}• net nodes: ${netNode}\n`
  result = `${result}• information nodes: ${informationNode}\n`
  result = `${result}• unidentified nodes: ${unidentifiedNode}\n`
  result = `${result}• asset nodes: ${assetNode}\n`
  result = `${result}• threat nodes: ${threatNode}\n`
  result = `${result}• vulnerability nodes: ${vulnNode}\n`
  result = `${result}• mechanism nodes: ${mechNode}\n`
  result = `${result}• constraint nodes: ${constraintNode}\n`
  result = `${result}• malicious actor nodes: ${malActorNode}\n`
  result = `${result}• actor nodes: ${actorNode}\n`
  result = `${result}• event sensor nodes: ${eventSensorNode}\n`
  result = `${result}• report sensor nodes: ${reportSensorNode}\n`
  result = `${result}• control sensor nodes: ${controlSensorNode}\n`

  printChat(result)
}
<|endoftext|>


<commit_before>//By Rajeshwar Patlolla
//https://github.com/rajeshwarpatlolla

(function () {
  'use strict';

  angular.module('ionic-timepicker')
    .directive('ionicTimepicker', ionicTimepicker);

  ionicTimepicker.$inject = ['$ionicPopup'];
  function ionicTimepicker($ionicPopup) {
    return {
      restrict: 'AE',
      replace: true,
      scope: {
        inputObj: "=inputObj"
      },
      link: function (scope, element, attrs) {

        console.log(scope.inputObj);

        var today = new Date();
        var currentEpoch = today.getHours();

        scope.inputEpochTime = scope.inputObj.inputEpochTime ? scope.inputObj.inputEpochTime : (currentEpoch * 60 * 60);
        scope.step = scope.inputObj.step ? scope.inputObj.step : 15;
        scope.format = scope.inputObj.format ? scope.inputObj.format : 24;
        scope.titleLabel = scope.inputObj.titleLabel ? scope.inputObj.titleLabel : 'Time Picker';
        scope.setLabel = scope.inputObj.setLabel ? scope.inputObj.setLabel : 'Set';
        scope.closeLabel = scope.inputObj.closeLabel ? scope.inputObj.closeLabel : 'Close';
        scope.setButtonType = scope.inputObj.setButtonType ? scope.inputObj.setButtonType : 'button-positive';
        scope.closeButtonType = scope.inputObj.closeButtonType ? scope.inputObj.closeButtonType : 'button-stable';

        var obj = {epochTime: scope.inputEpochTime, step: scope.step, format: scope.format};

        scope.time = {hours: 0, minutes: 0, meridian: ""};

        var objDate = new Date(obj.epochTime * 1000);       // Epoch time in milliseconds.

        scope.increaseHours = function () {
          scope.time.hours = Number(scope.time.hours);
          if (obj.format == 12) {
            if (scope.time.hours != 12) {
              scope.time.hours += 1;
            } else {
              scope.time.hours = 1;
            }
          }
          if (obj.format == 24) {
            if (scope.time.hours != 23) {
              scope.time.hours += 1;
            } else {
              scope.time.hours = 0;
            }
          }
          scope.time.hours = (scope.time.hours < 10) ? ('0' + scope.time.hours) : scope.time.hours;
        };

        scope.decreaseHours = function () {
          scope.time.hours = Number(scope.time.hours);
          if (obj.format == 12) {
            if (scope.time.hours > 1) {
              scope.time.hours -= 1;
            } else {
              scope.time.hours = 12;
            }
          }
          if (obj.format == 24) {
            if (scope.time.hours > 0) {
              scope.time.hours -= 1;
            } else {
              scope.time.hours = 23;
            }
          }
          scope.time.hours = (scope.time.hours < 10) ? ('0' + scope.time.hours) : scope.time.hours;
        };

        scope.increaseMinutes = function () {
          scope.time.minutes = Number(scope.time.minutes);

          if (scope.time.minutes != (60 - obj.step) && (scope.time.minutes + obj.step <= 60)) {
            scope.time.minutes += obj.step;
          } else {
            scope.time.minutes = 0;
          }
          scope.time.minutes = (scope.time.minutes < 10) ? ('0' + scope.time.minutes) : scope.time.minutes;
        };

        scope.decreaseMinutes = function () {
          scope.time.minutes = Number(scope.time.minutes);
          if (scope.time.minutes != 0 && (scope.time.minutes - obj.step > 0)) {
            scope.time.minutes -= obj.step;
          } else {
            scope.time.minutes = 60 - obj.step;
          }
          scope.time.minutes = (scope.time.minutes < 10) ? ('0' + scope.time.minutes) : scope.time.minutes;
        };

        scope.changeMeridian = function () {
          scope.time.meridian = (scope.time.meridian === "AM") ? "PM" : "AM";
        };

        element.on("click", function () {
          if (scope.inputObj.inputEpochTime) {
            objDate = new Date(scope.inputObj.inputEpochTime * 1000);
          }

          if (obj.format == 12) {

            scope.time.meridian = (objDate.getUTCHours() >= 12) ? "PM" : "AM";
            scope.time.hours = (objDate.getUTCHours() > 12) ? ((objDate.getUTCHours() - 12)) : (objDate.getUTCHours());
            scope.time.minutes = (objDate.getUTCMinutes());

            scope.time.hours = (scope.time.hours < 10) ? ("0" + scope.time.hours) : (scope.time.hours);
            scope.time.minutes = (scope.time.minutes < 10) ? ("0" + scope.time.minutes) : (scope.time.minutes);

            if (scope.time.hours == 0 && scope.time.meridian == "AM") {
              scope.time.hours = 12;
            }

            $ionicPopup.show({
              templateUrl: 'ionic-timepicker-12-hour.html',
              title: scope.titleLabel,
              subTitle: '',
              scope: scope,
              buttons: [
                {
                  text: scope.closeLabel,
                  type: scope.closeButtonType,
                  onTap: function (e) {
                    scope.inputObj.callback(undefined);
                  }
                },
                {
                  text: scope.setLabel,
                  type: scope.setButtonType,
                  onTap: function (e) {
                    scope.loadingContent = true;

                    var totalSec = 0;

                    if (scope.time.hours != 12) {
                      totalSec = (scope.time.hours * 60 * 60) + (scope.time.minutes * 60);
                    } else {
                      totalSec = scope.time.minutes * 60;
                    }

                    if (scope.time.meridian === "AM") {
                      totalSec += 0;
                    } else if (scope.time.meridian === "PM") {
                      totalSec += 43200;
                    }
                    scope.etime = totalSec;
                    scope.inputObj.callback(scope.etime);
                  }
                }
              ]
            })

          } else if (obj.format == 24) {

            scope.time.hours = (objDate.getUTCHours());
            scope.time.minutes = (objDate.getUTCMinutes());

            scope.time.hours = (scope.time.hours < 10) ? ("0" + scope.time.hours) : (scope.time.hours);
            scope.time.minutes = (scope.time.minutes < 10) ? ("0" + scope.time.minutes) : (scope.time.minutes);

            $ionicPopup.show({
              templateUrl: 'ionic-timepicker-24-hour.html',
              title: scope.titleLabel,
              subTitle: '',
              scope: scope,
              buttons: [
                {
                  text: scope.closeLabel,
                  type: scope.closeButtonType,
                  onTap: function (e) {
                    scope.inputObj.callback(undefined);
                  }
                },
                {
                  text: scope.setLabel,
                  type: scope.setButtonType,
                  onTap: function (e) {

                    scope.loadingContent = true;

                    var totalSec = 0;

                    if (scope.time.hours != 24) {
                      totalSec = (scope.time.hours * 60 * 60) + (scope.time.minutes * 60);
                    } else {
                      totalSec = scope.time.minutes * 60;
                    }
                    scope.etime = totalSec;
                    scope.inputObj.callback(scope.etime);
                  }
                }
              ]
            })
          }
        });
      }
    };
  }

})();<commit_msg>Fix decreaseMinutes bug<commit_after>//By Rajeshwar Patlolla
//https://github.com/rajeshwarpatlolla

(function () {
  'use strict';

  angular.module('ionic-timepicker')
    .directive('ionicTimepicker', ionicTimepicker);

  ionicTimepicker.$inject = ['$ionicPopup'];
  function ionicTimepicker($ionicPopup) {
    return {
      restrict: 'AE',
      replace: true,
      scope: {
        inputObj: "=inputObj"
      },
      link: function (scope, element, attrs) {

        console.log(scope.inputObj);

        var today = new Date();
        var currentEpoch = today.getHours();

        scope.inputEpochTime = scope.inputObj.inputEpochTime ? scope.inputObj.inputEpochTime : (currentEpoch * 60 * 60);
        scope.step = scope.inputObj.step ? scope.inputObj.step : 15;
        scope.format = scope.inputObj.format ? scope.inputObj.format : 24;
        scope.titleLabel = scope.inputObj.titleLabel ? scope.inputObj.titleLabel : 'Time Picker';
        scope.setLabel = scope.inputObj.setLabel ? scope.inputObj.setLabel : 'Set';
        scope.closeLabel = scope.inputObj.closeLabel ? scope.inputObj.closeLabel : 'Close';
        scope.setButtonType = scope.inputObj.setButtonType ? scope.inputObj.setButtonType : 'button-positive';
        scope.closeButtonType = scope.inputObj.closeButtonType ? scope.inputObj.closeButtonType : 'button-stable';

        var obj = {epochTime: scope.inputEpochTime, step: scope.step, format: scope.format};

        scope.time = {hours: 0, minutes: 0, meridian: ""};

        var objDate = new Date(obj.epochTime * 1000);       // Epoch time in milliseconds.

        scope.increaseHours = function () {
          scope.time.hours = Number(scope.time.hours);
          if (obj.format == 12) {
            if (scope.time.hours != 12) {
              scope.time.hours += 1;
            } else {
              scope.time.hours = 1;
            }
          }
          if (obj.format == 24) {
            if (scope.time.hours != 23) {
              scope.time.hours += 1;
            } else {
              scope.time.hours = 0;
            }
          }
          scope.time.hours = (scope.time.hours < 10) ? ('0' + scope.time.hours) : scope.time.hours;
        };

        scope.decreaseHours = function () {
          scope.time.hours = Number(scope.time.hours);
          if (obj.format == 12) {
            if (scope.time.hours > 1) {
              scope.time.hours -= 1;
            } else {
              scope.time.hours = 12;
            }
          }
          if (obj.format == 24) {
            if (scope.time.hours > 0) {
              scope.time.hours -= 1;
            } else {
              scope.time.hours = 23;
            }
          }
          scope.time.hours = (scope.time.hours < 10) ? ('0' + scope.time.hours) : scope.time.hours;
        };

        scope.increaseMinutes = function () {
          scope.time.minutes = Number(scope.time.minutes);

          if (scope.time.minutes != (60 - obj.step) && (scope.time.minutes + obj.step <= 60)) {
            scope.time.minutes += obj.step;
          } else {
            scope.time.minutes = 0;
          }
          scope.time.minutes = (scope.time.minutes < 10) ? ('0' + scope.time.minutes) : scope.time.minutes;
        };

        scope.decreaseMinutes = function () {
          scope.time.minutes = Number(scope.time.minutes);
          if (scope.time.minutes != 0 && (scope.time.minutes - obj.step >= 0)) {
            scope.time.minutes -= obj.step;
          } else {
            scope.time.minutes = 60 - obj.step;
          }
          scope.time.minutes = (scope.time.minutes < 10) ? ('0' + scope.time.minutes) : scope.time.minutes;
        };

        scope.changeMeridian = function () {
          scope.time.meridian = (scope.time.meridian === "AM") ? "PM" : "AM";
        };

        element.on("click", function () {
          if (scope.inputObj.inputEpochTime) {
            objDate = new Date(scope.inputObj.inputEpochTime * 1000);
          }

          if (obj.format == 12) {

            scope.time.meridian = (objDate.getUTCHours() >= 12) ? "PM" : "AM";
            scope.time.hours = (objDate.getUTCHours() > 12) ? ((objDate.getUTCHours() - 12)) : (objDate.getUTCHours());
            scope.time.minutes = (objDate.getUTCMinutes());

            scope.time.hours = (scope.time.hours < 10) ? ("0" + scope.time.hours) : (scope.time.hours);
            scope.time.minutes = (scope.time.minutes < 10) ? ("0" + scope.time.minutes) : (scope.time.minutes);

            if (scope.time.hours == 0 && scope.time.meridian == "AM") {
              scope.time.hours = 12;
            }

            $ionicPopup.show({
              templateUrl: 'ionic-timepicker-12-hour.html',
              title: scope.titleLabel,
              subTitle: '',
              scope: scope,
              buttons: [
                {
                  text: scope.closeLabel,
                  type: scope.closeButtonType,
                  onTap: function (e) {
                    scope.inputObj.callback(undefined);
                  }
                },
                {
                  text: scope.setLabel,
                  type: scope.setButtonType,
                  onTap: function (e) {
                    scope.loadingContent = true;

                    var totalSec = 0;

                    if (scope.time.hours != 12) {
                      totalSec = (scope.time.hours * 60 * 60) + (scope.time.minutes * 60);
                    } else {
                      totalSec = scope.time.minutes * 60;
                    }

                    if (scope.time.meridian === "AM") {
                      totalSec += 0;
                    } else if (scope.time.meridian === "PM") {
                      totalSec += 43200;
                    }
                    scope.etime = totalSec;
                    scope.inputObj.callback(scope.etime);
                  }
                }
              ]
            })

          } else if (obj.format == 24) {

            scope.time.hours = (objDate.getUTCHours());
            scope.time.minutes = (objDate.getUTCMinutes());

            scope.time.hours = (scope.time.hours < 10) ? ("0" + scope.time.hours) : (scope.time.hours);
            scope.time.minutes = (scope.time.minutes < 10) ? ("0" + scope.time.minutes) : (scope.time.minutes);

            $ionicPopup.show({
              templateUrl: 'ionic-timepicker-24-hour.html',
              title: scope.titleLabel,
              subTitle: '',
              scope: scope,
              buttons: [
                {
                  text: scope.closeLabel,
                  type: scope.closeButtonType,
                  onTap: function (e) {
                    scope.inputObj.callback(undefined);
                  }
                },
                {
                  text: scope.setLabel,
                  type: scope.setButtonType,
                  onTap: function (e) {

                    scope.loadingContent = true;

                    var totalSec = 0;

                    if (scope.time.hours != 24) {
                      totalSec = (scope.time.hours * 60 * 60) + (scope.time.minutes * 60);
                    } else {
                      totalSec = scope.time.minutes * 60;
                    }
                    scope.etime = totalSec;
                    scope.inputObj.callback(scope.etime);
                  }
                }
              ]
            })
          }
        });
      }
    };
  }

})();
<|endoftext|>


<commit_before>var React = require('react'),
    _ = require('underscore'),
    windowManager = require("../windowsListSingleton");
    fin = require('../vendor/openfin.js');

var _windowManager = windowManager.getInstance(),
    animationWindows = _windowManager.getWindows(),
    blotter,
    inLoop = false,
    cubeSize = 185,
    locations = [],
    numColumns = 6,
    numRows = 3,
    demoTiles = {},
    numTiles = numRows * numColumns + 1,
// Have the grid windows been created yet?
    _tilesCreated = false;

/* Static data for the floating 'trade' animation windows */

var rndData = [
    {ticker: "PCL", last: 21.251049070187836},
    {ticker: "SWI", last: 24.835458631124418},
    {ticker: "TCK", last: 6.235665990223004},
    {ticker: "DBD", last: 17.01733357355432},
    {ticker: "FHN", last: 6.624939800309766},
    {ticker: "EXR", last: 33.96528484183794},
    {ticker: "BP", last: 21.19160933461151},
    {ticker: "WCN", last: 23.501467942817747},
    {ticker: "PRE", last: 53.67873008625956},
    {ticker: "ITT", last: 22.803668802786465},
    {ticker: "BIN", last: 12.594969339431945},
    {ticker: "WTM", last: 348.8851038882928},
    {ticker: "FHN", last: 6.624939800309766},
    {ticker: "CYH", last: 19.131071861657016},
    {ticker: "SWK", last: 52.198226722926165},
    {ticker: "AMG", last: 127.23849660464248},
    {ticker: "BCE", last: 22.765628088640174},
    {ticker: "ACC", last: 14.787034222549517},
    {ticker: "AA", last: 13.787034222549517}];

var floor = Math.floor;
var random = Math.random;

fin.desktop.main(()=>{

    initAnimationWindows().then(function(val){
        fin.desktop.System.deleteCacheOnRestart(function () {
            console.log("successfully deleted cache");
        },function (err) {
            console.log("failure to delete cache: " + err);
        });

        fin.desktop.System.addEventListener('monitor-info-changed', function (evnt) {
            console.log("The monitor information has changed to: ", evnt);
            document.dispatchEvent(new CustomEvent('monitor-changed', {'detail': evnt}));
        }, function () {
            console.log("The registration of 'monitor-info-changed' was successful");
        },function (err) {
            console.log("failure: registration of 'monitor-info-changed' " + err);
        });
    });
});

/* Initialises all the floating 'trade' windows. */
var initAnimationWindows = function(){
    console.log("initAnimationWindows called _tilesCreated == ",_tilesCreated);
    return new Promise(function(resolve, reject){
        if(_tilesCreated){
            resolve()
        } else{
            var top = 5, left = 5, i = 1;
            for (; i < numTiles; i++){
                console.log("LOOP ",i, " numTiles ",numTiles);
                animationWindows.push(new fin.desktop.Window({
                    name: 'tile' + random(),
                    url: 'trade.html?t=' + rndData[i].ticker + '&l=' + rndData[i].last,
                    autoShow: false,
                    defaultHeight: cubeSize,
                    minHeight: cubeSize,
                    maxHeight:cubeSize,
                    defaultWidth: cubeSize,
                    minWidth:cubeSize,
                    maxWidth:cubeSize,
                    resizable:false,
                    frame: false,
                    maximizable: false,
                    saveWindowState: false,
                    defaultTop: top,
                    defaultLeft: left,
                    icon: "http://demoappdirectory.openf.in/desktop/config/apps/OpenFin/HelloOpenFin/img/openfin.ico"
                }));

                locations.push({
                    top: top,
                    left: left,
                    duration: 1000
                });

                left += cubeSize + 5;

                if (i && !(i % numColumns)) {
                    left = 5;
                    top += cubeSize + 5;
                }
                if(i === numTiles-1){
                    console.log(" _tilesCreated === true");
                    _tilesCreated = true;
                    resolve();
                }
            }
        }
    });
};

/* If the blotter has not been created yet, create it and return a promise...*/
var initBlotter = function(){
    var _blotterPromise = new Promise((resolve, reject)=>{
        blotter = new fin.desktop.Window({
            name: 'blotter',
            url: 'hypergrid.html',
            autoShow: false,
            defaultWidth: 960,
            maxWidth: 960,
            minWidth: 960,
            maxHeight: 594,
            defaultHeight: 594,
            minHeight: 594,
            resizable:false,
            frame: false,
            maximizable: false,
            "icon": "http://demoappdirectory.openf.in/desktop/config/apps/OpenFin/HelloOpenFin/img/openfin.ico"
        }, ()=>{
            resolve();
        })
    });
    return _blotterPromise
}

function showAsPromise (wnd) {
    return new Promise((resolve)=>{
        fin.desktop.main(()=>{
            wnd.show(()=>{
                resolve();
            },()=>{
                reject();
            });
        })
    })
}

function setTranspatentAsPromise(arr, opacity) {
    return new Promise((transparentFinished, transparentFailed)=>{
        Promise.all(arr.map((item)=>{
            return new Promise((resolve, reject)=>{
                item.updateOptions({opacity: opacity}, ()=>{
                    resolve();
                }, ()=>{
                    reject()
                });
            });
        }))
            .then(()=>{
                transparentFinished();
            }, ()=>{
                transparentFailed();
            });
    });
}

module.exports = React.createClass({
    closeApp: function(){
        fin.desktop.main(function(){
            fin.desktop.Application.getCurrent().close();
        });
    },
    minApp: function(){
        console.log("MINIFYING APP.")
        fin.desktop.main(function(){
            fin.desktop.Window.getCurrent().minimize();
        });
    },
    showWindows: function(){
        console.log("showWindows called");
        animationWindows.forEach((wnd)=>{
            try{
                wnd.show();
            }catch(err){
                //--
            }
        });
        this.animateWindows(animationWindows, false);
        this.setState({
            animationWindowsShowing: true,
            tilesMaximised: true
        });
    },
    toggleMinimised:function(){
        this.state.tilesMaximised ? this.minWindows() : this.restoreWindows();
    },
    minWindows: function() {
        animationWindows.forEach((wnd)=>{
            wnd.minimize();
        });
        this.setState({
            tilesMaximised: false
        })
    },
    restoreWindows: function () {
        this.openAnimationWindows();
        animationWindows.forEach((wnd)=>{
            wnd.restore();
        });

        this.setState({
            animationWindowsShowing: true,
            tilesMaximised: true
        })
    },
    toggleShowAnimationWindows:function(){
        console.log("toggleShowAnimationWindows called this. openAnimationWindows = ", this.openAnimationWindows);
        if(this.state.animationWindowsShowing){
            this.openAnimationWindows()
        }else{
            this.closeAnimationWindows();
        }
    },
    openAnimationWindows:function(){
        console.log(" openAnimationWindows called ");
        initAnimationWindows().then(()=>{
            console.log(" initAnimationWindows resolved ");
            this.showWindows();
        });
    },
    closeAnimationWindows: function(){
        this.toggleAnimateLoopStop();
        animationWindows.forEach((wnd)=>{
            wnd.close();
        });

        this.setState({
            animationWindowsShowing: false,
            tilesMaximised: false
        })
    },
    toggleAnimateLoop:function(){
        inLoop ? this.toggleAnimateLoopStop() : this.toggleAnimateLoopStart();
    },
    toggleAnimateLoopStart: function () {
        inLoop = true;
        this.setState({"inLoop":true});
        if (inLoop) {
            this.animateWindows(animationWindows);
        }
    },
    toggleAnimateLoopStop: function () {
        inLoop = false;
        this.setState({"inLoop":false});
    },
    // Abstracted out the function for randomising
    randomiseAnimationWindows: function(){
        return animationWindows
            .reduce(function(m, itm, idx, a) {
                m[0].push(m[1].splice(floor((random() * m[1].length)), 1)[0]);
                return m
            }, [
                [], animationWindows.slice()
            ])[0]
    },

    animateWindows: function(animationWindows, randomise){
        //Unless explicitly asked not to, randomise
        var _randomise = randomise !== false ? true : false;
        var _arr = _randomise ?  this.randomiseAnimationWindows() : animationWindows;
        setTranspatentAsPromise(animationWindows, 0.5).then(()=>{
            Promise.all(
                _arr
                    .map((item, index) => {
                        return new Promise((resolve, reject) => {
                            try{
                                item.animate({
                                    position: locations[index]
                                }, {}, () => {
                                    resolve()
                                })
                            }catch(err){
                                //-----
                            }
                        });
                    })
            ).then(() => {
                    setTranspatentAsPromise(animationWindows, 1).then(() => {
                        if (inLoop) {
                            setTimeout(() => {
                                this.animateWindows(animationWindows)
                            }, 700);
                        }
                    })
                });
        });
    },
    openBlotter: function(){
        if(!blotter){
            initBlotter().then(function(b){
                blotter.show();
            });
        }else{
            blotter.show();
        }
    },
    componentDidMount: function(){
        console.log('Component did mount...', this);
        var _repositionWindows = function(){
            if(!this.state.inLoop &&  this.state.animationWindowsShowing){
                this.animateWindows.call(this, animationWindows, false);
            }
        }.bind(this);

        document.addEventListener('monitor-changed', function(e){
            _repositionWindows();
        })
    },
    openExcel: function() {

        fin.desktop.main(function() {

          fin.desktop.System.launchExternalProcess({
            alias: 'hypergrid',
            arguments: '',
            listener: function(event){
               // react to close event
              if(event.topic === "exited" && event.exitCode === MY_KNOWN_BAD_STATE) {
                // your desired logic here
              }
            }
          });
        });

    },
    getInitialState: function(){
        return {
            animationWindowsShowing: false,
            tilesMaximised: false,
            inLoop : false
        }
    },
    getAnimationWindowsStyle:function(){
        return this.state.animationWindowsShowing ? "none" : "menuitem";
    },
    getAnimateClass:function(){
        if(this.state.animationWindowsShowing ){
            return this.state.inLoop ?  "fa fa-pause" : "fa fa-play";
        } else{
            return "none";
        }
    },

    getAnimateParentClass:function(){
        if(this.state.animationWindowsShowing ){
            return {"display" : "none"};
        } else{
            return {"display":"block"};
        }
    },

    getAnimateText:function(){
        if(this.state.animationWindowsShowing ){
            return this.state.inLoop ?   "Pause animation" :  "Play animation" ;
        }else{
            return "";
        }
    },
    getMinifyText:function(){
        if(this.state.animationWindowsShowing ){
            return this.state.tilesMaximised ?  {text: " Minimise", style: {"display" :"block"}, css: "none", icon:"fa fa-sort-amount-desc"} : {text: " Maximise", css: "", style: {"display" :"block"}, icon:"fa fa-sort-amount-asc"};
        } else{
            return {text: "Minimise", style: {"display" :"none"}, css: "none", icon:"fa fa-sort-amount-desc"};
        }
    },
    openGithub: function(){
        fin.desktop.System.openUrlWithBrowser("https://github.com/openfin/Hyperblotter/tree/develop", function () {
        },function (err) {
            console.log("Failed to open GitHub: " + err);
        });
    },
    render: function(){
        return

                <image className="" type="image/svg+xml" src="images/hyperblotter_sidetext.svg" />

    }
});

//function genPairs(arr) {
//    return arr.reduce(function(m, itm, idx, a) {
//        m[0].push(m[1].splice(floor((random() * m[1].length)), 1)[0]);
//        return m
//    }, [[], arr.slice()])[0].reduce(function(m, itm, idx, a) {
//
//            if (!(idx % 2)) {
//                m.push([itm, a[idx + 1]]);
//            }
//            return m
//        }, [])
//}

/*
 <image className="openfinLogo" type="image/svg+xml" src="images/openfin_logo.svg" />

 */<commit_msg>Added stop animation on window mimimise - still needs some refinement when cklosed during animation and reopened.<commit_after>var React = require('react'),
    _ = require('underscore'),
    windowManager = require("../windowsListSingleton");
    fin = require('../vendor/openfin.js');

var _windowManager = windowManager.getInstance(),
    animationWindows = _windowManager.getWindows(),
    blotter,
    inLoop = false,
    cubeSize = 185,
    locations = [],
    numColumns = 6,
    numRows = 3,
    demoTiles = {},
    numTiles = numRows * numColumns + 1,
// Have the grid windows been created yet?
    _tilesCreated = false;

/* Static data for the floating 'trade' animation windows */

var rndData = [
    {ticker: "PCL", last: 21.251049070187836},
    {ticker: "SWI", last: 24.835458631124418},
    {ticker: "TCK", last: 6.235665990223004},
    {ticker: "DBD", last: 17.01733357355432},
    {ticker: "FHN", last: 6.624939800309766},
    {ticker: "EXR", last: 33.96528484183794},
    {ticker: "BP", last: 21.19160933461151},
    {ticker: "WCN", last: 23.501467942817747},
    {ticker: "PRE", last: 53.67873008625956},
    {ticker: "ITT", last: 22.803668802786465},
    {ticker: "BIN", last: 12.594969339431945},
    {ticker: "WTM", last: 348.8851038882928},
    {ticker: "FHN", last: 6.624939800309766},
    {ticker: "CYH", last: 19.131071861657016},
    {ticker: "SWK", last: 52.198226722926165},
    {ticker: "AMG", last: 127.23849660464248},
    {ticker: "BCE", last: 22.765628088640174},
    {ticker: "ACC", last: 14.787034222549517},
    {ticker: "AA", last: 13.787034222549517}];

var floor = Math.floor;
var random = Math.random;

fin.desktop.main(()=>{

    initAnimationWindows().then(function(val){
        fin.desktop.System.deleteCacheOnRestart(function () {
            console.log("successfully deleted cache");
        },function (err) {
            console.log("failure to delete cache: " + err);
        });

        fin.desktop.System.addEventListener('monitor-info-changed', function (evnt) {
            console.log("The monitor information has changed to: ", evnt);
            document.dispatchEvent(new CustomEvent('monitor-changed', {'detail': evnt}));
        }, function () {
            console.log("The registration of 'monitor-info-changed' was successful");
        },function (err) {
            console.log("failure: registration of 'monitor-info-changed' " + err);
        });
    });
});

/* Initialises all the floating 'trade' windows. */
var initAnimationWindows = function(){
    console.log("initAnimationWindows called _tilesCreated == ",_tilesCreated);
    return new Promise(function(resolve, reject){
        if(_tilesCreated){
            resolve()
        } else{
            var leftOffset = 105, topOffset = 50, top = topOffset, left = leftOffset, tileMargin = 8,  i = 1;
            for (; i < numTiles; i++){
                console.log("LOOP ",i, " numTiles ",numTiles);
                animationWindows.push(new fin.desktop.Window({
                    name: 'tile' + random(),
                    url: 'trade.html?t=' + rndData[i].ticker + '&l=' + rndData[i].last,
                    autoShow: false,
                    defaultHeight: cubeSize,
                    minHeight: cubeSize,
                    maxHeight:cubeSize,
                    defaultWidth: cubeSize,
                    minWidth:cubeSize,
                    maxWidth:cubeSize,
                    resizable:false,
                    frame: false,
                    maximizable: false,
                    saveWindowState: false,
                    defaultTop: top,
                    defaultLeft: left,
                    icon: "http://demoappdirectory.openf.in/desktop/config/apps/OpenFin/HelloOpenFin/img/openfin.ico"
                }));

                locations.push({
                    top: top,
                    left: left,
                    duration: 1000
                });

                left += cubeSize + tileMargin;

                if (i && !(i % numColumns)) {
                    left = leftOffset;
                    top += cubeSize + tileMargin;
                }
                if(i === numTiles-1){
                    console.log(" _tilesCreated === true");
                    _tilesCreated = true;
                    resolve();
                }
            }
        }
    });
};

/* If the blotter has not been created yet, create it and return a promise...*/
var initBlotter = function(){
    var _blotterPromise = new Promise((resolve, reject)=>{
        blotter = new fin.desktop.Window({
            name: 'blotter',
            url: 'hypergrid.html',
            autoShow: false,
            defaultWidth: 960,
            maxWidth: 960,
            minWidth: 960,
            maxHeight: 594,
            defaultHeight: 594,
            minHeight: 594,
            resizable:false,
            frame: false,
            maximizable: false,
            "icon": "http://demoappdirectory.openf.in/desktop/config/apps/OpenFin/HelloOpenFin/img/openfin.ico"
        }, ()=>{
            resolve();
        })
    });
    return _blotterPromise
}

function showAsPromise (wnd) {
    return new Promise((resolve)=>{
        fin.desktop.main(()=>{
            wnd.show(()=>{
                resolve();
            },()=>{
                reject();
            });
        })
    })
}

function setTranspatentAsPromise(arr, opacity) {
    return new Promise((transparentFinished, transparentFailed)=>{
        Promise.all(arr.map((item)=>{
            return new Promise((resolve, reject)=>{
                item.updateOptions({opacity: opacity}, ()=>{
                    resolve();
                }, ()=>{
                    reject()
                });
            });
        }))
            .then(()=>{
                transparentFinished();
            }, ()=>{
                transparentFailed();
            });
    });
}

module.exports = React.createClass({
    closeApp: function(){
        fin.desktop.main(function(){
            fin.desktop.Application.getCurrent().close();
        });
    },
    minApp: function(){
        console.log("MINIFYING APP.")
        fin.desktop.main(function(){
            fin.desktop.Window.getCurrent().minimize();
        });
    },
    showWindows: function(){
        console.log("showWindows called");
        animationWindows.forEach((wnd)=>{
            try{
                wnd.show();
            }catch(err){
                //--
            }
        });
        this.animateWindows(animationWindows, false);
        this.setState({
            animationWindowsShowing: true,
            tilesMaximised: true
        });
    },
    toggleMinimised:function(){
        this.state.tilesMaximised ? this.minWindows() : this.restoreWindows();
    },
    minWindows: function() {
        this.toggleAnimateLoopStop();

        animationWindows.forEach((wnd)=>{
            wnd.minimize();
        });
        this.setState({
            tilesMaximised: false
        })
    },
    restoreWindows: function () {
        this.openAnimationWindows();
        animationWindows.forEach((wnd)=>{
            wnd.restore();
        });

        this.setState({
            animationWindowsShowing: true,
            tilesMaximised: true
        })
    },
    toggleShowAnimationWindows:function(){
        console.log("toggleShowAnimationWindows called this. openAnimationWindows = ", this.openAnimationWindows);
        if(this.state.animationWindowsShowing){
            this.openAnimationWindows()
        }else{
            this.closeAnimationWindows();
        }
    },
    openAnimationWindows:function(){
        console.log(" openAnimationWindows called ");
        initAnimationWindows().then(()=>{
            console.log(" initAnimationWindows resolved ");
            this.showWindows();
        });
    },
    closeAnimationWindows: function(){
        this.toggleAnimateLoopStop();
        animationWindows.forEach((wnd)=>{
            wnd.close();
        });

        this.setState({
            animationWindowsShowing: false,
            tilesMaximised: false
        })
    },
    toggleAnimateLoop:function(){
        inLoop ? this.toggleAnimateLoopStop() : this.toggleAnimateLoopStart();
    },
    toggleAnimateLoopStart: function () {
        inLoop = true;
        this.setState({"inLoop":true});
        if (inLoop) {
            this.animateWindows(animationWindows);
        }
    },
    toggleAnimateLoopStop: function () {
        inLoop = false;
        this.setState({"inLoop":false});
    },
    // Abstracted out the function for randomising
    randomiseAnimationWindows: function(){
        return animationWindows
            .reduce(function(m, itm, idx, a) {
                m[0].push(m[1].splice(floor((random() * m[1].length)), 1)[0]);
                return m
            }, [
                [], animationWindows.slice()
            ])[0]
    },

    animateWindows: function(animationWindows, randomise){
        //Unless explicitly asked not to, randomise
        var _randomise = randomise !== false ? true : false;
        var _arr = _randomise ?  this.randomiseAnimationWindows() : animationWindows;
        setTranspatentAsPromise(animationWindows, 0.5).then(()=>{
            Promise.all(
                _arr
                    .map((item, index) => {
                        return new Promise((resolve, reject) => {
                            try{
                                item.animate({
                                    position: locations[index]
                                }, {}, () => {
                                    resolve()
                                })
                            }catch(err){
                                //-----
                            }
                        });
                    })
            ).then(() => {
                    setTranspatentAsPromise(animationWindows, 1).then(() => {
                        if (inLoop) {
                            setTimeout(() => {
                                this.animateWindows(animationWindows)
                            }, 700);
                        }
                    })
                });
        });
    },
    openBlotter: function(){
        if(!blotter){
            initBlotter().then(function(b){
                blotter.show();
            });
        }else{
            blotter.show();
        }
    },
    componentDidMount: function(){
        console.log('Component did mount...', this);
        var _repositionWindows = function(){
            if(!this.state.inLoop &&  this.state.animationWindowsShowing){
                this.animateWindows.call(this, animationWindows, false);
            }
        }.bind(this);

        document.addEventListener('monitor-changed', function(e){
            _repositionWindows();
        })
    },
    openExcel: function() {

        fin.desktop.main(function() {

          fin.desktop.System.launchExternalProcess({
            alias: 'hypergrid',
            arguments: '',
            listener: function(event){
               // react to close event
              if(event.topic === "exited" && event.exitCode === MY_KNOWN_BAD_STATE) {
                // your desired logic here
              }
            }
          });
        });

    },
    getInitialState: function(){
        return {
            animationWindowsShowing: false,
            tilesMaximised: false,
            inLoop : false
        }
    },
    getAnimationWindowsStyle:function(){
        return this.state.animationWindowsShowing ? "none" : "menuitem";
    },
    getAnimateClass:function(){
        if(this.state.animationWindowsShowing ){
            return this.state.inLoop ?  "fa fa-pause" : "fa fa-play";
        } else{
            return "none";
        }
    },

    getAnimateParentClass:function(){
        if(this.state.animationWindowsShowing ){
            return {"display" : "none"};
        } else{
            return {"display":"block"};
        }
    },

    getAnimateText:function(){
        if(this.state.animationWindowsShowing ){
            return this.state.inLoop ?   "Pause animation" :  "Play animation" ;
        }else{
            return "";
        }
    },
    getMinifyText:function(){
        if(this.state.animationWindowsShowing ){
            return this.state.tilesMaximised ?  {text: " Minimise", style: {"display" :"block"}, css: "none", icon:"fa fa-sort-amount-desc"} : {text: " Maximise", css: "", style: {"display" :"block"}, icon:"fa fa-sort-amount-asc"};
        } else{
            return {text: "Minimise", style: {"display" :"none"}, css: "none", icon:"fa fa-sort-amount-desc"};
        }
    },
    openGithub: function(){
        fin.desktop.System.openUrlWithBrowser("https://github.com/openfin/Hyperblotter/tree/develop", function () {
        },function (err) {
            console.log("Failed to open GitHub: " + err);
        });
    },
    render: function(){
        return

                <image className="" type="image/svg+xml" src="images/hyperblotter_sidetext.svg" />

    }
});

//function genPairs(arr) {
//    return arr.reduce(function(m, itm, idx, a) {
//        m[0].push(m[1].splice(floor((random() * m[1].length)), 1)[0]);
//        return m
//    }, [[], arr.slice()])[0].reduce(function(m, itm, idx, a) {
//
//            if (!(idx % 2)) {
//                m.push([itm, a[idx + 1]]);
//            }
//            return m
//        }, [])
//}

/*
 <image className="openfinLogo" type="image/svg+xml" src="images/openfin_logo.svg" />

 */<|endoftext|>


<commit_before>;(function ($, window, document, undefined) {

  "use strict";

  // Create the defaults once
  var pluginName = "slashesAndCircles";
  var defaults = {
    elements: $(".slashes, .circles"),
    avoid: [],
    allowAnimation: true
  };

  // The actual plugin constructor
  function Plugin(element, options) {
    this.element = element;
    this.settings = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
  }

  // Avoid Plugin.prototype conflicts
  $.extend(Plugin.prototype, {
    initSlashKeypress: function (){
      var self = this;
      $(document).keypress(function (e) {
        if (e.which === 47) {
          self.randomizePositions(true);
        }
      });
    }, initResizeReflow: function () {
      var resizeTimer;
      $(window).on("resize", function () {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function () {
          // Run code here, resizing has "stopped"
          self.randomizePositions(false);
        }, 250);
      });
    }, init: function () {

      // check if TweenLite (a dependency) is defined
      if (typeof TweenLite !== "function") {
        console.error("TweenLite is not initialized. Quitting...");
        return;
      }

      // Place initialization logic here
      // You already have access to the DOM element and
      // the options via the instance, e.g. this.element
      // and this.settings
      // you can add more functions like the one below and
      // call them like the example below
      this.randomizePositions(true);

      // Randomize elements with /
      this.initSlashKeypress();

      // Finished resizing? Randomize elements
      this.initResizeReflow();
    },
    addAvoidCoords: function (){
      return $(this.settings.avoid).map(function (i, el) {
        var offset = $(el).offset();
        return {
          w: $(el).width(),
          h: $(el).height(),
          x: offset.left,
          y: offset.top
        };
      });
    }, randomizePositions: function (animatePositions) {
      var numberLimit;
      var limitElements;
      var percentageMedium;
      var positions;
      var svg;
      var self;

      self = this;

      // Get width and height of SVG
      svg = {
        w: this.element.getBBox().width,
        h: this.element.getBBox().height
      };

      // Add elements to avoid to positions array
      positions = this.addAvoidCoords();

      // 0 -> 21 elements (reach 21 by medium-up size)
      percentageMedium = ($(window).width() / 640);
      limitElements = (percentageMedium <= 1);
      numberLimit = Math.floor(percentageMedium * this.settings.elements.length) - 8;

      this.settings.elements.css({visibility: "hidden"}).each(function (i) {
        var tweenTo;
        var tweenFrom;
        var coords;

        if (limitElements && numberLimit === 0) {
          // console.log("limited");
          return;
        }

        coords = {
          w: $(this).data("width"),
          h: $(this).data("height")
        };

        var success = false;
        var maxTries = 50;

        // while we haven't found a spot that has no collisions, and max tries aren't exceeded
        while (!success && maxTries >= 0) {
          // randomize coordinates
          coords.x = parseInt(Math.random() * (svg.w - coords.w));
          coords.y = parseInt(Math.random() * (svg.h - coords.h));
          success = true;
          // make sure we haven't collided with anything previously placed
          for (var j = 0; j < positions.length; j++) {
            // if there's a collision
            if (
              coords.x <= (positions[j].x + positions[j].w) &&
              (coords.x + coords.w) >= positions[j].x &&
              coords.y <= (positions[j].y + positions[j].h) &&
              (coords.y + coords.h) >= positions[j].y
            ) {
              // we haven't succeeded, try again
              success = false;
            }
          }
          maxTries--;
        }

        // if we've reached the maximum amount of tries, hide and quit
        if (maxTries <= 0) {
          $(this).css({opacity: 0});
          // console.log("max tries exceeded", $(this));
          return;
        }

        positions.push(coords);

        // Animation time!
        // properties to tween from
        tweenFrom = {
          x: (coords.x - 663), // ~57.9% height to width ratio = 663/1145
          y: (coords.y + 1000),
          opacity: 0,
          visibility: "visible"
        };

        // properties to tween to
        tweenTo = {
          x: coords.x,
          y: coords.y,
          opacity: 1,
          visibility: "visible"
        };

        // if we want things to animate
        if (animatePositions === true && self.settings.allowAnimation === true) {
          tweenTo.ease = Expo.easeOut;
          tweenTo.delay = i * 0.05;
          TweenLite.fromTo($(this), 1, tweenFrom, tweenTo);
        } else {
          TweenLite.set($(this), tweenTo);
        }

        numberLimit--;
      });
    }
  });

  // A really lightweight plugin wrapper around the constructor,
  // preventing against multiple instantiations
  $.fn[pluginName] = function (options) {
    return this.each(function () {
      if (!$.data(this, "plugin_" + pluginName)) {
        $.data(this, "plugin_" + pluginName, new Plugin(this, options));
      }
    });
  };

})(jQuery, window, document);
<commit_msg>Only add avoid coordinates when needed<commit_after>;(function ($, window, document, undefined) {

  "use strict";

  // Create the defaults once
  var pluginName = "slashesAndCircles";
  var defaults = {
    elements: $(".slashes, .circles"),
    avoid: [],
    allowAnimation: true
  };

  // The actual plugin constructor
  function Plugin(element, options) {
    this.element = element;
    this.settings = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
  }

  // Avoid Plugin.prototype conflicts
  $.extend(Plugin.prototype, {
    initSlashKeypress: function (){
      var self = this;
      $(document).keypress(function (e) {
        if (e.which === 47) {
          self.randomizePositions(true);
        }
      });
    }, initResizeReflow: function () {
      var resizeTimer;
      var self = this;
      $(window).on("resize", function () {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function () {
          // need to recalculate avoidCoords since the screen size has changed
          self.avoidCoords = self.addAvoidCoords();
          self.randomizePositions(false);
        }, 250);
      });
    }, init: function () {
      // check if TweenLite (a dependency) is defined
      if (typeof TweenLite !== "function") {
        console.error("TweenLite is not initialized. Quitting...");
        return;
      }

      this.avoidCoords = this.addAvoidCoords();

      this.randomizePositions(true);

      // Randomize elements with /
      this.initSlashKeypress();

      // Finished resizing? Randomize elements
      this.initResizeReflow();
    },
    addAvoidCoords: function (){
      return $(this.settings.avoid).map(function (i, el) {
        var offset = $(el).offset();
        return {
          w: $(el).width(),
          h: $(el).height(),
          x: offset.left,
          y: offset.top
        };
      });
    }, randomizePositions: function (animatePositions) {
      var numberLimit;
      var limitElements;
      var percentageMedium;
      var positions;
      var svg;
      var self;

      self = this;

      // Get width and height of SVG
      svg = {
        w: this.element.getBBox().width,
        h: this.element.getBBox().height
      };

      // Add elements to avoid to positions array
      positions = jQuery.extend(true, {}, this.avoidCoords);

      // 0 -> 21 elements (reach 21 by medium-up size)
      percentageMedium = ($(window).width() / 640);
      limitElements = (percentageMedium <= 1);
      numberLimit = Math.floor(percentageMedium * this.settings.elements.length) - 8;

      this.settings.elements.css({visibility: "hidden"}).each(function (i) {
        var tweenTo;
        var tweenFrom;
        var coords;

        if (limitElements && numberLimit === 0) {
          // console.log("limited");
          return;
        }

        coords = {
          w: $(this).data("width"),
          h: $(this).data("height")
        };

        var success = false;
        var maxTries = 50;

        // while we haven't found a spot that has no collisions, and max tries aren't exceeded
        while (!success && maxTries >= 0) {
          // randomize coordinates
          coords.x = parseInt(Math.random() * (svg.w - coords.w));
          coords.y = parseInt(Math.random() * (svg.h - coords.h));
          success = true;
          // make sure we haven't collided with anything previously placed
          for (var j = 0; j < positions.length; j++) {
            // if there's a collision
            if (
              coords.x <= (positions[j].x + positions[j].w) &&
              (coords.x + coords.w) >= positions[j].x &&
              coords.y <= (positions[j].y + positions[j].h) &&
              (coords.y + coords.h) >= positions[j].y
            ) {
              // we haven't succeeded, try again
              success = false;
            }
          }
          maxTries--;
        }

        // if we've reached the maximum amount of tries, hide and quit
        if (maxTries <= 0) {
          $(this).css({opacity: 0});
          // console.log("max tries exceeded", $(this));
          return;
        }

        positions.push(coords);

        // Animation time!
        // properties to tween from
        tweenFrom = {
          x: (coords.x - 663), // ~57.9% height to width ratio = 663/1145
          y: (coords.y + 1000),
          opacity: 0,
          visibility: "visible"
        };

        // properties to tween to
        tweenTo = {
          x: coords.x,
          y: coords.y,
          opacity: 1,
          visibility: "visible"
        };

        // if we want things to animate
        if (animatePositions === true && self.settings.allowAnimation === true) {
          tweenTo.ease = Expo.easeOut;
          tweenTo.delay = i * 0.05;
          TweenLite.fromTo($(this), 1, tweenFrom, tweenTo);
        } else {
          TweenLite.set($(this), tweenTo);
        }

        numberLimit--;
      });
    }
  });

  // A really lightweight plugin wrapper around the constructor,
  // preventing against multiple instantiations
  $.fn[pluginName] = function (options) {
    return this.each(function () {
      if (!$.data(this, "plugin_" + pluginName)) {
        $.data(this, "plugin_" + pluginName, new Plugin(this, options));
      }
    });
  };

})(jQuery, window, document);
<|endoftext|>


<commit_before>app.service('TopicService', ['$rootScope', '$firebase', function($rootScope, $firebase) {
  var topicsRef = $firebase(fb.child('topics'));

  this.list = function() {
    return topicsRef;
  };

  this.add = function(topic) {
    topicsRef.$add(topic);
  };

  this.remove = function(topic) {
    topicsRef.$child(topic.$id).$remove();
  };

}]);<commit_msg>Add user reference to topic<commit_after>app.service('TopicService', ['$rootScope', '$firebase', function($rootScope, $firebase) {
  var topicsRef = $firebase(fb.child('topics'));

  this.list = function() {
    return topicsRef;
  };

  this.add = function(topic) {
    topic['user'] = $rootScope.user.given_name;
    topicsRef.$add(topic);
  };

  this.remove = function(topic) {
    topicsRef.$child(topic.$id).$remove();
  };

}]);<|endoftext|>


<commit_before>// -*- indent-tabs-mode: nil; tab-width: 2; -*-
// Copyright (C) 2013 Colin Walters <walters@verbum.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.

const GLib = imports.gi.GLib;
const Gio = imports.gi.Gio;
const Lang = imports.lang;
const Format = imports.format;

const GSystem = imports.gi.GSystem;
const OSTree = imports.gi.OSTree;

const Toolbox = imports.gi.Toolbox;

const Builtin = imports.builtin;
const ArgParse = imports.argparse;
const ProcUtil = imports.procutil;
const LibQA = imports.libqa;
const GuestFish = imports.guestfish;

const CreateVmDisk = new Lang.Class({
    Name: 'CreateVmDisk',
    Extends: Builtin.Builtin,

    DESCRIPTION: "Generate a qcow2 disk image",

    _init: function() {
        this.parent();
        this.parser.addArgument('--unconfigured-state', { description: 'Error mesage to use if OS needs further configuration' });
        this.parser.addArgument('repo');
        this.parser.addArgument('osname');
        this.parser.addArgument('ref');
        this.parser.addArgument('diskpath');
    },

    execute: function(args, loop, cancellable) {

        let enforcing = ProcUtil.runSyncGetOutputUTF8Stripped(['getenforce'], cancellable);
        if (enforcing != 'Disabled') {
            throw new Error("SELinux must be disabled; see https://bugzilla.redhat.com/show_bug.cgi?id=1060423");
        }

        Toolbox.unshare_namespaces(Toolbox.NamespaceFlags.MOUNT);
        Toolbox.remount_rootfs_private();

        let repoPath = Gio.File.new_for_path(args.repo);
        let repo = new OSTree.Repo({ path: repoPath });
        let [,rev] = repo.resolve_rev(args.ref, false);
        let path = Gio.File.new_for_path(args.diskpath);
        if (path.query_exists(null))
            throw new Error("" + path.get_path() + " exists");
        let tmppath = path.get_parent().get_child(path.get_basename() + '.tmp');
        GSystem.shutil_rm_rf(tmppath, cancellable);
        LibQA.createDisk(tmppath, cancellable);
        let tmpdir = Gio.File.new_for_path(GLib.dir_make_tmp('rpmostreetoolbox.XXXXXX'));
        let mntdir = tmpdir.get_child('mnt');
        GSystem.file_ensure_directory(mntdir, true, cancellable);
        let gfmnt = new GuestFish.GuestMount(tmppath, { partitionOpts: LibQA.DEFAULT_GF_PARTITION_OPTS,
                                                            readWrite: true });
        gfmnt.mount(mntdir, cancellable);
        try {
            let osname = args['osname'];
            LibQA.pullDeploy(mntdir, repoPath, osname, args.ref, rev, null,
                             cancellable, { addKernelArgs: [], unconfiguredState: args.unconfigured_state });
            print("Doing initial labeling");
            ProcUtil.runSync(['ostree', 'admin', '--sysroot=' + mntdir.get_path(),
                              'instutil', 'selinux-ensure-labeled',
		                          mntdir.get_path(),
		                          ""],
		                         cancellable,
		                         { logInitiation: true });
            let [sysroot, current] = LibQA.getSysrootAndCurrentDeployment(mntdir, osname);
            let deployDir = sysroot.get_deployment_directory(current);
            let etcSysconfigDockerStorage = deployDir.resolve_relative_path('etc/sysconfig/docker-storage');
            if (etcSysconfigDockerStorage.query_exists(null)) {
                print("Updating Docker storage: " + etcSysconfigDockerStorage.get_path());
                etcSysconfigDockerStorage.replace_contents('DOCKER_STORAGE_OPTIONS=--storage-opt dm.fs=xfs --storage-opt dm.datadev=/dev/mapper/atomicos-docker--data --storage-opt dm.metadatadev=/dev/mapper/atomicos-docker--meta\n', null, false, 0, null);
            } else {
                print("No Docker storage config detected in " + etcSysconfigDockerStorage.get_path());
            }
        } finally {
            gfmnt.umount(cancellable);
        }
        GSystem.file_rename(tmppath, path, cancellable);
        GSystem.shutil_rm_rf(tmpdir, cancellable);
        print("Created: " + path.get_path());
    }
});
<commit_msg>create-vm-disk: Add --origin-url argument<commit_after>// -*- indent-tabs-mode: nil; tab-width: 2; -*-
// Copyright (C) 2013 Colin Walters <walters@verbum.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.

const GLib = imports.gi.GLib;
const Gio = imports.gi.Gio;
const Lang = imports.lang;
const Format = imports.format;

const GSystem = imports.gi.GSystem;
const OSTree = imports.gi.OSTree;

const Toolbox = imports.gi.Toolbox;

const Builtin = imports.builtin;
const ArgParse = imports.argparse;
const ProcUtil = imports.procutil;
const LibQA = imports.libqa;
const GuestFish = imports.guestfish;

const CreateVmDisk = new Lang.Class({
    Name: 'CreateVmDisk',
    Extends: Builtin.Builtin,

    DESCRIPTION: "Generate a qcow2 disk image",

    _init: function() {
        this.parent();
        this.parser.addArgument('--unconfigured-state', { description: 'Error mesage to use if OS needs further configuration' });
        this.parser.addArgument('--origin-url', { description: 'URL for origin remote' });
        this.parser.addArgument('repo');
        this.parser.addArgument('osname');
        this.parser.addArgument('ref');
        this.parser.addArgument('diskpath');
    },

    execute: function(args, loop, cancellable) {

        let enforcing = ProcUtil.runSyncGetOutputUTF8Stripped(['getenforce'], cancellable);
        if (enforcing != 'Disabled') {
            throw new Error("SELinux must be disabled; see https://bugzilla.redhat.com/show_bug.cgi?id=1060423");
        }

        Toolbox.unshare_namespaces(Toolbox.NamespaceFlags.MOUNT);
        Toolbox.remount_rootfs_private();

        let repoPath = Gio.File.new_for_path(args.repo);
        let repo = new OSTree.Repo({ path: repoPath });
        let [,rev] = repo.resolve_rev(args.ref, false);
        let path = Gio.File.new_for_path(args.diskpath);
        if (path.query_exists(null))
            throw new Error("" + path.get_path() + " exists");
        let tmppath = path.get_parent().get_child(path.get_basename() + '.tmp');
        GSystem.shutil_rm_rf(tmppath, cancellable);
        LibQA.createDisk(tmppath, cancellable);
        let tmpdir = Gio.File.new_for_path(GLib.dir_make_tmp('rpmostreetoolbox.XXXXXX'));
        let mntdir = tmpdir.get_child('mnt');
        GSystem.file_ensure_directory(mntdir, true, cancellable);
        let gfmnt = new GuestFish.GuestMount(tmppath, { partitionOpts: LibQA.DEFAULT_GF_PARTITION_OPTS,
                                                            readWrite: true });
        gfmnt.mount(mntdir, cancellable);
        try {
            let osname = args['osname'];
            LibQA.pullDeploy(mntdir, repoPath, osname, args.ref, rev, args.origin_url,
                             cancellable, { addKernelArgs: [], unconfiguredState: args.unconfigured_state });
            print("Doing initial labeling");
            ProcUtil.runSync(['ostree', 'admin', '--sysroot=' + mntdir.get_path(),
                              'instutil', 'selinux-ensure-labeled',
		                          mntdir.get_path(),
		                          ""],
		                         cancellable,
		                         { logInitiation: true });
            let [sysroot, current] = LibQA.getSysrootAndCurrentDeployment(mntdir, osname);
            let deployDir = sysroot.get_deployment_directory(current);
            let etcSysconfigDockerStorage = deployDir.resolve_relative_path('etc/sysconfig/docker-storage');
            if (etcSysconfigDockerStorage.query_exists(null)) {
                print("Updating Docker storage: " + etcSysconfigDockerStorage.get_path());
                etcSysconfigDockerStorage.replace_contents('DOCKER_STORAGE_OPTIONS=--storage-opt dm.fs=xfs --storage-opt dm.datadev=/dev/mapper/atomicos-docker--data --storage-opt dm.metadatadev=/dev/mapper/atomicos-docker--meta\n', null, false, 0, null);
            } else {
                print("No Docker storage config detected in " + etcSysconfigDockerStorage.get_path());
            }
        } finally {
            gfmnt.umount(cancellable);
        }
        GSystem.file_rename(tmppath, path, cancellable);
        GSystem.shutil_rm_rf(tmpdir, cancellable);
        print("Created: " + path.get_path());
    }
});
<|endoftext|>


<commit_before>angular.module('copayApp.controllers').controller('paperWalletController',
  function($scope, $timeout, $log, $ionicModal, $ionicHistory, feeService, popupService, gettextCatalog, platformInfo, configService, profileService, $state, bitcore, ongoingProcess, txFormatService, $stateParams, walletService) {

    function _scanFunds(cb) {
      function getPrivateKey(scannedKey, isPkEncrypted, passphrase, cb) {
        if (!isPkEncrypted) return cb(null, scannedKey);
        $scope.wallet.decryptBIP38PrivateKey(scannedKey, passphrase, null, cb);
      };

      function getBalance(privateKey, cb) {
        $scope.wallet.getBalanceFromPrivateKey(privateKey, cb);
      };

      function checkPrivateKey(privateKey) {
        try {
          new bitcore.PrivateKey(privateKey, 'livenet');
        } catch (err) {
          return false;
        }
        return true;
      };

      getPrivateKey($scope.scannedKey, $scope.isPkEncrypted, $scope.passphrase, function(err, privateKey) {
        if (err) return cb(err);
        if (!checkPrivateKey(privateKey)) return cb(new Error('Invalid private key'));

        getBalance(privateKey, function(err, balance) {
          if (err) return cb(err);
          return cb(null, privateKey, balance);
        });
      });
    };

    $scope.scanFunds = function() {
      ongoingProcess.set('scanning', true);
      $timeout(function() {
        _scanFunds(function(err, privateKey, balance) {
          ongoingProcess.set('scanning', false);
          if (err) {
            $log.error(err);
            popupService.showAlert(gettextCatalog.getString('Error scanning funds:'), err || err.toString());
            $state.go('tabs.home');
          } else {
            $scope.privateKey = privateKey;
            $scope.balanceSat = balance;
            if ($scope.balanceSat <= 0)
              popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Not funds found'));
            var config = configService.getSync().wallet.settings;
            $scope.balance = txFormatService.formatAmount(balance) + ' ' + config.unitName;
          }
          $scope.$apply();
        });
      }, 100);
    };

    function _sweepWallet(cb) {
      walletService.getAddress($scope.wallet, true, function(err, destinationAddress) {
        if (err) return cb(err);

        $scope.wallet.buildTxFromPrivateKey($scope.privateKey, destinationAddress, null, function(err, testTx) {
          if (err) return cb(err);
          var rawTxLength = testTx.serialize().length;
          feeService.getCurrentFeeValue($scope.wallet, function(err, feePerKB) {
            var opts = {};
            opts.fee = Math.round((feePerKB * rawTxLength) / 2000);
            $scope.wallet.buildTxFromPrivateKey($scope.privateKey, destinationAddress, opts, function(err, tx) {
              if (err) return cb(err);
              $scope.wallet.broadcastRawTx({
                rawTx: tx.serialize(),
                network: 'livenet'
              }, function(err, txid) {
                if (err) return cb(err);
                return cb(null, destinationAddress, txid);
              });
            });
          });
        });
      });
    };

    $scope.sweepWallet = function() {
      ongoingProcess.set('sweepingWallet', true);
      $scope.sending = true;

      $timeout(function() {
        _sweepWallet(function(err, destinationAddress, txid) {
          ongoingProcess.set('sweepingWallet', false);
          $scope.sending = false;
          if (err) {
            $log.error(err);
            popupService.showAlert(gettextCatalog.getString('Error sweeping wallet:'), err || err.toString());
          } else {
            $scope.sendStatus = 'success';
          }
          $scope.$apply();
        });
      }, 100);
    };

    $scope.onSuccessConfirm = function() {
      $state.go('tabs.home');
    };

    $scope.$on('Wallet/Changed', function(event, wallet) {
      if (!wallet) {
        $log.debug('No wallet provided');
        return;
      }
      if (wallet == $scope.wallet) {
        $log.debug('No change in wallet');
        return;
      }
      $scope.wallet = wallet;
      $log.debug('Wallet changed: ' + wallet.name);
      $timeout(function() {
        $scope.$apply();
      });
    });

    $scope.$on("$ionicView.beforeEnter", function(event, data) {
      $scope.scannedKey = (data.stateParams && data.stateParams.privateKey) ? data.stateParams.privateKey : null;
      $scope.isPkEncrypted = $scope.scannedKey ? ($scope.scannedKey.substring(0, 2) == '6P') : null;
      $scope.sendStatus = null;
      $scope.error = false;

      $scope.wallets = profileService.getWallets({
        onlyComplete: true,
        network: 'livenet',
      });

      if (!$scope.wallets || !$scope.wallets.length) {
        $scope.noMatchingWallet = true;
        return;
      }
    });

    $scope.$on("$ionicView.enter", function(event, data) {
      $scope.wallet = $scope.wallets[0];
      if (!$scope.wallet) return;
      if (!$scope.isPkEncrypted) $scope.scanFunds();
      else {
        var message = gettextCatalog.getString('Private key encrypted. Enter password');
        popupService.showPrompt(null, message, null, function(res) {
          $scope.passphrase = res;
          $scope.scanFunds();
        });
      }
    });

  });
<commit_msg>fix feeService param<commit_after>angular.module('copayApp.controllers').controller('paperWalletController',
  function($scope, $timeout, $log, $ionicModal, $ionicHistory, feeService, popupService, gettextCatalog, platformInfo, configService, profileService, $state, bitcore, ongoingProcess, txFormatService, $stateParams, walletService) {

    function _scanFunds(cb) {
      function getPrivateKey(scannedKey, isPkEncrypted, passphrase, cb) {
        if (!isPkEncrypted) return cb(null, scannedKey);
        $scope.wallet.decryptBIP38PrivateKey(scannedKey, passphrase, null, cb);
      };

      function getBalance(privateKey, cb) {
        $scope.wallet.getBalanceFromPrivateKey(privateKey, cb);
      };

      function checkPrivateKey(privateKey) {
        try {
          new bitcore.PrivateKey(privateKey, 'livenet');
        } catch (err) {
          return false;
        }
        return true;
      };

      getPrivateKey($scope.scannedKey, $scope.isPkEncrypted, $scope.passphrase, function(err, privateKey) {
        if (err) return cb(err);
        if (!checkPrivateKey(privateKey)) return cb(new Error('Invalid private key'));

        getBalance(privateKey, function(err, balance) {
          if (err) return cb(err);
          return cb(null, privateKey, balance);
        });
      });
    };

    $scope.scanFunds = function() {
      ongoingProcess.set('scanning', true);
      $timeout(function() {
        _scanFunds(function(err, privateKey, balance) {
          ongoingProcess.set('scanning', false);
          if (err) {
            $log.error(err);
            popupService.showAlert(gettextCatalog.getString('Error scanning funds:'), err || err.toString());
            $state.go('tabs.home');
          } else {
            $scope.privateKey = privateKey;
            $scope.balanceSat = balance;
            if ($scope.balanceSat <= 0)
              popupService.showAlert(gettextCatalog.getString('Error'), gettextCatalog.getString('Not funds found'));
            var config = configService.getSync().wallet.settings;
            $scope.balance = txFormatService.formatAmount(balance) + ' ' + config.unitName;
          }
          $scope.$apply();
        });
      }, 100);
    };

    function _sweepWallet(cb) {
      walletService.getAddress($scope.wallet, true, function(err, destinationAddress) {
        if (err) return cb(err);

        $scope.wallet.buildTxFromPrivateKey($scope.privateKey, destinationAddress, null, function(err, testTx) {
          if (err) return cb(err);
          var rawTxLength = testTx.serialize().length;
          feeService.getCurrentFeeValue('livenet', function(err, feePerKB) {
            var opts = {};
            opts.fee = Math.round((feePerKB * rawTxLength) / 2000);
            $scope.wallet.buildTxFromPrivateKey($scope.privateKey, destinationAddress, opts, function(err, tx) {
              if (err) return cb(err);
              $scope.wallet.broadcastRawTx({
                rawTx: tx.serialize(),
                network: 'livenet'
              }, function(err, txid) {
                if (err) return cb(err);
                return cb(null, destinationAddress, txid);
              });
            });
          });
        });
      });
    };

    $scope.sweepWallet = function() {
      ongoingProcess.set('sweepingWallet', true);
      $scope.sending = true;

      $timeout(function() {
        _sweepWallet(function(err, destinationAddress, txid) {
          ongoingProcess.set('sweepingWallet', false);
          $scope.sending = false;
          if (err) {
            $log.error(err);
            popupService.showAlert(gettextCatalog.getString('Error sweeping wallet:'), err || err.toString());
          } else {
            $scope.sendStatus = 'success';
          }
          $scope.$apply();
        });
      }, 100);
    };

    $scope.onSuccessConfirm = function() {
      $state.go('tabs.home');
    };

    $scope.$on('Wallet/Changed', function(event, wallet) {
      if (!wallet) {
        $log.debug('No wallet provided');
        return;
      }
      if (wallet == $scope.wallet) {
        $log.debug('No change in wallet');
        return;
      }
      $scope.wallet = wallet;
      $log.debug('Wallet changed: ' + wallet.name);
      $timeout(function() {
        $scope.$apply();
      });
    });

    $scope.$on("$ionicView.beforeEnter", function(event, data) {
      $scope.scannedKey = (data.stateParams && data.stateParams.privateKey) ? data.stateParams.privateKey : null;
      $scope.isPkEncrypted = $scope.scannedKey ? ($scope.scannedKey.substring(0, 2) == '6P') : null;
      $scope.sendStatus = null;
      $scope.error = false;

      $scope.wallets = profileService.getWallets({
        onlyComplete: true,
        network: 'livenet',
      });

      if (!$scope.wallets || !$scope.wallets.length) {
        $scope.noMatchingWallet = true;
        return;
      }
    });

    $scope.$on("$ionicView.enter", function(event, data) {
      $scope.wallet = $scope.wallets[0];
      if (!$scope.wallet) return;
      if (!$scope.isPkEncrypted) $scope.scanFunds();
      else {
        var message = gettextCatalog.getString('Private key encrypted. Enter password');
        popupService.showPrompt(null, message, null, function(res) {
          $scope.passphrase = res;
          $scope.scanFunds();
        });
      }
    });

  });
<|endoftext|>