<commit_before>(function(ko) {
    function ViewModel() {
        var self = this;

        self.settings = {
            uppercase: true
        };

        self.base = ko.observable(1);
        self.checked = ko.observableArray();
        self.selectedValue = ko.computed(function() {
            var value = 0;
            var checked = self.checked();
            for(var i=0;i<checked.length; ++i) {
                value = value | checked[i];
            }
            return value;
        });
        self.engine = ko.observable();
        self.engineParam = ko.observable();
        self.engineParamVisible = ko.observable();
        self.engines = ko.observableArray();
        self.keyedEngines = {};

        self.values = ko.observableArray([]);
        self.keyedValues = {};
        self.valuesToAdd = ko.observable('');
        self.valuesToAgg = ko.observable('');
        self.valueToAgg = ko.observable('');
        self.aggPlaceholder = ko.computed(function() {
            if(self.selectedValue())
                return self.selectedValue();
        });

        self.values.subscribe(function(objects){
            for(var i=0;i<objects.length;++i) {
                var i_value = objects[i].value;
                var i_status = objects[i].status;
                if(i_status == 'added')
                    self.keyedValues[i_value.name] = i_value.base;
                else if(i_status == 'deleted' && !objects[i].moved)
                    delete self.keyedValues[i_value.name];
            }

            self.values.sort(function(a,b){return a.base-b.base;});
            var sorted = Object.keys(self.keyedValues).sort(function(a,b){return self.keyedValues[a]-self.keyedValues[b];});
            var newKeyedValues = {};
            for(var j=0;j<sorted.length;++j) {
                newKeyedValues[sorted[j]] = self.keyedValues[sorted[j]];
            }
            self.keyedValues = newKeyedValues;
        }, null, 'arrayChange');

        self.rendered = ko.computed(function() {
            if(undefined !== self.keyedEngines[self.engine()]) {
                var engineObject = self.keyedEngines[self.engine()];
                return engineObject.callback.call(self, self.values(), self.engineParam());
            }
        });

        self.addIt = function() {
            var success = true;
            var arr = self.valuesToAdd().trim().split("\n");
            for(var i=0; i<arr.length;++i) {
                var name = arr[i].trim();
                if(name.length > 0)
                    success = success & addValue(name);
            }
            if(success) self.valuesToAdd('');
        };
        self.aggIt = function() {
            var arr = self.valuesToAgg()?self.valuesToAgg().trim().split("\n"):[];
            var base = 0;
            var success = true;
            if(arr.length === 0 && self.selectedValue()) {
                base = self.selectedValue();
            }
            else
                for(var i=0; i<arr.length;++i) {
                    var i_name = arr[i].trim();
                    if(i_name.length > 0) {
                        if (i_name == '*'){
                            base = base | self.base()-1;
                        }
                        else if(undefined !== self.keyedValues[i_name]) {
                            base = base | self.keyedValues[i_name];
                        }
                        else if (parseInt(i_name)){
                            base = base | parseInt(i_name);
                        }
                        else {
                            success = false;
                        }
                    }
                }
                var name = self.valueToAgg().trim();
                if(success && base && undefined === self.keyedValues[name] && name.length) {
                    self.values.push({'name': name, 'base': base});
                    self.valueToAgg('');
                    self.valuesToAgg('');
                }
            };

            function addValue(name) {
                if(undefined === self.keyedValues[name]) {
                    var base = self.base();
                    self.values.push({'name': name, 'base': base});
                    self.base(self.base()*2);
                    return true;
                }
                return false;
            }
            var addValues = function(json) {
                var max = 0;
                for(var i=0; i<json.length;++i) {
                    var i_value = json[i];
                    self.values.push({'name': i_value.name, 'base': i_value.base});
                    if(i_value.base > max)
                        max = i_value.base;
                }
                self.base(Math.pow(2, 1+Math.floor(Math.log(max)/Math.log(2))));
            };
            self.addValues = addValues;
            self.reset = function() {
                self.base(1);
                self.values.splice(0);
                wisebit.valueToAgg('');
                wisebit.valuesToAgg('');
                wisebit.valuesToAdd('');
            };

            self.registerEngine = function(name, callback, param) {
                self.keyedEngines[name] = { name: name, callback: callback, param: param };
                self.engines.push(name);
            };
            self.switchEngine = function(engine) {
                self.engine(engine);
                if(undefined !== self.keyedEngines[self.engine()]) {
                    var engineObject = self.keyedEngines[self.engine()];
                    self.engineParam(engineObject.param);
                    self.engineParamVisible(engineObject.param && engineObject.param.length>0);
                }
            };

            self.examples = ko.observableArray([]);
            self.doExample = function(example) {
                self.reset();
                example.callback.call(self, self);
            };
        }

        var vm = new ViewModel();
        ko.applyBindings(vm, document.getElementById('vm'));

        vm.registerEngine('JSON', function(values) {
            return JSON.stringify(this.keyedValues);
        });
        vm.registerEngine('JSON 2', function(values) {
            return JSON.stringify(this.values());
        });
        vm.registerEngine('PHP', function(values) {
            var str = 'array(';
                for(var name in this.keyedValues)
                    str += "'"+name+"' => "+this.keyedValues[name]+", ";
                str += ')';
        return str;
    });
        vm.registerEngine('C', function(values) {
            var str = 'enum WISEBIT {\n';
            for(var i=0;i<values.length;++i) {
                var name = values[i].name;
                var base = values[i].base;
                str += "    "+name.toUpperCase()+" = "+base;
                if(i < values.length-1) str += ",";
                str += "\n";
            }
            str += '}';
            return str;
        });
        vm.registerEngine('Python', function(values) {
            var str = 'class Wisebit(Enum):\n';
            for(var name in this.keyedValues)
                str += "\t"+name+" = "+this.keyedValues[name] + "\n";
            return str;
        });
        vm.registerEngine('static', function(values, param) {
            var str = '    /* Wisebits */\n';
            for(var name in this.keyedValues)
                str += "    "+param+" "+name.toUpperCase()+" = "+this.keyedValues[name] + ";\n";
            return str;
        }, 'public const int');

        vm.switchEngine(vm.engines()[0]);

window.wisebit = vm; // Leak into global namespace

})(ko);

// Examples here
wisebit.examples([{name: 'States', callback: function(wisebit) {

    wisebit.switchEngine("static");
    wisebit.addValues([
        {name: 'State1', base: 1 },
        {name: 'State2', base: 2 },
        {name: 'State3', base: 4 },
        {name: 'StateMask', base: 7 }
        ]);
    wisebit.valueToAgg('State1|2');
    wisebit.valuesToAgg('State1\nState2');
}
},
{name: 'Rights', callback: function(wisebit) {

    wisebit.switchEngine("JSON");
    wisebit.addValues([
        {name: 'Read', base: 1 },
        {name: 'Write', base: 2 },
        {name: 'Manage', base: 4 },
        {name: 'Admin', base: 7 }
        ]);
    wisebit.valueToAgg('Editor');
    wisebit.valuesToAgg('Read\nWrite');

}
},
{name: 'UNIX', callback: function(wisebit) {

    wisebit.switchEngine("JSON");
    wisebit.addValues([
        {name: 'Execute', base: 1 },
        {name: 'Write', base: 2 },
        {name: 'Read', base: 4 },
        {name: 'All', base: 7 }
        ]);
}
},
{name: 'PHP Errors', callback: function(wisebit) {

    wisebit.switchEngine("JSON");
    wisebit.valuesToAdd("E_ERROR\nE_WARNING\nE_PARSE\nE_NOTICE\nE_CORE_ERROR\nE_CORE_WARNING\nE_COMPILE_ERROR\nE_COMPILE_WARNING\nE_USER_ERROR\nE_USER_WARNING\nE_USER_NOTICE\nE_STRICT\nE_RECOVERABLE_ERROR\nE_DEPRECATED\nE_USER_DEPRECATED\n");
    wisebit.valueToAgg("E_ALL");
    wisebit.valuesToAgg("*");
    wisebit.switchEngine("static");
    wisebit.engineParam("const");
// http://php.net/manual/errorfunc.constants.php
/*
wisebit.addValues([
{'base': 1, 'name': 'E_ERROR'},
{'base': 2, 'name': 'E_WARNING'},
{'base': 4, 'name': 'E_PARSE'},
{'base': 8, 'name': 'E_NOTICE'},
{'base': 16,    'name': 'E_CORE_ERROR'},
{'base': 32,    'name': 'E_CORE_WARNING'},
{'base': 64,    'name': 'E_COMPILE_ERROR'},
{'base': 128,   'name': 'E_COMPILE_WARNING'},
{'base': 256,   'name': 'E_USER_ERROR'},
{'base': 512,   'name': 'E_USER_WARNING'},
{'base': 1024,  'name': 'E_USER_NOTICE'},
{'base': 2048,  'name': 'E_STRICT'},
{'base': 4096,  'name': 'E_RECOVERABLE_ERROR'},
{'base': 8192,  'name': 'E_DEPRECATED'},
{'base': 16384, 'name': 'E_USER_DEPRECATED'},
{'base': 32767, 'name': 'E_ALL'}
]);
*/

}
}
]);
<commit_msg>wisebit.js proper indent who did that in the first place =O !<commit_after>(function(ko) {
    function ViewModel() {
        var self = this;

        self.settings = {
            uppercase: true
        };

        self.base = ko.observable(1);
        self.checked = ko.observableArray();
        self.selectedValue = ko.computed(function() {
            var value = 0;
            var checked = self.checked();
            for(var i=0;i<checked.length; ++i) {
                value = value | checked[i];
            }
            return value;
        });
        self.engine = ko.observable();
        self.engineParam = ko.observable();
        self.engineParamVisible = ko.observable();
        self.engines = ko.observableArray();
        self.keyedEngines = {};

        self.values = ko.observableArray([]);
        self.keyedValues = {};
        self.valuesToAdd = ko.observable('');
        self.valuesToAgg = ko.observable('');
        self.valueToAgg = ko.observable('');
        self.aggPlaceholder = ko.computed(function() {
            if(self.selectedValue())
                return self.selectedValue();
        });

        self.values.subscribe(function(objects){
            for(var i=0;i<objects.length;++i) {
                var i_value = objects[i].value;
                var i_status = objects[i].status;
                if(i_status == 'added')
                    self.keyedValues[i_value.name] = i_value.base;
                else if(i_status == 'deleted' && !objects[i].moved)
                    delete self.keyedValues[i_value.name];
            }

            self.values.sort(function(a,b){return a.base-b.base;});
            var sorted = Object.keys(self.keyedValues).sort(function(a,b){return self.keyedValues[a]-self.keyedValues[b];});
            var newKeyedValues = {};
            for(var j=0;j<sorted.length;++j) {
                newKeyedValues[sorted[j]] = self.keyedValues[sorted[j]];
            }
            self.keyedValues = newKeyedValues;
        }, null, 'arrayChange');

        self.rendered = ko.computed(function() {
            if(undefined !== self.keyedEngines[self.engine()]) {
                var engineObject = self.keyedEngines[self.engine()];
                return engineObject.callback.call(self, self.values(), self.engineParam());
            }
        });

        self.addIt = function() {
            var success = true;
            var arr = self.valuesToAdd().trim().split("\n");
            for(var i=0; i<arr.length;++i) {
                var name = arr[i].trim();
                if(name.length > 0)
                    success = success & addValue(name);
            }
            if(success) self.valuesToAdd('');
        };
        self.aggIt = function() {
            var arr = self.valuesToAgg()?self.valuesToAgg().trim().split("\n"):[];
            var base = 0;
            var success = true;
            if(arr.length === 0 && self.selectedValue()) {
                base = self.selectedValue();
            }
            else
                for(var i=0; i<arr.length;++i) {
                    var i_name = arr[i].trim();
                    if(i_name.length > 0) {
                        if (i_name == '*'){
                            base = base | self.base()-1;
                        }
                        else if(undefined !== self.keyedValues[i_name]) {
                            base = base | self.keyedValues[i_name];
                        }
                        else if (parseInt(i_name)){
                            base = base | parseInt(i_name);
                        }
                        else {
                            success = false;
                        }
                    }
                }
            var name = self.valueToAgg().trim();
            if(success && base && undefined === self.keyedValues[name] && name.length) {
                self.values.push({'name': name, 'base': base});
                self.valueToAgg('');
                self.valuesToAgg('');
            }
        };

        function addValue(name) {
            if(undefined === self.keyedValues[name]) {
                var base = self.base();
                self.values.push({'name': name, 'base': base});
                self.base(self.base()*2);
                return true;
            }
            return false;
        }
        var addValues = function(json) {
            var max = 0;
            for(var i=0; i<json.length;++i) {
                var i_value = json[i];
                self.values.push({'name': i_value.name, 'base': i_value.base});
                if(i_value.base > max)
                    max = i_value.base;
            }
            self.base(Math.pow(2, 1+Math.floor(Math.log(max)/Math.log(2))));
        };
        self.addValues = addValues;
        self.reset = function() {
            self.base(1);
            self.values.splice(0);
            wisebit.valueToAgg('');
            wisebit.valuesToAgg('');
            wisebit.valuesToAdd('');
        };

        self.registerEngine = function(name, callback, param) {
            self.keyedEngines[name] = { name: name, callback: callback, param: param };
            self.engines.push(name);
        };
        self.switchEngine = function(engine) {
            self.engine(engine);
            if(undefined !== self.keyedEngines[self.engine()]) {
                var engineObject = self.keyedEngines[self.engine()];
                self.engineParam(engineObject.param);
                self.engineParamVisible(engineObject.param && engineObject.param.length>0);
            }
        };

        self.examples = ko.observableArray([]);
        self.doExample = function(example) {
            self.reset();
            example.callback.call(self, self);
        };
    }

    var vm = new ViewModel();
    ko.applyBindings(vm, document.getElementById('vm'));

    vm.registerEngine('JSON', function(values) {
        return JSON.stringify(this.keyedValues);
    });
    vm.registerEngine('JSON 2', function(values) {
        return JSON.stringify(this.values());
    });
    vm.registerEngine('PHP', function(values) {
        var str = 'array(';
            for(var name in this.keyedValues)
                str += "'"+name+"' => "+this.keyedValues[name]+", ";
            str += ')';
        return str;
    });
    vm.registerEngine('C', function(values) {
        var str = 'enum WISEBIT {\n';
        for(var i=0;i<values.length;++i) {
            var name = values[i].name;
            var base = values[i].base;
            str += "    "+name.toUpperCase()+" = "+base;
            if(i < values.length-1) str += ",";
            str += "\n";
        }
        str += '}';
        return str;
    });
    vm.registerEngine('Python', function(values) {
        var str = 'class Wisebit(Enum):\n';
        for(var name in this.keyedValues)
            str += "\t"+name+" = "+this.keyedValues[name] + "\n";
        return str;
    });
    vm.registerEngine('static', function(values, param) {
        var str = '    /* Wisebits */\n';
        for(var name in this.keyedValues)
            str += "    "+param+" "+name.toUpperCase()+" = "+this.keyedValues[name] + ";\n";
        return str;
    }, 'public const int');

    vm.switchEngine(vm.engines()[0]);

    window.wisebit = vm; // Leak into global namespace

})(ko);

