<commit_before>/*global define*/
define([
        '../Core/BoundingSphere',
        '../Core/defaultValue',
        '../Core/defined',
        '../Core/defineProperties',
        '../Core/destroyObject',
        '../Core/DeveloperError',
        '../Core/EventHelper',
        '../Scene/GroundPrimitive',
        './BillboardVisualizer',
        './BoundingSphereState',
        './BoxGeometryUpdater',
        './CorridorGeometryUpdater',
        './CustomDataSource',
        './CylinderGeometryUpdater',
        './EllipseGeometryUpdater',
        './EllipsoidGeometryUpdater',
        './GeometryVisualizer',
        './LabelVisualizer',
        './ModelVisualizer',
        './PathVisualizer',
        './PointVisualizer',
        './PolygonGeometryUpdater',
        './PolylineGeometryUpdater',
        './PolylineVolumeGeometryUpdater',
        './RectangleGeometryUpdater',
        './WallGeometryUpdater'
    ], function(
        BoundingSphere,
        defaultValue,
        defined,
        defineProperties,
        destroyObject,
        DeveloperError,
        EventHelper,
        GroundPrimitive,
        BillboardVisualizer,
        BoundingSphereState,
        BoxGeometryUpdater,
        CorridorGeometryUpdater,
        CustomDataSource,
        CylinderGeometryUpdater,
        EllipseGeometryUpdater,
        EllipsoidGeometryUpdater,
        GeometryVisualizer,
        LabelVisualizer,
        ModelVisualizer,
        PathVisualizer,
        PointVisualizer,
        PolygonGeometryUpdater,
        PolylineGeometryUpdater,
        PolylineVolumeGeometryUpdater,
        RectangleGeometryUpdater,
        WallGeometryUpdater) {
    'use strict';

    /**
     * Visualizes a collection of {@link DataSource} instances.
     * @alias DataSourceDisplay
     * @constructor
     *
     * @param {Object} options Object with the following properties:
     * @param {Scene} options.scene The scene in which to display the data.
     * @param {DataSourceCollection} options.dataSourceCollection The data sources to display.
     * @param {DataSourceDisplay~VisualizersCallback} [options.visualizersCallback=DataSourceDisplay.defaultVisualizersCallback]
     *        A function which creates an array of visualizers used for visualization.
     *        If undefined, all standard visualizers are used.
     */
    function DataSourceDisplay(options) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(options)) {
            throw new DeveloperError('options is required.');
        }
        if (!defined(options.scene)) {
            throw new DeveloperError('scene is required.');
        }
        if (!defined(options.dataSourceCollection)) {
            throw new DeveloperError('dataSourceCollection is required.');
        }
        //>>includeEnd('debug');

        GroundPrimitive.initializeTerrainHeights();

        var scene = options.scene;
        var dataSourceCollection = options.dataSourceCollection;

        this._eventHelper = new EventHelper();
        this._eventHelper.add(dataSourceCollection.dataSourceAdded, this._onDataSourceAdded, this);
        this._eventHelper.add(dataSourceCollection.dataSourceRemoved, this._onDataSourceRemoved, this);

        this._dataSourceCollection = dataSourceCollection;
        this._scene = scene;
        this._visualizersCallback = defaultValue(options.visualizersCallback, DataSourceDisplay.defaultVisualizersCallback);

        for (var i = 0, len = dataSourceCollection.length; i < len; i++) {
            this._onDataSourceAdded(dataSourceCollection, dataSourceCollection.get(i));
        }

        var defaultDataSource = new CustomDataSource();
        this._onDataSourceAdded(undefined, defaultDataSource);
        this._defaultDataSource = defaultDataSource;

        this._ready = false;
    }

    /**
     * Gets or sets the default function which creates an array of visualizers used for visualization.
     * By default, this function uses all standard visualizers.
     *
     * @member
     * @type {DataSourceDisplay~VisualizersCallback}
     */
    DataSourceDisplay.defaultVisualizersCallback = function(scene, entityCluster, dataSource) {
        var entities = dataSource.entities;
        return [new BillboardVisualizer(entityCluster, entities),
                new GeometryVisualizer(BoxGeometryUpdater, scene, entities),
                new GeometryVisualizer(CylinderGeometryUpdater, scene, entities),
                new GeometryVisualizer(CorridorGeometryUpdater, scene, entities),
                new GeometryVisualizer(EllipseGeometryUpdater, scene, entities),
                new GeometryVisualizer(EllipsoidGeometryUpdater, scene, entities),
                new GeometryVisualizer(PolygonGeometryUpdater, scene, entities),
                new GeometryVisualizer(PolylineGeometryUpdater, scene, entities),
                new GeometryVisualizer(PolylineVolumeGeometryUpdater, scene, entities),
                new GeometryVisualizer(RectangleGeometryUpdater, scene, entities),
                new GeometryVisualizer(WallGeometryUpdater, scene, entities),
                new LabelVisualizer(entityCluster, entities),
                new ModelVisualizer(scene, entities),
                new PointVisualizer(entityCluster, entities),
                new PathVisualizer(scene, entities)];
    };

    defineProperties(DataSourceDisplay.prototype, {
        /**
         * Gets the scene associated with this display.
         * @memberof DataSourceDisplay.prototype
         * @type {Scene}
         */
        scene : {
            get : function() {
                return this._scene;
            }
        },
        /**
         * Gets the collection of data sources to display.
         * @memberof DataSourceDisplay.prototype
         * @type {DataSourceCollection}
         */
        dataSources : {
            get : function() {
                return this._dataSourceCollection;
            }
        },
        /**
         * Gets the default data source instance which can be used to
         * manually create and visualize entities not tied to
         * a specific data source. This instance is always available
         * and does not appear in the list dataSources collection.
         * @memberof DataSourceDisplay.prototype
         * @type {CustomDataSource}
         */
        defaultDataSource : {
            get : function() {
                return this._defaultDataSource;
            }
        },

        /**
         * Gets a value indicating whether or not all entities in the data source are ready
         * @memberof DataSourceDisplay.prototype
         * @type {Boolean}
         * @readonly
         */
        ready : {
            get : function() {
                return this._ready;
            }
        }
    });

    /**
     * Returns true if this object was destroyed; otherwise, false.
     *

     * If this object was destroyed, it should not be used; calling any function other than
     * isDestroyed will result in a {@link DeveloperError} exception.
     *
     * @returns {Boolean} True if this object was destroyed; otherwise, false.
     *
     * @see DataSourceDisplay#destroy
     */
    DataSourceDisplay.prototype.isDestroyed = function() {
        return false;
    };

    /**
     * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
     * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
     *

     * Once an object is destroyed, it should not be used; calling any function other than
     * isDestroyed will result in a {@link DeveloperError} exception.  Therefore,
     * assign the return value (undefined) to the object as done in the example.
     *
     * @returns {undefined}
     *
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     *
     * @example
     * dataSourceDisplay = dataSourceDisplay.destroy();
     *
     * @see DataSourceDisplay#isDestroyed
     */
    DataSourceDisplay.prototype.destroy = function() {
        this._eventHelper.removeAll();

        var dataSourceCollection = this._dataSourceCollection;
        for (var i = 0, length = dataSourceCollection.length; i < length; ++i) {
            this._onDataSourceRemoved(this._dataSourceCollection, dataSourceCollection.get(i));
        }
        this._onDataSourceRemoved(undefined, this._defaultDataSource);

        return destroyObject(this);
    };

    /**
     * Updates the display to the provided time.
     *
     * @param {JulianDate} time The simulation time.
     * @returns {Boolean} True if all data sources are ready to be displayed, false otherwise.
     */
    DataSourceDisplay.prototype.update = function(time) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(time)) {
            throw new DeveloperError('time is required.');
        }
        //>>includeEnd('debug');

        if (!GroundPrimitive._initialized) {
            this._ready = false;
            return false;
        }

        var result = true;

        var i;
        var x;
        var visualizers;
        var vLength;
        var dataSources = this._dataSourceCollection;
        var length = dataSources.length;
        for (i = 0; i < length; i++) {
            var dataSource = dataSources.get(i);
            if (defined(dataSource.update)) {
                result = dataSource.update(time) && result;
            }

            visualizers = dataSource._visualizers;
            vLength = visualizers.length;
            for (x = 0; x < vLength; x++) {
                result = visualizers[x].update(time) && result;
            }
        }

        visualizers = this._defaultDataSource._visualizers;
        vLength = visualizers.length;
        for (x = 0; x < vLength; x++) {
            result = visualizers[x].update(time) && result;
        }

        this._ready = result;

        return result;
    };

    var getBoundingSphereArrayScratch = [];
    var getBoundingSphereBoundingSphereScratch = new BoundingSphere();

    /**
     * Computes a bounding sphere which encloses the visualization produced for the specified entity.
     * The bounding sphere is in the fixed frame of the scene's globe.
     *
     * @param {Entity} entity The entity whose bounding sphere to compute.
     * @param {Boolean} allowPartial If true, pending bounding spheres are ignored and an answer will be returned from the currently available data.
     *                               If false, the the function will halt and return pending if any of the bounding spheres are pending.
     * @param {BoundingSphere} result The bounding sphere onto which to store the result.
     * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
     *                       BoundingSphereState.PENDING if the result is still being computed, or
     *                       BoundingSphereState.FAILED if the entity has no visualization in the current scene.
     * @private
     */
    DataSourceDisplay.prototype.getBoundingSphere = function(entity, allowPartial, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(entity)) {
            throw new DeveloperError('entity is required.');
        }
        if (!defined(allowPartial)) {
            throw new DeveloperError('allowPartial is required.');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required.');
        }
        //>>includeEnd('debug');

        if (!this._ready) {
            return BoundingSphereState.PENDING;
        }

        var i;
        var length;
        var dataSource = this._defaultDataSource;
        if (!dataSource.entities.contains(entity)) {
            dataSource = undefined;

            var dataSources = this._dataSourceCollection;
            length = dataSources.length;
            for (i = 0; i < length; i++) {
                var d = dataSources.get(i);
                if (d.entities.contains(entity)) {
                    dataSource = d;
                    break;
                }
            }
        }

        if (!defined(dataSource)) {
            return BoundingSphereState.FAILED;
        }

        var boundingSpheres = getBoundingSphereArrayScratch;
        var tmp = getBoundingSphereBoundingSphereScratch;

        var count = 0;
        var state = BoundingSphereState.DONE;
        var visualizers = dataSource._visualizers;
        var visualizersLength = visualizers.length;

        for (i = 0; i < visualizersLength; i++) {
            var visualizer = visualizers[i];
            if (defined(visualizer.getBoundingSphere)) {
                state = visualizers[i].getBoundingSphere(entity, tmp);
                if (!allowPartial && state === BoundingSphereState.PENDING) {
                    return BoundingSphereState.PENDING;
                } else if (state === BoundingSphereState.DONE) {
                    boundingSpheres[count] = BoundingSphere.clone(tmp, boundingSpheres[count]);
                    count++;
                }
            }
        }

        if (count === 0) {
            return BoundingSphereState.FAILED;
        }

        boundingSpheres.length = count;
        BoundingSphere.fromBoundingSpheres(boundingSpheres, result);
        return BoundingSphereState.DONE;
    };

    DataSourceDisplay.prototype._onDataSourceAdded = function(dataSourceCollection, dataSource) {
        var scene = this._scene;

        var entityCluster = dataSource.clustering;
        entityCluster._initialize(scene);

        scene.primitives.add(entityCluster);

        dataSource._visualizers = this._visualizersCallback(scene, entityCluster, dataSource);
    };

    DataSourceDisplay.prototype._onDataSourceRemoved = function(dataSourceCollection, dataSource) {
        var scene = this._scene;
        var entityCluster = dataSource.clustering;
        scene.primitives.remove(entityCluster);

        var visualizers = dataSource._visualizers;
        var length = visualizers.length;
        for (var i = 0; i < length; i++) {
            visualizers[i].destroy();
        }

        dataSource._visualizers = undefined;
    };

    /**
     * A function which creates an array of visualizers used for visualization.
     * @callback DataSourceDisplay~VisualizersCallback
     *
     * @param {Scene} scene The scene to create visualizers for.
     * @param {DataSource} dataSource The data source to create visualizers for.
     * @returns {Visualizer[]} An array of visualizers used for visualization.
     *
     * @example
     * function createVisualizers(scene, dataSource) {
     *     return [new Cesium.BillboardVisualizer(scene, dataSource.entities)];
     * }
     */

    return DataSourceDisplay;
});
<commit_msg>DeveloperError(s) replaced with Check(s) in DataSourceDisplay<commit_after>/*global define*/
define([
        '../Core/BoundingSphere',
        '../Core/Check',
        '../Core/defaultValue',
        '../Core/defined',
        '../Core/defineProperties',
        '../Core/destroyObject',
        '../Core/DeveloperError',
        '../Core/EventHelper',
        '../Scene/GroundPrimitive',
        './BillboardVisualizer',
        './BoundingSphereState',
        './BoxGeometryUpdater',
        './CorridorGeometryUpdater',
        './CustomDataSource',
        './CylinderGeometryUpdater',
        './EllipseGeometryUpdater',
        './EllipsoidGeometryUpdater',
        './GeometryVisualizer',
        './LabelVisualizer',
        './ModelVisualizer',
        './PathVisualizer',
        './PointVisualizer',
        './PolygonGeometryUpdater',
        './PolylineGeometryUpdater',
        './PolylineVolumeGeometryUpdater',
        './RectangleGeometryUpdater',
        './WallGeometryUpdater'
    ], function(
        BoundingSphere,
        Check,
        defaultValue,
        defined,
        defineProperties,
        destroyObject,
        DeveloperError,
        EventHelper,
        GroundPrimitive,
        BillboardVisualizer,
        BoundingSphereState,
        BoxGeometryUpdater,
        CorridorGeometryUpdater,
        CustomDataSource,
        CylinderGeometryUpdater,
        EllipseGeometryUpdater,
        EllipsoidGeometryUpdater,
        GeometryVisualizer,
        LabelVisualizer,
        ModelVisualizer,
        PathVisualizer,
        PointVisualizer,
        PolygonGeometryUpdater,
        PolylineGeometryUpdater,
        PolylineVolumeGeometryUpdater,
        RectangleGeometryUpdater,
        WallGeometryUpdater) {
    'use strict';

    /**
     * Visualizes a collection of {@link DataSource} instances.
     * @alias DataSourceDisplay
     * @constructor
     *
     * @param {Object} options Object with the following properties:
     * @param {Scene} options.scene The scene in which to display the data.
     * @param {DataSourceCollection} options.dataSourceCollection The data sources to display.
     * @param {DataSourceDisplay~VisualizersCallback} [options.visualizersCallback=DataSourceDisplay.defaultVisualizersCallback]
     *        A function which creates an array of visualizers used for visualization.
     *        If undefined, all standard visualizers are used.
     */
    function DataSourceDisplay(options) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.object('options', options);
        Check.typeOf.object('options.scene', options.scene);
        Check.typeOf.object('options.dataSourceCollection', options.dataSourceCollection);
        //>>includeEnd('debug');

        GroundPrimitive.initializeTerrainHeights();

        var scene = options.scene;
        var dataSourceCollection = options.dataSourceCollection;

        this._eventHelper = new EventHelper();
        this._eventHelper.add(dataSourceCollection.dataSourceAdded, this._onDataSourceAdded, this);
        this._eventHelper.add(dataSourceCollection.dataSourceRemoved, this._onDataSourceRemoved, this);

        this._dataSourceCollection = dataSourceCollection;
        this._scene = scene;
        this._visualizersCallback = defaultValue(options.visualizersCallback, DataSourceDisplay.defaultVisualizersCallback);

        for (var i = 0, len = dataSourceCollection.length; i < len; i++) {
            this._onDataSourceAdded(dataSourceCollection, dataSourceCollection.get(i));
        }

        var defaultDataSource = new CustomDataSource();
        this._onDataSourceAdded(undefined, defaultDataSource);
        this._defaultDataSource = defaultDataSource;

        this._ready = false;
    }

    /**
     * Gets or sets the default function which creates an array of visualizers used for visualization.
     * By default, this function uses all standard visualizers.
     *
     * @member
     * @type {DataSourceDisplay~VisualizersCallback}
     */
    DataSourceDisplay.defaultVisualizersCallback = function(scene, entityCluster, dataSource) {
        var entities = dataSource.entities;
        return [new BillboardVisualizer(entityCluster, entities),
                new GeometryVisualizer(BoxGeometryUpdater, scene, entities),
                new GeometryVisualizer(CylinderGeometryUpdater, scene, entities),
                new GeometryVisualizer(CorridorGeometryUpdater, scene, entities),
                new GeometryVisualizer(EllipseGeometryUpdater, scene, entities),
                new GeometryVisualizer(EllipsoidGeometryUpdater, scene, entities),
                new GeometryVisualizer(PolygonGeometryUpdater, scene, entities),
                new GeometryVisualizer(PolylineGeometryUpdater, scene, entities),
                new GeometryVisualizer(PolylineVolumeGeometryUpdater, scene, entities),
                new GeometryVisualizer(RectangleGeometryUpdater, scene, entities),
                new GeometryVisualizer(WallGeometryUpdater, scene, entities),
                new LabelVisualizer(entityCluster, entities),
                new ModelVisualizer(scene, entities),
                new PointVisualizer(entityCluster, entities),
                new PathVisualizer(scene, entities)];
    };

    defineProperties(DataSourceDisplay.prototype, {
        /**
         * Gets the scene associated with this display.
         * @memberof DataSourceDisplay.prototype
         * @type {Scene}
         */
        scene : {
            get : function() {
                return this._scene;
            }
        },
        /**
         * Gets the collection of data sources to display.
         * @memberof DataSourceDisplay.prototype
         * @type {DataSourceCollection}
         */
        dataSources : {
            get : function() {
                return this._dataSourceCollection;
            }
        },
        /**
         * Gets the default data source instance which can be used to
         * manually create and visualize entities not tied to
         * a specific data source. This instance is always available
         * and does not appear in the list dataSources collection.
         * @memberof DataSourceDisplay.prototype
         * @type {CustomDataSource}
         */
        defaultDataSource : {
            get : function() {
                return this._defaultDataSource;
            }
        },

        /**
         * Gets a value indicating whether or not all entities in the data source are ready
         * @memberof DataSourceDisplay.prototype
         * @type {Boolean}
         * @readonly
         */
        ready : {
            get : function() {
                return this._ready;
            }
        }
    });

    /**
     * Returns true if this object was destroyed; otherwise, false.
     *

     * If this object was destroyed, it should not be used; calling any function other than
     * isDestroyed will result in a {@link DeveloperError} exception.
     *
     * @returns {Boolean} True if this object was destroyed; otherwise, false.
     *
     * @see DataSourceDisplay#destroy
     */
    DataSourceDisplay.prototype.isDestroyed = function() {
        return false;
    };

    /**
     * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
     * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
     *

     * Once an object is destroyed, it should not be used; calling any function other than
     * isDestroyed will result in a {@link DeveloperError} exception.  Therefore,
     * assign the return value (undefined) to the object as done in the example.
     *
     * @returns {undefined}
     *
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     *
     * @example
     * dataSourceDisplay = dataSourceDisplay.destroy();
     *
     * @see DataSourceDisplay#isDestroyed
     */
    DataSourceDisplay.prototype.destroy = function() {
        this._eventHelper.removeAll();

        var dataSourceCollection = this._dataSourceCollection;
        for (var i = 0, length = dataSourceCollection.length; i < length; ++i) {
            this._onDataSourceRemoved(this._dataSourceCollection, dataSourceCollection.get(i));
        }
        this._onDataSourceRemoved(undefined, this._defaultDataSource);

        return destroyObject(this);
    };

    /**
     * Updates the display to the provided time.
     *
     * @param {JulianDate} time The simulation time.
     * @returns {Boolean} True if all data sources are ready to be displayed, false otherwise.
     */
    DataSourceDisplay.prototype.update = function(time) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(time)) {
            throw new DeveloperError('time is required.');
        }
        //>>includeEnd('debug');

        if (!GroundPrimitive._initialized) {
            this._ready = false;
            return false;
        }

        var result = true;

        var i;
        var x;
        var visualizers;
        var vLength;
        var dataSources = this._dataSourceCollection;
        var length = dataSources.length;
        for (i = 0; i < length; i++) {
            var dataSource = dataSources.get(i);
            if (defined(dataSource.update)) {
                result = dataSource.update(time) && result;
            }

            visualizers = dataSource._visualizers;
            vLength = visualizers.length;
            for (x = 0; x < vLength; x++) {
                result = visualizers[x].update(time) && result;
            }
        }

        visualizers = this._defaultDataSource._visualizers;
        vLength = visualizers.length;
        for (x = 0; x < vLength; x++) {
            result = visualizers[x].update(time) && result;
        }

        this._ready = result;

        return result;
    };

    var getBoundingSphereArrayScratch = [];
    var getBoundingSphereBoundingSphereScratch = new BoundingSphere();

    /**
     * Computes a bounding sphere which encloses the visualization produced for the specified entity.
     * The bounding sphere is in the fixed frame of the scene's globe.
     *
     * @param {Entity} entity The entity whose bounding sphere to compute.
     * @param {Boolean} allowPartial If true, pending bounding spheres are ignored and an answer will be returned from the currently available data.
     *                               If false, the the function will halt and return pending if any of the bounding spheres are pending.
     * @param {BoundingSphere} result The bounding sphere onto which to store the result.
     * @returns {BoundingSphereState} BoundingSphereState.DONE if the result contains the bounding sphere,
     *                       BoundingSphereState.PENDING if the result is still being computed, or
     *                       BoundingSphereState.FAILED if the entity has no visualization in the current scene.
     * @private
     */
    DataSourceDisplay.prototype.getBoundingSphere = function(entity, allowPartial, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(entity)) {
            throw new DeveloperError('entity is required.');
        }
        if (!defined(allowPartial)) {
            throw new DeveloperError('allowPartial is required.');
        }
        if (!defined(result)) {
            throw new DeveloperError('result is required.');
        }
        //>>includeEnd('debug');

        if (!this._ready) {
            return BoundingSphereState.PENDING;
        }

        var i;
        var length;
        var dataSource = this._defaultDataSource;
        if (!dataSource.entities.contains(entity)) {
            dataSource = undefined;

            var dataSources = this._dataSourceCollection;
            length = dataSources.length;
            for (i = 0; i < length; i++) {
                var d = dataSources.get(i);
                if (d.entities.contains(entity)) {
                    dataSource = d;
                    break;
                }
            }
        }

        if (!defined(dataSource)) {
            return BoundingSphereState.FAILED;
        }

        var boundingSpheres = getBoundingSphereArrayScratch;
        var tmp = getBoundingSphereBoundingSphereScratch;

        var count = 0;
        var state = BoundingSphereState.DONE;
        var visualizers = dataSource._visualizers;
        var visualizersLength = visualizers.length;

        for (i = 0; i < visualizersLength; i++) {
            var visualizer = visualizers[i];
            if (defined(visualizer.getBoundingSphere)) {
                state = visualizers[i].getBoundingSphere(entity, tmp);
                if (!allowPartial && state === BoundingSphereState.PENDING) {
                    return BoundingSphereState.PENDING;
                } else if (state === BoundingSphereState.DONE) {
                    boundingSpheres[count] = BoundingSphere.clone(tmp, boundingSpheres[count]);
                    count++;
                }
            }
        }

        if (count === 0) {
            return BoundingSphereState.FAILED;
        }

        boundingSpheres.length = count;
        BoundingSphere.fromBoundingSpheres(boundingSpheres, result);
        return BoundingSphereState.DONE;
    };

    DataSourceDisplay.prototype._onDataSourceAdded = function(dataSourceCollection, dataSource) {
        var scene = this._scene;

        var entityCluster = dataSource.clustering;
        entityCluster._initialize(scene);

        scene.primitives.add(entityCluster);

        dataSource._visualizers = this._visualizersCallback(scene, entityCluster, dataSource);
    };

    DataSourceDisplay.prototype._onDataSourceRemoved = function(dataSourceCollection, dataSource) {
        var scene = this._scene;
        var entityCluster = dataSource.clustering;
        scene.primitives.remove(entityCluster);

        var visualizers = dataSource._visualizers;
        var length = visualizers.length;
        for (var i = 0; i < length; i++) {
            visualizers[i].destroy();
        }

        dataSource._visualizers = undefined;
    };

    /**
     * A function which creates an array of visualizers used for visualization.
     * @callback DataSourceDisplay~VisualizersCallback
     *
     * @param {Scene} scene The scene to create visualizers for.
     * @param {DataSource} dataSource The data source to create visualizers for.
     * @returns {Visualizer[]} An array of visualizers used for visualization.
     *
     * @example
     * function createVisualizers(scene, dataSource) {
     *     return [new Cesium.BillboardVisualizer(scene, dataSource.entities)];
     * }
     */

    return DataSourceDisplay;
});
<|endoftext|>


