<commit_before>'use strict';

var Download = require('download');
var exec = require('child_process').exec;
var extfs = require('extfs');
var fs = require('fs');
var chalk = require('chalk');
var runCommand = require('./utils/run-command');
var tarsUtils = require('../utils');
var configPromt = require('../promt/config-promt');
var fsPromt = require('../promt/fs-promt');
var saveAnswers = require('../promt/save-answers');
var tarsZipUrl = 'https://github.com/tars/tars/archive/master.zip';
var commandOptions = {};

/**
 * Main init funciton, download all additional tasks.
 * @param  {Object} answers         Object with answers from promt
 */
function mainInit(answers) {
    var cwd = process.cwd();
    var downloadTars = new Download({
        mode: '755',
        extract: true,
        strip: 1
    }).get(tarsZipUrl).dest(cwd);

    tarsUtils.tarsSay('Please, wait for a moment, while magic is happening...');

    downloadTars.run(function (downloadErr) {

        if (downloadErr) {
            tarsUtils.spinner.stop(true);
            throw downloadErr;
        }

        if (answers) {
            saveAnswers(answers);
        }

        var userPackage = require(cwd + '/user-package.json');

        process.env.tarsVersion = require(cwd + '/package.json').version;
        tarsUtils.tarsSay('Tars version is: ' + process.env.tarsVersion);

        extfs.remove(['package.json', 'user-package.json', '_package.json'], function () {
            var packageJson = require(process.env.cliRoot + 'templates/package.json');

            packageJson.dependencies = userPackage.dependencies || {};
            packageJson.devDependencies = userPackage.devDependencies || {};
            packageJson.optionalDependencies = userPackage.optionalDependencies || {};
            fs.writeFileSync('package.json', JSON.stringify(packageJson, null, 2) + '\n');
            tarsUtils.tarsSay('Local package.json has been created');

            exec('npm i && npm i gulp --save', function (error, stdout, stderr) {
                if (error) {
                    console.log(stderr);
                } else {
                    tarsUtils.tarsSay('Local dependencies has been installed');
                    runCommand('./node_modules/.bin/gulp', ['init', '--silent']);
                }
            });
        });
    });
}

/**
 * Start initialization
 */
function startInit() {
    var cwd = process.cwd();

    tarsUtils.tarsSay(chalk.underline('Initialization has been started!') + '\n');
    tarsUtils.tarsSay('I\'ll be inited in ' + chalk.cyan('"' + cwd + '"'));
    tarsUtils.tarsSay('TARS source will be downloaded from ' + chalk.cyan('"' + tarsZipUrl + '"'));

    if (!commandOptions.source) {
        tarsUtils.tarsSay('You can specify source url by using flag ' + chalk.cyan('"--source"') + ' or ' + chalk.cyan('"-s"'));
        tarsUtils.tarsSay('Example: ' + chalk.cyan('"tars init -s http://url.to.zip.with.tars"'));
        tarsUtils.tarsSay('Run command ' + chalk.cyan('"tars init --help"') + ' for more info.\n');
    }

    tarsUtils.tarsSay('I\'m going to install "gulp" localy and create local package.json');
    tarsUtils.tarsSay('You can modify package.json by using command ' + chalk.cyan('"npm init"') + ' or manually.');

    if (commandOptions.silent) {
        mainInit();
    } else {
        configPromt(mainInit);
    }
}

/**
 * Init TARS
 * @param  {Object} options Options of init
 */
module.exports = function init(options) {
    var cwd = process.cwd();

    commandOptions = options;
    tarsUtils.spinner.start();

    if (options.source) {
        tarsZipUrl = options.source;
    }

    if (tarsUtils.isTarsInited()) {
        tarsUtils.tarsSay('Tars has been inited already!');
        tarsUtils.tarsSay('You can\'t init Tars in current directory again.');
        tarsUtils.tarsSay('If you need to change preproc or templater, run tars ' + chalk.cyan('"tars re-init"') + '.', true);
        return;
    }

    console.log('\n');
    extfs.isEmpty(cwd, function (empty) {
        if (!empty) {
            tarsUtils.tarsSay(chalk.red('Directory "' + cwd + '" is not empty.'), true);
            fsPromt(startInit);
        } else {
            startInit();
        }
    });
};
<commit_msg>Изменен текст уведомления об установке локальных зависимостей<commit_after>'use strict';

var Download = require('download');
var exec = require('child_process').exec;
var extfs = require('extfs');
var fs = require('fs');
var chalk = require('chalk');
var runCommand = require('./utils/run-command');
var tarsUtils = require('../utils');
var configPromt = require('../promt/config-promt');
var fsPromt = require('../promt/fs-promt');
var saveAnswers = require('../promt/save-answers');
var tarsZipUrl = 'https://github.com/tars/tars/archive/master.zip';
var commandOptions = {};

/**
 * Main init funciton, download all additional tasks.
 * @param  {Object} answers         Object with answers from promt
 */
function mainInit(answers) {
    var cwd = process.cwd();
    var downloadTars = new Download({
        mode: '755',
        extract: true,
        strip: 1
    }).get(tarsZipUrl).dest(cwd);

    tarsUtils.tarsSay('Please, wait for a moment, while magic is happening...');

    downloadTars.run(function (downloadErr) {

        if (downloadErr) {
            tarsUtils.spinner.stop(true);
            throw downloadErr;
        }

        if (answers) {
            saveAnswers(answers);
        }

        var userPackage = require(cwd + '/user-package.json');

        process.env.tarsVersion = require(cwd + '/package.json').version;
        tarsUtils.tarsSay('Tars version is: ' + process.env.tarsVersion);

        extfs.remove(['package.json', 'user-package.json', '_package.json'], function () {
            var packageJson = require(process.env.cliRoot + 'templates/package.json');

            packageJson.dependencies = userPackage.dependencies || {};
            packageJson.devDependencies = userPackage.devDependencies || {};
            packageJson.optionalDependencies = userPackage.optionalDependencies || {};
            fs.writeFileSync('package.json', JSON.stringify(packageJson, null, 2) + '\n');
            tarsUtils.tarsSay('Local package.json has been created');

            exec('npm i && npm i gulp --save', function (error, stdout, stderr) {
                if (error) {
                    console.log(stderr);
                } else {
                    tarsUtils.tarsSay('Local gulp and other dependencies has been installed');
                    runCommand('./node_modules/.bin/gulp', ['init', '--silent']);
                }
            });
        });
    });
}

/**
 * Start initialization
 */
function startInit() {
    var cwd = process.cwd();

    tarsUtils.tarsSay(chalk.underline('Initialization has been started!') + '\n');
    tarsUtils.tarsSay('I\'ll be inited in ' + chalk.cyan('"' + cwd + '"'));
    tarsUtils.tarsSay('TARS source will be downloaded from ' + chalk.cyan('"' + tarsZipUrl + '"'));

    if (!commandOptions.source) {
        tarsUtils.tarsSay('You can specify source url by using flag ' + chalk.cyan('"--source"') + ' or ' + chalk.cyan('"-s"'));
        tarsUtils.tarsSay('Example: ' + chalk.cyan('"tars init -s http://url.to.zip.with.tars"'));
        tarsUtils.tarsSay('Run command ' + chalk.cyan('"tars init --help"') + ' for more info.\n');
    }

    tarsUtils.tarsSay('I\'m going to install "gulp" localy and create local package.json');
    tarsUtils.tarsSay('You can modify package.json by using command ' + chalk.cyan('"npm init"') + ' or manually.');

    if (commandOptions.silent) {
        mainInit();
    } else {
        configPromt(mainInit);
    }
}

/**
 * Init TARS
 * @param  {Object} options Options of init
 */
module.exports = function init(options) {
    var cwd = process.cwd();

    commandOptions = options;
    tarsUtils.spinner.start();

    if (options.source) {
        tarsZipUrl = options.source;
    }

    if (tarsUtils.isTarsInited()) {
        tarsUtils.tarsSay('Tars has been inited already!');
        tarsUtils.tarsSay('You can\'t init Tars in current directory again.');
        tarsUtils.tarsSay('If you need to change preproc or templater, run tars ' + chalk.cyan('"tars re-init"') + '.', true);
        return;
    }

    console.log('\n');
    extfs.isEmpty(cwd, function (empty) {
        if (!empty) {
            tarsUtils.tarsSay(chalk.red('Directory "' + cwd + '" is not empty.'), true);
            fsPromt(startInit);
        } else {
            startInit();
        }
    });
};
<|endoftext|>


