<commit_before>describe('iD.svgMidpoints', function () {
    var context, surface,
        projection = d3.geoProjection(function(x, y) { return [x, -y]; })
            .translate([0, 0])
            .scale(180 / Math.PI)
            .clipExtent([[0, 0], [Infinity, Infinity]]),
        filter = function() { return true; };

    beforeEach(function () {
        context = iD.Context();
        d3.select(document.createElement('div'))
            .attr('id', 'map')
            .call(context.map());
        surface = context.surface();
    });

    it('creates midpoint on segment completely within the extent', function () {
        var a = iD.Node({loc: [0, 0]}),
            b = iD.Node({loc: [50, 0]}),
            line = iD.Way({nodes: [a.id, b.id]}),
            graph = iD.Graph([a, b, line]),
            extent = iD.geoExtent([0, 0], [100, 100]);

        context.selectedIDs = function() { return [line.id]; };
        context.entity = function(id) { return graph.entity(id); };
        surface.call(iD.svgMidpoints(projection, context), graph, [line], filter, extent);

        expect(surface.selectAll('.midpoint').datum().loc).to.eql([25, 0]);
    });

    it('doesn\'t create midpoint on segment with pixel length less than 40', function () {
        var a = iD.Node({loc: [0, 0]}),
            b = iD.Node({loc: [39, 0]}),
            line = iD.Way({nodes: [a.id, b.id]}),
            graph = iD.Graph([a, b, line]),
            extent = iD.geoExtent([0, 0], [100, 100]);

        context.selectedIDs = function() { return [line.id]; };
        surface.call(iD.svgMidpoints(projection, context), graph, [line], filter, extent);

        expect(surface.selectAll('.midpoint').nodes()).to.have.length(0);
    });

    it('doesn\'t create midpoint on segment completely outside of the extent', function () {
        var a = iD.Node({loc: [-100, 0]}),
            b = iD.Node({loc: [-50, 0]}),
            line = iD.Way({nodes: [a.id, b.id]}),
            graph = iD.Graph([a, b, line]),
            extent = iD.geoExtent([0, 0], [100, 100]);

        context.selectedIDs = function() { return [line.id]; };
        surface.call(iD.svgMidpoints(projection, context), graph, [line], filter, extent);

        expect(surface.selectAll('.midpoint').nodes()).to.have.length(0);
    });

    it('creates midpoint on extent edge for segment partially outside of the extent', function () {
        var a = iD.Node({loc: [50, 0]}),
            b = iD.Node({loc: [500, 0]}),
            line = iD.Way({nodes: [a.id, b.id]}),
            graph = iD.Graph([a, b, line]),
            extent = iD.geoExtent([0, 0], [100, 100]);

        context.selectedIDs = function() { return [line.id]; };
        context.entity = function(id) { return graph.entity(id); };
        surface.call(iD.svgMidpoints(projection, context), graph, [line], filter, extent);

        expect(surface.selectAll('.midpoint').datum().loc).to.eql([100, 0]);
    });

    it('doesn\'t create midpoint on extent edge for segment with pixel length less than 20', function () {
        var a = iD.Node({loc: [81, 0]}),
            b = iD.Node({loc: [500, 0]}),
            line = iD.Way({nodes: [a.id, b.id]}),
            graph = iD.Graph([a, b, line]),
            extent = iD.geoExtent([0, 0], [100, 100]);

        context.selectedIDs = function() { return [line.id]; };
        surface.call(iD.svgMidpoints(projection, context), graph, [line], filter, extent);

        expect(surface.selectAll('.midpoint').nodes()).to.have.length(0);
    });

});
<commit_msg>Better mock for select mode, fixes false test failures<commit_after>describe('iD.svgMidpoints', function () {
    var context, surface,
        selectedIDs = [],
        projection = d3.geoProjection(function(x, y) { return [x, -y]; })
            .translate([0, 0])
            .scale(180 / Math.PI)
            .clipExtent([[0, 0], [Infinity, Infinity]]),
        filter = function() { return true; };

    beforeEach(function () {
        context = iD.Context();
        context.mode = function() {
            return {
                id: 'select',
                selectedIDs: function() { return selectedIDs; }
            };
        };
        d3.select(document.createElement('div'))
            .attr('id', 'map')
            .call(context.map());
        surface = context.surface();
    });

    it('creates midpoint on segment completely within the extent', function () {
        var a = iD.Node({loc: [0, 0]}),
            b = iD.Node({loc: [50, 0]}),
            line = iD.Way({nodes: [a.id, b.id]}),
            graph = iD.Graph([a, b, line]),
            extent = iD.geoExtent([0, 0], [100, 100]);

        selectedIDs = [line.id];
        context.selectedIDs = function() { return selectedIDs; };
        context.entity = function(id) { return graph.entity(id); };
        context.hasEntity = context.entity;

        surface.call(iD.svgMidpoints(projection, context), graph, [line], filter, extent);
        expect(surface.selectAll('.midpoint').datum().loc).to.eql([25, 0]);
    });

    it('doesn\'t create midpoint on segment with pixel length less than 40', function () {
        var a = iD.Node({loc: [0, 0]}),
            b = iD.Node({loc: [39, 0]}),
            line = iD.Way({nodes: [a.id, b.id]}),
            graph = iD.Graph([a, b, line]),
            extent = iD.geoExtent([0, 0], [100, 100]);

        selectedIDs = [line.id];
        context.selectedIDs = function() { return selectedIDs; };
        context.entity = function(id) { return graph.entity(id); };
        context.hasEntity = context.entity;

        surface.call(iD.svgMidpoints(projection, context), graph, [line], filter, extent);
        expect(surface.selectAll('.midpoint').nodes()).to.have.length(0);
    });

    it('doesn\'t create midpoint on segment completely outside of the extent', function () {
        var a = iD.Node({loc: [-100, 0]}),
            b = iD.Node({loc: [-50, 0]}),
            line = iD.Way({nodes: [a.id, b.id]}),
            graph = iD.Graph([a, b, line]),
            extent = iD.geoExtent([0, 0], [100, 100]);

        selectedIDs = [line.id];
        context.selectedIDs = function() { return selectedIDs; };
        context.entity = function(id) { return graph.entity(id); };
        context.hasEntity = context.entity;

        surface.call(iD.svgMidpoints(projection, context), graph, [line], filter, extent);
        expect(surface.selectAll('.midpoint').nodes()).to.have.length(0);
    });

    it('creates midpoint on extent edge for segment partially outside of the extent', function () {
        var a = iD.Node({loc: [50, 0]}),
            b = iD.Node({loc: [500, 0]}),
            line = iD.Way({nodes: [a.id, b.id]}),
            graph = iD.Graph([a, b, line]),
            extent = iD.geoExtent([0, 0], [100, 100]);

        selectedIDs = [line.id];
        context.selectedIDs = function() { return selectedIDs; };
        context.entity = function(id) { return graph.entity(id); };
        context.hasEntity = context.entity;

        surface.call(iD.svgMidpoints(projection, context), graph, [line], filter, extent);
        expect(surface.selectAll('.midpoint').datum().loc).to.eql([100, 0]);
    });

    it('doesn\'t create midpoint on extent edge for segment with pixel length less than 20', function () {
        var a = iD.Node({loc: [81, 0]}),
            b = iD.Node({loc: [500, 0]}),
            line = iD.Way({nodes: [a.id, b.id]}),
            graph = iD.Graph([a, b, line]),
            extent = iD.geoExtent([0, 0], [100, 100]);

        selectedIDs = [line.id];
        context.selectedIDs = function() { return selectedIDs; };
        context.entity = function(id) { return graph.entity(id); };
        context.hasEntity = context.entity;

        surface.call(iD.svgMidpoints(projection, context), graph, [line], filter, extent);
        expect(surface.selectAll('.midpoint').nodes()).to.have.length(0);
    });

});
<|endoftext|>