<commit_before>'use strict';
const Trait = require('traits.js');

const globalStates = new Map();

const getState = (key) => {
    return globalStates.get(key);
}

const setState = (key, value) => {
    globalStates.set(key, value);
}

const basePrototype = () => {
    return {};
}

const targets = new WeakMap();

// I dont know if I should use let or const for this.. I'll see implications
// later!!!
const TBase = Trait({ filter: Trait.required });

const TAllow = Trait.compose(TBase, Trait({
    filter: function (tar, prop, rec, args) {
        return this.allowedProperties.indexOf(prop) !== -1
    }
}));

const TParamAt = Trait.compose(TBase, Trait({

    idxParam: Trait.required,
    otherParam: Trait.required,
    operatorFn: Trait.required,

    filter: function (tar, prop, rec, args, opType) {
        //Policy NOT! applicable for property reads!!!
        if (opType === 'readProperty') {
            return true;
        }
        /**
         * document.createElement(stringOf(fakeDiv))
         * apply(p,t,args){
         *  if(policy.filter(...)) should change args to the desired type-value in the policy and use it subsequently
         *  return p.apply(t,args)
         * }
         */
        let newVal = this.idxParam(args);
        return this.operatorFn(newVal, this.otherParam);
    }
}));

/**
 * This function is used to prevent abusing toString and valueOf (we should look at other functions like that)
 * example of usage: ParamAt(equals, getVType(0,String), 'iframe')
 * Be sure that the type parameter returns a primitive object (string, number,...)
 */