<commit_before>resizeCamera = function() {
     const camera = document.getElementById("camera");
     camera.style.width = "100%";
     camera.style.height = camera.style.width * (56.25/100);
};<commit_msg>Camera Resize<commit_after>resizeCamera = function() {
     const camera = document.getElementById("camera");
     camera.style.width = "100%";
     camera.style.height = camera.style.width * (75/100);
};<|endoftext|>


<commit_before>/*global define*/
define([
        '../Core/appendForwardSlash',
        '../Core/defaultValue',
        '../Core/defined',
        '../Core/defineProperties',
        '../Core/destroyObject',
        '../Core/DeveloperError',
        '../Core/Intersect',
        '../Core/loadJson',
        '../Core/Math',
        '../Core/Queue',
        './Cesium3DTile',
        './SceneMode',
        '../ThirdParty/when'
    ], function(
        appendForwardSlash,
        defaultValue,
        defined,
        defineProperties,
        destroyObject,
        DeveloperError,
        Intersect,
        loadJson,
        CesiumMath,
        Queue,
        Cesium3DTile,
        SceneMode,
        when) {
    "use strict";

    /**
     * DOC_TBA
     *
     * @param {Object} options Object with the following properties:
     * @param {String} options.url TODO
     * @param {Boolean} [options.show=true] TODO
     * @param {Boolean} [options.maximumScreenSpaceError=2] TODO
     *
     * @alias Cesium3DTiles
     * @constructor
     * @private
     */
    var Cesium3DTiles = function(options) {
        options = defaultValue(options, defaultValue.EMPTY_OBJECT);

        var url = options.url;

        //>>includeStart('debug', pragmas.debug);
        if (!defined(url)) {
            throw new DeveloperError('options.url is required.');
        }
        //>>includeEnd('debug');

        var baseUrl = appendForwardSlash(url);

        this._url = url;
        this._root = undefined;
        this._geometricError = undefined; // Geometric error when the tree is not rendered at all
// TODO: a linked list would be better depending on how how it allocates/frees.
        this._processingQueue = [];

        /**
         * DOC_TBA
         */
        this.show = defaultValue(options.show, true);

        /**
         * DOC_TBA
         */
        this.maximumScreenSpaceError = defaultValue(options.maximumScreenSpaceError, 100);

        var that = this;

        loadJson(baseUrl + 'tree.json').then(function(tree) {
            that._geometricError = tree.geometricError;
            that._root = new Cesium3DTile(baseUrl, tree.root, undefined);

            var stack = [];
            stack.push({
                skeletonTile : tree.root,
                cesium3DTile : that._root
            });

// TODO: allow skeleton tree itself to be out-of-core
            while (stack.length > 0) {
                var n = stack.pop();
                var skeletonChildren = n.skeletonTile.children;
                var length = skeletonChildren.length;
                for (var k = 0; k < length; ++k) {
                    var skeletonChild = skeletonChildren[k];
                    var cesium3DTileChild = new Cesium3DTile(baseUrl, skeletonChild, n.cesium3DTile);
                    n.cesium3DTile.children.push(cesium3DTileChild);

                    stack.push({
                        skeletonTile : skeletonChild,
                        cesium3DTile : cesium3DTileChild
                    });
                }
            }
        });
    };

    defineProperties(Cesium3DTiles.prototype, {
        /**
         * DOC_TBA
         *
         * @memberof Cesium3DTiles.prototype
         *
         * @type {String}
         * @readonly
         */
        url : {
            get : function() {
                return this._url;
            }
        }
    });

    function visible(tile, cullingVolume) {
        // Exploit temporal coherence: if a tile is completely in the view frustum
        // then so are its children so they do not need to be culled.
        if (tile.parentFullyVisible) {
            return Intersect.INSIDE;
        }

        return tile.visibility(cullingVolume);
    }

    function contentsVisible(tile, cullingVolume) {
        if (tile.parentFullyVisible) {
            return true;
        }

        return tile.contentsVisibility(cullingVolume) !== Intersect.OUTSIDE;
    }

    function getScreenSpaceError(tile, context, frameState) {
// TODO: screenSpaceError2D like QuadtreePrimitive.js
        if (tile.geometricError === 0.0) {
            // Leaf nodes do not have any error so save the computation
            return tile.geometricError;
        }

        return getExplicitScreenSpaceError(tile.geometricError, tile, context, frameState);
    }

    function getExplicitScreenSpaceError(geometricError, tile, context, frameState) {
        // Avoid divide by zero when viewer is inside the tile
        var distance = Math.max(tile.distanceToCamera, CesiumMath.EPSILON7);
        var height = context.drawingBufferHeight;
        var sseDenominator = frameState.camera.frustum.sseDenominator;

        return (geometricError * height) / (distance * sseDenominator);
    }

    function computeDistanceToCamera(children, frameState) {
        var camera = frameState.camera;
        var length = children.length;
        for (var i = 0; i < length; ++i) {
            var child = children[i];
            child.distanceToCamera = child.distanceToTile(frameState);
        }
    }

// TODO: is it worth exploiting frame-to-frame coherence in the sort?
    function sortChildrenByDistanceToCamera(a, b) {
        // Sort by closest child first
        return a.distanceToCamera - b.distanceToCamera;
    }

    function requestChild(tiles3D, tile) {
        tile.requestContent();
        var removeFunction = removeFromProcessingQueue(tiles3D, tile);
        when(tile.processingPromise).then(addToProcessingQueue(tiles3D, tile));
        when(tile.readyPromise).then(removeFunction).otherwise(removeFunction);
    }

    function requestChildren(tiles3D, parent, frameState) {
        var children = parent.children;
        var length = children.length;

        // Sort to request tiles closest to the viewer first
        computeDistanceToCamera(children, frameState);
        children.sort(sortChildrenByDistanceToCamera);

        for (var i = 0; i < length; ++i) {
            var child = children[i];
            if (child.isContentUnloaded()) {
                requestChild(tiles3D, child);
            }
 // TODO: when we don't require all four children for refinement and we don't require top-down rendering, we can only request visible children, e.g.,
 //   (parentFullyVisible || (contentsVisible(child, frameState.cullingVolume) !== Intersect.OUTSIDE))
        }
    }

    function addCommands(tile, fullyVisible, context, frameState, commandList) {
        // There may also be a tight box around just the tile's contents, e.g., for a city, we may be
        // zoomed into a neighborhood and can cull the skyscrapers in the root node.
        if (tile.isReady() && (fullyVisible || contentsVisible(tile, frameState.cullingVolume))) {
            tile.update(context, frameState, commandList);
        }
    }

    var scratchQueue = new Queue({
        compact : false
    });

    function spatialTraverse(tiles3D, context, frameState, commandList) {
        var maximumScreenSpaceError = tiles3D.maximumScreenSpaceError;
        var cullingVolume = frameState.cullingVolume;

        var root = tiles3D._root;
        root.distanceToCamera = root.distanceToTile(frameState);

        if (getExplicitScreenSpaceError(tiles3D._geometricError, root, context, frameState) <= maximumScreenSpaceError) {
            // The SSE of not rendering the tree is small enough that the tree does not need to be rendered
            return;
        }

        if (root.isContentUnloaded()) {
            requestChild(tiles3D, root);
            return;
        }

        var queue = scratchQueue;
        queue.enqueue(root);
//console.log('---');
        while (queue.length > 0) {
            // Level-order breath-first
            var t = queue.dequeue();

            var visibility = visible(t, cullingVolume);
            var fullyVisible = (visibility === Intersect.INSIDE);
            if (visibility === Intersect.OUTSIDE) {
                // Tile is completely outside of the view frustum; therefore
                // so are all of its children.
                continue;
            }

            // Tile is inside/intersects the view frustum.  How many pixels is its geometric error?
            var sse = getScreenSpaceError(t, context, frameState);
// TODO: refine also based on (1) occlusion/VMSSE and/or (2) center of viewport

            var children = t.children;
            var childrenLength = children.length;
            var allChildrenLoaded = t.numberOfChildrenWithoutContent === 0;

            if ((sse <= maximumScreenSpaceError) || (childrenLength === 0.0)) {
                // This tile meets the SSE so add its commands.
                //
                // We also checked if the tile is a leaf (childrenLength === 0.0) for the potential case when the leaf
                // node has a non-zero geometric error, e.g., because its contents is another 3D Tiles tree.
                addCommands(t, fullyVisible, context, frameState, commandList);
//console.log(t._content._url);
            } else if (!allChildrenLoaded) {
                // Tile does not meet SSE.  Add its commands since it is the best we have and request its children.
                addCommands(t, fullyVisible, context, frameState, commandList);
//console.log(t._content._url);
                requestChildren(tiles3D, t, frameState);
            } else {
                // Tile does not meet SEE and its children are loaded.  Refine to them in front-to-back order.

                // Distance is used for sorting now and for computing SSE when the tile comes off the queue.
                computeDistanceToCamera(children, frameState);

                // Sort children by distance for (1) request ordering, and (2) early-z
                children.sort(sortChildrenByDistanceToCamera);
// TODO: is pixel size better?  Same question for requestChildren().
// TODO: consider priority queue instead of explicit sort, which would no longer be BFS, and would not average detail throughout the tree

                for (var k = 0; k < childrenLength; ++k) {
                    var child = children[k];
                    child.parentFullyVisible = fullyVisible;
                    queue.enqueue(child);
                }
            }
        }

        queue.clear();
    }

    ///////////////////////////////////////////////////////////////////////////

    function addToProcessingQueue(tiles3D, tile) {
        return function() {
            tiles3D._processingQueue.push(tile);
        };
    }

    function removeFromProcessingQueue(tiles3D, tile) {
        return function() {
            var index = tiles3D._processingQueue.indexOf(tile);
            tiles3D._processingQueue.splice(index, 1);
        };
    }

    function processTiles(tiles3D, context, frameState) {
        var tiles = tiles3D._processingQueue;
        var length = tiles.length;

        // Process tiles in the PROCESSING state so they will eventually move to the READY state.
        // Traverse backwards in case a tile is removed as a result of calling process()
        for (var i = length - 1; i >= 0; --i) {
            tiles[i].process(context, frameState);
        }
// TODO: timeslice like QuadtreePrimitive.js (but with round robin?) Or should that happen at a lower-level, e.g., models/renderer?
    }

    ///////////////////////////////////////////////////////////////////////////

    /**
     * DOC_TBA
     */
    Cesium3DTiles.prototype.update = function(context, frameState, commandList) {
        // TODO: Support 2D and CV
        if (!this.show || !defined(this._root) || (frameState.mode !== SceneMode.SCENE3D)) {
            return;
        }

        processTiles(this, context, frameState);
        spatialTraverse(this, context, frameState, commandList);
    };

    /**
     * DOC_TBA
     */
    Cesium3DTiles.prototype.isDestroyed = function() {
        return false;
    };

    /**
     * DOC_TBA
     */
    Cesium3DTiles.prototype.destroy = function() {
// TODO: traverse and destroy...careful of pending loads/processing
        return destroyObject(this);
    };

    return Cesium3DTiles;
});<commit_msg>Switch from queue to stack to get depth-first requests and render sorting<commit_after>/*global define*/
define([
        '../Core/appendForwardSlash',
        '../Core/defaultValue',
        '../Core/defined',
        '../Core/defineProperties',
        '../Core/destroyObject',
        '../Core/DeveloperError',
        '../Core/Intersect',
        '../Core/loadJson',
        '../Core/Math',
        './Cesium3DTile',
        './SceneMode',
        '../ThirdParty/when'
    ], function(
        appendForwardSlash,
        defaultValue,
        defined,
        defineProperties,
        destroyObject,
        DeveloperError,
        Intersect,
        loadJson,
        CesiumMath,
        Cesium3DTile,
        SceneMode,
        when) {
    "use strict";

    /**
     * DOC_TBA
     *
     * @param {Object} options Object with the following properties:
     * @param {String} options.url TODO
     * @param {Boolean} [options.show=true] TODO
     * @param {Boolean} [options.maximumScreenSpaceError=2] TODO
     *
     * @alias Cesium3DTiles
     * @constructor
     * @private
     */
    var Cesium3DTiles = function(options) {
        options = defaultValue(options, defaultValue.EMPTY_OBJECT);

        var url = options.url;

        //>>includeStart('debug', pragmas.debug);
        if (!defined(url)) {
            throw new DeveloperError('options.url is required.');
        }
        //>>includeEnd('debug');

        var baseUrl = appendForwardSlash(url);

        this._url = url;
        this._root = undefined;
        this._geometricError = undefined; // Geometric error when the tree is not rendered at all
// TODO: a linked list would be better depending on how how it allocates/frees.
        this._processingQueue = [];

        /**
         * DOC_TBA
         */
        this.show = defaultValue(options.show, true);

        /**
         * DOC_TBA
         */
        this.maximumScreenSpaceError = defaultValue(options.maximumScreenSpaceError, 100);

        var that = this;

        loadJson(baseUrl + 'tree.json').then(function(tree) {
            that._geometricError = tree.geometricError;
            that._root = new Cesium3DTile(baseUrl, tree.root, undefined);

            var stack = [];
            stack.push({
                skeletonTile : tree.root,
                cesium3DTile : that._root
            });

// TODO: allow skeleton tree itself to be out-of-core
            while (stack.length > 0) {
                var n = stack.pop();
                var skeletonChildren = n.skeletonTile.children;
                var length = skeletonChildren.length;
                for (var k = 0; k < length; ++k) {
                    var skeletonChild = skeletonChildren[k];
                    var cesium3DTileChild = new Cesium3DTile(baseUrl, skeletonChild, n.cesium3DTile);
                    n.cesium3DTile.children.push(cesium3DTileChild);

                    stack.push({
                        skeletonTile : skeletonChild,
                        cesium3DTile : cesium3DTileChild
                    });
                }
            }
        });
    };

    defineProperties(Cesium3DTiles.prototype, {
        /**
         * DOC_TBA
         *
         * @memberof Cesium3DTiles.prototype
         *
         * @type {String}
         * @readonly
         */
        url : {
            get : function() {
                return this._url;
            }
        }
    });

    function visible(tile, cullingVolume) {
        // Exploit temporal coherence: if a tile is completely in the view frustum
        // then so are its children so they do not need to be culled.
        if (tile.parentFullyVisible) {
            return Intersect.INSIDE;
        }

        return tile.visibility(cullingVolume);
    }

    function contentsVisible(tile, cullingVolume) {
        if (tile.parentFullyVisible) {
            return true;
        }

        return tile.contentsVisibility(cullingVolume) !== Intersect.OUTSIDE;
    }

    function getScreenSpaceError(tile, context, frameState) {
// TODO: screenSpaceError2D like QuadtreePrimitive.js
        if (tile.geometricError === 0.0) {
            // Leaf nodes do not have any error so save the computation
            return tile.geometricError;
        }

        return getExplicitScreenSpaceError(tile.geometricError, tile, context, frameState);
    }

    function getExplicitScreenSpaceError(geometricError, tile, context, frameState) {
        // Avoid divide by zero when viewer is inside the tile
        var distance = Math.max(tile.distanceToCamera, CesiumMath.EPSILON7);
        var height = context.drawingBufferHeight;
        var sseDenominator = frameState.camera.frustum.sseDenominator;

        return (geometricError * height) / (distance * sseDenominator);
    }

    function computeDistanceToCamera(children, frameState) {
        var camera = frameState.camera;
        var length = children.length;
        for (var i = 0; i < length; ++i) {
            var child = children[i];
            child.distanceToCamera = child.distanceToTile(frameState);
        }
    }

// TODO: is it worth exploiting frame-to-frame coherence in the sort?
    function sortChildrenByDistanceToCamera(a, b) {
        // Sort by farthest child first since this is going on a stack
        return b.distanceToCamera - a.distanceToCamera;
    }

    function requestChild(tiles3D, tile) {
        tile.requestContent();
        var removeFunction = removeFromProcessingQueue(tiles3D, tile);
        when(tile.processingPromise).then(addToProcessingQueue(tiles3D, tile));
        when(tile.readyPromise).then(removeFunction).otherwise(removeFunction);
    }

    function requestChildren(tiles3D, parent, frameState) {
        var children = parent.children;
        var length = children.length;

        // Sort to request tiles closest to the viewer first
        computeDistanceToCamera(children, frameState);
        children.sort(sortChildrenByDistanceToCamera);

        for (var i = 0; i < length; ++i) {
            var child = children[i];
            if (child.isContentUnloaded()) {
                requestChild(tiles3D, child);
            }
 // TODO: when we don't require all four children for refinement and we don't require top-down rendering, we can only request visible children, e.g.,
 //   (parentFullyVisible || (contentsVisible(child, frameState.cullingVolume) !== Intersect.OUTSIDE))
        }
    }

    function addCommands(tile, fullyVisible, context, frameState, commandList) {
        // There may also be a tight box around just the tile's contents, e.g., for a city, we may be
        // zoomed into a neighborhood and can cull the skyscrapers in the root node.
        if (tile.isReady() && (fullyVisible || contentsVisible(tile, frameState.cullingVolume))) {
            tile.update(context, frameState, commandList);
        }
    }

    var scratchStack = [];

    function spatialTraverse(tiles3D, context, frameState, commandList) {
        var maximumScreenSpaceError = tiles3D.maximumScreenSpaceError;
        var cullingVolume = frameState.cullingVolume;

        var root = tiles3D._root;
        root.distanceToCamera = root.distanceToTile(frameState);

        if (getExplicitScreenSpaceError(tiles3D._geometricError, root, context, frameState) <= maximumScreenSpaceError) {
            // The SSE of not rendering the tree is small enough that the tree does not need to be rendered
            return;
        }

        if (root.isContentUnloaded()) {
            requestChild(tiles3D, root);
            return;
        }

        var stack = scratchStack;
        stack.push(root);
//console.log('---');
        while (stack.length > 0) {
            // Depth first.  We want the high detail tiles first.
            var t = stack.pop();

            var visibility = visible(t, cullingVolume);
            var fullyVisible = (visibility === Intersect.INSIDE);
            if (visibility === Intersect.OUTSIDE) {
                // Tile is completely outside of the view frustum; therefore
                // so are all of its children.
                continue;
            }

            // Tile is inside/intersects the view frustum.  How many pixels is its geometric error?
            var sse = getScreenSpaceError(t, context, frameState);
// TODO: refine also based on (1) occlusion/VMSSE and/or (2) center of viewport

            var children = t.children;
            var childrenLength = children.length;
            var allChildrenLoaded = t.numberOfChildrenWithoutContent === 0;

            if ((sse <= maximumScreenSpaceError) || (childrenLength === 0.0)) {
                // This tile meets the SSE so add its commands.
                //
                // We also checked if the tile is a leaf (childrenLength === 0.0) for the potential case when the leaf
                // node has a non-zero geometric error, e.g., because its contents is another 3D Tiles tree.
                addCommands(t, fullyVisible, context, frameState, commandList);
//console.log(t._content._url);
            } else if (!allChildrenLoaded) {
                // Tile does not meet SSE.  Add its commands since it is the best we have and request its children.
                addCommands(t, fullyVisible, context, frameState, commandList);
//console.log(t._content._url);
                requestChildren(tiles3D, t, frameState);
            } else {
                // Tile does not meet SEE and its children are loaded.  Refine to them in front-to-back order.

                // Distance is used for sorting now and for computing SSE when the tile comes off the stack.
                computeDistanceToCamera(children, frameState);

                // Sort children by distance for (1) request ordering, and (2) early-z
                children.sort(sortChildrenByDistanceToCamera);
// TODO: is pixel size better?  Same question for requestChildren().
// TODO: consider priority queue instead of explicit sort, which would no longer be BFS, and would not average detail throughout the tree

                for (var k = 0; k < childrenLength; ++k) {
                    var child = children[k];
                    child.parentFullyVisible = fullyVisible;
                    stack.push(child);
                }
            }
        }

        if (stack.length !== 0) {
            debugger;
        }
    }

    ///////////////////////////////////////////////////////////////////////////

    function addToProcessingQueue(tiles3D, tile) {
        return function() {
            tiles3D._processingQueue.push(tile);
        };
    }

    function removeFromProcessingQueue(tiles3D, tile) {
        return function() {
            var index = tiles3D._processingQueue.indexOf(tile);
            tiles3D._processingQueue.splice(index, 1);
        };
    }

    function processTiles(tiles3D, context, frameState) {
        var tiles = tiles3D._processingQueue;
        var length = tiles.length;

        // Process tiles in the PROCESSING state so they will eventually move to the READY state.
        // Traverse backwards in case a tile is removed as a result of calling process()
        for (var i = length - 1; i >= 0; --i) {
            tiles[i].process(context, frameState);
        }
// TODO: timeslice like QuadtreePrimitive.js (but with round robin?) Or should that happen at a lower-level, e.g., models/renderer?
    }

    ///////////////////////////////////////////////////////////////////////////

    /**
     * DOC_TBA
     */
    Cesium3DTiles.prototype.update = function(context, frameState, commandList) {
        // TODO: Support 2D and CV
        if (!this.show || !defined(this._root) || (frameState.mode !== SceneMode.SCENE3D)) {
            return;
        }

        processTiles(this, context, frameState);
        spatialTraverse(this, context, frameState, commandList);
    };

    /**
     * DOC_TBA
     */
    Cesium3DTiles.prototype.isDestroyed = function() {
        return false;
    };

    /**
     * DOC_TBA
     */
    Cesium3DTiles.prototype.destroy = function() {
// TODO: traverse and destroy...careful of pending loads/processing
        return destroyObject(this);
    };

    return Cesium3DTiles;
});<|endoftext|>


