<commit_before>(function () {
    'use strict';
    angular
        .module('app.form')
        .controller('indFormController', indFormController);

    function indFormController() {
        var vm = this;
        vm.set1 = null;
        vm.set2 = null;
        vm.set3 = null;
        vm.set4a = null;
        vm.set4b = null;
        vm.set5a = null;
        vm.set5b = null;
        vm.set6 = null;
        vm.indivContrib = null;
        vm.coCare = null;
        vm.diff = null;
        vm.form = {
            premium: 0,
            deductible: 0,
            copay: 0,
            expenses: 0,
            w2: 0,
            otherIncome: null,
            filing: null,
            irsSum: 0,
            irs20b: 0,
            irsRetirement: 0,
            spouseA: {
                age: null,
                monthlySS: 0,
                ssShare: null,
                exemption: null
            },
            spouseB: {
                age: null,
                monthlySS: 0,
                ssShare: null,
                exemption: null
            }
        };

        vm.move = move;
        vm.startOver = startOver;

        activate();

        function activate() {
            vm.set1 = true;
            console.log('init indFormController vm.set1', vm.set1);
        }

        function move(set){
            switch(set){
                case 'set1':
                    vm.set1 = true;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set2':
                    vm.set1 = null;
                    vm.set2 = true;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set3':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = true;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set4a':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = true;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set4b':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = true;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set5a':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = true;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set5b':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = true;
                    vm.set6 = null;
                    break;
                case 'set6':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = true;
                    calc();
                    break;
            }
        }

        function startOver() {
            vm.form = {
                premium: 0,
                deductible: 0,
                copay: 0,
                expenses: 0,
                filing: null,
                irsSum: 0,
                irs20b: 0,
                irsRetirement: 0,
                spouseA: {
                    age: null,
                    monthlySS: 0,
                    ssShare: null,
                    exemption: null
                },
                spouseB: {
                    age: null,
                    monthlySS: 0,
                    ssShare: null,
                    exemption: null
                }
            };
            move('set1');
        }

        function ssRatioCalc(){
            vm.form.spouseA.ssShare = (vm.form.spouseA.monthlySS /
                (vm.form.spouseA.monthlySS + vm.form.spouseB.monthlySS)) * vm.form.irs20b;
            vm.form.spouseB.ssShare = (vm.form.spouseB.monthlySS /
                (vm.form.spouseA.monthlySS + vm.form.spouseB.monthlySS)) * vm.form.irs20b;
        }

        function jointCalc(){
            console.log('jointCalc vm.form', vm.form);
            var taxIncome = vm.form.irsSum - (vm.form.spouseA.exemption + vm.form.spouseB.exemption);
            vm.coCare = (taxIncome * 0.1) + (vm.form.w2 * 0.0333);
            vm.diff = vm.indivContrib - vm.coCare;
        }

        function calc() {
            vm.indivContrib = vm.form.premium * 12 + vm.form.deductible + vm.form.copay + vm.form.expenses;
            switch(vm.form.filing){
                case 'single':
                    switch(vm.form.spouseA.age){
                        case 'under':
                            vm.coCare = (0.1 * vm.form.irsSum) + (vm.form.w2 * 0.0333);
                            vm.diff = vm.indivContrib - vm.coCare;
                            break;
                        case 'between':
                            var sum = vm.form.irs20b + vm.form.irsRetirement;
                            if(sum > 20000){
                                vm.coCare = (0.1 * (vm.form.irsSum - 20000)) + (vm.form.w2 * 0.0333);
                            }
                            else {
                                vm.coCare = (0.1 * (vm.form.irsSum - sum)) + (vm.form.w2 * 0.0333);
                            }
                            vm.diff = vm.indivContrib - vm.coCare;
                            break;
                        case 'over':
                            var sum = vm.form.irs20b + vm.form.irsRetirement;
                            if(sum > 24000){
                                vm.coCare = (0.1 * (vm.form.irsSum - 24000)) + (vm.form.w2 * 0.0333);
                            }
                            else{
                                vm.coCare = (0.1 * (vm.form.irsSum - sum)) + (vm.form.w2 * 0.0333);
                            }
                            vm.diff = vm.indivContrib - vm.coCare;
                            break;
                    }
                    break;
                case 'joint':
                    ssRatioCalc();
                    switch(vm.form.spouseA.age){
                        case 'under':
                            vm.form.spouseA.exemption = 0;
                            break;
                        case 'between':
                            var sum = vm.form.irsRetirement + vm.form.spouseA.ssShare;
                            if(sum > 20000){
                                vm.form.spouseA.exemption = 20000;
                            }
                            else{
                                vm.form.spouseA.exemption = sum;
                            }
                            break;
                        case 'over':
                            var sum = vm.form.irsRetirement + vm.form.spouseA.ssShare;
                            if(sum > 24000){
                                vm.form.spouseA.exemption = 24000;
                            }
                            else{
                                vm.form.spouseA.exemption = sum;
                            }
                            break;
                    }
                    switch(vm.form.spouseB.age){
                        case 'under':
                            vm.form.spouseB.exemption = 0;
                            break;
                        case 'between':
                            var sum = vm.form.irsRetirement + vm.form.spouseB.ssShare;
                            if(sum > 20000){
                                vm.form.spouseB.exemption = 20000;
                            }
                            else{
                                vm.form.spouseB.exemption = sum;
                            }
                            break;
                        case 'over':
                            var sum = vm.form.irsRetirement + vm.form.spouseB.ssShare;
                            if(sum > 24000){
                                vm.form.spouseB.exemption = 24000;
                            }
                            else{
                                vm.form.spouseB.exemption = sum;
                            }
                            break;
                    }
                    jointCalc();
                    break;
                default:
                    vm.coCare = vm.form.w2 * 0.0333;
                    vm.diff = vm.indivContrib - vm.coCare;
            }
        }
    }
})();<commit_msg>fixed decimal places<commit_after>(function () {
    'use strict';
    angular
        .module('app.form')
        .controller('indFormController', indFormController);

    function indFormController() {
        var vm = this;
        vm.set1 = null;
        vm.set2 = null;
        vm.set3 = null;
        vm.set4a = null;
        vm.set4b = null;
        vm.set5a = null;
        vm.set5b = null;
        vm.set6 = null;
        vm.indivContrib = null;
        vm.coCare = null;
        vm.diff = null;
        vm.form = {
            premium: 0,
            deductible: 0,
            copay: 0,
            expenses: 0,
            w2: 0,
            otherIncome: null,
            filing: null,
            irsSum: 0,
            irs20b: 0,
            irsRetirement: 0,
            spouseA: {
                age: null,
                monthlySS: 0,
                ssShare: null,
                exemption: null
            },
            spouseB: {
                age: null,
                monthlySS: 0,
                ssShare: null,
                exemption: null
            }
        };

        vm.move = move;
        vm.startOver = startOver;

        activate();

        function activate() {
            vm.set1 = true;
            console.log('init indFormController vm.set1', vm.set1);
        }

        function move(set){
            switch(set){
                case 'set1':
                    vm.set1 = true;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set2':
                    vm.set1 = null;
                    vm.set2 = true;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set3':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = true;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set4a':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = true;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set4b':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = true;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set5a':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = true;
                    vm.set5b = null;
                    vm.set6 = null;
                    break;
                case 'set5b':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = true;
                    vm.set6 = null;
                    break;
                case 'set6':
                    vm.set1 = null;
                    vm.set2 = null;
                    vm.set3 = null;
                    vm.set4a = null;
                    vm.set4b = null;
                    vm.set5a = null;
                    vm.set5b = null;
                    vm.set6 = true;
                    calc();
                    break;
            }
        }

        function startOver() {
            vm.form = {
                premium: 0,
                deductible: 0,
                copay: 0,
                expenses: 0,
                filing: null,
                irsSum: 0,
                irs20b: 0,
                irsRetirement: 0,
                spouseA: {
                    age: null,
                    monthlySS: 0,
                    ssShare: null,
                    exemption: null
                },
                spouseB: {
                    age: null,
                    monthlySS: 0,
                    ssShare: null,
                    exemption: null
                }
            };
            move('set1');
        }

        function ssRatioCalc(){
            vm.form.spouseA.ssShare = (vm.form.spouseA.monthlySS /
                (vm.form.spouseA.monthlySS + vm.form.spouseB.monthlySS)) * vm.form.irs20b;
            vm.form.spouseB.ssShare = (vm.form.spouseB.monthlySS /
                (vm.form.spouseA.monthlySS + vm.form.spouseB.monthlySS)) * vm.form.irs20b;
        }

        function jointCalc(){
            console.log('jointCalc vm.form', vm.form);
            var taxIncome = vm.form.irsSum - (vm.form.spouseA.exemption + vm.form.spouseB.exemption);
            vm.coCare = Number((taxIncome * 0.1) + (vm.form.w2 * 0.0333)).toFixed(2);
            vm.diff = (vm.indivContrib - vm.coCare).toFixed(2);
        }

        function calc() {
            vm.indivContrib = vm.form.premium * 12 + vm.form.deductible + vm.form.copay + vm.form.expenses;
            switch(vm.form.filing){
                case 'single':
                    switch(vm.form.spouseA.age){
                        case 'under':
                            vm.coCare = (0.1 * vm.form.irsSum) + (vm.form.w2 * 0.0333);
                            vm.diff = vm.indivContrib - vm.coCare;
                            break;
                        case 'between':
                            var sum = vm.form.irs20b + vm.form.irsRetirement;
                            if(sum > 20000){
                                vm.coCare = Number((0.1 * (vm.form.irsSum - 20000)) + (vm.form.w2 * 0.0333)).toFixed(2);
                            }
                            else {
                                vm.coCare = Number((0.1 * (vm.form.irsSum - sum)) + (vm.form.w2 * 0.0333)).toFixed(2);
                            }
                            vm.diff = vm.indivContrib - vm.coCare;
                            break;
                        case 'over':
                            var sum = vm.form.irs20b + vm.form.irsRetirement;
                            if(sum > 24000){
                                vm.coCare = Number((0.1 * (vm.form.irsSum - 24000)) + (vm.form.w2 * 0.0333)).toFixed(2);
                            }
                            else{
                                vm.coCare = Number((0.1 * (vm.form.irsSum - sum)) + (vm.form.w2 * 0.0333)).toFixed(2);
                            }
                            vm.diff = vm.indivContrib - vm.coCare;
                            break;
                    }
                    break;
                case 'joint':
                    ssRatioCalc();
                    switch(vm.form.spouseA.age){
                        case 'under':
                            vm.form.spouseA.exemption = 0;
                            break;
                        case 'between':
                            var sum = vm.form.irsRetirement + vm.form.spouseA.ssShare;
                            if(sum > 20000){
                                vm.form.spouseA.exemption = 20000;
                            }
                            else{
                                vm.form.spouseA.exemption = sum;
                            }
                            break;
                        case 'over':
                            var sum = vm.form.irsRetirement + vm.form.spouseA.ssShare;
                            if(sum > 24000){
                                vm.form.spouseA.exemption = 24000;
                            }
                            else{
                                vm.form.spouseA.exemption = sum;
                            }
                            break;
                    }
                    switch(vm.form.spouseB.age){
                        case 'under':
                            vm.form.spouseB.exemption = 0;
                            break;
                        case 'between':
                            var sum = vm.form.irsRetirement + vm.form.spouseB.ssShare;
                            if(sum > 20000){
                                vm.form.spouseB.exemption = 20000;
                            }
                            else{
                                vm.form.spouseB.exemption = sum;
                            }
                            break;
                        case 'over':
                            var sum = vm.form.irsRetirement + vm.form.spouseB.ssShare;
                            if(sum > 24000){
                                vm.form.spouseB.exemption = 24000;
                            }
                            else{
                                vm.form.spouseB.exemption = sum;
                            }
                            break;
                    }
                    jointCalc();
                    break;
                default:
                    vm.coCare = Number(vm.form.w2 * 0.0333).toFixed(2);
                    vm.diff = (vm.indivContrib - vm.coCare).toFixed(2);
            }
        }
    }
})();<|endoftext|>


