<commit_before>"use strict";
/*jslint browser: true*/
/*global Tangram, gui */

// initialize variables
var map, views, queue, nextView,
    newImg, newCanvas, newCtx, newData,
    oldImg, oldCanvas, oldCtx, oldData,
    diffCanvas, diffCtx, diff;
var testsFile = "./views.json";
var imgDir = "images/";
var imgType = ".png";
var size = 250; // pixels
var scores = [], totalScore = 0;
var tests = document.getElementById("tests");
var statusDiv = document.getElementById("status");
var totalScoreDiv = document.getElementById("totalScore");

// load file
function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}

// setup divs and canvases
var prep = new Promise( function (resolve, reject) {

    // load and parse test json
    readTextFile(testsFile, function(text){
        var data = JSON.parse(text);
        // convert tests to an array for easier traversal
        views = Object.keys(data.tests).map(function (key) {
            // add test's name as a property of the test
            data.tests[key].name = key;
            return data.tests[key];
        });

        // clone views array
        queue = views.slice(0);
        nextView = queue.shift(); // pop first
        // then initialize Tangram with the first view
        map = (function () {
            // console.log('views:', views);
            // console.log('nextView', nextView.location);
            var map_start_location = nextView.location;

            /*** Map ***/

            var map = L.map('map', {
                keyboardZoomOffset : .05,
                zoomControl: false,
                attributionControl : false
            });

            var layer = Tangram.leafletLayer({
                scene: nextView.url,
                // highDensityDisplay: false
            });

            window.layer = layer;
            var scene = layer.scene;
            window.scene = scene;

            // setView expects format ([lat, long], zoom)
            map.setView(map_start_location.slice(0, 3), map_start_location[2]);

            layer.addTo(map);

            return map;

        }());

        // subscribe to Tangram's published view_complete event to
        // load the next scene when the current scene is done drawing
        scene.subscribe({
            view_complete: function () {
                // console.log('nextView:', nextView);
                if (nextView) {
                    // when prep is done, screenshot is made, and oldImg is loaded...
                    Promise.all([prep,screenshot(true),loadOld(imgDir+nextView.name+imgType)]).then(function() {
                        // perform the diff
                        doDiff(nextView);
                        // move along
                        if (queue.length > 0) {
                            nextView = queue.shift(); // pop first
                            loadView(nextView);
                        } else return;
                    });
                } else {
                    console.log('view_complete, no nextView');
                    return viewComplete();
                }
            }
        });

        // set page title
        document.getElementById('title').innerHTML = testsFile;

    });

    // set sizes
    document.getElementById("map").style.height = size+"px";
    document.getElementById("map").style.width = size+"px";

    // set up canvases

    // make canvas for the old image
    oldCanvas = document.createElement('canvas');
    oldCanvas.height = size;
    oldCanvas.width = size;
    oldCtx = oldCanvas.getContext('2d');

    // make a canvas for the newly-drawn map image
    newCanvas = document.createElement('canvas');
    newCanvas.height = size;
    newCanvas.width = size;
    newCtx = newCanvas.getContext('2d');

    // make a canvas for the diff
    diffCanvas = document.createElement('canvas');
    diffCanvas.height = size;
    diffCanvas.width = size;
    diffCtx = diffCanvas.getContext('2d');
    diff = diffCtx.createImageData(size, size);

    resolve();
});

// load an image asynchronously with a Promise
function loadImage (url, target) {
    return new Promise(function(resolve, reject) {
        var image = target || new Image();
        image.onload = function() {
            resolve({ url: url, image: image });
        };
        image.onerror = function(error) {
            resolve({ error: error });
        };
        image.crossOrigin = 'anonymous';
        // force-refresh any local images with a cache-buster
        if (url.slice(-4) == ".png") url += "?" + new Date().getTime();
        image.src = url;
    });
}

// load the old image
function loadOld (img) {
    oldImg = new Image();
    return loadImage(img).then(function(result){
        if (result.url) {
            // set the old image to be drawn to the canvas once the image loads
            oldImg = result.image;
            oldCtx.drawImage(oldImg, 0, 0, oldImg.width, oldImg.height, 0, 0, oldCanvas.width, oldCanvas.height);
        }
        // make the data available to pixelmatch
        oldData = oldCtx.getImageData(0, 0, size, size);
        return result;
    });
};

// take a screenshot
function screenshot (save) {
    return scene.screenshot().then(function(data) {
        // save it to a file
        if (save) saveAs(data.blob, nextView.name);

        var urlCreator = window.URL || window.webkitURL;
        newImg = new Image();
        return loadImage(urlCreator.createObjectURL( data.blob ), newImg);
    });
};

// perform the image comparison and update the html
function doDiff( test ) {
    // save the new image to the new canvas, stretching it to fit (in case it's retina)
    newCtx.drawImage(newImg, 0, 0, newImg.width, newImg.height, 0, 0, newCanvas.width, newCanvas.height);
    // make the data available
    var newData = newCtx.getImageData(0, 0, size, size);

    // run the diff
    var difference = pixelmatch(newData.data, oldData.data, diff.data, size, size, {threshold: 0.1});

    // UPDATE READOUTS
    var count = views.length-queue.length;
    statusDiv.innerHTML = count + " of " + views.length;

    // calculate match percentage
    var match = 100-(difference/(size*size)*100*100)/100;
    var matchScore = Math.floor(match);

    // update master percentage
    scores[test.name] = match;
    var totalSum = 0;
    for (var v in scores) {
        totalSum += scores[v];
    }
    totalScore = Math.floor(totalSum/(100*count)*100);
    var threatLevel = totalScore > 99 ? "green" : totalScore > 98 ? "orange" : "red";
    totalScoreDiv.innerHTML = "
"+totalScore+"% match

";

    // put the diff in its canvas
    diffCtx.putImageData(diff, 0, 0);

    // make an output row
    makeRow(test, matchScore);
};

function loadView (view) {
    // load and draw scene
    scene.load(view.url).then(function() {
        // if (view) console
        if (!view) return;
        scene.animated = false;
        map.setView([view.location[0], view.location[1]], view.location[2]);
        scene.requestRedraw();
    });
}

// save a file with a POST request to the server
function saveAs( file, filename ) {
    var url = '/save';
    var data = new FormData();

    data.append("image", file, filename);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.onload = function () {
        // console.log('response:', this.responseText);
        // window.location.href = ".#"+this.responseText;
    };
    xhr.send(data);
}

function stop() {
    console.log('stop button');
    nextView = false;
    queue = false;
}

// convert event to promise
function viewComplete () {
    console.log('viewComplete');
    return new Promise(function(resolve, reject) {
        console.log('viewComplete sent');
        resolve();
    });
}

function makeRow(test, matchScore) {
    // check to see if div already exists (if re-running a test);
    var testdiv = document.getElementById(test.name);

    if (testdiv === null) {
        // generate test output row
        var testdiv = document.createElement('div');
        testdiv.className = 'test';
        testdiv.id = test.name;
        tests.insertBefore(testdiv, tests.firstChild);
    } else {
        // clear it out
        testdiv.innerHTML = "";
    }
    testdiv.style.minHeight = size+"px";

    var title = document.createElement('div');
    title.className = 'testname';
    title.innerHTML = test.name;
    testdiv.appendChild(title);

    var oldcolumn = document.createElement('span');
    oldcolumn.className = 'column';
    oldcolumn.id = "old";
    oldcolumn.innerHTML = "old";
    testdiv.appendChild(oldcolumn);

    var newcolumn = document.createElement('span');
    newcolumn.className = 'column';
    newcolumn.id = "new";
    newcolumn.innerHTML = "new";
    testdiv.appendChild(newcolumn);

    var diffcolumn = document.createElement('span');
    diffcolumn.className = 'column';
    diffcolumn.id = "diff";
    diffcolumn.innerHTML = "diff";
    testdiv.appendChild(diffcolumn);

    // per-test controls
    var controls = document.createElement('div');
    testdiv.appendChild(controls);

    controls.className = 'controls';
    var threatLevel = matchScore > 99 ? "green" : matchScore > 98 ? "orange" : "red";
    controls.innerHTML = "
"+matchScore+"% match

";

        var refreshButton =  document.createElement('button');
        refreshButton.innerHTML = "refresh " + test.name;
        controls.appendChild(refreshButton);
        refreshButton.onclick = function() {refresh(test);}

        var exportButton =  document.createElement('button');
        exportButton.innerHTML = "export " + test.name;
        // controls.appendChild(exportButton);

        var exportStripButton =  document.createElement('button');
        exportStripButton.innerHTML = "export strip";
        exportStripButton.onclick = "export strip";
        // controls.appendChild(exportStripButton);

        var exportGifButton =  document.createElement('button');
        exportGifButton.innerHTML = "export gif";
        // controls.appendChild(exportGifButton);

    // make imgs for new, old, and diff and attach them to the document
    newImg.width = size;
    newImg.height = size;
    newcolumn.appendChild( newImg );

    oldImg.width = size;
    oldImg.height = size;
    oldcolumn.appendChild( oldImg );

    var diffimg = document.createElement('img');
    diffimg.src = diffCanvas.toDataURL("image/png");
    diffcolumn.appendChild( diffimg );

}

function rerunAll() {
    console.log('refresh all button');
    tests.innerHTML = "";
    totalScoreDiv.innerHTML = "";
    nextView = false;
    totalSum = 0;
    totalScore = 0;
    queue = views.slice(0);
    startRender();
}

function refresh(test) {
    // console.log('refreshing:', test);
    // var testdiv = document.getElementById(test.name);
    // testdiv.innerHTML = "";
    queue = [test];
    startRender();
}