<commit_before>var ForecastIo = require('forecastio');

var forecastIo = new ForecastIo('ce1e9e7c47068378251586a90ecb14cd');
forecastIo.forecast('47.8669', -121.6780).then(function(data) {
  console.log(JSON.stringify(data, null, 2));
});
<commit_msg>output rain chance<commit_after>const ForecastIo = require('forecastio');
const fs = require('fs');

var forecastIo = new ForecastIo('ce1e9e7c47068378251586a90ecb14cd');
forecastIo.forecast('47.8669', -121.6780).then(function(data) {
  var jsonString = JSON.stringify((data) , null, 2);
  var parsed = JSON.parse(jsonString);
  console.log(parsed);
});

<|endoftext|>


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

angular.module("neonDemo.services")
.factory("FilterService",
    function() {
        var service = {};

        /**
         * Creates and returns a mapping of names from the given tables to unique filter keys for each table.
         * @param {String} The name of the visualization
         * @param {Array} The array of table objects
         * @method createFilterKeys
         * @return {Object} The mapping of table names to filter keys
         */
        service.createFilterKeys = function(visualizationName, tables) {
            var filterKeys = {};
            for(var i = 0; i < tables.length; ++i) {
                filterKeys[tables[i].name] = visualizationName + "-" + tables[i].name + "-" + uuid();
            }
            return filterKeys;
        };

        /**
         * Returns the list of field names or arrays based on the data contained within the map of fields in the given relation to be used by a filter clause
         * creation function.
         * @param {Object} relation A relation object containing a map of field names to arrays of related field names
         * @method getArgumentFieldsList
         * @return {Array} A list of {String} related field names if the map of field names in the given relation object only contains one field name key;
         * otherwise, a list of {Array} lists of {String} related field names representing each combination of the different field name keys.  Either way, the
         * elements of this list will be used to call the filter clause creation functions in filterService.createFilter() below.
         */
        service.getArgumentFieldsList = function(relation) {
            // The relation will contain each field used by the filter clause creation function mapped to a list of the related fields for that field.
            // Note:  Sort the keys so, if multiple fields exist, the filter clause creation function can expect them in alphabetical order.
            var fieldNames = Object.keys(relation.fields).sort();

            // If only one field is used by the filter clause creation function, just return the list of related fields for that field.
            if(fieldNames.length === 1) {
                return relation.fields[fieldNames[0]];
            }

            // Else we need to create a list of all combinations of the related fields.  First, create a list containing all the lists of related fields.
            var relationFieldsList = [];
            for(var i = 0; i < fieldNames.length; ++i) {
                relationFieldsList.push(relation.fields[fieldNames[i]]);
            }

            // Create a list of arguments representing the fields using all combinations of the related fields.
            var getArgumentFieldsListHelper = function(unfinishedArgumentFields, unusedRelationFields) {
                var argumentFieldsList = [];
                // Iterate over each element (list) in the first unused relation field.
                for(var i = 0; i < unusedRelationFields[0].length; ++i) {
                    // Clone the unfinished arguments array and append the current unused relation field element.
                    var fields = unfinishedArgumentFields.slice(0);
                    fields.push(unusedRelationFields[0][i]);

                    if(unusedRelationFields.length === 1) {
                        // If there are no more unused relation fields, we have finished creating this arguments array.
                        argumentFieldsList.push(fields);
                    } else {
                        // Else, get the next element for the arguments array from the next unused relation field.
                        argumentFieldsList = argumentFieldsList.concat(getArgumentFieldsListHelper(fields, unusedRelationFields.slice(1)));
                    }
                }
                return argumentFieldsList;
            };

            return getArgumentFieldsListHelper([], relationFieldsList);
        };

        /**
         * Creates and returns a filter on the given table and field(s) using the given callback.
         * @param {Object} relation A relation object containing:
         *

         *
 {String} database The database name

         *
 {Stirng} table The table name

         *
 {Object} fields The map of field names to arrays of related field names

         *

         * @param {Function} createFilterClauseFunction The function used to create the filter clause for each field name in the given array
         * @method createFilter
         * @return {Object} A neon.query.Filter object
         */
        service.createFilter = function(relation, createFilterClauseFunction) {
            // Creates a list of arguments for the filter clause creation function.  Each element is either a {String} or an {Array} depending on the number
            // of field keys in relation.fields.
            var argumentFieldsList = service.getArgumentFieldsList(relation);

            var filterClause;
            if(argumentFieldsList.length === 1) {
                filterClause = createFilterClauseFunction(relation.table, argumentFieldsList[0]);
            } else {
                var filterClauses = [];
                for(var i = 0; i < argumentFieldsList.length; ++i) {
                    filterClauses.push(createFilterClauseFunction(relation.table, argumentFieldsList[i]));
                }
                filterClause = neon.query.or.apply(neon.query, filterClauses);
            }
            return new neon.query.Filter().selectFrom(relation.database, relation.table).where(filterClause);
        };

        /**
         * Adds filters for the given relations using the given filter keys.
         * @param {Object} messenger The messenger object used to add the filters
         * @param {Array} relations The array of relations containing a database name, a table name, and a map of fields
         * @param {Object} filterKeys The map of table names to filter keys used by the messenger
         * @param {Function} createFilterClauseFunction The function used to create the filter clause with arguments for the table name and field name(s)
         * @param {Function} successCallback The function called once all the filters have been added (optional)
         * @param {Function} errorCallback The function called if an error is returned for any of the filter calls (optional)
         * @method addFilters
         */
        service.addFilters = function(messenger, relations, filterKeys, createFilterClauseFunction, successCallback, errorCallback) {
            var addFilter = function(relationsToAdd) {
                var relation = relationsToAdd.shift();
                var filter = service.createFilter(relation, createFilterClauseFunction);
                messenger.addFilter(filterKeys[relation.table], filter, function() {
                    if(relationsToAdd.length) {
                        addFilter(relationsToAdd);
                    } else if(successCallback) {
                        successCallback();
                    }
                }, errorCallback);
            };

            addFilter(relations);
        };

        /**
         * Replaces filters for the given relations using the given filter keys.
         * @param {Object} messenger The messenger object used to replace the filters
         * @param {Array} relations The array of relations containing a database name, a table name, and a map of fields
         * @param {Object} filterKeys The map of table names to filter keys used by the messenger
         * @param {Function} createFilterClauseFunction The function used to create the filter clause with arguments for the table name and field name(s)
         * @param {Function} successFunction The function called once all the filters have been replaced (optional)
         * @param {Function} errorFunction The function called if an error is returned for any of the filter calls (optional)
         * @method replaceFilters
         */
        service.replaceFilters = function(messenger, relations, filterKeys, createFilterClauseFunction, successCallback, errorCallback) {
            var replaceFilter = function(relationsToReplace) {
                var relation = relationsToReplace.shift();
                var filter = service.createFilter(relation, createFilterClauseFunction);
                messenger.replaceFilter(filterKeys[relation.table], filter, function() {
                    if(relationsToReplace.length) {
                        replaceFilter(relationsToReplace);
                    } else if(successCallback) {
                        successCallback();
                    }
                }, errorCallback);
            };

            replaceFilter(relations);
        };

        /**
         * Removes filters for all the given filter keys.
         * @param {Object} messenger The messenger object used to remove the filters
         * @param {Object} filterKeys The map of table names to filter keys used by the messenger
         * @param {Function} successCallback The function called once all the filters have been removed (optional)
         * @param {Function} errorCallback The function called if an error is returned for any of the filter calls (optional)
         * @method removeFilters
         */
        service.removeFilters = function(messenger, filterKeys, successCallback, errorCallback) {
            var removeFilter = function(filterKeysToRemove) {
                var filterKey = filterKeysToRemove.shift();
                messenger.removeFilter(filterKey, function() {
                    if(filterKeysToRemove.length) {
                        removeFilter(filterKeysToRemove);
                    } else if(successCallback) {
                        successCallback();
                    }
                }, errorCallback);
            };

            var tableNames = Object.keys(filterKeys);
            var filterKeysToRemove = [];
            for(var i = 0; i < tableNames.length; ++i) {
                filterKeysToRemove.push(filterKeys[tableNames[i]]);
            }

            removeFilter(filterKeysToRemove);
        };

        return service;
    }
);
<commit_msg>NEON-1440 Clarified the header documentation for functions in the filter service as recommended during our code review.<commit_after>'use strict';
/*
 * Copyright 2015 Next Century Corporation
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

angular.module("neonDemo.services")
.factory("FilterService",
    function() {
        var service = {};

        /**
         * Creates and returns a mapping of names from the given tables to unique filter keys for each table.
         * @param {String} The name of the visualization
         * @param {Array} The array of table objects
         * @method createFilterKeys
         * @return {Object} The mapping of table names to filter keys
         */
        service.createFilterKeys = function(visualizationName, tables) {
            var filterKeys = {};
            for(var i = 0; i < tables.length; ++i) {
                filterKeys[tables[i].name] = visualizationName + "-" + tables[i].name + "-" + uuid();
            }
            return filterKeys;
        };

        /**
         * Returns the list of field names or arrays based on the data contained within the map of fields in the given relation to be used by a filter clause
         * creation function.
         * @param {Object} relation A relation object containing a map of field names to arrays of related field names
         * @method getArgumentFieldsList
         * @return {Array} A list of {String} related field names if the map of field names in the given relation object only contains one field name key;
         * otherwise, a list of {Array} lists of {String} related field names representing each combination of the different field name keys.  Either way, the
         * elements of this list will be used to call the filter clause creation functions in filterService.createFilter() below.
         */
        service.getArgumentFieldsList = function(relation) {
            // The relation will contain each field used by the filter clause creation function mapped to a list of the related fields for that field.
            // Note:  Sort the keys so, if multiple fields exist, the filter clause creation function can expect them in alphabetical order.
            var fieldNames = Object.keys(relation.fields).sort();

            // If only one field is used by the filter clause creation function, just return the list of related fields for that field.
            if(fieldNames.length === 1) {
                return relation.fields[fieldNames[0]];
            }

            // Else we need to create a list of all combinations of the related fields.  First, create a list containing all the lists of related fields.
            var relationFieldsList = [];
            for(var i = 0; i < fieldNames.length; ++i) {
                relationFieldsList.push(relation.fields[fieldNames[i]]);
            }

            // Create a list of arguments representing the fields using all combinations of the related fields.
            var getArgumentFieldsListHelper = function(unfinishedArgumentFields, unusedRelationFields) {
                var argumentFieldsList = [];
                // Iterate over each element (list) in the first unused relation field.
                for(var i = 0; i < unusedRelationFields[0].length; ++i) {
                    // Clone the unfinished arguments array and append the current unused relation field element.
                    var fields = unfinishedArgumentFields.slice(0);
                    fields.push(unusedRelationFields[0][i]);

                    if(unusedRelationFields.length === 1) {
                        // If there are no more unused relation fields, we have finished creating this arguments array.
                        argumentFieldsList.push(fields);
                    } else {
                        // Else, get the next element for the arguments array from the next unused relation field.
                        argumentFieldsList = argumentFieldsList.concat(getArgumentFieldsListHelper(fields, unusedRelationFields.slice(1)));
                    }
                }
                return argumentFieldsList;
            };

            return getArgumentFieldsListHelper([], relationFieldsList);
        };

        /**
         * Creates and returns a filter on the given table and field(s) using the given callback.
         * @param {Object} relation A relation object containing:
         *

         *
 {String} database The database name

         *
 {Stirng} table The table name

         *
 {Object} fields The map of field names to arrays of related field names

         *

         * @param {Function} createFilterClauseFunction The function used to create the filter clause for each field, with arguments:
         *

         *
 {String} The table name

         *
 {String} or {Array} The field name(s)

         *

         * @method createFilter
         * @return {Object} A neon.query.Filter object
         */
        service.createFilter = function(relation, createFilterClauseFunction) {
            // Creates a list of arguments for the filter clause creation function.  Each element is either a {String} or an {Array} depending on the number
            // of field keys in relation.fields.
            var argumentFieldsList = service.getArgumentFieldsList(relation);

            var filterClause;
            if(argumentFieldsList.length === 1) {
                filterClause = createFilterClauseFunction(relation.table, argumentFieldsList[0]);
            } else {
                var filterClauses = [];
                for(var i = 0; i < argumentFieldsList.length; ++i) {
                    filterClauses.push(createFilterClauseFunction(relation.table, argumentFieldsList[i]));
                }
                filterClause = neon.query.or.apply(neon.query, filterClauses);
            }
            return new neon.query.Filter().selectFrom(relation.database, relation.table).where(filterClause);
        };

        /**
         * Adds filters for the given relations using the given filter keys.
         * @param {Object} messenger The messenger object used to add the filters
         * @param {Array} relations The array of relations containing a database name, a table name, and a map of fields
         * @param {Object} filterKeys The map of table names to filter keys used by the messenger
         * @param {Function} createFilterClauseFunction The function used to create the filter clause for each field, with arguments:
         *

         *
 {String} The table name

         *
 {String} or {Array} The field name(s)

         *

         * @param {Function} successCallback The function called once all the filters have been added (optional)
         * @param {Function} errorCallback The function called if an error is returned for any of the filter calls (optional)
         * @method addFilters
         */
        service.addFilters = function(messenger, relations, filterKeys, createFilterClauseFunction, successCallback, errorCallback) {
            var addFilter = function(relationsToAdd) {
                var relation = relationsToAdd.shift();
                var filter = service.createFilter(relation, createFilterClauseFunction);
                messenger.addFilter(filterKeys[relation.table], filter, function() {
                    if(relationsToAdd.length) {
                        addFilter(relationsToAdd);
                    } else if(successCallback) {
                        successCallback();
                    }
                }, errorCallback);
            };

            addFilter(relations);
        };

        /**
         * Replaces filters for the given relations using the given filter keys.
         * @param {Object} messenger The messenger object used to replace the filters
         * @param {Array} relations The array of relations containing a database name, a table name, and a map of fields
         * @param {Object} filterKeys The map of table names to filter keys used by the messenger
         * @param {Function} createFilterClauseFunction The function used to create the filter clause for each field, with arguments:
         *

         *
 {String} The table name

         *
 {String} or {Array} The field name(s)

         *

         * @param {Function} successFunction The function called once all the filters have been replaced (optional)
         * @param {Function} errorFunction The function called if an error is returned for any of the filter calls (optional)
         * @method replaceFilters
         */
        service.replaceFilters = function(messenger, relations, filterKeys, createFilterClauseFunction, successCallback, errorCallback) {
            var replaceFilter = function(relationsToReplace) {
                var relation = relationsToReplace.shift();
                var filter = service.createFilter(relation, createFilterClauseFunction);
                messenger.replaceFilter(filterKeys[relation.table], filter, function() {
                    if(relationsToReplace.length) {
                        replaceFilter(relationsToReplace);
                    } else if(successCallback) {
                        successCallback();
                    }
                }, errorCallback);
            };

            replaceFilter(relations);
        };

        /**
         * Removes filters for all the given filter keys.
         * @param {Object} messenger The messenger object used to remove the filters
         * @param {Object} filterKeys The map of table names to filter keys used by the messenger
         * @param {Function} successCallback The function called once all the filters have been removed (optional)
         * @param {Function} errorCallback The function called if an error is returned for any of the filter calls (optional)
         * @method removeFilters
         */
        service.removeFilters = function(messenger, filterKeys, successCallback, errorCallback) {
            var removeFilter = function(filterKeysToRemove) {
                var filterKey = filterKeysToRemove.shift();
                messenger.removeFilter(filterKey, function() {
                    if(filterKeysToRemove.length) {
                        removeFilter(filterKeysToRemove);
                    } else if(successCallback) {
                        successCallback();
                    }
                }, errorCallback);
            };

            var tableNames = Object.keys(filterKeys);
            var filterKeysToRemove = [];
            for(var i = 0; i < tableNames.length; ++i) {
                filterKeysToRemove.push(filterKeys[tableNames[i]]);
            }

            removeFilter(filterKeysToRemove);
        };

        return service;
    }
);
<|endoftext|>