<commit_before>(function () {
    var tdv = function(data) {
        return {
        	// The div that will contain the visualization
        	_container: null,

        	// Camera settings
        	_fov: 75,
        	_near: 0.1,
        	_far: null,

        	// Camera position

        	_cameraX: 0,
        	_cameraY: 0,
        	_cameraZ: 0,

        	// THREE layout
        	_scene: null,
        	_camera: null,
        	_renderer: null,

        	// Lighting
        	_directionalLight: { // directional lighting
        		color: 0xffffff,
        		intensity: 1.0,
        		position: {
        			x: 80,
        			y: 300,
        			z: 590
        		}
        	},

        	//Skybox
        	_skyboxColor: 0xffffff,

        	createScene: function() {
        		var containerWidth = parseInt(this._container.style.width,10),
        			containerHeight = parseInt(this._container.style.height,10);

				this._scene = new THREE.Scene();

				this._renderer = new THREE.WebGLRenderer({ antialias: true });
				this._renderer.setSize(containerWidth, containerHeight);

				this._container.appendChild(this._renderer.domElement);

				var directionalLight = new THREE.DirectionalLight(this._directionalLight.color, this._directionalLight.intensity);
				directionalLight.position.set(this._directionalLight.position.x, this._directionalLight.position.y, this._directionalLight.position.z);

				this._scene.add(directionalLight);
        	},

        	addCamera: function() {
        		var containerWidth = parseInt(this._container.style.width,10),
        			containerHeight = parseInt(this._container.style.height,10);

				this._camera = new THREE.PerspectiveCamera(this._fov, this._aspectRatio, this._near, this._far);

				if (this._cameraX) this._camera.position.x = this._cameraX;
				if (this._cameraY) this._camera.position.y = this._cameraY;
				if (this._cameraZ) this._camera.position.z = this._cameraZ;
        	},

			startRenderScene: function() {
				var that = this;

				var render = function () {
					requestAnimationFrame( render );

					that._renderer.render(that._scene, that._camera);
				};

				render();
			},

        	createSkybox: function(skySize) {
				var skyMesh = new THREE.Mesh(new THREE.BoxGeometry(skySize, skySize, skySize), new THREE.MeshBasicMaterial({
					color: this._skyboxColor,
					side:THREE.DoubleSide
				}));

				this._scene.add(skyMesh);
        	},

        	createBase: function(baseWidth, baseLength, color) {
	    		// Create the base (a simple plane should do)
				var base = new THREE.Mesh(new THREE.PlaneGeometry(baseWidth, baseLength), new THREE.MeshBasicMaterial({
					color: color,
					side: THREE.DoubleSide
				}));

				// rotate it 90 degrees so it's flat
				base.rotation.x = (Math.PI/2);

				return base;
        	},

        	bar: function(container, data, options) {
				var self = this;

				// This is the maximum value allowed to be reached before it starts to factor
				var maxValueBeforeFactor = 150;

        		// Set up the basic configuration for the bar
        		var barWidth = 15,
        			barOpacity = 0.75,
        			columnSpace = 10,
        			rowSpace = 30,
        			baseColor = 0xaaaaaa,
        			baseEdge = 10,
        			baseWidth = 200,
        			baseLength = 200;

        		// Allow the override using the options if they exist
        		if (options) {
        			if (options.maxValueBeforeFactor) maxValueBeforeFactor = options.maxValueBeforeFactor;

        			if (options.barWidth) barWidth = options.barWidth;

        			if (options.barWidth) barWidth = options.barWidth;

        			if (options.barOpacity) barOpacity = options.barOpacity;

        			if (options.columnSpace) columnSpace = options.columnSpace;

        			if (options.rowSpace) rowSpace = options.rowSpace;

        			if (options.baseColor) baseColor = new THREE.Color(options.baseColor);

        			if (options.baseEdge) baseEdge = options.baseEdge;

        			if (options.baseWidth) baseWidth = options.baseWidth;

        			if (options.baseLength) baseLength = options.baseLength;

        			if (options.background) this._skyboxColor = new THREE.Color(options.background);

        			if (options.camera) {
        				if (options.camera.x) this._cameraX = 0;
        				if (options.camera.y) this._cameraY = 0;
        				if (options.camera.z) this._cameraZ = 0;
        			}
        		}

        		// The method to create the bar. Actually easier to plot the verticies than use available shapes
				var createBar = function(row, col, val, color) {
					// First, calculate the bar geometry

					var xPos = ((baseWidth/2)*-1), // this is our zero
						zPos = ((baseLength/2)*-1);

					xPos += ((col*columnSpace) + (col*barWidth)) + baseEdge + (barWidth/2);
					zPos += ((row*rowSpace) + (row*barWidth)) + baseEdge + (barWidth/2);

					var barGeometry = new THREE.Geometry();

					// Plot the verticies
					barGeometry.vertices.push(new THREE.Vector3(xPos-(barWidth/2), 0, zPos-(barWidth/2)));
					barGeometry.vertices.push(new THREE.Vector3(xPos-(barWidth/2), 0, zPos+(barWidth/2)));

					barGeometry.vertices.push(new THREE.Vector3(xPos+(barWidth/2), 0, zPos-(barWidth/2)));
					barGeometry.vertices.push(new THREE.Vector3(xPos+(barWidth/2), 0, zPos+(barWidth/2)));

					barGeometry.vertices.push(new THREE.Vector3(xPos-(barWidth/2), val, zPos-(barWidth/2)));
					barGeometry.vertices.push(new THREE.Vector3(xPos-(barWidth/2), val, zPos+(barWidth/2)));

					barGeometry.vertices.push(new THREE.Vector3(xPos+(barWidth/2), val, zPos-(barWidth/2)));
					barGeometry.vertices.push(new THREE.Vector3(xPos+(barWidth/2), val, zPos+(barWidth/2)));

					// Add the faces
					barGeometry.faces.push( new THREE.Face3( 0, 1, 4 ) );
					barGeometry.faces.push( new THREE.Face3( 4, 5, 1 ) );

					barGeometry.faces.push( new THREE.Face3( 3, 2, 7 ) );
					barGeometry.faces.push( new THREE.Face3( 7, 6, 2 ) );

					barGeometry.faces.push( new THREE.Face3( 1, 3, 5 ) );
					barGeometry.faces.push( new THREE.Face3( 5, 7, 3 ) );

					barGeometry.faces.push( new THREE.Face3( 0, 2, 4 ) );
					barGeometry.faces.push( new THREE.Face3( 4, 6, 2 ) );

					barGeometry.faces.push( new THREE.Face3( 4, 5, 7 ) );
					barGeometry.faces.push( new THREE.Face3( 6, 7, 4 ) );

					barGeometry.faces.push( new THREE.Face3( 0, 1, 3 ) );
					barGeometry.faces.push( new THREE.Face3( 0, 2, 3 ) );

					barGeometry.computeFaceNormals();

					var barMesh = new THREE.Mesh(barGeometry, new THREE.MeshLambertMaterial({
						color: color,
						side: THREE.DoubleSide,
						transparent: true,
						opacity: barOpacity
					}));

					return barMesh;
				}

				// This attempts to find a camera position based on data
				var calculateCamera = function(baseX, baseZ, maxBarHeight) {
        			self._cameraX = (baseX);
        			self._cameraY = (maxBarHeight+40);
        			self._cameraZ = (baseZ+100);

        			self._far = (Math.max(baseX, baseZ, maxBarHeight)+1000)*2;
	        	};

	        	var calculateLookAt = function(centerx, centerY, centerZ) {
	        		if (self._camera) self._camera.lookAt(new THREE.Vector3(centerx,centerY,centerZ));
	        	}

        		this._container = document.getElementById(container);

        		this.createScene();

        		// The actual graph object
        		var graphObject = new THREE.Object3D();

        		// Give it a name just for simplicity
        		if ((options) && (options.name)) graphObject.name = options.name;
        		else graphObject.name = "barGraph";

        		// Setting up the base plane for the bar chart (assuming that there is data)
    			if (data) {
    				// Get the length (the z axis)
    				baseLength = (barWidth*data.length) + (rowSpace*data.length) - rowSpace + (baseEdge*2);

    				// Figure out what the base length should be (the x axis)
    				var maxData = 0;

    				for (var i=0; i<data.length; i++) {
						if ((data[i].data) && (data[i].data.length > maxData)) maxData = data[i].data.length;
					}

    				if (maxData) baseWidth = (barWidth*maxData) + (columnSpace*maxData) - columnSpace + (baseEdge*2);
        		}

				// add it to the scene
				graphObject.add(this.createBase(baseWidth, baseLength, baseColor));

				var maxDataVal = 0,
					factor = 1;

				// check that we've have some data passed in
				if (data) {
					// First get the max value so we can factor values
    				for (var i=0; i<data.length; i++) {
    					for (var j=0; j<data[i].data.length; j++) {
							if (data[i].data[j] > maxDataVal) maxDataVal = data[i].data[j];
    					}
					}

					// Normalize the data so that the max value is at 100 units tall
					var originalMaxValue = maxDataVal;

					maxDataVal = maxValueBeforeFactor;

    				for (var i=0; i<data.length; i++) {
    					for (var j=0; j<data[i].data.length; j++) {
    						var percentageOfMax = data[i].data[j]/originalMaxValue;

							data[i].data[j] = maxDataVal*percentageOfMax;
    					}
					}

    				for (var i=0; i<data.length; i++) {
    					// Figure out the color for the bar. Pick a random one is one isn't defined
    					var barColor = null;

    					if (data[i].color) barColor = new THREE.Color(data[i].color);
    					else barColor = new THREE.Color("#"+Math.floor(Math.random()*16777215).toString(16));

    					for (var j=0; j<data[i].data.length; j++) {
							graphObject.add(createBar(i, j, (data[i].data[j]/factor), barColor));
    					}
					}
				}

				// Add the graph to the scene
				this._scene.add(graphObject)

        		// If we don't have camera options then we'll try and determine the camera position
    			if ((!options) || (!options.camera)) calculateCamera((baseWidth/2), (baseLength/2), maxValueBeforeFactor);

				this.addCamera();

				calculateLookAt(0, maxValueBeforeFactor/2, 0);

        		this.createSkybox(Math.max((baseWidth, baseLength, (maxDataVal/factor))+500)*2);

        		if (this._camera) this.startRenderScene();
        	}
        }
    };

    if(!window.tdv) window.tdv = tdv;
})();<commit_msg>adding outlines to bars and reworking code<commit_after>(function () {
    var tdv = function(data) {
        return {
        	// The div that will contain the visualization
        	_container: null,

        	// Camera settings
        	_fov: 75,
        	_near: 0.1,
        	_far: null,

        	// Camera position

        	_cameraX: 0,
        	_cameraY: 0,
        	_cameraZ: 0,

        	// THREE layout
        	_scene: null,
        	_camera: null,
        	_renderer: null,

        	// Lighting
        	_directionalLight: { // directional lighting
        		color: 0xffffff,
        		intensity: 1.0,
        		position: {
        			x: 80,
        			y: 300,
        			z: 590
        		}
        	},

        	//Skybox
        	_skyboxColor: 0xffffff,

        	createScene: function() {
        		var containerWidth = parseInt(this._container.style.width,10),
        			containerHeight = parseInt(this._container.style.height,10);

				this._scene = new THREE.Scene();

				this._renderer = new THREE.WebGLRenderer({ antialias: true });
				this._renderer.setSize(containerWidth, containerHeight);

				this._container.appendChild(this._renderer.domElement);

				var directionalLight = new THREE.DirectionalLight(this._directionalLight.color, this._directionalLight.intensity);
				directionalLight.position.set(this._directionalLight.position.x, this._directionalLight.position.y, this._directionalLight.position.z);

				this._scene.add(directionalLight);
        	},

        	addCamera: function() {
        		var containerWidth = parseInt(this._container.style.width,10),
        			containerHeight = parseInt(this._container.style.height,10);

				this._camera = new THREE.PerspectiveCamera(this._fov, this._aspectRatio, this._near, this._far);

				if (this._cameraX) this._camera.position.x = this._cameraX;
				if (this._cameraY) this._camera.position.y = this._cameraY;
				if (this._cameraZ) this._camera.position.z = this._cameraZ;
        	},

			startRenderScene: function() {
				var that = this;

				var render = function () {
					requestAnimationFrame( render );

					that._renderer.render(that._scene, that._camera);
				};

				render();
			},

        	createSkybox: function(skySize) {
				var skyMesh = new THREE.Mesh(new THREE.BoxGeometry(skySize, skySize, skySize), new THREE.MeshBasicMaterial({
					color: this._skyboxColor,
					side:THREE.DoubleSide
				}));

				this._scene.add(skyMesh);
        	},

        	createBase: function(baseWidth, baseLength, color) {
	    		// Create the base (a simple plane should do)
				var base = new THREE.Mesh(new THREE.PlaneGeometry(baseWidth, baseLength), new THREE.MeshBasicMaterial({
					color: color,
					side: THREE.DoubleSide
				}));

				// rotate it 90 degrees so it's flat
				base.rotation.x = (Math.PI/2);

				return base;
        	},

        	bar: function(container, data, options) {
				var self = this;

				// This is the maximum value allowed to be reached before it starts to factor
				var maxValueBeforeFactor = 150;

        		// Set up the basic configuration for the bar
        		var barWidth = 15,
        			barOpacity = 0.65,
        			columnSpace = 10,
        			rowSpace = 30,
        			baseColor = 0xaaaaaa,
        			baseEdge = 10,
        			baseWidth = 200,
        			baseLength = 200;

        		// Allow the override using the options if they exist
        		if (options) {
        			if (options.maxValueBeforeFactor) maxValueBeforeFactor = options.maxValueBeforeFactor;

        			if (options.barWidth) barWidth = options.barWidth;

        			if (options.barWidth) barWidth = options.barWidth;

        			if (options.barOpacity) barOpacity = options.barOpacity;

        			if (options.columnSpace) columnSpace = options.columnSpace;

        			if (options.rowSpace) rowSpace = options.rowSpace;

        			if (options.baseColor) baseColor = new THREE.Color(options.baseColor);

        			if (options.baseEdge) baseEdge = options.baseEdge;

        			if (options.baseWidth) baseWidth = options.baseWidth;

        			if (options.baseLength) baseLength = options.baseLength;

        			if (options.background) this._skyboxColor = new THREE.Color(options.background);

        			if (options.camera) {
        				if (options.camera.x) this._cameraX = 0;
        				if (options.camera.y) this._cameraY = 0;
        				if (options.camera.z) this._cameraZ = 0;
        			}
        		}

        		// The method to create the bar. Actually easier to plot the verticies than use available shapes
				var createBar = function(row, col, val, color) {
	        		var barObject = new THREE.Object3D();

					// First, calculate the bar geometry

					var xPos = ((baseWidth/2)*-1), // this is our zero
						zPos = ((baseLength/2)*-1);

					xPos += ((col*columnSpace) + (col*barWidth)) + baseEdge + (barWidth/2);
					zPos += ((row*rowSpace) + (row*barWidth)) + baseEdge + (barWidth/2);

					var barGeometry = new THREE.Geometry();

					// Plot the verticies
					barGeometry.vertices.push(new THREE.Vector3(xPos-(barWidth/2), 0, zPos-(barWidth/2)));
					barGeometry.vertices.push(new THREE.Vector3(xPos-(barWidth/2), 0, zPos+(barWidth/2)));

					barGeometry.vertices.push(new THREE.Vector3(xPos+(barWidth/2), 0, zPos-(barWidth/2)));
					barGeometry.vertices.push(new THREE.Vector3(xPos+(barWidth/2), 0, zPos+(barWidth/2)));

					barGeometry.vertices.push(new THREE.Vector3(xPos-(barWidth/2), val, zPos-(barWidth/2)));
					barGeometry.vertices.push(new THREE.Vector3(xPos-(barWidth/2), val, zPos+(barWidth/2)));

					barGeometry.vertices.push(new THREE.Vector3(xPos+(barWidth/2), val, zPos-(barWidth/2)));
					barGeometry.vertices.push(new THREE.Vector3(xPos+(barWidth/2), val, zPos+(barWidth/2)));

					// Add the faces
					barGeometry.faces.push( new THREE.Face3( 0, 1, 4 ) );
					barGeometry.faces.push( new THREE.Face3( 4, 5, 1 ) );

					barGeometry.faces.push( new THREE.Face3( 3, 2, 7 ) );
					barGeometry.faces.push( new THREE.Face3( 7, 6, 2 ) );

					barGeometry.faces.push( new THREE.Face3( 1, 3, 5 ) );
					barGeometry.faces.push( new THREE.Face3( 5, 7, 3 ) );

					barGeometry.faces.push( new THREE.Face3( 0, 2, 4 ) );
					barGeometry.faces.push( new THREE.Face3( 4, 6, 2 ) );

					barGeometry.faces.push( new THREE.Face3( 4, 5, 7 ) );
					barGeometry.faces.push( new THREE.Face3( 6, 7, 4 ) );

					barGeometry.faces.push( new THREE.Face3( 0, 1, 3 ) );
					barGeometry.faces.push( new THREE.Face3( 0, 2, 3 ) );

					barGeometry.computeFaceNormals();

					var barMesh = new THREE.Mesh(barGeometry, new THREE.MeshLambertMaterial({
						color: color,
						side: THREE.DoubleSide,
						transparent: true,
						opacity: barOpacity
					}));

					barObject.add(barMesh);

					// Generate the outlines
					var front = new THREE.Geometry();
					front.vertices.push(new THREE.Vector3(xPos-(barWidth/2), 0, zPos+(barWidth/2)));
					front.vertices.push(new THREE.Vector3(xPos-(barWidth/2), val, zPos+(barWidth/2)));
					front.vertices.push(new THREE.Vector3(xPos+(barWidth/2), val, zPos+(barWidth/2)));
					front.vertices.push(new THREE.Vector3(xPos+(barWidth/2), 0, zPos+(barWidth/2)));

					var frontLine = new THREE.Line(front, new THREE.LineBasicMaterial({
						color: color
					}));

					barObject.add(frontLine);

					var back = new THREE.Geometry();
					back.vertices.push(new THREE.Vector3(xPos-(barWidth/2), 0, zPos-(barWidth/2)));
					back.vertices.push(new THREE.Vector3(xPos-(barWidth/2), val, zPos-(barWidth/2)));
					back.vertices.push(new THREE.Vector3(xPos+(barWidth/2), val, zPos-(barWidth/2)));
					back.vertices.push(new THREE.Vector3(xPos+(barWidth/2), 0, zPos-(barWidth/2)));

					var backLine = new THREE.Line(back, new THREE.LineBasicMaterial({
						color: color
					}));

					barObject.add(backLine);

					var left = new THREE.Geometry();
					left.vertices.push(new THREE.Vector3(xPos+(barWidth/2), 0, zPos+(barWidth/2)));
					left.vertices.push(new THREE.Vector3(xPos+(barWidth/2), val, zPos+(barWidth/2)));
					left.vertices.push(new THREE.Vector3(xPos+(barWidth/2), val, zPos-(barWidth/2)));
					left.vertices.push(new THREE.Vector3(xPos+(barWidth/2), 0, zPos-(barWidth/2)));

					var leftLine = new THREE.Line(left, new THREE.LineBasicMaterial({
						color: color
					}));

					barObject.add(leftLine);

					var right = new THREE.Geometry();
					right.vertices.push(new THREE.Vector3(xPos-(barWidth/2), 0, zPos+(barWidth/2)));
					right.vertices.push(new THREE.Vector3(xPos-(barWidth/2), val, zPos+(barWidth/2)));
					right.vertices.push(new THREE.Vector3(xPos-(barWidth/2), val, zPos-(barWidth/2)));
					right.vertices.push(new THREE.Vector3(xPos-(barWidth/2), 0, zPos-(barWidth/2)));

					var rightLine = new THREE.Line(right, new THREE.LineBasicMaterial({
						color: color
					}));

					barObject.add(rightLine);

					return barObject;
				}

				// This attempts to find a camera position based on data
				var calculateCamera = function(baseX, baseZ, maxBarHeight) {
        			self._cameraX = (baseX);
        			self._cameraY = (maxBarHeight+40);
        			self._cameraZ = (baseZ+100);

        			self._far = (Math.max(baseX, baseZ, maxBarHeight)+1000)*2;
	        	};

	        	var calculateLookAt = function(centerx, centerY, centerZ) {
	        		if (self._camera) self._camera.lookAt(new THREE.Vector3(centerx,centerY,centerZ));
	        	}

        		this._container = document.getElementById(container);

        		this.createScene();

        		// The actual graph object
        		var graphObject = new THREE.Object3D();

        		// Give it a name just for simplicity
        		if ((options) && (options.name)) graphObject.name = options.name;
        		else graphObject.name = "barGraph";

        		// Setting up the base plane for the bar chart (assuming that there is data)
    			if (data) {
    				// Get the length (the z axis)
    				baseLength = (barWidth*data.length) + (rowSpace*data.length) - rowSpace + (baseEdge*2);

    				// Figure out what the base length should be (the x axis)
    				var maxData = 0;

    				for (var i=0; i<data.length; i++) {
						if ((data[i].data) && (data[i].data.length > maxData)) maxData = data[i].data.length;
					}

    				if (maxData) baseWidth = (barWidth*maxData) + (columnSpace*maxData) - columnSpace + (baseEdge*2);
        		}

				// add it to the scene
				graphObject.add(this.createBase(baseWidth, baseLength, baseColor));

				var maxDataVal = 0,
					factor = 1;

				// check that we've have some data passed in
				if (data) {
					// First get the max value so we can factor values
    				for (var i=0; i<data.length; i++) {
    					for (var j=0; j<data[i].data.length; j++) {
							if (data[i].data[j] > maxDataVal) maxDataVal = data[i].data[j];
    					}
					}

					// Normalize the data so that the max value is at 100 units tall
					var originalMaxValue = maxDataVal;

					maxDataVal = maxValueBeforeFactor;

    				for (var i=0; i<data.length; i++) {
    					for (var j=0; j<data[i].data.length; j++) {
    						var percentageOfMax = data[i].data[j]/originalMaxValue;

							data[i].data[j] = maxDataVal*percentageOfMax;
    					}
					}

    				for (var i=0; i<data.length; i++) {
    					// Figure out the color for the bar. Pick a random one is one isn't defined
    					var barColor = null;

    					if (data[i].color) barColor = new THREE.Color(data[i].color);
    					else barColor = new THREE.Color("#"+Math.floor(Math.random()*16777215).toString(16));

    					for (var j=0; j<data[i].data.length; j++) {
							graphObject.add(createBar(i, j, (data[i].data[j]/factor), barColor));
    					}
					}
				}

				// Add the graph to the scene
				this._scene.add(graphObject)

        		// If we don't have camera options then we'll try and determine the camera position
    			if ((!options) || (!options.camera)) calculateCamera((baseWidth/2), (baseLength/2), maxValueBeforeFactor);

				this.addCamera();

				calculateLookAt(0, maxValueBeforeFactor/2, 0);

        		this.createSkybox(Math.max((baseWidth, baseLength, (maxDataVal/factor))+500)*2);

        		if (this._camera) this.startRenderScene();
        	}
        }
    };

    if(!window.tdv) window.tdv = tdv;
})();<|endoftext|>


