<commit_before>// Copyright (C) 2017 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
(function() {
  'use strict';

  // we need to be on codemirror 5.33.0+ to get the support for
  // text/x-php in CodeMirror.findModeByMIME
  const LANGUAGE_MAP = {
    'text/x-php': 'php',
  };

  Polymer({
    is: 'gr-editor',
    /**
     * Fired when the content of the editor changes.
     *
     * @event content-change
     */

    properties: {
      fileContent: String,
      fileType: String,
      mirror: Object,
      prefs: Object,
    },

    attached() {
      this.scopeSubtree(this.$.wrapper, true);
      const params =
          this.getCodeMirrorParams(this.fileType, this.fileContent, this.prefs);
      this.mirror = CodeMirror(this.$.wrapper, params);
      this.async(() => { this.mirror.refresh(); }, 1);
      this.addEventListeners();
    },

    addEventListeners() {
      this.mirror.on('change', e => {
        this.dispatchEvent(new CustomEvent('content-change',
            {detail: {value: e.getValue()}, bubbles: true}));
      });
    },

    getCodeMirrorParams(type, value, prefs) {
      const params = {value, viewportMargin: Infinity};

      if (prefs) {
        // TODO: Add gerrit's customizations from java codemirror to javascript
        // gerrit-gwtui/src/main/java/net/codemirror/lib/Extras.java
        params.autoCloseBrackets = prefs.auto_close_brackets;
        params.cursorBlinkRate = prefs.cursor_blink_rate;
        params.cursorHeight = 0.85;
        params.hideTopMenu = prefs.hide_top_menu;
        params.indentUnit = prefs.indent_unit;
        params.indentWithTabs = prefs.indent_with_tabs;
        // TODO(kaspern): Add support for keymaps.
        // params.keyMap = prefs.key_map_type.toLowerCase();
        params.lineLength = prefs.line_length;
        params.lineNumbers = prefs.hide_line_numbers;
        params.lineWrapping = prefs.line_wrapping;
        params.indentWithTabs = prefs.indent_with_tabs;
        params.matchBrackets = prefs.match_brackets;
        // TODO: Add support for a new commit msg MIME type
        // Support for this is somewhere in gerrit's codebase
        // needs backporting to javascript
        params.mode = prefs.syntax_highlighting ? this._mapFileType(type) : '';
        params.showTabs = prefs.show_tabs;
        params.showTrailingSpace = prefs.show_whitespace_errors;
        params.tabSize = prefs.tab_size;
        // TODO(kaspern): Add support for themes.
        // params.theme = prefs.theme.toLowerCase();

        if (value && value.includes('\r\n')) {
          params.lineSeparator = '\r\n';
        }
      }

      return params;
    },

    _mapFileType(type) {
      return LANGUAGE_MAP[type] || type || '';
    },
  });
})();
<commit_msg>Remove some deleted prefs values<commit_after>// Copyright (C) 2017 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
(function() {
  'use strict';

  // we need to be on codemirror 5.33.0+ to get the support for
  // text/x-php in CodeMirror.findModeByMIME
  const LANGUAGE_MAP = {
    'text/x-php': 'php',
  };

  Polymer({
    is: 'gr-editor',
    /**
     * Fired when the content of the editor changes.
     *
     * @event content-change
     */

    properties: {
      fileContent: String,
      fileType: String,
      mirror: Object,
      prefs: Object,
    },

    attached() {
      this.scopeSubtree(this.$.wrapper, true);
      const params =
          this.getCodeMirrorParams(this.fileType, this.fileContent, this.prefs);
      this.mirror = CodeMirror(this.$.wrapper, params);
      this.async(() => { this.mirror.refresh(); }, 1);
      this.addEventListeners();
    },

    addEventListeners() {
      this.mirror.on('change', e => {
        this.dispatchEvent(new CustomEvent('content-change',
            {detail: {value: e.getValue()}, bubbles: true}));
      });
    },

    getCodeMirrorParams(type, value, prefs) {
      const params = {value, viewportMargin: Infinity};

      if (prefs) {
        // TODO: Add gerrit's customizations from java codemirror to javascript
        // gerrit-gwtui/src/main/java/net/codemirror/lib/Extras.java
        params.autoCloseBrackets = prefs.auto_close_brackets;
        params.cursorHeight = 0.85;
        params.indentUnit = prefs.indent_unit;
        params.indentWithTabs = prefs.indent_with_tabs;
        // TODO(kaspern): Add support for keymaps.
        // params.keyMap = prefs.key_map_type.toLowerCase();
        params.lineLength = prefs.line_length;
        params.lineNumbers = !prefs.hide_line_numbers;
        params.lineWrapping = prefs.line_wrapping;
        params.indentWithTabs = prefs.indent_with_tabs;
        params.matchBrackets = prefs.match_brackets;
        // TODO: Add support for a new commit msg MIME type
        // Support for this is somewhere in gerrit's codebase
        // needs backporting to javascript
        params.mode = prefs.syntax_highlighting ? this._mapFileType(type) : '';
        params.showTabs = prefs.show_tabs;
        params.showTrailingSpace = prefs.show_whitespace_errors;
        params.tabSize = prefs.tab_size;
        // TODO(kaspern): Add support for themes.
        // params.theme = prefs.theme.toLowerCase();

        if (value && value.includes('\r\n')) {
          params.lineSeparator = '\r\n';
        }
      }

      return params;
    },

    _mapFileType(type) {
      return LANGUAGE_MAP[type] || type || '';
    },
  });
})();
<|endoftext|>


<commit_before>/**
 * @author yomboprime https://github.com/yomboprime
 *
 * GPUComputationRenderer, based on SimulationRenderer by zz85
 *
 * The GPUComputationRenderer uses the concept of variables. These variables are RGBA float textures that hold 4 floats
 * for each compute element (texel)
 *
 * Each variable has a fragment shader that defines the computation made to obtain the variable in question.
 * You can use as many variables you need, and make dependencies so you can use textures of other variables in the shader
 * (the sampler uniforms are added automatically) Most of the variables will need themselves as dependency.
 *
 * The renderer has actually two render targets per variable, to make ping-pong. Textures from the current frame are used
 * as inputs to render the textures of the next frame.
 *
 * The render targets of the variables can be used as input textures for your visualization shaders.
 *
 * Variable names should be valid identifiers and should not collide with THREE GLSL used identifiers.
 * a common approach could be to use 'texture' prefixing the variable name; i.e texturePosition, textureVelocity...
 *
 * The size of the computation (sizeX * sizeY) is defined as 'resolution' automatically in the shader. For example:
 * #DEFINE resolution vec2( 1024.0, 1024.0 )
 *
 * -------------
 *
 * Basic use:
 *
 * // Initialization...
 *
 * // Create computation renderer
 * var gpuCompute = new GPUComputationRenderer( 1024, 1024, renderer );
 *
 * // Create initial state float textures
 * var pos0 = gpuCompute.createTexture();
 * var vel0 = gpuCompute.createTexture();
 * // and fill in here the texture data...
 *
 * // Add texture variables
 * var velVar = gpuCompute.addVariable( "textureVelocity", fragmentShaderVel, pos0 );
 * var posVar = gpuCompute.addVariable( "texturePosition", fragmentShaderPos, vel0 );
 *
 * // Add variable dependencies
 * gpuCompute.setVariableDependencies( velVar, [ velVar, posVar ] );
 * gpuCompute.setVariableDependencies( posVar, [ velVar, posVar ] );
 *
 * // Add custom uniforms
 * velVar.material.uniforms.time = { value: 0.0 };
 *
 * // Check for completeness
 * var error = gpuCompute.init();
 * if ( error !== null ) {
 *		console.error( error );
  * }
 *
 *
 * // In each frame...
 *
 * // Compute!
 * gpuCompute.compute();
 *
 * // Update texture uniforms in your visualization materials with the gpu renderer output
 * myMaterial.uniforms.myTexture.value = gpuCompute.getCurrentRenderTarget( posVar ).texture;
 *
 * // Do your rendering
 * renderer.render( myScene, myCamera );
 *
 * -------------
 *
 * Also, you can use utility functions to create ShaderMaterial and perform computations (rendering between textures)
 * Note that the shaders can have multiple input textures.
 *
 * var myFilter1 = gpuCompute.createShaderMaterial( myFilterFragmentShader1, { theTexture: { value: null } } );
 * var myFilter2 = gpuCompute.createShaderMaterial( myFilterFragmentShader2, { theTexture: { value: null } } );
 *
 * var inputTexture = gpuCompute.createTexture();
 *
 * // Fill in here inputTexture...
 *
 * myFilter1.uniforms.theTexture.value = inputTexture;
 *
 * var myRenderTarget = gpuCompute.createRenderTarget();
 * myFilter2.uniforms.theTexture.value = myRenderTarget.texture;
 *
 * var outputRenderTarget = gpuCompute.createRenderTarget();
 *
 * // Now use the output texture where you want:
 * myMaterial.uniforms.map.value = outputRenderTarget.texture;
 *
 * // And compute each frame, before rendering to screen:
 * gpuCompute.doRenderTarget( myFilter1, myRenderTarget );
 * gpuCompute.doRenderTarget( myFilter2, outputRenderTarget );
 *
 *
 *
 * @param {int} sizeX Computation problem size is always 2d: sizeX * sizeY elements.
 * @param {int} sizeY Computation problem size is always 2d: sizeX * sizeY elements.
 * @param {WebGLRenderer} renderer The renderer
  */