<commit_before>'use strict'
const _ = require('lodash')
const smokesignals = require('smokesignals')
const fs = require('fs')

const packs = [
  require('trailpack-router'),
  require('trailpack-express'),
  require('../') // trailpack-stripe
]

const ORM = process.env.ORM || 'sequelize'

const stores = {
  sqlitedev: {
    adapter: require('sails-disk')
  }
}

if (ORM === 'waterline') {
  packs.push(require('trailpack-waterline'))
}
else if (ORM === 'js-data') {
  packs.push(require('trailpack-js-data'))
  stores.sqlitedev = {
    database: 'dev',
    storage: './.tmp/jsdata.sqlite',
    host: '127.0.0.1',
    dialect: 'sqlite'
  }
}
else if (ORM === 'sequelize') {
  packs.push(require('trailpack-sequelize'))
  stores.sqlitedev = {
    database: 'dev',
    storage: './.tmp/sequelize.sqlite',
    host: '127.0.0.1',
    dialect: 'sqlite'
  }
}

const App = {
  pkg: {
    name: 'stripe-trailpack-test',
    version: '1.0.0'
  },
  api: {
    controllers: {
      DefaultController: class DefaultController extends require('trails-controller') {
        info(req, res){
          res.send('ok')
        }
      }
    }
  },
  config: {
    database: {
      stores: stores,
      models: {
        defaultStore: 'sqlitedev',
        migrate: 'drop'
      }
    },
    stripe: {
      public: 'test',
      secret: 'test',
      validate: 'false'
    },
    main: {
      packs: packs
    },
    routes: [{
      path: '/',
      method: ['GET'],
      handler: 'DefaultController.info'
    }],
    policies: {

    },
    web: {
      express: require('express'),
      middlewares: {
        order: [
          'addMethods',
          'cookieParser',
          'session',
          'bodyParser',
          'passportInit',
          'passportSession',
          'methodOverride',
          'router',
          'www',
          '404',
          '500'
        ]
      }
    }
  }
}
const dbPath = __dirname + '/../.tmp/sqlitedev.db'
if (fs.existsSync(dbPath))
  fs.unlinkSync(dbPath)