<commit_before>describe('Woopra Client Snippet', function() {
    var visitorProperties = {
            name: 'WoopraUser',
            email: 'test@woopra.com',
            company: 'Woopra'
        },
        woopra,
        b = ['config', 'track', 'identify', 'visit', 'push'],
        i,
        spy = {},
        tracker;

    before(function() {
        (function () {
            var i,
                s,
                z,
                w = window,
                d = document,
                a = arguments,
                q = 'script',
                f = ['config', 'track', 'identify', 'visit', 'push', 'call'],
                c = function () {
                    var i,
                    self = this,
                    createStubs = function(name) {
                        // create stub functions for tracker instance
                        self[name] = function () {
                            // need to do this so params get called properly
                            self._e.push([name].concat(Array.prototype.slice.call(arguments, 0)));
                            return self;
                        };
                    };

                    self._e = [];
                    for (i = 0; i < f.length; i++) {
                        createStubs(f[i]);
                    }
                };

            window._w = window._w || {};
            // check if instance of tracker exists
            for (i = 0; i < a.length; i++) {
                window._w[a[i]] = window[a[i]] = window[a[i]] || new c();
            }
            // insert tracker script
            s = d.createElement(q);
            s.async = 1;
            s.src = '//localhost:4141/wpt.min.js';
            z = d.getElementsByTagName(q)[0];
            z.parentNode.insertBefore(s, z);
        })('woopra', 'woopra2', 'woopra3');

    });

    beforeEach(function() {
        // create spies for all of the public methods
        for (i = 0; i < b.length; i++) {
            spy[b[i]] = sinon.spy(Woopra.Tracker.prototype, b[i]);
        }
    });
    afterEach(function() {
        // restore spies
        for (i = 0; i < b.length; i++) {
            Woopra.Tracker.prototype[b[i]].restore();
        }
    });

    it('has the instance name of "woopra"', function() {
        expect(window.woopra).to.be.defined;
    });

    it('support multiple instances of tracker', function() {
        expect(window.woopra2).to.be.defined;
        expect(window.woopra3).to.be.defined;
        expect(window.woopra2).to.not.equal(window.woopra);
    });

    it('make sure stub methods are created', function() {
        var i = 0;
        expect(window.woopra._e.length).to.equal(0);
        for (i = 0; i < b.length; i++) {
            expect(window.woopra[b[i]]).to.be.defined;
        }
    });

    // lets queue up some events since woopra tracker isn't loaded yet
    // shouldn't need to test all of the public methods
    it('queues track() call', function() {
        expect(window.woopra._e.length).to.equal(0);
        window.woopra.track('testEvent', {title: 'testTitle'});
        expect(window.woopra._e.length).to.equal(1);
    });

    it('initializes the tracker and processes the queued up track() call', function() {
        var tSpy = sinon.spy(Woopra.Tracker.prototype, '_processQueue');

        woopra = new Woopra.Tracker('woopra');
        woopra.init();
        expect(tSpy).was.called;
        expect(spy.track).was.called;
        expect(spy.track).was.calledWith('testEvent', sinon.match({title: 'testTitle'}));
        tSpy.restore();
    });
});
<commit_msg>Fix tests to use non-conflicting instance names<commit_after>describe('Woopra Client Snippet', function() {
    var visitorProperties = {
            name: 'WoopraUser',
            email: 'test@woopra.com',
            company: 'Woopra'
        },
        woopra,
        b = ['config', 'track', 'identify', 'visit', 'push'],
        i,
        spy = {},
        tracker;

    before(function() {
        (function () {
            var i,
                s,
                z,
                w = window,
                d = document,
                a = arguments,
                q = 'script',
                f = ['config', 'track', 'identify', 'visit', 'push', 'call'],
                c = function () {
                    var i,
                    self = this,
                    createStubs = function(name) {
                        // create stub functions for tracker instance
                        self[name] = function () {
                            // need to do this so params get called properly
                            self._e.push([name].concat(Array.prototype.slice.call(arguments, 0)));
                            return self;
                        };
                    };

                    self._e = [];
                    for (i = 0; i < f.length; i++) {
                        createStubs(f[i]);
                    }
                };

            window._w = window._w || {};
            // check if instance of tracker exists
            for (i = 0; i < a.length; i++) {
                window._w[a[i]] = window[a[i]] = window[a[i]] || new c();
            }
            // insert tracker script
            s = d.createElement(q);
            s.async = 1;
            s.src = '//localhost:4141/wpt.min.js';
            z = d.getElementsByTagName(q)[0];
            z.parentNode.insertBefore(s, z);
        })('woopra_c1', 'woopra_c2', 'woopra_c3');

    });

    beforeEach(function() {
        // create spies for all of the public methods
        for (i = 0; i < b.length; i++) {
            spy[b[i]] = sinon.spy(Woopra.Tracker.prototype, b[i]);
        }
    });
    afterEach(function() {
        // restore spies
        for (i = 0; i < b.length; i++) {
            Woopra.Tracker.prototype[b[i]].restore();
        }
    });

    it('has the instance name of "woopra"', function() {
        expect(window.woopra_c1).to.be.defined;
    });

    it('support multiple instances of tracker', function() {
        expect(window.woopra_c2).to.be.defined;
        expect(window.woopra_c3).to.be.defined;
        expect(window.woopra_c2).to.not.equal(window.woopra_c1);
    });

    it('make sure stub methods are created', function() {
        var i = 0;
        expect(window.woopra_c1._e.length).to.equal(0);
        for (i = 0; i < b.length; i++) {
            expect(window.woopra_c1[b[i]]).to.be.defined;
        }
    });

    // lets queue up some events since woopra tracker isn't loaded yet
    // shouldn't need to test all of the public methods
    it('queues track() call', function() {
        expect(window.woopra_c1._e.length).to.equal(0);
        window.woopra_c1.track('testEvent', {title: 'testTitle'});
        expect(window.woopra_c1._e.length).to.equal(1);
    });

    it('initializes the tracker and processes the queued up track() call', function() {
        var tSpy = sinon.spy(Woopra.Tracker.prototype, '_processQueue');
        var woopra = new Woopra.Tracker('woopra_c1');
        woopra.init();
        expect(tSpy).was.called;
        expect(spy.track).was.called;
        expect(spy.track).was.calledWith('testEvent', sinon.match({title: 'testTitle'}));
        tSpy.restore();
    });
});
<|endoftext|>


<commit_before>/*
 * Build dependencies and configuration
 */
var fs                = require('fs'),
    glob              = require('glob-all'),
    mkdirp            = require('mkdirp'),
    path              = require('path'),
    uglifyjs          = require('uglify-js'),
    prompt            = require('prompt'),
    async             = require('async'),
    AWS               = require('aws-sdk'),
    config            = require('../config.js'),
    getToken          = require('../utilities/token.js'),
    sources           = require('../utilities/sources.js'),
    assets            = require('../utilities/assets.js'),
    pkg               = require('../package.json'),
    setup             = require('../deployment/setup.js'),
    base              = pkg.folders.jsSource,
    deploy            = pkg.folders.build + pkg.name + '/',
    deploymentList    = [],
    accountList       = [],
    execfile          = require('child_process').execFile;

console.log('> Building: ' + deploy);

/*
 * Source location mappings for glob
 */
var source = {
    "application": [
        base + '**/*.js',
        '!' + base + 'build/**',
        '!' + base + 'git-hooks/**',
        '!' + base + 'node_modules/**',
        '!' + base + 'target/**',
        '!' + base + 'utility/**',
        '!' + base + 'deployment/**'
    ],
    "config": [
        base + 'package.json'
    ]
};

/*
 * Create the node_modules directory so that it exists for installation regardless of module definitions for deployment
 */
mkdirp(deploy + 'node_modules/', function (err) {
    execfile('npm', ['install', '--production', '--prefix', 'target/ci_lambda_checks'], function(err, stdout) {});
    if (err) {
        return onErr(err);
    }
});

/*
 * Execute glob based distribution of source files
 */
for ( var section in source ) {
    switch (section) {
        default:
            glob.sync(source[section]).forEach(function(item) {
                mkdirp(path.dirname(item.replace(base, deploy)), function (err) {
                    if (err) {
                        return onErr(err);
                    } else {
                        switch (this.section) {
                            case 'application':
                                var minified = uglifyjs.minify(item, {mangle: false});
                                fs.writeFile(item.replace(base, deploy), minified.code.replace('release.version', pkg.version));
                                break;
                            default:
                                fs.createReadStream(item).pipe(fs.createWriteStream(item.replace(base, deploy)));
                                break;
                        }
                    }
                }.bind({section: section}));
            });
            break;
    }
}

/*
 * Let's fix this to actually use the users credentials to promprt the proper selections using CI.
 * Let's also use aws-sdk to automatically publish the resulting checks to the right region
 */

/*
 * Update the config.js file with proper information if anything is empty
 */
function onErr(err) {
    if (err !== null) {
        console.error("Error: " + err);
        return 1;
    }
}

var updated    = false,
    properties = [],
    callback   = function() {},
    required   = {
        "api_url": ""
    };

for ( var requirement in required ) {
    var value = config[requirement];
    if (config[requirement] === "") {
        properties.push({"name": requirement});
        updated = true;
    }
}

// Prompt the user for data or fail
if (properties.length > 0) {
    console.log("Some required properties have not been set, please provide them below and we will update your config.js file for you.");
    prompt.start();
    prompt.get(properties, function (err, result) {
        if (err) { return onErr(err); }
        for ( var key in result ) {
            config[key] = result[key];
        };
    });
}

var ciLogin = [
        {"name": "identifier"},
        {"name": "secret"}
    ];

console.log("Please sign in to Cloud Insight so that we can integrate with your environments.");
prompt.start();
prompt.get(ciLogin, function (err, result) {
    if (err) { return onErr(err); }
    for ( var key in result ) {
        config[key] = result[key];
    };

    async.waterfall(
        [
            /*
             * Fetch token or fail
             */
            function(onErr) {
                getToken(function(status, token) {
                    console.log("Logging you in to the Cloud Insight API.");
                    if ( status === "SUCCESS" ) {
                        config.accountId = JSON.parse(new Buffer(token.split(".")[1], 'base64')).account;
                        onErr(null, token);
                    } else {
                        onErr(status);
                    }
                });
            },
            /*
             * Get list of available environments
             */
            function(token, callback) {
                sources.getSources(token, function(status, environments) {
                    console.log("Getting your environment list.");
                    if ( status === "SUCCESS" ) {
                        callback(null, token, environments.sources);
                    } else {
                        callback("Unable to fetch environments.");
                    }
                });
            },
            /*
             * Process source records
             */
            function(token, rows, callback) {
                var done = rows.length,
                    count = 0,
                    sourcesAsync = require('async');
                console.log("Processing applicable environments and scope for application in AWS Lambda regions.");
                sourcesAsync.eachSeries(rows, function(row, sourcesAsyncCallback) {
                    count = count + 1;
                    var source = row.source;
                    sources.getCredential(token, source.config.aws.credential.id, function(status, credential) {
                        if ( status === "SUCCESS" ) {
                            config.environmentId = source.id;
                            var zipped           = '../ci_lambda_checks-' + config.accountId + '-' + source.name + '-' + source.id + '-' + pkg.version + '.zip';
                            fs.writeFileSync(deploy + 'config.js', 'var config = ' + JSON.stringify(config) + ';\nmodule.exports = config;');
                            process.chdir('target/ci_lambda_checks');
                            execfile('zip', ['-r', '-X', zipped, './'], function(err, stdout) {});
                            process.chdir('../../');
                            var deployment = {
                                "account": {
                                    "awsAccountId": credential.credential.iam_role.arn.split(":")[4],
                                    "id": config.accountId
                                },
                                "environment": {
                                    "name": source.name,
                                    "id": source.id,
                                    "file": "ci_lambda_checks-" + config.accountId + "-" + source.name + "-" + source.id + "-" + pkg.version + ".zip",
                                    "regions": []
                                }
                            };
                            assets.getRegionsInScope(token, source.id, function(status, regions) {
                                if ( status === "SUCCESS" ) {
                                    for (var region in regions.assets) {
                                        var target = regions.assets[region][0].key.split('/')[2];
                                        if ( config.supported.indexOf(target) > -1 ) {
                                            deployment.environment.regions.push(target);
                                        }
                                    }
                                    if (deployment.environment.regions.length > 0) {
                                        deploymentList.push(function(callback) {
                                            promptForProfile(deployment, callback);
                                        });
                                    }
                                    sourcesAsyncCallback(null);
                                } else {
                                    sourcesAsyncCallback("Unable to process environment regions.");
                                }
                            });
                        } else {
                            sourcesAsyncCallback("Unable to process credentials.");
                        }
                    });
                },
                function(err) {
                    if (err) {
                        console.log("Failed to build deployment artifaacts. Error: " + JSON.stringify(err));
                    } else {
                        console.log("Successfully built deployment artifacts.");
                    }
                    callback(null, deploymentList);
                });
            },
            function(deploymentList, callback) {
                var promptAsync = require('async');
                promptAsync.series(
                    deploymentList,
                    function(err, deployments) {
                        if (err) {
                            console.log("Error: " + JSON.stringify(err));
                        } else {
                            callback(null, deployments);
                        }
                    }
                );
            },
            function(deploymentList, callback) {
                console.log("Beginning deployment process to AWS Lambda.");
                setup(deploymentList, callback);
            }
        ],
        function (err) {
            if (err) {
                console.log("Build failed. Error: " + JSON.stringify(err));
            }
            callback(err);
        }
    );
});