const getVType = (idx, type) => {
    return (array) => {
        let val = type(array[idx]);
        array[idx] = val;
        return val;
    }
}

const ParamAt = (fn, idx, other) => {
    var paramPrototype = basePrototype();

    paramPrototype.operatorFn = fn;
    paramPrototype.idxParam = idx;
    paramPrototype.otherParam = other;

    return Trait.create(paramPrototype, TParamAt);
}

const TStateOverParams = Trait.compose(TBase, Trait({

    stateKey: Trait.required,
    operatorFn: Trait.required,
    otherParam: Trait.required,

    filter: function () { //TODO check the parameters...
        var obj = getState(this.stateKey);
        var res = this.operatorFn(obj, this.otherParam);
        return res;
    }
}));

const StateFnParam = (fn, key, param) => {

    var stateParamPrototype = basePrototype()

    stateParamPrototype.stateKey = key;
    stateParamPrototype.operatorFn = fn;
    stateParamPrototype.otherParam = param;

    return Trait.create(stateParamPrototype, TStateOverParams);
}

const And = function (...policies) {
    return Trait.create(basePrototype(), Trait.compose(TBase, Trait({
        filter: function (tar, prop, rec, args) {
            for (var policy of policies) {
                if (!policy.filter(tar, prop, rec, args)) {
                    return false;
                }
            }
            return true;
        }
    })))
}

const Not = function (p1) {

    return Trait.create(basePrototype(), Trait.compose(TBase, Trait({
        filter: function (tar, prop, rec, args) {
            return !p1.filter(tar, prop, rec, args);
        }
    })));
}