<commit_before>var game = new Game();
var player1 = new Paddle(game);
var player2 = new Paddle(game);
var ball = new Ball(game);

ball.position = { x: 21, y: (game.canvas.height / 2) - 5 };
player1.position = { x: 10, y: (game.canvas.height / 2) - 50 };
player2.position = { x: game.canvas.width - 20, y: (game.canvas.height / 2) - 50 };

$("#canvas").css({"background-color": "#000"});

game.drawBackground(function(paper) {
  paper.save();
  paper.globalAlpha = 0.5;
  paper.beginPath();
  paper.moveTo(game.canvas.width / 2, -1);
  paper.lineTo(game.canvas.width / 2, game.canvas.height);
  paper.closePath();
  paper.strokeStyle = "white";
  paper.stroke();
  paper.restore();
});

game.loop(function() {
  if (isKeyPressed('up')) {
    player2.moveUp();
  }

  if (isKeyPressed('down')) {
    player2.moveDown();
  }

  if (isKeyPressed('w')) {
    player1.moveUp();
  }

  if (isKeyPressed('s')) {
    player1.moveDown();
  }

  if (!ball.isFired() && isKeyPressed('space')) {
    ball.fire();
  }

  player1.draw();
  player2.draw();
  ball.draw();
});

game.start();
<commit_msg>move only if the ball is fired<commit_after>var game = new Game();
var player1 = new Paddle(game);
var player2 = new Paddle(game);
var ball = new Ball(game);