_.defaultsDeep(App, smokesignals.FailsafeConfig)
module.exports = App
<commit_msg>Last part of 2.0<commit_after>'use strict'
const _ = require('lodash')
const smokesignals = require('smokesignals')
const fs = require('fs')

const packs = [
  require('trailpack-router'),
  require('trailpack-express'),
  require('../') // trailpack-stripe
]

const ORM = process.env.ORM || 'sequelize'

const stores = {
  sqlitedev: {
    adapter: require('sails-disk')
  }
}

if (ORM === 'waterline') {
  packs.push(require('trailpack-waterline'))
}
else if (ORM === 'js-data') {
  packs.push(require('trailpack-js-data'))
  stores.sqlitedev = {
    database: 'dev',
    storage: './.tmp/jsdata.sqlite',
    host: '127.0.0.1',
    dialect: 'sqlite'
  }
}
else if (ORM === 'sequelize') {
  packs.push(require('trailpack-sequelize'))
  stores.sqlitedev = {
    database: 'dev',
    storage: './.tmp/sequelize.sqlite',
    host: '127.0.0.1',
    dialect: 'sqlite'
  }
}

const App = {
  pkg: {
    name: 'stripe-trailpack-test',
    version: '1.0.0'
  },
  api: {
    controllers: {
      DefaultController: class DefaultController extends require('trails/controller') {
        info(req, res){
          res.send('ok')
        }
      }
    }
  },
  config: {
    database: {
      stores: stores,
      models: {
        defaultStore: 'sqlitedev',
        migrate: 'drop'
      }
    },
    stripe: {
      public: 'test',
      secret: 'test',
      validate: 'false'
    },
    main: {
      packs: packs
    },
    routes: [{
      path: '/',
      method: ['GET'],
      handler: 'DefaultController.info'
    }],
    policies: {

    },
    web: {
      express: require('express'),
      middlewares: {
        order: [
          'addMethods',
          'cookieParser',
          'session',
          'bodyParser',
          'passportInit',
          'passportSession',
          'methodOverride',
          'router',
          'www',
          '404',
          '500'
        ]
      }
    }
  }
}
const dbPath = __dirname + '/../.tmp/sqlitedev.db'
if (fs.existsSync(dbPath))
  fs.unlinkSync(dbPath)