function startRender() {
    // if map is rendering, wait for it to finish, then start over
    Promise.all([viewComplete]).then(function() {
        // console.log('viewComplete received');
        // move along
        nextView = queue.shift()
        loadView(nextView);
    });
}<commit_msg>cleanup<commit_after>"use strict";
/*jslint browser: true*/
/*global Tangram, gui */

// initialize variables
var map, views, queue, nextView,
    newImg, newCanvas, newCtx, newData,
    oldImg, oldCanvas, oldCtx, oldData,
    diffCanvas, diffCtx, diff;
var testsFile = "./views.json";
var imgDir = "images/";
var imgType = ".png";
var size = 250; // pixels
var scores = [], totalScore = 0;
var tests = document.getElementById("tests");
var statusDiv = document.getElementById("status");
var totalScoreDiv = document.getElementById("totalScore");

// load file
function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}

// setup divs and canvases
var prep = new Promise( function (resolve, reject) {

    // load and parse test json
    readTextFile(testsFile, function(text){
        var data = JSON.parse(text);
        // convert tests to an array for easier traversal
        views = Object.keys(data.tests).map(function (key) {
            // add test's name as a property of the test
            data.tests[key].name = key;
            return data.tests[key];
        });

        // clone views array
        queue = views.slice(0);
        nextView = queue.shift(); // pop first
        // then initialize Tangram with the first view
        map = (function () {
            // console.log('views:', views);
            // console.log('nextView', nextView.location);
            var map_start_location = nextView.location;

            /*** Map ***/

            var map = L.map('map', {
                keyboardZoomOffset : .05,
                zoomControl: false,
                attributionControl : false
            });

            var layer = Tangram.leafletLayer({
                scene: nextView.url,
                // highDensityDisplay: false
            });

            window.layer = layer;
            var scene = layer.scene;
            window.scene = scene;

            // setView expects format ([lat, long], zoom)
            map.setView(map_start_location.slice(0, 3), map_start_location[2]);

            layer.addTo(map);

            return map;

        }());

        // subscribe to Tangram's published view_complete event to
        // load the next scene when the current scene is done drawing
        scene.subscribe({
            view_complete: function () {
                // console.log('nextView:', nextView);
                if (nextView) {
                    // when prep is done, screenshot is made, and oldImg is loaded...
                    Promise.all([prep,screenshot(true),loadOld(imgDir+nextView.name+imgType)]).then(function() {
                        // perform the diff
                        doDiff(nextView);
                        // move along
                        if (queue.length > 0) {
                            nextView = queue.shift(); // pop first
                            loadView(nextView);
                        } else return;
                    });
                } else {
                    console.log('view_complete, no nextView');
                    return viewComplete();
                }
            }
        });

        // set page title
        document.getElementById('title').innerHTML = testsFile;

    });

    // set sizes
    document.getElementById("map").style.height = size+"px";
    document.getElementById("map").style.width = size+"px";

    // set up canvases

    // make canvas for the old image
    oldCanvas = document.createElement('canvas');
    oldCanvas.height = size;
    oldCanvas.width = size;
    oldCtx = oldCanvas.getContext('2d');

    // make a canvas for the newly-drawn map image
    newCanvas = document.createElement('canvas');
    newCanvas.height = size;
    newCanvas.width = size;
    newCtx = newCanvas.getContext('2d');

    // make a canvas for the diff
    diffCanvas = document.createElement('canvas');
    diffCanvas.height = size;
    diffCanvas.width = size;
    diffCtx = diffCanvas.getContext('2d');
    diff = diffCtx.createImageData(size, size);

    resolve();
});

// load an image asynchronously with a Promise
function loadImage (url, target) {
    return new Promise(function(resolve, reject) {
        var image = target || new Image();
        image.onload = function() {
            resolve({ url: url, image: image });
        };
        image.onerror = function(error) {
            resolve({ error: error });
        };
        image.crossOrigin = 'anonymous';
        // force-refresh any local images with a cache-buster
        if (url.slice(-4) == imgType) url += "?" + new Date().getTime();
        image.src = url;
    });
}

// load the old image
function loadOld (img) {
    oldImg = new Image();
    return loadImage(img).then(function(result){
        if (result.url) {
            // set the old image to be drawn to the canvas once the image loads
            oldImg = result.image;
            oldCtx.drawImage(oldImg, 0, 0, oldImg.width, oldImg.height, 0, 0, oldCanvas.width, oldCanvas.height);
        }
        // make the data available to pixelmatch
        oldData = oldCtx.getImageData(0, 0, size, size);
        return result;
    });
};

// take a screenshot
function screenshot (save) {
    return scene.screenshot().then(function(data) {
        // save it to a file
        if (save) saveAs(data.blob, nextView.name);

        var urlCreator = window.URL || window.webkitURL;
        newImg = new Image();
        return loadImage(urlCreator.createObjectURL( data.blob ), newImg);
    });
};

// perform the image comparison and update the html
function doDiff( test ) {
    // save the new image to the new canvas, stretching it to fit (in case it's retina)
    newCtx.drawImage(newImg, 0, 0, newImg.width, newImg.height, 0, 0, newCanvas.width, newCanvas.height);
    // make the data available
    var newData = newCtx.getImageData(0, 0, size, size);

    // run the diff
    var difference = pixelmatch(newData.data, oldData.data, diff.data, size, size, {threshold: 0.1});

    // UPDATE READOUTS
    var count = views.length-queue.length;
    statusDiv.innerHTML = count + " of " + views.length;

    // calculate match percentage
    var match = 100-(difference/(size*size)*100*100)/100;
    var matchScore = Math.floor(match);

    // update master percentage
    scores[test.name] = match;
    var totalSum = 0;
    for (var v in scores) {
        totalSum += scores[v];
    }
    totalScore = Math.floor(totalSum/(100*count)*100);
    var threatLevel = totalScore > 99 ? "green" : totalScore > 98 ? "orange" : "red";
    totalScoreDiv.innerHTML = "
"+totalScore+"% match

";

    // put the diff in its canvas
    diffCtx.putImageData(diff, 0, 0);

    // make an output row
    makeRow(test, matchScore);
};

function loadView (view) {
    // load and draw scene
    scene.load(view.url).then(function() {
        // if (view) console
        if (!view) return;
        scene.animated = false;
        map.setView([view.location[0], view.location[1]], view.location[2]);
        scene.requestRedraw();
    });
}

// save a file with a POST request to the server
function saveAs( file, filename ) {
    var url = '/save';
    var data = new FormData();

    data.append("image", file, filename);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.onload = function () {
        // console.log('response:', this.responseText);
        // window.location.href = ".#"+this.responseText;
    };
    xhr.send(data);
}

function stop() {
    console.log('stop button');
    nextView = false;
    queue = false;
}

// convert event to promise
function viewComplete () {
    console.log('viewComplete');
    return new Promise(function(resolve, reject) {
        console.log('viewComplete sent');
        resolve();
    });
}

function makeRow(test, matchScore) {
    // check to see if div already exists (if re-running a test);
    var testdiv = document.getElementById(test.name);

    if (testdiv === null) {
        // generate test output row
        var testdiv = document.createElement('div');
        testdiv.className = 'test';
        testdiv.id = test.name;
        tests.insertBefore(testdiv, tests.firstChild);
    } else {
        // clear it out
        testdiv.innerHTML = "";
    }
    testdiv.style.minHeight = size+"px";

    var title = document.createElement('div');
    title.className = 'testname';
    title.innerHTML = test.name;
    testdiv.appendChild(title);

    var oldcolumn = document.createElement('span');
    oldcolumn.className = 'column';
    oldcolumn.id = "old";
    oldcolumn.innerHTML = "old";
    testdiv.appendChild(oldcolumn);

    var newcolumn = document.createElement('span');
    newcolumn.className = 'column';
    newcolumn.id = "new";
    newcolumn.innerHTML = "new";
    testdiv.appendChild(newcolumn);

    var diffcolumn = document.createElement('span');
    diffcolumn.className = 'column';
    diffcolumn.id = "diff";
    diffcolumn.innerHTML = "diff";
    testdiv.appendChild(diffcolumn);

    // per-test controls
    var controls = document.createElement('div');
    testdiv.appendChild(controls);

    controls.className = 'controls';
    var threatLevel = matchScore > 99 ? "green" : matchScore > 98 ? "orange" : "red";
    controls.innerHTML = "
"+matchScore+"% match

";

        var refreshButton =  document.createElement('button');
        refreshButton.innerHTML = "refresh " + test.name;
        controls.appendChild(refreshButton);
        refreshButton.onclick = function() {refresh(test);}

        var exportButton =  document.createElement('button');
        exportButton.innerHTML = "export " + test.name;
        // controls.appendChild(exportButton);

        var exportStripButton =  document.createElement('button');
        exportStripButton.innerHTML = "export strip";
        exportStripButton.onclick = "export strip";
        // controls.appendChild(exportStripButton);

        var exportGifButton =  document.createElement('button');
        exportGifButton.innerHTML = "export gif";
        // controls.appendChild(exportGifButton);

    // make imgs for new, old, and diff and attach them to the document
    newImg.width = size;
    newImg.height = size;
    newcolumn.appendChild( newImg );

    oldImg.width = size;
    oldImg.height = size;
    oldcolumn.appendChild( oldImg );

    var diffimg = document.createElement('img');
    diffimg.src = diffCanvas.toDataURL("image/png");
    diffcolumn.appendChild( diffimg );

}