// Examples here
wisebit.examples([
    {name: 'States', callback: function(wisebit) {

        wisebit.switchEngine("static");
        wisebit.addValues([
            {name: 'State1', base: 1 },
            {name: 'State2', base: 2 },
            {name: 'State3', base: 4 },
            {name: 'StateMask', base: 7 }
            ]);
        wisebit.valueToAgg('State1|2');
        wisebit.valuesToAgg('State1\nState2');
    }},
    {name: 'Rights', callback: function(wisebit) {

        wisebit.switchEngine("JSON");
        wisebit.addValues([
            {name: 'Read', base: 1 },
            {name: 'Write', base: 2 },
            {name: 'Manage', base: 4 },
            {name: 'Admin', base: 7 }
            ]);
        wisebit.valueToAgg('Editor');
        wisebit.valuesToAgg('Read\nWrite');

    }},
    {name: 'UNIX', callback: function(wisebit) {

        wisebit.switchEngine("JSON");
        wisebit.addValues([
            {name: 'Execute', base: 1 },
            {name: 'Write', base: 2 },
            {name: 'Read', base: 4 },
            {name: 'All', base: 7 }
            ]);
    }},
    {name: 'PHP Errors', callback: function(wisebit) {

        wisebit.switchEngine("JSON");
        wisebit.valuesToAdd("E_ERROR\nE_WARNING\nE_PARSE\nE_NOTICE\nE_CORE_ERROR\nE_CORE_WARNING\nE_COMPILE_ERROR\nE_COMPILE_WARNING\nE_USER_ERROR\nE_USER_WARNING\nE_USER_NOTICE\nE_STRICT\nE_RECOVERABLE_ERROR\nE_DEPRECATED\nE_USER_DEPRECATED\n");
        wisebit.valueToAgg("E_ALL");
        wisebit.valuesToAgg("*");
        wisebit.switchEngine("static");
        wisebit.engineParam("const");
        // http://php.net/manual/errorfunc.constants.php
        /*
        wisebit.addValues([
        {'base': 1, 'name': 'E_ERROR'},
        {'base': 2, 'name': 'E_WARNING'},
        {'base': 4, 'name': 'E_PARSE'},
        {'base': 8, 'name': 'E_NOTICE'},
        {'base': 16,    'name': 'E_CORE_ERROR'},
        {'base': 32,    'name': 'E_CORE_WARNING'},
        {'base': 64,    'name': 'E_COMPILE_ERROR'},
        {'base': 128,   'name': 'E_COMPILE_WARNING'},
        {'base': 256,   'name': 'E_USER_ERROR'},
        {'base': 512,   'name': 'E_USER_WARNING'},
        {'base': 1024,  'name': 'E_USER_NOTICE'},
        {'base': 2048,  'name': 'E_STRICT'},
        {'base': 4096,  'name': 'E_RECOVERABLE_ERROR'},
        {'base': 8192,  'name': 'E_DEPRECATED'},
        {'base': 16384, 'name': 'E_USER_DEPRECATED'},
        {'base': 32767, 'name': 'E_ALL'}
        ]);
        */

    }}
]);
<|endoftext|>


<commit_before>// display: table and table-cell test. (both are tested under one name "table-cell" )
// By @scottjehl
Modernizr.addTest( "display-table",function(){
	var doc		= window.document,
		docElem	= doc.documentElement,
		create	= function( el ){
			return doc.createElement( el );
		},
		parent	= create( "div" ),
		child	= create( "div" ),
		childb	= create( "div" ),
		ret;

	parent.style.display = "table";
	child.style.display = childb.style.display = "table-cell";
	child.style.padding = childb.style.padding = "10px";

	parent.appendChild( child );
	parent.appendChild( childb );
	docElem.insertBefore( parent, docElem.firstChild );

	ret = child.offsetLeft < childb.offsetLeft;
	docElem.removeChild(parent);
	return ret;
});<commit_msg>fixing scott's table display detect so it sucks less. :)<commit_after>// display: table and table-cell test. (both are tested under one name "table-cell" )
// By @scottjehl

// all additional table display values are here: http://pastebin.com/Gk9PeVaQ though Scott has seen some IE false positives with that sort of weak detection.
// more testing neccessary perhaps.

Modernizr.addTest( "display-table",function(){

  var doc   = window.document,
      docElem = doc.documentElement,
      create  = function( el ){
        return doc.createElement( el );
      },
    parent  = create( "div" ),
    child = create( "div" ),
    childb  = create( "div" ),
    ret;

  parent.style.display = "table";
  child.style.display = childb.style.display = "table-cell";
  child.style.padding = childb.style.padding = "10px";

  parent.appendChild( child );
  parent.appendChild( childb );
  docElem.insertBefore( parent, docElem.firstChild );

  ret = child.offsetLeft < childb.offsetLeft;
  docElem.removeChild(parent);
  return ret;
});

<|endoftext|>


<commit_before>/* eslint-env es6 */
/* global THREE, VertexIndices */

function transformBoxVertices( method ) {
  'use strict';

  const vector = new THREE.Vector3();
  const zero = new THREE.Vector3();

  function baseTransform( geometry, key, delta, ...args ) {
    const indices = VertexIndices[ key.toUpperCase() ];

    if ( Array.isArray( delta ) ) {
      vector.fromArray( delta );
    } else if ( typeof delta === 'object' ) {
      Object.assign( vector, zero, delta );
    } else if ( typeof delta === 'number' ) {
      vector.setScalar( delta );
    } else {
      return geometry;
    }

    if ( Array.isArray( indices ) ) {
      indices.forEach( index =>
        geometry.vertices[ index ][ method ]( vector, ...args )
      );
    }

    return geometry;
  }

  return function transform( geometry, vectors, ...args ) {
    if ( typeof vectors === 'string' ) {
      return baseTransform( geometry, vectors, ...args );
    } else if ( typeof vectors === 'object' ) {
      Object.keys( vectors ).forEach( key => {
        const delta = vectors[ key ];
        baseTransform( geometry, key, delta, ...args );
      });
    }

    return geometry;
  };
}

window.translateBoxVertices = transformBoxVertices( 'add' );
window.scaleBoxVertices = transformBoxVertices( 'multiply' );
window.lerpBoxVertices = transformBoxVertices( 'lerp' );

// Per-axis THREE.BoxGeometry methods.
const transformAxisBoxVertices = (function() {
  'use strict';

  const vector = new THREE.Vector3();

  return ( method, identity = new THREE.Vector3() ) => {
    return axis => {
      function baseTransformAxis(
        geometry,
        key,
        delta = identity.getComponent( axis ),
        ...args
      ) {
        const indices = VertexIndices[ key.toUpperCase() ];

        if ( Array.isArray( indices ) ) {
          vector
            .copy( identity )
            .setComponent( axis, delta );

          indices.forEach( index =>
            geometry.vertices[ index ][ method ]( vector, ...args )
          );
        }

        return geometry;
      }

      return function transformAxis( geometry, vectors, ...args ) {
        if ( typeof vectors === 'string' ) {
          const delta = args.shift();
          return baseTransformAxis( geometry, vectors, delta, ...args );
        } else if ( typeof vectors === 'object' ) {
          Object.keys( vectors ).forEach( key => {
            const delta = vectors[ key ];
            baseTransformAxis( geometry, key, delta, ...args );
          });
        }

        return geometry;
      };
    };
  };
}());

const translateAxisBoxVertices = transformAxisBoxVertices( 'add' );