const Or = function (...policies) {
    return Trait.create(basePrototype(), Trait.compose(TBase, Trait({
        filter: function (tar, prop, rec, args) {
            // se puede mejorar empleando los operadores de JS
            for (var policy of policies) {
                if (policy.filter(tar, prop, rec, args)) {
                    return true;
                }
            }
            return false;
        }
    })))
}

 const Allow = function (properties) {
    var proto = basePrototype();
    proto.allowedProperties = properties;
    var allowedPropPolicy = Trait.create(proto, TAllow);
    return allowedPropPolicy;
}

//Combined Policies

const Deny = function (properties) {
    return Not(Allow(properties))
}

const ParamInList = function (idx, list) {
    return ParamAt((y, xs) => {
        xs.indexOf(y) !== -1
    }, idx, list);
}

const findPropertyOwner = function (obj, prop) {
    do {
        if (obj.hasOwnProperty(prop)) {
            return obj;
        }
    } while (obj = Object.getPrototypeOf(obj));
}

const isBuiltin = function (obj) {
    if (global['window']) {
        return ((obj == window) || (obj == document) || (obj == location) || (obj == navigator) || (obj == navigator.geolocation) && obj) //continue!!
    }
    return false;
}

const installPolicy = (policy) => {

    let notify = (listeners, target, method, receiver, arglist) => {
        if (listeners) {
            for (let listener of listeners) {
                listener.notify(target, method, receiver, arglist)
            }
        }
    }

    return {
        on: function (target) {
            // !!!!!!!!!!!   iterar una sola vez cuando funcione las polizas en la
            // properties !!!!!!!!!!!!!!!...
            let methods = [];
            let properties = [];

            if (isBuiltin(target)) {
                for (let key in target) {
                    let data = target[key];
                    if (data instanceof Function) {
                        methods.push(key);
                    } else if (data) {
                        properties.push(key);
                    }
                }
                //still work todo here
                /* for (let x of properties) {
                    let owner = findPropertyOwner(target, x);
                    if (owner) {
                        var pd = Reflect.getOwnPropertyDescriptor(owner, x);
                        if (pd.configurable && pd.set && !pd.value) {
                            var m = Reflect.defineProperty(target, x, {
                                get: () => {
                                    return target.x;
                                },
                                set: (value) => {
                                    target.x = value
                                }
                            })
                        }
                    }
                }*/

                //proxy on methods
                for (let method of methods) {
                    let fnProxy = new Proxy(target[method], {
                        apply: function (targetFn, thisArg, arglist) {
                            //enforcing
                            if (policy['whenRead']) {
                                for (let pol of policy['whenRead']) {
                                    if (!pol.filter(target, method, undefined, arglist, 'call')) {
                                        throw new Error('[' + method + '] Not allowed!');
                                    }
                                }
                            }
                            //updating listeners
                            notify(policy['readListeners'], target, method, undefined, arglist);
                            return targetFn.apply(thisArg, arglist);
                        }
                    });

                    fnProxy.toString = Function
                        .prototype
                        .toString
                        .bind(target[method]) //Proxies invariants flaws!!!!

                    Object.defineProperty(target, method, {
                        configurable: false,
                        writable: false,
                        value: fnProxy
                    })
                   // target[method] = fnProxy;
                }

                return target;

            } else {
                // console.log('no es built in!!'); install the policy in not builtin objects.
                return new Proxy(target, {
                    get: function (tar, property, receiver) {
                        if (tar[property] instanceof Function) {
                            return function (...args) {
                                if (policy['whenRead']) {
                                    for (let pol of policy['whenRead']) {
                                        if (!pol.filter(tar, property, receiver, args, 'call')) {
                                            throw new Error('Read of [' + property + '] is not allowed!');
                                        }
                                    }
                                }
                                notify(policy['readListeners'], tar, property, undefined, args);
                                return tar[property](...args)
                            }
                        } else {

                            if (policy['whenRead']) {
                                for (let pol of policy['whenRead']) {
                                    if (!pol.filter(tar, property, receiver, 'propertyRead')) {
                                        throw new Error('Read of [' + property + '] is not allowed!');
                                    }
                                }
                            }
                            notify(policy['readListeners'], tar, property, undefined, undefined);
                            return Reflect.get(tar, property, receiver);
                        }
                    },
                    set: function (target, property, value, receiver) {
                        if (policy['whenWrite']) {
                            for (let pol of policy['whenWrite']) {
                                if (!pol.filter(target, property, receiver, value, 'call')) {
                                    throw new Error('Write to [' + property + '] is not allowed!');
                                }
                            }
                        }
                        notify(policy['writeListeners'], target, property, undefined, value);
                        return Reflect.set(target, property, value, receiver);
                    }
                });
            }
        },
        onAll: function (targets) {
            for (let item of targets) {
                console.log('target: ' + item);
                this.on(item);
            }
        }
    }
}

var installPolicyCons = function (policy, targetFn) {
    if (targetFn instanceof Function) {
        var proxy = new Proxy(targetFn, {
            construct: function (target, params, newTarget) {
                let image = Reflect.construct(target, params, newTarget);
                image = installPolicy(policy).on(image);
                return image;
            }
        });
        return proxy;
    } else {
        throw new Error('Target must be a contructor!');
    }
}

/**
 * This function is intended to be used for external enforcement mechanisms. The idea is that
 * the provided mechanism call it with the runtime information and guardia should take care of
 * determining the permissions.
 *
 * @param {Object | Function} tar
 * @param {String} prop
 * @param {Object} rec
 * @param {*} args
 * @param {String} hook
 */

const enforce = (tar, prop, rec, args, hook) => {
    if (targets.has(tar)) { // if we already have registered a secured object
        var pols = Array.from(targets.get(tar))
        for (var pol of pols) {
            for (var rpol of pol[hook]) {
                if (!rpol.filter(tar, prop, rec, args))
                    return false;
            }
        }
    }
    return true;
}

const install = (pol, tar) => {
    if (targets.has(tar)) {
        var x = targets.get(tar)
        x.add(pol);
        targets.set(tar, x);
    } else {
        var t = new Set()
        t.add(pol)
        targets.set(tar, t);
    }
}

/**
 * for installing policies on functions
 * pd should { listeners : [] , execPol: []}
 */
const installOnFunction = (pd, fn) => {
    if (tgt instanceof Function) {
        let fnProxy = new Proxy(fn, {
            apply: function (target, thisArg, argumentsList) {
                if (pd.enforce(target, thisArg, argumentsList)) {
                    throw new Error('Not Allowed');
                }
                return Reflect.apply(target, thisArg, argumentsList);
            }
        });
        return fnProxy;
    }
    throw new Error('Not a function');
}

exports.installPolicy = installPolicy;
exports.installPolicyCons = installPolicyCons;
exports.Allow = Allow;
exports.Deny = Deny;
exports.And = And;
exports.Or = Or;
exports.Not = Not;
exports.ParamInList = ParamInList;
exports.ParamAt = ParamAt;
exports.StateFnParam = StateFnParam;
exports.setState = setState;
exports.getState = getState;
exports.getVType = getVType;

//this needs to be tested yet
exports.enforce = enforce;
exports.installOn = install;
<commit_msg>Minnor changes<commit_after>'use strict';
const Trait = require('traits.js');

const globalStates = new Map();

const getState = (key) => {
    return globalStates.get(key);
}

const setState = (key, value) => {
    globalStates.set(key, value);
}

const basePrototype = () => {
    return {};
}

const targets = new WeakMap();

// I dont know if I should use let or const for this.. I'll see implications
// later!!!
const TBase = Trait({ filter: Trait.required });

const TAllow = Trait.compose(TBase, Trait({
    filter: function (tar, prop, rec, args) {
        return this.allowedProperties.indexOf(prop) !== -1
    }
}));

const TParamAt = Trait.compose(TBase, Trait({

    idxParam: Trait.required,
    otherParam: Trait.required,
    operatorFn: Trait.required,

    filter: function (tar, prop, rec, args, opType) {
        //Policy NOT! applicable for property reads!!!
        if (opType === 'readProperty') {
            return true;
        }
        /**
         * document.createElement(stringOf(fakeDiv))
         * apply(p,t,args){
         *  if(policy.filter(...)) should change args to the desired type-value in the policy and use it subsequently
         *  return p.apply(t,args)
         * }
         */
        let newVal = this.idxParam(args);
        return this.operatorFn(newVal, this.otherParam);
    }
}));

/**
 * This function is used to prevent abusing toString and valueOf (we should look at other functions like that)
 * example of usage: ParamAt(equals, getVType(0,String), 'iframe')
 * Be sure that the type parameter returns a primitive object (string, number,...)
 */

const getVType = (idx, type) => {
    return (array) => {
        let val = type(array[idx]);
        array[idx] = val;
        return val;
    }
}

const ParamAt = (fn, idx, other) => {
    var paramPrototype = basePrototype();

    paramPrototype.operatorFn = fn;
    paramPrototype.idxParam = idx;
    paramPrototype.otherParam = other;

    return Trait.create(paramPrototype, TParamAt);
}

const TStateOverParams = Trait.compose(TBase, Trait({

    stateKey: Trait.required,
    operatorFn: Trait.required,
    otherParam: Trait.required,

    filter: function () { //TODO check the parameters...
        var obj = getState(this.stateKey);
        var res = this.operatorFn(obj, this.otherParam);
        return res;
    }
}));

const StateFnParam = (fn, key, param) => {

    var stateParamPrototype = basePrototype()

    stateParamPrototype.stateKey = key;
    stateParamPrototype.operatorFn = fn;
    stateParamPrototype.otherParam = param;

    return Trait.create(stateParamPrototype, TStateOverParams);
}