function promptForProfile(deployment, callback) {
    "use strict";
    console.log("Please provide the name of the AWS profile for AWS Account: '" + deployment.account.awsAccountId + "' for Alert Logic environment: '" + deployment.environment.name + "'.");
    var awsConfig = require("../aws_config.json");
    for (var row in awsConfig.environments) {
        if (deployment.environment.id === awsConfig.environments[row].id) {
            deployment.account.profile = awsConfig.environments[row].profile;
            return callback(null, deployment);
        }
    }
    for (var account in accountList) {
        console.log(accountList[account].account + " : " + deployment.account.awsAccountId);
        if (accountList[account].account === deployment.account.awsAccountId) {
            deployment.account.profile = accountList[account].profile;
            return callback(null, deployment);
        }
    }
    prompt.start();
    prompt.get('profile', function (err, profile) {
        if (err) { return onErr(err); }
        accountList.push({
            "account": deployment.account.awsAccountId,
            "profile": profile.profile
        });
        deployment.account.profile = profile.profile;
        return callback(null, deployment);
    });
}
<commit_msg>Remove matching debug logging on build process<commit_after>/*
 * Build dependencies and configuration
 */
var fs                = require('fs'),
    glob              = require('glob-all'),
    mkdirp            = require('mkdirp'),
    path              = require('path'),
    uglifyjs          = require('uglify-js'),
    prompt            = require('prompt'),
    async             = require('async'),
    AWS               = require('aws-sdk'),
    config            = require('../config.js'),
    getToken          = require('../utilities/token.js'),
    sources           = require('../utilities/sources.js'),
    assets            = require('../utilities/assets.js'),
    pkg               = require('../package.json'),
    setup             = require('../deployment/setup.js'),
    base              = pkg.folders.jsSource,
    deploy            = pkg.folders.build + pkg.name + '/',
    deploymentList    = [],
    accountList       = [],
    execfile          = require('child_process').execFile;

console.log('> Building: ' + deploy);

/*
 * Source location mappings for glob
 */
var source = {
    "application": [
        base + '**/*.js',
        '!' + base + 'build/**',
        '!' + base + 'git-hooks/**',
        '!' + base + 'node_modules/**',
        '!' + base + 'target/**',
        '!' + base + 'utility/**',
        '!' + base + 'deployment/**'
    ],
    "config": [
        base + 'package.json'
    ]
};

/*
 * Create the node_modules directory so that it exists for installation regardless of module definitions for deployment
 */
mkdirp(deploy + 'node_modules/', function (err) {
    execfile('npm', ['install', '--production', '--prefix', 'target/ci_lambda_checks'], function(err, stdout) {});
    if (err) {
        return onErr(err);
    }
});

/*
 * Execute glob based distribution of source files
 */
for ( var section in source ) {
    switch (section) {
        default:
            glob.sync(source[section]).forEach(function(item) {
                mkdirp(path.dirname(item.replace(base, deploy)), function (err) {
                    if (err) {
                        return onErr(err);
                    } else {
                        switch (this.section) {
                            case 'application':
                                var minified = uglifyjs.minify(item, {mangle: false});
                                fs.writeFile(item.replace(base, deploy), minified.code.replace('release.version', pkg.version));
                                break;
                            default:
                                fs.createReadStream(item).pipe(fs.createWriteStream(item.replace(base, deploy)));
                                break;
                        }
                    }
                }.bind({section: section}));
            });
            break;
    }
}

/*
 * Let's fix this to actually use the users credentials to promprt the proper selections using CI.
 * Let's also use aws-sdk to automatically publish the resulting checks to the right region
 */

/*
 * Update the config.js file with proper information if anything is empty
 */
function onErr(err) {
    if (err !== null) {
        console.error("Error: " + err);
        return 1;
    }
}

var updated    = false,
    properties = [],
    callback   = function() {},
    required   = {
        "api_url": ""
    };

for ( var requirement in required ) {
    var value = config[requirement];
    if (config[requirement] === "") {
        properties.push({"name": requirement});
        updated = true;
    }
}

// Prompt the user for data or fail
if (properties.length > 0) {
    console.log("Some required properties have not been set, please provide them below and we will update your config.js file for you.");
    prompt.start();
    prompt.get(properties, function (err, result) {
        if (err) { return onErr(err); }
        for ( var key in result ) {
            config[key] = result[key];
        };
    });
}

var ciLogin = [
        {"name": "identifier"},
        {"name": "secret"}
    ];

console.log("Please sign in to Cloud Insight so that we can integrate with your environments.");
prompt.start();
prompt.get(ciLogin, function (err, result) {
    if (err) { return onErr(err); }
    for ( var key in result ) {
        config[key] = result[key];
    };

    async.waterfall(
        [
            /*
             * Fetch token or fail
             */
            function(onErr) {
                getToken(function(status, token) {
                    console.log("Logging you in to the Cloud Insight API.");
                    if ( status === "SUCCESS" ) {
                        config.accountId = JSON.parse(new Buffer(token.split(".")[1], 'base64')).account;
                        onErr(null, token);
                    } else {
                        onErr(status);
                    }
                });
            },
            /*
             * Get list of available environments
             */
            function(token, callback) {
                sources.getSources(token, function(status, environments) {
                    console.log("Getting your environment list.");
                    if ( status === "SUCCESS" ) {
                        callback(null, token, environments.sources);
                    } else {
                        callback("Unable to fetch environments.");
                    }
                });
            },
            /*
             * Process source records
             */
            function(token, rows, callback) {
                var done = rows.length,
                    count = 0,
                    sourcesAsync = require('async');
                console.log("Processing applicable environments and scope for application in AWS Lambda regions.");
                sourcesAsync.eachSeries(rows, function(row, sourcesAsyncCallback) {
                    count = count + 1;
                    var source = row.source;
                    sources.getCredential(token, source.config.aws.credential.id, function(status, credential) {
                        if ( status === "SUCCESS" ) {
                            config.environmentId = source.id;
                            var zipped           = '../ci_lambda_checks-' + config.accountId + '-' + source.name + '-' + source.id + '-' + pkg.version + '.zip';
                            fs.writeFileSync(deploy + 'config.js', 'var config = ' + JSON.stringify(config) + ';\nmodule.exports = config;');
                            process.chdir('target/ci_lambda_checks');
                            execfile('zip', ['-r', '-X', zipped, './'], function(err, stdout) {});
                            process.chdir('../../');
                            var deployment = {
                                "account": {
                                    "awsAccountId": credential.credential.iam_role.arn.split(":")[4],
                                    "id": config.accountId
                                },
                                "environment": {
                                    "name": source.name,
                                    "id": source.id,
                                    "file": "ci_lambda_checks-" + config.accountId + "-" + source.name + "-" + source.id + "-" + pkg.version + ".zip",
                                    "regions": []
                                }
                            };
                            assets.getRegionsInScope(token, source.id, function(status, regions) {
                                if ( status === "SUCCESS" ) {
                                    for (var region in regions.assets) {
                                        var target = regions.assets[region][0].key.split('/')[2];
                                        if ( config.supported.indexOf(target) > -1 ) {
                                            deployment.environment.regions.push(target);
                                        }
                                    }
                                    if (deployment.environment.regions.length > 0) {
                                        deploymentList.push(function(callback) {
                                            promptForProfile(deployment, callback);
                                        });
                                    }
                                    sourcesAsyncCallback(null);
                                } else {
                                    sourcesAsyncCallback("Unable to process environment regions.");
                                }
                            });
                        } else {
                            sourcesAsyncCallback("Unable to process credentials.");
                        }
                    });
                },
                function(err) {
                    if (err) {
                        console.log("Failed to build deployment artifaacts. Error: " + JSON.stringify(err));
                    } else {
                        console.log("Successfully built deployment artifacts.");
                    }
                    callback(null, deploymentList);
                });
            },
            function(deploymentList, callback) {
                var promptAsync = require('async');
                promptAsync.series(
                    deploymentList,
                    function(err, deployments) {
                        if (err) {
                            console.log("Error: " + JSON.stringify(err));
                        } else {
                            callback(null, deployments);
                        }
                    }
                );
            },
            function(deploymentList, callback) {
                console.log("Beginning deployment process to AWS Lambda.");
                setup(deploymentList, callback);
            }
        ],
        function (err) {
            if (err) {
                console.log("Build failed. Error: " + JSON.stringify(err));
            }
            callback(err);
        }
    );
});