_.defaultsDeep(App, smokesignals.FailsafeConfig)
module.exports = App
<|endoftext|>


<commit_before>function injectViewportMetaTag() {
  var meta = $(document.createElement('meta'));
  meta.name = 'viewport';
  meta.content = 'width=450';
  $$('head')[0].insert(meta);
};

ProjectMenuBuilder = {
  buildMenuItem: function(project) {
    var link = $(document.createElement('a'));
    link.href = project.url;
    link.innerHTML = project.name;
    if (project.selected) {
      link.addClassName('selected');
    };
    var li = $(document.createElement('li'));
    li.appendChild(link);

    return li;
  },

  buildList: function(projectSelector) {
    var projects = ProjectMenuBuilder.getProjects(projectSelector);
    var projectList = $(document.createElement('ul'));
    projectList.addClassName('projects');
    projectList.setStyle({ display: 'none' });

    projects.each(function(project, index) {
      projectList.appendChild(ProjectMenuBuilder.buildMenuItem(project));
    });

    return projectList;
  },

  buildProjectSelector: function(selectElement) {
    var selector = $(document.createElement('div'));
    selector.addClassName('project_selector');

    var title = ProjectMenuBuilder.getTitle(selectElement);
    selector.appendChild(ProjectMenuBuilder.buildToggle(title));

    var projectList = ProjectMenuBuilder.buildList(selectElement);
    selector.appendChild(projectList);

    return selector;
  },

  buildToggle: function(title) {
    var toggle = $(document.createElement('a'));
    toggle.href = '#'; // Makes it behave like a real link
    toggle.addClassName('toggle');
    toggle.title = title;
    toggle.innerHTML = toggle.title.replace('...', '…');

    return toggle;
  },

  getProjects: function(element) {
    var projectOptions = element.getElementsBySelector('option[value!=""]');
    return projectOptions.collect(function(node) {
      return {
        url: node.value,
        name: node.innerHTML,
        selected: node.readAttribute('selected') == 'selected'
      };
    });
  },

  getTitle: function(element) {
    var title = element.childElements().first().innerHTML;
    return title;
  },

  bindEvents: function(selector) {
    // Hook up events
    selector.toggleProjects = function() {
      $(this).down('.projects').toggle();
      $(this).down('.toggle').toggleClassName('active');
    };

    // Display the project dropdown when the toggle is clicked
    selector.down('.toggle').observe('click', function(event) {
      selector.toggleProjects();
      event.stop();
    });

    // Hide the dropdown again a short while after we've moved the mouse away
    selector.down('.projects').observe('mouseout', function(event) {
      selector.toggleTimer = new PeriodicalExecuter(function(pe) {
        selector.toggleProjects();
        pe.stop();
      }, 1);
    });

    // Cancel the timer to hide the dropdown if we move the mouse back over the menu
    selector.down('.projects').observe('mouseover', function(event) {
      if (selector.toggleTimer) {
        selector.toggleTimer.stop();
      };
    });
  },

  // Creates a menu with links to all the users projects and adds it next to the project name
  moveProjectSelectorToProjectName: function(projectSelector, projectName) {
    if (!projectSelector || !projectName) {
      return false;
    }

    var selector = ProjectMenuBuilder.buildProjectSelector(projectSelector);
    ProjectMenuBuilder.bindEvents(selector);

    // Insert the project selector after the project name
    projectName.insert({ after: selector });

    // Remove the original select list
    projectSelector.hide();
  }
};