const And = function (...policies) {
    return Trait.create(basePrototype(), Trait.compose(TBase, Trait({
        filter: function (tar, prop, rec, args) {
            for (var policy of policies) {
                if (!policy.filter(tar, prop, rec, args)) {
                    return false;
                }
            }
            return true;
        }
    })))
}

const Not = function (p1) {

    return Trait.create(basePrototype(), Trait.compose(TBase, Trait({
        filter: function (tar, prop, rec, args) {
            return !p1.filter(tar, prop, rec, args);
        }
    })));
}

const Or = function (...policies) {
    return Trait.create(basePrototype(), Trait.compose(TBase, Trait({
        filter: function (tar, prop, rec, args) {
            // se puede mejorar empleando los operadores de JS
            for (var policy of policies) {
                if (policy.filter(tar, prop, rec, args)) {
                    return true;
                }
            }
            return false;
        }
    })))
}

const Allow = function (properties) {
    var proto = basePrototype();
    proto.allowedProperties = properties;
    var allowedPropPolicy = Trait.create(proto, TAllow);
    return allowedPropPolicy;
}

//Combined Policies

const Deny = function (properties) {
    return Not(Allow(properties))
}

const ParamInList = function (idx, list) {
    return ParamAt((y, xs) => {
        xs.indexOf(y) !== -1
    }, idx, list);
}

const findPropertyOwner = function (obj, prop) {
    do {
        if (obj.hasOwnProperty(prop)) {
            return obj;
        }
    } while (obj = Object.getPrototypeOf(obj));
}

const isBuiltin = function (obj) {
    if (global['window']) {
        return ((obj == window) || (obj == document) || (obj == location) || (obj == navigator) || (obj == navigator.geolocation) && obj) //continue!!
    }
    return false;
}

const installPolicy = (policy) => {

    let notify = (listeners, target, method, receiver, arglist) => {
        if (listeners) {
            for (let listener of listeners) {
                listener.notify(target, method, receiver, arglist)
            }
        }
    }

    return {
        on: function (target) {
            // !!!!!!!!!!!   iterar una sola vez cuando funcione las polizas en la
            // properties !!!!!!!!!!!!!!!...
            let methods = [];
            let properties = [];

            if (isBuiltin(target)) {
                for (let key in target) {
                    let data = target[key];
                    if (data instanceof Function) {
                        methods.push(key);
                    } else if (data) {
                        properties.push(key);
                    }
                }
                //still work todo here
                /* for (let x of properties) {
                    let owner = findPropertyOwner(target, x);
                    if (owner) {
                        var pd = Reflect.getOwnPropertyDescriptor(owner, x);
                        if (pd.configurable && pd.set && !pd.value) {
                            var m = Reflect.defineProperty(target, x, {
                                get: () => {
                                    return target.x;
                                },
                                set: (value) => {
                                    target.x = value
                                }
                            })
                        }
                    }
                }*/

                //proxy on methods
                for (let method of methods) {
                    let fnProxy = new Proxy(target[method], {
                        apply: function (targetFn, thisArg, arglist) {
                            //enforcing
                            if (policy['whenRead']) {
                                for (let pol of policy['whenRead']) {
                                    if (!pol.filter(target, method, undefined, arglist, 'call')) {
                                        throw new Error('[' + method + '] Not allowed!');
                                    }
                                }
                            }
                            //updating listeners
                            notify(policy['readListeners'], target, method, undefined, arglist);
                            return targetFn.apply(thisArg, arglist);
                        }
                    });

                    fnProxy.toString = Function
                        .prototype
                        .toString
                        .bind(target[method]); //Proxies invariants flaws!!!!
                    //This can affect transparency but 'figth' against re-attaching functions
                    Object.defineProperty(target, method, {
                        configurable: false,
                        writable: false,
                        value: fnProxy
                    })
                }

                return target;

            } else {
                // console.log('no es built in!!'); install the policy in not builtin objects.
                return new Proxy(target, {
                    get: function (tar, property, receiver) {
                        if (tar[property] instanceof Function) {
                            return function (...args) {
                                if (policy['whenRead']) {
                                    for (let pol of policy['whenRead']) {
                                        if (!pol.filter(tar, property, receiver, args, 'call')) {
                                            throw new Error('Read of [' + property + '] is not allowed!');
                                        }
                                    }
                                }
                                notify(policy['readListeners'], tar, property, undefined, args);
                                return tar[property](...args)
                            }
                        } else {

                            if (policy['whenRead']) {
                                for (let pol of policy['whenRead']) {
                                    if (!pol.filter(tar, property, receiver, 'propertyRead')) {
                                        throw new Error('Read of [' + property + '] is not allowed!');
                                    }
                                }
                            }
                            notify(policy['readListeners'], tar, property, undefined, undefined);
                            return Reflect.get(tar, property, receiver);
                        }
                    },
                    set: function (target, property, value, receiver) {
                        if (policy['whenWrite']) {
                            for (let pol of policy['whenWrite']) {
                                if (!pol.filter(target, property, receiver, value, 'call')) {
                                    throw new Error('Write to [' + property + '] is not allowed!');
                                }
                            }
                        }
                        notify(policy['writeListeners'], target, property, undefined, value);
                        return Reflect.set(target, property, value, receiver);
                    }
                });
            }
        },
        onAll: function (targets) {
            for (let item of targets) {
                console.log('target: ' + item);
                this.on(item);
            }
        }
    }
}

var installPolicyCons = function (policy, targetFn) {
    if (targetFn instanceof Function) {
        var proxy = new Proxy(targetFn, {
            construct: function (target, params, newTarget) {
                let image = Reflect.construct(target, params, newTarget);
                image = installPolicy(policy).on(image);
                return image;
            }
        });
        return proxy;
    } else {
        throw new Error('Target must be a contructor!');
    }
}

/**
 * This function is intended to be used for external enforcement mechanisms. The idea is that
 * the provided mechanism call it with the runtime information and guardia should take care of
 * determining the permissions.
 *
 * @param {Object | Function} tar
 * @param {String} prop
 * @param {Object} rec
 * @param {*} args
 * @param {String} hook
 */

const enforce = (tar, prop, rec, args, hook) => {
    if (targets.has(tar)) { // if we already have registered a secured object
        var pols = Array.from(targets.get(tar))
        for (var pol of pols) {
            for (var rpol of pol[hook]) {
                if (!rpol.filter(tar, prop, rec, args))
                    return false;
            }
        }
    }
    return true;
}

const install = (pol, tar) => {
    if (targets.has(tar)) {
        var x = targets.get(tar)
        x.add(pol);
        targets.set(tar, x);
    } else {
        var t = new Set()
        t.add(pol)
        targets.set(tar, t);
    }
}

/**
 * for installing policies on functions
 * pd should { listeners : [] , execPol: []}
 */
const installOnFunction = (pd, fn) => {
    if (tgt instanceof Function) {
        let fnProxy = new Proxy(fn, {
            apply: function (target, thisArg, argumentsList) {
                if (pd.enforce(target, thisArg, argumentsList)) {
                    throw new Error('Not Allowed');
                }
                return Reflect.apply(target, thisArg, argumentsList);
            }
        });
        return fnProxy;
    }
    throw new Error('Not a function');
}

exports.installPolicy = installPolicy;
exports.installPolicyCons = installPolicyCons;
exports.Allow = Allow;
exports.Deny = Deny;
exports.And = And;
exports.Or = Or;
exports.Not = Not;
exports.ParamInList = ParamInList;
exports.ParamAt = ParamAt;
exports.StateFnParam = StateFnParam;
exports.setState = setState;
exports.getState = getState;
exports.getVType = getVType;

//this needs to be tested yet
exports.enforce = enforce;
exports.installOn = install;
<|endoftext|>


<commit_before>module.exports = {
   printWidth: 80,
   singleQuote: true,
   trailingComma: 'es5',
   arrowParens: 'always',
};
<commit_msg>chore(conf): Update config format<commit_after>module.exports = {
  printWidth: 80,
  singleQuote: true,
  trailingComma: 'es5',
  arrowParens: 'always',
};
<|endoftext|>


<commit_before>const path = require('path');

// Middleware plugin
// Restore some of the old Express functionality
module.exports = {
  name: 'core',
  options: {
    compress: {
      default: {},
      type: Object
    },
    public: {
      type: String,
      inherit: 'public',
      clean: (value, arg, env, all, schema) => {
        console.log(process.platform, value);
        if (/^win/.test(process.platform)) {
          if (value === 'C:\\Users\\Public') {
            // return (arg.public || schema.public.default);
            // return path.normalize(path.join(process.cwd(), 'test'));
            value = arg.public || schema.default;
            const fullpath = path.isAbsolute(value) ? value : path.join(process.cwd(), value);
            return path.normalize(fullpath);
          }
        }
        return value;
      }
    },
    favicon: {
      type: String
    },
    session: {
      default: {
        resave: false,
        saveUninitialized: true,
        cookie: {}
      },
      type: Object,
      env: 'express-session',
      extend: true
    },
    timing: {
      default: {},
      type: Object
    },
    csrf: {
      default: {},
      type: Object
    }
  },

  init: require('./init'),
  before: []   // It is populated in "init()"
};
<commit_msg>Debugging windows<commit_after>const path = require('path');