function promptForProfile(deployment, callback) {
    "use strict";
    console.log("Please provide the name of the AWS profile for AWS Account: '" + deployment.account.awsAccountId + "' for Alert Logic environment: '" + deployment.environment.name + "'.");
    var awsConfig = require("../aws_config.json");
    for (var row in awsConfig.environments) {
        if (deployment.environment.id === awsConfig.environments[row].id) {
            deployment.account.profile = awsConfig.environments[row].profile;
            return callback(null, deployment);
        }
    }
    for (var account in accountList) {
        if (accountList[account].account === deployment.account.awsAccountId) {
            deployment.account.profile = accountList[account].profile;
            return callback(null, deployment);
        }
    }
    prompt.start();
    prompt.get('profile', function (err, profile) {
        if (err) { return onErr(err); }
        accountList.push({
            "account": deployment.account.awsAccountId,
            "profile": profile.profile
        });
        deployment.account.profile = profile.profile;
        return callback(null, deployment);
    });
}
<|endoftext|>


<commit_before>define([
    'require',
    '../lib/jquery.form/jquery.form',
    '../logging',
    '../utils'
], function(require) {
    var log = require('../logging').getLogger('autosubmit'),
        utils = require('../utils');

    // can be called on a form or an element in a form
    var init = function($el) {
        // get parameters from markup
        var $form = $el.is('form') ? $el : $el.parents('form').first();

        var submit = function(event) {
            // ignore auto-suggest fields, the change event will be
            // triggered on the hidden input
            if ($(event.target).is('.auto-suggest')) {
                log.debug('ignored event from autosuggest field');
                return;
            }
            log.info("triggered by " + event.type);
            $form.submit();
        };

        // submit if a (specific) form element changed
        $el.on("change", submit);

        // debounced keyup submit, if enabled
        if ($el.hasClass('auto-submit-keyup')) {
            ($el.is('input') ? $el : $el.find('input'))
                .on("keyup", utils.debounce(submit, 400));
        }

        // XXX: test whether on webkit and enable only if supported
        // XXX: add code to check whether the click actually changed
        // something
        ($el.is('input[type=search]') ? $el : $el.find('input[type=search]'))
            .on("click", submit);

        // allow for chaining
        return $el;
    };

    var pattern = {
        markup_trigger: ".auto-submit, .auto-submit-keyup",
        initialised_class: "auto-submit",
        init: init
    };

    return pattern;
});
<commit_msg>autosubmit: click on type=search only submits if value changed<commit_after>define([
    'require',
    '../lib/jquery.form/jquery.form',
    '../logging',
    '../utils'
], function(require) {
    var log = require('../logging').getLogger('autosubmit'),
        utils = require('../utils');

    // can be called on a form or an element in a form
    var init = function($el) {
        // get parameters from markup
        var $form = $el.is('form') ? $el : $el.parents('form').first();

        var submit = function(ev) {
            var $target = $(ev.target);

            // ignore auto-suggest fields, the change event will be
            // triggered on the hidden input
            if ($target.is('.auto-suggest')) {
                log.debug('ignored event from autosuggest field');
                return;
            }

            if ($target.is('input[type=search]')) {
                // clicking X on type=search deletes data attrs,
                // therefore we store the old value on the form.
                var name = $target.attr('name'),
                    key = name + '-autosubmit-oldvalue',
                    oldvalue = $form.data(key) || "",
                    curvalue = $target[0].value || "";

                if (!name) {
                    log.warn('type=search without name, will be a problem'
                             + ' if there are multiple', $target);
                }
                if (oldvalue === curvalue) return;

                $form.data(key, curvalue);
            }

            log.info("triggered by " + ev.type);

            $form.submit();
        };

        // submit if a (specific) form element changed
        $el.on("change", submit);

        // debounced keyup submit, if enabled
        if ($el.hasClass('auto-submit-keyup')) {
            ($el.is('input') ? $el : $el.find('input'))
                .on("keyup", utils.debounce(submit, 400));
        }

        // XXX: test whether on webkit and enable only if supported
        ($el.is('input[type=search]') ? $el : $el.find('input[type=search]'))
            .on("click", submit);

        // allow for chaining
        return $el;
    };

    var pattern = {
        markup_trigger: ".auto-submit, .auto-submit-keyup",
        initialised_class: "auto-submit",
        init: init
    };

    return pattern;
});
<|endoftext|>


<commit_before>describe('Woopra Client Snippet', function() {
    var b = ['config', 'track', 'identify', 'visit', 'push'];

    it('Can be loaded asynchronously', function(done) {
        window.woopraLoaded = function() {
            window.woopraLoaded = null;
            window.woopra_c1 = null;
            done();
        };

        (function () {
            var i,
                s,
                z,
                w = window,
                d = document,
                a = arguments,
                q = 'script',
                f = ['config', 'track', 'identify', 'visit', 'push', 'call'],
                C = function () {
                    var i,
                    self = this,
                    createStubs = function(name) {
                        // create stub functions for tracker instance
                        self[name] = function () {
                            // need to do this so params get called properly
                            self._e.push([name].concat(Array.prototype.slice.call(arguments, 0)));
                            return self;
                        };
                    };

                    self._e = [];
                    for (i = 0; i < f.length; i++) {
                        createStubs(f[i]);
                    }
                };

            w._w = w._w || {};
            // check if instance of tracker exists
            for (i = 0; i < a.length; i++) {
                w._w[a[i]] = w[a[i]] = w[a[i]] || new C();
            }
            // insert tracker script
            s = d.createElement(q);
            s.async = 1;
            s.src = 'http://localhost:4141/wpt.js';
            z = d.getElementsByTagName(q)[0];
            z.parentNode.insertBefore(s, z);
        })('woopra');
    });

    describe('Multiple Instances', function() {
        var insert_tracker;
        var init_cb = {};

        before(function() {
            window.woopra.dispose();
            window.woopra = null;
            window.woopraTracker = null;
            window.Woopra.Tracker = null;
            window._w = {};

            (function () {
                var i,
                s,
                z,
                w = window,
                d = document,
                a = arguments,
                q = 'script',
                f = ['config', 'track', 'identify', 'visit', 'push', 'call'],
                C = function () {
                    var i,
                    self = this,
                    createStubs = function(name) {
                        // create stub functions for tracker instance
                        self[name] = function () {
                            // need to do this so params get called properly
                            self._e.push([name].concat(Array.prototype.slice.call(arguments, 0)));
                            return self;
                        };
                    };

                    self._e = [];
                    for (i = 0; i < f.length; i++) {
                        createStubs(f[i]);
                    }
                };

                w._w = w._w || {};
                // check if instance of tracker exists
                for (i = 0; i < a.length; i++) {
                    w._w[a[i]] = w[a[i]] = w[a[i]] || new C();
                }

                insert_tracker = function() {
                    // insert tracker script
                    s = d.createElement(q);
                    s.async = 1;
                    s.src = 'http://localhost:4141/wpt.js';
                    z = d.getElementsByTagName(q)[0];
                    z.parentNode.insertBefore(s, z);
                };
            })('woopra_c1', 'woopra_c2', 'woopra_c3');
        });

        after(function() {
            window.woopra_c1.dispose();
            window.woopra_c2.dispose();
            window.woopra_c3.dispose();
        });

        it('Creates multiple instances of tracker stubs', function() {
            expect(window.woopra_c1).to.not.be(undefined);
            expect(window.woopra_c2).to.not.be(undefined);
            expect(window.woopra_c3).to.not.be(undefined);
            expect(window.woopra_c2).to.not.equal(window.woopra_c1);
        });

        it('Stub methods are created for all instances', function() {
            var j;
            var i;

            for (j = 1; j <= 3; j++) {
                expect(window['woopra_c' + j]._e.length).to.equal(0);
                for (i = 0; i < b.length; i++) {
                    expect(window['woopra_c' + j][b[i]]).to.not.be(undefined);
                }
            }
        });

        // lets queue up some events since woopra tracker isn't loaded yet
        // shouldn't need to test all of the public methods
        it('Queues track() calls for all instances', function() {
            var name;
            var j;
            var spy;

            for (j = 1; j <= 3; j++) {
                name = 'woopra_c' + j;
                spy = sinon.spy();
                init_cb[j] = spy;

                expect(window[name]._e.length).to.equal(0);
                window[name].track('testEvent' + j, {title: 'testTitle'});
                window[name].config('initialized', spy);
                expect(window[name]._e.length).to.equal(2);
            }
        });

        it('Programmatically insert tracker into the DOM', function(done) {
            // Stub Tracker.init so we can manually initialize
            window.woopraLoaded = function() {
                /* jshint ignore:start */
                var stub = sinon.stub(Woopra.Tracker.prototype, 'init');
                /* jshint ignore:end */
                done();
            };
            insert_tracker();
        });

        it('Processes queues when `init` is called', function() {
            var spy;
            var qSpy;
            var name;

            Woopra.Tracker.prototype.init.restore();

            for (var i = 1; i <= 3; i++) {
                spy = sinon.spy(Woopra.Tracker.prototype, 'track');
                qSpy = sinon.spy(Woopra.Tracker.prototype,  '_processQueue');

                name = 'woopra_c' + i;

                expect(qSpy).was.notCalled();
                expect(spy).was.notCalled();

                window[name].init();

                expect(qSpy).was.called();
                expect(spy).was.called();
                expect(spy).was.calledWithMatch('testEvent' + i, {title: 'testTitle'});
                spy.restore();
                qSpy.restore();
            }
        });

        it('Call all queued up initialize callbacks', function() {
            for (var i = 1; i <= 3; i++) {
                expect(init_cb[i]).was.called();
            }
        });

        it('Set and call initialize callbacks after tracker has been loaded', function() {
            for (var i = 1; i <= 3; i++) {
                expect(init_cb[i]).was.called();
            }
        });

    });
});
<commit_msg>Skip some tracker client tests for now<commit_after>describe('Woopra Client Snippet', function() {
    var b = ['config', 'track', 'identify', 'visit', 'push'];

    it('Can be loaded asynchronously', function(done) {
        window.woopraLoaded = function() {
            window.woopraLoaded = null;
            window.woopra_c1 = null;
            done();
        };

        (function () {
            var i,
                s,
                z,
                w = window,
                d = document,
                a = arguments,
                q = 'script',
                f = ['config', 'track', 'identify', 'visit', 'push', 'call'],
                C = function () {
                    var i,
                    self = this,
                    createStubs = function(name) {
                        // create stub functions for tracker instance
                        self[name] = function () {
                            // need to do this so params get called properly
                            self._e.push([name].concat(Array.prototype.slice.call(arguments, 0)));
                            return self;
                        };
                    };

                    self._e = [];
                    for (i = 0; i < f.length; i++) {
                        createStubs(f[i]);
                    }
                };

            w._w = w._w || {};
            // check if instance of tracker exists
            for (i = 0; i < a.length; i++) {
                w._w[a[i]] = w[a[i]] = w[a[i]] || new C();
            }
            // insert tracker script
            s = d.createElement(q);
            s.async = 1;
            s.src = 'http://localhost:4141/wpt.js';
            z = d.getElementsByTagName(q)[0];
            z.parentNode.insertBefore(s, z);
        })('woopra');
    });

    describe('Multiple Instances', function() {
        var insert_tracker;
        var init_cb = {};

        before(function() {
            window.woopra.dispose();
            window.woopra = null;
            window.woopraTracker = null;
            window.Woopra.Tracker = null;
            window._w = {};

            (function () {
                var i,
                s,
                z,
                w = window,
                d = document,
                a = arguments,
                q = 'script',
                f = ['config', 'track', 'identify', 'visit', 'push', 'call'],
                C = function () {
                    var i,
                    self = this,
                    createStubs = function(name) {
                        // create stub functions for tracker instance
                        self[name] = function () {
                            // need to do this so params get called properly
                            self._e.push([name].concat(Array.prototype.slice.call(arguments, 0)));
                            return self;
                        };
                    };

                    self._e = [];
                    for (i = 0; i < f.length; i++) {
                        createStubs(f[i]);
                    }
                };

                w._w = w._w || {};
                // check if instance of tracker exists
                for (i = 0; i < a.length; i++) {
                    w._w[a[i]] = w[a[i]] = w[a[i]] || new C();
                }

                insert_tracker = function() {
                    // insert tracker script
                    s = d.createElement(q);
                    s.async = 1;
                    s.src = 'http://localhost:4141/wpt.js';
                    z = d.getElementsByTagName(q)[0];
                    z.parentNode.insertBefore(s, z);
                };
            })('woopra_c1', 'woopra_c2', 'woopra_c3');
        });

        after(function() {
            window.woopra_c1.dispose();
            window.woopra_c2.dispose();
            window.woopra_c3.dispose();
        });

        it('Creates multiple instances of tracker stubs', function() {
            expect(window.woopra_c1).to.not.be(undefined);
            expect(window.woopra_c2).to.not.be(undefined);
            expect(window.woopra_c3).to.not.be(undefined);
            expect(window.woopra_c2).to.not.equal(window.woopra_c1);
        });

        it('Stub methods are created for all instances', function() {
            var j;
            var i;

            for (j = 1; j <= 3; j++) {
                expect(window['woopra_c' + j]._e.length).to.equal(0);
                for (i = 0; i < b.length; i++) {
                    expect(window['woopra_c' + j][b[i]]).to.not.be(undefined);
                }
            }
        });

        // lets queue up some events since woopra tracker isn't loaded yet
        // shouldn't need to test all of the public methods
        it('Queues track() calls for all instances', function() {
            var name;
            var j;
            var spy;

            for (j = 1; j <= 3; j++) {
                name = 'woopra_c' + j;
                spy = sinon.spy();
                init_cb[j] = spy;

                expect(window[name]._e.length).to.equal(0);
                window[name].track('testEvent' + j, {title: 'testTitle'});
                window[name].config('initialized', spy);
                expect(window[name]._e.length).to.equal(2);
            }
        });

        it('Programmatically insert tracker into the DOM', function(done) {
            // Stub Tracker.init so we can manually initialize
            window.woopraLoaded = function() {
                /* jshint ignore:start */
                var stub = sinon.stub(Woopra.Tracker.prototype, 'init');
                /* jshint ignore:end */
                done();
            };
            insert_tracker();
        });

        it.skip('Processes queues when `init` is called', function(done) {
            var spy;
            var qSpy;
            var name;

            var test_func = function(qSpy, spy, i) {
                expect(qSpy).was.called();
                expect(spy).was.called();
                expect(spy).was.calledWithMatch('testEvent' + i, {title: 'testTitle'});
                spy.restore();
                qSpy.restore();
            };

            Woopra.Tracker.prototype.init.restore();

            for (var i = 1; i <= 3; i++) {
                spy = sinon.spy(Woopra.Tracker.prototype, 'track');
                qSpy = sinon.spy(Woopra.Tracker.prototype,  '_processQueue');

                name = 'woopra_c' + i;

                expect(qSpy).was.notCalled();
                expect(spy).was.notCalled();

                window[name].init();

                setTimeout(test_func(qSpy, spy, i), 10);
            }

            setTimeout(function() {
                done();
            }, 250);
        });

        it.skip('Call all queued up initialize callbacks', function() {
            for (var i = 1; i <= 3; i++) {
                expect(init_cb[i]).was.called();
            }
        });

        it.skip('Set and call initialize callbacks after tracker has been loaded', function() {
            for (var i = 1; i <= 3; i++) {
                expect(init_cb[i]).was.called();
            }
        });

    });
});
<|endoftext|>


