<commit_before>namespace('Sy.Kernel');

/**
 * Framework heart
 *
 * @package Sy
 * @subpackage Kernel
 * @class
 */

Sy.Kernel.Core = function () {
    this.config = new Sy.Configurator();
    this.container = new Sy.ServiceContainer.Core();
    this.controllerManager = new Sy.Kernel.ControllerManager();
    this.actionDispatcher = new Sy.Kernel.ActionDispatcher();
};
Sy.Kernel.Core.prototype = Object.create(Object.prototype, {

    /**
     * Return the framework config object
     *
     * @return {Sy.Configurator}
     */

    getConfig: {
        value: function () {
            return this.config;
        }
    },

    /**
     * Return the service container object
     *
     * @return {Sy.ServiceContainer}
     */

    getContainer: {
        value: function () {
            return this.container;
        }
    },

    /**
     * Initiate the kernel that will inspect the app and build necessary data
     *
     * @return {Sy.Kernel.Core}
     */

    boot: {
        value: function () {

            var tester = new Sy.Kernel.FeatureTester(),
                parser = new Sy.Kernel.AppParser();

            tester.testBrowser();

            if (this.config.get('env') !== 'prod') {
                parser.setLogger(this.container.get('sy::core::logger'));
            }

            this.config.set('parameters.app.meta', {
                bundles: parser.getBundles(),
                controllers: parser.getControllers(),
                entities: parser.getEntities(),
                viewscreens: parser.getViewScreens()
            });

            parser
                .buildServices(this.container)
                .buildConfig(this.config)
                .registerValidationRules(this.container);

            this
                .registerControllers(parser.getControllers())
                .configureLogger()
                .registerShutdownListener()
                .registerFormTypes()
                .registerEventSubscribers();

            this.container.compile();

        }
    },

    /**
     * Register all app controllers into the manager
     *
     * @private
     * @param {Array} controllers
     *
     * @return {Sy.Kernel.Core}
     */

    registerControllers: {
        value: function (controllers) {

            var registryFactory = this.container.get('sy::core::registry::factory'),
                mediator = this.container.get('sy::core::mediator'),
                viewport = this.container.get('sy::core::viewport'),
                logger = this.container.get('sy::core::logger'),
                viewscreensManager = this.container.get('sy::core::view::manager');

            this.controllerManager
                .setMetaRegistry(registryFactory.make())
                .setLoadedControllersRegistry(registryFactory.make())
                .setMediator(mediator)
                .setServiceContainer(this.container)
                .setCache(this.config.get('controllers.cache'))
                .setCacheLength(this.config.get('controllers.cacheLength'));

            this.actionDispatcher
                .setViewPort(viewport)
                .setControllerManager(this.controllerManager)
                .setMediator(mediator)
                .setLogger(logger);

            for (var i = 0, l = controllers.length; i < l; i++) {
                this.controllerManager.registerController(
                    controllers[i].name,
                    controllers[i].creator
                );
            }

            this.controllerManager.boot();
            this.actionDispatcher.bindViewScreens(
                viewscreensManager.getViewScreens()
            );

            if (viewport.getCurrentViewScreen()) {
                this.controllerManager.buildController(
                    viewport.getCurrentViewScreen()
                );
            }

            return this;

        }
    },

    /**
     * Adapt the handlers available in the logger depending on the app env
     * If env set to 'prod' remove all of them except for 'error'
     *
     * @return {Sy.Kernel.Core}
     */

    configureLogger: {
        value: function () {

            var env = this.config.get('env'),
                logger = this.container.get('sy::core::logger');

            if (env === 'prod') {
                logger
                    .removeHandler(logger.LOG)
                    .removeHandler(logger.DEBUG)
                    .removeHandler(logger.INFO);
            }

            return this;

        }
    },

    /**
     * Add a `beforeunload` on the window to fire a channel to notify the app
     * it's being closed, so it can be properly shutdown
     *
     * @return {Sy.Kernel.Core}
     */

    registerShutdownListener: {
        value: function () {
            window.addEventListener('beforeunload', function (event) {
                try {
                    var evt = new Sy.Event.AppShutdownEvent(event);

                    this.container.get('sy::core::mediator').publish(
                        evt.KEY,
                        evt
                    );
                } catch (error) {
                    return error.message;
                }
            }.bind(this), false);

            return this;
        }
    },

    /**
     * Retrieve services tagged as form type and register them in the form builder
     *
     * @return {Sy.Kernel.Core} self
     */

    registerFormTypes: {
        value: function () {
            this.container
                .findTaggedServiceIds('form.type')
                .forEach(function (el) {
                    this.container
                        .get('sy::core::form')
                        .registerFormType(
                            this.container.get(el.id)
                        );
                }, this);

            return this;
        }
    },

    /**
     * Retrieve services tagged as event subscriber and register them
     * in the mediator
     *
     * @return {Sy.Kernel.Core} self
     */

    registerEventSubscribers: {
        value: function () {
            this.container
                .findTaggedServiceIds('event.subscriber')
                .forEach(function (el) {
                    var subscriber = this.container.get(el.id),
                        events;

                    if (!(subscriber instanceof Sy.EventSubscriberInterface)) {
                        throw new TypeError('Invalid event subscriber');
                    }

                    events = subscriber.getSubscribedEvents();

                    for (var evt in events) {
                        if (events.hasOwnProperty(evt)) {
                            this.container
                                .get('sy::core::mediator')
                                .subscribe({
                                    channel: evt,
                                    fn: subscriber[events[evt].method],
                                    context: subscriber,
                                    priority: subscriber[events[evt].priority],
                                    async: subscriber[events[evt].async]
                                });
                        }
                    }

                }, this);

            return this;
        }
    }

});
<commit_msg>#26 register the config before services<commit_after>namespace('Sy.Kernel');

/**
 * Framework heart
 *
 * @package Sy
 * @subpackage Kernel
 * @class
 */

Sy.Kernel.Core = function () {
    this.config = new Sy.Configurator();
    this.container = new Sy.ServiceContainer.Core();
    this.controllerManager = new Sy.Kernel.ControllerManager();
    this.actionDispatcher = new Sy.Kernel.ActionDispatcher();
};
Sy.Kernel.Core.prototype = Object.create(Object.prototype, {

    /**
     * Return the framework config object
     *
     * @return {Sy.Configurator}
     */

    getConfig: {
        value: function () {
            return this.config;
        }
    },

    /**
     * Return the service container object
     *
     * @return {Sy.ServiceContainer}
     */

    getContainer: {
        value: function () {
            return this.container;
        }
    },

    /**
     * Initiate the kernel that will inspect the app and build necessary data
     *
     * @return {Sy.Kernel.Core}
     */

    boot: {
        value: function () {

            var tester = new Sy.Kernel.FeatureTester(),
                parser = new Sy.Kernel.AppParser();

            tester.testBrowser();

            if (this.config.get('env') !== 'prod') {
                parser.setLogger(this.container.get('sy::core::logger'));
            }

            this.config.set('parameters.app.meta', {
                bundles: parser.getBundles(),
                controllers: parser.getControllers(),
                entities: parser.getEntities(),
                viewscreens: parser.getViewScreens()
            });

            parser
                .buildConfig(this.config)
                .buildServices(this.container)
                .registerValidationRules(this.container);

            this
                .registerControllers(parser.getControllers())
                .configureLogger()
                .registerShutdownListener()
                .registerFormTypes()
                .registerEventSubscribers();

            this.container.compile();

        }
    },

    /**
     * Register all app controllers into the manager
     *
     * @private
     * @param {Array} controllers
     *
     * @return {Sy.Kernel.Core}
     */

    registerControllers: {
        value: function (controllers) {

            var registryFactory = this.container.get('sy::core::registry::factory'),
                mediator = this.container.get('sy::core::mediator'),
                viewport = this.container.get('sy::core::viewport'),
                logger = this.container.get('sy::core::logger'),
                viewscreensManager = this.container.get('sy::core::view::manager');

            this.controllerManager
                .setMetaRegistry(registryFactory.make())
                .setLoadedControllersRegistry(registryFactory.make())
                .setMediator(mediator)
                .setServiceContainer(this.container)
                .setCache(this.config.get('controllers.cache'))
                .setCacheLength(this.config.get('controllers.cacheLength'));

            this.actionDispatcher
                .setViewPort(viewport)
                .setControllerManager(this.controllerManager)
                .setMediator(mediator)
                .setLogger(logger);

            for (var i = 0, l = controllers.length; i < l; i++) {
                this.controllerManager.registerController(
                    controllers[i].name,
                    controllers[i].creator
                );
            }

            this.controllerManager.boot();
            this.actionDispatcher.bindViewScreens(
                viewscreensManager.getViewScreens()
            );

            if (viewport.getCurrentViewScreen()) {
                this.controllerManager.buildController(
                    viewport.getCurrentViewScreen()
                );
            }

            return this;

        }
    },

    /**
     * Adapt the handlers available in the logger depending on the app env
     * If env set to 'prod' remove all of them except for 'error'
     *
     * @return {Sy.Kernel.Core}
     */

    configureLogger: {
        value: function () {

            var env = this.config.get('env'),
                logger = this.container.get('sy::core::logger');

            if (env === 'prod') {
                logger
                    .removeHandler(logger.LOG)
                    .removeHandler(logger.DEBUG)
                    .removeHandler(logger.INFO);
            }

            return this;

        }
    },

    /**
     * Add a `beforeunload` on the window to fire a channel to notify the app
     * it's being closed, so it can be properly shutdown
     *
     * @return {Sy.Kernel.Core}
     */

    registerShutdownListener: {
        value: function () {
            window.addEventListener('beforeunload', function (event) {
                try {
                    var evt = new Sy.Event.AppShutdownEvent(event);

                    this.container.get('sy::core::mediator').publish(
                        evt.KEY,
                        evt
                    );
                } catch (error) {
                    return error.message;
                }
            }.bind(this), false);

            return this;
        }
    },

    /**
     * Retrieve services tagged as form type and register them in the form builder
     *
     * @return {Sy.Kernel.Core} self
     */

    registerFormTypes: {
        value: function () {
            this.container
                .findTaggedServiceIds('form.type')
                .forEach(function (el) {
                    this.container
                        .get('sy::core::form')
                        .registerFormType(
                            this.container.get(el.id)
                        );
                }, this);

            return this;
        }
    },

    /**
     * Retrieve services tagged as event subscriber and register them
     * in the mediator
     *
     * @return {Sy.Kernel.Core} self
     */

    registerEventSubscribers: {
        value: function () {
            this.container
                .findTaggedServiceIds('event.subscriber')
                .forEach(function (el) {
                    var subscriber = this.container.get(el.id),
                        events;

                    if (!(subscriber instanceof Sy.EventSubscriberInterface)) {
                        throw new TypeError('Invalid event subscriber');
                    }

                    events = subscriber.getSubscribedEvents();

                    for (var evt in events) {
                        if (events.hasOwnProperty(evt)) {
                            this.container
                                .get('sy::core::mediator')
                                .subscribe({
                                    channel: evt,
                                    fn: subscriber[events[evt].method],
                                    context: subscriber,
                                    priority: subscriber[events[evt].priority],
                                    async: subscriber[events[evt].async]
                                });
                        }
                    }

                }, this);

            return this;
        }
    }

});
<|endoftext|>