function rerunAll() {
    console.log('refresh all button');
    tests.innerHTML = "";
    totalScoreDiv.innerHTML = "";
    nextView = false;
    totalSum = 0;
    totalScore = 0;
    queue = views.slice(0);
    startRender();
}

function refresh(test) {
    // console.log('refreshing:', test);
    queue.push(test);
    startRender();
}

function startRender() {
    // if map is rendering, wait for it to finish, then start over
    Promise.all([viewComplete]).then(function() {
        // move along
        nextView = queue.shift()
        loadView(nextView);
    });
}<|endoftext|>


<commit_before>/* global beforeEach, describe, expect, module, it, inject, spyOn */

(function () {

    'use strict';

    describe('login-redirect.services', function () {

        beforeEach(function () {
            var self = this;

            this.PROJECT_SETTINGS_MOCK = {
                API_HOST: '',
                TOKEN_AUTH: {
                    ALLOWED_HOSTS: []
                }
            };

            this.TOKEN_AUTH_MOCK = {};

            // Load some modules before mocking their constants.
            // angular-token-auth requires ngRoute but doesn't have it as a dep.
            module('ngRoute');
            module('angular-token-auth');
            module(function ($provide) {
                $provide.constant('PROJECT_SETTINGS', self.PROJECT_SETTINGS_MOCK);
                $provide.constant('TOKEN_AUTH', self.TOKEN_AUTH_MOCK);
            });

            module('angular-token-auth-login-redirect-token-auth-clear');

        });

        describe('onTokenAuthClear', function () {

            beforeEach(function () {

                this.$routeMock = {
                    current: {
                        $$route: {}
                    }
                };
                module({
                    $route: this.$routeMock
                });

                inject([
                    'authLoginRedirect.onTokenAuthClear',
                    function (onTokenAuthClear) {
                        this.onTokenAuthClear = onTokenAuthClear;
                    }
                ]);

            });

            describe('redirect method', function () {

                beforeEach(function () {

                    this.TOKEN_AUTH_MOCK.LOGOUT_REDIRECT_URL = '/?show-login';

                    inject(function ($location) {
                        this.$location = $location;
                    });
                    this.$location.url('/current/');
                    this.onTokenAuthClear.redirect();

                });

                it('should change the url to TOKEN_AUTH.LOGOUT_REDIRECT_URL with the next param set to the current path', function () {
                    expect(this.$location.path()).toBe('/');
                    expect(this.$location.search()).toEqual({
                        'show-login': true,
                        next: '/current/'
                    });
                });

            });

            describe('handler method', function () {

                beforeEach(function () {

                    spyOn(this.onTokenAuthClear, 'redirect');
                    spyOn(this.onTokenAuthClear, 'routeIsAnonymous');

                    this.run = function () {
                        this.onTokenAuthClear.handler();
                    };

                });

                it('should call routeIsAnonymous with the current route', function () {
                    this.run();
                    expect(this.onTokenAuthClear.routeIsAnonymous).toHaveBeenCalledWith(this.$routeMock.current.$$route);
                });

                it('should call redirect if routeIsAnonymous returns false', function () {
                    this.onTokenAuthClear.routeIsAnonymous.and.returnValue(false);
                    this.run();
                    expect(this.onTokenAuthClear.redirect).toHaveBeenCalled();
                });

                it('should not call redirect if routeIsAnonymous returns true', function () {
                    this.onTokenAuthClear.routeIsAnonymous.and.returnValue(true);
                    this.run();
                    expect(this.onTokenAuthClear.redirect).not.toHaveBeenCalled();
                });

            });

        });

    });

}());
<commit_msg>Ammend test.<commit_after>/* global beforeEach, describe, expect, module, it, inject, spyOn */

(function () {

    'use strict';

    describe('login-redirect.services', function () {

        beforeEach(function () {
            var self = this;

            this.PROJECT_SETTINGS_MOCK = {
                API_HOST: '',
                TOKEN_AUTH: {
                    ALLOWED_HOSTS: []
                }
            };

            this.TOKEN_AUTH_MOCK = {};

            // Load some modules before mocking their constants.
            // angular-token-auth requires ngRoute but doesn't have it as a dep.
            module('ngRoute');
            module('angular-token-auth');
            module(function ($provide) {
                $provide.constant('PROJECT_SETTINGS', self.PROJECT_SETTINGS_MOCK);
                $provide.constant('TOKEN_AUTH', self.TOKEN_AUTH_MOCK);
            });

            module('angular-token-auth-login-redirect-token-auth-clear');

        });

        describe('onTokenAuthClear', function () {

            beforeEach(function () {

                this.$routeMock = {
                    current: {
                        $$route: {}
                    }
                };
                module({
                    $route: this.$routeMock
                });

                inject([
                    'authLoginRedirect.onTokenAuthClear',
                    function (onTokenAuthClear) {
                        this.onTokenAuthClear = onTokenAuthClear;
                    }
                ]);

            });

            describe('routeIsAnonymous method', function () {

                beforeEach(function () {
                    var self = this;

                    // Routes are anonymous unless told not to be.
                    this.anonymousRoute = {};
                    this.nonAnonymousRoute = {
                        anonymous: false
                    };

                });

                it('should return false for a non-anonymous route', function () {
                    expect(this.onTokenAuthClear.routeIsAnonymous(self.nonAnonymousRoute)).toBe(false);
                });

                it('should return true for an anonymous route', function () {
                    expect(this.onTokenAuthClear.routeIsAnonymous(self.anonymousRoute)).toBe(true);
                });

            });

            describe('redirect method', function () {

                beforeEach(function () {

                    this.TOKEN_AUTH_MOCK.LOGOUT_REDIRECT_URL = '/?show-login';

                    inject(function ($location) {
                        this.$location = $location;
                    });
                    this.$location.url('/current/');
                });

                it('should change the url to TOKEN_AUTH.LOGOUT_REDIRECT_URL with the next param set to the current path', function () {
                    this.onTokenAuthClear.redirect();
                    expect(this.$location.path()).toBe('/');
                    expect(this.$location.search()).toEqual({
                        'show-login': true,
                        next: '/current/'
                    });
                });

            });

            describe('handler method', function () {

                beforeEach(function () {

                    spyOn(this.onTokenAuthClear, 'redirect');
                    spyOn(this.onTokenAuthClear, 'routeIsAnonymous');

                    this.run = function () {
                        this.onTokenAuthClear.handler();
                    };

                });

                it('should call routeIsAnonymous with the current route', function () {
                    this.run();
                    expect(this.onTokenAuthClear.routeIsAnonymous).toHaveBeenCalledWith(this.$routeMock.current.$$route);
                });

                it('should call redirect if routeIsAnonymous returns false', function () {
                    this.onTokenAuthClear.routeIsAnonymous.and.returnValue(false);
                    this.run();
                    expect(this.onTokenAuthClear.redirect).toHaveBeenCalled();
                });

                it('should not call redirect if routeIsAnonymous returns true', function () {
                    this.onTokenAuthClear.routeIsAnonymous.and.returnValue(true);
                    this.run();
                    expect(this.onTokenAuthClear.redirect).not.toHaveBeenCalled();
                });

            });

        });

    });

}());
<|endoftext|>


<commit_before>// Self executable function that handles the site routes and get's all the external modules
(function() {
    angular.module('ngWhisk', ['ui.bootstrap', 'ui.bootstrap.modal', 'ngSanitize', 'ngDialog', 'ngMessages']);
}());
<commit_msg>Delete<commit_after><|endoftext|>


<commit_before>// # Ghost Configuration
// Setup your Ghost install for various environments
// Documentation can be found at http://support.ghost.org/config/

var path = require('path'),
    config;

config = {
    // ### Production
    // When running Ghost in the wild, use the production environment
    // Configure your URL and mail settings here
    production: {
        url: 'http://baowenchen.com',
        mail: {},
        database: {
            client: 'sqlite3',
            connection: {
                filename: path.join(__dirname, '/content/data/ghost.db')
            },
            debug: false
        },

        server: {
            // Host to be passed to node's `net.Server#listen()`
            host: '128.199.128.146',
            // Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
            port: '2368'
        }
    },

    // ### Development **(default)**
    development: {
        // The url to use when providing links to the site, E.g. in RSS and email.
        // Change this to your Ghost blogs published URL.
        url: 'http://localhost:2368',

        // Example mail config
        // Visit http://support.ghost.org/mail for instructions
        // ```
        //  mail: {
        //      transport: 'SMTP',
        //      options: {
        //          service: 'Mailgun',
        //          auth: {
        //              user: '', // mailgun username
        //              pass: ''  // mailgun password
        //          }
        //      }
        //  },
        // ```

        database: {
            client: 'sqlite3',
            connection: {
                filename: path.join(__dirname, '/content/data/ghost-dev.db')
            },
            debug: false
        },
        server: {
            // Host to be passed to node's `net.Server#listen()`
            host: '127.0.0.1',
            // Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
            port: '2368'
        },
        paths: {
            contentPath: path.join(__dirname, '/content/')
        }
    },

    // **Developers only need to edit below here**

    // ### Testing
    // Used when developing Ghost to run tests and check the health of Ghost
    // Uses a different port number
    testing: {
        url: 'http://127.0.0.1:2369',
        database: {
            client: 'sqlite3',
            connection: {
                filename: path.join(__dirname, '/content/data/ghost-test.db')
            }
        },
        server: {
            host: '127.0.0.1',
            port: '2369'
        },
        logging: false
    },

    // ### Testing MySQL
    // Used by Travis - Automated testing run through GitHub
    'testing-mysql': {
        url: 'http://127.0.0.1:2369',
        database: {
            client: 'mysql',
            connection: {
                host     : '127.0.0.1',
                user     : 'root',
                password : '',
                database : 'ghost_testing',
                charset  : 'utf8'
            }
        },
        server: {
            host: '127.0.0.1',
            port: '2369'
        },
        logging: false
    },

    // ### Testing pg
    // Used by Travis - Automated testing run through GitHub
    'testing-pg': {
        url: 'http://127.0.0.1:2369',
        database: {
            client: 'pg',
            connection: {
                host     : '127.0.0.1',
                user     : 'postgres',
                password : '',
                database : 'ghost_testing',
                charset  : 'utf8'
            }
        },
        server: {
            host: '127.0.0.1',
            port: '2369'
        },
        logging: false
    }
};