<commit_before>const rollup = require("rollup");
const buble = require("rollup-plugin-buble");
const uglify = require("uglify-js");
const fs = require("fs");
const path = require("path");
const pkg = require("../package.json");
const cwd = process.cwd();
const ENV_RE = /__ENV__/g;

const comment = `/**
 * Moon v${pkg.version}
 * Copyright 2016-2018 Kabir Shah
 * Released under the MIT License
 * https://kbrsh.github.io/moon
 */\r\n`;

const options = {
  format: "iife",
  name: "Moon"
};

async function build() {
  const bundle = await rollup.rollup({
    input: path.join(cwd, "/src/index.js"),
    plugins: [
      buble()
    ]
  });

  let { code } = await bundle.generate(options);
  code = fs.readFileSync(path.join(cwd, "/src/wrapper.js")).toString().replace("INSERT", code.split("\n").slice(1, -3).join("\n")).replace("'use strict'", "\"use strict\"");

  fs.writeFileSync(path.join(cwd, "/dist/moon.js"), comment + code.replace(ENV_RE, '"development"'));
  fs.writeFileSync(path.join(cwd, "/dist/moon.min.js"), comment + uglify.minify(code.replace(ENV_RE, '"production"')).code);
}

build();
<commit_msg>use env variable MOON_ENV<commit_after>const rollup = require("rollup");
const buble = require("rollup-plugin-buble");
const uglify = require("uglify-js");
const fs = require("fs");
const path = require("path");
const pkg = require("../package.json");
const cwd = process.cwd();
const ENV_RE = /process\.env\.MOON_ENV/g;

const comment = `/**
 * Moon v${pkg.version}
 * Copyright 2016-2018 Kabir Shah
 * Released under the MIT License
 * https://kbrsh.github.io/moon
 */\r\n`;

const options = {
  format: "iife",
  name: "Moon"
};

async function build() {
  const bundle = await rollup.rollup({
    input: path.join(cwd, "/src/index.js"),
    plugins: [
      buble()
    ]
  });

  let { code } = await bundle.generate(options);
  code = fs.readFileSync(path.join(cwd, "/src/wrapper.js")).toString().replace("INSERT", code.split("\n").slice(1, -3).join("\n")).replace("'use strict'", "\"use strict\"");

  fs.writeFileSync(path.join(cwd, "/dist/moon.js"), comment + code.replace(ENV_RE, '"development"'));
  fs.writeFileSync(path.join(cwd, "/dist/moon.min.js"), comment + uglify.minify(code.replace(ENV_RE, '"production"')).code);
}

build();
<|endoftext|>