<commit_before>

function User() {
      this.id = 'Unknown';
      this.name = 'Unknown';
      this.email = 'Unknown';
      this.location = 'Unknown';
      this.state = 'Unknown';
}

function addUser(user) {
    console.log(user)
    spawn = require( 'child_process' ).spawn;
    ls = spawn( 'bash', [ './api/app/models/addUser.sh', user.name, user.passwd ] );

    ls.stdout.on( 'data', data => {
        console.log( `stdout: ${data}` );
    });

    ls.stderr.on( 'data', data => {
        console.log( `stderr: ${data}` );
    });

    ls.on( 'close', code => {
        console.log( `child process exited with code ${code}` );
    });
}

function updateUser(userName) {
    var nexpect = require('nexpect');
    nexpect.spawn('bash sudo /opt/pivpn/removeOVPN.sh',  { verbose: true })
      .wait("::: Please enter the Name of the client to be revoked from the list above:")
      .sendline(userName)
      .run(function (stdout, err) {
        console.log(stdout);
        if (!err) {
          console.log("revoked (or not), process exited");
        }
        else {
          console.log(err)
        }
      });
}

function processFile(inputFile) {
    var fs = require('fs');
    var myUserList = [];

    fs.readFileSync(inputFile).toString().match(/^.+$/gm).forEach(function (line) {
      var splitter = line.split('=');
      var userRead = new User();
      userRead.name = splitter[6].split('\/')[0];
      userRead.email = splitter[8];
      userRead.location = splitter[3].split('\/')[0];
      if (/^V/.test(line) == true) {
        console.log('Valid');
        userRead.state = 'Valid';
      }
      else if(/^R/.test(line) == true) {
        userRead.state = 'Revoked';
      }
      console.log(splitter[0].split(' '));
      userRead.id = splitter[0].split('\t')[1];
      myUserList.push(userRead);

    });
    return myUserList;
}

exports.User = User;
exports.processUserFile = processFile;
exports.updateUser = updateUser;
exports.addUser = addUser;
<commit_msg>Modified users.js<commit_after>

function User() {
      this.id = 'Unknown';
      this.name = 'Unknown';
      this.email = 'Unknown';
      this.location = 'Unknown';
      this.state = 'Unknown';
}

function addUser(user) {
    console.log(user)
    spawn = require( 'child_process' ).spawn;
    ls = spawn( 'bash', [ './api/app/models/addUser.sh', user.name, user.passwd ] );

    ls.stdout.on( 'data', data => {
        console.log( `stdout: ${data}` );
    });

    ls.stderr.on( 'data', data => {
        console.log( `stderr: ${data}` );
    });

    ls.on( 'close', code => {
        console.log( `child process exited with code ${code}` );
    });
}

function updateUser(userName) {
    var nexpect = require('nexpect');
    nexpect.spawn('sudo bash /opt/pivpn/removeOVPN.sh',  { verbose: true })
      .wait("::: Please enter the Name of the client to be revoked from the list above:")
      .sendline(userName)
      .run(function (stdout, err) {
        console.log(stdout);
        if (!err) {
          console.log("revoked (or not), process exited");
        }
        else {
          console.log(err)
        }
      });
}

function processFile(inputFile) {
    var fs = require('fs');
    var myUserList = [];

    fs.readFileSync(inputFile).toString().match(/^.+$/gm).forEach(function (line) {
      var splitter = line.split('=');
      var userRead = new User();
      userRead.name = splitter[6].split('\/')[0];
      userRead.email = splitter[8];
      userRead.location = splitter[3].split('\/')[0];
      if (/^V/.test(line) == true) {
        console.log('Valid');
        userRead.state = 'Valid';
      }
      else if(/^R/.test(line) == true) {
        userRead.state = 'Revoked';
      }
      console.log(splitter[0].split(' '));
      userRead.id = splitter[0].split('\t')[1];
      myUserList.push(userRead);

    });
    return myUserList;
}

exports.User = User;
exports.processUserFile = processFile;
exports.updateUser = updateUser;
exports.addUser = addUser;
<|endoftext|>


<commit_before>/**
 * @function UIDialog
 * @version 0.0.2
 */

import {keyCodes, defaultClassNames} from '../../constants';

const UIDialog = ({
        dialog = '.js-dialog',
        openBtn = '.js-dialog-btn',
        closeBtn = '.js-dialog-close-btn',
        isModal = false,
        showBackdrop = true
    } = {}) => {

    let DOM,
        state = {};

    // Create the backdrop
    const backdrop = document.createElement('div');

    backdrop.classList.add(defaultClassNames.DIALOG_BACKDROP);

    init();

    /**
     * @function init
     * @desc Initialises the dialog
     */
    function init() {

        // Save all DOM queries for future use
        DOM = {
            'page':     document.querySelectorAll('body')[0],
            'dialog':   document.querySelectorAll(dialog)[0],
            'openBtn':  document.querySelectorAll(openBtn)[0],
            'closeBtn': document.querySelectorAll(closeBtn)[0]
        };

        // Check if the dialog exists, return if not
        if (DOM.dialog === undefined) {
            return false;
        }

        // Remove backdrop if turned off
        if (!showBackdrop) {
            DOM.dialog.classList.add(defaultClassNames.NO_BACKDROP);
        }

        // Set page attribute
        DOM.page.setAttribute('data-ui-dialog', 'is-initialised');

        // Find dialog and hide if not already hidden
        DOM.dialog.classList.add(defaultClassNames.IS_HIDDEN);

        // Attach event listeners
        DOM.openBtn.addEventListener('click', show, false);
        DOM.closeBtn.addEventListener('click', hide, false);
        if (!isModal) {
            backdrop.addEventListener('click', hide, false);
        }
        document.addEventListener('keydown', keyHandler, false);
    }

    /**
     * @function show
     */
    function show() {
        state.isOpen = true;
        DOM.dialog.classList.remove(defaultClassNames.IS_HIDDEN);
        DOM.page.setAttribute('data-current-dialog', dialog);
        // Add the backdrop to the page
        DOM.page.appendChild(backdrop);
    };

    /**
     * @function hide
     */
    function hide() {
        state.isOpen = false;
        DOM.dialog.classList.add(defaultClassNames.IS_HIDDEN);
        DOM.page.removeAttribute('data-current-dialog');
        // Remove the backdrop from the page
        DOM.page.removeChild(backdrop);
    };

    /**
     * @function keyHandler
     * @desc Checks to see if escape (key 27) has been pressed and dialog not modal
     * @param {Event} e
     */
    function keyHandler(e) {
        if ([keyCodes.ESCAPE].indexOf(e.which) > -1 && state.isOpen === true && !isModal) {
            e.preventDefault();
            hide();
        }
    }

    // External API
    return {
        show,
        hide
    };
};

export default UIDialog;
<commit_msg>big rework of dialog.js, add basic a11y, utility functions, ability to target multiple instances of dialog<commit_after>import {keyCodes, defaultClassNames, focusableSelectors} from '../../constants';
import qa from '../../utils/qa';
import defer from '../../utils/defer';

/**
 * @function UIDialog
 * @version 0.0.2
 * @desc Main UIDialog function. Creates instances of the dialog based on
 * parameters passed in.
 * @param {object} settings
 */