// Middleware plugin
// Restore some of the old Express functionality
module.exports = {
  name: 'core',
  options: {
    compress: {
      default: {},
      type: Object
    },
    public: {
      type: String,
      inherit: 'public',
      clean: (value, arg, env, all, schema) => {
        console.log(process.platform, value);
        if (/^win/.test(process.platform)) {
          if (value === 'C:\\Users\\Public') {
            // return (arg.public || schema.public.default);
            // return path.normalize(path.join(process.cwd(), 'test'));
            value = arg.public || schema.default;
            return value;
            // const fullpath = path.isAbsolute(value) ? value : path.join(process.cwd(), value);
            // return path.normalize(fullpath);
          }
        }
        return value;
      }
    },
    favicon: {
      type: String
    },
    session: {
      default: {
        resave: false,
        saveUninitialized: true,
        cookie: {}
      },
      type: Object,
      env: 'express-session',
      extend: true
    },
    timing: {
      default: {},
      type: Object
    },
    csrf: {
      default: {},
      type: Object
    }
  },

  init: require('./init'),
  before: []   // It is populated in "init()"
};
<|endoftext|>


<commit_before>'use strict';
var _ = require('lodash');
var bluebird = require('bluebird');
var fs = require('fs');
var request = require('request-promise');

var authorize = require('./authorize.js');
var Authorize = new authorize();

class Bucket {
  createBucket(name, type, callback) {
    return Authorize.getBasicAuth().then(function(auth) {
      var opts = {
        url: auth.apiUrl + '/b2api/v1/b2_create_bucket',
        headers: {
          Authorization: auth.authorizationToken
        },
        body: {
          accountId: auth.accountId,
          bucketName: name,
          bucketType: type
        },
        json: true,
        method: 'POST'
      };

      return request(opts).then(function(bucket) {
        return bucket;
      }).catch(function(err) {
        return bluebird.reject(err.error);
      });
    }).asCallback(callback);
  }

  listBuckets(callback) {
    return Authorize.getBasicAuth().then(function(auth) {
      var opts = {
        url: auth.apiUrl + '/b2api/v1/b2_list_buckets',
        headers: {
          Authorization: auth.authorizationToken
        },
        body: {
          accountId: auth.accountId
        },
        json: true,
        method: 'POST'
      };

      return request(opts).then(function(response) {
        return response.buckets;
      }).catch(function(err) {
        return bluebird.reject(err.error);
      });
    }).asCallback(callback);
  }

  getBucketByName(name, callback) {
    // @todo caching
    return this.listBuckets(callback).then(function(buckets) {
      var theOne = _.find(buckets, function(bucket) {
        return bucket.bucketName === name;
      });
      if(theOne === null) {
        return bluebird.reject('The bucket `'+ name +'` does not exist.');
      }

      return bluebird.resolve(theOne);
    }).asCallback(callback);
  }

  getBucketFiles(name, startFileName, maxFileCount, callback) {
    if(typeof maxFileCount !== 'number') {
      maxFileCount = 100;
    } else if(maxFileCount > 1000) {
      maxFileCount = 1000;
    } else if(maxFileCount < 1) {
      maxFileCount = 1;
    }
    var props = {
      auth: Authorize.getBasicAuth(),
      bucket: this.getBucketByName(name)
    };
    return bluebird.props(props).then(function(res) {
      var opts = {
        url: res.auth.apiUrl + '/b2api/v1/b2_list_file_names',
        headers: {
          Authorization: res.auth.authorizationToken
        },
        body: {
          bucketId: res.bucket.bucketId,
          maxFileCount: maxFileCount
        },
        json: true,
        method: 'POST'
      };

      if(startFileName !== null && typeof startFileName === "string") {
        opts.body.startFileName = startFileName;
      }

      return request(opts).then(function(files) {
        return files;
      }).catch(function(err) {
        bluebird.reject(err.error);
      });
    }).asCallback(callback);
  }

}

module.exports = Bucket;<commit_msg>comment<commit_after>'use strict';
var _ = require('lodash');
var bluebird = require('bluebird');
var fs = require('fs');
var request = require('request-promise');

var authorize = require('./authorize.js');
var Authorize = new authorize();

class Bucket {
  createBucket(name, type, callback) {
    return Authorize.getBasicAuth().then(function(auth) {
      var opts = {
        url: auth.apiUrl + '/b2api/v1/b2_create_bucket',
        headers: {
          Authorization: auth.authorizationToken
        },
        body: {
          accountId: auth.accountId,
          bucketName: name,
          bucketType: type
        },
        json: true,
        method: 'POST'
      };

      return request(opts).then(function(bucket) {
        return bucket;
      }).catch(function(err) {
        return bluebird.reject(err.error);
      });
    }).asCallback(callback);
  }

  listBuckets(callback) {
    return Authorize.getBasicAuth().then(function(auth) {
      var opts = {
        url: auth.apiUrl + '/b2api/v1/b2_list_buckets',
        headers: {
          Authorization: auth.authorizationToken
        },
        body: {
          accountId: auth.accountId
        },
        json: true,
        method: 'POST'
      };

      return request(opts).then(function(response) {
        return response.buckets;
      }).catch(function(err) {
        return bluebird.reject(err.error);
      });
    }).asCallback(callback);
  }

  getBucketByName(name, callback) {
    // @todo caching
    return this.listBuckets(callback).then(function(buckets) {
      var theOne = _.find(buckets, function(bucket) {
        return bucket.bucketName === name;
      });
      if(theOne === null) {
        return bluebird.reject('The bucket `'+ name +'` does not exist.');
      }

      return bluebird.resolve(theOne);
    }).asCallback(callback);
  }

  getBucketFiles(name, startFileName, maxFileCount, callback) {
    // Make dealing with optional parameters easier
    if(typeof maxFileCount !== 'number') {
      maxFileCount = 100;
    } else if(maxFileCount > 1000) {
      maxFileCount = 1000;
    } else if(maxFileCount < 1) {
      maxFileCount = 1;
    }

    var props = {
      auth: Authorize.getBasicAuth(),
      bucket: this.getBucketByName(name)
    };
    return bluebird.props(props).then(function(res) {
      var opts = {
        url: res.auth.apiUrl + '/b2api/v1/b2_list_file_names',
        headers: {
          Authorization: res.auth.authorizationToken
        },
        body: {
          bucketId: res.bucket.bucketId,
          maxFileCount: maxFileCount
        },
        json: true,
        method: 'POST'
      };

      if(startFileName !== null && typeof startFileName === "string") {
        opts.body.startFileName = startFileName;
      }

      return request(opts).then(function(files) {
        return files;
      }).catch(function(err) {
        bluebird.reject(err.error);
      });
    }).asCallback(callback);
  }
}

module.exports = Bucket;<|endoftext|>


<commit_before>CacheStore = function(id, options) {

  var self = this;

  this.id = id || 'defaultCacheStore';

  _.extend(this, {
    persist: true,
    expires: null
  }, _.pick(options, 'persist', 'expires'));

  this.keys = _.object(_.map(amplify.store(), function(value, key) {
    if(key.match(self.id)) {
      Session.set(key, value);
      return [key, JSON.stringify(value)];
    }
  }));
}

_.extend(CacheStore.prototype, Session, {

  prefix: function(key) {
    return this.id + '__' + key;
  },

  set: function(key, value) {
    Session.set(this.prefix(key), value);
    if (this.persist) {
      amplify.store(this.prefix(key), value, {expires: this.expires});
    }
  },

  get: function(key) {
    return Session.get(this.prefix(key));
  },

  clear: function() {
    var self = this;
    _.each(this.keys, function(value, key) {
      self.set(key, null);
    });
  }

});<commit_msg>CachedStore now filters values from localStorage correctly<commit_after>CacheStore = function(id, options) {

  var self = this;

  this.id = id || 'defaultCacheStore';

  _.extend(this, {
    persist: true,
    expires: null
  }, _.pick(options, 'persist', 'expires'));

  this.keys = _.reduce(amplify.store(), function(memo, value, key) {
    if(key.match(self.id)) {
      Session.set(key, value);
      memo.push(key);
    }
    return memo;
  }, []);
}

_.extend(CacheStore.prototype, Session, {

  prefix: function(key) {
    return this.id + '__' + key;
  },

  set: function(key, value) {
    Session.set(this.prefix(key), value);
    if (this.persist) {
      amplify.store(this.prefix(key), value, {expires: this.expires});
    }
  },

  get: function(key) {
    return Session.get(this.prefix(key));
  },

  clear: function() {
    var self = this;
    _.each(this.keys, function(value, key) {
      self.set(key, null);
    });
  }

});<|endoftext|>