ball.position = { x: 21, y: (game.canvas.height / 2) - 5 };
player1.position = { x: 10, y: (game.canvas.height / 2) - 50 };
player2.position = { x: game.canvas.width - 20, y: (game.canvas.height / 2) - 50 };

$("#canvas").css({"background-color": "#000"});

game.drawBackground(function(paper) {
  paper.save();
  paper.globalAlpha = 0.5;
  paper.beginPath();
  paper.moveTo(game.canvas.width / 2, -1);
  paper.lineTo(game.canvas.width / 2, game.canvas.height);
  paper.closePath();
  paper.strokeStyle = "white";
  paper.stroke();
  paper.restore();
});

game.loop(function() {
  if (ball.isFired()) {
    if (isKeyPressed('up')) {
      player2.moveUp();
    }

    if (isKeyPressed('down')) {
      player2.moveDown();
    }

    if (isKeyPressed('w')) {
      player1.moveUp();
    }

    if (isKeyPressed('s')) {
      player1.moveDown();
    }
  }

  if (!ball.isFired() && isKeyPressed('space')) {
    ball.fire();
  }

  player1.draw();
  player2.draw();
  ball.draw();
});

game.start();
<|endoftext|>


<commit_before>define(
  [
    'dispatchers/AppDispatcher',
    'constants/InstanceConstants',
    'react',
    'globals',
    'context',
    'controllers/NotificationController',
    'components/modals/CancelConfirmModal.react',
    'components/modals/InstanceSuspendBody.react',
    'components/modals/InstanceResumeBody.react',
    'components/modals/InstanceStopBody.react',
    'components/modals/InstanceStartBody.react',
    'components/modals/InstanceTerminateBody.react',
    'components/modals/InstanceLaunchModal.react'
  ],
  function (AppDispatcher, InstanceConstants, React, globals, context, NotificationController, CancelConfirmModal, InstanceSuspendBody, InstanceResumeBody, InstanceStopBody, InstanceStartBody, InstanceTerminateBody, InstanceLaunchModal) {

    return {
      suspend: function (instance) {

        var onConfirm = function () {
          AppDispatcher.handleRouteAction({
            actionType: InstanceConstants.INSTANCE_SUSPEND,
            instance: instance
          });
        };

        var modal = CancelConfirmModal({
          header: "Suspend Instance",
          confirmButtonMessage: "Suspend Instance",
          onConfirm: onConfirm,
          body: InstanceSuspendBody.build()
        });

        React.renderComponent(modal, document.getElementById('modal'));
      },

      resume: function(instance){

        var onConfirm = function () {
          AppDispatcher.handleRouteAction({
            actionType: InstanceConstants.INSTANCE_RESUME,
            instance: instance
          });
        };

        var modal = CancelConfirmModal({
          header: "Resume Instance",
          confirmButtonMessage: "Resume Instance",
          onConfirm: onConfirm,
          body: InstanceResumeBody.build()
        });

        React.renderComponent(modal, document.getElementById('modal'));
      },

      stop: function(instance){

        var onConfirm = function () {
          AppDispatcher.handleRouteAction({
            actionType: InstanceConstants.INSTANCE_STOP,
            instance: instance
          });
        };

        var modal = CancelConfirmModal({
          header: "Stop Instance",
          confirmButtonMessage: "Stop Instance",
          onConfirm: onConfirm,
          body: InstanceStopBody.build()
        });

        React.renderComponent(modal, document.getElementById('modal'));
      },

      start: function(instance){

        var onConfirm = function () {
          AppDispatcher.handleRouteAction({
            actionType: InstanceConstants.INSTANCE_START,
            instance: instance
          });
        };

        var modal = CancelConfirmModal({
          header: "Start Instance",
          confirmButtonMessage: "Start Instance",
          onConfirm: onConfirm,
          body: InstanceStartBody.build()
        });

        React.renderComponent(modal, document.getElementById('modal'));
      },

      terminate: function(instance){

        var onConfirm = function () {
          AppDispatcher.handleRouteAction({
            actionType: InstanceConstants.INSTANCE_TERMINATE,
            instance: instance
          });
          // Since this is triggered from the instance details page, navigate off
          // that page and back to the instance list
          Backbone.history.navigate('instances', {trigger: true});
        };

        var modal = CancelConfirmModal({
          header: "Are you sure you want to terminate this instance?",
          confirmButtonMessage: "Yes, terminate this instance",
          onConfirm: onConfirm,
          body: InstanceTerminateBody.build(instance)
        });

        React.renderComponent(modal, document.getElementById('modal'));
      },

      launch: function(application){

        var onConfirm = function (identity, machineId, sizeId, instanceName, project) {
          AppDispatcher.handleRouteAction({
            actionType: InstanceConstants.INSTANCE_LAUNCH,
            identity: identity,
            machineId: machineId,
            sizeId: sizeId,
            instanceName: instanceName,
            project: project
          });
          // Since this is triggered from the images page, navigate off
          // that page and back to the instance list so the user can see
          // their instance being created
          Backbone.history.navigate('instances', {trigger: true});
        };

        var onCancel = function(){
          // Important! We need to un-mount the component so it un-registers from Stores and
          // also so that we can relaunch it again later.
          React.unmountComponentAtNode(document.getElementById('modal'));
        };

        var modal = InstanceLaunchModal({
          header: application.get('name'),
          application: application,
          confirmButtonMessage: "Launch instance",
          onConfirm: onConfirm,
          onCancel: onCancel,
          handleHidden: onCancel
        });

        React.renderComponent(modal, document.getElementById('modal'));
      },

      requestImage: function(instance, requestData){
        var providerId = instance.getCreds().provider_id;
        var identityId = instance.getCreds().identity_id;
        var requestUrl = globals.API_ROOT + "/provider/" + providerId + "/identity/" + identityId + "/request_image" + globals.slash();

        $.ajax({
          url: requestUrl,
          type: 'PUT',
          data: requestData,
          success: function (model) {
            NotificationController.info(null, "An image of your instance has been requested");
          },
          error: function (response, status, error) {
            NotificationController.error(null, response.responseText);
          }
        });
      },

      reportInstance: function(instance, reportInfo){
        var reportUrl = globals.API_ROOT + "/email/support" + globals.slash();

        var problemText = "";
        if(reportInfo.problems){
          _.each(reportInfo.problems, function(problem){
            problemText = problemText + "  -" + problem + "\n";
          })
        }

        var username = context.profile.get('username');

        var reportData = {
          username: username,
          message: "Instance IP: " + instance.get('ip_address') + "\n" +
                   "Instance ID: " + instance.id + "\n" +
                   "Provider ID: " + instance.get('identity').provider + "\n" +
                   "\n" +
                   "Problems" + "\n" +
                   problemText + "\n" +
                   "Message \n" +
                   reportInfo.message + "\n",
          subject: "Atmosphere Instance Report from " + username
        };

        $.ajax({
          url: reportUrl,
          type: 'POST',
          data: JSON.stringify(reportData),
          success: function (model) {
            NotificationController.info(null, "Your instance problems have been reported to support. You will be contacted within _TIMEFRAME_.");
          },
          error: function (response, status, error) {
            NotificationController.error(null, response.responseText);
          }
        });
      }

    };

  });