const UIDialog = ({
        dialog = '.js-dialog',
        openBtn = '.js-dialog-btn',
        closeBtn = '.js-dialog-close-btn',
        isModal = false,
        isAlert = false,
        readyClass = defaultClassNames.IS_READY,
        activeClass = defaultClassNames.IS_ACTIVE,
        showBackdrop = true
    } = {}) => {

    // Stores all the dom nodes for the module
    let DOM = {
        dialogs: qa(dialog)
    };

    // Keeps track of current state
    let state = {
        currentOpenButton: null,
        currentDialog: null,
        focusableElements: null //  elements within modal
    };

    /**
     * @function createBackdrop
     * @type private
     * @desc Creates the dialog backdrop
     */
    function createBackdrop() {
        // Create the backdrop
        DOM.backdrop = document.createElement('div');

        DOM.backdrop.classList.add(defaultClassNames.DIALOGBACKDROP);

        addBackdropA11y(DOM.backdrop);
    }

    /**
     * @function addDialogA11y
     * @type private
     * @desc Applies relevant roles and attributes to the dialog
     * @param {node} dialog
     */
    function addDialogA11y(dialog) {
        const role = isAlert ? 'alertdialog' : 'dialog';

        dialog.setAttribute('aria-hidden', 'true');
        dialog.setAttribute('role', role);
    }

    /**
     * @function addBackdropA11y
     * @type private
     * @desc Applies relevant roles and attributes to the backdrop
     * @param {node} backdrop
     */
    function addBackdropA11y(backdrop) {
        backdrop.setAttribute('aria-hidden', true);
    }

    /**
     * @function closeDialog
     * @type private
     * @desc sets up dialog ready to be hidden
     * @param {node} dialog
     */
    function closeDialog() {
        hideDialog(state.currentDialog);
    }

    /**
     * @function hideDialog
     * @type private
     * @desc adds aria attributes and hides dialog
     * @param {node} dialog
     */
    function hideDialog(dialog) {

        //  show container and focus the dialog
        dialog.setAttribute('aria-hidden', true);
        dialog.removeAttribute('tabindex');

        // TODO - Unbind events

        //  remove active state hook class
        dialog.classList.remove(activeClass);

        //  return focus to button that opened the dialog and reset state
        state.currentOpenButton.focus();
        state.currentOpenButton = null;
    }

    /**
     * @function openDialog
     * @type private
     * @desc sets up dialog and state ready to be shown
     * @param {node} dialog
     */
    function openDialog(e) {
        // get trigger button so focus can be returned to it later
        const button = e.target;
        // get dialog that should be opened
        const dialog = document.getElementById(button.getAttribute('aria-controls'));

        //  update State
        state.currentOpenButton = button;
        state.currentDialog = dialog;

        showDialog(dialog);
    }

    /**
     * @function bindOpenEvents
     * @type private
     * @desc Finds all open buttons and attaches click event listener
     * @param {node} dialog
     */
    function bindOpenEvents(dialog) {
        const id = dialog.getAttribute('id');

        // Grab all buttons which open this instance of the modal
        let openButtons = qa(`${openBtn}[aria-controls="${id}"]`);

        openButtons.forEach(button => button.addEventListener('click', openDialog));
    }

    /**
     * @function bindCloseEvents
     * @type private
     * @desc Finds all close buttons and attaches click event listener
     * @param {node} dialog
     */
    function bindCloseEvents(dialog = state.currentDialog) {
        // Grab all buttons which open this instance of the modal
        let closeButtons = qa(closeBtn);

        closeButtons.forEach(button => button.addEventListener('click', closeDialog));
    }

    /**
     * @function bindKeyCodeEvents
     * @type private
     * @desc Adds event listener for keydown on the document
     */
    function bindKeyCodeEvents() {
        document.addEventListener('keydown', handleKeyPress);
    }

    /**
     * @function bindBackdropEvents
     * @type private
     * @desc Adds event listener for keydown on the document
     */
    function bindBackdropEvents() {
        DOM.backdrop.addEventListener('click', handleBackdropClick);
    }

    /**
     * @function showDialog
     * @type private
     * @desc Sets up focusable elements, close and key events and displays modal
     */
    function showDialog(dialog) {
        //  Focus the modal and remove aria attributes
        dialog.setAttribute('tabindex', 1);
        dialog.setAttribute('aria-hidden', false);

        //  set first/last focusable elements
        state.focusableElements = qa(focusableSelectors.join(), dialog);

        //  focus first element if exists, otherwise focus dialog element
        if (state.focusableElements.length) {
            state.focusableElements[0].focus();
        } else {
            dialog.focus();
        }

        //  Bind events
        defer(bindKeyCodeEvents);
        defer(bindCloseEvents);
        if (!isModal && DOM.backdrop) defer(bindBackdropEvents);

        // Add backdrop if needed
        if (DOM.backdrop) {
            DOM.page.appendChild(DOM.backdrop);
        }

        //  Add class to make dialog visible
        dialog.classList.add(activeClass);
    }

    /**
     * @function handleKeyPress
     * @desc Checks to see if escape (key 27) has been pressed and dialog not modal
     * @param {Event} e
     */
    function handleKeyPress(e) {
        if (e.keyCode === keyCodes.ESCAPE && !isModal) {
            hideDialog(state.currentDialog);
        }
    }

    /**
     * @function handleBackdropClick
     * @desc If backdrop has been clicked, dismiss dialog
     * @param {Event} e
     */
    function handleBackdropClick(e) {
        if (e.target === DOM.backdrop) {
            hideDialog(state.currentDialog);
        }
    }

    /**
     * @function init
     * @desc Initialises the dialog
     */
    function init() {

        // Check if any dialogs exist, return if not
        if (DOM.dialogs === undefined) {
            return false;
        }

        // Add body element to the DOM object
        DOM.page = qa('body')[0];

        if (showBackdrop) {
            createBackdrop();
        }

        DOM.dialogs.forEach(dialog => {
            // add accessibility to dialog
            addDialogA11y(dialog);

            // set up event listeners for opening dialog
            bindOpenEvents(dialog);

            // set ready class
            dialog.classList.add(readyClass);
        });
    }

    // Initialise UIDialog module
    init();
};

export default UIDialog;
<|endoftext|>


<commit_before>var express = require('express');
var app = express()
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.use('/js', express.static('public/js'));

app.get('/', function (req, res) {
	res.sendFile(__dirname + '/views/index.html');
});

io.on('connection', function (socket) {
	socket.on('message', function (msg) {
		io.emit('message', msg);
	});
});

http.listen(3000, function () {
	console.log('Escuchando puerto 3000');
});<commit_msg>Se corrigio indentado.<commit_after>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.use('/js', express.static('public/js'));

app.get('/', function (req, res) {
	res.sendFile(__dirname + '/views/index.html');
});

io.on('connection', function (socket) {
	socket.on('message', function (msg) {
		io.emit('message', msg);
	});
});

http.listen(3000, function () {
	console.log('Escuchando puerto 3000');
});<|endoftext|>


<commit_before>$(function(){
	$(document).on('keydown', function(e){
        if ( e.which == 68 ){
    		$.ajax({
	    		url: '/logData',
		    	data: { json : JSON.stringify(data)} ,
			    type: 'POST',
                dataType : 'json',
    			success: function(response){
	    			console.log(response);
                    window.location.href="/startTrial";
			    },
    			err: function(error){
	    			console.log("shit");
		        }
    		});
        }
	});
});
<commit_msg>Update final.js<commit_after>$(function(){
	$(document).on('keydown', function(e){
        if ( e.which == 68 ){
    		$.ajax({
	    		url: '/logData',
		    	data: { json : JSON.stringify(data)} ,
			    type: 'POST',
                dataType : 'json',
    			success: function(response){
	    			console.log(response);
                    window.location.href="/startTrial";
			    },
    			err: function(error){
	    			console.log("error");
		        }
    		});
        }
	});
});
<|endoftext|>


<commit_before>import React from 'react';

import { createStructuredSelector } from 'reselect';

import {
  selectors as gameDataSelectors
} from '../redux/gameData.js';

import createContainer from '../containers/GenericContainer.js';

const PitchAnimation = (props) => {
  return (
    <a-box color="#ff0000" width="0.1" height="0.3" depth="0.1"
      alongpath={`curve: #pitch_${props.curveId}; loop:true; dur:${Number(props.animationTime) * 10}; rotate:true;`}>
    </a-box>
  );
};

export default createContainer({
  mapStateToProps: createStructuredSelector({
    curveId: gameDataSelectors.getSelectedPitchId,
    animationTime: gameDataSelectors.selectedPitchFinalTime
  }),
  Component: PitchAnimation
});<commit_msg>fixing animation duration and adding in baseball 3d model<commit_after>import React from 'react';

import { createStructuredSelector } from 'reselect';

import {
  selectors as gameDataSelectors
} from '../redux/gameData.js';

import createContainer from '../containers/GenericContainer.js';

const PitchAnimation = (props) => {
  return (
    <a-entity
      obj-model="obj: #baseball-obj; mtl: #baseball-mtl"
      alongpath={`curve: #pitch_${props.curveId}; loop:true; dur:${(Number(props.animationTime) * 10) * 1000}; rotate:true;`}>
    </a-entity>
  );
};

export default createContainer({
  mapStateToProps: createStructuredSelector({
    curveId: gameDataSelectors.getSelectedPitchId,
    animationTime: gameDataSelectors.selectedPitchFinalTime
  }),
  Component: PitchAnimation
});<|endoftext|>


<commit_before>var http = require('http'),
	infoServ = http.createServer(),
	parseUrl = require('url').parse,
	io = require('socket.io').listen(infoServ, {'log': false}),

	// infoView 拓展方法
	util = require('../mod.js').util,
	_addListener = [];

infoServ.on('request', function(req, res){
	var uri = parseUrl(req.url, true),
		is404 = true;
	util.eachArr(_addListener, function(){
		if (this(req, res, uri) === false) {
			is404 = false;
			return false;
		}
	});

	if (is404 && !res.headersSent) {
		res.statusCode = 404;
		res.end();
	}
});

module.exports = {
	'io': io,
	'infoServ': infoServ,
	'onRequest': function(callback){
		_addListener.push(callback);
	}
};<commit_msg>修正i2serv 404处理错误<commit_after>var http = require('http'),
	infoServ = http.createServer(),
	parseUrl = require('url').parse,
	io = require('socket.io').listen(infoServ, {'log': false}),

	// infoView 拓展方法
	util = require('../mod.js').util,
	_addListener = [];

infoServ.on('request', function(req, res){
	var uri = parseUrl(req.url, true);
	util.eachArr(_addListener, function(){
		return this(req, res, uri);
	});
});

module.exports = {
	'io': io,
	'infoServ': infoServ,
	'onRequest': function(callback){
		_addListener.push(callback);
	}
};<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////
// Copyright (c) Autodesk, Inc. All rights reserved
// Written by Forge Partner Development
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE.  AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
/////////////////////////////////////////////////////////////////////

if (!window.jQuery) alert('jQuery is required for this sample');
if (!window.XLSX) alert('Sheet JS is required for this sample');
//var fs=require('fs');