<commit_before>(function(window, document) {
    var path = window.location.pathname;
    with (window) {
        _location = {
            hash: location.hash,
            host: location.host,
            hostname: location.hostname,
            href: location.href,
            origin: location.origin,
            pathname: location.pathname,
            port: location.port,
            protocol: location.protocol,
            assign: function(url) {
                location.assign($url(url));
            },
            reload: function(bool) {
                location.assign(bool);
            },
            replace: function(url) {
                location.replace($url(url));
            },
            search: function(str) {
                location.search(str);
            },
            toString: function() {
                return location.toString();
            }
        };
    }

    function base_host(path) {
        parts = path.split("/");
        if (parts[1] == "s") {
            return "/s/" + parts[2];
        } else {
            return "/" + parts[1];
        }
    }

    function base_url(path) {
        if (path[path.length - 1] == '/') {
            return path;
        } else {
            parts = path.split("/");
            if (parts > 2) {
                parts.remove(parts.length - 1);
                return "/" + parts.join('/') + "/";
            } else {
                return path + "/";
            }
        }
    }

    var baseHost = base_host(path);
    var baseUrl = base_url(path);

    function safe_url(url) {

        if (url.indexOf("http://") === 0) {
            return url.replace("http://", "/");
        } else if (url.indexOf("//") === 0) {
            return url.replace("//", "/");
        } else if (url.indexOf("https://") === 0) {
            return url.replace("https://", "/s/");
        } else if (url.indexOf("/") === 0) {
            return baseHost + url;
        } else {
            return baseUrl + url;
        }

    }

    function is_safe_url(url) {
        return typeof url != "string" || url.indexOf("/s/") === 0 || url.indexOf(baseHost) === 0 || url.indexOf("data:image") === 0 || url.indexOf("about:blank") === 0 || url.indexOf("#") === 0 || url.match(/^\/[\w\.\:\@\-]{3,}\.[\w]{2,5}(:[0-9]+)?/g);
    }

    function $url(url) {
        if (!is_safe_url(url)) {
            return safe_url(url);
        } else {
            return url;
        }
    }

    function is_url_prop(name) {
        return name == "src" || name == "href" || name == "action";
    }

    function check_attribute(node, attrName) {
        if (node instanceof Element && node.hasAttribute(attrName)) {
            url = node.getAttribute(attrName);
            if (!is_safe_url(url)) {
                var safeUrl = safe_url(url);
                console.log("protecting url " + url + " safe_url = " + safeUrl);
                node.setAttribute(attrName, safeUrl);
            } else {
                console.log("url is safe " + url);
            }
        }
    }

    function protect_node(node) {
        function attrs(node) {
            check_attribute(node, "href");
            check_attribute(node, "src");
            check_attribute(node, "action");
        }
        attrs(node);
        for (var i = 0; i < node.childNodes.length; i++) {
            item = node[i];
            attrs(node);
        }
    }

    (function($open) {
        XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
            if (is_safe_url(url)) {
                var sUrl = url;
            } else {
                var sUrl = safe_url(url);
                console.log(url + " redirected to " + sUrl);
            }
            return $open.call(this, method, sUrl, async, user, pass);
        };
    })(XMLHttpRequest.prototype.open);

    (function($appendChild, $insertBefore, $replaceChild, $setAttribute, $setAttributeNS, $setAttributeNode, $setAttributeNodeNS) {
        Node.prototype.appendChild = function(node) {
            node = unwrap(node);
            protect_node(node);
            return $appendChild.call(this, node);
        };
        Node.prototype.insertBefore = function(newElement, referenceElement) {
            node = unwrap(newElement);
            protect_node(newElement);
            return $insertBefore.call(this, newElement, referenceElement);
        };
        Node.prototype.replaceChild = function(newChild, oldChild) {
            node = unwrap(newChild);
            protect_node(newChild);
            return $replaceChild.call(this, newChild, oldChild);
        };
        Element.prototype.setAttribute = function(name, value) {
            if (is_url_prop(name)) {
                value = $url(value);
            }

            return $setAttribute.call(this, name, value);
        };
        Element.prototype.setAttributeNS = function(namespace, name, value) {
            if (is_url_prop(name)) {
                value = $url(value);
            }

            return $setAttributeNS.call(this, namespace, name, value);
        };
        Element.prototype.setAttributeNode = function(attr) {
            if (attr) {
                var name = attr.name;
                if (is_url_prop(name)) {
                    value = $url(attr.value);
                }
            }

            return $setAttributeNode.call(this, attr);
        };
        Element.prototype.setAttributeNodeNS = function(attr) {
            if (attr) {
                var name = attr.name;
                if (is_url_prop(name)) {
                    value = $url(attr.value);
                }
            }

            return $setAttributeNodeNS.call(this, attr);
        };
    })(Node.prototype.appendChild, Node.prototype.insertBefore, Node.prototype.replaceChild,
        Element.prototype.setAttribute, Element.prototype.setAttributeNS, Element.prototype.setAttributeNode, Element.prototype.setAttributeNodeNS);

    if (MutationObserver) {
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                console.log(mutation.type);
            });
        });

        var config = { attributes: true, characterData: true, subtree: true, attributeFilter: ["src", "href", "action"] };
        observer.observe(document, config);
    }

    function wrap(object) {
        console.log("stub " + object.name);
        return function(args) {
            var $this = this;
            var _origin = new object();
            for (prop in _origin) {
                if (typeof _origin[prop] == 'function') {
                    var originalMethod = _origin[prop];
                    var method = function() {
                        console.log("method " + prop + " is called");
                        updateProps(this);
                        return originalMethod.apply(_origin, args);
                    }
                } else {
                    var val = _origin[prop];
                    if (val != 0 && val != "" && val != undefined) {
                        copy_prop(prop, _origin, this);
                    }
                }
            }

            function copy_prop(name, from, to) {
                if (from[name] != undefined && from[name] != to[name]) {
                    if (is_url_prop(name)) {
                        var url = $url(from[name]);
                        to[name] = url;
                        from[name] = url;
                    } else {
                        try {
                            to[name] = from[name];
                        } catch (e) {
                            //console.log(e);
                        }
                    }
                }
            }

            function updateProps(stub) {
                for(prop in _origin) {
                    if (typeof _origin[prop] != 'function') {
                        copy_prop(prop, stub, _origin);
                    }
                }
            }

            this._returnOrigin = function() {
                updateProps($this);
                return _origin;
            };

            window.setTimeout(function () {
                updateProps($this);
            }, 1000);

        };
    }

    function unwrap(object) {
        if (object instanceof wImage) {
            return object._returnOrigin();
        } else {
            return object;
        }
    }

    // todo intercept an insertion of this object into DOM
    window.Image = wImage = wrap(window.Image);

    //todo intercept document.createElement()

})(window, document);
<commit_msg>fixed bug<commit_after>(function(window, document) {
    var path = window.location.pathname;
    with (window) {
        _location = {
            hash: location.hash,
            host: location.host,
            hostname: location.hostname,
            href: location.href,
            origin: location.origin,
            pathname: location.pathname,
            port: location.port,
            protocol: location.protocol,
            assign: function(url) {
                location.assign($url(url));
            },
            reload: function(bool) {
                location.assign(bool);
            },
            replace: function(url) {
                location.replace($url(url));
            },
            search: function(str) {
                location.search(str);
            },
            toString: function() {
                return location.toString();
            }
        };
    }

    function base_host(path) {
        parts = path.split("/");
        if (parts[1] == "s") {
            return "/s/" + parts[2];
        } else {
            return "/" + parts[1];
        }
    }

    function base_url(path) {
        if (path[path.length - 1] == '/') {
            return path;
        } else {
            parts = path.split("/");
            if (parts > 2) {
                parts.remove(parts.length - 1);
                return "/" + parts.join('/') + "/";
            } else {
                return path + "/";
            }
        }
    }

    var baseHost = base_host(path);
    var baseUrl = base_url(path);

    function safe_url(url) {

        if (url.indexOf("http://") === 0) {
            return url.replace("http://", "/");
        } else if (url.indexOf("//") === 0) {
            return url.replace("//", "/");
        } else if (url.indexOf("https://") === 0) {
            return url.replace("https://", "/s/");
        } else if (url.indexOf("/") === 0) {
            return baseHost + url;
        } else {
            return baseUrl + url;
        }

    }

    function is_safe_url(url) {
        return typeof url != "string" || url.indexOf("/s/") === 0 || url.indexOf(baseHost) === 0 || url.indexOf("data:image") === 0 || url.indexOf("about:blank") === 0 || url.indexOf("#") === 0 || url.match(/^\/[\w\.\:\@\-]{3,}\.[\w]{2,5}(:[0-9]+)?/g);
    }

    function $url(url) {
        if (!is_safe_url(url)) {
            return safe_url(url);
        } else {
            return url;
        }
    }

    function is_url_prop(name) {
        return name == "src" || name == "href" || name == "action";
    }

    function check_attribute(node, attrName) {
        if (node instanceof Element && node.hasAttribute(attrName)) {
            url = node.getAttribute(attrName);
            if (!is_safe_url(url)) {
                var safeUrl = safe_url(url);
                console.log("protecting url " + url + " safe_url = " + safeUrl);
                node.setAttribute(attrName, safeUrl);
            } else {
                console.log("url is safe " + url);
            }
        }
    }

    function protect_node(node) {
        function attrs(node) {
            check_attribute(node, "href");
            check_attribute(node, "src");
            check_attribute(node, "action");
        }
        attrs(node);
        for (var i = 0; i < node.childNodes.length; i++) {
            item = node[i];
            attrs(node);
        }
    }

    (function($open) {
        XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
            if (is_safe_url(url)) {
                var sUrl = url;
            } else {
                var sUrl = safe_url(url);
                console.log(url + " redirected to " + sUrl);
            }
            return $open.call(this, method, sUrl, async, user, pass);
        };
    })(XMLHttpRequest.prototype.open);

    (function($appendChild, $insertBefore, $replaceChild, $setAttribute, $setAttributeNS, $setAttributeNode, $setAttributeNodeNS) {
        Node.prototype.appendChild = function(node) {
            node = unwrap(node);
            protect_node(node);
            return $appendChild.call(this, node);
        };
        Node.prototype.insertBefore = function(newElement, referenceElement) {
            node = unwrap(newElement);
            protect_node(newElement);
            return $insertBefore.call(this, newElement, referenceElement);
        };
        Node.prototype.replaceChild = function(newChild, oldChild) {
            node = unwrap(newChild);
            protect_node(newChild);
            return $replaceChild.call(this, newChild, oldChild);
        };
        Element.prototype.setAttribute = function(name, value) {
            if (is_url_prop(name)) {
                value = $url(value);
            }

            return $setAttribute.call(this, name, value);
        };
        Element.prototype.setAttributeNS = function(namespace, name, value) {
            if (is_url_prop(name)) {
                value = $url(value);
            }

            return $setAttributeNS.call(this, namespace, name, value);
        };
        Element.prototype.setAttributeNode = function(attr) {
            if (attr) {
                var name = attr.name;
                if (is_url_prop(name)) {
                    value = $url(attr.value);
                }
            }

            return $setAttributeNode.call(this, attr);
        };
        Element.prototype.setAttributeNodeNS = function(attr) {
            if (attr) {
                var name = attr.name;
                if (is_url_prop(name)) {
                    value = $url(attr.value);
                }
            }

            return $setAttributeNodeNS.call(this, attr);
        };
    })(Node.prototype.appendChild, Node.prototype.insertBefore, Node.prototype.replaceChild,
        Element.prototype.setAttribute, Element.prototype.setAttributeNS, Element.prototype.setAttributeNode, Element.prototype.setAttributeNodeNS);

    if (MutationObserver) {
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                console.log(mutation.type);
            });
        });

        var config = { attributes: true, characterData: true, subtree: true, attributeFilter: ["src", "href", "action"] };
        observer.observe(document, config);
    }

    function wrap(object) {
        console.log("stub " + object.name);
        return function(args) {
            var $this = this;
            var _origin = new object();
            for (prop in _origin) {
                if (typeof _origin[prop] == 'function') {
                    var originalMethod = _origin[prop];
                    var method = function() {
                        console.log("method " + prop + " is called");
                        updateProps(this);
                        return originalMethod.apply(_origin, arguments);
                    }
                } else {
                    var val = _origin[prop];
                    if (val != 0 && val != "" && val != undefined) {
                        copy_prop(prop, _origin, this);
                    }
                }
            }

            function copy_prop(name, from, to) {
                if (from[name] != undefined && from[name] != to[name]) {
                    if (is_url_prop(name)) {
                        var url = $url(from[name]);
                        to[name] = url;
                        from[name] = url;
                    } else {
                        try {
                            to[name] = from[name];
                        } catch (e) {
                            //console.log(e);
                        }
                    }
                }
            }

            function updateProps(stub) {
                for(prop in _origin) {
                    if (typeof _origin[prop] != 'function') {
                        copy_prop(prop, stub, _origin);
                    }
                }
            }

            this._returnOrigin = function() {
                updateProps($this);
                return _origin;
            };

            window.setTimeout(function () {
                updateProps($this);
            }, 1000);

        };
    }

    function unwrap(object) {
        if (object instanceof wImage) {
            return object._returnOrigin();
        } else {
            return object;
        }
    }

    // todo intercept an insertion of this object into DOM
    window.Image = wImage = wrap(window.Image);

    //todo intercept document.createElement()

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