// Export config
module.exports = config;
<commit_msg>changed url setting in config.js<commit_after>// # Ghost Configuration
// Setup your Ghost install for various environments
// Documentation can be found at http://support.ghost.org/config/

var path = require('path'),
    config;

config = {
    // ### Production
    // When running Ghost in the wild, use the production environment
    // Configure your URL and mail settings here
    production: {
        url: 'http://baowenchen.com:2368',
        mail: {},
        database: {
            client: 'sqlite3',
            connection: {
                filename: path.join(__dirname, '/content/data/ghost.db')
            },
            debug: false
        },

        server: {
            // Host to be passed to node's `net.Server#listen()`
            host: '128.199.128.146',
            // Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
            port: '2368'
        }
    },

    // ### Development **(default)**
    development: {
        // The url to use when providing links to the site, E.g. in RSS and email.
        // Change this to your Ghost blogs published URL.
        url: 'http://localhost:2368',

        // Example mail config
        // Visit http://support.ghost.org/mail for instructions
        // ```
        //  mail: {
        //      transport: 'SMTP',
        //      options: {
        //          service: 'Mailgun',
        //          auth: {
        //              user: '', // mailgun username
        //              pass: ''  // mailgun password
        //          }
        //      }
        //  },
        // ```

        database: {
            client: 'sqlite3',
            connection: {
                filename: path.join(__dirname, '/content/data/ghost-dev.db')
            },
            debug: false
        },
        server: {
            // Host to be passed to node's `net.Server#listen()`
            host: '127.0.0.1',
            // Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
            port: '2368'
        },
        paths: {
            contentPath: path.join(__dirname, '/content/')
        }
    },

    // **Developers only need to edit below here**

    // ### Testing
    // Used when developing Ghost to run tests and check the health of Ghost
    // Uses a different port number
    testing: {
        url: 'http://127.0.0.1:2369',
        database: {
            client: 'sqlite3',
            connection: {
                filename: path.join(__dirname, '/content/data/ghost-test.db')
            }
        },
        server: {
            host: '127.0.0.1',
            port: '2369'
        },
        logging: false
    },

    // ### Testing MySQL
    // Used by Travis - Automated testing run through GitHub
    'testing-mysql': {
        url: 'http://127.0.0.1:2369',
        database: {
            client: 'mysql',
            connection: {
                host     : '127.0.0.1',
                user     : 'root',
                password : '',
                database : 'ghost_testing',
                charset  : 'utf8'
            }
        },
        server: {
            host: '127.0.0.1',
            port: '2369'
        },
        logging: false
    },

    // ### Testing pg
    // Used by Travis - Automated testing run through GitHub
    'testing-pg': {
        url: 'http://127.0.0.1:2369',
        database: {
            client: 'pg',
            connection: {
                host     : '127.0.0.1',
                user     : 'postgres',
                password : '',
                database : 'ghost_testing',
                charset  : 'utf8'
            }
        },
        server: {
            host: '127.0.0.1',
            port: '2369'
        },
        logging: false
    }
};

// Export config
module.exports = config;
<|endoftext|>


<commit_before>import assign from 'object.assign';
import serialize, {hash_serializer} from 'form-serialize';

export function inputPropsLookup (inputProps, inputName){
    var props = inputProps[inputName];
    if(props) return assign({label: inputName}, props); // props found, easy.

    var inputNameTree = hash_serializer({}, inputName, null);
    var attrName = Object.keys(inputNameTree)[0]; // inputName describes only single path

    props = inputProps[attrName];

    if( !isNaN(parseInt(attrName)) ){ // skip number
        props = inputProps;
    }else if(props && props.type == 'nested'){ // continue with nested props
        props = props.fields;
    }else if(props){
        return props;
    }else throw (inputName+': props cannot be found.');

    var newInputName = inputName.replace(attrName, '');
    var nextAttrName =  Object.keys(inputNameTree[attrName])[0];

    // remove bracket
    newInputName = newInputName.replace('['+nextAttrName+']', '');
    newInputName = nextAttrName + newInputName;

    return inputPropsLookup(props, newInputName);
}

export function inputValueLookup(serializedValues, inputName){
    if(!serializedValues || Object.keys(serializedValues).length == 0) return null;

    var value = serializedValues[inputName];
    if(value) return value; // value found, easy.

    // try to serialize and traverse
    var inputNameTree = hash_serializer({}, inputName, null);
    var attrName = Object.keys(inputNameTree)[0]; // inputName describes only single path

    var next = inputNameTree[attrName];
    if(next == null) return null; // if it's already leaf, then no chance to be found.

    var nextAttrName =  Object.keys(next)[0];
    var newInputName = inputName.replace(attrName, '');

    // remove bracket
    newInputName = newInputName.replace('['+nextAttrName+']', '');

    if(newInputName === ''){
        return serializedValues[attrName] ?
            serializedValues[attrName][nextAttrName] : undefined;
    }
    newInputName = nextAttrName + newInputName;

    var nestedValues = serializedValues[attrName];
    return inputValueLookup(nestedValues, newInputName);
}

export function formInputsSerialize(form){
    return serialize(form, {hash: true});
}
<commit_msg>allow use options<commit_after>import assign from 'object.assign';
import serialize, {hash_serializer} from 'form-serialize';

export function inputPropsLookup (inputProps, inputName){
    var props = inputProps[inputName];
    if(props) return assign({label: inputName}, props); // props found, easy.

    var inputNameTree = hash_serializer({}, inputName, null);
    var attrName = Object.keys(inputNameTree)[0]; // inputName describes only single path

    props = inputProps[attrName];

    if( !isNaN(parseInt(attrName)) ){ // skip number
        props = inputProps;
    }else if(props && props.type == 'nested'){ // continue with nested props
        props = props.fields;
    }else if(props){
        return props;
    }else throw (inputName+': props cannot be found.');

    var newInputName = inputName.replace(attrName, '');
    var nextAttrName =  Object.keys(inputNameTree[attrName])[0];

    // remove bracket
    newInputName = newInputName.replace('['+nextAttrName+']', '');
    newInputName = nextAttrName + newInputName;

    return inputPropsLookup(props, newInputName);
}

export function inputValueLookup(serializedValues, inputName){
    if(!serializedValues || Object.keys(serializedValues).length == 0) return null;

    var value = serializedValues[inputName];
    if(value) return value; // value found, easy.

    // try to serialize and traverse
    var inputNameTree = hash_serializer({}, inputName, null);
    var attrName = Object.keys(inputNameTree)[0]; // inputName describes only single path

    var next = inputNameTree[attrName];
    if(next == null) return null; // if it's already leaf, then no chance to be found.

    var nextAttrName =  Object.keys(next)[0];
    var newInputName = inputName.replace(attrName, '');

    // remove bracket
    newInputName = newInputName.replace('['+nextAttrName+']', '');

    if(newInputName === ''){
        return serializedValues[attrName] ?
            serializedValues[attrName][nextAttrName] : undefined;
    }
    newInputName = nextAttrName + newInputName;

    var nestedValues = serializedValues[attrName];
    return inputValueLookup(nestedValues, newInputName);
}

export function formInputsSerialize(form, options){
    var options = options || { hash: true };
    return serialize(form, options);
}
<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.11.0');
		this.setClientTag('node:20-11-20');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2020  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('16.11.0');
		this.setClientTag('node:20-11-21');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>/**
 * Created by mcwmc on 28.05.2016.
 */
var config = require("./config.js");
var express = require("express");
var fs = require("fs");
var http = require("http");
var mysql = require("mysql");
var calendar = require('node-calendar');
const numCPUs = require('os').cpus().length;
const cluster = require('cluster');