<commit_msg>Remove timeframe from report confirmation message.<commit_after>define(
  [
    'dispatchers/AppDispatcher',
    'constants/InstanceConstants',
    'react',
    'globals',
    'context',
    'controllers/NotificationController',
    'components/modals/CancelConfirmModal.react',
    'components/modals/InstanceSuspendBody.react',
    'components/modals/InstanceResumeBody.react',
    'components/modals/InstanceStopBody.react',
    'components/modals/InstanceStartBody.react',
    'components/modals/InstanceTerminateBody.react',
    'components/modals/InstanceLaunchModal.react'
  ],
  function (AppDispatcher, InstanceConstants, React, globals, context, NotificationController, CancelConfirmModal, InstanceSuspendBody, InstanceResumeBody, InstanceStopBody, InstanceStartBody, InstanceTerminateBody, InstanceLaunchModal) {

    return {
      suspend: function (instance) {

        var onConfirm = function () {
          AppDispatcher.handleRouteAction({
            actionType: InstanceConstants.INSTANCE_SUSPEND,
            instance: instance
          });
        };

        var modal = CancelConfirmModal({
          header: "Suspend Instance",
          confirmButtonMessage: "Suspend Instance",
          onConfirm: onConfirm,
          body: InstanceSuspendBody.build()
        });

        React.renderComponent(modal, document.getElementById('modal'));
      },

      resume: function(instance){

        var onConfirm = function () {
          AppDispatcher.handleRouteAction({
            actionType: InstanceConstants.INSTANCE_RESUME,
            instance: instance
          });
        };

        var modal = CancelConfirmModal({
          header: "Resume Instance",
          confirmButtonMessage: "Resume Instance",
          onConfirm: onConfirm,
          body: InstanceResumeBody.build()
        });

        React.renderComponent(modal, document.getElementById('modal'));
      },

      stop: function(instance){

        var onConfirm = function () {
          AppDispatcher.handleRouteAction({
            actionType: InstanceConstants.INSTANCE_STOP,
            instance: instance
          });
        };

        var modal = CancelConfirmModal({
          header: "Stop Instance",
          confirmButtonMessage: "Stop Instance",
          onConfirm: onConfirm,
          body: InstanceStopBody.build()
        });

        React.renderComponent(modal, document.getElementById('modal'));
      },

      start: function(instance){

        var onConfirm = function () {
          AppDispatcher.handleRouteAction({
            actionType: InstanceConstants.INSTANCE_START,
            instance: instance
          });
        };

        var modal = CancelConfirmModal({
          header: "Start Instance",
          confirmButtonMessage: "Start Instance",
          onConfirm: onConfirm,
          body: InstanceStartBody.build()
        });

        React.renderComponent(modal, document.getElementById('modal'));
      },

      terminate: function(instance){

        var onConfirm = function () {
          AppDispatcher.handleRouteAction({
            actionType: InstanceConstants.INSTANCE_TERMINATE,
            instance: instance
          });
          // Since this is triggered from the instance details page, navigate off
          // that page and back to the instance list
          Backbone.history.navigate('instances', {trigger: true});
        };

        var modal = CancelConfirmModal({
          header: "Are you sure you want to terminate this instance?",
          confirmButtonMessage: "Yes, terminate this instance",
          onConfirm: onConfirm,
          body: InstanceTerminateBody.build(instance)
        });

        React.renderComponent(modal, document.getElementById('modal'));
      },

      launch: function(application){

        var onConfirm = function (identity, machineId, sizeId, instanceName, project) {
          AppDispatcher.handleRouteAction({
            actionType: InstanceConstants.INSTANCE_LAUNCH,
            identity: identity,
            machineId: machineId,
            sizeId: sizeId,
            instanceName: instanceName,
            project: project
          });
          // Since this is triggered from the images page, navigate off
          // that page and back to the instance list so the user can see
          // their instance being created
          Backbone.history.navigate('instances', {trigger: true});
        };

        var onCancel = function(){
          // Important! We need to un-mount the component so it un-registers from Stores and
          // also so that we can relaunch it again later.
          React.unmountComponentAtNode(document.getElementById('modal'));
        };

        var modal = InstanceLaunchModal({
          header: application.get('name'),
          application: application,
          confirmButtonMessage: "Launch instance",
          onConfirm: onConfirm,
          onCancel: onCancel,
          handleHidden: onCancel
        });

        React.renderComponent(modal, document.getElementById('modal'));
      },

      requestImage: function(instance, requestData){
        var providerId = instance.getCreds().provider_id;
        var identityId = instance.getCreds().identity_id;
        var requestUrl = globals.API_ROOT + "/provider/" + providerId + "/identity/" + identityId + "/request_image" + globals.slash();

        $.ajax({
          url: requestUrl,
          type: 'PUT',
          data: requestData,
          success: function (model) {
            NotificationController.info(null, "An image of your instance has been requested");
          },
          error: function (response, status, error) {
            NotificationController.error(null, response.responseText);
          }
        });
      },

      reportInstance: function(instance, reportInfo){
        var reportUrl = globals.API_ROOT + "/email/support" + globals.slash();

        var problemText = "";
        if(reportInfo.problems){
          _.each(reportInfo.problems, function(problem){
            problemText = problemText + "  -" + problem + "\n";
          })
        }

        var username = context.profile.get('username');

        var reportData = {
          username: username,
          message: "Instance IP: " + instance.get('ip_address') + "\n" +
                   "Instance ID: " + instance.id + "\n" +
                   "Provider ID: " + instance.get('identity').provider + "\n" +
                   "\n" +
                   "Problems" + "\n" +
                   problemText + "\n" +
                   "Message \n" +
                   reportInfo.message + "\n",
          subject: "Atmosphere Instance Report from " + username
        };

        $.ajax({
          url: reportUrl,
          type: 'POST',
          data: JSON.stringify(reportData),
          success: function (model) {
            NotificationController.info(null, "Your instance problems have been reported to support.");
          },
          error: function (response, status, error) {
            NotificationController.error(null, response.responseText);
          }
        });
      }

    };

  });
<|endoftext|>


<commit_before>Appify(function (app) {
	var $div = Appify.templates.$div;
	var $a = Appify.templates.$a;

	app.route(function (next, details) {
		console.log('Middleware!');
		next(details);
	});

	app.route('index', function (render, details) {
		render('index', details);
	});

	app.route('other', function (render, details) {
		render('other', details);
	});

	app.renderer(function ($outlet, details) {
		$div(
			$outlet()
		).class('application');
	});

	app.renderer('index', function (details) {
		return $div(
			$div('Home Page'),
			$a('Go to Other Page').on('click', function () {
				app.transitionTo('other');
			})
		).class('home');
	});

	app.renderer('other', function (details) {
		return $div(
			$div('Other Page'),
			$a('Go to Home Page').on('click', function () {
				app.transitionTo('index');
			})
		).class('other');
	});
});<commit_msg>Tweaks to simple sample<commit_after>Appify(function (app) {
	var $div = Appify.templates.$div;
	var $a = Appify.templates.$a;

	app.route(function (next, details) {
		console.log('route middleware');

		next(details);
	});

	app.route('index', function (render, details) {
		console.log('route index');

		render('index', details);
	});

	app.route('other', function (render, details) {
		console.log('route other');

		render('other', details);
	});

	app.renderer(function ($outlet, details) {
		console.log('renderer middleware');

		return $div(
			$outlet(details)
		).class('application');
	});

	app.renderer('index', function (details) {
		console.log('renderer index');

		return $div(
			$div('Home Page'),
			$a('Go to Other Page').on('click', function () {
				app.transitionTo('other');
			})
		).class('home');
	});

	app.renderer('other', function (details) {
		console.log('renderer other');

		return $div(
			$div('Other Page'),
			$a('Go to Home Page').on('click', function () {
				app.transitionTo('index');
			})
		).class('other');
	});
});<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com
 * @author Jesús Leganés Combarro "Piranna" <piranna@gmail.com>
 */