var ForgeXLS = {
  Utility: {
    Constants: {
      BASE_URL: 'https://developer.api.autodesk.com',
      MODEL_DERIVATIVE_V2: '/modelderivative/v2/designdata/'
    },

    forgeGetRequest: function (url, token, callback) {
      jQuery.ajax({
        url: url,
        beforeSend: function (request) {
          request.setRequestHeader('Authorization', 'Bearer ' + token);
        },
        success: function (response) {
          if (response.result && response.result === 'success') {
            setTimeout(function () {
              $.notify('Please wait. Retrieving meta-data for ' + fileName, { className: "info", position:"bottom right" });
              ForgeXLS.Utility.forgeGetRequest(url, token, callback);
            }, 3000);
            return;
          }
          if (callback)
            callback(response);
        }
      });
    },
    getMetadata: function (urn, token, callback) {
      console.log('Downloading metadata...');
      this.forgeGetRequest(this.Constants.BASE_URL + this.Constants.MODEL_DERIVATIVE_V2 + urn + '/metadata', token, callback);
    },

    getHierarchy: function (urn, guid, token, callback) {
      console.log('Downloading hierarchy...');
      this.forgeGetRequest(this.Constants.BASE_URL + this.Constants.MODEL_DERIVATIVE_V2 + urn + '/metadata/' + guid, token, callback);
    },

    getProperties: function (urn, guid, token, callback) {
      console.log('Downloading properties...');
      this.forgeGetRequest(this.Constants.BASE_URL + this.Constants.MODEL_DERIVATIVE_V2 + urn + '/metadata/' + guid + '/properties', token, callback);
    }
  },

  downloadXLSX: function (urn, fileName, token, status, fileType) {
    if (fileType.indexOf('rvt') == -1) {
      if (status) status(true, 'Not a Revit file. Only Revit files are supported, at the moment. Aborting conversion.');
      return;
    }

    if (status) {
      status(false, 'Preparing ' + fileName);
      status(false, 'Reading project information....');
    }

    this.prepareTables(urn, token, function (tables) {
      if (status) status(false, 'Building XLSX file...');

      var wb = new Workbook();
      jQuery.each(tables, function (name, table) {
     //  console.log(table);                                                 //intro
      // console.log(name);                                                  //intro

        /* fs.appendFile('empirestate.txt', 'table : '+ table +'and name : '+name, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */
        if (name.indexOf('<')==-1) { // skip tables starting with <
          var ws = ForgeXLS.sheetFromTable(table);
          wb.SheetNames.push(name);
          wb.Sheets[name] = ws;
        }
      });

      var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'binary'});
      saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), fileName);

      if (status) status(true, 'Downloading...');
    })
  },

  sheetFromTable: function (table) {
    var ws = {};
    var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};

    var allProperties = [];
    table.forEach(function (object) {
      jQuery.each(object, function (propName, propValue) {
        if (allProperties.indexOf(propName) == -1)
         //console.log(propName);                                    //intro
          /* fs.appendFile('empirestate.txt', 'propName : '+ propName, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */
          allProperties.push(propName);
      })
    });

    table.forEach(function (object) {
      allProperties.forEach(function (propName) {
        if (!object.hasOwnProperty(propName))
          object[propName] = '';
      });
    });

    var propsNames = [];
    for (var propName in table[0]) {
      propsNames.push(propName);
    }
    //propsNames.sort(); // removed due first 3 ID columns

    var R = 0;
    var C = 0;
    for (; C != propsNames.length; ++C) {
      var cell_ref = XLSX.utils.encode_cell({c: C, r: R});
      ws[cell_ref] = {v: propsNames[C], t: 's'};
    }
    R++;

    for (var index = 0; index != table.length; ++index) {
      C = 0;
      propsNames.forEach(function (propName) {
        if (range.s.r > R) range.s.r = 0;
        if (range.s.c > C) range.s.c = 0;
        if (range.e.r < R) range.e.r = R;
        if (range.e.c < C) range.e.c = C;
        var cell = {v: table[index][propName]};
        if (cell.v == null) return;
        var cell_ref = XLSX.utils.encode_cell({c: C, r: R});

        if (typeof cell.v === 'number') cell.t = 'n';
        else if (typeof cell.v === 'boolean') cell.t = 'b';
        else if (cell.v instanceof Date) {
          cell.t = 'n';
          cell.z = XLSX.SSF._table[14];
          cell.v = datenum(cell.v);
        }
        else cell.t = 's';

        ws[cell_ref] = cell;
        C++;
      });
      R++;
    }
    if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
    return ws;
  },

  prepareTables: function (urn, token, callback) {
    this.Utility.getMetadata(urn, token, function (metadata) {
      if (metadata.data.metadata.length == 0) {
        alert('Unexpected metadata');
        return;
      }
      var guid = metadata.data.metadata[0].guid;
            //console.log('guid:'+guid);                                                                //intro
      /* fs.appendFile('empirestate.txt', 'guid : '+ guid, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */
      ForgeXLS.Utility.getHierarchy(urn, guid, token, function (hierarchy) {
            //console.log('hierarchy:'+hierarchy);                                                      //intro

         /* fs.appendFile('empirestate.txt', 'hierarchy:'+hierarchy , (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */
        ForgeXLS.Utility.getProperties(urn, guid, token, function (properties) {
            //console.log('properties:'+properties);                                                    //intro
          /*  fs.appendFile('empirestate.txt','properties:'+properties, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */

          callback(ForgeXLS.prepareRawData(hierarchy, properties));
        });
      });
    });
  },

  prepareRawData: function (hierarchy, properties) {
    var tables = {};
    hierarchy.data.objects[0].objects.forEach(function (category) {
      var idsOnCategory = [];
      ForgeXLS.getAllElementsOnCategory(idsOnCategory, category.objects);

      var rows = [];
      idsOnCategory.forEach(function (objectid) {
        var columns = ForgeXLS.getProperties(objectid, properties);
        //console.log('columns:'+columns);
        rows.push(columns);
      });
      tables[category.name] = rows;
    });
    return tables;
  },

  getAllElementsOnCategory: function (ids, category) {
    category.forEach(function (item) {
      if (typeof(item.objects) === 'undefined') {
        if (!ids.indexOf(item.objectid) >= 0)
         //console.log('item.objectId:'+item.objectId);                                            //intro
          /*  fs.appendFile('empirestate.txt','item.objectId:'+item.objectId, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */

          ids.push(item.objectid);
      }
      else
        ForgeXLS.getAllElementsOnCategory(ids, item.objects);
    });
  },

  getProperties: function (id, objCollection) {
    var data = {};
    objCollection.data.collection.forEach(function (obj) {
      if (obj.objectid != id) return;

      data['Viewer ID'] = id;
      data['Revit ID'] = obj.name.match(/\d+/g)[0];
      data['Name'] = obj.name.replace('[' + data['Revit ID'] + ']', '').trim();

      //console.log('data[Name]':+ data['Name']);                                               //intro

        /*  fs.appendFile('empirestate.txt','data[Name]':+ data['Name'], (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */

      for (var propGroup in obj.properties) {
        if (propGroup.indexOf('__') > -1) break;
        if (obj.properties.hasOwnProperty(propGroup)) {
          for (var propName in obj.properties[propGroup]) {
            if (obj.properties[propGroup].hasOwnProperty(propName) && !Array.isArray(obj.properties[propGroup][propName]))
              data[propGroup + ':' + propName] = obj.properties[propGroup][propName];
          }
        }
      }
    });
    //console.log('data:'+ data);                                                            //intro

   /*  fs.appendFile('empirestate.txt','data:'+ data, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */

    return data;
  }
};

function Workbook() {
  if (!(this instanceof Workbook)) return new Workbook();
  this.SheetNames = [];
  //console.log('this.SheetNames :'+this.SheetNames);                                       //intro
   /* fs.appendFile('empirestate.txt','this.SheetNames :'+this.SheetNames, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */
  this.Sheets = {};
 // console.log('this.Sheets :'+this.Sheets);                                              //intro
   /* fs.appendFile('empirestate.txt','this.Sheets :'+this.Sheets, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */
}

function datenum(v, date1904) {
  if (date1904) v += 1462;
  var epoch = Date.parse(v);
  return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function s2ab(s) {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
}

 glu: function(){
  //var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
 // saveAs(blob, "hello world.txt");
   alert('go');
},

<commit_msg>Update ForgeXLS.js<commit_after>/////////////////////////////////////////////////////////////////////
// Copyright (c) Autodesk, Inc. All rights reserved
// Written by Forge Partner Development
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE.  AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
/////////////////////////////////////////////////////////////////////

if (!window.jQuery) alert('jQuery is required for this sample');
if (!window.XLSX) alert('Sheet JS is required for this sample');
//var fs=require('fs');

var ForgeXLS = {
  Utility: {
    Constants: {
      BASE_URL: 'https://developer.api.autodesk.com',
      MODEL_DERIVATIVE_V2: '/modelderivative/v2/designdata/'
    },

    forgeGetRequest: function (url, token, callback) {
      jQuery.ajax({
        url: url,
        beforeSend: function (request) {
          request.setRequestHeader('Authorization', 'Bearer ' + token);
        },
        success: function (response) {
          if (response.result && response.result === 'success') {
            setTimeout(function () {
              $.notify('Please wait. Retrieving meta-data for ' + fileName, { className: "info", position:"bottom right" });
              ForgeXLS.Utility.forgeGetRequest(url, token, callback);
            }, 3000);
            return;
          }
          if (callback)
            callback(response);
        }
      });
    },
    getMetadata: function (urn, token, callback) {
      console.log('Downloading metadata...');
      this.forgeGetRequest(this.Constants.BASE_URL + this.Constants.MODEL_DERIVATIVE_V2 + urn + '/metadata', token, callback);
    },

    getHierarchy: function (urn, guid, token, callback) {
      console.log('Downloading hierarchy...');
      this.forgeGetRequest(this.Constants.BASE_URL + this.Constants.MODEL_DERIVATIVE_V2 + urn + '/metadata/' + guid, token, callback);
    },

    getProperties: function (urn, guid, token, callback) {
      console.log('Downloading properties...');
      this.forgeGetRequest(this.Constants.BASE_URL + this.Constants.MODEL_DERIVATIVE_V2 + urn + '/metadata/' + guid + '/properties', token, callback);
    }
  },

  downloadXLSX: function (urn, fileName, token, status, fileType) {
    if (fileType.indexOf('rvt') == -1) {
      if (status) status(true, 'Not a Revit file. Only Revit files are supported, at the moment. Aborting conversion.');
      return;
    }

    if (status) {
      status(false, 'Preparing ' + fileName);
      status(false, 'Reading project information....');
    }

    this.prepareTables(urn, token, function (tables) {
      if (status) status(false, 'Building XLSX file...');

      var wb = new Workbook();
      jQuery.each(tables, function (name, table) {
     //  console.log(table);                                                 //intro
      // console.log(name);                                                  //intro

        /* fs.appendFile('empirestate.txt', 'table : '+ table +'and name : '+name, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */
        if (name.indexOf('<')==-1) { // skip tables starting with <
          var ws = ForgeXLS.sheetFromTable(table);
          wb.SheetNames.push(name);
          wb.Sheets[name] = ws;
        }
      });

      var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'binary'});
      saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), fileName);

      if (status) status(true, 'Downloading...');
    })
  },

  sheetFromTable: function (table) {
    var ws = {};
    var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};

    var allProperties = [];
    table.forEach(function (object) {
      jQuery.each(object, function (propName, propValue) {
        if (allProperties.indexOf(propName) == -1)
         //console.log(propName);                                    //intro
          /* fs.appendFile('empirestate.txt', 'propName : '+ propName, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */
          allProperties.push(propName);
      })
    });

    table.forEach(function (object) {
      allProperties.forEach(function (propName) {
        if (!object.hasOwnProperty(propName))
          object[propName] = '';
      });
    });

    var propsNames = [];
    for (var propName in table[0]) {
      propsNames.push(propName);
    }
    //propsNames.sort(); // removed due first 3 ID columns

    var R = 0;
    var C = 0;
    for (; C != propsNames.length; ++C) {
      var cell_ref = XLSX.utils.encode_cell({c: C, r: R});
      ws[cell_ref] = {v: propsNames[C], t: 's'};
    }
    R++;

    for (var index = 0; index != table.length; ++index) {
      C = 0;
      propsNames.forEach(function (propName) {
        if (range.s.r > R) range.s.r = 0;
        if (range.s.c > C) range.s.c = 0;
        if (range.e.r < R) range.e.r = R;
        if (range.e.c < C) range.e.c = C;
        var cell = {v: table[index][propName]};
        if (cell.v == null) return;
        var cell_ref = XLSX.utils.encode_cell({c: C, r: R});

        if (typeof cell.v === 'number') cell.t = 'n';
        else if (typeof cell.v === 'boolean') cell.t = 'b';
        else if (cell.v instanceof Date) {
          cell.t = 'n';
          cell.z = XLSX.SSF._table[14];
          cell.v = datenum(cell.v);
        }
        else cell.t = 's';

        ws[cell_ref] = cell;
        C++;
      });
      R++;
    }
    if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
    return ws;
  },

  prepareTables: function (urn, token, callback) {
    this.Utility.getMetadata(urn, token, function (metadata) {
      if (metadata.data.metadata.length == 0) {
        alert('Unexpected metadata');
        return;
      }
      var guid = metadata.data.metadata[0].guid;
            //console.log('guid:'+guid);                                                                //intro
      /* fs.appendFile('empirestate.txt', 'guid : '+ guid, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */
      ForgeXLS.Utility.getHierarchy(urn, guid, token, function (hierarchy) {
            //console.log('hierarchy:'+hierarchy);                                                      //intro

         /* fs.appendFile('empirestate.txt', 'hierarchy:'+hierarchy , (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */
        ForgeXLS.Utility.getProperties(urn, guid, token, function (properties) {
            //console.log('properties:'+properties);                                                    //intro
          /*  fs.appendFile('empirestate.txt','properties:'+properties, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */

          callback(ForgeXLS.prepareRawData(hierarchy, properties));
        });
      });
    });
  },

  prepareRawData: function (hierarchy, properties) {
    var tables = {};
    hierarchy.data.objects[0].objects.forEach(function (category) {
      var idsOnCategory = [];
      ForgeXLS.getAllElementsOnCategory(idsOnCategory, category.objects);

      var rows = [];
      idsOnCategory.forEach(function (objectid) {
        var columns = ForgeXLS.getProperties(objectid, properties);
        //console.log('columns:'+columns);
        rows.push(columns);
      });
      tables[category.name] = rows;
    });
    return tables;
  },

  getAllElementsOnCategory: function (ids, category) {
    category.forEach(function (item) {
      if (typeof(item.objects) === 'undefined') {
        if (!ids.indexOf(item.objectid) >= 0)
         //console.log('item.objectId:'+item.objectId);                                            //intro
          /*  fs.appendFile('empirestate.txt','item.objectId:'+item.objectId, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */

          ids.push(item.objectid);
      }
      else
        ForgeXLS.getAllElementsOnCategory(ids, item.objects);
    });
  },

  getProperties: function (id, objCollection) {
    var data = {};
    objCollection.data.collection.forEach(function (obj) {
      if (obj.objectid != id) return;

      data['Viewer ID'] = id;
      data['Revit ID'] = obj.name.match(/\d+/g)[0];
      data['Name'] = obj.name.replace('[' + data['Revit ID'] + ']', '').trim();

      //console.log('data[Name]':+ data['Name']);                                               //intro

        /*  fs.appendFile('empirestate.txt','data[Name]':+ data['Name'], (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */

      for (var propGroup in obj.properties) {
        if (propGroup.indexOf('__') > -1) break;
        if (obj.properties.hasOwnProperty(propGroup)) {
          for (var propName in obj.properties[propGroup]) {
            if (obj.properties[propGroup].hasOwnProperty(propName) && !Array.isArray(obj.properties[propGroup][propName]))
              data[propGroup + ':' + propName] = obj.properties[propGroup][propName];
          }
        }
      }
    });
    //console.log('data:'+ data);                                                            //intro

   /*  fs.appendFile('empirestate.txt','data:'+ data, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */

    return data;
  }
};