if (cluster.isMaster) {
    // Fork workers.
    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('exit', function (worker, code, signal) {
        console.log("worker ${worker.process.pid} died");
    });
} else {
    // Workers can share any TCP connection
    // In this case it is an HTTP server
    var cal = new calendar.Calendar(calendar.SUNDAY);
    var d = new Date();
    var currMonth = d.getMonth() + 1;
    var currDay = d.getDay();
    var table = cal.monthdayscalendar(d.getFullYear(), currMonth);
    var events = [
        {
            day: 40,
            month: 1
        }
    ]; // TODO: QUERY EVENTS SELECT day, month, id, name, desc FROM config.sqlEventTable
    var buildstring = "";
    table.forEach(function (currWeekArray) {
        buildstring += "
";
       currWeekArray.forEach(function (currDayIteration) {
           if (currDayIteration !== 0) {
               events.forEach(function (currEvent) {
                   if (currEvent.day == currDayIteration && currEvent.month == currMonth) {
                       buildstring += "
" + currDayIteration + "
";
                       buildstring += "	";
                   } else {
                       // lol kein event
                       buildstring += "";
                       buildstring += "	";
                   }
               });
           } else {
               buildstring += "";
               buildstring += "	";
           }
       });
        buildstring += "
"
    });

    var app = express();
    app.use(express.static('assets/static'));
    app.get('/', function (req, res) {
        var template = fs.readFileSync("assets/html/main.html", "utf8");

        res.send('
' + buildstring + '
');
    });
    app.listen(config.webPort, function () {
        console.log('Example app listening on port ' + config.webPort + '!');
    });

}<commit_msg>fixed table<commit_after>/**
 * Created by mcwmc on 28.05.2016.
 */
var config = require("./config.js");
var express = require("express");
var fs = require("fs");
var http = require("http");
var mysql = require("mysql");
var calendar = require('node-calendar');
const numCPUs = require('os').cpus().length;
const cluster = require('cluster');

if (cluster.isMaster) {
    // Fork workers.
    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('exit', function (worker, code, signal) {
        console.log("worker ${worker.process.pid} died");
    });
} else {
    // Workers can share any TCP connection
    // In this case it is an HTTP server
    var cal = new calendar.Calendar(calendar.SUNDAY);
    var d = new Date();
    var currMonth = d.getMonth() + 1;
    var currDay = d.getDay();
    var table = cal.monthdayscalendar(d.getFullYear(), currMonth);
    var events = [
        {
            day: 40,
            month: 1
        }
    ]; // TODO: QUERY EVENTS SELECT day, month, id, name, desc FROM config.sqlEventTable
    var buildstring = "";
    table.forEach(function (currWeekArray) {
        buildstring += "
";
       currWeekArray.forEach(function (currDayIteration) {
           if (currDayIteration !== 0) {
               events.forEach(function (currEvent) {
                   if (currEvent.day == currDayIteration && currEvent.month == currMonth) {
                       buildstring += "
" + currDayIteration + "
";
                       buildstring += "	";
                   } else {
                       // lol kein event
                       buildstring += "
" + currDayIteration + "
";
                       buildstring += "	";
                   }
               });
           } else {
               buildstring += "";
               buildstring += "	";
           }
       });
        buildstring += "
"
    });

    var app = express();
    app.use(express.static('assets/static'));
    app.get('/', function (req, res) {
        var template = fs.readFileSync("assets/html/main.html", "utf8");

        res.send('
' + buildstring + '
');
    });
    app.listen(config.webPort, function () {
        console.log('Example app listening on port ' + config.webPort + '!');
    });

}<|endoftext|>


<commit_before>Turns = {};

Turns.inHand = function (set, card) {
  for (var i = 0; i < set.length; i++) {
    if (matchCard(set[i], card)) return true;
  }
  return false;
};

function matchCard(a, b) {
  return a.suit === b.suit && a.value === b.value;
}

Turns.getMatch = function (card, set) {
  var matches = Turns.findMatches(card, set); //see below
  if (matches.length > 0 ) {
    return Turns.bestMatch(matches); //see below
  }
  return null;
};

Turns.findMatches = function (card, set) {
  var matches = [];
  set.forEach(function (tableCard) {
    if (tableCard.value === card.value) matches.push([tableCard]);
  });

  if (matches.length > 0 ) return matches;

  for (var i = 2; i <= set.length; i++) {
    combinations(set, i, function (potentialMatch) {
      if (sumCards(potentialMatch) === card.value) matches.push(potentialMatch.slice());
    });
  }
  return matches;
};

Turns.bestMatch = function (matches) {
  var mostCoins = [0, null],
      mostCards = [0, null];

  for (var i = 0; i < matches.length; i++) {
    var match = matches[i];

    for (var j = 0; j < match.length; j++)
      if (match[j].suit === 'Coins' && match[j].value === 7) return match;

    var coinCount = match.filter(function (card) { return card.suit === 'Coins'}).length;

    if (coinCount > mostCoins[0]) mostCoins = [coinCount, match];
    if (match.length > mostCards[0]) mostCards = [match.length, match];
  }

  return (mostCards[0] > mostCoins[0]) ? mostCards[1] : mostCoins[1];
};

Turns.takeMatch = function (game, id, card, match) {
  match.forEach(function (matchCard) {
    game.players[id].pile.push(matchCard);
    game.table = Turns.removeCard(matchCard, game.table);
  });

  game.players[id].pile.push(card);
  game.lastScorer = id;

  if (game.table.length === 0) {
    game.players[id].score.scopa++;
  }
};

Turns.removeCard = function (card,set) {
  return set.filter(function (setCard) {
    return !matchCard(card, setCard);
  });
};

function sumCards(set) {
  return set.reduce(function (a, b) {
    return a + b. value;
  }, 0);
}

function combinations(numArr, choose, callback) {
  var n = numArr.length;
  var c = [];
  var inner = function(start, choose_) {
    if (choose_ == 0) {
      callback(c);
    } else {
      for (var i = start; i <= n - choose_; ++i) {
        c.push(numArr[i]);
        inner(i + 1, choose_ - 1);
        c.pop();
      }
    }
  }
  inner(0, choose);
} <commit_msg>Modified Turns.js to match other hand<commit_after>Turns = {};

Turns.inHand = function (set, card) {
  for (var i = 0; i < set.length; i++) {
    if (matchCard(set[i], card)) return true;
  }
  return false;
};

function matchCard(a, b) {
  return a.suit === b.suit && a.value === b.value;
}

Turns.getMatch = function (card, set) {
  var matches = Turns.findMatches(card, set); //see below
  if (matches.length > 0 ) {
    // return Turns.bestMatch(matches); //see below
   for (var i = 0; i < matches.length; i++) {
    var match = matches[i];
  }
    console.log(match);
    return match; //experimental
  }
  return null;
};

Turns.findMatches = function (card, set) {
  var matches = [];
  set.forEach(function (tableCard) {
    if (tableCard.value === card.value) matches.push([tableCard]);
  });

  if (matches.length > 0 ) return matches;

  // for (var i = 2; i <= set.length; i++) {
  //   combinations(set, i, function (potentialMatch) {
  //     if (sumCards(potentialMatch) === card.value) matches.push(potentialMatch.slice());
  //   });
  // }
  return matches;
};

// Turns.bestMatch = function (matches) {
//   var mostCoins = [0, null],
//       mostCards = [0, null];

//   for (var i = 0; i < matches.length; i++) {
//     var match = matches[i];

//     for (var j = 0; j < match.length; j++)
//       if (match[j].suit === 'Coins' && match[j].value === 7) return match;

//     var coinCount = match.filter(function (card) { return card.suit === 'Coins'}).length;

//     if (coinCount > mostCoins[0]) mostCoins = [coinCount, match];
//     if (match.length > mostCards[0]) mostCards = [match.length, match];
//   }

//   return (mostCards[0] > mostCoins[0]) ? mostCards[1] : mostCoins[1];
// };

Turns.takeMatch = function (game, id, card, match) {
  match.forEach(function (matchCard) {
    game.players[id].pile.push(matchCard);
    game.table = Turns.removeCard(matchCard, game.table);
  });

  game.players[id].pile.push(card);
  game.lastScorer = id;

  if (game.table.length === 0) {
    game.players[id].score.scopa++;
  }
};

Turns.removeCard = function (card,set) {
  return set.filter(function (setCard) {
    return !matchCard(card, setCard);
  });
};

function sumCards(set) {
  return set.reduce(function (a, b) {
    return a + b. value;
  }, 0);
}

// function combinations(numArr, choose, callback) {
//   var n = numArr.length;
//   var c = [];
//   var inner = function(start, choose_) {
//     if (choose_ == 0) {
//       callback(c);
//     } else {
//       for (var i = start; i <= n - choose_; ++i) {
//         c.push(numArr[i]);
//         inner(i + 1, choose_ - 1);
//         c.pop();
//       }
//     }
//   }
//   inner(0, choose);
// } <|endoftext|>


<commit_before>var React = require('react');
var ReactDOM = require('react-dom');
var ReactRouter = require('react-router');
var PureRenderMixin = require('react-addons-pure-render-mixin');

var browserHistory = ReactRouter.browserHistory;
var Route = ReactRouter.Route;
var Router = ReactRouter.Router;
var Link = ReactRouter.Link;

var samples = require('./sample-data');

var App = React.createClass({
  getInitialState: function() {
    return {
      "humans": {},
      "stores": {}
     };
  },
  loadSampleData: function(){
    this.setState(samples);
  },
  // Handle when user navigates to a conversation directly without first loading the index...
  componentWillMount: function(){
    if('human' in this.props.params){
      this.loadSampleData();
    }
  },
  render: function() {
    return (

        <button onClick={this.loadSampleData}>Load Sample Data</button>

          <InboxPane humans={this.state.humans} />
          {this.props.children || "Select a Conversation from the Inbox"}
          <StorePane stores={this.state.stores} />

    )
  }
});

var InboxPane = React.createClass({
  renderConvoSum: function(human){
    return <InboxItem key={human} index={human} details={this.props.humans[human]} />;
  },
  render : function() {
    return (

Inbox

        {Object.keys(this.props.humans).map(this.renderConvoSum)}

    )
  }
});

var InboxItem = React.createClass({
  mixins: [PureRenderMixin],

  sortByDate: function(a, b) {
    return a.time>b.time ? -1 : a.time<b.time ? 1 : 0;
  },
  messageSummary: function(conversations){
    var lastMessage = conversations.sort(this.sortByDate)[0];
    return lastMessage.who + ' said: "' + lastMessage.text + '" @ ' + lastMessage.time.toDateString();
  },
  render: function(){
    return (

        <Link to={'/conversation/' + encodeURIComponent(this.props.index)}>Conversation with {this.props.index}</Link> ({this.props.details.orders.sort(this.sortByDate)[0].status})

    )
  }
});

var ConversationPane = React.createClass({
  loadSampleData: function(human){
    this.setState({conversation: samples.humans[human].conversations});
  },
  // Handle when User navigates from / to /conversation/:human
  componentWillMount: function() {
    this.loadSampleData(this.props.params.human);
  },
  // Handle when User navigates between conversations
  componentWillReceiveProps: function(nextProps) {
    this.loadSampleData(nextProps.params.human);
  },

  sortByDateDesc: function(a, b) {
    return a.time  b.time ? 1 : 0;
  },

  renderMessage: function(val){
    return <Message who={val.who} text={val.text} key={val.time.getTime()} />;
  },
  render: function() {
    return (

Conversation

{this.props.params.human}

         {this.state.conversation.sort(this.sortByDateDesc).map(this.renderMessage)}

    )
  }
});

var Message = React.createClass({
  mixins: [PureRenderMixin],

  render: function() {
    return (

 "{this.props.text}"

    )
  }
});

var StorePane = React.createClass({
  renderStore: function(store){
    return <Store key={store} index={store} details={this.props.stores[store]} />;
  },
  render: function() {
    return (

Stores & Ovens

          {Object.keys(this.props.stores).map(this.renderStore)}

    )
  }
});

var Store = React.createClass({
  mixins: [PureRenderMixin],

  getCount: function(status){
    return this.props.details.orders.filter(function(n){ return n.status === status}).length;
  },
  render: function(){
    return (

{this.props.index}

 {this.getCount("Confirmed")}

 {this.getCount("In The Oven")}

 {this.getCount("Delivered")}

    )
  }
});

ReactDOM.render((
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <Route path="/conversation/:human" component={ConversationPane}></Route>
    </Route>
  </Router>
), document.querySelector('#main'))
<commit_msg>Wrapped element in proper div with proper classes.<commit_after>var React = require('react');
var ReactDOM = require('react-dom');
var ReactRouter = require('react-router');
var PureRenderMixin = require('react-addons-pure-render-mixin');

var browserHistory = ReactRouter.browserHistory;
var Route = ReactRouter.Route;
var Router = ReactRouter.Router;
var Link = ReactRouter.Link;

var samples = require('./sample-data');

var App = React.createClass({
  getInitialState: function() {
    return {
      "humans": {},
      "stores": {}
     };
  },
  loadSampleData: function(){
    this.setState(samples);
  },
  // Handle when user navigates to a conversation directly without first loading the index...
  componentWillMount: function(){
    if('human' in this.props.params){
      this.loadSampleData();
    }
  },
  render: function() {
    return (

        <button onClick={this.loadSampleData}>Load Sample Data</button>

          <InboxPane humans={this.state.humans} />
          {this.props.children ||

Select a Conversation from the Inbox

}
          <StorePane stores={this.state.stores} />

    )
  }
});

var InboxPane = React.createClass({
  renderConvoSum: function(human){
    return <InboxItem key={human} index={human} details={this.props.humans[human]} />;
  },
  render : function() {
    return (

Inbox

        {Object.keys(this.props.humans).map(this.renderConvoSum)}

    )
  }
});

var InboxItem = React.createClass({
  mixins: [PureRenderMixin],

  sortByDate: function(a, b) {
    return a.time>b.time ? -1 : a.time<b.time ? 1 : 0;
  },
  messageSummary: function(conversations){
    var lastMessage = conversations.sort(this.sortByDate)[0];
    return lastMessage.who + ' said: "' + lastMessage.text + '" @ ' + lastMessage.time.toDateString();
  },
  render: function(){
    return (

        <Link to={'/conversation/' + encodeURIComponent(this.props.index)}>Conversation with {this.props.index}</Link> ({this.props.details.orders.sort(this.sortByDate)[0].status})

    )
  }
});

var ConversationPane = React.createClass({
  loadSampleData: function(human){
    this.setState({conversation: samples.humans[human].conversations});
  },
  // Handle when User navigates from / to /conversation/:human
  componentWillMount: function() {
    this.loadSampleData(this.props.params.human);
  },
  // Handle when User navigates between conversations
  componentWillReceiveProps: function(nextProps) {
    this.loadSampleData(nextProps.params.human);
  },

  sortByDateDesc: function(a, b) {
    return a.time  b.time ? 1 : 0;
  },

  renderMessage: function(val){
    return <Message who={val.who} text={val.text} key={val.time.getTime()} />;
  },
  render: function() {
    return (

Conversation

{this.props.params.human}

         {this.state.conversation.sort(this.sortByDateDesc).map(this.renderMessage)}

    )
  }
});

var Message = React.createClass({
  mixins: [PureRenderMixin],

  render: function() {
    return (

 "{this.props.text}"

    )
  }
});

var StorePane = React.createClass({
  renderStore: function(store){
    return <Store key={store} index={store} details={this.props.stores[store]} />;
  },
  render: function() {
    return (

Stores & Ovens

          {Object.keys(this.props.stores).map(this.renderStore)}

    )
  }
});

var Store = React.createClass({
  mixins: [PureRenderMixin],

  getCount: function(status){
    return this.props.details.orders.filter(function(n){ return n.status === status}).length;
  },
  render: function(){
    return (

{this.props.index}

 {this.getCount("Confirmed")}

 {this.getCount("In The Oven")}

 {this.getCount("Delivered")}

    )
  }
});

ReactDOM.render((
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <Route path="/conversation/:human" component={ConversationPane}></Route>
    </Route>
  </Router>
), document.querySelector('#main'))
<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2017  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('3.3.0');
		this.setClientTag('node:17-05-01');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2017  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('3.3.0');
		this.setClientTag('node:17-05-02');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before>angular.module('hypercube', [
    'ui.router',
    'ngMaterial',
    'ngStorage',
    'angular-jwt',

    'hypercube.auth',
    'hypercube.const',

    'hypercube.nav',

    'hypercube.account',
    'hypercube.home',
    'hypercube.applications',
    'hypercube.application'

  ])
.directive('stopEvent', function () {
  return {
    restrict: 'A',
    link: function (scope, element, attr) {
      element.bind('mouseover', function (e){
        e.stopPropagation();
      })
      element.bind('click', function (e) {
        e.stopPropagation();
      });
    }
  };
 })
//Set environment based on host
.service('ENV', ['$location', 'CONST', function($location, CONST){
  //TODO: Check for other environments as well (staging)
  if($location.host() == "localhost"){
    return {serverUrl:CONST.local.SERVER_URL, fbUrl:CONST.local.FB_URL};
  } else {
    return {serverUrl:CONST.production.SERVER_URL, fbUrl:CONST.production.FB_URL};
  }
}]);<commit_msg> and  decorators added to only show logs in local dev mode, and send to trackjs in production.<commit_after>angular.module('hypercube', [
    'ui.router',
    'ngMaterial',
    'ngStorage',
    'angular-jwt',

    'hypercube.auth',
    'hypercube.const',

    'hypercube.nav',

    'hypercube.account',
    'hypercube.home',
    'hypercube.applications',
    'hypercube.application'

  ])
.directive('stopEvent', function () {
  return {
    restrict: 'A',
    link: function (scope, element, attr) {
      element.bind('mouseover', function (e){
        e.stopPropagation();
      })
      element.bind('click', function (e) {
        e.stopPropagation();
      });
    }
  };
 })
//Set environment based on host
.service('ENV', ['$location', 'CONST', function ($location, CONST){
  //TODO: Check for other environments as well (staging)
  if($location.host() == "localhost"){
    return {serverUrl:CONST.local.SERVER_URL, fbUrl:CONST.local.FB_URL, logging:true};
  } else {
    return {serverUrl:CONST.production.SERVER_URL, fbUrl:CONST.production.FB_URL, logging:false};
  }
}])
.config(["$provide", function ($provide) {
  $provide.decorator('$log', ['$delegate', '$window', function ($delegate, $window){
    // Keep track of the original debug method, we'll need it later.
    var origDebug = $delegate.debug;
    var origLog = $delegate.log;
    /*
     * Intercept the call to $log.debug() so we can add on
     * our enhancement. We're going to add on a date and
     * time stamp to the message that will be logged.
     */
     //Not local development
     if($window.location.host.split(":")[0] != "localhost"){
      $delegate.log = angular.noop;
      $delegate.info = angular.noop;
      $delegate.debug = angular.noop;
      $delegate.error = angular.noop;
     } else {
      $delegate.debug = function () {
        var args = [].slice.call(arguments);
        args[0] = [new Date().toString(), ': ', args[0]].join('');

        // Send on our enhanced message to the original debug method.
        origDebug.apply(null, args);
      };
     }
    return $delegate;
  }])
  $provide.decorator('$exceptionHandler', ["$delegate", "$window", function ($delegate, $window) {
    return function (exception, cause) {
      console.log('$window.location:', $window.location.host);
      if($window.location.host.split(":")[0] != "localhost") {
        if($window.trackJs){
          $window.trackJs.track(exception);
        }
      }
      //Running locally
      else {
        $delegate(exception, cause);
      }
    };
  }]);
}]);
<|endoftext|>


<commit_before>var parser = require('swagger-parser'),
    Endpoint = require('../entities/endpoint'),
    Schema = require('../entities/schema'),
    Importer = require('./importer'),
    Project = require('../entities/project'),
    jsonHelper = require('../utils/json');

function Swagger() {
  this.metadata = null;
  this.$refs = null;
  this.filePath = null;
}

Swagger.prototype = new Importer();

Swagger.prototype._mapSecurityDefinitions = function(securityDefinitions) {
  var result = {};
  for(var name in securityDefinitions) {
    var type = securityDefinitions[name].type;
    result[type] = {};
    switch(type) {
      case 'apiKey':
        if (securityDefinitions[name].in !== undefined && securityDefinitions[name].in != '') {
          result[type][securityDefinitions[name].in] = {
            name: securityDefinitions[name].name,
            value: ''
          };
        }
        break;
      case 'oauth2':
        result[type] = {
          name: name,
          authorizationUrl: securityDefinitions[name].authorizationUrl || '',
          scopes: slScopes,
          tokenUrl: securityDefinitions[name].tokenUrl || ''
        };

        var slScopes = [], swaggerScopes = securityDefinitions[name].scopes;

        if (swaggerScopes) {
          for(var key in swaggerScopes) {
            var scope = {};
            scope['name'] = key;
            scope['value'] = swaggerScopes[key];
            slScopes.push(scope);
          }
        }

        if (securityDefinitions[name].flow) {
          result[type]['flow'] = securityDefinitions[name].flow;
        }

        if (slScopes.length > 0) {
          result[type]['scopes'] = slScopes;
        }

        break;
      case 'basic':
        result[type]['header'] = {
          name: securityDefinitions[name].name,
          value: '',
          description: securityDefinitions[name].description || ''
        };
        break;
    }
  }
  return result;
};

Swagger.prototype._mapSchema = function(schemaDefinitions) {
  var result = [];
  for (var schemaName in schemaDefinitions) {
    var sd = new Schema(schemaName);
    sd.Name = schemaName;
    sd.Definition = jsonHelper.stringify(schemaDefinitions[schemaName], 4);
    result.push(sd);
  }
  return result;
};

Swagger.prototype._mapQueryString = function(params) {
  var queryString = {type:'object', properties: {}, required: []};
  for (var i in params) {
    var param = params[i];
    if (param.in !== 'query') {
      //skip other type of params
      continue;
    }
    queryString.properties[param.name] = {
      type: param.type,
      description: param.description
    };
    if (param.required) {
      queryString.required.push(param.name);
    }
    if (param.type === 'array') {
      queryString.properties[param.name].items = param.items;
    }
  }
  return queryString;
};

Swagger.prototype._mapURIParams = function(params) {
  var pathParams = {};
  for (var i in params) {
    var param = params[i];
    if (param.hasOwnProperty('$ref')) {
      //any unresolved data?!?
      //console.log(i, param)
    }
    if (param.in !== 'path') {
      //skip other type of params
      continue;
    }
    pathParams[param.name] = {
      type: param.type,
      description: param.description
    };

    if (param.type === 'array') {
      pathParams[param.name].items = param.items;
    }
  }

  return pathParams;
};

Swagger.prototype._mapRequestBody = function(params, reqType) {
  var data = {mimeType: reqType || null, body: {properties: {}, required: []}, example: ''};

  for (var i in params) {
    var param = params[i];
    if (param.in !== 'body' && param.in !== 'formData') {
      //skip other type of params
      continue;
    }

    data.body.properties[param.name] = {};
    if (param.schema) {
      data.body.properties[param.name] = param.schema;
    }
    if (param.description) {
      data.body.properties[param.name].description = param.description;
    }
    else if (param.type) {
      data.body.properties[param.name]['type'] = param.type;
    }
    if (param.required) {
      data.body.required.push(param.name);
    }
  }
  //remove required field if doesn't have anything inside it
  if (data.body.required.length == 0) {
    delete data.body.required;
  }
  return data;
};

Swagger.prototype._mapResponseBody = function(responseBody, resType) {
  var data = [], defaultCodeTaken = false;
  for (var code in responseBody) {
    var res = {mimeType: resType, body: {}, example: '', codes: []};
    if (responseBody[code].schema) {
      res.body = responseBody[code].schema;
    }
    if (responseBody[code].hasOwnProperty('examples')) {
      for(var t in responseBody[code].examples) {
        if (t === resType) {
          res.example = jsonHelper.stringify(responseBody[code].examples[t], 4);
        }
      }
    }

    res.description = responseBody[code].description || '';
    res.body = jsonHelper.stringify(res.body, 4);

    if (code === 'default') {
      //swagger default usually meant for error responses:
      //https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#responses-object
      code = 400;
    }
    if (code === 400 || code === '400') {
      if (defaultCodeTaken) continue;
      defaultCodeTaken = true;
    }

    res.codes.push(code);
    data.push(res);
  }

  return data;
};

Swagger.prototype._mapRequestHeaders = function(params) {
  var data = {type: 'object', properties: {}, required: []};
  for (var i in params) {
    var param = params[i];
    if (param.in !== 'header') {
      //skip other type of params
      continue;
    }
    data.properties[param.name] = {
      type: param.type,
      description: param.description || ''
    };
    if (param.required) {
      data.required.push(param.name);
    }
  }
  return data;
};

Swagger.prototype.loadFile = function (path, cb) {
  var me = this;
  this.filePath = path;

  parser.parse(path)
  .then(function(api, metadata) {
    me.data = api;
    me.metadata = metadata;
    parser.resolve(path)
      .then(function($refs) {
        try {
          me.$refs = $refs.values()[me.filePath];
        } catch(err) {
          //ignore reference error
        }
        cb();
      })
      .catch(cb);
  })
  .catch(cb);
};

/*Swagger.prototype.loadData = function(data, cb) {
  parser.validate(myAPI)
  .then(function(api) {
    cb();
  })
  .catch(function(err) {
    ccb(err);
  });
};*/

//for now, if 'application/json' exist in supported type, use that
Swagger.prototype.findDefaultMimeType = function(mimeTypes) {
  if (!mimeTypes || mimeTypes.length <= 0) {
    return 'application/json';
  }
  for(var i in mimeTypes) {
    if (mimeTypes[i] === 'application/json') {
      return mimeTypes[i];
    }
  }
  return mimeTypes[0];
};

Swagger.prototype._import = function() {

  var defaultReqContentType = this.findDefaultMimeType(this.data.consumes),
      defaultResContentType = this.findDefaultMimeType(this.data.produces);

  this.project = new Project(this.data.info.title);
  this.project.Description = this.data.info.description || '';

  this.project.Environment.BasePath = this.data.basePath || '';
  this.project.Environment.Host = this.data.host || 'http://localhost:3000';
  this.project.Environment.Version = this.data.info.version;

  if (this.data.schemes && this.data.schemes.length > 0) {
    this.project.Environment.Protocols = this.data.schemes;
  }

  if (this.data.produces) {
    //taking the first as default one
    this.project.Environment.DefaultResponseType = defaultResContentType;
  }

  if (this.data.consumes) {
    //taking the first as default one
    this.project.Environment.DefaultRequestType = defaultReqContentType;
  }
  if (this.data.securityDefinitions) {
    this.project.SecuritySchemes = this._mapSecurityDefinitions(this.data.securityDefinitions);
  }

  for (var path in this.data.paths) {
    var methods = this.data.paths[path];
    var pathParams = {};
    if (methods.parameters) {
      pathParams = this._mapURIParams(methods.parameters);
    }

    for (var method in methods) {
      if (method === 'parameters') {
        continue;
      }
      var endpoint = new Endpoint(methods[method].operationId || ''),
        reqType = defaultReqContentType,
        resType = defaultResContentType;

      endpoint.Path = path;
      endpoint.Method = method;

      endpoint.Description = methods[method].description || methods[method].summary;
      endpoint.Summary = methods[method].summary || '';

      //map request body
      if (methods[method].consumes) {
        //taking only one
        reqType = this.findDefaultMimeType(methods[method].consumes);
      }
      endpoint.Body = this._mapRequestBody(methods[method].parameters, reqType);

      //map response body
      if (methods[method].produces) {
        //taking only one
        resType = this.findDefaultMimeType(methods[method].produces);
      }
      endpoint.Responses = this._mapResponseBody(methods[method].responses, resType);

      //map query string
      endpoint.QueryString = this._mapQueryString(methods[method].parameters);

      //map path params
      endpoint.PathParams = pathParams;

      //map headers
      endpoint.Headers = this._mapRequestHeaders(methods[method].parameters);

      //map security
      if (methods[method].security) {
        var securities = methods[method].security;
        for (var securityIndex in securities) {
          var keys = Object.keys(securities[securityIndex]);
          var securityName = keys[0];
          var scheme = this.data.securityDefinitions[securityName];
          if (!scheme) {
            //definition error
            continue;
          }
          switch(scheme.type) {
            case 'apiKey':
            case 'basic':
              if (endpoint.SecuredBy.none) {
                endpoint.SecuredBy = {};
              }
              endpoint.SecuredBy[scheme.type] = true;
              break;
            case 'oauth2':
              if (endpoint.SecuredBy.none) {
                endpoint.SecuredBy = {};
              }
              endpoint.SecuredBy[scheme.type] = securities[securityIndex][securityName];
              break;
          }
        }
      }

      this.project.addEndpoint(endpoint);
    }
  }

  var schemas = this._mapSchema(this.data.definitions);
  for(var i in schemas) {
    this.project.addSchema(schemas[i]);
  }
};

module.exports = Swagger;
<commit_msg>- Don't try to import request body if not proper http method.<commit_after>var parser = require('swagger-parser'),
    Endpoint = require('../entities/endpoint'),
    Schema = require('../entities/schema'),
    Importer = require('./importer'),
    Project = require('../entities/project'),
    jsonHelper = require('../utils/json');

function Swagger() {
  this.metadata = null;
  this.$refs = null;
  this.filePath = null;
}

Swagger.prototype = new Importer();

Swagger.prototype._mapSecurityDefinitions = function(securityDefinitions) {
  var result = {};
  for(var name in securityDefinitions) {
    var type = securityDefinitions[name].type;
    result[type] = {};
    switch(type) {
      case 'apiKey':
        if (securityDefinitions[name].in !== undefined && securityDefinitions[name].in != '') {
          result[type][securityDefinitions[name].in] = {
            name: securityDefinitions[name].name,
            value: ''
          };
        }
        break;
      case 'oauth2':
        result[type] = {
          name: name,
          authorizationUrl: securityDefinitions[name].authorizationUrl || '',
          scopes: slScopes,
          tokenUrl: securityDefinitions[name].tokenUrl || ''
        };

        var slScopes = [], swaggerScopes = securityDefinitions[name].scopes;

        if (swaggerScopes) {
          for(var key in swaggerScopes) {
            var scope = {};
            scope['name'] = key;
            scope['value'] = swaggerScopes[key];
            slScopes.push(scope);
          }
        }

        if (securityDefinitions[name].flow) {
          result[type]['flow'] = securityDefinitions[name].flow;
        }

        if (slScopes.length > 0) {
          result[type]['scopes'] = slScopes;
        }

        break;
      case 'basic':
        result[type]['header'] = {
          name: securityDefinitions[name].name,
          value: '',
          description: securityDefinitions[name].description || ''
        };
        break;
    }
  }
  return result;
};

Swagger.prototype._mapSchema = function(schemaDefinitions) {
  var result = [];
  for (var schemaName in schemaDefinitions) {
    var sd = new Schema(schemaName);
    sd.Name = schemaName;
    sd.Definition = jsonHelper.stringify(schemaDefinitions[schemaName], 4);
    result.push(sd);
  }
  return result;
};

Swagger.prototype._mapQueryString = function(params) {
  var queryString = {type:'object', properties: {}, required: []};
  for (var i in params) {
    var param = params[i];
    if (param.in !== 'query') {
      //skip other type of params
      continue;
    }
    queryString.properties[param.name] = {
      type: param.type,
      description: param.description
    };
    if (param.required) {
      queryString.required.push(param.name);
    }
    if (param.type === 'array') {
      queryString.properties[param.name].items = param.items;
    }
  }
  return queryString;
};

Swagger.prototype._mapURIParams = function(params) {
  var pathParams = {};
  for (var i in params) {
    var param = params[i];
    if (param.hasOwnProperty('$ref')) {
      //any unresolved data?!?
      //console.log(i, param)
    }
    if (param.in !== 'path') {
      //skip other type of params
      continue;
    }
    pathParams[param.name] = {
      type: param.type,
      description: param.description
    };

    if (param.type === 'array') {
      pathParams[param.name].items = param.items;
    }
  }

  return pathParams;
};

Swagger.prototype._mapRequestBody = function(params, reqType) {
  var data = {mimeType: reqType || null, body: {properties: {}, required: []}, example: ''};

  for (var i in params) {
    var param = params[i];
    if (param.in !== 'body' && param.in !== 'formData') {
      //skip other type of params
      continue;
    }

    data.body.properties[param.name] = {};
    if (param.schema) {
      data.body.properties[param.name] = param.schema;
    }
    if (param.description) {
      data.body.properties[param.name].description = param.description;
    }
    else if (param.type) {
      data.body.properties[param.name]['type'] = param.type;
    }
    if (param.required) {
      data.body.required.push(param.name);
    }
  }
  //remove required field if doesn't have anything inside it
  if (data.body.required.length == 0) {
    delete data.body.required;
  }
  return data;
};

Swagger.prototype._mapResponseBody = function(responseBody, resType) {
  var data = [], defaultCodeTaken = false;
  for (var code in responseBody) {
    var res = {mimeType: resType, body: {}, example: '', codes: []};
    if (responseBody[code].schema) {
      res.body = responseBody[code].schema;
    }
    if (responseBody[code].hasOwnProperty('examples')) {
      for(var t in responseBody[code].examples) {
        if (t === resType) {
          res.example = jsonHelper.stringify(responseBody[code].examples[t], 4);
        }
      }
    }

    res.description = responseBody[code].description || '';
    res.body = jsonHelper.stringify(res.body, 4);

    if (code === 'default') {
      //swagger default usually meant for error responses:
      //https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#responses-object
      code = 400;
    }
    if (code === 400 || code === '400') {
      if (defaultCodeTaken) continue;
      defaultCodeTaken = true;
    }

    res.codes.push(code);
    data.push(res);
  }

  return data;
};

Swagger.prototype._mapRequestHeaders = function(params) {
  var data = {type: 'object', properties: {}, required: []};
  for (var i in params) {
    var param = params[i];
    if (param.in !== 'header') {
      //skip other type of params
      continue;
    }
    data.properties[param.name] = {
      type: param.type,
      description: param.description || ''
    };
    if (param.required) {
      data.required.push(param.name);
    }
  }
  return data;
};

Swagger.prototype.loadFile = function (path, cb) {
  var me = this;
  this.filePath = path;

  parser.parse(path)
  .then(function(api, metadata) {
    me.data = api;
    me.metadata = metadata;
    parser.resolve(path)
      .then(function($refs) {
        try {
          me.$refs = $refs.values()[me.filePath];
        } catch(err) {
          //ignore reference error
        }
        cb();
      })
      .catch(cb);
  })
  .catch(cb);
};

/*Swagger.prototype.loadData = function(data, cb) {
  parser.validate(myAPI)
  .then(function(api) {
    cb();
  })
  .catch(function(err) {
    ccb(err);
  });
};*/

//for now, if 'application/json' exist in supported type, use that
Swagger.prototype.findDefaultMimeType = function(mimeTypes) {
  if (!mimeTypes || mimeTypes.length <= 0) {
    return 'application/json';
  }
  for(var i in mimeTypes) {
    if (mimeTypes[i] === 'application/json') {
      return mimeTypes[i];
    }
  }
  return mimeTypes[0];
};

Swagger.prototype._import = function() {

  var defaultReqContentType = this.findDefaultMimeType(this.data.consumes),
      defaultResContentType = this.findDefaultMimeType(this.data.produces);

  this.project = new Project(this.data.info.title);
  this.project.Description = this.data.info.description || '';

  this.project.Environment.BasePath = this.data.basePath || '';
  this.project.Environment.Host = this.data.host || 'http://localhost:3000';
  this.project.Environment.Version = this.data.info.version;

  if (this.data.schemes && this.data.schemes.length > 0) {
    this.project.Environment.Protocols = this.data.schemes;
  }

  if (this.data.produces) {
    //taking the first as default one
    this.project.Environment.DefaultResponseType = defaultResContentType;
  }

  if (this.data.consumes) {
    //taking the first as default one
    this.project.Environment.DefaultRequestType = defaultReqContentType;
  }
  if (this.data.securityDefinitions) {
    this.project.SecuritySchemes = this._mapSecurityDefinitions(this.data.securityDefinitions);
  }

  for (var path in this.data.paths) {
    var methods = this.data.paths[path];
    var pathParams = {};
    if (methods.parameters) {
      pathParams = this._mapURIParams(methods.parameters);
    }

    for (var method in methods) {
      if (method === 'parameters') {
        continue;
      }
      var endpoint = new Endpoint(methods[method].operationId || ''),
        reqType = defaultReqContentType,
        resType = defaultResContentType;

      endpoint.Path = path;
      endpoint.Method = method;

      endpoint.Description = methods[method].description || methods[method].summary;
      endpoint.Summary = methods[method].summary || '';

      //map request body
      if (methods[method].consumes) {
        //taking only one
        reqType = this.findDefaultMimeType(methods[method].consumes);
      }
      if (endpoint.Method.toLowerCase() !== 'get' &&
          endpoint.Method.toLowerCase() !== 'head') {
        endpoint.Body = this._mapRequestBody(methods[method].parameters, reqType);
      }

      //map response body
      if (methods[method].produces) {
        //taking only one
        resType = this.findDefaultMimeType(methods[method].produces);
      }
      endpoint.Responses = this._mapResponseBody(methods[method].responses, resType);

      //map query string
      endpoint.QueryString = this._mapQueryString(methods[method].parameters);

      //map path params
      endpoint.PathParams = pathParams;

      //map headers
      endpoint.Headers = this._mapRequestHeaders(methods[method].parameters);

      //map security
      if (methods[method].security) {
        var securities = methods[method].security;
        for (var securityIndex in securities) {
          var keys = Object.keys(securities[securityIndex]);
          var securityName = keys[0];
          var scheme = this.data.securityDefinitions[securityName];
          if (!scheme) {
            //definition error
            continue;
          }
          switch(scheme.type) {
            case 'apiKey':
            case 'basic':
              if (endpoint.SecuredBy.none) {
                endpoint.SecuredBy = {};
              }
              endpoint.SecuredBy[scheme.type] = true;
              break;
            case 'oauth2':
              if (endpoint.SecuredBy.none) {
                endpoint.SecuredBy = {};
              }
              endpoint.SecuredBy[scheme.type] = securities[securityIndex][securityName];
              break;
          }
        }
      }

      this.project.addEndpoint(endpoint);
    }
  }

  var schemas = this._mapSchema(this.data.definitions);
  for(var i in schemas) {
    this.project.addSchema(schemas[i]);
  }
};

module.exports = Swagger;
<|endoftext|>