<commit_before>"use strict";

    const express = require("express");
    const router = express.Router({mergeParams: true});
    const responseCodes = require("../response_codes.js");
    const C = require("../constants");
    const systemLogger = require("../logger.js").systemLogger;
    const serialize = require("serialize-javascript");
    const _ = require("lodash");
    const fs = require("fs");
    const addressMeta = require("../models/addressMeta");
    const units = require("../models/unit");
    const History = require("../models/history");
    const ModelHelper = require("../models/helper/model");
    const User = require("../models/user");
    const DEFAULT_PLUGIN_STRUCTURE = require("../plugin/plugin-structure.js").DEFAULT_PLUGIN_STRUCTURE;
    const path = require("path");

    const config = require("../config");

    /**
     * Get the pug files for the required state or plugin
     *
     * @param {string} required - Name of required plugin
     * @param {string} pathToStatesAndPlugins - Root path of plugins
     * @param {Object} params - Updates with information from plugin structure
     */
    function getPugFiles(required, pathToStatesAndPlugins, params) {
        let requiredFiles,
            requiredDir,
            fileSplit;

        requiredDir = pathToStatesAndPlugins + "/" + required + "/pug";
        try {
            fs.accessSync(requiredDir, fs.F_OK); // Throw for fail

            requiredFiles = fs.readdirSync(requiredDir);
            requiredFiles.forEach(function (file) {
                fileSplit = file.split(".");
                params.frontendPug.push({
                    id: fileSplit[0] + ".html",
                    path: requiredDir + "/" + file
                });
            });
        } catch (e) {
            // Pug files don"t exist
            systemLogger.logFatal(e.message);
        }
    }

    /**
     * Setup loading only the required states and plugins pug files
     *
     * @private
     * @param {string[]} statesAndPlugins - List of states and plugins to load
     * @param {string} required - Plugin to load
     * @param {string} pathToStatesAndPlugins - Base directory to load plugins from
     * @param {Object} params - Updates with information from plugin structure
     */
    function setupRequiredPug(statesAndPlugins, required, pathToStatesAndPlugins, params) {
        let i, length;

        if (statesAndPlugins.indexOf(required.plugin) !== -1) {
            getPugFiles(required.plugin, pathToStatesAndPlugins, params);

            // Friends
            if (required.hasOwnProperty("friends")) {
                for (i = 0, length = required.friends.length; i < length; i++) {
                    if (statesAndPlugins.indexOf(required.friends[i]) !== -1) {
                        getPugFiles(required.friends[i], pathToStatesAndPlugins, params);
                    }
                }
            }

            // Functions
            if (required.hasOwnProperty("functions")) {
                for (i = 0, length = required.functions.length; i < length; i++) {
                    if (statesAndPlugins.indexOf(required.functions[i]) !== -1) {
                        getPugFiles(required.functions[i], pathToStatesAndPlugins, params);
                    }
                }
            }

            // Recurse for children
            if (required.hasOwnProperty("children")) {
                for (i = 0, length = required.children.length; i < length; i++) {
                    setupRequiredPug(statesAndPlugins, required.children[i], pathToStatesAndPlugins, params);
                }
            }

        }
    }

    /**
     * Get all available states and plugins
     *
     * @param {Object} params - updates with information from plugin structure
     */
    function setupPug(params, pluginStructure) {

        const pathToStatesAndPlugins = path.join(__dirname + "./../../frontend/components");

        // Get all available states and plugins in the file system
        const statesAndPlugins = fs.readdirSync(pathToStatesAndPlugins);
        setupRequiredPug(statesAndPlugins, pluginStructure, pathToStatesAndPlugins, params);

    }

    function createClientConfig(serverConfig, req) {

        // TODO: Replace with user based plugin selection
        let pluginStructure = {};

        // If the serverConfig has a plugin structure, use that
        // else just use the default
        if (serverConfig.pluginStructure) {
            pluginStructure = require("../../" + serverConfig.pluginStructure);
        } else {
            pluginStructure = DEFAULT_PLUGIN_STRUCTURE;
        }

        let clientConfig = {
            "maintenanceMode": config.maintenanceMode,
            "ui": {},
            "uistate": {},
            "structure": pluginStructure,
            "frontendPug": [],
            "gaTrackId": config.gaTrackId,
            "development" : config.development,
            "googleConversionId": config.googleConversionId,
            "userNotice" : config.userNotice,
            "unitySettings" : config.unitySettings,
            "customLogins" : config.customLogins
        };

        if (config.hasOwnProperty("captcha_client_key")) {
            clientConfig.captcha_client_key = config.captcha_client_key;
        }

        // Set up the legal plugins
        if (config.hasOwnProperty("legal")) {
            for (let i = 0; i < config.legal.length; i += 1) {
                pluginStructure.functions.push(config.legal[i].page);
            }
        }

        if (config.hasOwnProperty("captcha_client_key")) {
            clientConfig.captcha_client_key = config.captcha_client_key;
        }

        if (req) {
            clientConfig.userId = _.get(req, "session.user.username");
        }

        // Set up the legal plugins
        clientConfig.legalTemplates = [];
        if (config.hasOwnProperty("legal")) {
            clientConfig.legalTemplates = config.legal;
        }

        clientConfig.apiUrls = config.apiUrls;

        clientConfig.C = {
            GET_API : C.GET_API,
            POST_API : C.POST_API,
            MAP_API : C.MAP_API
        };

        if (config.chat_server) {
            clientConfig.chatHost = config.chat_server.chat_host;
            clientConfig.chatPath = "/" + config.chat_server.subdirectory;
        }

        clientConfig.chatReconnectionAttempts = config.chat_reconnection_attempts;

        clientConfig.VERSION = config.version;

        if (serverConfig.backgroundImage) {
            clientConfig.backgroundImage = serverConfig.backgroundImage;
        }

        clientConfig.return_path = "/";

        clientConfig.auth =  config.auth;

        if(config.captcha && config.captcha.clientKey) {
            clientConfig.captcha_client_key = config.captcha.clientKey;
        }

        clientConfig.uploadSizeLimit = config.uploadSizeLimit;
        clientConfig.countries = addressMeta.countries;
        clientConfig.euCountriesCode = addressMeta.euCountriesCode;
        clientConfig.usStates = addressMeta.usStates;
        clientConfig.units = units;
        clientConfig.legal = config.legal;
        clientConfig.tagRegExp = History.tagRegExp;
        clientConfig.modelNameRegExp = ModelHelper.modelNameRegExp;
        clientConfig.fileNameRegExp = ModelHelper.fileNameRegExp;
        clientConfig.usernameRegExp = User.usernameRegExp;
        clientConfig.acceptedFormat = ModelHelper.acceptedFormat;
        clientConfig.login_check_interval = config.login_check_interval;

        clientConfig.responseCodes = _.each(responseCodes.codesMap);

        clientConfig.permissions = C.MODEL_PERM_OBJ;

        clientConfig.impliedPermission = C.IMPLIED_PERM;

        setupPug(clientConfig, pluginStructure);

        return clientConfig;
    }

    const clientConfig = createClientConfig(config);

    router.get("/version.json", function (req, res) {
        return res.json({"VERSION": clientConfig.VERSION });
    });

    router.get("/config.js", function (req, res) {

        // Only need to set the userId the rest is static
        clientConfig.userId = _.get(req, "session.user.username");

        // TODO: This used to be a long string concat,
        // this is marginally better but still a complete hack.
        // There is definitely a better way to do this
        const serializedConfig = serialize(clientConfig);

        res.header("Content-Type", "text/javascript");
        res.render(path.resolve(__dirname, "./../../pug/config.pug"), {config: serializedConfig});
    });

    module.exports = router;
<commit_msg>ISSUE #750 - Remove dead code regarding server side pug rendering<commit_after>"use strict";

    const express = require("express");
    const router = express.Router({mergeParams: true});
    const responseCodes = require("../response_codes.js");
    const C = require("../constants");
    const serialize = require("serialize-javascript");
    const _ = require("lodash");
    const addressMeta = require("../models/addressMeta");
    const units = require("../models/unit");
    const History = require("../models/history");
    const ModelHelper = require("../models/helper/model");
    const User = require("../models/user");
    const DEFAULT_PLUGIN_STRUCTURE = require("../plugin/plugin-structure.js").DEFAULT_PLUGIN_STRUCTURE;
    const path = require("path");

    const config = require("../config");

    function createClientConfig(serverConfig, req) {

        // TODO: Replace with user based plugin selection
        let pluginStructure = {};

        // If the serverConfig has a plugin structure, use that
        // else just use the default
        if (serverConfig.pluginStructure) {
            pluginStructure = require("../../" + serverConfig.pluginStructure);
        } else {
            pluginStructure = DEFAULT_PLUGIN_STRUCTURE;
        }

        let clientConfig = {
            "maintenanceMode": config.maintenanceMode,
            "ui": {},
            "uistate": {},
            "structure": pluginStructure,
            "frontendPug": [],
            "gaTrackId": config.gaTrackId,
            "development" : config.development,
            "googleConversionId": config.googleConversionId,
            "userNotice" : config.userNotice,
            "unitySettings" : config.unitySettings,
            "customLogins" : config.customLogins
        };

        if (config.hasOwnProperty("captcha_client_key")) {
            clientConfig.captcha_client_key = config.captcha_client_key;
        }

        // Set up the legal plugins
        if (config.hasOwnProperty("legal")) {
            for (let i = 0; i < config.legal.length; i += 1) {
                pluginStructure.functions.push(config.legal[i].page);
            }
        }

        if (config.hasOwnProperty("captcha_client_key")) {
            clientConfig.captcha_client_key = config.captcha_client_key;
        }

        if (req) {
            clientConfig.userId = _.get(req, "session.user.username");
        }

        // Set up the legal plugins
        clientConfig.legalTemplates = [];
        if (config.hasOwnProperty("legal")) {
            clientConfig.legalTemplates = config.legal;
        }

        clientConfig.apiUrls = config.apiUrls;

        clientConfig.C = {
            GET_API : C.GET_API,
            POST_API : C.POST_API,
            MAP_API : C.MAP_API
        };

        if (config.chat_server) {
            clientConfig.chatHost = config.chat_server.chat_host;
            clientConfig.chatPath = "/" + config.chat_server.subdirectory;
        }

        clientConfig.chatReconnectionAttempts = config.chat_reconnection_attempts;

        clientConfig.VERSION = config.version;

        if (serverConfig.backgroundImage) {
            clientConfig.backgroundImage = serverConfig.backgroundImage;
        }

        clientConfig.return_path = "/";

        clientConfig.auth =  config.auth;

        if(config.captcha && config.captcha.clientKey) {
            clientConfig.captcha_client_key = config.captcha.clientKey;
        }

        clientConfig.uploadSizeLimit = config.uploadSizeLimit;
        clientConfig.countries = addressMeta.countries;
        clientConfig.euCountriesCode = addressMeta.euCountriesCode;
        clientConfig.usStates = addressMeta.usStates;
        clientConfig.units = units;
        clientConfig.legal = config.legal;
        clientConfig.tagRegExp = History.tagRegExp;
        clientConfig.modelNameRegExp = ModelHelper.modelNameRegExp;
        clientConfig.fileNameRegExp = ModelHelper.fileNameRegExp;
        clientConfig.usernameRegExp = User.usernameRegExp;
        clientConfig.acceptedFormat = ModelHelper.acceptedFormat;
        clientConfig.login_check_interval = config.login_check_interval;

        clientConfig.responseCodes = _.each(responseCodes.codesMap);

        clientConfig.permissions = C.MODEL_PERM_OBJ;

        clientConfig.impliedPermission = C.IMPLIED_PERM;

        return clientConfig;
    }

    const clientConfig = createClientConfig(config);

    router.get("/version.json", function (req, res) {
        return res.json({"VERSION": clientConfig.VERSION });
    });

    router.get("/config.js", function (req, res) {

        // Only need to set the userId the rest is static
        clientConfig.userId = _.get(req, "session.user.username");

        // TODO: This used to be a long string concat,
        // this is marginally better but still a complete hack.
        // There is definitely a better way to do this
        const serializedConfig = serialize(clientConfig);

        res.header("Content-Type", "text/javascript");
        res.render(path.resolve(__dirname, "./../../pug/config.pug"), {config: serializedConfig});
    });

    module.exports = router;
<|endoftext|>