window.translateXBoxVertices = translateAxisBoxVertices( 0 );
window.translateYBoxVertices = translateAxisBoxVertices( 1 );
window.translateZBoxVertices = translateAxisBoxVertices( 2 );

const scaleAxisBoxVertices = transformAxisBoxVertices( 'multiply', new THREE.Vector3( 1, 1, 1 ) );

window.scaleXBoxVertices = scaleAxisBoxVertices( 0 );
window.scaleYBoxVertices = scaleAxisBoxVertices( 1 );
window.scaleZBoxVertices = scaleAxisBoxVertices( 2 );

// Call THREE.BoxGeometry methods directly.
function callBoxVertices( method ) {
  'use strict';

  function baseCall( geometry, key, ...args ) {
    const indices = VertexIndices[ key.toUpperCase() ];

    if ( Array.isArray( indices ) ) {
      indices.forEach( index =>
        geometry.vertices[ index ][ method ]( ...args )
      );
    }

    return geometry;
  }

  return function call( geometry, vectors, ...args ) {
    if ( typeof vectors === 'string' ) {
      return baseCall( geometry, vectors, ...args );
    } else if ( typeof vectors === 'object' ) {
      Object.keys( vectors ).forEach( key => {
        const value = vectors[ key ];
        baseCall( geometry, key, value, ...args );
      });
    }

    return geometry;
  };
}

window.setBoxVertices = callBoxVertices( 'set' );
window.setXBoxVertices = callBoxVertices( 'setX' );
window.setYBoxVertices = callBoxVertices( 'setY' );
window.setZBoxVertices = callBoxVertices( 'setZ' );
window.copyBoxVertices = callBoxVertices( 'copy' );

//  Get the first matching THREE.BoxGeometry vertex.
function getBoxVertex( geometry, key ) {
  'use strict';

  if ( key ) {
    const indices = VertexIndices[ key.toUpperCase() ];

    if ( Array.isArray( indices ) ) {
      return geometry.vertices[ indices[ 0 ] ];
    }
  }

  return geometry.vertices[ 0 ];
}

window.getBoxVertex = getBoxVertex;
<commit_msg>lathe[cuboid]: Support identity THREE.BoxGeometry vertex transforms.<commit_after>/* eslint-env es6 */
/* global THREE, VertexIndices */

const transformBoxVertices = (function() {
  'use strict';

  const vector = new THREE.Vector3();

  return ( method, identity = new THREE.Vector3() ) => {
    function baseTransform( geometry, key, delta, ...args ) {
      const indices = VertexIndices[ key.toUpperCase() ];

      if ( Array.isArray( delta ) ) {
        vector.fromArray( delta );
      } else if ( typeof delta === 'object' ) {
        Object.assign( vector, identity, delta );
      } else if ( typeof delta === 'number' ) {
        vector.setScalar( delta );
      } else {
        return geometry;
      }

      if ( Array.isArray( indices ) ) {
        indices.forEach( index =>
          geometry.vertices[ index ][ method ]( vector, ...args )
        );
      }

      return geometry;
    }

    return function transform( geometry, vectors, ...args ) {
      if ( typeof vectors === 'string' ) {
        return baseTransform( geometry, vectors, ...args );
      } else if ( typeof vectors === 'object' ) {
        Object.keys( vectors ).forEach( key => {
          const delta = vectors[ key ];
          baseTransform( geometry, key, delta, ...args );
        });
      }

      return geometry;
    };
  };
}());

window.translateBoxVertices = transformBoxVertices( 'add' );
window.scaleBoxVertices = transformBoxVertices( 'multiply', new THREE.Vector3( 1, 1, 1 ) );
window.lerpBoxVertices = transformBoxVertices( 'lerp' );

// Per-axis THREE.BoxGeometry methods.
const transformAxisBoxVertices = (function() {
  'use strict';

  const vector = new THREE.Vector3();

  return ( method, identity = new THREE.Vector3() ) => {
    return axis => {
      function baseTransformAxis(
        geometry,
        key,
        delta = identity.getComponent( axis ),
        ...args
      ) {
        const indices = VertexIndices[ key.toUpperCase() ];

        if ( Array.isArray( indices ) ) {
          vector
            .copy( identity )
            .setComponent( axis, delta );

          indices.forEach( index =>
            geometry.vertices[ index ][ method ]( vector, ...args )
          );
        }

        return geometry;
      }

      return function transformAxis( geometry, vectors, ...args ) {
        if ( typeof vectors === 'string' ) {
          const delta = args.shift();
          return baseTransformAxis( geometry, vectors, delta, ...args );
        } else if ( typeof vectors === 'object' ) {
          Object.keys( vectors ).forEach( key => {
            const delta = vectors[ key ];
            baseTransformAxis( geometry, key, delta, ...args );
          });
        }

        return geometry;
      };
    };
  };
}());

const translateAxisBoxVertices = transformAxisBoxVertices( 'add' );

window.translateXBoxVertices = translateAxisBoxVertices( 0 );
window.translateYBoxVertices = translateAxisBoxVertices( 1 );
window.translateZBoxVertices = translateAxisBoxVertices( 2 );

const scaleAxisBoxVertices = transformAxisBoxVertices( 'multiply', new THREE.Vector3( 1, 1, 1 ) );

window.scaleXBoxVertices = scaleAxisBoxVertices( 0 );
window.scaleYBoxVertices = scaleAxisBoxVertices( 1 );
window.scaleZBoxVertices = scaleAxisBoxVertices( 2 );

// Call THREE.BoxGeometry methods directly.
function callBoxVertices( method ) {
  'use strict';

  function baseCall( geometry, key, ...args ) {
    const indices = VertexIndices[ key.toUpperCase() ];

    if ( Array.isArray( indices ) ) {
      indices.forEach( index =>
        geometry.vertices[ index ][ method ]( ...args )
      );
    }

    return geometry;
  }

  return function call( geometry, vectors, ...args ) {
    if ( typeof vectors === 'string' ) {
      return baseCall( geometry, vectors, ...args );
    } else if ( typeof vectors === 'object' ) {
      Object.keys( vectors ).forEach( key => {
        const value = vectors[ key ];
        baseCall( geometry, key, value, ...args );
      });
    }

    return geometry;
  };
}

window.setBoxVertices = callBoxVertices( 'set' );
window.setXBoxVertices = callBoxVertices( 'setX' );
window.setYBoxVertices = callBoxVertices( 'setY' );
window.setZBoxVertices = callBoxVertices( 'setZ' );
window.copyBoxVertices = callBoxVertices( 'copy' );

//  Get the first matching THREE.BoxGeometry vertex.
function getBoxVertex( geometry, key ) {
  'use strict';

  if ( key ) {
    const indices = VertexIndices[ key.toUpperCase() ];

    if ( Array.isArray( indices ) ) {
      return geometry.vertices[ indices[ 0 ] ];
    }
  }

  return geometry.vertices[ 0 ];
}

window.getBoxVertex = getBoxVertex;
<|endoftext|>


<commit_before>var walk = require('../../libs/directories').walk;
var lib = require('../../libs');
var expect = require('chai').expect;
var path = require('path');
var util = require('util');

module.exports = function () {
  this.Given('I have a Sass file', function (callback) {
    callback();
  });

  this.When('I run the program', function (callback) {
    expect(this.sassFilesDirectory).to.be.ok;
    var data = walk(this.sassFilesDirectory);
    this.output = lib(data);
    callback();
  });

  this.Given('the file has {arg1:stringInDoubleQuotes}', function (arg1, callback) {
    switch (arg1) {
    case 'mixins':
      this.sassFilesDirectory = path.join(__dirname, 'test_files', 'mixins_test_files');
      break;

    case 'fonts':
      this.sassFilesDirectory = path.join(__dirname, 'test_files', 'fonts_test_files');
      break;

    case 'colors':
      this.sassFilesDirectory = path.join(__dirname, 'test_files', 'colors_test_files');
      break;

    case 'variables':
      this.sassFilesDirectory = path.join(__dirname, 'test_files', 'variables_test_files');
      break;

    case 'functions':
      this.sassFilesDirectory = path.join(__dirname, 'test_files', 'functions_test_files');
      break;

    default:
      return callback(Error(arg1 + ' has no matching module'));
    }

    callback();
  });

  this.Then('I should see how many times the {arg1:stringInDoubleQuotes} are used',
  function (arg1, callback) {
    switch (arg1) {
    case 'colors':
      verifyColors(this.output);
      break;

    case 'fonts':
      verifyFonts(this.output);
      break;

    case 'mixins':
      verifyMixins(this.output);
      break;

    case 'functions':
      verifyFunctions(this.output);
      break;

    case 'variables':
      verifyVariables(this.output);
      break;

    default:
      return callback(new Error(arg1 + ' has no matching module!'));
    }

    callback();
  });
};

function verifyFunctions (output) {
  expect(typeof output).to.equal('object');
  expect(typeof output.funcs).to.equal('object');

  expect(output.funcs.foo).to.equal(1);
}

function verifyVariables (output) {
  expect(typeof output).to.equal('object');
  expect(typeof output.vars).to.equal('object');

  expect(output.vars.bar).to.equal(1);
  expect(output.vars.baz).to.equal(2);
}

function verifyMixins (output) {
  expect(typeof output).to.equal('object');
  expect(typeof output.mixins).to.equal('object');

  expect(output.mixins.foo).to.equal(2);
}

function verifyFonts (output) {
  expect(typeof output).to.equal('object');
  expect(typeof output.fonts).to.equal('object');

  expect(output.fonts.helvetica).to.equal(1);
  expect(output.fonts.serif).to.equal(1);
}

function verifyColors (output) {
  expect(typeof output).to.equal('object');
  expect(typeof output.colors).to.equal('object');

  expect(output.colors['#ffffff']).to.equal(3);
  expect(output.colors['white']).to.equal(1);
  expect(output.colors['#fff']).to.equal(1);
  expect(output.colors['#eee']).to.equal(1);
  expect(output.colors['orange']).to.equal(1);
  expect(output.colors['#000000']).to.equal(1);
}<commit_msg>refactor<commit_after>var walk = require('../../libs/directories').walk;
var lib = require('../../libs');
var expect = require('chai').expect;
var path = require('path');

module.exports = function () {
  this.Given('I have a Sass file', function (callback) {
    callback();
  });

  this.When('I run the program', function (callback) {
    expect(this.sassFilesDirectory).to.be.ok;
    var data = walk(this.sassFilesDirectory);
    this.output = lib(data);
    callback();
  });

  this.Given('the file has {arg1:stringInDoubleQuotes}', function (arg1, callback) {
    switch (arg1) {
    case 'mixins':
      this.sassFilesDirectory = path.join(__dirname, 'test_files', 'mixins_test_files');
      break;

    case 'fonts':
      this.sassFilesDirectory = path.join(__dirname, 'test_files', 'fonts_test_files');
      break;

    case 'colors':
      this.sassFilesDirectory = path.join(__dirname, 'test_files', 'colors_test_files');
      break;

    case 'variables':
      this.sassFilesDirectory = path.join(__dirname, 'test_files', 'variables_test_files');
      break;

    case 'functions':
      this.sassFilesDirectory = path.join(__dirname, 'test_files', 'functions_test_files');
      break;

    default:
      return callback(Error(arg1 + ' has no matching module'));
    }

    callback();
  });

  this.Then('I should see how many times the {arg1:stringInDoubleQuotes} are used',
  function (arg1, callback) {
    switch (arg1) {
    case 'colors':
      verifyColors(this.output);
      break;

    case 'fonts':
      verifyFonts(this.output);
      break;

    case 'mixins':
      verifyMixins(this.output);
      break;

    case 'functions':
      verifyFunctions(this.output);
      break;

    case 'variables':
      verifyVariables(this.output);
      break;

    default:
      return callback(new Error(arg1 + ' has no matching module!'));
    }

    callback();
  });
};