document.observe("dom:loaded", function() {
  ProjectMenuBuilder.moveProjectSelectorToProjectName(
    $$('#quick-search select').first(),
    $$('#header h1').first()
  );
  injectViewportMetaTag();
});

<commit_msg>Be explicit about hiding and showing to project selector menu<commit_after>function injectViewportMetaTag() {
  var meta = $(document.createElement('meta'));
  meta.name = 'viewport';
  meta.content = 'width=450';
  $$('head')[0].insert(meta);
};

ProjectMenuBuilder = {
  buildMenuItem: function(project) {
    var link = $(document.createElement('a'));
    link.href = project.url;
    link.innerHTML = project.name;
    if (project.selected) {
      link.addClassName('selected');
    };
    var li = $(document.createElement('li'));
    li.appendChild(link);

    return li;
  },

  buildList: function(projectSelector) {
    var projects = ProjectMenuBuilder.getProjects(projectSelector);
    var projectList = $(document.createElement('ul'));
    projectList.addClassName('projects');
    projectList.setStyle({ display: 'none' });

    projects.each(function(project, index) {
      projectList.appendChild(ProjectMenuBuilder.buildMenuItem(project));
    });

    return projectList;
  },

  buildProjectSelector: function(selectElement) {
    var selector = $(document.createElement('div'));
    selector.addClassName('project_selector');

    var title = ProjectMenuBuilder.getTitle(selectElement);
    selector.appendChild(ProjectMenuBuilder.buildToggle(title));

    var projectList = ProjectMenuBuilder.buildList(selectElement);
    selector.appendChild(projectList);

    return selector;
  },

  buildToggle: function(title) {
    var toggle = $(document.createElement('a'));
    toggle.href = '#'; // Makes it behave like a real link
    toggle.addClassName('toggle');
    toggle.title = title;
    toggle.innerHTML = toggle.title.replace('...', '…');

    return toggle;
  },

  getProjects: function(element) {
    var projectOptions = element.getElementsBySelector('option[value!=""]');
    return projectOptions.collect(function(node) {
      return {
        url: node.value,
        name: node.innerHTML,
        selected: node.readAttribute('selected') == 'selected'
      };
    });
  },

  getTitle: function(element) {
    var title = element.childElements().first().innerHTML;
    return title;
  },

  // Hook up events
  bindEvents: function(selector) {
    selector.toggleProjects = function() {
      if ($(this).down('.projects').visible()) {
        this.hideProjects();
      } else {
        this.showProjects();
      };
    };

    selector.hideProjects = function() {
      $(this).down('.projects').hide()
      $(this).down('.toggle').removeClassName('active');
    };

    selector.showProjects = function() {
      $(this).down('.projects').show();
      $(this).down('.toggle').addClassName('active');
    };

    // Display the project dropdown when the toggle is clicked
    selector.down('.toggle').observe('click', function(event) {
      selector.toggleProjects();
      event.stop();
    });

    // Hide the dropdown again a short while after we've moved the mouse away
    selector.down('.projects').observe('mouseout', function(event) {
      selector.toggleTimer = new PeriodicalExecuter(function(pe) {
        selector.hideProjects();
        pe.stop();
      }, 1);
    });

    // Cancel the timer to hide the dropdown if we move the mouse back over the menu
    selector.down('.projects').observe('mouseover', function(event) {
      if (selector.toggleTimer) {
        selector.toggleTimer.stop();
      };
    });
  },

  // Creates a menu with links to all the users projects and adds it next to the project name
  moveProjectSelectorToProjectName: function(projectSelector, projectName) {
    if (!projectSelector || !projectName) {
      return false;
    }

    var selector = ProjectMenuBuilder.buildProjectSelector(projectSelector);
    ProjectMenuBuilder.bindEvents(selector);

    // Insert the project selector after the project name
    projectName.insert({ after: selector });

    // Remove the original select list
    projectSelector.hide();
  }
};