<commit_before>(function (root, factory) {
  if (typeof module !== 'undefined' && module.exports) {
    module.exports = factory(
      require('react'),
      require('react-dom'),
      require('swipe-js-iso'),
      require('object-assign')
    );
  } else {
    root.ReactSwipe = factory(
      root.React,
      root.ReactDOM,
      root.Swipe,
      root.objectAssign
    );
  }
})(this, function (React, ReactDOM, Swipe, objectAssign) {
  var styles = {
    container: {
      overflow: 'hidden',
      visibility: 'hidden',
      position: 'relative'
    },

    wrapper: {
      overflow: 'hidden',
      position: 'relative'
    },

    child: {
      float: 'left',
      width: '100%',
      position: 'relative',
      transitionProperty: 'transform'
    }
  };

  var ReactSwipe = React.createClass({
    // https://github.com/thebird/Swipe#config-options
    propTypes: {
      startSlide          : React.PropTypes.number,
      slideToIndex        : React.PropTypes.number,
      shouldUpdate        : React.PropTypes.func,
      speed               : React.PropTypes.number,
      auto                : React.PropTypes.number,
      continuous          : React.PropTypes.bool,
      disableScroll       : React.PropTypes.bool,
      stopPropagation     : React.PropTypes.bool,
      callback            : React.PropTypes.func,
      transitionEnd       : React.PropTypes.func,
      containerStyles     : React.PropTypes.object,
      wrapperStyles       : React.PropTypes.object,
      reinitSwipeOnUpdate : React.PropTypes.bool
    },

    componentDidMount: function () {
      this.swipe = Swipe(ReactDOM.findDOMNode(this), objectAssign({}, this.props));
    },

    componentDidUpdate: function () {
      if (this.props.reinitSwipeOnUpdate) {
        this.swipe.kill();
        this.swipe = Swipe(ReactDOM.findDOMNode(this), objectAssign({}, this.props));
      }
      if (this.props.slideToIndex || this.props.slideToIndex === 0) {
        this.swipe.slide(this.props.slideToIndex);
      }
    },

    componentWillUnmount: function () {
      this.swipe.kill();
      delete this.swipe;
    },

    shouldComponentUpdate: function (nextProps) {
      return (
        (this.props.slideToIndex !== nextProps.slideToIndex) ||
        (typeof this.props.shouldUpdate !== 'undefined') &&
        this.props.shouldUpdate(nextProps, this.props) ||
        (nextProps.children!==this.props.children)
      );
    },
    componentWillReceiveProps:function(newProps){
      if(this.swipe!=null){
        this.swipe.kill();
      }
      this.swipe = Swipe(this.getDOMNode(), this.props);
    },

    render: function() {
      return React.createElement('div', React.__spread({}, {style: objectAssign({}, styles.container, this.props.containerStyles)}, this.props),
        React.createElement('div', {style: objectAssign({}, styles.wrapper, this.props.wrapperStyles)},
          React.Children.map(this.props.children, function (child) {
            return React.cloneElement(child, {
              style: styles.child
            });
          })
        )
      );
    },

    next: function() {
      this.swipe.next();
    },

    prev: function() {
      this.swipe.prev();
    }
  });

  return ReactSwipe;
});
<commit_msg>Debugger friendly<commit_after>(function (root, factory) {
  if (typeof module !== 'undefined' && module.exports) {
    module.exports = factory(
      require('react'),
      require('react-dom'),
      require('swipe-js-iso'),
      require('object-assign')
    );
  } else {
    root.ReactSwipe = factory(
      root.React,
      root.ReactDOM,
      root.Swipe,
      root.objectAssign
    );
  }
})(this, function (React, ReactDOM, Swipe, objectAssign) {
  var styles = {
    container: {
      overflow: 'hidden',
      visibility: 'hidden',
      position: 'relative'
    },

    wrapper: {
      overflow: 'hidden',
      position: 'relative'
    },

    child: {
      float: 'left',
      width: '100%',
      position: 'relative',
      transitionProperty: 'transform'
    }
  };

  var ReactSwipe = React.createClass({
    displayName: 'ReactSwipe',

    // https://github.com/thebird/Swipe#config-options
    propTypes: {
      startSlide          : React.PropTypes.number,
      slideToIndex        : React.PropTypes.number,
      shouldUpdate        : React.PropTypes.func,
      speed               : React.PropTypes.number,
      auto                : React.PropTypes.number,
      continuous          : React.PropTypes.bool,
      disableScroll       : React.PropTypes.bool,
      stopPropagation     : React.PropTypes.bool,
      callback            : React.PropTypes.func,
      transitionEnd       : React.PropTypes.func,
      containerStyles     : React.PropTypes.object,
      wrapperStyles       : React.PropTypes.object,
      reinitSwipeOnUpdate : React.PropTypes.bool
    },

    componentDidMount: function () {
      this.swipe = Swipe(ReactDOM.findDOMNode(this), objectAssign({}, this.props));
    },

    componentDidUpdate: function () {
      if (this.props.reinitSwipeOnUpdate) {
        this.swipe.kill();
        this.swipe = Swipe(ReactDOM.findDOMNode(this), objectAssign({}, this.props));
      }
      if (this.props.slideToIndex || this.props.slideToIndex === 0) {
        this.swipe.slide(this.props.slideToIndex);
      }
    },

    componentWillUnmount: function () {
      this.swipe.kill();
      delete this.swipe;
    },

    shouldComponentUpdate: function (nextProps) {
      return (
        (this.props.slideToIndex !== nextProps.slideToIndex) ||
        (typeof this.props.shouldUpdate !== 'undefined') &&
        this.props.shouldUpdate(nextProps, this.props) ||
        (nextProps.children!==this.props.children)
      );
    },
    componentWillReceiveProps:function(newProps){
      if(this.swipe!=null){
        this.swipe.kill();
      }
      this.swipe = Swipe(this.getDOMNode(), this.props);
    },

    render: function() {
      return React.createElement('div', React.__spread({}, {style: objectAssign({}, styles.container, this.props.containerStyles)}, this.props),
        React.createElement('div', {style: objectAssign({}, styles.wrapper, this.props.wrapperStyles)},
          React.Children.map(this.props.children, function (child) {
            return React.cloneElement(child, {
              style: styles.child
            });
          })
        )
      );
    },

    next: function() {
      this.swipe.next();
    },

    prev: function() {
      this.swipe.prev();
    }
  });

  return ReactSwipe;
});
<|endoftext|>


<commit_before>// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;

/*server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

// Routing
app.use(express.static(__dirname + '/public'));

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new message', function (data) {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (username) {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', function () {
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', function () {
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });
});*/
<commit_msg>tweleth commit<commit_after>// Setup basic express server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
//var io = require('../..')(server);
var port = process.env.PORT || 3000;

// Routing
app.use(express.static(__dirname + '/public'));

/*server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

// Routing
app.use(express.static(__dirname + '/public'));

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new message', function (data) {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (username) {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', function () {
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', function () {
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });
});*/
<|endoftext|>