function Workbook() {
  if (!(this instanceof Workbook)) return new Workbook();
  this.SheetNames = [];
  //console.log('this.SheetNames :'+this.SheetNames);                                       //intro
   /* fs.appendFile('empirestate.txt','this.SheetNames :'+this.SheetNames, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */
  this.Sheets = {};
 // console.log('this.Sheets :'+this.Sheets);                                              //intro
   /* fs.appendFile('empirestate.txt','this.Sheets :'+this.Sheets, (err) => {
            if (err) throw err;
            console.log('The lyrics were updated!');
        }); */
}

function datenum(v, date1904) {
  if (date1904) v += 1462;
  var epoch = Date.parse(v);
  return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function s2ab(s) {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
}

function glu(){
  //var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
 // saveAs(blob, "hello world.txt");
   alert('go');
}

<|endoftext|>


<commit_before>#!/usr/bin/env node

process.stdin.setEncoding("utf8");

var fs      = require("fs"),
    fname   = process.argv[2] || "example",
    transit = require("../target/transit.js"),
    r       = transit.reader(),
    jstr    = fs.readFileSync("resources/"+fname+".json", "utf-8");
    tstr    = fs.readFileSync("resources/"+fname+".tjs", "utf-8");

function time(f, iters) {
    iters = iters || 1;
    for(var i = 0; i < iters; i++) {
        var s = new Date();
        f();
        console.log("Elapsed "+((new Date()).valueOf()-s.valueOf())+"ms");
        console.log("----------");
    }
}

console.log("JSON.parse 100 iters", JSON.parse(jstr).length);
time(function() {
    for(var i = 0; i < 100; i++) {
        JSON.parse(jstr);
    }
}, 5);

console.log("JSON.parse transit JSON 100 iters", JSON.parse(tstr).length);
time(function() {
    for(var i = 0; i < 100; i++) {
        JSON.parse(tstr);
    }
}, 5);

console.log("transit read 100 iters", r.read(tstr).length);
time(function() {
    for(var i = 0; i < 100; i++) {
        r.read(tstr);
    }
}, 5);
<commit_msg>allow supplying iter to bench/json.js<commit_after>#!/usr/bin/env node

process.stdin.setEncoding("utf8");

var fs      = require("fs"),
    fname   = process.argv[2] || "example",
    iter    = process.argv[3] ? parseInt(process.argv[3], 10) : 100,
    transit = require("../target/transit.js"),
    r       = transit.reader(),
    jstr    = fs.readFileSync("resources/"+fname+".json", "utf-8");
    tstr    = fs.readFileSync("resources/"+fname+".tjs", "utf-8");

function time(f, iters) {
    iters = iters || 1;
    for(var i = 0; i < iters; i++) {
        var s = new Date();
        f();
        console.log("Elapsed "+((new Date()).valueOf()-s.valueOf())+"ms");
        console.log("----------");
    }
}

console.log("JSON.parse "+iter+" iters");
time(function() {
    for(var i = 0; i < iter; i++) {
        JSON.parse(jstr);
    }
}, 5);

console.log("JSON.parse transit JSON "+iter+" iters");
time(function() {
    for(var i = 0; i < iter; i++) {
        JSON.parse(tstr);
    }
}, 5);

console.log("transit read "+iter+" iters");
time(function() {
    for(var i = 0; i < iter; i++) {
        r.read(tstr);
    }
}, 5);
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Stefano D'Angelo <zanga.mail@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*** Plot curve holding time-domain data (WebAudio/AnalyserNode-based). ***/

canvasPlot.scopeSignal = Object.create(canvasPlot.curve);

/* Trigger type definition. */
canvasPlot.scopeSignal.triggerType = {
	off:	0,
	up:	1,
	down:	2
};

/* Read/write members. */
canvasPlot.scopeSignal.analyser = null;	// WebAudio AnalyserNode
canvasPlot.scopeSignal.trigger = canvasPlot.scopeSignal.triggerType.off;
canvasPlot.scopeSignal.triggerLevel = NaN;

/* Private members. */
canvasPlot.scopeSignal.super = canvasPlot.curve;
canvasPlot.scopeSignal.data = null;
canvasPlot.scopeSignal.count = 0;
canvasPlot.scopeSignal.samplePeriod = NaN;
canvasPlot.scopeSignal.rw = { nextIn: NaN, nextOut: NaN };

canvasPlot.scopeSignal.init = function (samples, mSamples) {
	canvasPlot.superApply(this.super.init, this, arguments);

	this.data = new Float32Array(32768);

	for (var i = 0; i < this.data.length; i++)
		this.data[i] = NaN;
};

canvasPlot.scopeSignal.updateAnalyser = function () {
	this.samplePeriod = 1 / this.analyser.context.sampleRate;
};

canvasPlot.scopeSignal.updateSamples = function (time, resampler, points) {
	if (!this.analyser) {
		this.count = 0;
		return;
	}

	this.analyser.getFloatTimeDomainData(this.data);

	var i = 0;

	if (this.trigger == canvasPlot.scopeSignal.triggerType.up) {
		i = 1;
		for (; i < this.analyser.fftSize; i++)
			if (this.data[i] >= this.triggerLevel
			    && this.data[i - 1] < this.triggerLevel)
				break;
	} else if (this.trigger == canvasPlot.scopeSignal.triggerType.down) {
		i = 1;
		for (; i < this.analyser.fftSize; i++)
			if (this.data[i] <= this.triggerLevel
			    && this.data[i - 1] > this.triggerLevel)
				break;
	}

	if (resampler) {
		var timeStep = time / (points - 1);
		resampler.stepRatio =
			timeStep * this.analyser.context.sampleRate;
		resampler.update();
		if (i == 0) {
			resampler.offset = 0;
		} else {
			var iNext = i;
			i--;
			resampler.offset = (this.triggerLevel - this.data[i])
					   / (this.data[iNext] - this.data[i]);
		}
		if (points > this.samples.x.length)
			points = this.samples.x.length;
		resampler.process(this.data, this.samples.y, i, 0,
				  this.analyser.fftSize - i, points, this.rw);
		this.count = this.rw.nextOut;
		var t = 0;
		for (var j = 0; j < this.count; j++, t += timeStep)
			this.samples.x[j] = t;
	} else {
		var countMax = this.analyser.fftSize - i;
		if (countMax > this.samples.x.length)
			countMax = this.samples.x.length;
		var timeSamples =
			Math.ceil(time * this.analyser.context.sampleRate) + 1;
		if (countMax > timeSamples)
			countMax = timeSamples;

		var t = 0;
		this.count = 0;
		for (var j = 0; j < countMax;
		     i++, j++, t += this.samplePeriod, this.count++) {
			this.samples.x[j] = t;
			this.samples.y[j] = this.data[i];
		}
	}
};

canvasPlot.scopeSignal.updatePart = function (map, first, count) {
	if (count > this.count)
		count = this.count;
	if (count > 0)
		canvasPlot.superApply(this.super.updatePart, this, arguments);
};

canvasPlot.scopeSignal.drawPart = function (ctx, area, curveDrawer, first, last)
{
	if (last >= this.count)
		last = this.count - 1;
	if (last > first)
		canvasPlot.superApply(this.super.drawPart, this, arguments);
};
<commit_msg>fix scopeSignal when analyser is null<commit_after>/*
 * Copyright (C) 2015 Stefano D'Angelo <zanga.mail@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*** Plot curve holding time-domain data (WebAudio/AnalyserNode-based). ***/

canvasPlot.scopeSignal = Object.create(canvasPlot.curve);

/* Trigger type definition. */
canvasPlot.scopeSignal.triggerType = {
	off:	0,
	up:	1,
	down:	2
};

/* Read/write members. */
canvasPlot.scopeSignal.analyser = null;	// WebAudio AnalyserNode
canvasPlot.scopeSignal.trigger = canvasPlot.scopeSignal.triggerType.off;
canvasPlot.scopeSignal.triggerLevel = NaN;

/* Private members. */
canvasPlot.scopeSignal.super = canvasPlot.curve;
canvasPlot.scopeSignal.data = null;
canvasPlot.scopeSignal.count = 0;
canvasPlot.scopeSignal.samplePeriod = NaN;
canvasPlot.scopeSignal.rw = { nextIn: NaN, nextOut: NaN };

canvasPlot.scopeSignal.init = function (samples, mSamples) {
	canvasPlot.superApply(this.super.init, this, arguments);

	this.data = new Float32Array(32768);

	for (var i = 0; i < this.data.length; i++)
		this.data[i] = NaN;
};

canvasPlot.scopeSignal.updateAnalyser = function () {
	if (this.analyser)
		this.samplePeriod = 1 / this.analyser.context.sampleRate;
	else
		this.samplePeriod = NaN;
};

canvasPlot.scopeSignal.updateSamples = function (time, resampler, points) {
	if (!this.analyser) {
		this.count = 0;
		return;
	}

	this.analyser.getFloatTimeDomainData(this.data);

	var i = 0;

	if (this.trigger == canvasPlot.scopeSignal.triggerType.up) {
		i = 1;
		for (; i < this.analyser.fftSize; i++)
			if (this.data[i] >= this.triggerLevel
			    && this.data[i - 1] < this.triggerLevel)
				break;
	} else if (this.trigger == canvasPlot.scopeSignal.triggerType.down) {
		i = 1;
		for (; i < this.analyser.fftSize; i++)
			if (this.data[i] <= this.triggerLevel
			    && this.data[i - 1] > this.triggerLevel)
				break;
	}

	if (resampler) {
		var timeStep = time / (points - 1);
		resampler.stepRatio =
			timeStep * this.analyser.context.sampleRate;
		resampler.update();
		if (i == 0) {
			resampler.offset = 0;
		} else {
			var iNext = i;
			i--;
			resampler.offset = (this.triggerLevel - this.data[i])
					   / (this.data[iNext] - this.data[i]);
		}
		if (points > this.samples.x.length)
			points = this.samples.x.length;
		resampler.process(this.data, this.samples.y, i, 0,
				  this.analyser.fftSize - i, points, this.rw);
		this.count = this.rw.nextOut;
		var t = 0;
		for (var j = 0; j < this.count; j++, t += timeStep)
			this.samples.x[j] = t;
	} else {
		var countMax = this.analyser.fftSize - i;
		if (countMax > this.samples.x.length)
			countMax = this.samples.x.length;
		var timeSamples =
			Math.ceil(time * this.analyser.context.sampleRate) + 1;
		if (countMax > timeSamples)
			countMax = timeSamples;

		var t = 0;
		this.count = 0;
		for (var j = 0; j < countMax;
		     i++, j++, t += this.samplePeriod, this.count++) {
			this.samples.x[j] = t;
			this.samples.y[j] = this.data[i];
		}
	}
};

canvasPlot.scopeSignal.updatePart = function (map, first, count) {
	if (count > this.count)
		count = this.count;
	if (count > 0)
		canvasPlot.superApply(this.super.updatePart, this, arguments);
};

canvasPlot.scopeSignal.drawPart = function (ctx, area, curveDrawer, first, last)
{
	if (last >= this.count)
		last = this.count - 1;
	if (last > first)
		canvasPlot.superApply(this.super.drawPart, this, arguments);
};
<|endoftext|>


<commit_before>hqDefine("linked_domain/js/domain_links", [
    'jquery.rmi/jquery.rmi',
    'hqwebapp/js/initial_page_data',
    'underscore',
    'knockout',
    'hqwebapp/js/alert_user',
    'hqwebapp/js/multiselect_utils',
    'hqwebapp/js/components.ko', // for pagination and search box
    'hqwebapp/js/select2_knockout_bindings.ko',     // selects2 for fields
], function (
    RMI,
    initialPageData,
    _,
    ko,
    alertUser
) {
    var _private = {};
    _private.RMI = function () {};

    var LinkedDataViewModel = function (data) {
        var self = {};
        self.type = data.type;
        self.name = data.name;
        self.lastUpdate = ko.observable(data.last_update);
        self.detail = data.detail;
        self.showUpdate = ko.observable(data.can_update);
        self.update_url = null;

        if (self.type === 'app' && self.detail && self.detail.app_id) {
            self.update_url = initialPageData.reverse('app_settings', self.detail.app_id);
        }
        self.error = ko.observable("");
        self.hasSuccess = ko.observable(false);
        self.showSpinner = ko.observable(false);

        self.update = function () {
            self.showSpinner(true);
            self.showUpdate(false);
            _private.RMI("update_linked_model", {"model": {
                'type': self.type,
                'detail': self.detail,
            }}).done(function (data) {
                if (data.error) {
                    self.error(data.error);
                } else {
                    self.lastUpdate(data.last_update);
                    self.hasSuccess(true);
                }
                self.showSpinner(false);
            }).fail(function () {
                self.error(gettext("Error updating."));
                self.showSpinner(false);
            });
        };

        return self;
    };

    var DomainLinksViewModel = function (data) {
        var self = {};
        self.upstreamLink = data.master_link ? DomainLink(data.master_link) : null;

        // setup getting started view model
        var gettingStartedData = {
            parent: self,
            upstreamDomains: data.upstream_domains,
        };
        self.gettingStartedViewModel = GettingStartedViewModel(gettingStartedData);

        // setup add downstream domain modal view model
        var addDownstreamDomainData = {
            parent: self,
            availableDomains: data.available_domains,
        };
        self.addDownstreamDomainViewModel = AddDownstreamDomainViewModel(addDownstreamDomainData);

        // can only pull content if a link with an upstream domain exists
        var pullReleaseContentData = null;
        if (self.upstreamLink) {
            pullReleaseContentData = {
                parent: self,
                linkedDataViewModels: _.map(data.model_status, LinkedDataViewModel),
                domainLink: self.upstreamLink,
            };
            self.pullReleaseContentViewModel = PullReleaseContentViewModel(pullReleaseContentData);
        }

        // General data
        self.domain = data.domain;
        self.domain_links = ko.observableArray(_.map(data.linked_domains, DomainLink));
        self.showRemoteReports = function () {
            if (data.linkable_ucr) {
                return data.linkable_ucr.length > 0;
            }
            return false;
        };

        self.isUpstreamDomain = ko.computed(function () {
            return self.domain_links().length > 0;
        });
        // doesn't need to be observable because it is impossible to update the existing page to change this property
        self.isDownstreamDomain = data.is_downstream_domain;

        self.isOnlyDownstreamDomain = ko.computed(function () {
            return !self.isUpstreamDomain() && self.isDownstreamDomain;
        });

        // Tab Header Statuses
        self.manageDownstreamDomainsTabStatus = ko.computed(function () {
            return self.isUpstreamDomain() ? "active" : "";
        });

        self.pullContentTabStatus = ko.computed(function () {
            return self.isOnlyDownstreamDomain() ? "active" : "";
        });

        // Tab Content Statuses
        self.manageTabActiveStatus = ko.computed(function () {
            return self.isUpstreamDomain() ? "in active" : "";
        });

        self.pullTabActiveStatus = ko.computed(function () {
            return self.isOnlyDownstreamDomain() ? "in active" : "";
        });

        self.showGetStarted = ko.computed(function () {
            return !self.isUpstreamDomain() && !self.isDownstreamDomain;
        });

        self.showMultipleTabs = ko.computed(function () {
            return self.isUpstreamDomain() || (self.isDownstreamDomain && self.showRemoteReports());
        });

        // can only push content if a link with a downstream domain exists
        var pushContentData = {
            parent: self,
        };
        self.pushContentViewModel = PushContentViewModel(pushContentData);
        // Manage Downstream Domains Tab
        // search box
        self.query = ko.observable();
        self.filteredDomainLinks = ko.observableArray([]);
        self.matchesQuery = function (domainLink) {
            return !self.query() || domainLink.linked_domain().toLowerCase().indexOf(self.query().toLowerCase()) !== -1;
        };
        self.filter = function () {
            self.filteredDomainLinks(_.filter(self.domain_links(), self.matchesQuery));
            self.goToPage(1);
        };

        // pagination
        self.paginatedDomainLinks = ko.observableArray([]);
        self.itemsPerPage = ko.observable(5);
        self.totalItems = ko.computed(function () {
            return self.query() ? self.filteredDomainLinks().length : self.domain_links().length;
        });
        self.currentPage = 1;

        self.goToPage = function (page) {
            self.currentPage = page;
            self.paginatedDomainLinks.removeAll();
            var skip = (self.currentPage - 1) * self.itemsPerPage();
            var visibleDomains = self.query() ? self.filteredDomainLinks() : self.domain_links();
            self.paginatedDomainLinks(visibleDomains.slice(skip, skip + self.itemsPerPage()));
        };

        self.onPaginationLoad = function () {
            self.goToPage(1);
        };

        self.linkableUcr = ko.observableArray(_.map(data.linkable_ucr, function (report) {
            return RemoteLinkableReport(report, self.upstreamLink);
        }));

        self.createRemoteReportLink = function (reportId) {
            _private.RMI("create_remote_report_link", {
                "master_domain": self.upstreamLink.master_domain,
                "linked_domain": self.upstreamLink.linked_domain(),
                "report_id": reportId,
            }).done(function (data) {
                if (data.success) {
                    alertUser.alert_user(gettext('Report successfully linked.'), 'success');
                } else {
                    alertUser.alert_user(gettext(
                        'Something unexpected happened.\n' +
                        'Please try again, or report an issue if the problem persists.'), 'danger');
                }
            }).fail(function () {
                alertUser.alert_user(gettext(
                    'Something unexpected happened.\n' +
                    'Please try again, or report an issue if the problem persists.'), 'danger');
            });
        };

        self.deleteLink = function (link) {
            _private.RMI("delete_domain_link", {
                "linked_domain": link.linked_domain(),
            }).done(function () {
                self.domain_links.remove(link);
                var availableDomains = self.addDownstreamDomainViewModel.availableDomains();
                availableDomains.push(link.linked_domain());
                self.addDownstreamDomainViewModel.availableDomains(availableDomains.sort());
                self.goToPage(self.currentPage);
            }).fail(function () {
                alertUser.alert_user(gettext('Something unexpected happened.\n' +
                    'Please try again, or report an issue if the problem persists.'), 'danger');
            }).always(function () {
                // fix for b3
                $('body').removeClass('modal-open');
                var $modalBackdrop = $('.modal-backdrop');
                if ($modalBackdrop) {
                    $modalBackdrop.remove();
                }
            });
        };

        return self;
    };

    var DomainLink = function (link) {
        var self = {};
        self.linked_domain = ko.observable(link.linked_domain);
        self.is_remote = link.is_remote;
        self.master_domain = link.master_domain;
        self.lastUpdate = link.last_update;
        self.upstreamUrl = link.upstream_url;
        self.downstreamUrl = link.downstream_url;
        return self;
    };

    var PushContentViewModel = function (data) {
        self.parent = data.parent;
        self.domainsToPush = ko.observableArray();
        self.modelsToPush = ko.observableArray();
        self.buildAppsOnPush = ko.observable(false);
        self.pushInProgress = ko.observable(false);
        self.enablePushButton = ko.computed(function () {
            return self.domainsToPush().length && self.modelsToPush().length && !self.pushInProgress();
        });

        self.localDownstreamDomains = ko.computed(function () {
            return self.parent.domain_links().reduce(function (result, link) {
                if (!link.is_remote) {
                    return result.concat(link.linked_domain());
                }
                return result;
            }, []);
        });

        self.multiselectProperties = {
            selectableHeaderTitle: gettext("All project spaces"),
            selectedHeaderTitle: gettext("Project spaces to push to"),
            searchItemTitle: gettext("Search project spaces"),
        };

        self.canPush = ko.computed(function () {
            return self.localDownstreamDomains().length > 0;
        });

        self.pushContent = function () {
            self.pushInProgress(true);
            _private.RMI("create_release", {
                models: _.map(self.modelsToPush(), JSON.parse),
                linked_domains: self.domainsToPush(),
                build_apps: self.buildAppsOnPush(),
            }).done(function (data) {
                alertUser.alert_user(data.message, data.success ? 'success' : 'danger');
                self.pushInProgress(false);
            }).fail(function () {
                alertUser.alert_user(gettext('Something unexpected happened.\nPlease try again, or report an issue if the problem persists.'), 'danger');
                self.pushInProgress(false);
            });
        };

        return self;
    };

    var PullReleaseContentViewModel = function (data) {
        // Pull Content Tab
        self.parent = data.parent;
        self.linkedDataViewModels = data.linkedDataViewModels;
        self.domainLink = data.domainLink;

        // search box
        self.query = ko.observable();
        self.filteredLinkedDataViewModels = ko.observableArray([]);
        self.matchesQuery = function (linkedDataViewModel) {
            return !self.query() || linkedDataViewModel.name.toLowerCase().indexOf(self.query().toLowerCase()) !== -1;
        };
        self.filter = function () {
            self.filteredLinkedDataViewModels(_.filter(self.linkedDataViewModels, self.matchesQuery));
            self.goToPage(1);
        };

        // pagination
        self.paginatedLinkedDataViewModels = ko.observableArray([]);
        self.itemsPerPage = ko.observable(5);
        self.totalItems = ko.computed(function () {
            return self.query() ? self.filteredLinkedDataViewModels().length : self.linkedDataViewModels.length;
        });
        self.currentPage = 1;

        self.goToPage = function (page) {
            self.currentPage = page;
            self.paginatedLinkedDataViewModels.removeAll();
            var skip = (self.currentPage - 1) * self.itemsPerPage();
            var visibleLinkedDataViewModels = self.query() ? self.filteredLinkedDataViewModels() : self.linkedDataViewModels;
            self.paginatedLinkedDataViewModels(visibleLinkedDataViewModels.slice(skip, skip + self.itemsPerPage()));
        };

        self.onPaginationLoad = function () {
            self.goToPage(1);
        };

        return self;
    };

    var RemoteLinkableReport = function (report, upstreamLink) {
        var self = {};
        self.id = report.id;
        self.title = report.title;
        self.alreadyLinked = ko.observable(report.already_linked);

        self.createLink = function () {
            _private.RMI("create_remote_report_link", {
                "master_domain": upstreamLink.master_domain,
                "linked_domain": upstreamLink.linked_domain(),
                "report_id": self.id,
            }).done(function (data) {
                if (data.success) {
                    alertUser.alert_user(gettext('Report successfully linked.'), 'success');
                    self.alreadyLinked(true);
                } else {
                    alertUser.alert_user(gettext(
                        'Something unexpected happened.\n' +
                            'Please try again, or report an issue if the problem persists.'), 'danger');
                }
            }).fail(function () {
                alertUser.alert_user(gettext(
                    'Something unexpected happened.\n' +
                        'Please try again, or report an issue if the problem persists.'), 'danger');
            });
        };

        return self;
    };

    var AddDownstreamDomainViewModel = function (data) {
        var self = {};
        self.parent = data.parent;
        self.availableDomains = ko.observableArray(data.availableDomains.sort());
        self.value = ko.observable();

        self.addDownstreamDomain = function (viewModel) {
            _private.RMI("create_domain_link", {
                "downstream_domain": viewModel.value(),
            }).done(function (response) {
                if (response.success) {
                    self.availableDomains(_.filter(self.availableDomains(), function (item) {
                        return item !== viewModel.value();
                    }));
                    self.value(null);
                    self.parent.domain_links.unshift(DomainLink(response.domain_link));
                    self.parent.goToPage(1);
                } else {
                    var errorMessage = _.template(
                        gettext('Unable to link project spaces. <%- error %>\nYou must remove the existing link before creating this new link.')
                    )({error: response.message});
                    alertUser.alert_user(errorMessage, 'danger');
                }
            }).fail(function () {
                alertUser.alert_user(gettext('Unable to link project spaces.\nPlease try again, or report an issue if the problem persists.'), 'danger');
            });
        };
        return self;
    };

    var GettingStartedViewModel = function (data) {
        var self = {};
        self.parent = data.parent;
        var sortedUpstreamDomains = data.upstreamDomains.sort(function (first, second) {
            var firstName = first.name.toUpperCase();
            var secondName = second.name.toUpperCase();
            if (firstName > secondName) {
                return 1;
            } else if (firstName < secondName) {
                return -1;
            } else {
                return 0;
            }
        });
        self.upstreamDomains = ko.observableArray(sortedUpstreamDomains);

        self.upstreamButtonClass = ko.computed(function () {
            return self.upstreamDomains().length > 0 ? "btn-default" : "btn-primary";
        });

        self.goToUpstream = function (data) {
            window.location.href = data.upstreamDomains()[0].url;
        };
        return self;
    };

    var setRMI = function (rmiUrl, csrfToken) {
        var _rmi = RMI(rmiUrl, csrfToken);
        _private.RMI = function (remoteMethod, data) {
            return _rmi("", data, {headers: {"DjNg-Remote-Method": remoteMethod}});
        };
    };

    $(function () {
        var view_data = initialPageData.get('view_data');
        var csrfToken = $("#csrfTokenContainer").val();
        setRMI(initialPageData.reverse('linked_domain:domain_link_rmi'), csrfToken);

        var model = DomainLinksViewModel(view_data);
        $("#ko-linked-projects").koApplyBindings(model);

        if ($("#new-downstream-domain-modal").length) {
            $("#new-downstream-domain-modal").koApplyBindings(model.addDownstreamDomainViewModel);
        }

    });
});
<commit_msg>define self before use<commit_after>hqDefine("linked_domain/js/domain_links", [
    'jquery.rmi/jquery.rmi',
    'hqwebapp/js/initial_page_data',
    'underscore',
    'knockout',
    'hqwebapp/js/alert_user',
    'hqwebapp/js/multiselect_utils',
    'hqwebapp/js/components.ko', // for pagination and search box
    'hqwebapp/js/select2_knockout_bindings.ko',     // selects2 for fields
], function (
    RMI,
    initialPageData,
    _,
    ko,
    alertUser
) {
    var _private = {};
    _private.RMI = function () {};

    var LinkedDataViewModel = function (data) {
        var self = {};
        self.type = data.type;
        self.name = data.name;
        self.lastUpdate = ko.observable(data.last_update);
        self.detail = data.detail;
        self.showUpdate = ko.observable(data.can_update);
        self.update_url = null;

        if (self.type === 'app' && self.detail && self.detail.app_id) {
            self.update_url = initialPageData.reverse('app_settings', self.detail.app_id);
        }
        self.error = ko.observable("");
        self.hasSuccess = ko.observable(false);
        self.showSpinner = ko.observable(false);

        self.update = function () {
            self.showSpinner(true);
            self.showUpdate(false);
            _private.RMI("update_linked_model", {"model": {
                'type': self.type,
                'detail': self.detail,
            }}).done(function (data) {
                if (data.error) {
                    self.error(data.error);
                } else {
                    self.lastUpdate(data.last_update);
                    self.hasSuccess(true);
                }
                self.showSpinner(false);
            }).fail(function () {
                self.error(gettext("Error updating."));
                self.showSpinner(false);
            });
        };

        return self;
    };

    var DomainLinksViewModel = function (data) {
        var self = {};
        self.upstreamLink = data.master_link ? DomainLink(data.master_link) : null;

        // setup getting started view model
        var gettingStartedData = {
            parent: self,
            upstreamDomains: data.upstream_domains,
        };
        self.gettingStartedViewModel = GettingStartedViewModel(gettingStartedData);

        // setup add downstream domain modal view model
        var addDownstreamDomainData = {
            parent: self,
            availableDomains: data.available_domains,
        };
        self.addDownstreamDomainViewModel = AddDownstreamDomainViewModel(addDownstreamDomainData);

        // can only pull content if a link with an upstream domain exists
        var pullReleaseContentData = null;
        if (self.upstreamLink) {
            pullReleaseContentData = {
                parent: self,
                linkedDataViewModels: _.map(data.model_status, LinkedDataViewModel),
                domainLink: self.upstreamLink,
            };
            self.pullReleaseContentViewModel = PullReleaseContentViewModel(pullReleaseContentData);
        }

        // General data
        self.domain = data.domain;
        self.domain_links = ko.observableArray(_.map(data.linked_domains, DomainLink));
        self.showRemoteReports = function () {
            if (data.linkable_ucr) {
                return data.linkable_ucr.length > 0;
            }
            return false;
        };

        self.isUpstreamDomain = ko.computed(function () {
            return self.domain_links().length > 0;
        });
        // doesn't need to be observable because it is impossible to update the existing page to change this property
        self.isDownstreamDomain = data.is_downstream_domain;

        self.isOnlyDownstreamDomain = ko.computed(function () {
            return !self.isUpstreamDomain() && self.isDownstreamDomain;
        });

        // Tab Header Statuses
        self.manageDownstreamDomainsTabStatus = ko.computed(function () {
            return self.isUpstreamDomain() ? "active" : "";
        });

        self.pullContentTabStatus = ko.computed(function () {
            return self.isOnlyDownstreamDomain() ? "active" : "";
        });

        // Tab Content Statuses
        self.manageTabActiveStatus = ko.computed(function () {
            return self.isUpstreamDomain() ? "in active" : "";
        });

        self.pullTabActiveStatus = ko.computed(function () {
            return self.isOnlyDownstreamDomain() ? "in active" : "";
        });

        self.showGetStarted = ko.computed(function () {
            return !self.isUpstreamDomain() && !self.isDownstreamDomain;
        });

        self.showMultipleTabs = ko.computed(function () {
            return self.isUpstreamDomain() || (self.isDownstreamDomain && self.showRemoteReports());
        });

        // can only push content if a link with a downstream domain exists
        var pushContentData = {
            parent: self,
        };
        self.pushContentViewModel = PushContentViewModel(pushContentData);
        // Manage Downstream Domains Tab
        // search box
        self.query = ko.observable();
        self.filteredDomainLinks = ko.observableArray([]);
        self.matchesQuery = function (domainLink) {
            return !self.query() || domainLink.linked_domain().toLowerCase().indexOf(self.query().toLowerCase()) !== -1;
        };
        self.filter = function () {
            self.filteredDomainLinks(_.filter(self.domain_links(), self.matchesQuery));
            self.goToPage(1);
        };

        // pagination
        self.paginatedDomainLinks = ko.observableArray([]);
        self.itemsPerPage = ko.observable(5);
        self.totalItems = ko.computed(function () {
            return self.query() ? self.filteredDomainLinks().length : self.domain_links().length;
        });
        self.currentPage = 1;

        self.goToPage = function (page) {
            self.currentPage = page;
            self.paginatedDomainLinks.removeAll();
            var skip = (self.currentPage - 1) * self.itemsPerPage();
            var visibleDomains = self.query() ? self.filteredDomainLinks() : self.domain_links();
            self.paginatedDomainLinks(visibleDomains.slice(skip, skip + self.itemsPerPage()));
        };

        self.onPaginationLoad = function () {
            self.goToPage(1);
        };

        self.linkableUcr = ko.observableArray(_.map(data.linkable_ucr, function (report) {
            return RemoteLinkableReport(report, self.upstreamLink);
        }));

        self.createRemoteReportLink = function (reportId) {
            _private.RMI("create_remote_report_link", {
                "master_domain": self.upstreamLink.master_domain,
                "linked_domain": self.upstreamLink.linked_domain(),
                "report_id": reportId,
            }).done(function (data) {
                if (data.success) {
                    alertUser.alert_user(gettext('Report successfully linked.'), 'success');
                } else {
                    alertUser.alert_user(gettext(
                        'Something unexpected happened.\n' +
                        'Please try again, or report an issue if the problem persists.'), 'danger');
                }
            }).fail(function () {
                alertUser.alert_user(gettext(
                    'Something unexpected happened.\n' +
                    'Please try again, or report an issue if the problem persists.'), 'danger');
            });
        };

        self.deleteLink = function (link) {
            _private.RMI("delete_domain_link", {
                "linked_domain": link.linked_domain(),
            }).done(function () {
                self.domain_links.remove(link);
                var availableDomains = self.addDownstreamDomainViewModel.availableDomains();
                availableDomains.push(link.linked_domain());
                self.addDownstreamDomainViewModel.availableDomains(availableDomains.sort());
                self.goToPage(self.currentPage);
            }).fail(function () {
                alertUser.alert_user(gettext('Something unexpected happened.\n' +
                    'Please try again, or report an issue if the problem persists.'), 'danger');
            }).always(function () {
                // fix for b3
                $('body').removeClass('modal-open');
                var $modalBackdrop = $('.modal-backdrop');
                if ($modalBackdrop) {
                    $modalBackdrop.remove();
                }
            });
        };

        return self;
    };

    var DomainLink = function (link) {
        var self = {};
        self.linked_domain = ko.observable(link.linked_domain);
        self.is_remote = link.is_remote;
        self.master_domain = link.master_domain;
        self.lastUpdate = link.last_update;
        self.upstreamUrl = link.upstream_url;
        self.downstreamUrl = link.downstream_url;
        return self;
    };

    var PushContentViewModel = function (data) {
        var self = {};
        self.parent = data.parent;
        self.domainsToPush = ko.observableArray();
        self.modelsToPush = ko.observableArray();
        self.buildAppsOnPush = ko.observable(false);
        self.pushInProgress = ko.observable(false);
        self.enablePushButton = ko.computed(function () {
            return self.domainsToPush().length && self.modelsToPush().length && !self.pushInProgress();
        });

        self.localDownstreamDomains = ko.computed(function () {
            return self.parent.domain_links().reduce(function (result, link) {
                if (!link.is_remote) {
                    return result.concat(link.linked_domain());
                }
                return result;
            }, []);
        });

        self.multiselectProperties = {
            selectableHeaderTitle: gettext("All project spaces"),
            selectedHeaderTitle: gettext("Project spaces to push to"),
            searchItemTitle: gettext("Search project spaces"),
        };

        self.canPush = ko.computed(function () {
            return self.localDownstreamDomains().length > 0;
        });

        self.pushContent = function () {
            self.pushInProgress(true);
            _private.RMI("create_release", {
                models: _.map(self.modelsToPush(), JSON.parse),
                linked_domains: self.domainsToPush(),
                build_apps: self.buildAppsOnPush(),
            }).done(function (data) {
                alertUser.alert_user(data.message, data.success ? 'success' : 'danger');
                self.pushInProgress(false);
            }).fail(function () {
                alertUser.alert_user(gettext('Something unexpected happened.\nPlease try again, or report an issue if the problem persists.'), 'danger');
                self.pushInProgress(false);
            });
        };

        return self;
    };

    var PullReleaseContentViewModel = function (data) {
        var self = {};
        // Pull Content Tab
        self.parent = data.parent;
        self.linkedDataViewModels = data.linkedDataViewModels;
        self.domainLink = data.domainLink;

        // search box
        self.query = ko.observable();
        self.filteredLinkedDataViewModels = ko.observableArray([]);
        self.matchesQuery = function (linkedDataViewModel) {
            return !self.query() || linkedDataViewModel.name.toLowerCase().indexOf(self.query().toLowerCase()) !== -1;
        };
        self.filter = function () {
            self.filteredLinkedDataViewModels(_.filter(self.linkedDataViewModels, self.matchesQuery));
            self.goToPage(1);
        };

        // pagination
        self.paginatedLinkedDataViewModels = ko.observableArray([]);
        self.itemsPerPage = ko.observable(5);
        self.totalItems = ko.computed(function () {
            return self.query() ? self.filteredLinkedDataViewModels().length : self.linkedDataViewModels.length;
        });
        self.currentPage = 1;

        self.goToPage = function (page) {
            self.currentPage = page;
            self.paginatedLinkedDataViewModels.removeAll();
            var skip = (self.currentPage - 1) * self.itemsPerPage();
            var visibleLinkedDataViewModels = self.query() ? self.filteredLinkedDataViewModels() : self.linkedDataViewModels;
            self.paginatedLinkedDataViewModels(visibleLinkedDataViewModels.slice(skip, skip + self.itemsPerPage()));
        };

        self.onPaginationLoad = function () {
            self.goToPage(1);
        };

        return self;
    };

    var RemoteLinkableReport = function (report, upstreamLink) {
        var self = {};
        self.id = report.id;
        self.title = report.title;
        self.alreadyLinked = ko.observable(report.already_linked);

        self.createLink = function () {
            _private.RMI("create_remote_report_link", {
                "master_domain": upstreamLink.master_domain,
                "linked_domain": upstreamLink.linked_domain(),
                "report_id": self.id,
            }).done(function (data) {
                if (data.success) {
                    alertUser.alert_user(gettext('Report successfully linked.'), 'success');
                    self.alreadyLinked(true);
                } else {
                    alertUser.alert_user(gettext(
                        'Something unexpected happened.\n' +
                            'Please try again, or report an issue if the problem persists.'), 'danger');
                }
            }).fail(function () {
                alertUser.alert_user(gettext(
                    'Something unexpected happened.\n' +
                        'Please try again, or report an issue if the problem persists.'), 'danger');
            });
        };

        return self;
    };

    var AddDownstreamDomainViewModel = function (data) {
        var self = {};
        self.parent = data.parent;
        self.availableDomains = ko.observableArray(data.availableDomains.sort());
        self.value = ko.observable();

        self.addDownstreamDomain = function (viewModel) {
            _private.RMI("create_domain_link", {
                "downstream_domain": viewModel.value(),
            }).done(function (response) {
                if (response.success) {
                    self.availableDomains(_.filter(self.availableDomains(), function (item) {
                        return item !== viewModel.value();
                    }));
                    self.value(null);
                    self.parent.domain_links.unshift(DomainLink(response.domain_link));
                    self.parent.goToPage(1);
                } else {
                    var errorMessage = _.template(
                        gettext('Unable to link project spaces. <%- error %>\nYou must remove the existing link before creating this new link.')
                    )({error: response.message});
                    alertUser.alert_user(errorMessage, 'danger');
                }
            }).fail(function () {
                alertUser.alert_user(gettext('Unable to link project spaces.\nPlease try again, or report an issue if the problem persists.'), 'danger');
            });
        };
        return self;
    };

    var GettingStartedViewModel = function (data) {
        var self = {};
        self.parent = data.parent;
        var sortedUpstreamDomains = data.upstreamDomains.sort(function (first, second) {
            var firstName = first.name.toUpperCase();
            var secondName = second.name.toUpperCase();
            if (firstName > secondName) {
                return 1;
            } else if (firstName < secondName) {
                return -1;
            } else {
                return 0;
            }
        });
        self.upstreamDomains = ko.observableArray(sortedUpstreamDomains);

        self.upstreamButtonClass = ko.computed(function () {
            return self.upstreamDomains().length > 0 ? "btn-default" : "btn-primary";
        });

        self.goToUpstream = function (data) {
            window.location.href = data.upstreamDomains()[0].url;
        };
        return self;
    };

    var setRMI = function (rmiUrl, csrfToken) {
        var _rmi = RMI(rmiUrl, csrfToken);
        _private.RMI = function (remoteMethod, data) {
            return _rmi("", data, {headers: {"DjNg-Remote-Method": remoteMethod}});
        };
    };

    $(function () {
        var view_data = initialPageData.get('view_data');
        var csrfToken = $("#csrfTokenContainer").val();
        setRMI(initialPageData.reverse('linked_domain:domain_link_rmi'), csrfToken);

        var model = DomainLinksViewModel(view_data);
        $("#ko-linked-projects").koApplyBindings(model);

        if ($("#new-downstream-domain-modal").length) {
            $("#new-downstream-domain-modal").koApplyBindings(model.addDownstreamDomainViewModel);
        }

    });
});
<|endoftext|>