function EventTarget()
{
  var listeners = {};

  this.addEventListener = function(type, listener)
  {
    if(!listener) return

    var listeners_type = listeners[type]
    if(listeners_type === undefined)
      listeners[type] = listeners_type = [];

    for(var i=0,l; l=listeners_type[i]; i++)
      if(l === listener) return;

    listeners_type.push(listener);
  };

  this.dispatchEvent = function(event)
  {
    var type = event.type
    var listenerArray = (listeners[type] || []);

    var dummyListener = this['on' + type];
    if(typeof dummyListener == 'function')
      listenerArray = listenerArray.concat(dummyListener);

    for(var i=0,listener; listener=listenerArray[i]; i++)
      listener.call(this, event);
  };

  this.removeEventListener = function(type, listener)
  {
    if(!listener) return

    var listeners_type = listeners[type]
    if(listeners_type === undefined) return

    for(var i=0,l; l=listeners_type[i]; i++)
      if(l === listener)
      {
        listeners_type.splice(i, 1);
        break;
      }

    if(!listeners_type.length)
      delete listeners[type]
  };
};

if(typeof module !== 'undefined' && module.exports)
  module.exports = EventTarget;
<commit_msg>Improved behaviour of dispatchEvent()<commit_after>/**
 * @author mrdoob / http://mrdoob.com
 * @author Jesús Leganés Combarro "Piranna" <piranna@gmail.com>
 */

function EventTarget()
{
  var listeners = {};

  this.addEventListener = function(type, listener)
  {
    if(!listener) return

    var listeners_type = listeners[type]
    if(listeners_type === undefined)
      listeners[type] = listeners_type = [];

    for(var i=0,l; l=listeners_type[i]; i++)
      if(l === listener) return;

    listeners_type.push(listener);
  };

  this.dispatchEvent = function(event)
  {
    if(event._dispatched) throw 'InvalidStateError'
    event._dispatched = true

    var type = event.type
    if(type == undefined || type == '') throw 'UNSPECIFIED_EVENT_TYPE_ERR'

    var listenerArray = (listeners[type] || []);

    var dummyListener = this['on' + type];
    if(typeof dummyListener == 'function')
      listenerArray = listenerArray.concat(dummyListener);

    var stopImmediatePropagation = false

    // [ToDo] Use read-only properties instead of attributes when availables
    event.cancelable = true
    event.defaultPrevented = false
    event.isTrusted = false
    event.preventDefault = function()
    {
      if(this.cancelable)
        this.defaultPrevented = true
    }
    event.stopImmediatePropagation = function()
    {
      stopImmediatePropagation = true
    }
    event.target = this
    event.timeStamp = new Date().getTime()

    for(var i=0,listener; listener=listenerArray[i]; i++)
    {
      if(stopImmediatePropagation) break

      listener.call(this, event);
    }

    return !event.defaultPrevented
  };

  this.removeEventListener = function(type, listener)
  {
    if(!listener) return

    var listeners_type = listeners[type]
    if(listeners_type === undefined) return

    for(var i=0,l; l=listeners_type[i]; i++)
      if(l === listener)
      {
        listeners_type.splice(i, 1);
        break;
      }

    if(!listeners_type.length)
      delete listeners[type]
  };
};

if(typeof module !== 'undefined' && module.exports)
  module.exports = EventTarget;
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------- \\
// File: InfoBubbleView.js                                                    \\
// Module: View                                                               \\
// Requires: Core, Foundation, DOM, View.js                                   \\
// Author: Neil Jenkins                                                       \\
// License: © 2010–2012 Opera Software ASA. All rights reserved.              \\
// -------------------------------------------------------------------------- \\

"use strict";

( function ( NS ) {

var InfoBubbleView = NS.Class({

    Extends: NS.View,

    init: function () {
        InfoBubbleView.parent.init.apply( this, arguments );
        this.get( 'rootView' ).insertView( this );
    },

    destroy: function () {
        this.get( 'rootView' ).removeView( this );
        InfoBubbleView.parent.destroy.call( this );
    },

    className: function () {
        return 'InfoBubbleView ' + this.get( 'alignToThe' ) +
            ( this.get( 'isHidden' ) || !this.get( 'alignWithView' ) ?
                ' hidden' : '' );
    }.property( 'alignWithView', 'alignToThe', 'isHidden' ),

    zIndex: 5000,

    isHidden: true,
    alignWithView: null,
    alignToThe: 'top',
    text: '',

    positioning: 'absolute',

    layout: function () {
        var view = this.get( 'alignWithView' );
        if ( !view ) { return {}; }

        var bounds = view.get( 'layer' ).getBoundingClientRect(),
            layout = {
                left: parseInt( bounds.left, 10 ),
                top: parseInt( bounds.top, 10 )
            },
            alignToThe = this.get( 'alignToThe' );

        if ( alignToThe === 'right' ) {
            // IE8 doesn't support bounds.width
            layout.left += parseInt( bounds.right - bounds.left, 10 );
        }
        else if ( alignToThe === 'bottom' ) {
            // IE8 doesn't support bounds.height
            layout.top += parseInt( bounds.bottom - bounds.top, 10 );
        }
        return layout;
    }.property( 'alignWithView', 'alignToThe' ),

    _render: function ( layer ) {
        var el = NS.Element.create;
        layer.appendChild( el( 'span', [
            el( 'span', {
                text: NS.bind( 'text', this )
            }),
            el( 'b' )
        ]) );
    }
});

NS.InfoBubbleView = InfoBubbleView;

}( this.O ) );
<commit_msg>Update InfoBubbleView layout when parent scrolls.<commit_after>// -------------------------------------------------------------------------- \\
// File: InfoBubbleView.js                                                    \\
// Module: View                                                               \\
// Requires: Core, Foundation, DOM, View.js                                   \\
// Author: Neil Jenkins                                                       \\
// License: © 2010–2012 Opera Software ASA. All rights reserved.              \\
// -------------------------------------------------------------------------- \\

"use strict";