document.observe("dom:loaded", function() {
  ProjectMenuBuilder.moveProjectSelectorToProjectName(
    $$('#quick-search select').first(),
    $$('#header h1').first()
  );
  injectViewportMetaTag();
});

<|endoftext|>


<commit_before>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();
    console.log("entre amigo", map)

  } else {
    console.log("entre mapaboxs");
    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.marker_map = function(from, to, map){
    console.log("mapa from ->", from);
    console.log("mapa to ->", to);
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    //L.marker([37.35337508231001,-121.93626880645752], {icon: IconStart}).bindPopup('From').addTo(map);
    //L.marker([37.44377324953697,-122.16601610183714], {icon: IconEnd}).bindPopup('to').addTo(map);
    var markerform = new L.marker([from[0],from[1]], {icon: IconStart}).bindPopup('From').addTo(map);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd}).bindPopup('to').addTo(map);

    this.polyline_creadas.push(markerform);
    this.polyline_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    console.log("mapa point to ->", to);
    var name = to[2];

        var circle =
            L.circle([to[0], to[1]], {
            radius: 5,
            fillColor: "#ff7800",
            color: "#000",
            weight: 1,
            opacity: 1,
            fillOpacity: 0.8
        }).addTo(map);

    //L.animatedMarker([to[0], to[1]], 20, {
    //    color: '#000',
    //    fillColor: '#ffffff',
    //    fillOpacity: 1
    //}).addTo(map);

    this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(route,mode) {
      var color = '#000';
      var weight = 5;
      var dasharray= '';
        console.log("imprime mode ->", mode);
        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }
        else if(mode=="BUS") {
            color = '#FEF0B5';
             weight = 8;
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
        console.log("pintamos datos ->", this.polyline_creadas);
        //module.exports.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var bounds = new L.LatLngBounds([]);
      var boxpolys = new Array(boxes.length);

      for (var i = 0; i < boxes.length; i++) {
        bounds.extend(boxes[i]);
      }
      route.addTo(this.activeMap);
      this.activeMap.fitBounds(bounds);
};

<commit_msg>adding console<commit_after>var config = require('config');
var mapModule = require('map');
var plugins = require('./leaflet_plugins');
var polyUtil = require('./polyline_encoded.js');
var routeboxer = require('./leaflet_routeboxer.js');

var center = config.geocode().center.split(',').map(parseFloat)
if (config.map_provider && config.map_provider() !== 'AmigoCloud') {
  L.mapbox.accessToken = config.mapbox_access_token();
}

module.exports = function(el) {
  var map, realtime, southWest, northEast, blurLayer;

  if (config.map_provider && config.map_provider() === 'AmigoCloud') {
    southWest = L.latLng(35.946877085397,-123.480610897013);
    northEast = L.latLng(40.763279543715,-118.789317362500);
    map = (new L.amigo.map(el, {
      amigoLogo: 'right',
      loadAmigoLayers: false,
      inertia: false,
      zoomAnimation: $('.hide-map').css('display') !== 'none',
      maxBounds: L.latLngBounds(southWest, northEast),
      minZoom: 8
    })).setView([center[1], center[0]], config.geocode().zoom);

    L.amigo.auth.setToken(config.support_data_token());

    blurLayer = L.tileLayer(
    'https://www.amigocloud.com/api/v1/users/'+
	'23/projects/3019/datasets/23835/tiles/{z}/{x}/{y}.png?' +
	'token=' + config.support_data_token(),
      {
        name: 'Uncovered Area'
      }
    );

    map.addAuthLayer({
      id: config.mapbox_map_id(),
      accessToken: config.mapbox_access_token(),
      name: 'Gray',
      provider: 'mapbox'
    });
    map.addBaseLayer(L.amigo.AmigoGray);
    map.layersControl.addBaseLayer(
      L.bingLayer(
        config.bing_key(),
	{
	  type: 'Road',
	  attribution: 'Bing Maps'
	}
      ),
      'Bing Road'
    );
    map.layersControl.addOverlay(blurLayer);
    blurLayer.addTo(map);

    module.exports.activeMap = map;

    map.realtimeControl = L.control.toggleRealTime().addTo(map);

    realtime = mapModule.realtime();
    console.log("entre amigo", map)

  } else {
    console.log("entre mapaboxs");
    map = L.mapbox.map(el, config.mapbox_map_id(), {
      attributionControl: false,
      inertia: false,
      zoomAnimation: false
    }).setView([center[1], center[0]], config.geocode().zoom);
  }

  return map;
};

module.exports.getMap = function () {
  return this.activeMap;
};

module.exports.cleanRoute = function() {
    module.exports.activeRoute.removeLayer();
    module.exports.activeRoute = null;
};

module.exports.polyline_creadas = [];

module.exports.getpolyline_creadas = function () {
  return this.polyline_creadas;
};

module.exports.marker_map = function(from, to, map){
    console.log("mapa from ->", from);
    console.log("mapa to ->", to);
     var IconStart = L.icon({
        iconUrl: 'assets/images/graphics/start.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });
    var IconEnd = L.icon({
        iconUrl: 'assets/images/graphics/end.svg',
        iconSize: [40, 55],
        iconAnchor: [20, 50],
        popupAnchor:  [0, -50]
    });

    //L.marker([37.35337508231001,-121.93626880645752], {icon: IconStart}).bindPopup('From').addTo(map);
    //L.marker([37.44377324953697,-122.16601610183714], {icon: IconEnd}).bindPopup('to').addTo(map);
    var markerform = new L.marker([from[0],from[1]], {icon: IconStart}).bindPopup('From').addTo(map);
    var markerto = new L.marker([to[0],to[1]], {icon: IconEnd}).bindPopup('to').addTo(map);

    this.polyline_creadas.push(markerform);
    this.polyline_creadas.push(markerto);
};

module.exports.marker_map_point = function(to, map){

    console.log("mapa point to ->", to);
    var name = to[2];

        //var circle =
        //    L.circle([to[0], to[1]], {
        //    radius: 5,
        //    fillColor: "#ff7800",
        //    color: "#000",
        //    weight: 1,
        //    opacity: 1,
        //    fillOpacity: 0.8
        //}).addTo(map);

    L.circle([to[0], to[1]], 20, {
        color: '#000',
        fillColor: '#ff7800',
        fillOpacity: 1
    }).bindPopup(name).addTo(map);

    this.polyline_creadas.push(circle);
};

module.exports.drawRouteAmigo = function(route,mode) {
      var color = '#000';
      var weight = 5;
      var dasharray= '';
        console.log("imprime mode ->", mode);
        if (mode=="CAR") {
            color = '#9E9E9E';
            dasharray= '6';
            weight = 3;

        }else if(mode=="BICYCLE") {
            color = '#FF0000';
            dasharray= '6';
            weight = 3;

        }else if(mode=="SUBWAY" || mode=="RAIL") {
            color = '#FF0000';
             weight = 8;

        }
        else if(mode == "WALK") {
            color = '#0BC8F4';
            dasharray= '6';
             weight = 3;
        }
        else if(mode=="BUS") {
            color = '#FEF0B5';
             weight = 8;
        }

       var color_options = {
            color: color,
            opacity: 1,
            weight: weight,
            dashArray: dasharray
        };

      route = new L.Polyline(L.PolylineUtil.decode(route, 5), color_options);
      this.polyline_creadas.push(route);
        console.log("pintamos datos ->", this.polyline_creadas);
        //module.exports.polyline_creadas.push(route);
      var boxes = L.RouteBoxer.box(route, 5);
      var bounds = new L.LatLngBounds([]);
      var boxpolys = new Array(boxes.length);

      for (var i = 0; i < boxes.length; i++) {
        bounds.extend(boxes[i]);
      }
      route.addTo(this.activeMap);
      this.activeMap.fitBounds(bounds);
};

<|endoftext|>