function verifyFunctions (output) {
  expect(typeof output).to.equal('object');
  expect(typeof output.funcs).to.equal('object');

  expect(output.funcs.foo).to.equal(1);
}

function verifyVariables (output) {
  expect(typeof output).to.equal('object');
  expect(typeof output.vars).to.equal('object');

  expect(output.vars.bar).to.equal(1);
  expect(output.vars.baz).to.equal(2);
}

function verifyMixins (output) {
  expect(typeof output).to.equal('object');
  expect(typeof output.mixins).to.equal('object');

  expect(output.mixins.foo).to.equal(2);
}

function verifyFonts (output) {
  expect(typeof output).to.equal('object');
  expect(typeof output.fonts).to.equal('object');

  expect(output.fonts.helvetica).to.equal(1);
  expect(output.fonts.serif).to.equal(1);
}

function verifyColors (output) {
  expect(typeof output).to.equal('object');
  expect(typeof output.colors).to.equal('object');

  expect(output.colors['#ffffff']).to.equal(3);
  expect(output.colors['white']).to.equal(1);
  expect(output.colors['#fff']).to.equal(1);
  expect(output.colors['#eee']).to.equal(1);
  expect(output.colors['orange']).to.equal(1);
  expect(output.colors['#000000']).to.equal(1);
}<|endoftext|>


<commit_before>(function() {
    // save these original methods before they are overwritten
    var proto_initIcon = L.Marker.prototype._initIcon;
    var proto_setPos = L.Marker.prototype._setPos;

    var oldIE = (L.DomUtil.TRANSFORM === 'msTransform');

    L.Marker.addInitHook(function () {
        var iconAnchor = this.options.icon.options.iconAnchor;
        if (iconAnchor) {
            iconAnchor = (iconAnchor[0] + 'px ' + iconAnchor[1] + 'px');
        }
        this.options.rotationOrigin = this.options.rotationOrigin || iconAnchor || 'center bottom' ;
        this.options.rotationAngle = this.options.rotationAngle || 0;
    });

    L.Marker.include({
        _initIcon: function() {
            proto_initIcon.call(this);
        },

        _setPos: function (pos) {
            proto_setPos.call(this, pos);

            if(this.options.rotationAngle) {
                this._icon.style[L.DomUtil.TRANSFORM+'Origin'] = this.options.rotationOrigin;

                if(oldIE) {
                    // for IE 9, use the 2D rotation
                    this._icon.style[L.DomUtil.TRANSFORM] = 'rotate(' + this.options.rotationAngle + 'deg)';
                } else {
                    // for modern browsers, prefer the 3D accelerated version
                    this._icon.style[L.DomUtil.TRANSFORM] += ' rotateZ(' + this.options.rotationAngle + 'deg)';
                }
            }
        },

        setRotationAngle: function(angle) {
            this.options.rotationAngle = angle;
            this.update();
            return this;
        },

        setRotationOrigin: function(origin) {
            this.options.rotationOrigin = origin;
            this.update();
            return this;
        }
    });
})();
<commit_msg>Check if icon is valid<commit_after>(function() {
    // save these original methods before they are overwritten
    var proto_initIcon = L.Marker.prototype._initIcon;
    var proto_setPos = L.Marker.prototype._setPos;

    var oldIE = (L.DomUtil.TRANSFORM === 'msTransform');

    L.Marker.addInitHook(function () {
        var iconOptions = this.options.icon && this.options.icon.options;
        var iconAnchor = iconOptions && this.options.icon.options.iconAnchor;
        if (iconAnchor) {
            iconAnchor = (iconAnchor[0] + 'px ' + iconAnchor[1] + 'px');
        }
        this.options.rotationOrigin = this.options.rotationOrigin || iconAnchor || 'center bottom' ;
        this.options.rotationAngle = this.options.rotationAngle || 0;
    });

    L.Marker.include({
        _initIcon: function() {
            proto_initIcon.call(this);
        },

        _setPos: function (pos) {
            proto_setPos.call(this, pos);

            if(this.options.rotationAngle) {
                this._icon.style[L.DomUtil.TRANSFORM+'Origin'] = this.options.rotationOrigin;

                if(oldIE) {
                    // for IE 9, use the 2D rotation
                    this._icon.style[L.DomUtil.TRANSFORM] = 'rotate(' + this.options.rotationAngle + 'deg)';
                } else {
                    // for modern browsers, prefer the 3D accelerated version
                    this._icon.style[L.DomUtil.TRANSFORM] += ' rotateZ(' + this.options.rotationAngle + 'deg)';
                }
            }
        },

        setRotationAngle: function(angle) {
            this.options.rotationAngle = angle;
            this.update();
            return this;
        },

        setRotationOrigin: function(origin) {
            this.options.rotationOrigin = origin;
            this.update();
            return this;
        }
    });
})();
<|endoftext|>


<commit_before>import databaseAPI from '../../databaseAPI';
import _ from 'lodash';

export const ADD_PHOTO = 'ADD_PHOTO';
export function addPhoto(file, selectedRoom) {
  return function(dispatch) {
    databaseAPI.uploadPhoto(file).then(function(snapshot) {
      var url = snapshot.metadata.downloadURLs[0];
      databaseAPI.updatePhotoURL(url, selectedRoom);
      dispatch({
        type: ADD_PHOTO,
        url,
        selectedRoom: selectedRoom,
      });
    });
  };
}

//adds room to the redux rooms state and makes database call along the way
export const ADD_ROOM = 'ADD_ROOM';
export function addRoom(details, ignoreDbCall) {
  const roomContents = {
    size: details && details.size,
    notes: details && details.notes,
  };

  if (!ignoreDbCall) {
    //database call sends room with a empty object to later store new furniture
    databaseAPI.addRoom(roomContents, details && details.roomName);
  }

  return {
    type: ADD_ROOM,
    roomName: details && details.roomName,
    contents: roomContents,
  };
}

export const UPDATE_ROOM_DETAILS = 'UPDATE_ROOM_DETAILS';
export function updateRoomDetails(oldRoomName, roomContents, newRoomDetails, ignoreDbCall) {
  const clonedRoom = _.cloneDeep(roomContents);
  const newRoomName = newRoomDetails.roomName;
  delete newRoomDetails.roomName;
  Object.assign(clonedRoom, newRoomDetails);

  if (!ignoreDbCall) {
    databaseAPI.updateRoom(oldRoomName, newRoomName, clonedRoom);
  }

  return {
    type: UPDATE_ROOM_DETAILS,
    oldRoomName,
    newRoomName,
    contents: clonedRoom,
  };
}

export const MAKE_PUBLIC_PRIVATE = 'MAKE_PUBLIC_PRIVATE';
export function makePublic_Private(newPublicStatus) {
  // Update the public status of the project in the database
  databaseAPI.toggleProjectPrivacy(newPublicStatus);

  return {
    type: MAKE_PUBLIC_PRIVATE,
    newPublicStatus,
  };
}

export const GET_COLOR = "GET_COLOR";
export function getColor(color, room) {
    databaseAPI.updateRoomColor(color, room);
  return {
    type: GET_COLOR,
    color,
    room
  }
}

export const SET_DESIGN = "SET_DESIGN";
export function setRoomDesign(design, room) {
  return {
    type: SET_DESIGN,
    design,
    room
  }
}

export const SELECT_ROOM = 'SELECT_ROOM';
export function selectRoom(roomName) {
  return {
    type: SELECT_ROOM,
    roomName,
  };
}

//initial pull from the database
export const GET_ROOMS = 'GET_ROOMS';
export function getRooms() {
  //database call with promise stored in rooms
  let rooms = databaseAPI.getRooms();

  return {
    type: GET_ROOMS,
    //promise passed as action.payload
    payload: rooms
  };
}

export const REMOVE_ROOM = 'REMOVE_ROOM';
export function removeRoom(title) {
  databaseAPI.removeRoom(title);
  return {
    type: REMOVE_ROOM,
    title,
  };
}
<commit_msg>refactor(add room): change add room action to give default values<commit_after>import databaseAPI from '../../databaseAPI';
import _ from 'lodash';

export const ADD_PHOTO = 'ADD_PHOTO';
export function addPhoto(file, selectedRoom) {
  return function(dispatch) {
    databaseAPI.uploadPhoto(file).then(function(snapshot) {
      var url = snapshot.metadata.downloadURLs[0];
      databaseAPI.updatePhotoURL(url, selectedRoom);
      dispatch({
        type: ADD_PHOTO,
        url,
        selectedRoom: selectedRoom,
      });
    });
  };
}

//adds room to the redux rooms state and makes database call along the way
export const ADD_ROOM = 'ADD_ROOM';
export function addRoom(details, ignoreDbCall) {

  const roomContents = {
    size: (details && details.size)|| false,
    notes: (details && details.notes)|| false,
  };

  if (!(ignoreDbCall === true)) {
    //database call sends room with a empty object to later store new furniture
    databaseAPI.addRoom(roomContents, details && details.roomName);
  }

  return {
    type: ADD_ROOM,
    roomName: details && details.roomName,
    contents: roomContents,
  };
}

export const UPDATE_ROOM_DETAILS = 'UPDATE_ROOM_DETAILS';
export function updateRoomDetails(oldRoomName, roomContents, newRoomDetails, ignoreDbCall) {
  const clonedRoom = _.cloneDeep(roomContents);
  const newRoomName = newRoomDetails.roomName;
  delete newRoomDetails.roomName;
  Object.assign(clonedRoom, newRoomDetails);

  if (!ignoreDbCall) {
    databaseAPI.updateRoom(oldRoomName, newRoomName, clonedRoom);
  }

  return {
    type: UPDATE_ROOM_DETAILS,
    oldRoomName,
    newRoomName,
    contents: clonedRoom,
  };
}

export const MAKE_PUBLIC_PRIVATE = 'MAKE_PUBLIC_PRIVATE';
export function makePublic_Private(newPublicStatus) {
  // Update the public status of the project in the database
  databaseAPI.toggleProjectPrivacy(newPublicStatus);

  return {
    type: MAKE_PUBLIC_PRIVATE,
    newPublicStatus,
  };
}

export const GET_COLOR = "GET_COLOR";
export function getColor(color, room) {
    databaseAPI.updateRoomColor(color, room);
  return {
    type: GET_COLOR,
    color,
    room
  }
}

export const SET_DESIGN = "SET_DESIGN";
export function setRoomDesign(design, room) {
  return {
    type: SET_DESIGN,
    design,
    room
  }
}

export const SELECT_ROOM = 'SELECT_ROOM';
export function selectRoom(roomName) {
  return {
    type: SELECT_ROOM,
    roomName,
  };
}

//initial pull from the database
export const GET_ROOMS = 'GET_ROOMS';
export function getRooms() {
  //database call with promise stored in rooms
  let rooms = databaseAPI.getRooms();

  return {
    type: GET_ROOMS,
    //promise passed as action.payload
    payload: rooms
  };
}