( function ( NS ) {

var InfoBubbleView = NS.Class({

    Extends: NS.View,

    zIndex: 5000,

    isHidden: true,
    alignWithView: null,
    alignToThe: 'top',
    text: '',

    positioning: 'absolute',

    className: function () {
        return 'InfoBubbleView ' + this.get( 'alignToThe' );
    }.property( 'alignToThe' ),

    insertOrRemove: function () {
        var shouldBeInDoc = !this.get( 'isHidden' ) &&
                !!this.get( 'alignWithView' ),
            isInDocument = this.get( 'isInDocument' ),
            rootView = this.get( 'rootView' );
        if ( shouldBeInDoc && !isInDocument ) {
            rootView.insertView( this );
        }
        if ( !shouldBeInDoc && isInDocument ) {
            rootView.removeView( this );
        }
    }.observes( 'isHidden', 'alignWithView' ),

    monitorScrolls: function () {
        var alignWithView = this.get( 'alignWithView' ),
            scrollAncestors = this._scrollAncestors;
        if ( scrollAncestors ) {
            scrollAncestors.forEach( function ( view ) {
                view.detach( 'scroll', this, 'parentViewDidResize' );
            });
        }
        scrollAncestors = null;
        if ( alignWithView ) {
            scrollAncestors = [];
            while ( alignWithView = alignWithView.getParent( NS.ScrollView ) ) {
                alignWithView.on( 'scroll', this, 'parentViewDidResize' );
                scrollAncestors.push( alignWithView );
            }
        }
        this._scrollAncestors = scrollAncestors;
    }.observes( 'alignWithView' ),

    layout: function () {
        var alignWithView = this.get( 'alignWithView' );
        if ( !alignWithView ) { return {}; }

        var alignToThe = this.get( 'alignToThe' ),
            bounds = alignWithView.get( 'layer' ).getBoundingClientRect(),
            layout = {
                top: parseInt( bounds.top, 10 ),
                left: parseInt( bounds.left, 10 ),
            };

        if ( alignToThe === 'right' ) {
            // IE8 doesn't support bounds.width
            layout.left += parseInt( bounds.right - bounds.left, 10 );
        }
        else if ( alignToThe === 'bottom' ) {
            // IE8 doesn't support bounds.height
            layout.top += parseInt( bounds.bottom - bounds.top, 10 );
        }
        return layout;
    }.property( 'alignWithView', 'alignToThe' ),

    _render: function ( layer ) {
        var el = NS.Element.create;
        layer.appendChild( el( 'span', [
            el( 'span', {
                text: NS.bind( 'text', this )
            }),
            el( 'b' )
        ]) );
    },

    parentViewDidResize: function () {
        this.computedPropertyDidChange( 'layout' );
    }
});

NS.InfoBubbleView = InfoBubbleView;

}( this.O ) );
<|endoftext|>


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

    angular
        .module('app.tests')
        .controller('TestsCreateController', TestsCreateController);

    TestsCreateController.$inject = ['logger', 'TestsService'];
    /* @ngInject */
    function TestsCreateController(logger, TestsService) {
        var vm = this;

        activate();

        vm.addStep = addStep;
        vm.delStep = delStep;
        vm.stepsEmpty = stepsEmpty;
        vm.submitAddCase = submitAddCase;
        vm.currentSuite = TestsService.getCurrentSuite();
        vm.category = TestsService.getCategory();
        vm.priority = TestsService.getPriority();
        vm.sprint = TestsService.getSprint();
        vm.steps = [];
        addStep();

        // date
        var created = new Date();
        vm.created = created.getTime();
        // id
        var testsLen = vm.currentSuite.tests.length;
        var lastTest = vm.currentSuite.tests[testsLen - 1];
        vm._id = 1;
        if (testsLen > 0) vm._id = lastTest._id + 1;
        // other
        vm.casePriority = '2';
        vm.caseCategory = '10';
        vm.creator = 'John Doe';
        vm.caseSprint = vm.sprint[vm.sprint.length - 1].toString();
        vm.onCrtlEnterPress = onCrtlEnterPress;

        function activate() {
            logger.info('Activated New Case View');
        }

        function addStep() {
            var stepNumber = vm.steps.length + 1;
            var newStep = {
                stepNumber: stepNumber,
                stepDescription: '',
                expectedResult: ''
            };
            vm.steps.push(newStep);
        }

        function delStep($index) {
            vm.steps.splice($index,1);
        }

        function stepsEmpty() {
            var i;
            var stepsLen = vm.steps.length;
            var empty = false;
            for (i = 0; i < stepsLen; i++) {
                if (vm.steps[i].stepDescription === '' || vm.steps[i].expectedResult === '') {empty = true;}
            }
            return empty;
        }

        function submitAddCase() {
            var newCase = {};
            newCase.testName = vm.testName;
            newCase.casePriority = vm.casePriority;
            newCase.caseCategory = vm.caseCategory;
            newCase.created = vm.created;
            newCase.creator = vm.creator;
            newCase._id = vm._id;
            newCase.issues = 0;
            newCase.testDescription = vm.testDescription;
            newCase.caseSprint = vm.caseSprint;
            console.log(typeof(newCase.caseSprint));
            newCase.preConditions = vm.preConditions;
            newCase.steps = vm.steps;
            vm.currentSuite.tests.push(newCase);
            TestsService.setCurrentSuite(vm.currentSuite);
            logger.success('New Case created');

        }

        function onCrtlEnterPress(event) {
            if (event.charCode === 10) {
                addStep();
            }
        }
    }

})();
<commit_msg>works on firefox<commit_after>(function () {
    'use strict';

    angular
        .module('app.tests')
        .controller('TestsCreateController', TestsCreateController);

    TestsCreateController.$inject = ['logger', 'TestsService'];
    /* @ngInject */
    function TestsCreateController(logger, TestsService) {
        var vm = this;

        activate();

        vm.addStep = addStep;
        vm.delStep = delStep;
        vm.stepsEmpty = stepsEmpty;
        vm.submitAddCase = submitAddCase;
        vm.currentSuite = TestsService.getCurrentSuite();
        vm.category = TestsService.getCategory();
        vm.priority = TestsService.getPriority();
        vm.sprint = TestsService.getSprint();
        vm.steps = [];
        addStep();

        // date
        var created = new Date();
        vm.created = created.getTime();
        // id
        var testsLen = vm.currentSuite.tests.length;
        var lastTest = vm.currentSuite.tests[testsLen - 1];
        vm._id = 1;
        if (testsLen > 0) vm._id = lastTest._id + 1;
        // other
        vm.casePriority = '2';
        vm.caseCategory = '10';
        vm.creator = 'John Doe';
        vm.caseSprint = vm.sprint[vm.sprint.length - 1].toString();
        vm.onCrtlEnterPress = onCrtlEnterPress;

        function activate() {
            logger.info('Activated New Case View');
        }

        function addStep() {
            var stepNumber = vm.steps.length + 1;
            var newStep = {
                stepNumber: stepNumber,
                stepDescription: '',
                expectedResult: ''
            };
            vm.steps.push(newStep);
        }

        function delStep($index) {
            vm.steps.splice($index,1);
        }

        function stepsEmpty() {
            var i;
            var stepsLen = vm.steps.length;
            var empty = false;
            for (i = 0; i < stepsLen; i++) {
                if (vm.steps[i].stepDescription === '' || vm.steps[i].expectedResult === '') {empty = true;}
            }
            return empty;
        }

        function submitAddCase() {
            var newCase = {};
            newCase.testName = vm.testName;
            newCase.casePriority = vm.casePriority;
            newCase.caseCategory = vm.caseCategory;
            newCase.created = vm.created;
            newCase.creator = vm.creator;
            newCase._id = vm._id;
            newCase.issues = 0;
            newCase.testDescription = vm.testDescription;
            newCase.caseSprint = vm.caseSprint;
            console.log(typeof(newCase.caseSprint));
            newCase.preConditions = vm.preConditions;
            newCase.steps = vm.steps;
            vm.currentSuite.tests.push(newCase);
            TestsService.setCurrentSuite(vm.currentSuite);
            logger.success('New Case created');

        }

        function onCrtlEnterPress(event) {
            var charCode = (event.keyCode) ? event.keyCode : event.charCode;

            if ((event.ctrlKey && charCode === 13) || (event.ctrlKey && charCode === 10)) {
                addStep();
            }
        }

    }

})();
<|endoftext|>


<commit_before>/**
 * Created by daniel.irwin on 9/1/16.
 */

module.exports = (function(){

    var netscan = require('netscan')();

    function analyze(data){

        function keyValues(camera) {
            if (camera.uri.indexOf('get_status.cgi') > -1) {
                camera.type = 'FOSCAM';
                return camera.body.split('\n')
            }
            else if (camera.uri.indexOf('system.cgi') > -1) {
                camera.type = 'KEEBOX';
                return camera.body.split('\r\n');
            }
            return [];
        }

        function unstring(stringOfString){
            if(typeof stringOfString !== 'string'){
                return '';
            }
            return stringOfString.replace(/'|"/g,'').replace('var ', '').replace(';','');
        }

        data.forEach((camera) => {
            var newBody = {};
            keyValues(camera).forEach((keyValue) => {
                var kv = keyValue.split('=');
                var key = unstring(kv[0]);
                var value = unstring(kv[1]);
                if(key && value) {
                    newBody[key] = value;
                }
            });

            camera.alias = newBody.CameraName || newBody.alias;
            delete camera.body;

        });

        return data;
    }

    function ipscan(callback){
        netscan.scan({

            protocol : ['http'],

            octet0: [192],
            octet1: [168],
            octet2: [0],
            octet3: [{min: 100, max: 126}], //range of 7 to 10 inclusive

            ports: [80],

            codes: [200, 201, 202, 400, 401, 402, 403], //only count it if a 200 comes back,

            errors : [],

            paths: ['/system.cgi', '/get_status.cgi'], // optional to have it hit a specific endpoint

            headers: {
                Authorization:  'Basic ' + (new Buffer('admin' + ':' + 'admin', 'utf8')).toString('base64')
            }, // include the following headers in all request so you can do auth or something,

            timeout: 10000 //10 seconds timeout)

            //ignoreResponse : true
        }, function(results){

            callback(analyze(results));
        });
    }

    return {
        scan : ipscan
    }

})();<commit_msg>up the timeout<commit_after>/**
 * Created by daniel.irwin on 9/1/16.
 */

module.exports = (function(){

    var netscan = require('netscan')();

    function analyze(data){

        function keyValues(camera) {
            if (camera.uri.indexOf('get_status.cgi') > -1) {
                camera.type = 'FOSCAM';
                return camera.body.split('\n')
            }
            else if (camera.uri.indexOf('system.cgi') > -1) {
                camera.type = 'KEEBOX';
                return camera.body.split('\r\n');
            }
            return [];
        }

        function unstring(stringOfString){
            if(typeof stringOfString !== 'string'){
                return '';
            }
            return stringOfString.replace(/'|"/g,'').replace('var ', '').replace(';','');
        }

        data.forEach((camera) => {
            var newBody = {};
            keyValues(camera).forEach((keyValue) => {
                var kv = keyValue.split('=');
                var key = unstring(kv[0]);
                var value = unstring(kv[1]);
                if(key && value) {
                    newBody[key] = value;
                }
            });

            camera.alias = newBody.CameraName || newBody.alias;
            delete camera.body;

        });

        return data;
    }

    function ipscan(callback){
        netscan.scan({

            protocol : ['http'],

            octet0: [192],
            octet1: [168],
            octet2: [0],
            octet3: [{min: 100, max: 130}], //range of 7 to 10 inclusive

            ports: [80],

            codes: [200, 201, 202, 400, 401, 402, 403], //only count it if a 200 comes back,

            errors : [],

            paths: ['/system.cgi', '/get_status.cgi'], // optional to have it hit a specific endpoint

            headers: {
                Authorization:  'Basic ' + (new Buffer('admin' + ':' + 'admin', 'utf8')).toString('base64')
            }, // include the following headers in all request so you can do auth or something,

            timeout: 20000 //10 seconds timeout)

            //ignoreResponse : true
        }, function(results){

            callback(analyze(results));
        });
    }

    return {
        scan : ipscan
    }

})();<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView
} from 'react-native';
import { View as AnimatableView } from 'react-native-animatable';
import Component from './AbstractComponent';
import Button from './bootstrap/Button';
import Dialog from './Dialog';

const height = 50;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,.4)',
    justifyContent: 'flex-end'
  },
  contentContainer: {
    margin: 10
  },
  content: {
    backgroundColor: '#FFF',
    borderRadius: 10
  },
  title: {
    height,
    justifyContent: 'center'
  },
  titleText: {
    color: '#8F8F91',
    textAlign: 'center'
  },
  button: {
    borderRadius: 0,
    height,
    borderTopColor: '#DADADA',
    borderTopWidth: 1,
    backgroundColor: '#FFF'
  },
  cancel: {
    marginTop: 10,
    height,
    justifyContent: 'center'
  },
  cancelText: {
    fontWeight: '700',
    color: '#0977FF',
    fontSize: 18
  }
});

/**
 * @author 田尘殇Sean(sean.snow@live.com)
 * @date 16/6/12
 */
class ActionSheet extends Component {

  static propTypes = {
    open: PropTypes.bool,

    //（字符串数组） - 一组按钮的标题（必选）
    options: PropTypes.arrayOf(PropTypes.object).isRequired,

    // （字符串） - 弹出框顶部的标题
    title: PropTypes.string,

    cancel: PropTypes.string,
    cancelPress: PropTypes.func,

    // （字符串） - 弹出框顶部标题下方的信息
    message: PropTypes.string
  };

  static defaultProps = {
    open: false
  };

  constructor(props) {
    super(props);
    this.state = {
      open: props.open
    };
  }

  state = {};

  componentWillReceiveProps(nextProps) {
    if (nextProps.open && !this.state.open) {
      this.switchOpen();
    }
  }

  showAnimation = {
    animation: 'fadeIn',
    duration: 500
  };

  hideAnimation = {
    animation: 'fadeOut',
    duration: 500
  };

  contentShowAnimation = {
    animation: 'fadeInUpBig',
    duration: 500
  };
  contentHideAnimation = {
    animation: 'fadeOutDownBig',
    duration: 500
  };

  cancelPress() {
    this.switchOpen();
    const {cancelPress} = this.props;
    cancelPress && cancelPress();
  }