function GPUComputationRenderer( sizeX, sizeY, renderer ) {

	this.variables = [];

	this.currentTextureIndex = 0;

	var scene = new THREE.Scene();

	var camera = new THREE.Camera();
	camera.position.z = 1;

	var passThruUniforms = {
		texture: { value: null }
	};

	var passThruShader = createShaderMaterial( getPassThroughFragmentShader(), passThruUniforms );

	var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ), passThruShader );
	scene.add( mesh );

	this.addVariable = function( variableName, computeFragmentShader, initialValueTexture ) {

		var material = this.createShaderMaterial( computeFragmentShader );

		var variable = {
			name: variableName,
			initialValueTexture: initialValueTexture,
			material: material,
			dependencies: null,
			renderTargets: [],
			wrapS: null,
			wrapT: null,
			minFilter: THREE.NearestFilter,
			magFilter: THREE.NearestFilter
		};

		this.variables.push( variable );

		return variable;

	};

	this.setVariableDependencies = function( variable, dependencies ) {

		variable.dependencies = dependencies;

	};

	this.init = function() {

		if ( ! renderer.extensions.get( "OES_texture_float" ) ) {

			return "No OES_texture_float support for float textures.";

		}

		if ( renderer.capabilities.maxVertexTextures === 0 ) {

			return "No support for vertex shader textures.";

		}

		for ( var i = 0; i < this.variables.length; i++ ) {

			var variable = this.variables[ i ];

			// Creates rendertargets and initialize them with input texture
			variable.renderTargets[ 0 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
			variable.renderTargets[ 1 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
			this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 0 ] );
			this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 1 ] );

			// Adds dependencies uniforms to the ShaderMaterial
			var material = variable.material;
			var uniforms = material.uniforms;
			if ( variable.dependencies !== null ) {

				for ( var d = 0; d < variable.dependencies.length; d++ ) {

					var depVar = variable.dependencies[ d ];

					if ( depVar.name !== variable.name ) {

						// Checks if variable exists
						var found = false;
						for ( var j = 0; j < this.variables.length; j++ ) {

							if ( depVar.name === this.variables[ j ].name ) {
								found = true;
								break;
							}

						}
						if ( ! found ) {
							return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name;
						}

					}

					uniforms[ depVar.name ] = { value: null };

					material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader;

				}
			}
		}

		this.currentTextureIndex = 0;

		return null;

	};

	this.compute = function() {

		var currentTextureIndex = this.currentTextureIndex;
		var nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0;

		for ( var i = 0, il = this.variables.length; i < il; i++ ) {

			var variable = this.variables[ i ];

			// Sets texture dependencies uniforms
			if ( variable.dependencies !== null ) {

				var uniforms = variable.material.uniforms;
				for ( var d = 0, dl = variable.dependencies.length; d < dl; d++ ) {

					var depVar = variable.dependencies[ d ];

					uniforms[ depVar.name ].value = depVar.renderTargets[ currentTextureIndex ].texture;

				}

			}

			// Performs the computation for this variable
			this.doRenderTarget( variable.material, variable.renderTargets[ nextTextureIndex ] );

		}

		this.currentTextureIndex = nextTextureIndex;
	};

	this.getCurrentRenderTarget = function( variable ) {

		return variable.renderTargets[ this.currentTextureIndex ];

	};

	this.getAlternateRenderTarget = function( variable ) {

		return variable.renderTargets[ this.currentTextureIndex === 0 ? 1 : 0 ];

	};

	function addResolutionDefine( materialShader ) {

		materialShader.defines.resolution = 'vec2( ' + sizeX.toFixed( 1 ) + ', ' + sizeY.toFixed( 1 ) + " )";

	};
	this.addResolutionDefine = addResolutionDefine;

	// The following functions can be used to compute things manually

	function createShaderMaterial( computeFragmentShader, uniforms ) {

		uniforms = uniforms || {};

		var material = new THREE.ShaderMaterial( {
			uniforms: uniforms,
			vertexShader: getPassThroughVertexShader(),
			fragmentShader: computeFragmentShader
		} );

		addResolutionDefine( material );

		return material;
	};
	this.createShaderMaterial = createShaderMaterial;

	this.createRenderTarget = function( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) {

		sizeXTexture = sizeXTexture || sizeX;
		sizeYTexture = sizeYTexture || sizeY;

		wrapS = wrapS || THREE.ClampToEdgeWrapping;
		wrapT = wrapT || THREE.ClampToEdgeWrapping;

		minFilter = minFilter || THREE.NearestFilter;
		magFilter = magFilter || THREE.NearestFilter;

		var renderTarget = new THREE.WebGLRenderTarget( sizeXTexture, sizeYTexture, {
			wrapS: wrapS,
			wrapT: wrapT,
			minFilter: minFilter,
			magFilter: magFilter,
			format: THREE.RGBAFormat,
			type: THREE.FloatType,
			stencilBuffer: false
		} );

		return renderTarget;

	};

    this.createTexture = function( sizeXTexture, sizeYTexture ) {

		sizeXTexture = sizeXTexture || sizeX;
		sizeYTexture = sizeYTexture || sizeY;

		var a = new Float32Array( sizeXTexture * sizeYTexture * 4 );
		var texture = new THREE.DataTexture( a, sizeX, sizeY, THREE.RGBAFormat, THREE.FloatType );
		texture.needsUpdate = true;

		return texture;

	};

	this.renderTexture = function( input, output ) {

		// Takes a texture, and render out in rendertarget
		// input = Texture
		// output = RenderTarget

		passThruUniforms.texture.value = input;

		this.doRenderTarget( passThruShader, output);

		passThruUniforms.texture.value = null;

	};

	this.doRenderTarget = function( material, output ) {

		mesh.material = material;
		renderer.render( scene, camera, output );
		mesh.material = passThruShader;

	};

	// Shaders

	function getPassThroughVertexShader() {

		return	"void main()	{\n" +
				"\n" +
				"	gl_Position = vec4( position, 1.0 );\n" +
				"\n" +
				"}\n";

	}

	function getPassThroughFragmentShader() {

		return	"uniform sampler2D texture;\n" +
				"\n" +
				"void main() {\n" +
				"\n" +
				"	vec2 uv = gl_FragCoord.xy / resolution.xy;\n" +
				"\n" +
				"	gl_FragColor = texture2D( texture, uv );\n" +
				"\n" +
				"}\n";

	}

}<commit_msg>GPUComputationRenderer: Added check to make it work on iOS. (#9644)<commit_after>/**
 * @author yomboprime https://github.com/yomboprime
 *
 * GPUComputationRenderer, based on SimulationRenderer by zz85
 *
 * The GPUComputationRenderer uses the concept of variables. These variables are RGBA float textures that hold 4 floats
 * for each compute element (texel)
 *
 * Each variable has a fragment shader that defines the computation made to obtain the variable in question.
 * You can use as many variables you need, and make dependencies so you can use textures of other variables in the shader
 * (the sampler uniforms are added automatically) Most of the variables will need themselves as dependency.
 *
 * The renderer has actually two render targets per variable, to make ping-pong. Textures from the current frame are used
 * as inputs to render the textures of the next frame.
 *
 * The render targets of the variables can be used as input textures for your visualization shaders.
 *
 * Variable names should be valid identifiers and should not collide with THREE GLSL used identifiers.
 * a common approach could be to use 'texture' prefixing the variable name; i.e texturePosition, textureVelocity...
 *
 * The size of the computation (sizeX * sizeY) is defined as 'resolution' automatically in the shader. For example:
 * #DEFINE resolution vec2( 1024.0, 1024.0 )
 *
 * -------------
 *
 * Basic use:
 *
 * // Initialization...
 *
 * // Create computation renderer
 * var gpuCompute = new GPUComputationRenderer( 1024, 1024, renderer );
 *
 * // Create initial state float textures
 * var pos0 = gpuCompute.createTexture();
 * var vel0 = gpuCompute.createTexture();
 * // and fill in here the texture data...
 *
 * // Add texture variables
 * var velVar = gpuCompute.addVariable( "textureVelocity", fragmentShaderVel, pos0 );
 * var posVar = gpuCompute.addVariable( "texturePosition", fragmentShaderPos, vel0 );
 *
 * // Add variable dependencies
 * gpuCompute.setVariableDependencies( velVar, [ velVar, posVar ] );
 * gpuCompute.setVariableDependencies( posVar, [ velVar, posVar ] );
 *
 * // Add custom uniforms
 * velVar.material.uniforms.time = { value: 0.0 };
 *
 * // Check for completeness
 * var error = gpuCompute.init();
 * if ( error !== null ) {
 *		console.error( error );
  * }
 *
 *
 * // In each frame...
 *
 * // Compute!
 * gpuCompute.compute();
 *
 * // Update texture uniforms in your visualization materials with the gpu renderer output
 * myMaterial.uniforms.myTexture.value = gpuCompute.getCurrentRenderTarget( posVar ).texture;
 *
 * // Do your rendering
 * renderer.render( myScene, myCamera );
 *
 * -------------
 *
 * Also, you can use utility functions to create ShaderMaterial and perform computations (rendering between textures)
 * Note that the shaders can have multiple input textures.
 *
 * var myFilter1 = gpuCompute.createShaderMaterial( myFilterFragmentShader1, { theTexture: { value: null } } );
 * var myFilter2 = gpuCompute.createShaderMaterial( myFilterFragmentShader2, { theTexture: { value: null } } );
 *
 * var inputTexture = gpuCompute.createTexture();
 *
 * // Fill in here inputTexture...
 *
 * myFilter1.uniforms.theTexture.value = inputTexture;
 *
 * var myRenderTarget = gpuCompute.createRenderTarget();
 * myFilter2.uniforms.theTexture.value = myRenderTarget.texture;
 *
 * var outputRenderTarget = gpuCompute.createRenderTarget();
 *
 * // Now use the output texture where you want:
 * myMaterial.uniforms.map.value = outputRenderTarget.texture;
 *
 * // And compute each frame, before rendering to screen:
 * gpuCompute.doRenderTarget( myFilter1, myRenderTarget );
 * gpuCompute.doRenderTarget( myFilter2, outputRenderTarget );
 *
 *
 *
 * @param {int} sizeX Computation problem size is always 2d: sizeX * sizeY elements.
 * @param {int} sizeY Computation problem size is always 2d: sizeX * sizeY elements.
 * @param {WebGLRenderer} renderer The renderer
  */

function GPUComputationRenderer( sizeX, sizeY, renderer ) {

	this.variables = [];

	this.currentTextureIndex = 0;

	var scene = new THREE.Scene();

	var camera = new THREE.Camera();
	camera.position.z = 1;

	var passThruUniforms = {
		texture: { value: null }
	};

	var passThruShader = createShaderMaterial( getPassThroughFragmentShader(), passThruUniforms );

	var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ), passThruShader );
	scene.add( mesh );

	this.addVariable = function( variableName, computeFragmentShader, initialValueTexture ) {

		var material = this.createShaderMaterial( computeFragmentShader );

		var variable = {
			name: variableName,
			initialValueTexture: initialValueTexture,
			material: material,
			dependencies: null,
			renderTargets: [],
			wrapS: null,
			wrapT: null,
			minFilter: THREE.NearestFilter,
			magFilter: THREE.NearestFilter
		};

		this.variables.push( variable );

		return variable;

	};

	this.setVariableDependencies = function( variable, dependencies ) {

		variable.dependencies = dependencies;

	};

	this.init = function() {

		if ( ! renderer.extensions.get( "OES_texture_float" ) ) {

			return "No OES_texture_float support for float textures.";

		}

		if ( renderer.capabilities.maxVertexTextures === 0 ) {

			return "No support for vertex shader textures.";

		}

		for ( var i = 0; i < this.variables.length; i++ ) {

			var variable = this.variables[ i ];

			// Creates rendertargets and initialize them with input texture
			variable.renderTargets[ 0 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
			variable.renderTargets[ 1 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
			this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 0 ] );
			this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 1 ] );

			// Adds dependencies uniforms to the ShaderMaterial
			var material = variable.material;
			var uniforms = material.uniforms;
			if ( variable.dependencies !== null ) {

				for ( var d = 0; d < variable.dependencies.length; d++ ) {

					var depVar = variable.dependencies[ d ];

					if ( depVar.name !== variable.name ) {

						// Checks if variable exists
						var found = false;
						for ( var j = 0; j < this.variables.length; j++ ) {

							if ( depVar.name === this.variables[ j ].name ) {
								found = true;
								break;
							}

						}
						if ( ! found ) {
							return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name;
						}

					}

					uniforms[ depVar.name ] = { value: null };

					material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader;

				}
			}
		}

		this.currentTextureIndex = 0;

		return null;

	};

	this.compute = function() {

		var currentTextureIndex = this.currentTextureIndex;
		var nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0;

		for ( var i = 0, il = this.variables.length; i < il; i++ ) {

			var variable = this.variables[ i ];

			// Sets texture dependencies uniforms
			if ( variable.dependencies !== null ) {

				var uniforms = variable.material.uniforms;
				for ( var d = 0, dl = variable.dependencies.length; d < dl; d++ ) {

					var depVar = variable.dependencies[ d ];

					uniforms[ depVar.name ].value = depVar.renderTargets[ currentTextureIndex ].texture;

				}

			}

			// Performs the computation for this variable
			this.doRenderTarget( variable.material, variable.renderTargets[ nextTextureIndex ] );

		}

		this.currentTextureIndex = nextTextureIndex;
	};

	this.getCurrentRenderTarget = function( variable ) {

		return variable.renderTargets[ this.currentTextureIndex ];

	};

	this.getAlternateRenderTarget = function( variable ) {

		return variable.renderTargets[ this.currentTextureIndex === 0 ? 1 : 0 ];

	};

	function addResolutionDefine( materialShader ) {

		materialShader.defines.resolution = 'vec2( ' + sizeX.toFixed( 1 ) + ', ' + sizeY.toFixed( 1 ) + " )";

	};
	this.addResolutionDefine = addResolutionDefine;

	// The following functions can be used to compute things manually

	function createShaderMaterial( computeFragmentShader, uniforms ) {

		uniforms = uniforms || {};

		var material = new THREE.ShaderMaterial( {
			uniforms: uniforms,
			vertexShader: getPassThroughVertexShader(),
			fragmentShader: computeFragmentShader
		} );

		addResolutionDefine( material );

		return material;
	};
	this.createShaderMaterial = createShaderMaterial;

	this.createRenderTarget = function( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) {

		sizeXTexture = sizeXTexture || sizeX;
		sizeYTexture = sizeYTexture || sizeY;

		wrapS = wrapS || THREE.ClampToEdgeWrapping;
		wrapT = wrapT || THREE.ClampToEdgeWrapping;

		minFilter = minFilter || THREE.NearestFilter;
		magFilter = magFilter || THREE.NearestFilter;

		var renderTarget = new THREE.WebGLRenderTarget( sizeXTexture, sizeYTexture, {
			wrapS: wrapS,
			wrapT: wrapT,
			minFilter: minFilter,
			magFilter: magFilter,
			format: THREE.RGBAFormat,
			type: ( /(iPad|iPhone|iPod)/g.test( navigator.userAgent ) ) ? THREE.HalfFloatType : THREE.FloatType,
			stencilBuffer: false
		} );

		return renderTarget;

	};

    this.createTexture = function( sizeXTexture, sizeYTexture ) {

		sizeXTexture = sizeXTexture || sizeX;
		sizeYTexture = sizeYTexture || sizeY;

		var a = new Float32Array( sizeXTexture * sizeYTexture * 4 );
		var texture = new THREE.DataTexture( a, sizeX, sizeY, THREE.RGBAFormat, THREE.FloatType );
		texture.needsUpdate = true;

		return texture;

	};

	this.renderTexture = function( input, output ) {

		// Takes a texture, and render out in rendertarget
		// input = Texture
		// output = RenderTarget

		passThruUniforms.texture.value = input;

		this.doRenderTarget( passThruShader, output);

		passThruUniforms.texture.value = null;

	};

	this.doRenderTarget = function( material, output ) {

		mesh.material = material;
		renderer.render( scene, camera, output );
		mesh.material = passThruShader;

	};

	// Shaders

	function getPassThroughVertexShader() {

		return	"void main()	{\n" +
				"\n" +
				"	gl_Position = vec4( position, 1.0 );\n" +
				"\n" +
				"}\n";

	}

	function getPassThroughFragmentShader() {

		return	"uniform sampler2D texture;\n" +
				"\n" +
				"void main() {\n" +
				"\n" +
				"	vec2 uv = gl_FragCoord.xy / resolution.xy;\n" +
				"\n" +
				"	gl_FragColor = texture2D( texture, uv );\n" +
				"\n" +
				"}\n";

	}

}<|endoftext|>