export const REMOVE_ROOM = 'REMOVE_ROOM';
export function removeRoom(title) {
  databaseAPI.removeRoom(title);
  return {
    type: REMOVE_ROOM,
    title,
  };
}
<|endoftext|>


<commit_before>// coding: utf-8

var i18n = {
  "lang": {
    "en": "English",
    "fr": "French",
    "de": "German",
    "es": "Spanish",
    "pl": "Polish",
    "ar": "Arabic",
  },
  "from": {
    "en": "From:",
    "fr": "De :",
    "de": "Von:",
    "es": "De :",
    "pl": "Od:",
    "ar": "من :",
  },
  "to": {
    "en": "To:",
    "fr": "Pour :",
    "de": "An:",
    "es": "Para :",
    "pl": "Do:",
    "ar": "إلى :",
  },
  "cc": {
    "en": "Cc:",
    "fr": "Cc :",
    "de": "Cc:",
    "es": "Cc :",
    "pl": "Cc:", // or "Do wiadomości"
    "ar": "Cc :",
  },
  "subject": {
    "en": "Subject:",
    "fr": "Objet :",
    "de": "Betreff:",
    "es": "Sujeto :",
    "pl": "Temat:",
    "ar": "الموضوع :",
  },
  "date": {
    "en": "Date:",
    "fr": "Date :",
    "de": "Datum:",
    "es": "Fecha :",
    "pl": "Data:",
    "ar": "التاريخ :",
  },
  "sent": {
    "en": "Sent:",
    "fr": "Envoyé :",
    "de": "Gesendet:",
    "es": "Enviado :",
    "pl": "Wysłane:",
    "ar": "المرسلة :",
  },
  "forwarded_message": {
    "en": "Forwarded Message",
    "fr": "Message transféré",
    "de": "Weitergeleitete Nachricht",
    "es": "Mensaje transferido",
    "pl": "Przekazana wiadomość",
    "ar": "اعادة التوجيه",
  },
  "original_message": {
    "en": "Original Message",
    "fr": "Message d'origine",
    "de": "Ursprüngliche Nachricht",
    "es": "Mensaje original",
    "pl": "Wiadomość oryginalna",
    "ar": "الرسالة الأصلية",
  },
};
<commit_msg>Add Japanese (jp) translations (#56)<commit_after>// coding: utf-8

var i18n = {
  "lang": {
    "en": "English",
    "fr": "French",
    "de": "German",
    "es": "Spanish",
    "jp": "Japanese",
    "pl": "Polish",
    "ar": "Arabic",
  },
  "from": {
    "en": "From:",
    "fr": "De :",
    "de": "Von:",
    "es": "De :",
    "jp": "送信者:",
    "pl": "Od:",
    "ar": "من :",
  },
  "to": {
    "en": "To:",
    "fr": "Pour :",
    "de": "An:",
    "es": "Para :",
    "jp": "宛先:",
    "pl": "Do:",
    "ar": "إلى :",
  },
  "cc": {
    "en": "Cc:",
    "fr": "Cc :",
    "de": "Cc:",
    "es": "Cc :",
    "jp": "Cc:",
    "pl": "Cc:", // or "Do wiadomości"
    "ar": "Cc :",
  },
  "subject": {
    "en": "Subject:",
    "fr": "Objet :",
    "de": "Betreff:",
    "es": "Sujeto :",
    "jp": "件名:",
    "pl": "Temat:",
    "ar": "الموضوع :",
  },
  "date": {
    "en": "Date:",
    "fr": "Date :",
    "de": "Datum:",
    "es": "Fecha :",
    "jp": "日時:",
    "pl": "Data:",
    "ar": "التاريخ :",
  },
  "sent": {
    "en": "Sent:",
    "fr": "Envoyé :",
    "de": "Gesendet:",
    "es": "Enviado :",
    "jp": "送信メール:",
    "pl": "Wysłane:",
    "ar": "المرسلة :",
  },
  "forwarded_message": {
    "en": "Forwarded Message",
    "fr": "Message transféré",
    "de": "Weitergeleitete Nachricht",
    "es": "Mensaje transferido",
    "jp": "転送メール",
    "pl": "Przekazana wiadomość",
    "ar": "اعادة التوجيه",
  },
  "original_message": {
    "en": "Original Message",
    "fr": "Message d'origine",
    "de": "Ursprüngliche Nachricht",
    "es": "Mensaje original",
    "jp": "元のメール",
    "pl": "Wiadomość oryginalna",
    "ar": "الرسالة الأصلية",
  },
};
<|endoftext|>


<commit_before>"use strict";
var VScroller = {
Core: {
  animate: null,
  calibrationBoundary: 150,
  maxCalibration: 1.6,
  minCalibration: 0.5,
  // high:  60f / 1000ms :  400ms / 24f # 600 / 28
  // low:   15f /  250ms :   33ms /  2f # 200 / 6
  maxInterval: 28,
  minDelay: 600,
  performScroll: function(el, di, amount) {
    var before;
    if (di) {
      if (el) {
        before = el.scrollTop;
        el.scrollTop += amount;
        return el.scrollTop !== before;
      } else {
        before = window.scrollY;
        window.scrollBy(0, amount);
        return window.scrollY !== before;
      }
    } else if (el) {
      before = el.scrollLeft;
      el.scrollLeft += amount;
      return el.scrollLeft !== before;
    } else {
      before = window.scrollX;
      window.scrollBy(amount, 0);
      return window.scrollX !== before;
    }
  },
  scroll: function(element, di, amount) {
    if (!amount) { return; }
    if (!VSettings.cache.smoothScroll) {
      this.performScroll(element, di, amount);
      VDom.isVisibile(VScroller.current) || (VScroller.current = element);
      return;
    }
    this.animate(amount, di, element);
  }
},

  current: null,
  top: null,
  keyIsDown: 0,
  scale: 1,
  Properties: ["clientWidth", "clientHeight", "scrollWidth", "scrollHeight", "scrollLeft", "scrollTop"],
  scrollBy: function(di, amount, factor) {
    if (VHints.tryNestedFrame("VScroller.scrollBy", arguments)) { return; }
    var element = this.findScrollable(this.getActivatedElement(), di, amount);
    amount = !factor ? this.adjustAmount(di, amount, element)
      : factor === 1 ? (amount > 0 ? Math.ceil : Math.floor)(amount)
      : amount * this.getDimension(element, di, factor === "max" ? 2 : 0);
    this.Core.scroll(element, di, amount);
    this.top = null;
  },
  scrollTo: function(di, amount, fromMax) {
    if (VHints.tryNestedFrame("VScroller.scrollTo", arguments)) { return; }
    var element = this.findScrollable(this.getActivatedElement(), di, fromMax ? 1 : -1);
    amount = this.adjustAmount(di, amount, element);
    amount = fromMax ? this.getDimension(element, di, 2) - amount : amount;
    amount -= element ? element[this.Properties[4 + di]] : di ? window.scrollY : window.scrollX;
    this.Core.scroll(element, di, amount);
    this.top = null;
  },
  adjustAmount: function(di, amount, element) {
    amount *= VSettings.cache.scrollStepSize;
    return amount && !di && element && element.scrollWidth <= element.scrollHeight * 2
      ? Math.ceil(amount * 0.6) : amount;
  },
  findScrollable: function(element, di, amount) {
    while (element !== this.top && !(this.scrollDo(element, di, amount) && this.shouldScroll(element, di))) {
      element = element.getDestinationInsertionPoints && element.getDestinationInsertionPoints()[0] ||
        element.parentElement || (element.parentNode instanceof ShadowRoot && element.parentNode.host) || this.top;
    }
    return element;
  },
  getActivatedElement: function() {
    var element = this.current;
    this.top = document.scrollingElement || document.body || document.documentElement;
    this.scale = Math.max(1, 1 / (window.devicePixelRatio || 1));
    if (element) { return element; }
    element = this.top;
    return this.current = element && (this.selectFirst(element) || element);
  },
  getDimension: function(el, di, index) {
    return el !== this.top || (index && el) ? (el || this.top)[this.Properties[index + di]]
      : di ? window.innerHeight : window.innerWidth;
  },
  scrollDo: function(element, di, amount) {
    amount = (amount > 0 ? 1 : -1) * this.scale;
    return this.Core.performScroll(element, di, amount) && this.Core.performScroll(element, di, -amount);
  },
  selectFirst: function(element) {
    if (this.scrollDo(element, 1, 1) || this.scrollDo(element, 1, 0)) {
      return element;
    }
    VDom.prepareCrop();
    var children = [], rect, _ref = element.children, _len = _ref.length;
    while (0 < _len--) {
      element = _ref[_len];
      if (rect = VDom.getVisibleClientRect(element)) {
        children.push([(rect[2] - rect[0]) * (rect[3] - rect[1]), element]);
      }
    }
    children.sort(this.sortBy0);
    for (_len = children.length; 0 < _len--; ) {
      if (element = this.selectFirst(children[_len][1])) { return element; }
    }
    return null;
  },
  scrollIntoView: function(el) {
    this.getActivatedElement();
    var rect = el.getClientRects()[0], amount, height, width, hasY, oldSmooth;
    if (!rect) { return; }
    height = window.innerHeight, width = window.innerWidth;
    amount = rect.bottom < 0 ? rect.bottom - Math.min(rect.height, height)
      : height < rect.top ? rect.top + Math.min(rect.height, height, 0) : 0;
    if (amount) {
      this.Core.scroll(this.findScrollable(el, 1, amount), 1, amount);
      VScroller.keyIsDown = 0;
    }
    hasY = amount;
    amount = rect.right < 0 ? rect.right - Math.min(rect.width, width)
      : width < rect.left ? rect.left + Math.min(rect.width - width, 0) : 0;
    if (!amount) { this.top = null; return; }
    oldSmooth = VSettings.cache.smoothScroll;
    VSettings.cache.smoothScroll = !hasY;
    el = this.findScrollable(el, 0, amount);
    this.Core.scroll(el, 0, amount);
    VSettings.cache.smoothScroll = oldSmooth;
    VScroller.keyIsDown = 0;
    this.top = null;
  },
  shouldScroll: function(element, di) {
    var st = window.getComputedStyle(element);
    return (di ? st.overflowY : st.overflowX) !== "hidden" && VDom.isStyleVisible(st);
  },
  isScrollable: function(el, di) {
    return this.scrollDo(el, di, +!(di ? el.scrollTop : el.scrollLeft)) && this.shouldScroll(el, di);
  },
  sortBy0: function(a, b) {
    return a[0] - b[0];
  }
};

VScroller.Core.animate = function () {
  var amount = 0, calibration = 1.0, di = 0, duration = 0, element = null, //
  sign = 0, timestamp = -1, totalDelta = 0, totalElapsed = 0.0, //
  animate = function(newTimestamp) {
    var int1 = timestamp, elapsed, continuous, _this;
    timestamp = newTimestamp;
    if (int1 === -1) {
      requestAnimationFrame(animate);
      return;
    }
    elapsed = newTimestamp - int1;
    int1 = (totalElapsed += elapsed);
    _this = VScroller.Core;
    if (continuous = VScroller.keyIsDown > 0) {
      if (int1 >= 75) {
        if (int1 > _this.minDelay) { --VScroller.keyIsDown; }
        int1 = calibration;
        if (_this.minCalibration <= int1 && int1 <= _this.maxCalibration) {
          int1 = _this.calibrationBoundary / amount / int1;
          calibration *= (int1 > 1.05) ? 1.05 : (int1 < 0.95) ? 0.95 : 1.0;
        }
      }
    }
    int1 = Math.ceil(amount * (elapsed / duration) * calibration);
    int1 = continuous ? int1 : Math.max(0, Math.min(int1, amount - totalDelta));
    if (int1 && _this.performScroll(element, di, sign * int1)) {
      totalDelta += int1;
      requestAnimationFrame(animate);
      return;
    }
    if (VScroller.current !== element) {
      VDom.isVisibile(VScroller.current) || (VScroller.current = element);
    }
    element = null;
  };
  this.animate = function(newAmount, newDi, newEl) {
    amount = Math.abs(newAmount); calibration = 1.0; di = newDi;
    duration = Math.max(100, 20 * Math.log(amount)); element = newEl;
    sign = newAmount === 0 ? 0 : newAmount < 0 ? -1 : 1;
    timestamp = -1; totalDelta = 0; totalElapsed = 0.0;
    var keyboard = VSettings.cache.keyboard;
    this.maxInterval = Math.round(keyboard[1] / 16.67) + 4;
    this.minDelay = (((keyboard[0] - keyboard[1]) / 30) | 0) * 30;
    VScroller.keyIsDown = this.maxInterval;
    requestAnimationFrame(animate);
  };
  this.animate.apply(this, arguments);
};
<commit_msg>noop: review and clean code<commit_after>"use strict";
var VScroller = {
Core: {
  animate: null,
  calibrationBoundary: 150,
  maxCalibration: 1.6,
  minCalibration: 0.5,
  // high:  60f / 1000ms :  400ms / 24f # 600 / 28
  // low:   15f /  250ms :   33ms /  2f # 200 / 6
  maxInterval: 28,
  minDelay: 600,
  performScroll: function(el, di, amount) {
    var before;
    if (di) {
      if (el) {
        before = el.scrollTop;
        el.scrollTop += amount;
        return el.scrollTop !== before;
      } else {
        before = window.scrollY;
        window.scrollBy(0, amount);
        return window.scrollY !== before;
      }
    } else if (el) {
      before = el.scrollLeft;
      el.scrollLeft += amount;
      return el.scrollLeft !== before;
    } else {
      before = window.scrollX;
      window.scrollBy(amount, 0);
      return window.scrollX !== before;
    }
  },
  scroll: function(element, di, amount) {
    if (!amount) { return; }
    if (VSettings.cache.smoothScroll) {
      this.animate(amount, di, element);
      return;
    }
    this.performScroll(element, di, amount);
    VScroller.checkCurrent(element);
  }
},

  current: null,
  top: null,
  keyIsDown: 0,
  scale: 1,
  Properties: ["clientWidth", "clientHeight", "scrollWidth", "scrollHeight", "scrollLeft", "scrollTop"],
  scrollBy: function(di, amount, factor) {
    if (VHints.tryNestedFrame("VScroller.scrollBy", arguments)) { return; }
    var element = this.findScrollable(this.getActivatedElement(), di, amount);
    amount = !factor ? this.adjustAmount(di, amount, element)
      : factor === 1 ? (amount > 0 ? Math.ceil : Math.floor)(amount)
      : amount * this.getDimension(element, di, factor === "max" ? 2 : 0);
    this.Core.scroll(element, di, amount);
    this.top = null;
  },
  scrollTo: function(di, amount, fromMax) {
    if (VHints.tryNestedFrame("VScroller.scrollTo", arguments)) { return; }
    var element = this.findScrollable(this.getActivatedElement(), di, fromMax ? 1 : -1);
    amount = this.adjustAmount(di, amount, element);
    fromMax && (amount = this.getDimension(element, di, 2) - amount);
    amount -= element ? element[this.Properties[4 + di]] : di ? window.scrollY : window.scrollX;
    this.Core.scroll(element, di, amount);
    this.top = null;
  },
  adjustAmount: function(di, amount, element) {
    amount *= VSettings.cache.scrollStepSize;
    return !di && amount && element && element.scrollWidth <= element.scrollHeight * 2
      ? Math.ceil(amount * 0.6) : amount;
  },
  findScrollable: function(element, di, amount) {
    while (element !== this.top && !(this.scrollDo(element, di, amount) && this.shouldScroll(element, di))) {
      element = element.getDestinationInsertionPoints && element.getDestinationInsertionPoints()[0] ||
        element.parentElement || (element.parentNode instanceof ShadowRoot && element.parentNode.host) || this.top;
    }
    return element;
  },
  getActivatedElement: function() {
    var element;
    this.top = document.scrollingElement || document.body || document.documentElement;
    this.scale = Math.max(1, 1 / (window.devicePixelRatio || 1));
    if (element = this.current) { return element; }
    element = this.top;
    return this.current = element && (this.selectFirst(element) || element);
  },
  checkCurrent: function(el) {
    this.current === el || VDom.isVisibile(this.current) || (this.current = el);
  },
  getDimension: function(el, di, index) {
    return el !== this.top || (index && el) ? (el || this.top)[this.Properties[index + di]]
      : di ? window.innerHeight : window.innerWidth;
  },
  scrollDo: function(element, di, amount) {
    amount = (amount > 0 ? 1 : -1) * this.scale;
    return this.Core.performScroll(element, di, amount) && this.Core.performScroll(element, di, -amount);
  },
  selectFirst: function(element) {
    if (this.scrollDo(element, 1, 1) || this.scrollDo(element, 1, 0)) {
      return element;
    }
    VDom.prepareCrop();
    var children = [], rect, _ref = element.children, _len = _ref.length;
    while (0 < _len--) {
      element = _ref[_len];
      if (rect = VDom.getVisibleClientRect(element)) {
        children.push([(rect[2] - rect[0]) * (rect[3] - rect[1]), element]);
      }
    }
    children.sort(this.sortBy0);
    for (_len = children.length; 0 < _len--; ) {
      if (element = this.selectFirst(children[_len][1])) { return element; }
    }
    return null;
  },
  scrollIntoView: function(el) {
    this.getActivatedElement();
    var rect = el.getClientRects()[0], amount, height, width, hasY, ref, oldSmooth;
    if (!rect) { return; }
    height = window.innerHeight, width = window.innerWidth;
    amount = rect.bottom < 0 ? rect.bottom - Math.min(rect.height, height)
      : height < rect.top ? rect.top + Math.min(rect.height, height, 0) : 0;
    if (hasY = amount) {
      this.Core.scroll(this.findScrollable(el, 1, amount), 1, amount);
      VScroller.keyIsDown = 0;
    }
    amount = rect.right < 0 ? rect.right - Math.min(rect.width, width)
      : width < rect.left ? rect.left + Math.min(rect.width - width, 0) : 0;
    if (amount) {
      ref = VSettings.cache;
      oldSmooth = ref.smoothScroll;
      ref.smoothScroll = !hasY;
      this.Core.scroll(this.findScrollable(el, 0, amount), 0, amount);
      ref.smoothScroll = oldSmooth;
      VScroller.keyIsDown = 0;
    }
    this.top = null;
  },
  shouldScroll: function(element, di) {
    var st = window.getComputedStyle(element);
    return (di ? st.overflowY : st.overflowX) !== "hidden" && VDom.isStyleVisible(st);
  },
  isScrollable: function(el, di) {
    return this.scrollDo(el, di, +!(di ? el.scrollTop : el.scrollLeft)) && this.shouldScroll(el, di);
  },
  sortBy0: function(a, b) {
    return a[0] - b[0];
  }
};

VScroller.Core.animate = function () {
  var amount = 0, calibration = 1.0, di = 0, duration = 0, element = null, //
  sign = 0, timestamp = -1.0, totalDelta = 0.0, totalElapsed = 0.0, //
  animate = function(newTimestamp) {
    var int1 = timestamp, elapsed, continuous, _this;
    timestamp = newTimestamp;
    if (int1 === -1) {
      requestAnimationFrame(animate);
      return;
    }
    elapsed = newTimestamp - int1;
    int1 = (totalElapsed += elapsed);
    _this = VScroller.Core;
    if (continuous = VScroller.keyIsDown > 0) {
      if (int1 >= 75) {
        if (int1 > _this.minDelay) { --VScroller.keyIsDown; }
        int1 = calibration;
        if (_this.minCalibration <= int1 && int1 <= _this.maxCalibration) {
          int1 = _this.calibrationBoundary / amount / int1;
          calibration *= (int1 > 1.05) ? 1.05 : (int1 < 0.95) ? 0.95 : 1.0;
        }
      }
    }
    int1 = Math.ceil(amount * (elapsed / duration) * calibration);
    continuous || (int1 = Math.min(int1, amount - totalDelta));
    if (int1 > 0 && _this.performScroll(element, di, sign * int1)) {
      totalDelta += int1;
      requestAnimationFrame(animate);
      return;
    }
    VScroller.checkCurrent(element);
    element = null;
  };
  this.animate = function(newAmount, newDi, newEl) {
    amount = Math.abs(newAmount); calibration = 1.0; di = newDi;
    duration = Math.max(100, 20 * Math.log(amount)); element = newEl;
    sign = newAmount < 0 ? -1 : 1;
    timestamp = -1.0; totalDelta = totalElapsed = 0.0;
    var keyboard = VSettings.cache.keyboard;
    this.maxInterval = Math.round(keyboard[1] / 16.67) + 4;
    this.minDelay = (((keyboard[0] - keyboard[1]) / 30) | 0) * 30;
    VScroller.keyIsDown = this.maxInterval;
    requestAnimationFrame(animate);
  };
  this.animate.apply(this, arguments);
};
<|endoftext|>


<commit_before>;(function($$){

    /**
    * @brief :  default layout options
    */
    var defaults = {
	ready     : function(){},
	stop      : function(){},
	numIter   : 10,
	refresh   : 1,     // TODO: Change it to 0
	fit       : true,
	randomize : false
    };

    /**
     * @brief       : constructor
     * @arg options : object containing layout options
     */
    function CoseLayout(options){
	this.options = $$.util.extend(true, {}, defaults, options);
    }

    /**
     * @brief     : Creates an object which is contains all the data
                    used in the layout process
     * @arg cy    : cytoscape.js object
     * @return    : layoutInfo object initialized
     */
    function createLayoutInfo(cy) {
	var layoutInfo   = {
	    layoutNodes  : [],
	    idToIndex    : {},
	    nodeSize     : cy.nodes().size(),
	    graphSet     : [],
	    indexToGraph : [],
	    layoutEdges  : [],
	    edgeSize     : cy.edges().size()
	};

	// Shortcut
	var nodes = cy.nodes();

	// Iterate over all nodes, creating layout nodes
	for (var i = 0; i < layoutInfo.nodeSize; i++) {
	    var tempNode        = {};
	    tempNode.id         = nodes[i].data('id');
	    tempNode.parentId   = nodes[i].data('parent');
	    tempNode.children   = [];
	    tempNode.positionX  = nodes[i].position('x');
	    tempNode.positionY  = nodes[i].position('y');
	    tempNode.offsetX    = 0;
	    tempNode.offsetY    = 0;
	    // Add new node
	    layoutInfo.layoutNodes.push(tempNode);
	    // Add entry to id-index map
	    layoutInfo.idToIndex[tempNode.id] = i;
	}

	// Inline implementation of a queue, used for traversing the graph in BFS order
	var queue = [];
	var start = 0;   // Points to the start the queue
	var end   = -1;  // Points to the end of the queue

	var tempGraph = [];

	// Second pass to add child information and
	// initialize queue for hierarchical traversal
	for (var i = 0; i < layoutInfo.nodeSize; i++) {
	    var n = layoutInfo.layoutNodes[i];
	    var p_id = n.parentId;
	    // Check if node n has a parent node
	    if (undefined != p_id) {
		// Add node Id to parent's list of children
		layoutInfo.layoutNodes[layoutInfo.idToIndex[p_id]].children.push(n.id);
	    } else {
		// If a node doesn't have a parent, then it's in the root graph
		queue[++end] = n.id;
		tempGraph.push(n.id);

	    }
	}

	// Add root graph to graphSet
	layoutInfo.graphSet.push(tempGraph);

	// Traverse the graph, level by level,
	while (start <= end) {
	    // Get the node to visit and remove it from queue
	    var node_id  = queue[start++];
	    var node_ix  = layoutInfo.idToIndex[node_id];
	    var node     = layoutInfo.layoutNodes[node_ix];
	    var children = node.children;
	    if (children.length > 0) {
		// Add children nodes as a new graph to graph set
		layoutInfo.graphSet.push(children);
		// Add children to que queue to be visited
		for (var i = 0; i < children.length; i++) {
		    queue[++end] = children[i];
		}
	    }
	}

	// Create indexToGraph map
	for (var i = 0; i < layoutInfo.graphSet.length; i++) {
	    var graph = layoutInfo.graphSet[i];
	    for (var j = 0; j < graph.length; j++) {
		var index = layoutInfo.idToIndex[graph[j]];
		layoutInfo.indexToGraph[index] = i;
	    }
	}

	// Shortcut
	var edges = cy.edges();

	// Iterate over all edges, creating Layout Edges
	for (var i = 0; i < layoutInfo.edgeSize; i++) {
	    var e = edges[i];
	    var tempEdge = {};
	    tempEdge.id       = e.data('id');
	    tempEdge.sourceId = e.data('source');
	    tempEdge.targetId = e.data('target');
	    var weigth = e.data('weigth');
	    if (undefined != weigth) {
		tempEdge.weigth = weigth;
	    } else {
		tempEdge.weigth = 1; // TODO: Define an option for default weigth
	    }
	    layoutInfo.layoutEdges.push(tempEdge);
	}

	// Finally, return layoutInfo object
	return layoutInfo;
    }

    /**
     * @brief: printsLayoutInfo into js console
     *         Only used for debbuging
     */
    function printLayoutInfo(layoutInfo) {
	console.debug("layoutNodes:");
	for (var i = 0; i < layoutInfo.nodeSize; i++) {
	    var n = layoutInfo.layoutNodes[i];
	    var s =
		"\nindex: "     + i +
		"\nId: "        + n.id +
		"\nChildren: "  + n.children.toString() +
		"\nparentId: "  + n.parentId  +
		"\npositionX: " + n.positionX +
		"\npositionY: " + n.positionY;
	    console.debug(s);
	}

	console.debug("idToIndex");
	for (var i in layoutInfo.idToIndex) {
	    console.debug("Id: " + i + "\nIndex: " + layoutInfo.idToIndex[i]);
	}

	console.debug("Graph Set");
	var set = layoutInfo.graphSet;
	for (var i = 0; i < set.length; i ++) {
	    console.debug("Set : " + i + ": " + set[i].toString());
	}

	var s = "IndexToGraph";
	for (var i = 0; i < layoutInfo.indexToGraph.length; i ++) {
	    s += "\nIndex : " + i + " Graph: "+ layoutInfo.indexToGraph[i]
	}
	console.debug(s);

	s = "Layout Edges";
	for (var i = 0; i < layoutInfo.layoutEdges.length; i++) {
	    var e = layoutInfo.layoutEdges[i];
	    s += "\nEdge Index: " + i + " ID: " + e.id +
		" SouceID: " + e.sourceId + " TargetId: " + e.targetId +
		" Weigth: " + e.weigth;
	}
	console.debug(s);

	return;
    }

    /**
     * @brief          : Updates the positions
     * @arg layoutInfo : LayoutInfo object
     * @arg cy         : Cytoscape object
     * @arg options    : Layout options
     */
    function updatePositions(layoutInfo, cy, options) {
	var container = cy.container();
	var width     = container.clientWidth;
	var height    = container.clientHeight;

	cy.nodes().positions(function(i, ele){
	    lnode = layoutInfo.layoutNodes[layoutInfo.idToIndex[ele.data('id')]];
	    return {
		x: lnode.positionX,
		y: lnode.positionY
	    };
	});

	if (true != updatePositions.ready) {
	    updatePositions.ready = true;
	    cy.one("layoutready", options.ready);
	    cy.trigger("layoutready");
	}
    }

    /**
     * @brief :
     */
    randomizePositions(layoutInfo, cy) {

    }

    /**
     * @brief :
     */
    calculateNodeForces(layoutInfo, cy, options) {

    }

    /**
     * @brief :
     */
    calculateEdgeForces(layoutInfo, cy, options) {

    }

    /**
     * @brief :
     */
    calculateGravityForces(layoutInfo, cy, options) {

    }

    /**
     * @brief          : Performs one iteration of the physical simulation
     * @arg layoutInfo : LayoutInfo object already initialized
     * @arg cy         : Cytoscape object
     * @arg options    : Layout options
     */
    function step(layoutInfo, cy, options) {
	// Calculate node repulsions
	calculateNodeForces(layoutInfo, cy, options);
	// Calculate edge forces
	calculateEdgeForces(layoutInfo, cy, options);
	// Calculate gravity forces
	calculateGravityForces(layoutInfo, cy, options);
    }

    /**
     * @brief : runs the layout
     */
    CoseLayout.prototype.run = function(){
	var options = this.options;
	var cy      = options.cy;

	// Initialize layout info
	var layoutInfo = createLayoutInfo(cy);

	// Only for debbuging - TODO: Remove before release
	printLayoutInfo(layoutInfo);

	// If required, randomize node positions
	if (true == options.randomize) {
	    randomizePositions(layoutInfo, cy);
	}

	// Main loop
	for (var i = 0; i < options.numIter; i++) {
	    // Do one step in the phisical simmulation
	    step(layoutInfo, cy, options);

	    // If required, update positions
	    if (0 < options.refresh &&
		0 == i % options.refresh) {
		updatePositions(layoutInfo, cy, options);
	    }

	    // ONLY FOR DEBUGIGNG! TODO: Remove before release
// 	    var delay       = 1;
// 	    var now         = new Date();
// 	    var desiredTime = new Date().setSeconds(now.getSeconds() + delay);
// 	    while (now < desiredTime) {
// 		now = new Date();
// 	    }

	}

	updatePositions(layoutInfo, cy, options);

	// Fit the graph
	if (true == options.fit) {
	    cy.fit();
	}

	// Layout has finished
	cy.one("layoutstop", options.stop);
	cy.trigger("layoutstop");
    };

    /**
     * @brief : called on continuous layouts to stop them before they finish
     */
    CoseLayout.prototype.stop = function(){
	var options = this.options;

	cy.one("layoutstop", options.stop);
	cy.trigger("layoutstop");
    };

    // register the layout
    $$("layout", "cose", CoseLayout);

})(cytoscape);<commit_msg>Implemented step(), calculateNodeForces, randomizePositions()<commit_after>;(function($$){

    /**
     * @brief :  default layout options
     */
    var defaults = {
	ready     : function(){},
	stop      : function(){},
	numIter   : 10,
	refresh   : 1,     // TODO: Change it to 0
	fit       : true,
	randomize : false
    };

    /**
     * @brief       : constructor
     * @arg options : object containing layout options
     */
    function CoseLayout(options){
	this.options = $$.util.extend(true, {}, defaults, options);
    }

    /**
     * @brief     : Creates an object which is contains all the data
     *              used in the layout process
     * @arg cy    : cytoscape.js object
     * @return    : layoutInfo object initialized
     */
    function createLayoutInfo(cy) {
	var layoutInfo   = {
	    layoutNodes  : [],
	    idToIndex    : {},
	    nodeSize     : cy.nodes().size(),
	    graphSet     : [],
	    indexToGraph : [],
	    layoutEdges  : [],
	    edgeSize     : cy.edges().size()
	};

	// Shortcut
	var nodes = cy.nodes();

	// Iterate over all nodes, creating layout nodes
	for (var i = 0; i < layoutInfo.nodeSize; i++) {
	    var tempNode        = {};
	    tempNode.id         = nodes[i].data('id');
	    tempNode.parentId   = nodes[i].data('parent');
	    tempNode.children   = [];
	    tempNode.positionX  = nodes[i].position('x');
	    tempNode.positionY  = nodes[i].position('y');
	    tempNode.offsetX    = 0;
	    tempNode.offsetY    = 0;
	    // Add new node
	    layoutInfo.layoutNodes.push(tempNode);
	    // Add entry to id-index map
	    layoutInfo.idToIndex[tempNode.id] = i;
	}

	// Inline implementation of a queue, used for traversing the graph in BFS order
	var queue = [];
	var start = 0;   // Points to the start the queue
	var end   = -1;  // Points to the end of the queue

	var tempGraph = [];

	// Second pass to add child information and
	// initialize queue for hierarchical traversal
	for (var i = 0; i < layoutInfo.nodeSize; i++) {
	    var n = layoutInfo.layoutNodes[i];
	    var p_id = n.parentId;
	    // Check if node n has a parent node
	    if (undefined != p_id) {
		// Add node Id to parent's list of children
		layoutInfo.layoutNodes[layoutInfo.idToIndex[p_id]].children.push(n.id);
	    } else {
		// If a node doesn't have a parent, then it's in the root graph
		queue[++end] = n.id;
		tempGraph.push(n.id);

	    }
	}

	// Add root graph to graphSet
	layoutInfo.graphSet.push(tempGraph);

	// Traverse the graph, level by level,
	while (start <= end) {
	    // Get the node to visit and remove it from queue
	    var node_id  = queue[start++];
	    var node_ix  = layoutInfo.idToIndex[node_id];
	    var node     = layoutInfo.layoutNodes[node_ix];
	    var children = node.children;
	    if (children.length > 0) {
		// Add children nodes as a new graph to graph set
		layoutInfo.graphSet.push(children);
		// Add children to que queue to be visited
		for (var i = 0; i < children.length; i++) {
		    queue[++end] = children[i];
		}
	    }
	}

	// Create indexToGraph map
	for (var i = 0; i < layoutInfo.graphSet.length; i++) {
	    var graph = layoutInfo.graphSet[i];
	    for (var j = 0; j < graph.length; j++) {
		var index = layoutInfo.idToIndex[graph[j]];
		layoutInfo.indexToGraph[index] = i;
	    }
	}

	// Shortcut
	var edges = cy.edges();

	// Iterate over all edges, creating Layout Edges
	for (var i = 0; i < layoutInfo.edgeSize; i++) {
	    var e = edges[i];
	    var tempEdge = {};
	    tempEdge.id       = e.data('id');
	    tempEdge.sourceId = e.data('source');
	    tempEdge.targetId = e.data('target');
	    var weigth = e.data('weigth');
	    if (undefined != weigth) {
		tempEdge.weigth = weigth;
	    } else {
		tempEdge.weigth = 1; // TODO: Define an option for default weigth
	    }
	    layoutInfo.layoutEdges.push(tempEdge);
	}

	// Finally, return layoutInfo object
	return layoutInfo;
    }

    /**
     * @brief: printsLayoutInfo into js console
     *         Only used for debbuging
     */
    function printLayoutInfo(layoutInfo) {
	console.debug("layoutNodes:");
	for (var i = 0; i < layoutInfo.nodeSize; i++) {
	    var n = layoutInfo.layoutNodes[i];
	    var s =
		"\nindex: "     + i +
		"\nId: "        + n.id +
		"\nChildren: "  + n.children.toString() +
		"\nparentId: "  + n.parentId  +
		"\npositionX: " + n.positionX +
		"\npositionY: " + n.positionY;
	    console.debug(s);
	}

	console.debug("idToIndex");
	for (var i in layoutInfo.idToIndex) {
	    console.debug("Id: " + i + "\nIndex: " + layoutInfo.idToIndex[i]);
	}

	console.debug("Graph Set");
	var set = layoutInfo.graphSet;
	for (var i = 0; i < set.length; i ++) {
	    console.debug("Set : " + i + ": " + set[i].toString());
	}

	var s = "IndexToGraph";
	for (var i = 0; i < layoutInfo.indexToGraph.length; i ++) {
	    s += "\nIndex : " + i + " Graph: "+ layoutInfo.indexToGraph[i];
	}
	console.debug(s);

	s = "Layout Edges";
	for (var i = 0; i < layoutInfo.layoutEdges.length; i++) {
	    var e = layoutInfo.layoutEdges[i];
	    s += "\nEdge Index: " + i + " ID: " + e.id +
		" SouceID: " + e.sourceId + " TargetId: " + e.targetId +
		" Weigth: " + e.weigth;
	}
	console.debug(s);

	return;
    }

    /**
     * @brief          : Updates the positions
     * @arg layoutInfo : LayoutInfo object
     * @arg cy         : Cytoscape object
     * @arg options    : Layout options
     */
    function refreshPositions(layoutInfo, cy, options) {
	var container = cy.container();
	var width     = container.clientWidth;
	var height    = container.clientHeight;

	cy.nodes().positions(function(i, ele) {
	    lnode = layoutInfo.layoutNodes[layoutInfo.idToIndex[ele.data('id')]];
	    return {
		x: lnode.positionX,
		y: lnode.positionY
	    };
	});

	if (true != refreshPositions.ready) {
	    refreshPositions.ready = true;
	    cy.one("layoutready", options.ready);
	    cy.trigger("layoutready");
	}
    }

    /**
     * @brief :
     */
    function randomizePositions(layoutInfo, cy) {
	var container = cy.container();
	var width     = container.clientWidth;
	var height    = container.clientHeight;

	for (var i = 0; i < layoutInfo.nodeSize; i++) {
	    var n = layoutInfo.layoutNodes[i];
	    n.positionX = Math.round(Math.random() * width);
	    n.positionY = Math.round(Math.random() * height);
	}
    }

    /**
     * @brief :
     */
    function calculateNodeForces(layoutInfo, cy, options) {
	// Go through each of the graphs in graphSet
	// Nodes only repel each other if they belong to the same graph
	for (var i = 0; i < layoutInfo.graphSet.length; i ++) {
	    var graph    = layoutInfo.graphSet[i];
	    var numNodes = graph.length;
	    // Now get all the pairs of nodes
	    // Only get each pair once, (A, B) = (B, A)
	    for (var j = 0; i < numNodes; j++) {
		var node1 = graph[j];
		for (var k = j + 1; k < numNodes; k++) {
		    var node2 = graph[k];
		    nodeRepulsion(node1, node2, layoutInfo, cy, options);
		}
	    }
	}
    }

    /**
     * @brief :
     */
    function calculateEdgeForces(layoutInfo, cy, options) {
	return;
    }

    /**
     * @brief :
     */
    function calculateGravityForces(layoutInfo, cy, options) {
	return;
    }

    /**
     * @brief :
     */
    function nodeRepulsion(node1, node2, layoutInfo, cy, options) {
	return;
    }

    /**
     * @brief :
     */
    function updatePositions(layoutInfo, cy, options) {
	return;
    }

    /**
     * @brief          : Performs one iteration of the physical simulation
     * @arg layoutInfo : LayoutInfo object already initialized
     * @arg cy         : Cytoscape object
     * @arg options    : Layout options
     */
    function step(layoutInfo, cy, options) {
	// Calculate node repulsions
	calculateNodeForces(layoutInfo, cy, options);
	// Calculate edge forces
	calculateEdgeForces(layoutInfo, cy, options);
	// Calculate gravity forces
	calculateGravityForces(layoutInfo, cy, options);
	// Update positions based on calculated forces
	updatePositions(layoutInfo, cy, options);
    }

    /**
     * @brief : runs the layout
     */
    CoseLayout.prototype.run = function(){
	var options = this.options;
	var cy      = options.cy;

	// Initialize layout info
	var layoutInfo = createLayoutInfo(cy);

	// Only for debbuging - TODO: Remove before release
	printLayoutInfo(layoutInfo);

	// If required, randomize node positions
	if (true == options.randomize) {
	    randomizePositions(layoutInfo, cy);
	}

	// Main loop
	for (var i = 0; i < options.numIter; i++) {
	    // Do one step in the phisical simmulation
	    step(layoutInfo, cy, options);

	    // If required, update positions
	    if (0 < options.refresh && 0 == (i % options.refresh)) {
		refreshPositions(layoutInfo, cy, options);
	    }

	    // ONLY FOR DEBUGIGNG! TODO: Remove before release
	    // 	    var delay       = 1;
	    // 	    var now         = new Date();
	    // 	    var desiredTime = new Date().setSeconds(now.getSeconds() + delay);
	    // 	    while (now < desiredTime) {
	    // 		now = new Date();
	    // 	    }

	}

	refreshPositions(layoutInfo, cy, options);

	// Fit the graph if necessary
	if (true == options.fit) {
	    cy.fit();
	}

	// Layout has finished
	cy.one("layoutstop", options.stop);
	cy.trigger("layoutstop");
    };

    /**
     * @brief : called on continuous layouts to stop them before they finish
     */
    CoseLayout.prototype.stop = function(){
	var options = this.options;

	cy.one("layoutstop", options.stop);
	cy.trigger("layoutstop");
    };

    // register the layout
    $$("layout", "cose", CoseLayout);

})(cytoscape);<|endoftext|>


<commit_before>/*
 *
 * Content
 *
 */

import React from 'react';
import { connect } from 'react-redux';
import styles from './styles.scss';
import { createSelector } from 'reselect';
import { selectPlugins } from 'containers/App/selectors';

export class Content extends React.Component { // eslint-disable-line react/prefer-stateless-function
  render() {
    let plugin;

    // Detect plugin according to params
    this.props.plugins.map(p => {
      if (this.props.params.plugin === p.id) {
        plugin = p;
      }
    });

    let content;
    if (!plugin) {
      content =
Unknown plugin.

    } else {
      const Elem = plugin.mainComponent;
      content = <Elem plugin={plugin}></Elem>;
    }

    return (

          Welcome! You successfully loaded the admin panel.

        {content}

    );
  }
}

Content.propTypes = {
  plugins: React.PropTypes.object,
  onRegisterPluginClicked: React.PropTypes.func,
};

const mapStateToProps = createSelector(
  selectPlugins(),
  (plugins) => ({ plugins })
);

function mapDispatchToProps(dispatch) {
  return {
    dispatch,
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Content);
<commit_msg>Remove welcome message<commit_after>/*
 *
 * Content
 *
 */

import React from 'react';
import { connect } from 'react-redux';
import styles from './styles.scss';
import { createSelector } from 'reselect';
import { selectPlugins } from 'containers/App/selectors';

export class Content extends React.Component { // eslint-disable-line react/prefer-stateless-function
  render() {
    let plugin;

    // Detect plugin according to params
    this.props.plugins.map(p => {
      if (this.props.params.plugin === p.id) {
        plugin = p;
      }
    });

    let content;
    if (!plugin) {
      content =
Unknown plugin.

    } else {
      const Elem = plugin.mainComponent;
      content = <Elem plugin={plugin}></Elem>;
    }

    return (

        {content}

    );
  }
}

Content.propTypes = {
  plugins: React.PropTypes.object,
  onRegisterPluginClicked: React.PropTypes.func,
};

const mapStateToProps = createSelector(
  selectPlugins(),
  (plugins) => ({ plugins })
);

function mapDispatchToProps(dispatch) {
  return {
    dispatch,
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Content);
<|endoftext|>


<commit_before>angular.module('app').service('IdentityService', ['$http', 'HostFactory', function($http, HostFactory)
	var baseUrl = HostFactory.serverName ;

	IdentityService.getCurrentUser = function(token){
				return "";
	}

	}]);<commit_msg> Creating IdentityService but i need know if the way that i call the api is correct<commit_after>angular.module('app').service('IdentityService', ['$http', 'HostFactory', function($http, HostFactory)
	var baseUrl = HostFactory.serverName ;

	IdentityService.getCurrentUser = function(token)
				return  return $http.get(baseUrl + '/api/User',token);
	}

	}]);<|endoftext|>