  switchOpen() {
    this.setState({open: !this.state.open});
  }

  render() {

    let props = this.state.open ? this.contentShowAnimation : this.contentHideAnimation;

    const {
      options,
      title,
      cancel
    } = this.props;

    return (
      <Dialog hideAnimation={this.hideAnimation}
              onPress={this.switchOpen}
              showAnimation={this.showAnimation}
              statusBarAutoHidden={false}
              style={styles.container}
              visible={this.state.open}
      >
        <AnimatableView {...props}
          style={styles.contentContainer}
        >
          <View style={[styles.content]}>
            <View style={styles.title}>
              <Text style={styles.titleText}>{title}</Text>
            </View>
            <ScrollView alwaysBounceVertical={false}>
              {
                options.map((option, index)=> {
                  let tmp = null;
                  if (options.length - 1 === index) {
                    tmp = {
                      borderBottomLeftRadius: 10,
                      borderBottomRightRadius: 10
                    };
                  }
                  return (
                    <Button color="#0977FF"
                            key={index}
                            onPress={option.onPress}
                            style={[styles.button, tmp]}
                    >
                      {option.label}
                    </Button>
                  );
                })
              }
            </ScrollView>
          </View>
          <Button onPress={this.cancelPress}
                  style={[styles.content, styles.cancel]}
          >
            <Text style={styles.cancelText}>
              {cancel}
            </Text>
          </Button>
        </AnimatableView>
      </Dialog>
    );
  }

}

export default ActionSheet;
<commit_msg>使用静态API 处理<commit_after>import React, { PropTypes } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView
} from 'react-native';
import { View as AnimatableView } from 'react-native-animatable';
import RootSiblings from 'react-native-root-siblings';
import Component from './AbstractComponent';
import Button from './bootstrap/Button';
import Dialog from './Dialog';

const height = 50;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,.4)',
    justifyContent: 'flex-end'
  },
  contentContainer: {
    margin: 10
  },
  content: {
    backgroundColor: '#FFF',
    borderRadius: 10
  },
  title: {
    height,
    justifyContent: 'center'
  },
  titleText: {
    color: '#8F8F91',
    textAlign: 'center'
  },
  button: {
    borderRadius: 0,
    height,
    borderTopColor: '#DADADA',
    borderTopWidth: 1,
    backgroundColor: '#FFF'
  },
  cancel: {
    marginTop: 10,
    height,
    justifyContent: 'center'
  },
  cancelText: {
    fontWeight: '700',
    color: '#0977FF',
    fontSize: 18
  }
});

/**
 * @author 田尘殇Sean(sean.snow@live.com)
 * @date 16/6/12
 */
class ActionSheetComponent extends Component {

  static propTypes = {
    /**
     * （字符串数组） - 一组按钮的标题（必选）
     */
    options: PropTypes.arrayOf(PropTypes.object).isRequired,

    cancel: PropTypes.string,
    cancelPress: PropTypes.func,

    manager: PropTypes.object,
    /**
     * （字符串） - 弹出框顶部标题下方的信息
     */
    message: PropTypes.string,

    // （字符串） - 弹出框顶部的标题
    title: PropTypes.string
  };

  state = {
    open: true
  };

  componentDidUpdate() {
    if (!this.state.open) {
      this.props.manager.destroy();
    }
  }

  showAnimation = {
    animation: 'fadeIn',
    duration: 500
  };

  hideAnimation = {
    animation: 'fadeOut',
    duration: 500
  };

  contentShowAnimation = {
    animation: 'fadeInUpBig',
    duration: 500
  };
  contentHideAnimation = {
    animation: 'fadeOutDownBig',
    duration: 500
  };

  cancelPress() {
    this.switchOpen();
    const {cancelPress} = this.props;
    cancelPress && cancelPress();
  }

  switchOpen() {
    this.setState({open: !this.state.open});
  }

  render() {

    let props = this.state.open ? this.contentShowAnimation : this.contentHideAnimation;

    const {
      options,
      title,
      cancel
    } = this.props;

    return (
      <Dialog hideAnimation={this.hideAnimation}
              onPress={this.switchOpen}
              showAnimation={this.showAnimation}
              statusBarAutoHidden={false}
              style={styles.container}
              visible={this.state.open}
      >
        <AnimatableView {...props}
          style={styles.contentContainer}
        >
          <View style={[styles.content]}>
            <View style={styles.title}>
              <Text style={styles.titleText}>{title || 'Action'}</Text>
            </View>
            <ScrollView alwaysBounceVertical={false}>
              {
                options.map((option, index)=> {
                  let tmp = null;
                  if (options.length - 1 === index) {
                    tmp = {
                      borderBottomLeftRadius: 10,
                      borderBottomRightRadius: 10
                    };
                  }
                  return (
                    <Button color="#0977FF"
                            key={index}
                            onPress={option.onPress}
                            style={[styles.button, tmp]}
                    >
                      {option.label}
                    </Button>
                  );
                })
              }
            </ScrollView>
          </View>
          <Button onPress={this.cancelPress}
                  style={[styles.content, styles.cancel]}
          >
            <Text style={styles.cancelText}>
              {cancel || 'Cancel'}
            </Text>
          </Button>
        </AnimatableView>
      </Dialog>
    );
  }

}

class ActionSheet {
  /**
   * @param options
   * options（字符串数组） - 一组按钮的标题（必选）
   * cancelButtonIndex（整型） - 选项中取消按钮所在的位置（索引）
   * destructiveButtonIndex（整型） - 选项中删除按钮所在的位置（索引）
   * title（字符串） - 弹出框顶部的标题
   * message（字符串） - 弹出框顶部标题下方的信息
   * @param callback
   */
  static showActionSheetWithOptions(options:Object, callback:Function) {
    let actionSheet = new RootSiblings(<View />);
    actionSheet.update(
      <ActionSheetComponent {...options}
        manager={actionSheet}
      />
    );

  }
}

export default ActionSheet;
<|endoftext|>


<commit_before>import PathDescriptorBase from './PathDescriptorBase';

import resource from '../../decorators/resource';

import HoleAction from '../../../Shapes/HoleAction';

import invariant from 'fbjs/lib/invariant';

import THREE from 'three';

class HoleDescriptor extends PathDescriptorBase {
  construct() {
    return new HoleAction();
  }

  performChildAction(threeObject, child) {
    debugger;
    child.performAction(threeObject.path);
  }

  setParent(threeObject, parentObject3D) {
    invariant(parentObject3D instanceof THREE.Shape, 'Holes can only be added to shapes.');

    return super.setParent(threeObject, parentObject3D);
  }
}

export default HoleDescriptor;
<commit_msg>Eslint<commit_after>import PathDescriptorBase from './PathDescriptorBase';

import HoleAction from '../../../Shapes/HoleAction';

import invariant from 'fbjs/lib/invariant';

import THREE from 'three';

class HoleDescriptor extends PathDescriptorBase {
  construct() {
    return new HoleAction();
  }

  performChildAction(threeObject, child) {
    child.performAction(threeObject.path);
  }

  setParent(threeObject, parentObject3D) {
    invariant(parentObject3D instanceof THREE.Shape, 'Holes can only be added to shapes.');

    return super.setParent(threeObject, parentObject3D);
  }
}

export default HoleDescriptor;
<|endoftext|>


<commit_before>import UICorePlugin from 'base/ui_core_plugin'

describe('UI Core Plugin', function() {
  class MyPlugin extends UICorePlugin {
    render() { }
  }
  it('constructs', () => {
    let callCount = 0
    class MyPlugin extends UICorePlugin {
      bindEvents() { callCount += 1 }
      render() { callCount += 1 }
    }
    const plugin = new MyPlugin(42)

    expect(plugin.core).to.be.equals(42)
    expect(plugin.enabled).to.be.true
    expect(callCount).to.be.equals(2)
  })

  it('enables', () => {
    const plugin = new MyPlugin({})
    const spy = sinon.spy(plugin, 'bindEvents')
    const show = sinon.spy()
    plugin.$el = { show: show }
    plugin.enabled = false

    plugin.enable()

    expect(spy).to.have.been.calledOnce
    expect(show).to.have.been.calledOnce
    expect(plugin.enabled).to.be.true
  })

  it('disables', () => {
    const plugin = new MyPlugin({})
    const spy = sinon.spy(plugin, 'stopListening')
    const hide = sinon.spy()
    plugin.$el = { hide: hide }

    plugin.disable()

    expect(spy).to.have.been.calledOnce
    expect(hide).to.have.been.calledOnce
    expect(plugin.enabled).to.be.false
  })

  it('destroys', () => {
    const plugin = new MyPlugin({})
    const spy = sinon.spy(plugin, 'remove')

    plugin.destroy()

    expect(spy).to.have.been.calledOnce
  })
})
<commit_msg>tests(ui_core_plugin): adapt to use the remove method<commit_after>import UICorePlugin from 'base/ui_core_plugin'

describe('UI Core Plugin', function() {
  class MyPlugin extends UICorePlugin {
    render() { }
  }
  it('constructs', () => {
    let callCount = 0
    class MyPlugin extends UICorePlugin {
      bindEvents() { callCount += 1 }
      render() { callCount += 1 }
    }
    const plugin = new MyPlugin(42)

    expect(plugin.core).to.be.equals(42)
    expect(plugin.enabled).to.be.true
    expect(callCount).to.be.equals(2)
  })

  it('enables', () => {
    const plugin = new MyPlugin({})
    const spy = sinon.spy(plugin, 'bindEvents')
    const show = sinon.spy()
    plugin.$el = { show: show }
    plugin.enabled = false

    plugin.enable()

    expect(spy).to.have.been.calledOnce
    expect(show).to.have.been.calledOnce
    expect(plugin.enabled).to.be.true
  })

  it('disables', () => {
    const plugin = new MyPlugin({})
    const spy = sinon.spy(plugin, 'stopListening')
    const hide = sinon.spy()
    plugin.$el = { hide: hide }

    plugin.disable()

    expect(spy).to.have.been.calledOnce
    expect(hide).to.have.been.calledOnce
    expect(plugin.enabled).to.be.false
  })

  it('destroys', () => {
    const plugin = new MyPlugin({})
    const spy = sinon.spy(plugin, 'remove')

    plugin.remove()

    expect(spy).to.have.been.calledOnce
  })
})
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_t<commit_msg>Reverting changes<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_ti<|endoftext|>