<commit_before>module.exports = {
  up: (queryInterface, Sequelize) => queryInterface.createTable('Users', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: Sequelize.INTEGER
    },
    username: {
      type: Sequelize.STRING
    },
    firstname: {
      type: Sequelize.STRING
    },
    lastname: {
      type: Sequelize.STRING
    },
    email: {
      type: Sequelize.STRING
    },
    password: {
      type: Sequelize.STRING
    },
    roleId: {
      type: Sequelize.INTEGER,
      references: {
        model: 'Roles',
        key: 'id',
      }
    },
    createdAt: {
      allowNull: false,
      type: Sequelize.DATE
    },
    updatedAt: {
      allowNull: false,
      type: Sequelize.DATE
    }
  }),
  down: queryInterface => queryInterface.dropTable('Users')
};
<commit_msg>chore(migrations/...create-users.js): delete migrations for users and migrate users again to fix validation error [#144210907]<commit_after><|endoftext|>


<commit_before>/**
 * This class handles LZW encoding
 * Adapted from Jef Poskanzer's Java port by way of J. M. G. Elliott.
 * @author Kevin Weiner (original Java version - kweiner@fmsware.com)
 * @author Thibault Imbert (AS3 version - bytearray.org)
 * @author Kevin Kwok (JavaScript version - https://github.com/antimatter15/jsgif)
 * @version 0.1 AS3 implementation
 */

LZWEncoder = function()
{
    var exports = {};
	var EOF = -1;
	var imgW;
	var imgH
	var pixAry;
	var initCodeSize;
	var remaining;
	var curPixel;

	// GIFCOMPR.C - GIF Image compression routines
	// Lempel-Ziv compression based on 'compress'. GIF modifications by
	// David Rowley (mgardi@watdcsu.waterloo.edu)
	// General DEFINEs

	var BITS = 12;
	var HSIZE = 5003; // 80% occupancy

	// GIF Image compression - modified 'compress'
	// Based on: compress.c - File compression ala IEEE Computer, June 1984.
	// By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)
	// Jim McKie (decvax!mcvax!jim)
	// Steve Davies (decvax!vax135!petsd!peora!srd)
	// Ken Turkowski (decvax!decwrl!turtlevax!ken)
	// James A. Woods (decvax!ihnp4!ames!jaw)
	// Joe Orost (decvax!vax135!petsd!joe)

	var n_bits // number of bits/code
	var maxbits = BITS; // user settable max # bits/code
	var maxcode // maximum code, given n_bits
	var maxmaxcode = 1 << BITS; // should NEVER generate this code
	var htab = new Array;
	var codetab = new Array;
	var hsize = HSIZE; // for dynamic table sizing
	var free_ent = 0; // first unused entry

	// block compression parameters -- after all codes are used up,
	// and compression rate changes, start over.

	var clear_flg = false;

	// Algorithm: use open addressing double hashing (no chaining) on the
	// prefix code / next character combination. We do a variant of Knuth's
	// algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
	// secondary probe. Here, the modular division first probe is gives way
	// to a faster exclusive-or manipulation. Also do block compression with
	// an adaptive reset, whereby the code table is cleared when the compression
	// ratio decreases, but after the table fills. The variable-length output
	// codes are re-sized at this point, and a special CLEAR code is generated
	// for the decompressor. Late addition: construct the table according to
	// file size for noticeable speed improvement on small files. Please direct
	// questions about this implementation to ames!jaw.

	var g_init_bits;
	var ClearCode;
	var EOFCode;

	// output
	// Output the given code.
	// Inputs:
	// code: A n_bits-bit integer. If == -1, then EOF. This assumes
	// that n_bits =< wordsize - 1.
	// Outputs:
	// Outputs code to the file.
	// Assumptions:
	// Chars are 8 bits long.
	// Algorithm:
	// Maintain a BITS character long buffer (so that 8 codes will
	// fit in it exactly). Use the VAX insv instruction to insert each
	// code in turn. When the buffer fills up empty it and start over.

	var cur_accum = 0;
	var cur_bits = 0;
	var masks = [ 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF ];

	// Number of characters so far in this 'packet'
	var a_count;

	// Define the storage for the packet accumulator
	var accum = [];

	var LZWEncoder = exports.LZWEncoder = function LZWEncoder (width, height, pixels, color_depth)
	{

		imgW = width;
		imgH = height;
		pixAry = pixels;
		initCodeSize = Math.max(2, color_depth);

	}

	// Add a character to the end of the current packet, and if it is 254
	// characters, flush the packet to disk.
	var char_out = function char_out(c, outs)
	{
		accum[a_count++] = c;
		if (a_count >= 254) flush_char(outs);

	}

	// Clear out the hash table
	// table clear for block compress

	var cl_block = function cl_block(outs)
	{

		cl_hash(hsize);
		free_ent = ClearCode + 2;
		clear_flg = true;
		output(ClearCode, outs);

	}

	// reset code table
	var cl_hash = function cl_hash(hsize)
	{

		for (var i = 0; i < hsize; ++i) htab[i] = -1;

	}

	var compress = exports.compress = function compress(init_bits, outs)

	{
		var fcode;
		var i /* = 0 */;
		var c;
		var ent;
		var disp;
		var hsize_reg;
		var hshift;

		// Set up the globals: g_init_bits - initial number of bits
		g_init_bits = init_bits;

		// Set up the necessary values
		clear_flg = false;
		n_bits = g_init_bits;
		maxcode = MAXCODE(n_bits);

		ClearCode = 1 << (init_bits - 1);
		EOFCode = ClearCode + 1;
		free_ent = ClearCode + 2;

		a_count = 0; // clear packet

		ent = nextPixel();

		hshift = 0;
		for (fcode = hsize; fcode < 65536; fcode *= 2)
			++hshift;
		hshift = 8 - hshift; // set hash code range bound

		hsize_reg = hsize;
		cl_hash(hsize_reg); // clear hash table

		output(ClearCode, outs);

		outer_loop: while ((c = nextPixel()) != EOF)

		{

			fcode = (c << maxbits) + ent;
			i = (c << hshift) ^ ent; // xor hashing

			if (htab[i] == fcode) {
				ent = codetab[i];
				continue;
			} else if (htab[i] >= 0) // non-empty slot
			{
				disp = hsize_reg - i; // secondary hash (after G. Knott)
				if (i == 0)
					disp = 1;
				do {

					if ((i -= disp) < 0) i += hsize_reg;

					if (htab[i] == fcode) {
						ent = codetab[i];
						continue outer_loop;
					}
				} while (htab[i] >= 0);
			}

			output(ent, outs);
			ent = c;
			if (free_ent < maxmaxcode) {
				codetab[i] = free_ent++; // code -> hashtable
				htab[i] = fcode;
			} else cl_block(outs);
		}

		// Put out the final code.
		output(ent, outs);
		output(EOFCode, outs);

	}

	// ----------------------------------------------------------------------------
	var encode = exports.encode = function encode(os)
	{
		os.writeByte(initCodeSize); // write "initial code size" byte
		remaining = imgW * imgH; // reset navigation variables
		curPixel = 0;
		compress(initCodeSize + 1, os); // compress and write the pixel data
		os.writeByte(0); // write block terminator

	}

	// Flush the packet to disk, and reset the accumulator
	var flush_char = function flush_char(outs)
	{

		if (a_count > 0)
		{
			outs.writeByte(a_count);
			outs.writeBytes(accum, 0, a_count);
			a_count = 0;
		}

	}

	var MAXCODE = function MAXCODE(n_bits)
	{

		return (1 << n_bits) - 1;

	}

	// ----------------------------------------------------------------------------
	// Return the next pixel from the image
	// ----------------------------------------------------------------------------

	var nextPixel = function nextPixel()
	{

		if (remaining == 0) return EOF;

		--remaining;

		var pix = pixAry[curPixel++];

		return pix & 0xff;

	}

	var output = function output(code, outs)

	{
		cur_accum &= masks[cur_bits];

		if (cur_bits > 0) cur_accum |= (code << cur_bits);
		else cur_accum = code;

		cur_bits += n_bits;

		while (cur_bits >= 8)

		{

			char_out((cur_accum & 0xff), outs);
			cur_accum >>= 8;
			cur_bits -= 8;

		}

		// If the next entry is going to be too big for the code size,
		// then increase it, if possible.

		if (free_ent > maxcode || clear_flg) {

			if (clear_flg) {

				maxcode = MAXCODE(n_bits = g_init_bits);
				clear_flg = false;

			} else {

				++n_bits;

				if (n_bits == maxbits) maxcode = maxmaxcode;

				else maxcode = MAXCODE(n_bits);

			}

		}

		if (code == EOFCode)
		{

			// At EOF, write the rest of the buffer.
			while (cur_bits > 0)
			{

				char_out((cur_accum & 0xff), outs);
				cur_accum >>= 8;
				cur_bits -= 8;
			}

			flush_char(outs);

		}

	}
	LZWEncoder.apply(this, arguments);
	return exports;
}
<commit_msg>Remove spacing which doesn't improve readability.<commit_after>/**
 * This class handles LZW encoding
 * Adapted from Jef Poskanzer's Java port by way of J. M. G. Elliott.
 * @author Kevin Weiner (original Java version - kweiner@fmsware.com)
 * @author Thibault Imbert (AS3 version - bytearray.org)
 * @author Kevin Kwok (JavaScript version - https://github.com/antimatter15/jsgif)
 * @version 0.1 AS3 implementation
 */

LZWEncoder = function()
{
    var exports = {};
	var EOF = -1;
	var imgW;
	var imgH
	var pixAry;
	var initCodeSize;
	var remaining;
	var curPixel;

	// GIFCOMPR.C - GIF Image compression routines
	// Lempel-Ziv compression based on 'compress'. GIF modifications by
	// David Rowley (mgardi@watdcsu.waterloo.edu)
	// General DEFINEs

	var BITS = 12;
	var HSIZE = 5003; // 80% occupancy

	// GIF Image compression - modified 'compress'
	// Based on: compress.c - File compression ala IEEE Computer, June 1984.
	// By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)
	// Jim McKie (decvax!mcvax!jim)
	// Steve Davies (decvax!vax135!petsd!peora!srd)
	// Ken Turkowski (decvax!decwrl!turtlevax!ken)
	// James A. Woods (decvax!ihnp4!ames!jaw)
	// Joe Orost (decvax!vax135!petsd!joe)

	var n_bits // number of bits/code
	var maxbits = BITS; // user settable max # bits/code
	var maxcode // maximum code, given n_bits
	var maxmaxcode = 1 << BITS; // should NEVER generate this code
	var htab = new Array;
	var codetab = new Array;
	var hsize = HSIZE; // for dynamic table sizing
	var free_ent = 0; // first unused entry

	// block compression parameters -- after all codes are used up,
	// and compression rate changes, start over.

	var clear_flg = false;

	// Algorithm: use open addressing double hashing (no chaining) on the
	// prefix code / next character combination. We do a variant of Knuth's
	// algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
	// secondary probe. Here, the modular division first probe is gives way
	// to a faster exclusive-or manipulation. Also do block compression with
	// an adaptive reset, whereby the code table is cleared when the compression
	// ratio decreases, but after the table fills. The variable-length output
	// codes are re-sized at this point, and a special CLEAR code is generated
	// for the decompressor. Late addition: construct the table according to
	// file size for noticeable speed improvement on small files. Please direct
	// questions about this implementation to ames!jaw.

	var g_init_bits;
	var ClearCode;
	var EOFCode;

	// output
	// Output the given code.
	// Inputs:
	// code: A n_bits-bit integer. If == -1, then EOF. This assumes
	// that n_bits =< wordsize - 1.
	// Outputs:
	// Outputs code to the file.
	// Assumptions:
	// Chars are 8 bits long.
	// Algorithm:
	// Maintain a BITS character long buffer (so that 8 codes will
	// fit in it exactly). Use the VAX insv instruction to insert each
	// code in turn. When the buffer fills up empty it and start over.

	var cur_accum = 0;
	var cur_bits = 0;
	var masks = [ 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF ];

	// Number of characters so far in this 'packet'
	var a_count;

	// Define the storage for the packet accumulator
	var accum = [];

	var LZWEncoder = exports.LZWEncoder = function LZWEncoder (width, height, pixels, color_depth)
	{
		imgW = width;
		imgH = height;
		pixAry = pixels;
		initCodeSize = Math.max(2, color_depth);
	}

	// Add a character to the end of the current packet, and if it is 254
	// characters, flush the packet to disk.
	var char_out = function char_out(c, outs)
	{
		accum[a_count++] = c;
		if (a_count >= 254) flush_char(outs);
	}

	// Clear out the hash table
	// table clear for block compress

	var cl_block = function cl_block(outs)
	{
		cl_hash(hsize);
		free_ent = ClearCode + 2;
		clear_flg = true;
		output(ClearCode, outs);
	}

	// reset code table
	var cl_hash = function cl_hash(hsize)
	{
		for (var i = 0; i < hsize; ++i) htab[i] = -1;
	}

	var compress = exports.compress = function compress(init_bits, outs)
	{
		var fcode;
		var i /* = 0 */;
		var c;
		var ent;
		var disp;
		var hsize_reg;
		var hshift;

		// Set up the globals: g_init_bits - initial number of bits
		g_init_bits = init_bits;

		// Set up the necessary values
		clear_flg = false;
		n_bits = g_init_bits;
		maxcode = MAXCODE(n_bits);

		ClearCode = 1 << (init_bits - 1);
		EOFCode = ClearCode + 1;
		free_ent = ClearCode + 2;

		a_count = 0; // clear packet

		ent = nextPixel();

		hshift = 0;
		for (fcode = hsize; fcode < 65536; fcode *= 2)
			++hshift;
		hshift = 8 - hshift; // set hash code range bound

		hsize_reg = hsize;
		cl_hash(hsize_reg); // clear hash table

		output(ClearCode, outs);

		outer_loop: while ((c = nextPixel()) != EOF)

		{
			fcode = (c << maxbits) + ent;
			i = (c << hshift) ^ ent; // xor hashing

			if (htab[i] == fcode) {
				ent = codetab[i];
				continue;
			} else if (htab[i] >= 0) // non-empty slot
			{
				disp = hsize_reg - i; // secondary hash (after G. Knott)
				if (i == 0)
					disp = 1;
				do {

					if ((i -= disp) < 0) i += hsize_reg;

					if (htab[i] == fcode) {
						ent = codetab[i];
						continue outer_loop;
					}
				} while (htab[i] >= 0);
			}

			output(ent, outs);
			ent = c;
			if (free_ent < maxmaxcode) {
				codetab[i] = free_ent++; // code -> hashtable
				htab[i] = fcode;
			} else cl_block(outs);
		}

		// Put out the final code.
		output(ent, outs);
		output(EOFCode, outs);
	}

	// ----------------------------------------------------------------------------
	var encode = exports.encode = function encode(os)
	{
		os.writeByte(initCodeSize); // write "initial code size" byte
		remaining = imgW * imgH; // reset navigation variables
		curPixel = 0;
		compress(initCodeSize + 1, os); // compress and write the pixel data
		os.writeByte(0); // write block terminator
	}

	// Flush the packet to disk, and reset the accumulator
	var flush_char = function flush_char(outs)
	{

		if (a_count > 0)
		{
			outs.writeByte(a_count);
			outs.writeBytes(accum, 0, a_count);
			a_count = 0;
		}
	}

	var MAXCODE = function MAXCODE(n_bits)
	{
		return (1 << n_bits) - 1;
	}

	// ----------------------------------------------------------------------------
	// Return the next pixel from the image
	// ----------------------------------------------------------------------------

	var nextPixel = function nextPixel()
	{
		if (remaining == 0) return EOF;
		--remaining;
		var pix = pixAry[curPixel++];
		return pix & 0xff;
	}

	var output = function output(code, outs)

	{
		cur_accum &= masks[cur_bits];

		if (cur_bits > 0) cur_accum |= (code << cur_bits);
		else cur_accum = code;

		cur_bits += n_bits;

		while (cur_bits >= 8)

		{
			char_out((cur_accum & 0xff), outs);
			cur_accum >>= 8;
			cur_bits -= 8;
		}

		// If the next entry is going to be too big for the code size,
		// then increase it, if possible.

		if (free_ent > maxcode || clear_flg) {

			if (clear_flg) {

				maxcode = MAXCODE(n_bits = g_init_bits);
				clear_flg = false;

			} else {

				++n_bits;
				if (n_bits == maxbits) maxcode = maxmaxcode;
				else maxcode = MAXCODE(n_bits);
			}
		}

		if (code == EOFCode)
		{

			// At EOF, write the rest of the buffer.
			while (cur_bits > 0)
			{
				char_out((cur_accum & 0xff), outs);
				cur_accum >>= 8;
				cur_bits -= 8;
			}

			flush_char(outs);
		}
	}

	LZWEncoder.apply(this, arguments);
	return exports;
}
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

Menubar.Edit = function ( editor ) {

	var container = new UI.Panel();
	container.setClass( 'menu' );

	var title = new UI.Panel();
	title.setClass( 'title' );
	title.setTextContent( 'Edit' );
	container.add( title );

	var options = new UI.Panel();
	options.setClass( 'options' );
	container.add( options );

	// Clone

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Clone' );
	option.onClick( function () {

		var object = editor.selected;

		if ( object.parent === undefined ) return; // avoid cloning the camera or scene

		object = object.clone();

		editor.addObject( object );
		editor.select( object );

	} );
	options.add( option );

	// Delete

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Delete' );
	option.onClick( function () {

		var object = editor.selected;

		if ( confirm( 'Delete ' + object.name + '?' ) === false ) return;

		var parent = object.parent;
		editor.removeObject( object );
		editor.select( parent );

	} );
	options.add( option );

	return container;

};
<commit_msg>Editor: GLSL minification.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

Menubar.Edit = function ( editor ) {

	var container = new UI.Panel();
	container.setClass( 'menu' );

	var title = new UI.Panel();
	title.setClass( 'title' );
	title.setTextContent( 'Edit' );
	container.add( title );

	var options = new UI.Panel();
	options.setClass( 'options' );
	container.add( options );

	// Clone

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Clone' );
	option.onClick( function () {

		var object = editor.selected;

		if ( object.parent === undefined ) return; // avoid cloning the camera or scene

		object = object.clone();

		editor.addObject( object );
		editor.select( object );

	} );
	options.add( option );

	// Delete

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Delete' );
	option.onClick( function () {

		var object = editor.selected;

		if ( confirm( 'Delete ' + object.name + '?' ) === false ) return;

		var parent = object.parent;
		editor.removeObject( object );
		editor.select( parent );

	} );
	options.add( option );

	// Minify shaders

	var option = new UI.Panel();
	option.setClass( 'option' );
	option.setTextContent( 'Minify Shaders' );
	option.onClick( function() {

		var root = editor.selected || editor.scene;

		var errors = [];
		var nMaterialsChanged = 0;

		var path = [];

		function getPath ( object ) {

			path.length = 0;

			var parent = object.parent;
			if ( parent !== undefined ) getPath( parent );

			path.push( object.name || object.uuid );

			return path;

		}

		root.traverse( function ( object ) {

			var material = object.material;

			if ( material instanceof THREE.ShaderMaterial ) {

				try {

					var shader = glslprep.minifyGlsl( [
							material.vertexShader, material.fragmentShader ] );

					material.vertexShader = shader[ 0 ];
					material.fragmentShader = shader[ 1 ];

					++nMaterialsChanged;

				} catch ( e ) {

					var path = getPath( object ).join( "/" );

					if ( e instanceof glslprep.SyntaxError )

						errors.push( path + ":" +
								e.line + ":" + e.column + ": " + e.message );

					else {

						errors.push( path +
								": Unexpected error (see console for details)." );

						console.error( e.stack || e );

					}

				}

			}

		} );

		window.alert( nMaterialsChanged +
				" material(s) were changed.\n" + errors.join( "\n" ) );

	} );
	options.add( option );

	return container;

};
<|endoftext|>