<commit_before>"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require("@angular/core");
var SelectionRelayService = (function () {
    function SelectionRelayService() {
        this.setAll = new core_1.EventEmitter();
        this.deleteSelected = new core_1.EventEmitter();
    }
    SelectionRelayService.prototype.sendSetAll = function (value) {
        console.log("selecting all");
        this.setAll.emit(value);
    };
    SelectionRelayService.prototype.sendDeleteSelected = function () {
        this.deleteSelected.emit(true);
    };
    return SelectionRelayService;
}());
exports.SelectionRelayService = SelectionRelayService;
var SelectionRelayComponent = (function () {
    function SelectionRelayComponent(broadcast) {
        var _this = this;
        this.broadcast = broadcast;
        this.selected = false;
        this.selectedChange = new core_1.EventEmitter();
        this.deleteSelected = this.broadcast.deleteSelected;
        broadcast.setAll.subscribe(function (b) {
            _this.selected = b;
            _this.selectedChange.emit(b);
        });
    }
    __decorate([
        core_1.Input(),
        __metadata('design:type', Boolean)
    ], SelectionRelayComponent.prototype, "selected", void 0);
    __decorate([
        core_1.Output(),
        __metadata('design:type', core_1.EventEmitter)
    ], SelectionRelayComponent.prototype, "selectedChange", void 0);
    __decorate([
        core_1.Output(),
        __metadata('design:type', core_1.EventEmitter)
    ], SelectionRelayComponent.prototype, "deleteSelected", void 0);
    SelectionRelayComponent = __decorate([
        core_1.Component({
            selector: "selection-relay",
            template: '<div *ngIf="false">relay: {{selected}}</div>'
        }),
        __metadata('design:paramtypes', [SelectionRelayService])
    ], SelectionRelayComponent);
    return SelectionRelayComponent;
}());
exports.SelectionRelayComponent = SelectionRelayComponent;
//# sourceMappingURL=selection.component.js.map<commit_msg>removed js files<commit_after><|endoftext|>