<commit_before>// `ddg_spice_urban_dictionary` is a callback function that gets
// "urban dictionary cool" or "urban dictionary ROTFL."

// Note: This plugin can display adult content and profanity.

function ddg_spice_urban_dictionary(response) {
  "use strict";

	if (!(response || response.response.result_type === "exact"
            || response.list || response.list[0])) {
        return;
  }

    var word       = response.list[0].word;
	var definition = response.list[0].definition.replace(/(\r?\n)+/gi, '
');

    Spice.render({
        data             : { 'definition' : definition },
        header1          : word + " (Urban Dictionary)",
        source_url       : 'http://www.urbandictionary.com/define.php?term=' + word,
        source_name      : 'Urban Dictionary',
        template_normal  : 'urban_dictionary',
        force_big_header : true,
    });
}
<commit_msg>Fix whitespace tabs-versus-spaces conflict in Urban_dictionary Spice.<commit_after>// `ddg_spice_urban_dictionary` is a callback function that gets
// "urban dictionary cool" or "urban dictionary ROTFL."

// Note: This plugin can display adult content and profanity.

function ddg_spice_urban_dictionary(response) {
  "use strict";

  if (!(response || response.response.result_type === "exact"
      || response.list || response.list[0])) {
    return;
  }

  var word       = response.list[0].word;
  var definition = response.list[0].definition.replace(/(\r?\n)+/gi, '
');

  Spice.render({
    data             : { 'definition' : definition },
    header1          : word + " (Urban Dictionary)",
    source_url       : 'http://www.urbandictionary.com/define.php?term=' + word,
    source_name      : 'Urban Dictionary',
    template_normal  : 'urban_dictionary',
    force_big_header : true,
  });
}
<|endoftext|>


<commit_before>
 /**
 * This adds {fileName, lineNumber} annotations to React component definitions
 * and to jsx tag literals.
 *
 *
 * == JSX Literals ==
 *
 * <sometag />
 *
 * becomes:
 *
 * var __jsxFileName = 'this/file.js';
 * <sometag __source={{fileName: __jsxFileName, lineNumber: 10}}/>
 */

const TRACE_ID = "__source";
const FILE_NAME_VAR = "__jsxFileName";

export default function ({ types: t }) {
  function makeTrace(lineNumber) {
    const fileLineLiteral = lineNumber != null ? t.numericLiteral(lineNumber) : t.nullLiteral();
    const fileNameProperty = t.objectProperty(t.identifier("fileName"), t.identifier(FILE_NAME_VAR));
    const lineNumberProperty = t.objectProperty(t.identifier("lineNumber"), fileLineLiteral);
    return t.objectExpression([fileNameProperty, lineNumberProperty]);
  }

  function makeFileNameConst(fileName) {
    const declaration = t.variableDeclarator(t.identifier(FILE_NAME_VAR), t.stringLiteral(fileName));
    return t.variableDeclaration("var", [declaration]);
  }

  let visitor = {
    Program(node, state) {
      const fileName = state.file.log.filename !== "unknown"
        ? state.file.log.filename
        : null;

      node.container.program.body.unshift(makeFileNameConst(fileName));
    },

    JSXOpeningElement(node) {
      const id = t.jSXIdentifier(TRACE_ID);
      const location = node.container.openingElement.loc; // undefined for generated elements
      if (location) {
        const trace = makeTrace(location.start.line);
        node.container.openingElement.attributes.push(t.jSXAttribute(id, t.jSXExpressionContainer(trace)));
      }
    }
  };

  return {
    visitor
  };
}
<commit_msg>Generate unique filename variable<commit_after>
 /**
 * This adds {fileName, lineNumber} annotations to React component definitions
 * and to jsx tag literals.
 *
 *
 * == JSX Literals ==
 *
 * <sometag />
 *
 * becomes:
 *
 * var __jsxFileName = 'this/file.js';
 * <sometag __source={{fileName: __jsxFileName, lineNumber: 10}}/>
 */

const TRACE_ID = "__source";
const FILE_NAME_VAR = "_jsxFileName";

export default function ({ types: t }) {
  function makeTrace(fileNameIdentifier, lineNumber) {
    const fileLineLiteral = lineNumber != null ? t.numericLiteral(lineNumber) : t.nullLiteral();
    const fileNameProperty = t.objectProperty(t.identifier("fileName"), fileNameIdentifier);
    const lineNumberProperty = t.objectProperty(t.identifier("lineNumber"), fileLineLiteral);
    return t.objectExpression([fileNameProperty, lineNumberProperty]);
  }

  let jsxVisitor = {
    JSXOpeningElement(node) {
      const id = t.jSXIdentifier(TRACE_ID);
      const location = node.container.openingElement.loc; // undefined for generated elements
      if (location) {
        const trace = makeTrace(this.fileNameIdentifier, location.start.line);
        node.container.openingElement.attributes.push(t.jSXAttribute(id, t.jSXExpressionContainer(trace)));
      }
    }
  };

  let visitor = {
    Program(node, state) {
      const fileName = state.file.log.filename !== "unknown"
        ? state.file.log.filename
        : null;

      const fileNameIdentifier = node.scope.generateUidIdentifier(FILE_NAME_VAR);
      node.scope.push({id: fileNameIdentifier, init: t.stringLiteral(fileName)});
      node.traverse(jsxVisitor, {fileNameIdentifier});
    },
  };

  return {
    visitor
  };
}
<|endoftext|>


<commit_before>var fs = require('fs');
var svm = require('node-svm');

var data = fs.readFileSync('dummy1.json', 'utf8');
var data2 = fs.readFileSync('dummy2.json', 'utf8');
var data3 = fs.readFileSync('dummy3.json', 'utf8');
var data4 = fs.readFileSync('dummy4.json', 'utf8');

var json_data = JSON.parse(data);

var location_pokemon = [];

json_data.forEach(function (element) {
    location_pokemon.push([[element.latitude, element.longitude], element.pokemonId]);
});

console.log(location_pokemon);

var classifier = new svm.CSVC({
    kFold:10
});

classifier.train(location_pokemon).done(function () {
    location_pokemon.forEach(function (element) {
        var prediction = classifier.predictSync(element[0]);
        console.log('%d - %d -- %d', element[0][0], element[0][1], prediction);
    });
});
<commit_msg>Concat on Json files<commit_after>var fs = require('fs');
var svm = require('node-svm');

var data = fs.readFileSync('json/dummy1.json', 'utf8');
var data2 = fs.readFileSync('json/dummy2.json', 'utf8');
var data3 = fs.readFileSync('json/dummy3.json', 'utf8');
var data4 = fs.readFileSync('json/dummy4.json', 'utf8');

var json_data = JSON.parse(data);
var json_data2 = JSON.parse(data2);
var json_data3 = JSON.parse(data3);
var json_data4 = JSON.parse(data4);

json_data = json_data.concat(json_data2);
json_data = json_data.concat(json_data3);
json_data = json_data.concat(json_data4);

var location_pokemon = [];

json_data.forEach(function (element) {
    location_pokemon.push([[element.latitude, element.longitude], element.pokemonId]);
});

console.log(location_pokemon);

var classifier = new svm.CSVC({
    kFold:10
});

classifier.train(location_pokemon)
    .progress(function(progress){
        console.log('training progress: %d%', Math.round(progress*100));
    })

    .done(function () {
        location_pokemon.forEach(function (element) {
            var prediction = classifier.predictSync(element[0]);
            console.log('%d - %d -- %d', element[0][0], element[0][1], prediction);
        });
    });
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

 /**
 * @quotasconfig.api.js
 *     - Handlers for project quotas
 *     - Interfaces with config api server
 */
var rest        = require(process.mainModule.exports["corePath"] +
                          '/src/serverroot/common/rest.api');
var async       = require('async');
var quotasconfigapi = module.exports;
var logutils    = require(process.mainModule.exports["corePath"] +
                          '/src/serverroot/utils/log.utils');
var commonUtils = require(process.mainModule.exports["corePath"] +
                          '/src/serverroot/utils/common.utils');
var config      = require(process.mainModule.exports["corePath"] +
                          '/config/config.global.js');
var messages    = require(process.mainModule.exports["corePath"] +
                          '/src/serverroot/common/messages');
var global      = require(process.mainModule.exports["corePath"] +
                          '/src/serverroot/common/global');
var appErrors   = require(process.mainModule.exports["corePath"] +
                          '/src/serverroot/errors/app.errors');
var util        = require('util');
var url         = require('url');
var configApiServer = require(process.mainModule.exports["corePath"] +
                              '/src/serverroot/common/configServer.api');
var async = require('async');
/**
 * @parseProjectQuotas
 * private function
 * 1. prepares the quota object from the project response
 */
function parseProjectQuotas(error, projData, appData, callback)
{
    var quotaData =  projData["project"]["quota"];
    if(quotaData != undefined) {
         callback(error, projData);
    }
    else {
        callback(error, null);
    }
}

/**
 * @getProjectQuotasCb
 * private function
 * 1. Callback for getProjectQuotas
 * 2. Reads the response of a particular project from config api server
 */
function getProjectQuotasCb (error, projectGetData, appData, callback)
{
    if (error) {
       callback(error, null);
       return;
    }
    parseProjectQuotas(error, projectGetData, appData, callback);
}

/**
 * @readProjectQuotas
 * private function
 * 1. Needs project uuid in string format
 */
function readProjectQuotas (projectIdStr, appData, callback)
{
    var quotasGetURL = '/project/';
    if (projectIdStr.length) {
        quotasGetURL += projectIdStr;
    } else {
        error = new appErrors.RESTServerError('Add Project id');
        callback(error, null);
        return;
    }
    configApiServer.apiGet(quotasGetURL, appData,
                         function(error, data) {
                         getProjectQuotasCb(error, data, appData, callback);
                         });
}

/**
 * @getProjectQuotas
 * public function
 * 1. URL /api/tenants/config/project-quotas/:id
 * 2. Gets project quotas from config api server
 * 3. Needs project id
 */
function getProjectQuotas (request, response, appData)
{
    var projectId = validateProjectId(request);
    projectQuotasAPIGet(projectId, response, appData);
}

/**
 * @updateProjectQuotas
 * public function
 * 1. URL /api/tenants/config/update-quotas/:id
 * 2. Updates project quotas in config api server
 * 3. Needs project id
 */
function updateProjectQuotas(request, response, appData)
{
    var projectId = validateProjectId(request);
    var updateData = request.body;
    var url = "/project/";
    url += projectId ;
    configApiServer.apiPut(url, updateData, appData, function(err, data){
        if (err) {
            commonUtils.handleJSONResponse(err, response, null);
            return;
        }
        projectQuotasAPIGet(projectId, response, appData);
    });
}

function projectQuotasAPIGet(projectId, response, appData) {
    readProjectQuotas(projectId, appData,
                   function(err, data) {
        commonUtils.handleJSONResponse(err, response, data);
    });
}

function processAsyncReq(req, callback) {
    configApiServer.apiGet(req.url, req.appData, function(err, data){
        callback(err, data);
    });
}

/**
 * @getProjectQuotaUsedInfo
 * public function
 * 1. URL /api/tenants/config/quota-used/:name
 * 2. Gets all project resources from config api server to get the count
 * 3. Needs project name
 */
function getProjectQuotaUsedInfo(request, response, appData)
{
    var usedResCnt = {};
    var projName = validateProjectName(request);
    var resources = [{key : 'floating-ips', value : 'floating_ip'},
        {key : 'floating-ip-pools', value : 'floating_ip_pool'},
        {key : 'network-ipams', value : 'network_ipam'},
        {key : 'security-groups', value : 'security_group'},
        {key : 'service-instances', value : 'service_instance'},
        {key : 'virtual-networks', value : 'virtual_network'},
        {key : 'virtual-machine-interfaces', value : 'virtual_machine_interface'},
        {key : 'access-control-lists', value : 'access_control_list'},
        {key : 'network-policys', value : 'network_policy'},
        {key : 'logical-routers', value : 'logical_router'}
    ];
    var callObj = [];
    for(var featureCnt = 0; featureCnt < resources.length; featureCnt ++) {
        var reqObj = {};
        reqObj.url = '/' + resources[featureCnt].key;
        reqObj.appData = appData;
        callObj.push(reqObj);
    }
    async.map(callObj, processAsyncReq, function(err, data){
        if (err) {
            commonUtils.handleJSONResponse(err, response, null);
            return;
        }
        var callVNObj = [];
        var callSGObj = [];
        for(var dataCnt = 0; dataCnt < data.length ; dataCnt++) {
            for(var resCnt = 0; resCnt <  resources.length; resCnt++) {
                var resource = resources[resCnt];
                if(resource.key in data[dataCnt]) {
                    var resData =  data[dataCnt][resource.key];
                    var resCntPerProj = 0;
                    if(resData && resData.length > 0) {
                        for(var resDataCnt = 0; resDataCnt < resData.length ; resDataCnt++) {
                            if(resData[resDataCnt].fq_name[1] ===  projName) {
                               resCntPerProj ++;
                               if(resource.key === 'virtual-networks') {
                                   var vnReqObj = {};
                                   vnReqObj.url =  '/virtual-network/' + resData[resDataCnt].uuid;
                                   vnReqObj.appData = appData;
                                   callVNObj.push(vnReqObj);
                               }
                               if(resource.key === 'security-groups') {
                                   var sgReqObj = {};
                                   sgReqObj.url =  '/security-group/' + resData[resDataCnt].uuid;
                                   sgReqObj.appData = appData;
                                   callSGObj.push(sgReqObj);
                               }
                            }
                        }
                    }
                    usedResCnt[resource.value] = resCntPerProj;
                }
            }
        }
        if(callVNObj.length <= 0) {
            userResCnt['subnet'] = 0;
            if(callSGObj.length <= 0) {
                usedResCnt['security_group_rule'] = 0;
                commonUtils.handleJSONResponse(err, response, usedResCnt);
            } else {
                getSecurityGroupRule(callSGObj, usedResCnt, response, function(error, data) {
                    commonUtils.handleJSONResponse(error, response, usedResCnt);
                });
            }
        } else {
            if(callSGObj.length <= 0) {
                usedResCnt['security_group_rule'] = 0;
                getSubNetsUsedInfo(callVNObj, usedResCnt, response, function(error, data) {
                    commonUtils.handleJSONResponse(error, response, usedResCnt);
                });
            } else {
                getSubNetsUsedInfo(callVNObj, usedResCnt, response, function(error, data) {
                    getSecurityGroupRule(callSGObj, usedResCnt, response, function(error, data) {
                        commonUtils.handleJSONResponse(error, response, usedResCnt);
                    });
                });
            }
        }
    });
}

function getSubNetsUsedInfo(callVNObj, usedResCnt, response, callback)
{
    //prepare used info count for subnets
    async.map(callVNObj, processAsyncReq, function(err, resData) {
        if (err) {
            commonUtils.handleJSONResponse(err, response, null);
            return;
        }
        var resCntPerProj = 0;
        for(var resDataCnt = 0; resDataCnt < resData.length ; resDataCnt++) {
            var ipams = resData[resDataCnt]['virtual-network']['network_ipam_refs'];
            if(ipams && ipams.length > 0) {
                for(var ipamCnt = 0; ipamCnt < ipams.length; ipamCnt++) {
                    var attr = ipams[ipamCnt]['attr'];
                    var subnetsCnt =  attr['ipam_subnets'] ? attr['ipam_subnets'].length : 0;
                    resCntPerProj = resCntPerProj + subnetsCnt;
                }
            }
        }
        usedResCnt['subnet'] = resCntPerProj;
        callback();
    });
}

function getSecurityGroupRule(sgReqObj, usedResCnt, response, callback)
{
    //prepare used info count for subnets
    async.map(sgReqObj, processAsyncReq, function(err, resData) {
        if (err) {
            commonUtils.handleJSONResponse(err, response, null);
            return;
        }
        var subGrpCnt = 0;
        for(var resDataCnt = 0; resDataCnt < resData.length ; resDataCnt++) {
            var sg = resData[resDataCnt]['security-group']['security_group_entries'];
            subGrpCnt += sg['policy_rule'] ? sg['policy_rule'].length : 0;
        }
        usedResCnt['security_group_rule'] = subGrpCnt;
        callback();
    });
}

function validateProjectId (request)
{
    var projectId = null;
    if (!(projectId = request.param('id').toString())) {
        error = new appErrors.RESTServerError('Add Project id');
        commonUtils.handleJSONResponse(error, response, null);
        return;
    }
    return projectId;
}

function validateProjectName (request)
{
    var projectName = null;
    if (!(projectName = request.param('name').toString())) {
        error = new appErrors.RESTServerError('Add Project Name');
        commonUtils.handleJSONResponse(error, response, null);
        return;
    }
    return projectName;
}

 /* List all public function here */

 exports.getProjectQuotas = getProjectQuotas;
 exports.updateProjectQuotas = updateProjectQuotas;
 exports.getProjectQuotaUsedInfo = getProjectQuotaUsedInfo;
<commit_msg>Fixed a bug. - When subnet is set Quata Used was showing "-" Fixed it.  Please enter the commit message for your changes. Lines starting<commit_after>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

 /**
 * @quotasconfig.api.js
 *     - Handlers for project quotas
 *     - Interfaces with config api server
 */
var rest        = require(process.mainModule.exports["corePath"] +
                          '/src/serverroot/common/rest.api');
var async       = require('async');
var quotasconfigapi = module.exports;
var logutils    = require(process.mainModule.exports["corePath"] +
                          '/src/serverroot/utils/log.utils');
var commonUtils = require(process.mainModule.exports["corePath"] +
                          '/src/serverroot/utils/common.utils');
var config      = require(process.mainModule.exports["corePath"] +
                          '/config/config.global.js');
var messages    = require(process.mainModule.exports["corePath"] +
                          '/src/serverroot/common/messages');
var global      = require(process.mainModule.exports["corePath"] +
                          '/src/serverroot/common/global');
var appErrors   = require(process.mainModule.exports["corePath"] +
                          '/src/serverroot/errors/app.errors');
var util        = require('util');
var url         = require('url');
var configApiServer = require(process.mainModule.exports["corePath"] +
                              '/src/serverroot/common/configServer.api');
var async = require('async');
/**
 * @parseProjectQuotas
 * private function
 * 1. prepares the quota object from the project response
 */
function parseProjectQuotas(error, projData, appData, callback)
{
    var quotaData =  projData["project"]["quota"];
    if(quotaData != undefined) {
         callback(error, projData);
    }
    else {
        callback(error, null);
    }
}

/**
 * @getProjectQuotasCb
 * private function
 * 1. Callback for getProjectQuotas
 * 2. Reads the response of a particular project from config api server
 */
function getProjectQuotasCb (error, projectGetData, appData, callback)
{
    if (error) {
       callback(error, null);
       return;
    }
    parseProjectQuotas(error, projectGetData, appData, callback);
}

/**
 * @readProjectQuotas
 * private function
 * 1. Needs project uuid in string format
 */
function readProjectQuotas (projectIdStr, appData, callback)
{
    var quotasGetURL = '/project/';
    if (projectIdStr.length) {
        quotasGetURL += projectIdStr;
    } else {
        error = new appErrors.RESTServerError('Add Project id');
        callback(error, null);
        return;
    }
    configApiServer.apiGet(quotasGetURL, appData,
                         function(error, data) {
                         getProjectQuotasCb(error, data, appData, callback);
                         });
}

/**
 * @getProjectQuotas
 * public function
 * 1. URL /api/tenants/config/project-quotas/:id
 * 2. Gets project quotas from config api server
 * 3. Needs project id
 */
function getProjectQuotas (request, response, appData)
{
    var projectId = validateProjectId(request);
    projectQuotasAPIGet(projectId, response, appData);
}

/**
 * @updateProjectQuotas
 * public function
 * 1. URL /api/tenants/config/update-quotas/:id
 * 2. Updates project quotas in config api server
 * 3. Needs project id
 */
function updateProjectQuotas(request, response, appData)
{
    var projectId = validateProjectId(request);
    var updateData = request.body;
    var url = "/project/";
    url += projectId ;
    configApiServer.apiPut(url, updateData, appData, function(err, data){
        if (err) {
            commonUtils.handleJSONResponse(err, response, null);
            return;
        }
        projectQuotasAPIGet(projectId, response, appData);
    });
}

function projectQuotasAPIGet(projectId, response, appData) {
    readProjectQuotas(projectId, appData,
                   function(err, data) {
        commonUtils.handleJSONResponse(err, response, data);
    });
}

function processAsyncReq(req, callback) {
    configApiServer.apiGet(req.url, req.appData, function(err, data){
        callback(err, data);
    });
}

/**
 * @getProjectQuotaUsedInfo
 * public function
 * 1. URL /api/tenants/config/quota-used/:name
 * 2. Gets all project resources from config api server to get the count
 * 3. Needs project name
 */
function getProjectQuotaUsedInfo(request, response, appData)
{
    var usedResCnt = {};
    var projName = validateProjectName(request);
    var resources = [{key : 'floating-ips', value : 'floating_ip'},
        {key : 'floating-ip-pools', value : 'floating_ip_pool'},
        {key : 'network-ipams', value : 'network_ipam'},
        {key : 'security-groups', value : 'security_group'},
        {key : 'service-instances', value : 'service_instance'},
        {key : 'virtual-networks', value : 'virtual_network'},
        {key : 'virtual-machine-interfaces', value : 'virtual_machine_interface'},
        {key : 'access-control-lists', value : 'access_control_list'},
        {key : 'network-policys', value : 'network_policy'},
        {key : 'logical-routers', value : 'logical_router'}
    ];
    var callObj = [];
    for(var featureCnt = 0; featureCnt < resources.length; featureCnt ++) {
        var reqObj = {};
        reqObj.url = '/' + resources[featureCnt].key;
        reqObj.appData = appData;
        callObj.push(reqObj);
    }
    async.map(callObj, processAsyncReq, function(err, data){
        if (err) {
            commonUtils.handleJSONResponse(err, response, null);
            return;
        }
        var callVNObj = [];
        var callSGObj = [];
        for(var dataCnt = 0; dataCnt < data.length ; dataCnt++) {
            for(var resCnt = 0; resCnt <  resources.length; resCnt++) {
                var resource = resources[resCnt];
                if(resource.key in data[dataCnt]) {
                    var resData =  data[dataCnt][resource.key];
                    var resCntPerProj = 0;
                    if(resData && resData.length > 0) {
                        for(var resDataCnt = 0; resDataCnt < resData.length ; resDataCnt++) {
                            if(resData[resDataCnt].fq_name[1] ===  projName) {
                               resCntPerProj ++;
                               if(resource.key === 'virtual-networks') {
                                   var vnReqObj = {};
                                   vnReqObj.url =  '/virtual-network/' + resData[resDataCnt].uuid;
                                   vnReqObj.appData = appData;
                                   callVNObj.push(vnReqObj);
                               }
                               if(resource.key === 'security-groups') {
                                   var sgReqObj = {};
                                   sgReqObj.url =  '/security-group/' + resData[resDataCnt].uuid;
                                   sgReqObj.appData = appData;
                                   callSGObj.push(sgReqObj);
                               }
                            }
                        }
                    }
                    usedResCnt[resource.value] = resCntPerProj;
                }
            }
        }
        if(callVNObj.length <= 0) {
            usedResCnt['subnet'] = 0;
            if(callSGObj.length <= 0) {
                usedResCnt['security_group_rule'] = 0;
                commonUtils.handleJSONResponse(err, response, usedResCnt);
            } else {
                getSecurityGroupRule(callSGObj, usedResCnt, response, function(error, data) {
                    commonUtils.handleJSONResponse(error, response, usedResCnt);
                });
            }
        } else {
            if(callSGObj.length <= 0) {
                usedResCnt['security_group_rule'] = 0;
                getSubNetsUsedInfo(callVNObj, usedResCnt, response, function(error, data) {
                    commonUtils.handleJSONResponse(error, response, usedResCnt);
                });
            } else {
                getSubNetsUsedInfo(callVNObj, usedResCnt, response, function(error, data) {
                    getSecurityGroupRule(callSGObj, usedResCnt, response, function(error, data) {
                        commonUtils.handleJSONResponse(error, response, usedResCnt);
                    });
                });
            }
        }
    });
}

function getSubNetsUsedInfo(callVNObj, usedResCnt, response, callback)
{
    //prepare used info count for subnets
    async.map(callVNObj, processAsyncReq, function(err, resData) {
        if (err) {
            commonUtils.handleJSONResponse(err, response, null);
            return;
        }
        var resCntPerProj = 0;
        for(var resDataCnt = 0; resDataCnt < resData.length ; resDataCnt++) {
            var ipams = resData[resDataCnt]['virtual-network']['network_ipam_refs'];
            if(ipams && ipams.length > 0) {
                for(var ipamCnt = 0; ipamCnt < ipams.length; ipamCnt++) {
                    var attr = ipams[ipamCnt]['attr'];
                    var subnetsCnt =  attr['ipam_subnets'] ? attr['ipam_subnets'].length : 0;
                    resCntPerProj = resCntPerProj + subnetsCnt;
                }
            }
        }
        usedResCnt['subnet'] = resCntPerProj;
        callback();
    });
}

function getSecurityGroupRule(sgReqObj, usedResCnt, response, callback)
{
    //prepare used info count for subnets
    async.map(sgReqObj, processAsyncReq, function(err, resData) {
        if (err) {
            commonUtils.handleJSONResponse(err, response, null);
            return;
        }
        var subGrpCnt = 0;
        for(var resDataCnt = 0; resDataCnt < resData.length ; resDataCnt++) {
            var sg = resData[resDataCnt]['security-group']['security_group_entries'];
            subGrpCnt += sg['policy_rule'] ? sg['policy_rule'].length : 0;
        }
        usedResCnt['security_group_rule'] = subGrpCnt;
        callback();
    });
}

function validateProjectId (request)
{
    var projectId = null;
    if (!(projectId = request.param('id').toString())) {
        error = new appErrors.RESTServerError('Add Project id');
        commonUtils.handleJSONResponse(error, response, null);
        return;
    }
    return projectId;
}

function validateProjectName (request)
{
    var projectName = null;
    if (!(projectName = request.param('name').toString())) {
        error = new appErrors.RESTServerError('Add Project Name');
        commonUtils.handleJSONResponse(error, response, null);
        return;
    }
    return projectName;
}

 /* List all public function here */

 exports.getProjectQuotas = getProjectQuotas;
 exports.updateProjectQuotas = updateProjectQuotas;
 exports.getProjectQuotaUsedInfo = getProjectQuotaUsedInfo;
<|endoftext|>


<commit_before>function UI(domElement) {

    // <EVENT HANDLING>

    // Thanks for these two functions to the noVNC project. You are great.
    // https://github.com/kanaka/noVNC/blob/master/include/util.js#L121

    // Get DOM element position on page
    this.getPosition = function (obj) {
        var x = 0, y = 0;
        if (obj.offsetParent) {
            do {
                x += obj.offsetLeft;
                y += obj.offsetTop;
                obj = obj.offsetParent;
            } while (obj);
        }
        return {'x': x, 'y': y};
    };

    // Get mouse event position in DOM element (don't know how to use scale yet).
    this.getEventPosition = function (e, obj, scale) {
        var evt, docX, docY, pos;
        //if (!e) evt = window.event;
        evt = (e ? e : window.event);
        if (evt.pageX || evt.pageY) {
            docX = evt.pageX;
            docY = evt.pageY;
        } else if (evt.clientX || evt.clientY) {
            docX = evt.clientX + document.body.scrollLeft +
                document.documentElement.scrollLeft;
            docY = evt.clientY + document.body.scrollTop +
                document.documentElement.scrollTop;
        }
        pos = this.getPosition(obj);
        if (typeof scale === "undefined") {
            scale = 1;
        }
        return {'x': (docX - pos.x) / scale, 'y': (docY - pos.y) / scale};
    };

    // Event handlers: we need closures here, because they will be called as callbacks.

    // On mouseMove event
    this.onMouseMoveFunc = function () {
        var that = this;
            return function (evt) {

            //var realCoords = that.calculateOffset(evt);
            var realCoords = that.getEventPosition (evt, that.domElement);

            // Only if the mouse button is still down (This could be useless TODO).
            if (that.mouseUp === false) {
                that.elementsNotifyEvent(realCoords.x, realCoords.y, "onMouseMove");
            }
        };
    };

    // On mouseDown event
    this.onMouseDownFunc = function () {
        var that = this;
            return function (evt) {

            var realCoords = that.getEventPosition (evt, that.domElement);

            that.mouseUp = false;
            that.elementsNotifyEvent(realCoords.x, realCoords.y, "onMouseDown");
        };
    };

    // On mouseUp event
    this.onMouseUpFunc = function () {
        var that = this;
            return function (evt) {

            var realCoords = that.getEventPosition (evt, that.domElement);

            that.mouseUp = true;
            that.elementsNotifyEvent(realCoords.x, realCoords.y, "onMouseUp");

        };
    };

    // Notify every element about the event.
    this.elementsNotifyEvent = function (x, y, event) {
        // For every element
        for (var name in this.elements) {
            // If it is a real element
            if (this.elements.hasOwnProperty(name)){
                // If the element wants to be bothered with events
                if (this.elements[name].getClickable()) {
                    // Notify the element
                    ret = this.elements[name][event](x, y);
                    // See if the element changed its value
                    if (ret !== undefined) {
                        // console.log("UI: Element ", name, " changed its value on event ", event);
                        this.setValue(name, ret.slot, ret.value);
                    }
                }
            }
        }
    };

    // <END OF EVENT HANDLING>

    // <CONSTRUCTOR>
    this.domElement = domElement;

    this.domElement.addEventListener("mousedown", this.onMouseDownFunc(), true);
    this.domElement.addEventListener("mouseup", this.onMouseUpFunc(), true);
    this.domElement.addEventListener("mousemove", this.onMouseMoveFunc(), true);

    this.mouseUp = true;

    var ret;

    //Elements in this UI.
    this.elements = {};

    //Connection between elements
    this.connections = {};

    // Z-index lists.
    this.zArray = [];
    this.zArrayUndefined = [];

    // </CONSTRUCTOR>

    // <ELEMENT HANDLING>

    // *** Add an UI element **** //
    this.addElement = function (element, drawClass, elementParameters) {
        var slot,
            slots;

        // This encapsulates the drawing class into the GUI element.
        element.setDrawClass(drawClass);

        if (this.elements[element.name] !== undefined) {
            throw new Error("Conflicting / Duplicated name in UI: " + element.name + " (names are identifiers and should be unique)");
            return;
        }

        this.elements[element.name] = element;

        // Insert the element in the connection keys.
        this.connections[element.name] = {};

        // Get the slots available from the element.
        slots = element.getValues();

        // Insert all possible elements in the connection matrix TODO ARRAY
        for (slot in slots) {
            if (slots.hasOwnProperty(slot)) {
                this.connections[element.name][slots[slot]] = [];
            }
        }

        // Store the parameters

        // Z Index.
        if (elementParameters !== undefined) {
            if (typeof(elementParameters.zIndex) === "number") {
                // Insert the element's z-index
                this.elements[element.name].zIndex = elementParameters.zIndex;
                // if it's the first of its kind, initialize the array.
                if (this.zArray[elementParameters.zIndex] === undefined) {
                    this.zArray[elementParameters.zIndex] = [];
                }
                // Update the maximum and minimum z index.
                this.zArray[elementParameters.zIndex].push(this.elements[element.name]);
                if ((this.zMin === undefined) || (this.zMin >  elementParameters.zIndex)) {
                    this.zMin = elementParameters.zIndex;
                }
                if ((this.zMax === undefined) || (this.zMax <  elementParameters.zIndex)) {
                    this.zMax = elementParameters.zIndex;
                }
            }
        }

        else {
            //We store the "undefined" as the lowest z-indexed layers.
            this.elements[element.name].zIndex = undefined;
            this.zArrayUndefined.push(this.elements[element.name]);
        }

    };

    // </ELEMENT HANDLING>

    // <CONNECTION HANDLING>

    // Connect slots, so that one element can "listen" to the other
    this.connectSlots  = function (senderElement, senderSlot, receiverElement, receiverSlot, connectParameters) {

        //Check for the elements.
        if ((this.elements[senderElement] !== undefined) && (this.elements[receiverElement] !== undefined)) {
            // //Check for the slots.
            if ((this.elements[senderElement].values[senderSlot] === undefined) ||
                (this.elements[receiverElement].values[receiverSlot] === undefined))  {
                throw new Error("Slot " + senderSlot + " or " + receiverSlot + " not present.");
            }

            else {

                //The sender & receiver element & slot exist. Do the connection.
                var receiverHash = {"recvElement" : receiverElement, "recvSlot": receiverSlot};

                //Check if there are optional parameters
                if (connectParameters !== undefined) {
                    // Is there a callback?
                    if (typeof(connectParameters.callback) === "function") {
                        receiverHash.callback = connectParameters.callback;
                    }
                }

                // Push the destination element/slot in the connections matrix.
                this.connections[senderElement][senderSlot].push(receiverHash);
            }

        }
        else {
            throw new Error("Element " + senderElement + " or " + receiverElement + " not present.");
        }
    };

    //</CONNECTION HANDLING>

    // <VALUE HANDLING>

    // This method handles one set value event and propagates it in the connections matrix
    this.setValue = function (elementName, slot, value, history) {
        var hist = [],
            receiverHash,
            recvElementName,
            recvSlot,
            i
            RECURSIONMAX = 1000;

        if (this.elements[elementName] !== undefined) {

            // First of all, check history if it is present.
            if (history !== undefined) {
                hist = history;
                // Is this an infinite loop?
                for(var k = 0; k < hist.length ; k += 1) {
                    // This is for precaution.
                    if (hist.length > RECURSIONMAX) {
                        throw new Error ("Recursion exceeded");
                        return;
                    }
                    if ((hist[k]["element"] === elementName) && (hist[k]["slot"] === slot)) {
                        // Loop is infinite; bail out!
                        console.log ("Broke recursion!");
                        return;
                    }
                }
            }
            // Element is present an there's no need to break a loop
            // really set value.
            this.elements[elementName].setValue(slot, value);

            // This element has been already set: update history
            hist.push({"element" : elementName, "slot" : slot});
        }

        else {
            throw new Error("Element " + elementName + " not present.");
        }

        // Z-Index handling: refresh every >z element, starting with z+1
        this.refreshZ(this.elements[elementName].zIndex + 1);

        // Check if this element has connections
        if (this.connections[elementName][slot] !== undefined) {

            // For every connection the element has
            for (i in this.connections[elementName][slot]) {

                if (this.connections[elementName][slot].hasOwnProperty(i)){

                    // Retrieve the other connection end and the connection parameters.
                    receiverHash = this.connections[elementName][slot][i];

                    recvElementName = receiverHash.recvElement;
                    recvSlot = receiverHash.recvSlot;

                    //Check the callback here.
                    if (typeof(receiverHash.callback) === "function") {
                        // We have a callback to call. This is typically
                        // used as a filter to translate the values.
                        value = receiverHash.callback (value);
                    }

                    // Recursively calls itself, keeping an history in the stack
                    // this.elements[recvHash].setValue(recvSlot, value);
                    this.setValue(recvElementName, recvSlot, value, hist);
                }
            }
        }
    };
    // </VALUE HANDLING>

    // <REFRESH HANDLING>
    this.refreshZ = function (z) {
        //Refresh every layer, starting from z to the last one.
        for (var i = z, length =  this.zArray.length; i < length; i += 1) {
            if (typeof(this.zArray[i]) === "object") {
                for (var k = 0, z_length = this.zArray[i].length; k < z_length; k += 1) {
                    this.zArray[i][k].setTainted(true);
                    this.zArray[i][k].refresh();
                }
            }
        }
    }

    this.refresh = function () {
        // Refresh the undefined z-index elements.
        for (var k = 0, z_length = this.zArrayUndefined.length; k < z_length; k += 1) {
            this.zArrayUndefined[k].setTainted(true);
            this.zArrayUndefined[k].refresh();
        }
        // Then refresh everything from the smallest z-value, if there is one.
        if (this.zMin !== undefined) {
            this.refreshZ(this.zMin);
        }
    }

    // </REFRESH HANDLING>

}
<commit_msg>UI handles arrays if returned from onEvent(). Closes #36<commit_after>function UI(domElement) {

    // <EVENT HANDLING>

    // Thanks for these two functions to the noVNC project. You are great.
    // https://github.com/kanaka/noVNC/blob/master/include/util.js#L121

    // Get DOM element position on page
    this.getPosition = function (obj) {
        var x = 0, y = 0;
        if (obj.offsetParent) {
            do {
                x += obj.offsetLeft;
                y += obj.offsetTop;
                obj = obj.offsetParent;
            } while (obj);
        }
        return {'x': x, 'y': y};
    };

    // Get mouse event position in DOM element (don't know how to use scale yet).
    this.getEventPosition = function (e, obj, scale) {
        var evt, docX, docY, pos;
        //if (!e) evt = window.event;
        evt = (e ? e : window.event);
        if (evt.pageX || evt.pageY) {
            docX = evt.pageX;
            docY = evt.pageY;
        } else if (evt.clientX || evt.clientY) {
            docX = evt.clientX + document.body.scrollLeft +
                document.documentElement.scrollLeft;
            docY = evt.clientY + document.body.scrollTop +
                document.documentElement.scrollTop;
        }
        pos = this.getPosition(obj);
        if (typeof scale === "undefined") {
            scale = 1;
        }
        return {'x': (docX - pos.x) / scale, 'y': (docY - pos.y) / scale};
    };

    // Event handlers: we need closures here, because they will be called as callbacks.

    // On mouseMove event
    this.onMouseMoveFunc = function () {
        var that = this;
            return function (evt) {

            //var realCoords = that.calculateOffset(evt);
            var realCoords = that.getEventPosition (evt, that.domElement);

            // Only if the mouse button is still down (This could be useless TODO).
            if (that.mouseUp === false) {
                that.elementsNotifyEvent(realCoords.x, realCoords.y, "onMouseMove");
            }
        };
    };

    // On mouseDown event
    this.onMouseDownFunc = function () {
        var that = this;
            return function (evt) {

            var realCoords = that.getEventPosition (evt, that.domElement);

            that.mouseUp = false;
            that.elementsNotifyEvent(realCoords.x, realCoords.y, "onMouseDown");
        };
    };

    // On mouseUp event
    this.onMouseUpFunc = function () {
        var that = this;
            return function (evt) {

            var realCoords = that.getEventPosition (evt, that.domElement);

            that.mouseUp = true;
            that.elementsNotifyEvent(realCoords.x, realCoords.y, "onMouseUp");

        };
    };

    // Notify every element about the event.
    this.elementsNotifyEvent = function (x, y, event) {
        // For every element
        for (var name in this.elements) {
            // If it is a real element
            if (this.elements.hasOwnProperty(name)){
                // If the element wants to be bothered with events
                if (this.elements[name].getClickable()) {
                    // Notify the element
                    ret = this.elements[name][event](x, y);
                    // See if the element changed its value
                    if (ret !== undefined) {
                        if (ret instanceof Array) {
                            // An element could change multiple slots of itself.
                            for (var i = 0; i < ret.length; i+=1) {
                                this.setValue(name, ret[i].slot, ret[i].value);
                            }
                        }
                        else {
                            // console.log("UI: Element ", name, " changed its value on event ", event);
                            this.setValue(name, ret.slot, ret.value);
                        }
                    }
                }
            }
        }
    };

    // <END OF EVENT HANDLING>

    // <CONSTRUCTOR>
    this.domElement = domElement;

    this.domElement.addEventListener("mousedown", this.onMouseDownFunc(), true);
    this.domElement.addEventListener("mouseup", this.onMouseUpFunc(), true);
    this.domElement.addEventListener("mousemove", this.onMouseMoveFunc(), true);

    this.mouseUp = true;

    var ret;

    //Elements in this UI.
    this.elements = {};

    //Connection between elements
    this.connections = {};

    // Z-index lists.
    this.zArray = [];
    this.zArrayUndefined = [];

    // </CONSTRUCTOR>

    // <ELEMENT HANDLING>

    // *** Add an UI element **** //
    this.addElement = function (element, drawClass, elementParameters) {
        var slot,
            slots;

        // This encapsulates the drawing class into the GUI element.
        element.setDrawClass(drawClass);

        if (this.elements[element.name] !== undefined) {
            throw new Error("Conflicting / Duplicated name in UI: " + element.name + " (names are identifiers and should be unique)");
            return;
        }

        this.elements[element.name] = element;

        // Insert the element in the connection keys.
        this.connections[element.name] = {};

        // Get the slots available from the element.
        slots = element.getValues();

        // Insert all possible elements in the connection matrix TODO ARRAY
        for (slot in slots) {
            if (slots.hasOwnProperty(slot)) {
                this.connections[element.name][slots[slot]] = [];
            }
        }

        // Store the parameters

        // Z Index.
        if (elementParameters !== undefined) {
            if (typeof(elementParameters.zIndex) === "number") {
                // Insert the element's z-index
                this.elements[element.name].zIndex = elementParameters.zIndex;
                // if it's the first of its kind, initialize the array.
                if (this.zArray[elementParameters.zIndex] === undefined) {
                    this.zArray[elementParameters.zIndex] = [];
                }
                // Update the maximum and minimum z index.
                this.zArray[elementParameters.zIndex].push(this.elements[element.name]);
                if ((this.zMin === undefined) || (this.zMin >  elementParameters.zIndex)) {
                    this.zMin = elementParameters.zIndex;
                }
                if ((this.zMax === undefined) || (this.zMax <  elementParameters.zIndex)) {
                    this.zMax = elementParameters.zIndex;
                }
            }
        }

        else {
            //We store the "undefined" as the lowest z-indexed layers.
            this.elements[element.name].zIndex = undefined;
            this.zArrayUndefined.push(this.elements[element.name]);
        }

    };

    // </ELEMENT HANDLING>

    // <CONNECTION HANDLING>

    // Connect slots, so that one element can "listen" to the other
    this.connectSlots  = function (senderElement, senderSlot, receiverElement, receiverSlot, connectParameters) {

        //Check for the elements.
        if ((this.elements[senderElement] !== undefined) && (this.elements[receiverElement] !== undefined)) {
            // //Check for the slots.
            if ((this.elements[senderElement].values[senderSlot] === undefined) ||
                (this.elements[receiverElement].values[receiverSlot] === undefined))  {
                throw new Error("Slot " + senderSlot + " or " + receiverSlot + " not present.");
            }

            else {

                //The sender & receiver element & slot exist. Do the connection.
                var receiverHash = {"recvElement" : receiverElement, "recvSlot": receiverSlot};

                //Check if there are optional parameters
                if (connectParameters !== undefined) {
                    // Is there a callback?
                    if (typeof(connectParameters.callback) === "function") {
                        receiverHash.callback = connectParameters.callback;
                    }
                }

                // Push the destination element/slot in the connections matrix.
                this.connections[senderElement][senderSlot].push(receiverHash);
            }

        }
        else {
            throw new Error("Element " + senderElement + " or " + receiverElement + " not present.");
        }
    };

    //</CONNECTION HANDLING>

    // <VALUE HANDLING>

    // This method handles one set value event and propagates it in the connections matrix
    this.setValue = function (elementName, slot, value, history) {
        var hist = [],
            receiverHash,
            recvElementName,
            recvSlot,
            i
            RECURSIONMAX = 1000;

        if (this.elements[elementName] !== undefined) {

            // First of all, check history if it is present.
            if (history !== undefined) {
                hist = history;
                // Is this an infinite loop?
                for(var k = 0; k < hist.length ; k += 1) {
                    // This is for precaution.
                    if (hist.length > RECURSIONMAX) {
                        throw new Error ("Recursion exceeded");
                        return;
                    }
                    if ((hist[k]["element"] === elementName) && (hist[k]["slot"] === slot)) {
                        // Loop is infinite; bail out!
                        console.log ("Broke recursion!");
                        return;
                    }
                }
            }
            // Element is present an there's no need to break a loop
            // really set value.
            this.elements[elementName].setValue(slot, value);

            // This element has been already set: update history
            hist.push({"element" : elementName, "slot" : slot});
        }

        else {
            throw new Error("Element " + elementName + " not present.");
        }

        // Z-Index handling: refresh every >z element, starting with z+1
        this.refreshZ(this.elements[elementName].zIndex + 1);

        // Check if this element has connections
        if (this.connections[elementName][slot] !== undefined) {

            // For every connection the element has
            for (i in this.connections[elementName][slot]) {

                if (this.connections[elementName][slot].hasOwnProperty(i)){

                    // Retrieve the other connection end and the connection parameters.
                    receiverHash = this.connections[elementName][slot][i];

                    recvElementName = receiverHash.recvElement;
                    recvSlot = receiverHash.recvSlot;

                    //Check the callback here.
                    if (typeof(receiverHash.callback) === "function") {
                        // We have a callback to call. This is typically
                        // used as a filter to translate the values.
                        value = receiverHash.callback (value);
                    }

                    // Recursively calls itself, keeping an history in the stack
                    // this.elements[recvHash].setValue(recvSlot, value);
                    this.setValue(recvElementName, recvSlot, value, hist);
                }
            }
        }
    };
    // </VALUE HANDLING>

    // <REFRESH HANDLING>
    this.refreshZ = function (z) {
        //Refresh every layer, starting from z to the last one.
        for (var i = z, length =  this.zArray.length; i < length; i += 1) {
            if (typeof(this.zArray[i]) === "object") {
                for (var k = 0, z_length = this.zArray[i].length; k < z_length; k += 1) {
                    this.zArray[i][k].setTainted(true);
                    this.zArray[i][k].refresh();
                }
            }
        }
    }

    this.refresh = function () {
        // Refresh the undefined z-index elements.
        for (var k = 0, z_length = this.zArrayUndefined.length; k < z_length; k += 1) {
            this.zArrayUndefined[k].setTainted(true);
            this.zArrayUndefined[k].refresh();
        }
        // Then refresh everything from the smallest z-value, if there is one.
        if (this.zMin !== undefined) {
            this.refreshZ(this.zMin);
        }
    }

    // </REFRESH HANDLING>

}
<|endoftext|>


<commit_before>

  /**
   * User options dropdown (extends Dropdown)
   *
   * It shows the content in a dropdown (or dropup) with a special effect.
   *
   * Usage example:
   *
      var user_menu = new cdb.admin.DropdownMenu({
        target: $('a.account'),
        model: {username: username}, // No necessary indeed
        template_base: 'common/views/settings_item'
      });
   *
   */

  cdb.admin.DropdownMenu = cdb.ui.common.Dropdown.extend({

    show: function() {
      var dfd = $.Deferred();
      var self = this;
      //sometimes this dialog is child of a node that is removed
      //for that reason we link again DOM events just in case
      this.delegateEvents();
      this.$el
        .css({
          marginTop: self.options.vertical_position == "down" ? "-10px" : "10px",
          opacity:0,
          display:"block"
        })
        .animate({
          margin: "0",
          opacity: 1
        }, {
          "duration": this.options.speedIn,
          "complete": function(){
            dfd.resolve();
          }
        });
      this.trigger("onDropdownShown",this.el);

      return dfd.promise();
    },

    /**
     * open the dialog at x, y
     */
    openAt: function(x, y) {
      var dfd = $.Deferred();

      this.$el.css({
        top: y,
        left: x,
        width: this.options.width
      })
      .addClass(
        (this.options.vertical_position == "up" ? "vertical_top" : "vertical_bottom" )
        + " " +
        (this.options.horizontal_position == "right" ? "horizontal_right" : "horizontal_left" )
        + " " +
        // Add tick class
        "tick_" + this.options.tick
      )

      this.isOpen = true;

      // Show
      $.when(this.show()).done(function(){ dfd.resolve();})
      // xabel: I've add the deferred to make it easily testable

      return dfd.promise();
    },

    hide: function(done) {
      var self = this;
      this.isOpen = false;

      this.$el.animate({
        marginTop: self.options.vertical_position == "down" ? "10px" : "-10px",
        opacity: 0
      },this.options.speedOut, function(){
        // Remove selected class
        $(self.options.target).removeClass("selected");
        // And hide it
        self.$el.hide();
        done && done();
      });
      this.trigger("onDropdownHidden",this.el);
    }
  });
<commit_msg>The dropdowns can be open now after resizing the viewport<commit_after>

  /**
   * User options dropdown (extends Dropdown)
   *
   * It shows the content in a dropdown (or dropup) with a special effect.
   *
   * Usage example:
   *
      var user_menu = new cdb.admin.DropdownMenu({
        target: $('a.account'),
        model: {username: username}, // No necessary indeed
        template_base: 'common/views/settings_item'
      });
   *
   */

  cdb.admin.DropdownMenu = cdb.ui.common.Dropdown.extend({

    show: function() {
      var dfd = $.Deferred();
      var self = this;
      //sometimes this dialog is child of a node that is removed
      //for that reason we link again DOM events just in case
      this.delegateEvents();
      this.$el
        .css({
          marginTop: self.options.vertical_position == "down" ? "-10px" : "10px",
          opacity:0,
          display:"block"
        })
        .animate({
          margin: "0",
          opacity: 1
        }, {
          "duration": this.options.speedIn,
          "complete": function(){
            dfd.resolve();
          }
        });
      this.trigger("onDropdownShown",this.el);

      return dfd.promise();
    },

    /**
     * open the dialog at x, y
     */
    openAt: function(x, y) {
      var dfd = $.Deferred();

      this.$el.css({
        top: y,
        left: x,
        width: this.options.width
      })
      .addClass(
        (this.options.vertical_position == "up" ? "vertical_top" : "vertical_bottom" )
        + " " +
        (this.options.horizontal_position == "right" ? "horizontal_right" : "horizontal_left" )
        + " " +
        // Add tick class
        "tick_" + this.options.tick
      )

      this.isOpen = true;

      // Show
      $.when(this.show()).done(function(){ dfd.resolve();})
      // xabel: I've add the deferred to make it easily testable

      return dfd.promise();
    },

    hide: function(done) {

      // don't attempt to hide the dropdown if it's already hidden
      if (!this.isOpen) return;

      var self    = this;
      this.isOpen = false;

      this.$el.animate({

        marginTop: self.options.vertical_position == "down" ? "10px" : "-10px",
        opacity: 0

      }, this.options.speedOut, function(){

        // Remove selected class
        $(self.options.target).removeClass("selected");

        // And hide it
        self.$el.hide();
        done && done();

      });

      this.trigger("onDropdownHidden",this.el);

    }
  });
<|endoftext|>