<commit_before>/**
 * Copyright (c) 2016-present, Alejandro Mantilla <@AlejoJamC>.
 * All rights reserved.
 *
 * This source code is licensed under the MIT license found in the LICENSE
 * file in the root directory of this source tree or translated in the assets folder.
 */

var express     = require('express');
var base64      = require('../config/base64');
var crypto      = require('crypto');
var dashRoutes  = express.Router();
var fs          = require('fs');
var logger      = require('../config/logger').logger;
var multer      = require('multer');
var oracledb    = require('oracledb');
var path        = require('path');
var uuid        = require('node-uuid');

// Upload and rename files
var storage = multer.diskStorage({
    destination: 'uploads/',
    filename: function (req, file, cb) {
        crypto.pseudoRandomBytes(16, function (err, raw) {
            if (err) return cb(err);

            cb(null, raw.toString('hex') + path.extname(file.originalname))
        })
    }
});
var upload = multer({ storage: storage });

/* GET Index page. */
dashRoutes.get('/', function (req, res) {
    var error = '';
    // Basic error validator
    // Error
    if(typeof req.query.error !== 'undefined'){
        error = req.query.error;
    }
    // Session
    if(typeof req.session.userId === 'undefined' || typeof req.session.userId === ''){
        return res.redirect('/login');
    }
    // User Rol
    // If ............
    res.render('dash/search', {
        title   : 'Buscar | Identico',
        level   : '',
        layout  : 'dash',
        error   : error
    });
});

dashRoutes.get('/search/ajax', function (req, res) {
    var personDoc = req.query.cedula;
    oracledb.getConnection({
        user            : process.env.ORACLE_USERNAME,
        password        : process.env.ORACLE_PASSWORD,
        connectString   : process.env.ORACLE_HOST + ':' + process.env.ORACLE_PORT
        + '/' + process.env.ORACLE_SID
    }, function (err, connection) {
        if (err){
            logger.error(err.message);
            // error=0 trying to connect with database
            return res.send({ err : 'Error trying to connect with database.' , errCode : 0});
        }

        var sql = "SELECT N.IDPERSONA,N.PRIMERAPELLIDO,N.SEGUNDOAPELLIDO,N.PRIMERNOMBRE,N.SEGUNDONOMBRE," +
            "A.IDPERSONA AFILIADO, T.IDREFERIDO REFERIDO, " +
            "DECODE (NVL2(A.IDPERSONA,1,0) + NVL2(T.IDREFERIDO,2,0), 0, 'NO AFILIADO NI REFERIDO'," +
            " 1, 'AFILIADO', 2, 'REFERIDO',3, 'AFILIADO Y REFERIDO') TIPO" +
            " FROM NPERSONAS N, NAFILIADOS A, NAUTORIZACIONES T" +
            " WHERE N.IDPERSONA=A.IDPERSONA(+) AND N.IDPERSONA=T.IDREFERIDO(+) " +
            "AND N.NODOCUMENTO=" + personDoc;

        logger.info(sql);

        connection.execute(
            // The statement to execute
            sql,
            [ ],

            // The Callback function handles the SQL execution results
            function (err, result) {
                if (err) {
                    logger.error(err.message);
                    connection.close(
                        function(err) {
                            if (err) {
                                // error=1 trying to disconnect of database
                                logger.error(err.message);
                                return res.send({ err : 'trying to disconnect of database.' , errCode : 1});
                            }
                            logger.info('Connection to Oracle closed successfully!');
                            logger.info("1");
                        });
                    // Error doing select statement
                    return res.send({ err : 'Error doing select statement.'});
                }

                // Login success
                // Create the session
                if(typeof result.metaData === 'undefined' && typeof result.rows === 'undefined'){
                    logger.info('Validation error, empty values returned.');
                    connection.close(
                        function(err) {
                            if (err) {
                                // error=1 trying to disconnect of database
                                logger.error(err.message);
                                return res.send({ err : 'trying to disconnect of database.' , errCode : 1});
                            }
                            logger.info('Connection to Oracle closed successfully!');
                        });
                    return res.send({ data : 'Empty values returned.', code : 1});
                } else if(typeof result.rows[0] === 'undefined') {
                    logger.info('Validation error, empty values returned.');
                    connection.close(
                        function(err) {
                            if (err) {
                                // error=1 trying to disconnect of database
                                logger.error(err.message);
                                return res.send({ err : 'trying to disconnect of database.' , errCode : 1});
                            }
                            logger.info('Connection to Oracle closed successfully!');
                            logger.info("2");
                        });
                    return res.send({ data : 'Empty values returned.', code : 2});
                } else {
                    if(result.rows[0] == ''){
                        logger.info('Error trying to validate user credentials');
                        connection.close(
                            function(err) {
                                if (err) {
                                    // error=1 trying to disconnect of database
                                    logger.error(err.message);
                                    return res.send({ err : 'trying to disconnect of database.' , errCode : 1});
                                }
                                logger.info('Connection to Oracle closed successfully!');
                            });
                        return res.send({ data : 'Empty values returned.', code : 3});
                    }
                }

                var data = result;

                connection.close(
                    function(err) {
                        if (err) {
                            // error=1 trying to disconnect of database
                            logger.error(err.message);
                            return res.send({ err : 'trying to disconnect of database.' , errCode : 1});
                        }
                        logger.info('Connection to Oracle closed successfully!');
                        logger.info("3");

                    });
                logger.info(data);

                return res.send(data);

            }
        );
    });
});

/* GET Index page | Dashboard. */
dashRoutes.get('/dashboard', function (req, res) {
    // Basic error validator
    // Session
    if(typeof req.session.userId === 'undefined' || typeof req.session.userId === ''){
        return res.redirect('/login');
    }

    res.render('dash/index', {
        title   : 'Analytics Website | Index',
        level   : '',
        layout  : 'dash'
    });
});

/* GET Images handler page | Dashboard. */
dashRoutes.get('/dashboard/images', function (req, res) {
    res.render('dash/image', {
        title   : 'Analytics Website | Images',
        level   : '../',
        layout  : 'dash'
    });
});

/* POST Images handler page | Dashboard. */
dashRoutes.post('/dashboard/images/capture',  function (req, res) {

    if( typeof req.body.personid === 'undefined' || req.body.personid === ''){
        logger.info('Login credentials: Empty values.');
        // error=12 No person Id using image capture.
        return res.redirect('/dashboard/images?error=12');
    }

    //logger.info(req.body);

    //var encoded_image = req.body.finalimage;
    var binary_data = req.body.finalimage;

    // Random uuid to asign the new image
    var randomImageName = uuid.v4();
    var imagepath = 'uploads/' + randomImageName +'.jpg';
    // Create the file inside uploads folder
    var fileresult = fs.writeFile(imagepath, binary_data, {encoding: 'base64'}, function (err) {
        if(err){
            logger.info(err);
            logger.info('Error creating capture image');
            return res.redirect('/login?error=15');
        }

        // Save the image path in the database
        var personId = req.body.personid;
        // read the file
        var buf = fs.readFileSync(imagepath);
        var sql = "UPDATE HUELLA.NPERSONAS SET HUELLA.NPERSONAS.FOTO = :blob WHERE HUELLA.NPERSONAS.IDPERSONA =" + personId;

        // Save image route
        oracledb.autoCommit = true;
        oracledb.getConnection({
            user            : process.env.ORACLE_USERNAME,
            password        : process.env.ORACLE_PASSWORD,
            connectString   : process.env.ORACLE_HOST + ':' + process.env.ORACLE_PORT
            + '/' + process.env.ORACLE_SID
        }, function (err, connection) {
            if (err){
                logger.error(err.message);
                // error=0 trying to connect with database
                return res.redirect('/dashboard/images?error=0');
            }
            connection.execute(
                sql,
                [buf],
                // The Callback function handles the SQL execution results
                function (err, result) {
                    if (err) {
                        logger.error(err.message);
                        connection.close(
                            function(err) {
                                if (err) {
                                    // error=1 trying to disconnect of database
                                    logger.error(err.message);
                                    return res.redirect('/dashboard/images?error=1');
                                }
                                logger.info('Connection to Oracle closed successfully!');
                            });
                        // Error doing select statement
                        return res.redirect('/dashboard/images?error=12');
                    }

                    logger.info(result);

                    // UPDATE image capture success
                    connection.close(
                        function(err) {
                            if (err) {
                                // error=1 trying to disconnect of database
                                logger.error(err.message);
                                return res.redirect('/dashboard/images?error=1');
                            }
                            logger.info('Connection to Oracle closed successfully!');
                        });
                    res.redirect('/dashboard/images?flag=success');
                }
            );
        });
    });
});

/* POST Images handler page | Dashboard. */
dashRoutes.post('/dashboard/images/input', upload.single('inputpicture'), function (req, res) {
    if( typeof req.body.personid === 'undefined' || req.body.personid === ''){
        logger.info('Login credentials: Empty values.');
        // error=12 No person Id using image capture.
        return res.redirect('/login?error=12');
    }

    logger.info(req.file);
    //logger.info(req.body);

    var personId = req.body.personid;

    // read the file
    var buf = fs.readFileSync(req.file.path);

    /*var sql = "UPDATE HUELLA.NPERSONAS SET HUELLA.NPERSONAS.FOTO = " +
     buf + " WHERE HUELLA.NPERSONAS.IDPERSONA =" + personId;*/

    var sql = "UPDATE HUELLA.NPERSONAS SET HUELLA.NPERSONAS.FOTO = :blob WHERE HUELLA.NPERSONAS.IDPERSONA =" + personId;

    // Save image route
    oracledb.autoCommit = true;
    oracledb.getConnection({
        user            : process.env.ORACLE_USERNAME,
        password        : process.env.ORACLE_PASSWORD,
        connectString   : process.env.ORACLE_HOST + ':' + process.env.ORACLE_PORT
        + '/' + process.env.ORACLE_SID
    }, function (err, connection) {
        if (err){
            logger.error(err.message);
            // error=0 trying to connect with database
            return res.redirect('/dashboard/images?error=0');
        }

        connection.execute(
            sql,
            [buf],
            // The Callback function handles the SQL execution results
            function (err, result) {
                if (err) {
                    logger.error(err.message);
                    connection.close(
                        function(err) {
                            if (err) {
                                // error=1 trying to disconnect of database
                                logger.error(err.message);
                                return res.redirect('/dashboard/images?error=1');
                            }
                            logger.info('Connection to Oracle closed successfully!');
                        });
                    // Error doing select statement
                    return res.redirect('/dashboard/images?error=12');
                }

                if (result.rowsAffected != 1) {
                    logger.info('Error updating the image');
                    return res.redirect('/dashboard/images?error=2');
                }

                logger.info(result);

                // UPDATE image capture success
                connection.close(
                    function(err) {
                        if (err) {
                            // error=1 trying to disconnect of database
                            logger.error(err.message);
                            return res.redirect('/dashboard/images?error=1');
                        }
                        logger.info('Connection to Oracle closed successfully!');
                    });
                res.redirect('/dashboard/images?flag=success');
            }
        );
    });
});

/* GET Fingerprint applet page. */
dashRoutes.get('/applet', function (req, res) {
    var error = '';
    // Basic error validator
    // Error
    if(typeof req.query.error !== 'undefined'){
        error = req.query.error;
    }
    // Session
    if(typeof req.session.userId === 'undefined' || typeof req.session.userId === ''){
        return res.redirect('/login');
    }
    // User Rol
    // If ............
    res.render('dash/applet', {
        title   : 'Applet | Identico',
        level   : '',
        layout  : 'dash',
        error   : error
    });
});

module.exports = dashRoutes;<commit_msg>cleaning code<commit_after>/**
 * Copyright (c) 2016-present, Alejandro Mantilla <@AlejoJamC>.
 * All rights reserved.
 *
 * This source code is licensed under the MIT license found in the LICENSE
 * file in the root directory of this source tree or translated in the assets folder.
 */

var express     = require('express');
var base64      = require('../config/base64');
var crypto      = require('crypto');
var dashRoutes  = express.Router();
var fs          = require('fs');
var logger      = require('../config/logger').logger;
var multer      = require('multer');
var oracledb    = require('oracledb');
var path        = require('path');
var uuid        = require('node-uuid');

// Upload and rename files
var storage = multer.diskStorage({
    destination: 'uploads/',
    filename: function (req, file, cb) {
        crypto.pseudoRandomBytes(16, function (err, raw) {
            if (err) return cb(err);

            cb(null, raw.toString('hex') + path.extname(file.originalname))
        })
    }
});
var upload = multer({ storage: storage });

/* GET Index page. */
dashRoutes.get('/', function (req, res) {
    var error = '';
    // Basic error validator
    // Error
    if(typeof req.query.error !== 'undefined'){
        error = req.query.error;
    }
    // Session
    if(typeof req.session.userId === 'undefined' || typeof req.session.userId === ''){
        return res.redirect('/login');
    }
    // User Rol
    // If ............
    res.render('dash/search', {
        title   : 'Buscar | Identico',
        level   : '',
        layout  : 'dash',
        error   : error
    });
});

dashRoutes.get('/search/ajax', function (req, res) {
    var personDoc = req.query.cedula;
    oracledb.getConnection({
        user            : process.env.ORACLE_USERNAME,
        password        : process.env.ORACLE_PASSWORD,
        connectString   : process.env.ORACLE_HOST + ':' + process.env.ORACLE_PORT
        + '/' + process.env.ORACLE_SID
    }, function (err, connection) {
        if (err){
            logger.error(err.message);
            // error=0 trying to connect with database
            return res.send({ err : 'Error trying to connect with database.' , errCode : 0});
        }

        var sql = "SELECT N.IDPERSONA,N.PRIMERAPELLIDO,N.SEGUNDOAPELLIDO,N.PRIMERNOMBRE,N.SEGUNDONOMBRE," +
            "A.IDPERSONA AFILIADO, T.IDREFERIDO REFERIDO, " +
            "DECODE (NVL2(A.IDPERSONA,1,0) + NVL2(T.IDREFERIDO,2,0), 0, 'NO AFILIADO NI REFERIDO'," +
            " 1, 'AFILIADO', 2, 'REFERIDO',3, 'AFILIADO Y REFERIDO') TIPO" +
            " FROM NPERSONAS N, NAFILIADOS A, NAUTORIZACIONES T" +
            " WHERE N.IDPERSONA=A.IDPERSONA(+) AND N.IDPERSONA=T.IDREFERIDO(+) " +
            "AND N.NODOCUMENTO=" + personDoc;

        //logger.info(sql);

        connection.execute(
            // The statement to execute
            sql,
            [ ],

            // The Callback function handles the SQL execution results
            function (err, result) {
                if (err) {
                    logger.error(err.message);
                    connection.close(
                        function(err) {
                            if (err) {
                                // error=1 trying to disconnect of database
                                logger.error(err.message);
                                return res.send({ err : 'trying to disconnect of database.' , errCode : 1});
                            }
                            logger.info('Connection to Oracle closed successfully!');
                        });
                    // Error doing select statement
                    return res.send({ err : 'Error doing select statement.'});
                }

                // Login success
                // Create the session
                if(typeof result.metaData === 'undefined' && typeof result.rows === 'undefined'){
                    logger.info('Validation error, empty values returned.');
                    connection.close(
                        function(err) {
                            if (err) {
                                // error=1 trying to disconnect of database
                                logger.error(err.message);
                                return res.send({ err : 'trying to disconnect of database.' , errCode : 1});
                            }
                            logger.info('Connection to Oracle closed successfully!');
                        });
                    return res.send({ data : 'Empty values returned.', code : 1});
                } else if(typeof result.rows[0] === 'undefined') {
                    logger.info('Validation error, empty values returned.');
                    connection.close(
                        function(err) {
                            if (err) {
                                // error=1 trying to disconnect of database
                                logger.error(err.message);
                                return res.send({ err : 'trying to disconnect of database.' , errCode : 1});
                            }
                            logger.info('Connection to Oracle closed successfully!');
                        });
                    return res.send({ data : 'Empty values returned.', code : 2});
                } else {
                    if(result.rows[0] == ''){
                        logger.info('Error trying to validate user credentials');
                        connection.close(
                            function(err) {
                                if (err) {
                                    // error=1 trying to disconnect of database
                                    logger.error(err.message);
                                    return res.send({ err : 'trying to disconnect of database.' , errCode : 1});
                                }
                                logger.info('Connection to Oracle closed successfully!');
                            });
                        return res.send({ data : 'Empty values returned.', code : 3});
                    }
                }

                var data = result;

                connection.close(
                    function(err) {
                        if (err) {
                            // error=1 trying to disconnect of database
                            logger.error(err.message);
                            return res.send({ err : 'trying to disconnect of database.' , errCode : 1});
                        }
                        logger.info('Connection to Oracle closed successfully!');
                        logger.info("3");

                    });
                return res.send(data);
            }
        );
    });
});

/* GET Index page | Dashboard. */
dashRoutes.get('/dashboard', function (req, res) {
    // Basic error validator
    // Session
    if(typeof req.session.userId === 'undefined' || typeof req.session.userId === ''){
        return res.redirect('/login');
    }

    res.render('dash/index', {
        title   : 'Analytics Website | Index',
        level   : '',
        layout  : 'dash'
    });
});

/* GET Images handler page | Dashboard. */
dashRoutes.get('/dashboard/images', function (req, res) {
    res.render('dash/image', {
        title   : 'Analytics Website | Images',
        level   : '../',
        layout  : 'dash'
    });
});

/* POST Images handler page | Dashboard. */
dashRoutes.post('/dashboard/images/capture',  function (req, res) {

    if( typeof req.body.personid === 'undefined' || req.body.personid === ''){
        logger.info('Login credentials: Empty values.');
        // error=12 No person Id using image capture.
        return res.redirect('/dashboard/images?error=12');
    }

    //logger.info(req.body);

    //var encoded_image = req.body.finalimage;
    var binary_data = req.body.finalimage;

    // Random uuid to asign the new image
    var randomImageName = uuid.v4();
    var imagepath = 'uploads/' + randomImageName +'.jpg';
    // Create the file inside uploads folder
    var fileresult = fs.writeFile(imagepath, binary_data, {encoding: 'base64'}, function (err) {
        if(err){
            logger.info(err);
            logger.info('Error creating capture image');
            return res.redirect('/login?error=15');
        }

        // Save the image path in the database
        var personId = req.body.personid;
        // read the file
        var buf = fs.readFileSync(imagepath);
        var sql = "UPDATE HUELLA.NPERSONAS SET HUELLA.NPERSONAS.FOTO = :blob WHERE HUELLA.NPERSONAS.IDPERSONA =" + personId;

        // Save image route
        oracledb.autoCommit = true;
        oracledb.getConnection({
            user            : process.env.ORACLE_USERNAME,
            password        : process.env.ORACLE_PASSWORD,
            connectString   : process.env.ORACLE_HOST + ':' + process.env.ORACLE_PORT
            + '/' + process.env.ORACLE_SID
        }, function (err, connection) {
            if (err){
                logger.error(err.message);
                // error=0 trying to connect with database
                return res.redirect('/dashboard/images?error=0');
            }
            connection.execute(
                sql,
                [buf],
                // The Callback function handles the SQL execution results
                function (err, result) {
                    if (err) {
                        logger.error(err.message);
                        connection.close(
                            function(err) {
                                if (err) {
                                    // error=1 trying to disconnect of database
                                    logger.error(err.message);
                                    return res.redirect('/dashboard/images?error=1');
                                }
                                logger.info('Connection to Oracle closed successfully!');
                            });
                        // Error doing select statement
                        return res.redirect('/dashboard/images?error=12');
                    }

                    logger.info(result);

                    // UPDATE image capture success
                    connection.close(
                        function(err) {
                            if (err) {
                                // error=1 trying to disconnect of database
                                logger.error(err.message);
                                return res.redirect('/dashboard/images?error=1');
                            }
                            logger.info('Connection to Oracle closed successfully!');
                        });
                    res.redirect('/dashboard/images?flag=success');
                }
            );
        });
    });
});

/* POST Images handler page | Dashboard. */
dashRoutes.post('/dashboard/images/input', upload.single('inputpicture'), function (req, res) {
    if( typeof req.body.personid === 'undefined' || req.body.personid === ''){
        logger.info('Login credentials: Empty values.');
        // error=12 No person Id using image capture.
        return res.redirect('/login?error=12');
    }

    logger.info(req.file);
    //logger.info(req.body);

    var personId = req.body.personid;

    // read the file
    var buf = fs.readFileSync(req.file.path);

    /*var sql = "UPDATE HUELLA.NPERSONAS SET HUELLA.NPERSONAS.FOTO = " +
     buf + " WHERE HUELLA.NPERSONAS.IDPERSONA =" + personId;*/

    var sql = "UPDATE HUELLA.NPERSONAS SET HUELLA.NPERSONAS.FOTO = :blob WHERE HUELLA.NPERSONAS.IDPERSONA =" + personId;

    // Save image route
    oracledb.autoCommit = true;
    oracledb.getConnection({
        user            : process.env.ORACLE_USERNAME,
        password        : process.env.ORACLE_PASSWORD,
        connectString   : process.env.ORACLE_HOST + ':' + process.env.ORACLE_PORT
        + '/' + process.env.ORACLE_SID
    }, function (err, connection) {
        if (err){
            logger.error(err.message);
            // error=0 trying to connect with database
            return res.redirect('/dashboard/images?error=0');
        }

        connection.execute(
            sql,
            [buf],
            // The Callback function handles the SQL execution results
            function (err, result) {
                if (err) {
                    logger.error(err.message);
                    connection.close(
                        function(err) {
                            if (err) {
                                // error=1 trying to disconnect of database
                                logger.error(err.message);
                                return res.redirect('/dashboard/images?error=1');
                            }
                            logger.info('Connection to Oracle closed successfully!');
                        });
                    // Error doing select statement
                    return res.redirect('/dashboard/images?error=12');
                }

                if (result.rowsAffected != 1) {
                    logger.info('Error updating the image');
                    return res.redirect('/dashboard/images?error=2');
                }

                logger.info(result);

                // UPDATE image capture success
                connection.close(
                    function(err) {
                        if (err) {
                            // error=1 trying to disconnect of database
                            logger.error(err.message);
                            return res.redirect('/dashboard/images?error=1');
                        }
                        logger.info('Connection to Oracle closed successfully!');
                    });
                res.redirect('/dashboard/images?flag=success');
            }
        );
    });
});

/* GET Fingerprint applet page. */
dashRoutes.get('/applet', function (req, res) {
    var error = '';
    // Basic error validator
    // Error
    if(typeof req.query.error !== 'undefined'){
        error = req.query.error;
    }
    // Session
    if(typeof req.session.userId === 'undefined' || typeof req.session.userId === ''){
        return res.redirect('/login');
    }
    // User Rol
    // If ............
    res.render('dash/applet', {
        title   : 'Applet | Identico',
        level   : '',
        layout  : 'dash',
        error   : error
    });
});

module.exports = dashRoutes;<|endoftext|>


<commit_before>'use strict';

var ChildProcess = require("child_process");

// child states
var IDLE = 0,
    DEAD = 1,
    SPAWNING = 2,
    BUSY = 3;

/////////////////////////////////
// Endpoint controller
// - Note that this runs in the main process
function EndpointController(config) {
    // need to spawn child proc
    this.child = null;
    this.childState = DEAD;
    this.currentReq = null;
    this.requestQueue = [];
}

EndpointController.prototype.attach = function(app, base) {
    this._spawnWorker();
    this.base = base + "/:id";
    // ensure the request is handled with a slash
    app.use(this.base + "/", this.handler.bind(this));
};

EndpointController.prototype.handler = function(req, res) {
    this.requestQueue.push({ req : req, res : res });
    this._runNext();
};

EndpointController.prototype._runNext = function() {
    if (!this.requestQueue.length || this.childState !== IDLE) {
	return;
    }
    this.childState = BUSY;
    this.currentReq = this.requestQueue.pop();
    var req = this.currentReq.req;
    var message = {
	type : "request",
	data : {
	    path : req.path,
	    method : req.method,
	    params : req.params,
	    body : req.body,
	    query : req.body,
	    headers : req.headers
	}
    };
    this.child.send(message);
};

EndpointController.prototype._spawnWorker = function() {
    this.child = ChildProcess.fork(__dirname + "/../endpoints/runner.js");
    this.childState = SPAWNING;
    this.child.on("message", function(msg) {
	var type = msg.type;
	var data = msg.data;
	if (type === "done") {
	    this.childState = IDLE;
	    var res = this.currentReq.res;
	    this.currentReq = null;
	    res.status(data.status);
	    res.set("Content-Type", data.mime);
	    res.send(data.data);
	    this._runNext();
	} else if (type === "ready") {
	    this.childState = IDLE;
	    this._runNext();
	}
    }.bind(this));
};

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

// all route controllers expose a setup method
module.exports.setup = function(app, config) {
    var controller = new EndpointController(config);
    controller.attach(app, "/api/v1.1/endpoints");
};

<commit_msg>Fixing tabs/spaces issue<commit_after>'use strict';

var ChildProcess = require("child_process");

// child states
var IDLE = 0,
    DEAD = 1,
    SPAWNING = 2,
    BUSY = 3;

/////////////////////////////////
// Endpoint controller
// - Note that this runs in the main process
function EndpointController(config) {
    // need to spawn child proc
    this.child = null;
    this.childState = DEAD;
    this.currentReq = null;
    this.requestQueue = [];
}

EndpointController.prototype.attach = function(app, base) {
    this._spawnWorker();
    this.base = base + "/:id";
    // ensure the request is handled with a slash
    app.use(this.base + "/", this.handler.bind(this));
};

EndpointController.prototype.handler = function(req, res) {
    this.requestQueue.push({ req : req, res : res });
    this._runNext();
};

EndpointController.prototype._runNext = function() {
    if (!this.requestQueue.length || this.childState !== IDLE) {
        return;
    }
    this.childState = BUSY;
    this.currentReq = this.requestQueue.pop();
    var req = this.currentReq.req;
    var message = {
        type : "request",
        data : {
            path : req.path,
            method : req.method,
            params : req.params,
            body : req.body,
            query : req.body,
            headers : req.headers
        }
    };
    this.child.send(message);
};

EndpointController.prototype._spawnWorker = function() {
    this.child = ChildProcess.fork(__dirname + "/../endpoints/runner.js");
    this.childState = SPAWNING;
    this.child.on("message", function(msg) {
        var type = msg.type;
        var data = msg.data;
        if (type === "done") {
            this.childState = IDLE;
            var res = this.currentReq.res;
            this.currentReq = null;
            res.status(data.status);
            res.set("Content-Type", data.mime);
            res.send(data.data);
            this._runNext();
        } else if (type === "ready") {
            this.childState = IDLE;
            this._runNext();
        }
    }.bind(this));
};

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

// all route controllers expose a setup method
module.exports.setup = function(app, config) {
    var controller = new EndpointController(config);
    controller.attach(app, "/api/v1.1/endpoints");
};

<|endoftext|>


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

(function(scope, testing) {

  var propertyHandlers = {};

  function addPropertyHandler(parser, merger, property) {
    propertyHandlers[property] = propertyHandlers[property] || [];
    propertyHandlers[property].push([parser, merger]);
  }
  function addPropertiesHandler(parser, merger, properties) {
    for (var i = 0; i < properties.length; i++) {
      var property = properties[i];
      WEB_ANIMATIONS_TESTING && console.assert(property.toLowerCase() === property);
      addPropertyHandler(parser, merger, property);
      if (/-/.test(property)) {
        // Add camel cased variant.
        addPropertyHandler(parser, merger, property.replace(/-(.)/g, function(_, c) {
          return c.toUpperCase();
        }));
      }
    }
  }
  scope.addPropertiesHandler = addPropertiesHandler;

  function propertyInterpolation(property, left, right) {
    var handlers = left == right ? [] : propertyHandlers[property];
    for (var i = 0; handlers && i < handlers.length; i++) {
      var parsedLeft = handlers[i][0](left);
      var parsedRight = handlers[i][0](right);
      if (parsedLeft !== undefined && parsedRight !== undefined) {
        var interpolationArgs = handlers[i][1](parsedLeft, parsedRight);
        if (interpolationArgs)
          return scope.Interpolation.apply(null, interpolationArgs);
      }
    }
    return scope.Interpolation(false, true, function(bool) {
      return bool ? right : left;
    });
  }
  scope.propertyInterpolation = propertyInterpolation;

})(webAnimationsMinifill, webAnimationsTesting);

<commit_msg>Output specified values when fraction is the same as a specified offset<commit_after>// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
// limitations under the License.

(function(scope, testing) {

  var propertyHandlers = {};

  function addPropertyHandler(parser, merger, property) {
    propertyHandlers[property] = propertyHandlers[property] || [];
    propertyHandlers[property].push([parser, merger]);
  }
  function addPropertiesHandler(parser, merger, properties) {
    for (var i = 0; i < properties.length; i++) {
      var property = properties[i];
      WEB_ANIMATIONS_TESTING && console.assert(property.toLowerCase() === property);
      addPropertyHandler(parser, merger, property);
      if (/-/.test(property)) {
        // Add camel cased variant.
        addPropertyHandler(parser, merger, property.replace(/-(.)/g, function(_, c) {
          return c.toUpperCase();
        }));
      }
    }
  }
  scope.addPropertiesHandler = addPropertiesHandler;

  function propertyInterpolation(property, left, right) {
    var handlers = left == right ? [] : propertyHandlers[property];
    for (var i = 0; handlers && i < handlers.length; i++) {
      var parsedLeft = handlers[i][0](left);
      var parsedRight = handlers[i][0](right);
      if (parsedLeft !== undefined && parsedRight !== undefined) {
        var interpolationArgs = handlers[i][1](parsedLeft, parsedRight);
        if (interpolationArgs) {
          var interp =  scope.Interpolation.apply(null, interpolationArgs);
          return function(t) {
            if (t == 0) return left;
            if (t == 1) return right;
            return interp(t);
          };
        }
      }
    }
    return scope.Interpolation(false, true, function(bool) {
      return bool ? right : left;
    });
  }
  scope.propertyInterpolation = propertyInterpolation;

})(webAnimationsMinifill, webAnimationsTesting);

<|endoftext|>


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

'use strict';

import Ember from 'ember';
import commandParser from './commandParser';

export default Ember.Object.extend({
    sessionId: 0,

    _pollSeq: 0,
    _sendSeq: 0,
    _sendQueue: [],
    _callbacks: {},
    _firstPoll: true,
    _unsolicitedParser: null,
    _state: 'normal',

    init: function(friendsModel) {
        this._super();
        this._pollMsgs();
        this._unsolicitedParser = commandParser.create({
            friendsModel: this.get('friendsModel'),
            nicksModel: this.get('nicksModel'),
            usersModel: usersModel
        });
    },

    send: function(command, callback) {
        this._sendQueue.push(command);

        if (callback) {
            this._callbacks[command.id + '_RESP'] = callback;
        }

        Ember.Logger.info('Outgoing command buffered: ' + command.id + ' (Queue len: ' +
            this._sendQueue.length + ')');

        if (this._sendQueue.length === 1) {
            this._sendMsg(this._sendQueue[0]);
        }
    },

    _sendMsg: function(message) {
        var data = {
            sessionId: this.sessionId,
            seq: this._sendSeq,
            command: message
        };

        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: ':3200/api/v1/send',
            data: JSON.stringify(data),
            success: this._sendMsgSuccess,
            error: this._sendMsgFailure,
            context: this,
            timeout: 10000
        });

        Ember.Logger.info('--> MSG: ' + message.id);
    },

    _sendMsgSuccess: function() {
        this._sendQueue.shift();
        this._sendSeq++;

        if (this._state === 'error') {
            this._state = 'normal';
            // this._.setStatusTextCb.call(this._cbCtx, '');
        }

        this._sendMsgFinished();
    },

    _sendMsgFailure: function(jqXHR) {
        var code = jqXHR.status;
        this._state = 'error';

        Ember.Logger.error('sendMsg: XHR request failed, code: ' + code);

        if (code === 401 || code === 406) {
            this._logout();
        } else {
            // TBD: Add notification: 'Connection to MAS server lost, trying to reconnect...'

            // Stay optimistic and keep trying
            setTimeout(function() {
                this._sendMsgFinished();
            }.bind(this), 2000);
        }
    },

    _sendMsgFinished: function() {
        if (this._sendQueue.length > 0) {
            var message = this._sendQueue[0];
            this._sendMsg(message);
        }
    },

    _pollMsgs: function() {
        var data = { seq: this._pollSeq };

        if (this._firstPoll) {
            data.clientName = 'webclient';
            data.clientOS = navigator.platform;
        } else {
            data.sessionId = this.sessionId;
        }

        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            url: 'http://localhost:3200/api/v1/listen',
            data: JSON.stringify(data),
            success: this._pollMsgsSuccess,
            error: this._pollMsgsFailure,
            context: this,
            timeout: 35000
        });

        Ember.Logger.info('--> Polling request sent (seq ' + this._pollSeq + ')');
    },

    _pollMsgsSuccess: function(data) {
        this._pollSeq++;

        if (this._firstPoll) {
            this._firstPoll = false;
        }

        this._processCommands(data);
        this._pollMsgs();
    },

    _processCommands: function(commands) {
        for (var i = 0; i < commands.length; i++) {
            var command = commands[i];
            Ember.Logger.info('<-- MSG: ' + JSON.stringify(command));

            if (this._callbacks[command.id]) {
                // Command is a response to command we sent earlier
                this._callbacks[command.id](command);
            } else if (command.id === 'SESSIONID') {
                // Special unsolicited command that can be handle directly here
                this.sessionId = command.sessionId;
            } else {
                // Other Unsolicited command
                this._unsolicitedParser.process(command);
            }
        }
    },

    _pollMsgsFailure: function(jqXHR, textStatus, error ) {
        var code = jqXHR.status;

        if (code === 401 || code === 406) {
            this._logout();
        }

        var err = textStatus + ', ' + error;
        Ember.Logger.warn('Request Failed: ' + err );

        // Stay positive, keep trying
        setTimeout(function() {
            this._pollMsgs();
        }.bind(this), 2000);
    },

    _logout: function() {
        $.removeCookie('auth', { path: '/' });
        window.location = '/';
    }
});
<commit_msg>Init network module properly and use correct URL<commit_after>//
//   Copyright 2009-2014 Ilkka Oksanen <iao@iki.fi>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing,
//   software distributed under the License is distributed on an "AS
//   IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
//   express or implied.  See the License for the specific language
//   governing permissions and limitations under the License.
//

'use strict';

import Ember from 'ember';
import commandParser from './commandParser';

export default Ember.Object.extend({
    sessionId: 0,

    _pollSeq: 0,
    _sendSeq: 0,
    _sendQueue: [],
    _callbacks: {},
    _firstPoll: true,
    _unsolicitedParser: null,
    _state: 'normal',

    init: function() {
        this._super();
        this._pollMsgs();
        this._unsolicitedParser = commandParser.create({
            windowsModel: this.get('windowsModel'),
            friendsModel: this.get('friendsModel'),
            nicksModel: this.get('nicksModel'),
            usersModel: this.get('usersModel')
        });
    },

    send: function(command, callback) {
        this._sendQueue.push(command);

        if (callback) {
            this._callbacks[command.id + '_RESP'] = callback;
        }

        Ember.Logger.info('Outgoing command buffered: ' + command.id + ' (Queue len: ' +
            this._sendQueue.length + ')');

        if (this._sendQueue.length === 1) {
            this._sendMsg(this._sendQueue[0]);
        }
    },

    _sendMsg: function(message) {
        var data = {
            sessionId: this.sessionId,
            seq: this._sendSeq,
            command: message
        };

        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: '/api/v1/send',
            data: JSON.stringify(data),
            success: this._sendMsgSuccess,
            error: this._sendMsgFailure,
            context: this,
            timeout: 10000
        });

        Ember.Logger.info('--> MSG: ' + message.id);
    },

    _sendMsgSuccess: function() {
        this._sendQueue.shift();
        this._sendSeq++;

        if (this._state === 'error') {
            this._state = 'normal';
            // this._.setStatusTextCb.call(this._cbCtx, '');
        }

        this._sendMsgFinished();
    },

    _sendMsgFailure: function(jqXHR) {
        var code = jqXHR.status;
        this._state = 'error';

        Ember.Logger.error('sendMsg: XHR request failed, code: ' + code);

        if (code === 401 || code === 406) {
            this._logout();
        } else {
            // TBD: Add notification: 'Connection to MAS server lost, trying to reconnect...'

            // Stay optimistic and keep trying
            setTimeout(function() {
                this._sendMsgFinished();
            }.bind(this), 2000);
        }
    },

    _sendMsgFinished: function() {
        if (this._sendQueue.length > 0) {
            var message = this._sendQueue[0];
            this._sendMsg(message);
        }
    },

    _pollMsgs: function() {
        var data = { seq: this._pollSeq };

        if (this._firstPoll) {
            data.clientName = 'webclient';
            data.clientOS = navigator.platform;
        } else {
            data.sessionId = this.sessionId;
        }

        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            url: 'http://localhost:3200/api/v1/listen',
            data: JSON.stringify(data),
            success: this._pollMsgsSuccess,
            error: this._pollMsgsFailure,
            context: this,
            timeout: 35000
        });

        Ember.Logger.info('--> Polling request sent (seq ' + this._pollSeq + ')');
    },

    _pollMsgsSuccess: function(data) {
        this._pollSeq++;

        if (this._firstPoll) {
            this._firstPoll = false;
        }

        this._processCommands(data);
        this._pollMsgs();
    },

    _processCommands: function(commands) {
        for (var i = 0; i < commands.length; i++) {
            var command = commands[i];
            Ember.Logger.info('<-- MSG: ' + JSON.stringify(command));

            if (this._callbacks[command.id]) {
                // Command is a response to command we sent earlier
                this._callbacks[command.id](command);
            } else if (command.id === 'SESSIONID') {
                // Special unsolicited command that can be handle directly here
                this.sessionId = command.sessionId;
            } else {
                // Other Unsolicited command
                this._unsolicitedParser.process(command);
            }
        }
    },

    _pollMsgsFailure: function(jqXHR, textStatus, error ) {
        var code = jqXHR.status;

        if (code === 401 || code === 406) {
            this._logout();
        }

        var err = textStatus + ', ' + error;
        Ember.Logger.warn('Request Failed: ' + err );

        // Stay positive, keep trying
        setTimeout(function() {
            this._pollMsgs();
        }.bind(this), 2000);
    },

    _logout: function() {
        $.removeCookie('auth', { path: '/' });
        window.location = '/';
    }
});
<|endoftext|>


<commit_before>var cssUrls = [
    'schmux.css',
    'jquery.terminal.css',         // http://terminal.jcubic.pl/js/jquery.terminal.css
    'jquery-ui.css',               // http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css
    'client.css'
];

var scriptUrls = [
    'jquery.js',
    'jquery.svg.js',
    'jquery.terminal.js',          // http://terminal.jcubic.pl/js/jquery.terminal-0.4.12.min.js
    'jquery.mousewheel.js',        // http://terminal.jcubic.pl/js/jquery.mousewheel-min.js
    'eeprom-web.js',
    'autoadvance.js',
    'processing.js',
    'jquery-ui.min.js',         // http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js
    'weatherstation.js',
    'bone.js',
    'ajaxorg-ace-builds-c2f3abb/ace.js' // https://github.com/ajaxorg/ace-builds/commit/c2f3abb2ecd3287f90225d804132f0fd26cfb639
];

var doAlert = function(m) {
    alert(JSON.stringify(m));
};

var demoRun = function(id) {
    var myScript = document.getElementById(id).innerHTML;
    myScript = myScript.replace("<", "<");
    myScript = myScript.replace(">", ">");
    myScript = myScript.replace("&", "&");
    eval(myScript);
};

var callbacks = {};
var seqnum = 0;
var seqcall = function(data) {
    if(data.seq && (typeof callbacks[data.seq] == 'function')) {
        callbacks[data.seq](data);
        if(data.oneshot) delete callbacks[data.seq];
    }
}

var printPin = function(pinname) {
    $("#" + pinname).css("background-color", "#000000");
}

var clearPin = function(pinname) {
    $("#" + pinname).css("background-color", "#EAF2D3");
}

var completeMux = function(data) {
    bone = data.platform;
    for(var pinname in bone) {
        $("#" + pinname + "_name").html(bone[pinname].name);
        if(bone[pinname].mux) {
            getPinMode(bone[pinname], setMuxSelect);
        }
    }
};

//var slidyDisable = function() {
//  document.removeEventListener('keydown', w3c_slidy.key_down);
//  document.removeEventListener('keypress', w3c_slidy.key_press);
//};
//
//var slidyEnable = function() {
//  w3c_slidy.add_listener(document, 'keydown', w3c_slidy.key_down);
//  w3c_slidy.add_listener(document, 'keypress', w3c_slidy.key_press);
//}

var initClient = function() {
    $("#slider1").slider();
    $("#slider2").slider();

    $("#buttons").append("
" +
      "<button class=\"dynlink\" onclick=\"demoRun('code')\">Run</button>" +
      "<button class=\"dynlink\" onclick=\"demoEdit('code')\">Editor</button>" +
      "<button class=\"dynlink\" onclick=\"openJSTerm('js_term')\">Interpreter</button>" +
      "
");

    demoEdit = function(id) {
        var editor = ace.edit(id);
        editor.setTheme("ace/theme/monokai");
        editor.getSession().setMode("ace/mode/javascript");
        var originalDemoRun = demoRun;
        demoRun = function(myid) {
            if(myid == id) eval(editor.getValue());
            else originalDemoRun(myid);
        }
    };

    try {
        var canvas = document.getElementById("canvas1");
        var graphDataSize = 50;
        window.graphData = new Array(graphDataSize);
        for(var i=0; i<graphDataSize; i++) {
            window.graphData[i] = 0;
        }
        var sketchProc = function(p) {
            p.size(600, 250);

            // variables referenced elsewhere
            window.height = p.height;

            // variables that might get updated
            window.rangeLow = 0;
            window.rangeHigh = 1;
            window.scaleY = window.height / (window.rangeHigh - window.rangeLow);

            // local variables
            var stepX = p.width / (graphDataSize - 1);
            var centerY = window.height / 2;

            p.noLoop();
            p.draw = function() {
                // erase background
                p.background(224);

                // draw axis
                p.stroke(25);
                p.strokeWeight(1);
                p.line(0, centerY, p.width, centerY);

                // draw graph
                p.stroke(0);
                p.strokeWeight(3);
                //p.line(0, centerY+1, p.width, centerY+1);
                var lastX = 0, nextX = 0, lastY, nextY;
                for(var point in window.graphData) {
                    nextY = ((window.rangeHigh - window.graphData[point]) * scaleY);
                    if(point != 0) {
                        p.line(lastX, lastY, nextX, nextY);
                        lastX += stepX;
                    }
                    nextX += stepX;
                    lastY = nextY;
                }
            };
        };
        var processing = new Processing(canvas, sketchProc);
        graphDraw = function(data) {
            var myData = parseFloat(data);
            for(var i=0; i<graphDataSize-1; i++) {
                window.graphData[i] = window.graphData[i+1];
            }
            window.graphData[i] = myData;
            if (myData > rangeHigh) {
                rangeHigh = myData;
                window.scaleY = window.height / (window.rangeHigh - window.rangeLow);
            }
            if (myData < rangeLow) {
                rangeLow = myData;
                window.scaleY = window.height / (window.rangeHigh - window.rangeLow);
            }
            processing.redraw();
        };
    } catch(ex) {
        console.log('Unable to attach Processing.JS to canvas because ' + ex);
    }

    var onSocketIOLoaded = function() {
        try {
            var socket = io.connect('');
            var myfuncs = {
                'digitalWrite': [ 'pin', 'value' ],
                'digitalRead': [ 'pin' ],
                'analogRead': [ 'pin' ],
                'analogWrite': [ 'pin', 'value', 'freq' ],
                'pinMode': [ 'pin', 'direction', 'mux', 'pullup', 'slew' ],
                'shiftOut': [ 'dataPin', 'clockPin', 'bitOrder', 'val' ],
                'attachInterrupt': [ 'pin', 'handler', 'mode' ],
                'detachInterrupt': [ 'pin' ],
                'getPinMode': [ 'pin' ],
                'getEeproms': [],
                'platform': [],
                'shell': [ 'command' ],
                'echo': [ 'data' ],
                'doEval': [ 'evalFunc' ],
                'addLoop': [ 'loopFunc', 'loopDelay' ],
                'getLoops': [],
                'removeLoop': [ 'loopid' ],
                'removeLoops': [],
                'readTextFile': [ 'filename' ],
                'writeTextFile': [ 'filename', 'data' ]
            };
            for(var x in myfuncs) {
                socket.on(x, function(data) {
                    seqcall(data);
                });
                var myargs = myfuncs[x];
                var objString = '';
                for(var y in myargs) {
                    if(isNaN(y)) continue;  // Need to find the source of this bug
                    objString += ' if(typeof ' + myargs[y] + ' == "function") {\n';
                    objString += '  ' + myargs[y] + ' = ' + myargs[y] + '.toString();\n';
                    objString += ' }\n';
                    objString += ' calldata.' + myargs[y] + ' = ' + myargs[y] + ';\n';
                }
                myargs.push('callback');
                var argsString = myargs.join(', ');
                var handyfunc = x + ' = ' +
                    'function (' + argsString + ') {\n' +
                    ' var calldata = {};\n' +
                    objString +
                    ' if(callback) {\n' +
                    '  seqnum++;\n' +
                    '  callbacks[seqnum] = callback;\n' +
                    '  calldata.seq = seqnum;\n' +
                    ' }\n' +
                    ' socket.emit("' + x + '", calldata);\n' +
                    '};\n';
                eval(handyfunc);
            }

            try {
                var addedShellListener = false;
                $('#shell').terminal(
                    function(command, term) {
                        if(!addedShellListener) {
                            socket.on('shell', function(s) {
                                term.echo(s);
                            });
                            addedShellListener = true;
                        }
                        shell(command);
                    },
                    {
                        greetings: "BeagleBone bash shell",
                        name: "bash",
                        height: 600,
                        prompt: 'bash>'
                    }
                );
            } catch(ex) {
                console.log("Unable to open shell terminal window due to " + ex);
            }
            var js_term = {};
            var dir = function(obj) {
                var y = [];
                for(var x in obj) {
                    if(obj.hasOwnProperty(x)) {
                        y.push(x);
                    }
                }
                return y.join(', ');
            }
            js_term.term = function(command, term) {
                if(command !== '') {
                    var result = eval(command);
                    if (result !== undefined) {
                        term.echo(String(result));
                    }
                }
            };
            js_term.args = {
                    greetings: 'Javascript Interpreter',
                    name: 'js_demo',
                    height: 300,
                    prompt: 'js>'
            };
            openJSTerm = function(id) {
                var myJSTerm = document.getElementById(id);
                if(myJSTerm.hasTerminal && myJSTerm.isEnabled) {
                    $(myJSTerm).terminal.disable();
                    myJSTerm.isEnabled = false;
                } else {
                    $(myJSTerm).terminal(js_term.term, js_term.args);
                    myJSTerm.isEnabled = true;
                }
                myJSTerm.hasTerminal = true;
            };

            var setMuxSelect = function(data) {
                var pinname = data.pin;
                if(data.options) {
                    var muxSelect = "<select class='mux'>\n";
                    for(var option in data.options) {
                        if(isNaN(option)) continue;
                        var pinFunction = data.options[option];
                        var muxSelected = "";
                        // Select the signal the pin is currently muxed to
                        if(option == data.mux) {
                            muxSelected = "selected=true";
                        }
                        muxSelect += "<option " + muxSelected + ">" + option + ": " + pinFunction + "</option>";
                    }
                    muxSelect += "</select>\n";
                    $("#" + pinname + "_name").html(muxSelect);
                    //console.log(pinname + ": " + pinMode);
                }
            };

            //setup handler for receiving the strict with all the expansion pins from the server
            platform(completeMux);
        } catch(ex) {
            console.log("Unable to attach socket functions due to " + ex);
        }
    };

    completeMux(exports.bone);
    loadScript('/socket.io/socket.io.js', onSocketIOLoaded);

    $("#i2c1").hover(
        function () {
            printPin("P9_17");
            printPin("P9_18");
        },
        function () {
            clearPin("P9_17");
            clearPin("P9_18");
        }
    );

    $("#i2c2").hover(
        function () {
            printPin("P9_19");
            printPin("P9_20");
        },
        function () {
            clearPin("P9_19");
            clearPin("P9_20");
        }
    );

    $("#spi1").hover(
        function () {
            printPin("P9_28");
            printPin("P9_29");
            printPin("P9_30");
        },
        function () {
            clearPin("P9_28");
            clearPin("P9_29");
            clearPin("P9_30");
        }
    );
};

var loadScript = function(url, callback) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    script.charset = 'UTF-8';
    var scriptObj = head.appendChild(script);
    scriptObj.onload = callback;
}

// based loosely on http://stackoverflow.com/questions/950087/include-javascript-file-inside-javascript-file
var loadScripts = function() {
    var url = scriptUrls.shift();
    if(url) {
        loadScript(url, loadScripts);
    } else {
        initClient();
    }
};

var loadCss = function() {
    var url = cssUrls.shift();
    if(url) {
        var head = document.getElementsByTagName('head')[0];
        var link = document.createElement('link');
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.href = url;
        var linkObj = head.appendChild(link);
        loadCss();
    } else {
        loadScripts();
    }
};

loadCss();
<commit_msg>bone101: Attempted to fix misplaced of setMuxSelect definition<commit_after>var cssUrls = [
    'schmux.css',
    'jquery.terminal.css',         // http://terminal.jcubic.pl/js/jquery.terminal.css
    'jquery-ui.css',               // http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css
    'client.css'
];

var scriptUrls = [
    'jquery.js',
    'jquery.svg.js',
    'jquery.terminal.js',          // http://terminal.jcubic.pl/js/jquery.terminal-0.4.12.min.js
    'jquery.mousewheel.js',        // http://terminal.jcubic.pl/js/jquery.mousewheel-min.js
    'eeprom-web.js',
    'autoadvance.js',
    'processing.js',
    'jquery-ui.min.js',         // http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js
    'weatherstation.js',
    'bone.js',
    'ajaxorg-ace-builds-c2f3abb/ace.js' // https://github.com/ajaxorg/ace-builds/commit/c2f3abb2ecd3287f90225d804132f0fd26cfb639
];

var doAlert = function(m) {
    alert(JSON.stringify(m));
};

var demoRun = function(id) {
    var myScript = document.getElementById(id).innerHTML;
    myScript = myScript.replace("<", "<");
    myScript = myScript.replace(">", ">");
    myScript = myScript.replace("&", "&");
    eval(myScript);
};

var callbacks = {};
var seqnum = 0;
var seqcall = function(data) {
    if(data.seq && (typeof callbacks[data.seq] == 'function')) {
        callbacks[data.seq](data);
        if(data.oneshot) delete callbacks[data.seq];
    }
}

var printPin = function(pinname) {
    $("#" + pinname).css("background-color", "#000000");
}

var clearPin = function(pinname) {
    $("#" + pinname).css("background-color", "#EAF2D3");
}

var setMuxSelect = function(data) {
    var pinname = data.pin;
    if(data.options) {
        var muxSelect = "<select class='mux'>\n";
        for(var option in data.options) {
            if(isNaN(option)) continue;
            var pinFunction = data.options[option];
            var muxSelected = "";
            // Select the signal the pin is currently muxed to
            if(option == data.mux) {
                muxSelected = "selected=true";
            }
            muxSelect += "<option " + muxSelected + ">" + option + ": " + pinFunction + "</option>";
        }
        muxSelect += "</select>\n";
        $("#" + pinname + "_name").html(muxSelect);
        //console.log(pinname + ": " + pinMode);
    }
};

var completeMux = function(data, onMux) {
    var bone = data.platform;
    for(var pinname in bone) {
        $("#" + pinname + "_name").html(bone[pinname].name);
        if(bone[pinname].mux) {
            onMux(bone[pinname], setMuxSelect);
        }
    }
};

//var slidyDisable = function() {
//  document.removeEventListener('keydown', w3c_slidy.key_down);
//  document.removeEventListener('keypress', w3c_slidy.key_press);
//};
//
//var slidyEnable = function() {
//  w3c_slidy.add_listener(document, 'keydown', w3c_slidy.key_down);
//  w3c_slidy.add_listener(document, 'keypress', w3c_slidy.key_press);
//}

var initClient = function() {
    $("#slider1").slider();
    $("#slider2").slider();

    $("#buttons").append("
" +
      "<button class=\"dynlink\" onclick=\"demoRun('code')\">Run</button>" +
      "<button class=\"dynlink\" onclick=\"demoEdit('code')\">Editor</button>" +
      "<button class=\"dynlink\" onclick=\"openJSTerm('js_term')\">Interpreter</button>" +
      "
");

    demoEdit = function(id) {
        var editor = ace.edit(id);
        editor.setTheme("ace/theme/monokai");
        editor.getSession().setMode("ace/mode/javascript");
        var originalDemoRun = demoRun;
        demoRun = function(myid) {
            if(myid == id) eval(editor.getValue());
            else originalDemoRun(myid);
        }
    };

    try {
        var canvas = document.getElementById("canvas1");
        var graphDataSize = 50;
        window.graphData = new Array(graphDataSize);
        for(var i=0; i<graphDataSize; i++) {
            window.graphData[i] = 0;
        }
        var sketchProc = function(p) {
            p.size(600, 250);

            // variables referenced elsewhere
            window.height = p.height;

            // variables that might get updated
            window.rangeLow = 0;
            window.rangeHigh = 1;
            window.scaleY = window.height / (window.rangeHigh - window.rangeLow);

            // local variables
            var stepX = p.width / (graphDataSize - 1);
            var centerY = window.height / 2;

            p.noLoop();
            p.draw = function() {
                // erase background
                p.background(224);

                // draw axis
                p.stroke(25);
                p.strokeWeight(1);
                p.line(0, centerY, p.width, centerY);

                // draw graph
                p.stroke(0);
                p.strokeWeight(3);
                //p.line(0, centerY+1, p.width, centerY+1);
                var lastX = 0, nextX = 0, lastY, nextY;
                for(var point in window.graphData) {
                    nextY = ((window.rangeHigh - window.graphData[point]) * scaleY);
                    if(point != 0) {
                        p.line(lastX, lastY, nextX, nextY);
                        lastX += stepX;
                    }
                    nextX += stepX;
                    lastY = nextY;
                }
            };
        };
        var processing = new Processing(canvas, sketchProc);
        graphDraw = function(data) {
            var myData = parseFloat(data);
            for(var i=0; i<graphDataSize-1; i++) {
                window.graphData[i] = window.graphData[i+1];
            }
            window.graphData[i] = myData;
            if (myData > rangeHigh) {
                rangeHigh = myData;
                window.scaleY = window.height / (window.rangeHigh - window.rangeLow);
            }
            if (myData < rangeLow) {
                rangeLow = myData;
                window.scaleY = window.height / (window.rangeHigh - window.rangeLow);
            }
            processing.redraw();
        };
    } catch(ex) {
        console.log('Unable to attach Processing.JS to canvas because ' + ex);
    }

    var onSocketIOLoaded = function() {
        try {
            var socket = io.connect('');
            var myfuncs = {
                'digitalWrite': [ 'pin', 'value' ],
                'digitalRead': [ 'pin' ],
                'analogRead': [ 'pin' ],
                'analogWrite': [ 'pin', 'value', 'freq' ],
                'pinMode': [ 'pin', 'direction', 'mux', 'pullup', 'slew' ],
                'shiftOut': [ 'dataPin', 'clockPin', 'bitOrder', 'val' ],
                'attachInterrupt': [ 'pin', 'handler', 'mode' ],
                'detachInterrupt': [ 'pin' ],
                'getPinMode': [ 'pin' ],
                'getEeproms': [],
                'platform': [],
                'shell': [ 'command' ],
                'echo': [ 'data' ],
                'doEval': [ 'evalFunc' ],
                'addLoop': [ 'loopFunc', 'loopDelay' ],
                'getLoops': [],
                'removeLoop': [ 'loopid' ],
                'removeLoops': [],
                'readTextFile': [ 'filename' ],
                'writeTextFile': [ 'filename', 'data' ]
            };
            for(var x in myfuncs) {
                socket.on(x, function(data) {
                    seqcall(data);
                });
                var myargs = myfuncs[x];
                var objString = '';
                for(var y in myargs) {
                    if(isNaN(y)) continue;  // Need to find the source of this bug
                    objString += ' if(typeof ' + myargs[y] + ' == "function") {\n';
                    objString += '  ' + myargs[y] + ' = ' + myargs[y] + '.toString();\n';
                    objString += ' }\n';
                    objString += ' calldata.' + myargs[y] + ' = ' + myargs[y] + ';\n';
                }
                myargs.push('callback');
                var argsString = myargs.join(', ');
                var handyfunc = x + ' = ' +
                    'function (' + argsString + ') {\n' +
                    ' var calldata = {};\n' +
                    objString +
                    ' if(callback) {\n' +
                    '  seqnum++;\n' +
                    '  callbacks[seqnum] = callback;\n' +
                    '  calldata.seq = seqnum;\n' +
                    ' }\n' +
                    ' socket.emit("' + x + '", calldata);\n' +
                    '};\n';
                eval(handyfunc);
            }

            try {
                var addedShellListener = false;
                $('#shell').terminal(
                    function(command, term) {
                        if(!addedShellListener) {
                            socket.on('shell', function(s) {
                                term.echo(s);
                            });
                            addedShellListener = true;
                        }
                        shell(command);
                    },
                    {
                        greetings: "BeagleBone bash shell",
                        name: "bash",
                        height: 600,
                        prompt: 'bash>'
                    }
                );
            } catch(ex) {
                console.log("Unable to open shell terminal window due to " + ex);
            }
            var js_term = {};
            var dir = function(obj) {
                var y = [];
                for(var x in obj) {
                    if(obj.hasOwnProperty(x)) {
                        y.push(x);
                    }
                }
                return y.join(', ');
            }
            js_term.term = function(command, term) {
                if(command !== '') {
                    var result = eval(command);
                    if (result !== undefined) {
                        term.echo(String(result));
                    }
                }
            };
            js_term.args = {
                    greetings: 'Javascript Interpreter',
                    name: 'js_demo',
                    height: 300,
                    prompt: 'js>'
            };
            openJSTerm = function(id) {
                var myJSTerm = document.getElementById(id);
                if(myJSTerm.hasTerminal && myJSTerm.isEnabled) {
                    $(myJSTerm).terminal.disable();
                    myJSTerm.isEnabled = false;
                } else {
                    $(myJSTerm).terminal(js_term.term, js_term.args);
                    myJSTerm.isEnabled = true;
                }
                myJSTerm.hasTerminal = true;
            };

            //setup handler for receiving the strict with all the expansion pins from the server
            var completeMuxWrapper = function(data) {
                completeMux(data, getPinMode);
            };
            platform(completeMuxWrapper);

        } catch(ex) {
            console.log("Unable to attach socket functions due to " + ex);
        }
    };

    var getDefaultMode = function(pin, callback) {
        callback({pin:exports.bone[pin]});
    };
    completeMux(exports.bone, getDefaultMode);
    loadScript('/socket.io/socket.io.js', onSocketIOLoaded);

    $("#i2c1").hover(
        function () {
            printPin("P9_17");
            printPin("P9_18");
        },
        function () {
            clearPin("P9_17");
            clearPin("P9_18");
        }
    );

    $("#i2c2").hover(
        function () {
            printPin("P9_19");
            printPin("P9_20");
        },
        function () {
            clearPin("P9_19");
            clearPin("P9_20");
        }
    );

    $("#spi1").hover(
        function () {
            printPin("P9_28");
            printPin("P9_29");
            printPin("P9_30");
        },
        function () {
            clearPin("P9_28");
            clearPin("P9_29");
            clearPin("P9_30");
        }
    );
};

var loadScript = function(url, callback) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    script.charset = 'UTF-8';
    var scriptObj = head.appendChild(script);
    scriptObj.onload = callback;
}

// based loosely on http://stackoverflow.com/questions/950087/include-javascript-file-inside-javascript-file
var loadScripts = function() {
    var url = scriptUrls.shift();
    if(url) {
        loadScript(url, loadScripts);
    } else {
        initClient();
    }
};

var loadCss = function() {
    var url = cssUrls.shift();
    if(url) {
        var head = document.getElementsByTagName('head')[0];
        var link = document.createElement('link');
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.href = url;
        var linkObj = head.appendChild(link);
        loadCss();
    } else {
        loadScripts();
    }
};

loadCss();
<|endoftext|>


<commit_before>(function (enyo, scope) {
	/**
	* Fires when the current text changes.
	*
	* _event.value_ contains the value of the input.
	*
	* @event moon.ExpandableInput#event:onChange
	* @type {Object}
	* @property {Object} sender - The [component]{@link enyo.Component} that most recently
	*	propagated the [event]{@link external:event}.
	* @property {Object} event - An [object]{@link external:Object} containing
	*	[event]{@link external:event} information.
	* @public
	*/

	/**
	* _moon.ExpandableInput_, which extends
	* [moon.ExpandableListItem]{@link moon.ExpandableListItem}, is a drop-down input that
	* prompts the user to enter text.
	*
	* @ui
	* @class moon.ExpandableInput
	* @extends moon.ExpandableListItem
	* @public
	*/
	enyo.kind(
		/** @lends moon.ExpandableInput.prototype */ {

		/**
		* @private
		*/
		name: 'moon.ExpandableInput',

		/**
		* @private
		*/
		kind: 'moon.ExpandableListItem',

		/**
		* @private
		*/
		classes: 'moon-expandable-input',

		/**
		* @private
		*/
		events: {

			/** {@link moon.ExpandableInput#event:onChange} */
			onChange: ''
		},

		/**
		* @private
		*/
		published: /** @lends moon.ExpandableInput.prototype */ {

			/**
			* Text to be displayed in the _currentValue_ control if no item is currently selected
			*
			* @type {String}
			* @default ''
			* @public
			*/
			noneText: '',

			/**
			* Text to be displayed in the input if no text has been entered
			*
			* @type {String}
			* @default ''
			* @public
			*/
			placeholder: '',

			/**
			* Initial value of the input
			*
			* @type {String}
			* @default ''
			* @public
			*/
			value: ''
		},

		/**
		* @private
		*/
		autoCollapse: true,

		/**
		* @private
		*/
		lockBottom: false,

		/**
		* @private
		*/
		components: [
			{name: 'headerWrapper', kind: 'moon.Item', classes: 'moon-expandable-picker-header-wrapper', onSpotlightFocus: 'headerFocus', ondown: 'headerDown', ontap: 'expandContract', components: [
				// headerContainer required to avoid bad scrollWidth returned in RTL for certain text widths (webkit bug)
				{name: 'headerContainer', classes: 'moon-expandable-list-item-header moon-expandable-picker-header moon-expandable-input-header', components: [
					{name: 'header', kind: 'moon.MarqueeText'}
				]},
				{name: 'currentValue', kind: 'moon.MarqueeText', classes: 'moon-expandable-picker-current-value'}
			]},
			{name: 'drawer', kind: 'enyo.Drawer', resizeContainer:false, classes:'moon-expandable-list-item-client indented', components: [
				{name: 'inputDecorator', kind: 'moon.InputDecorator', onSpotlightBlur: 'inputBlur', onSpotlightFocus: 'inputFocus', onSpotlightDown: 'inputDown', components: [
					{name: 'clientInput', kind: 'moon.Input', onchange: 'doChange', onkeyup: 'inputKeyUp'}
				]}
			]}
		],

		/**
		* @private
		*/
		bindings: [
			{from: '.value', to: '.$.clientInput.value', oneWay: false},
			{from: '.placeholder', to: '.$.clientInput.placeholder'},
			{from: '.showCurrentValue', to: '.$.currentValue.showing'},
			{from: '.currentValueText', to: '.$.currentValue.content'},
			{from: '.disabled', to: '.$.headerWrapper.disabled'}
		],

		/**
		* @private
		*/
		computed: {
			'showCurrentValue': ['open', 'value', 'noneText'],
			'currentValueText': ['value', 'noneText']
		},

		/**
		* Computed prop
		*
		* @private
		*/
		showCurrentValue: function () {
			return !this.open && this.currentValueText() !== '';
		},

		/**
		* Computed prop
		*
		* @private
		*/
		currentValueText: function () {
			return (this.value === '') ? this.noneText : this.value;
		},

		/**
		* @private
		*/
		expandContract: function () {
			if (this.disabled) {
				return true;
			}
			if (this.getOpen()) {
				this.closeDrawerAndHighlightHeader();
			} else {
				this.toggleActive();
			}
		},

		/**
		* @private
		*/
		toggleActive: function () {
			if (this.getOpen()) {
				this.setActive(false);
				this.$.clientInput.blur();
			} else {
				this.setActive(true);
				enyo.Spotlight.unspot();
				enyo.Spotlight.freeze();
			}
		},

		/**
		* Focuses the {@link moon.Input} when the input decorator receives focus.
		*
		* @private
		*/
		inputFocus: function (inSender, inEvent) {
			var direction = inEvent && inEvent.dir;
			if (this.getOpen() && direction) {
				this.focusInput();
			}
		},

		/**
		* value should submit if user clicks outside control. We check for 'down' to make sure not to
		* contract on mousemove
		*
		* @private
		*/
		inputBlur: function (inSender, inEvent) {
			if (this.$.clientInput.hasFocus() && enyo.Spotlight.getPointerMode() && enyo.Spotlight.getLastEvent().type === 'down') {
				this.toggleActive();
			}
		},

		/**
		* @private
		*/
		inputKeyUp: function (inSender, inEvent) {
			if (inEvent.keyCode === 13) {
				this.closeDrawerAndHighlightHeader();
			}
		},

		/**
		* @private
		*/
		headerDown: function () {
			enyo.Spotlight.unfreeze();
		},

		/**
		* Focuses the input field if navigating down from the header while the drawer is open.
		*
		* @private
		*/
		spotlightDown: function (inSender, inEvent) {
			if (inEvent.originator === this.$.headerWrapper && this.getOpen()) {
				this.focusInput();
			}
		},

		/**
		* Focuses the input field.
		*
		* @private
		*/
		focusInput: function () {
			this.$.clientInput.focus();
			// Force cursor to end of text. We were sometimes seeing the
			// cursor positioned at the start of the text, which caused
			// problems in 5-way mode (where there's no way to move the
			// cursor).
			this.$.clientInput.hasNode().selectionStart = this.value.length;
		},

		/**
		* If {@link moon.ExpandableInput#lockBottom} is _true_, don't allow user to navigate down from
		* the input field. If {@link moon.ExpandableInput#lockBottom} is _false_, close drawer and
		* return true to keep spotlight on header.
		*
		* @private
		*/
		inputDown: function (inSender, inEvent) {
			if (this.getLockBottom()) {
				this.focusInput();
			} else {
				this.closeDrawerAndHighlightHeader();
			}
			return true;
		},

		/**
		* @private
		*/
		drawerAnimationEnd: function () {
			enyo.Spotlight.unfreeze();
			if (this.getOpen()) {
				this.focusInput();
			}
			this.inherited(arguments);
		},

		/**
		* We manually set pointer mode to false as it was seemingly the
		* least harmful method to re-highlight the header after the drawer
		* closes. The other options had side effects of resetting the
		* current spotted control to the root, or requiring a double-press to
		* subsequently 5-way move.
		*
		* @private
		*/
		closeDrawerAndHighlightHeader: function () {
			enyo.Spotlight.setPointerMode(false);
			enyo.Spotlight.unfreeze();
			enyo.Spotlight.spot(this.$.headerWrapper);
			this.toggleActive();
		}
	});

})(enyo, this);
<commit_msg>BHV-11123: modify ExpandableInput.js to be able to open only one ExpandableInput<commit_after>(function (enyo, scope) {
	/**
	* Fires when the current text changes.
	*
	* _event.value_ contains the value of the input.
	*
	* @event moon.ExpandableInput#event:onChange
	* @type {Object}
	* @property {Object} sender - The [component]{@link enyo.Component} that most recently
	*	propagated the [event]{@link external:event}.
	* @property {Object} event - An [object]{@link external:Object} containing
	*	[event]{@link external:event} information.
	* @public
	*/

	/**
	* _moon.ExpandableInput_, which extends
	* [moon.ExpandableListItem]{@link moon.ExpandableListItem}, is a drop-down input that
	* prompts the user to enter text.
	*
	* @ui
	* @class moon.ExpandableInput
	* @extends moon.ExpandableListItem
	* @public
	*/
	enyo.kind(
		/** @lends moon.ExpandableInput.prototype */ {

		/**
		* @private
		*/
		name: 'moon.ExpandableInput',

		/**
		* @private
		*/
		kind: 'moon.ExpandableListItem',

		/**
		* @private
		*/
		classes: 'moon-expandable-input',

		/**
		* @private
		*/
		events: {

			/** {@link moon.ExpandableInput#event:onChange} */
			onChange: ''
		},

		/**
		* @private
		*/
		published: /** @lends moon.ExpandableInput.prototype */ {

			/**
			* Text to be displayed in the _currentValue_ control if no item is currently selected
			*
			* @type {String}
			* @default ''
			* @public
			*/
			noneText: '',

			/**
			* Text to be displayed in the input if no text has been entered
			*
			* @type {String}
			* @default ''
			* @public
			*/
			placeholder: '',

			/**
			* Initial value of the input
			*
			* @type {String}
			* @default ''
			* @public
			*/
			value: ''
		},

		/**
		* @private
		*/
		autoCollapse: true,

		/**
		* @private
		*/
		lockBottom: false,

		/**
		* @private
		*/
		components: [
			{name: 'headerWrapper', kind: 'moon.Item', classes: 'moon-expandable-picker-header-wrapper', onSpotlightFocus: 'headerFocus', ondown: 'headerDown', ontap: 'expandContract', components: [
				// headerContainer required to avoid bad scrollWidth returned in RTL for certain text widths (webkit bug)
				{name: 'headerContainer', classes: 'moon-expandable-list-item-header moon-expandable-picker-header moon-expandable-input-header', components: [
					{name: 'header', kind: 'moon.MarqueeText'}
				]},
				{name: 'currentValue', kind: 'moon.MarqueeText', classes: 'moon-expandable-picker-current-value'}
			]},
			{name: 'drawer', kind: 'enyo.Drawer', resizeContainer:false, classes:'moon-expandable-list-item-client indented', components: [
				{name: 'inputDecorator', kind: 'moon.InputDecorator', onSpotlightBlur: 'inputBlur', onSpotlightFocus: 'inputFocus', onSpotlightDown: 'inputDown', components: [
					{name: 'clientInput', kind: 'moon.Input', onchange: 'doChange', onkeyup: 'inputKeyUp'}
				]}
			]}
		],

		/**
		* @private
		*/
		bindings: [
			{from: '.value', to: '.$.clientInput.value', oneWay: false},
			{from: '.placeholder', to: '.$.clientInput.placeholder'},
			{from: '.showCurrentValue', to: '.$.currentValue.showing'},
			{from: '.currentValueText', to: '.$.currentValue.content'},
			{from: '.disabled', to: '.$.headerWrapper.disabled'}
		],

		/**
		* @private
		*/
		computed: {
			'showCurrentValue': ['open', 'value', 'noneText'],
			'currentValueText': ['value', 'noneText']
		},

		/**
		* Computed prop
		*
		* @private
		*/
		showCurrentValue: function () {
			return !this.open && this.currentValueText() !== '';
		},

		/**
		* Computed prop
		*
		* @private
		*/
		currentValueText: function () {
			return (this.value === '') ? this.noneText : this.value;
		},

		/**
		* @private
		*/
		expandContract: function () {
			if (this.disabled) {
				return true;
			}
			if (this.getOpen()) {
				this.closeDrawerAndHighlightHeader();
			} else {
				this.toggleActive();
			}
		},

		/**
		* @private
		*/
		toggleActive: function () {
			if (this.getOpen()) {
				this.setActive(false);
				this.$.clientInput.blur();
			} else {
				this.setActive(true);
				enyo.Spotlight.unspot();
				enyo.Spotlight.freeze();
			}
		},

		/**
		* Focuses the {@link moon.Input} when the input decorator receives focus.
		*
		* @private
		*/
		inputFocus: function (inSender, inEvent) {
			var direction = inEvent && inEvent.dir;
			if (this.getOpen() && direction) {
				this.focusInput();
			}
		},

		/**
		* value should submit if user clicks outside control. We check for 'down' to make sure not to
		* contract on mousemove
		*
		* @private
		*/
		inputBlur: function (inSender, inEvent) {
			var eventType = enyo.Spotlight.getLastEvent().type;
			if (enyo.Spotlight.getPointerMode() && eventType !== 'onSpotlightFocus' && eventType !== 'mouseover') {
				this.toggleActive();
			}
		},

		/**
		* @private
		*/
		inputKeyUp: function (inSender, inEvent) {
			if (inEvent.keyCode === 13) {
				this.closeDrawerAndHighlightHeader();
			}
		},

		/**
		* @private
		*/
		headerDown: function () {
			enyo.Spotlight.unfreeze();
		},

		/**
		* Focuses the input field if navigating down from the header while the drawer is open.
		*
		* @private
		*/
		spotlightDown: function (inSender, inEvent) {
			if (inEvent.originator === this.$.headerWrapper && this.getOpen()) {
				this.focusInput();
			}
		},

		/**
		* Focuses the input field.
		*
		* @private
		*/
		focusInput: function () {
			this.$.clientInput.focus();
			// Force cursor to end of text. We were sometimes seeing the
			// cursor positioned at the start of the text, which caused
			// problems in 5-way mode (where there's no way to move the
			// cursor).
			this.$.clientInput.hasNode().selectionStart = this.value.length;
		},

		/**
		* If {@link moon.ExpandableInput#lockBottom} is _true_, don't allow user to navigate down from
		* the input field. If {@link moon.ExpandableInput#lockBottom} is _false_, close drawer and
		* return true to keep spotlight on header.
		*
		* @private
		*/
		inputDown: function (inSender, inEvent) {
			if (this.getLockBottom()) {
				this.focusInput();
			} else {
				this.closeDrawerAndHighlightHeader();
			}
			return true;
		},

		/**
		* @private
		*/
		drawerAnimationEnd: function () {
			if (this.getOpen()) {
				enyo.Spotlight.unfreeze();
				this.focusInput();
			}
			this.inherited(arguments);
		},

		/**
		* We manually set pointer mode to false as it was seemingly the
		* least harmful method to re-highlight the header after the drawer
		* closes. The other options had side effects of resetting the
		* current spotted control to the root, or requiring a double-press to
		* subsequently 5-way move.
		*
		* @private
		*/
		closeDrawerAndHighlightHeader: function () {
			var mode = enyo.Spotlight.getPointerMode();
			enyo.Spotlight.setPointerMode(false);
			enyo.Spotlight.unfreeze();
			enyo.Spotlight.spot(this.$.headerWrapper);
			enyo.Spotlight.setPointerMode(mode);
			this.toggleActive();
		}
	});

})(enyo, this);
<|endoftext|>


<commit_before>var data = require('../data.json');
var currentEvent;
exports.view = function(req, res){
	if (typeof req.query.name != 'undefined'){
		var serverUrl = 'https://api.parse.com/1/files/' + req.query.image;
		console.log("submitting new idea");
		console.log("image:");
		console.log(req.query.image);
		var imageURL = "images/cropped-gift-box.png";
		if(req.query.image != ''){
			imageURL = req.query.image;
		}
		var newIdea = {
					"eventid": currentEvent,
					"name": req.query.name,
					"price": req.query.price,
					"description": req.query.description,
					"image": imageURL,
					"bought": "false",
					"vote": "0",
					"voteDir": ""
		};
		console.log(newIdea);
		var code = currentEvent;
		var e = data[code];
		console.log(e);
		console.log(e.idea);
		e.idea.push(newIdea);
		res.render('eventpage', e);
	}
	else if(typeof req.query.newevent != 'undefined'){
		console.log("creating new event");
		var id = req.query.newevent.split('+')[0];
		var title = req.query.newevent.split('+')[1];
		var date = req.query.newevent.split('+')[2];
		var description = req.query.newevent.split('+')[3];
		var newevent = {
			"id": id,
			"title": title,
			"date": date,
			"description": description,
			"idea" : []
		}
		currentEvent = id;
		data[id] = newevent;
		res.render('eventpage', data[id]);
	}
	else if (typeof req.query.upvote != 'undefined'){
		var params = req.query.upvote.split('+');
		var eventCode = params[0];
		if (params.length > 1){
			var ideaVoted = params[1];
			console.log("ideaVoted");
			console.log(ideaVoted);
			var voteTally = parseInt(params[2]);
			var e = data[eventCode];
			var idealist = e.idea;
			for (i in idealist){
				var idea = idealist[i];
				if (idea.name == ideaVoted){
					idea.vote = voteTally+1;
					idea.voteDir="up";
				}
			}
			idealist = sort(idealist);
			console.log(idealist);
			data[eventCode].idea = idealist;
		}
		res.render('eventpage', data[eventCode]);
	}
	else if (typeof req.query.downvote != 'undefined'){
		var params = req.query.downvote.split('+');
		var eventCode = params[0];
		if (params.length > 1){
			var ideaVoted = params[1];
			var voteTally = parseInt(params[2]);
			var e = data[eventCode];
			var idealist = e.idea;
			for (i in idealist){
				var idea = idealist[i];
				if (idea.name == ideaVoted){
					idea.vote = voteTally-1;
					idea.voteDir="down";
				}
			}
			idealist = sort(idealist);
			data[eventCode].idea = idealist;
		}
		res.render('eventpage', data[eventCode]);
	}
	else if(req.query.eventcode.length > 0){
		var params = req.query.eventcode.split('+');
		console.log(params);
		var code = params[0];
		console.log(params);
		if (params.length > 1){
			var ideaBought = params[1];
			var e = data[code];
			var idealist = e.idea;
			for (i in idealist){
				var idea = idealist[i];
				if (idea.name == ideaBought){
					console.log("idea bought!");
					console.log(idea.name);
					idea.bought = "true";
				}
			}
		}
		console.log(data);
		console.log(code);
		console.log(data[code]);
		currentEvent = code;
		idealist = sort(idealist);
		data[eventCode].idea = idealist;
		res.render('eventpage', data[code]);
	}
}

function sort(array) {
    return array.sort(function(a, b) {
    	console.log(a["vote"]);
        var x = a["vote"]; var y = b["vote"];
        return ((x > y) ? -1 : ((x < y) ? 1 : 0));
    });
}<commit_msg>ordred<commit_after>var data = require('../data.json');
var currentEvent;
exports.view = function(req, res){
	if (typeof req.query.name != 'undefined'){
		var serverUrl = 'https://api.parse.com/1/files/' + req.query.image;
		console.log("submitting new idea");
		console.log("image:");
		console.log(req.query.image);
		var imageURL = "images/cropped-gift-box.png";
		if(req.query.image != ''){
			imageURL = req.query.image;
		}
		var newIdea = {
					"eventid": currentEvent,
					"name": req.query.name,
					"price": req.query.price,
					"description": req.query.description,
					"image": imageURL,
					"bought": "false",
					"vote": "0",
					"voteDir": ""
		};
		console.log(newIdea);
		var code = currentEvent;
		var e = data[code];
		console.log(e);
		console.log(e.idea);
		e.idea.push(newIdea);
		res.render('eventpage', e);
	}
	else if(typeof req.query.newevent != 'undefined'){
		console.log("creating new event");
		var id = req.query.newevent.split('+')[0];
		var title = req.query.newevent.split('+')[1];
		var date = req.query.newevent.split('+')[2];
		var description = req.query.newevent.split('+')[3];
		var newevent = {
			"id": id,
			"title": title,
			"date": date,
			"description": description,
			"idea" : []
		}
		currentEvent = id;
		data[id] = newevent;
		res.render('eventpage', data[id]);
	}
	else if (typeof req.query.upvote != 'undefined'){
		var params = req.query.upvote.split('+');
		var eventCode = params[0];
		if (params.length > 1){
			var ideaVoted = params[1];
			console.log("ideaVoted");
			console.log(ideaVoted);
			var voteTally = parseInt(params[2]);
			var e = data[eventCode];
			var idealist = e.idea;
			for (i in idealist){
				var idea = idealist[i];
				if (idea.name == ideaVoted){
					idea.vote = voteTally+1;
					idea.voteDir="up";
				}
			}
			idealist = sort(idealist);
			console.log(idealist);
			data[eventCode].idea = idealist;
		}
		res.render('eventpage', data[eventCode]);
	}
	else if (typeof req.query.downvote != 'undefined'){
		var params = req.query.downvote.split('+');
		var eventCode = params[0];
		if (params.length > 1){
			var ideaVoted = params[1];
			var voteTally = parseInt(params[2]);
			var e = data[eventCode];
			var idealist = e.idea;
			for (i in idealist){
				var idea = idealist[i];
				if (idea.name == ideaVoted){
					idea.vote = voteTally-1;
					idea.voteDir="down";
				}
			}
			idealist = sort(idealist);
			data[eventCode].idea = idealist;
		}
		res.render('eventpage', data[eventCode]);
	}
	else if(req.query.eventcode.length > 0){
		var params = req.query.eventcode.split('+');
		console.log(params);
		var code = params[0];
		console.log(params);
		if (params.length > 1){
			var ideaBought = params[1];
			var e = data[code];
			var idealist = e.idea;
			for (i in idealist){
				var idea = idealist[i];
				if (idea.name == ideaBought){
					console.log("idea bought!");
					console.log(idea.name);
					idea.bought = "true";
				}
			}
		}
		console.log(data);
		console.log(code);
		console.log(data[code]);
		currentEvent = code;
		var e = data[eventCode];
		var idealist = e.idea;
		idealist = sort(idealist);
		data[eventCode].idea = idealist;
		res.render('eventpage', data[code]);
	}
}

function sort(array) {
    return array.sort(function(a, b) {
    	console.log(a["vote"]);
        var x = a["vote"]; var y = b["vote"];
        return ((x > y) ? -1 : ((x < y) ? 1 : 0));
    });
}<|endoftext|>


<commit_before>/** @jsx m */

"use strict";
require("./Dropdown.scss");

var _ = require("underscore");
var m = require("mithril");
var cx = require("../utils/ClassSet.js");

var ScrollIntoView = require("../utils/ScrollIntoView.js");

var Dropdown = {};

Dropdown.instances = {};

Dropdown.controller = function(options) {
  options = options || {};

  this.open = m.prop(false);
  this.className = options.className || "";
  this.label = options.label;
  this.caret = _.isUndefined(options.caret) ? true : options.caret;

  var _this = this;
  this.toggle = function(e) {
    _this.open(!_this.open());
  };

  this.close = function() {
    _this.open(false);
  };

  this.id = _.uniqueId();
  Dropdown.instances[this.id] = this;
  this.onunload = function() {
    delete Dropdown.instances[_this.id];
  };

  this.contentConfig = function(el, isInitialized) {
    _this.contentEl = el;
    if (!isInitialized) {
      ScrollIntoView(el);
    }
  };

  this.buttonConfig = function(el, isInitialized) {
    _this.buttonEl = el;
  };
};

Dropdown.view = function(ctrl, content, label) {
  if (ctrl.open()) {
    var dropdownContent =
{content}
;
  }

  if (ctrl.caret) {
    var caret = ;
  }

  return (

      <button type="button" className="btn btn_subtle" onmousedown={ctrl.toggle} config={ctrl.buttonConfig}>
        {label || ctrl.label} {caret}
      </button>
      {dropdownContent}

  );
};

document.addEventListener("mousedown", closeDropdownsOnMousedown);
document.addEventListener("touchstart", closeDropdownsOnMousedown);

module.exports = Dropdown;

// helpers

function closeDropdownsOnMousedown(e) {
  _.each(Dropdown.instances, function(dropdown) {
    if (dropdown.open() && dropdown.buttonEl && dropdown.contentEl && !dropdown.buttonEl.contains(e.target) && !dropdown.contentEl.contains(e.target)) {
      dropdown.close();
    }
  });
  m.redraw();
}
<commit_msg>Dropdown: add touch support<commit_after>/** @jsx m */

"use strict";
require("./Dropdown.scss");

var _ = require("underscore");
var m = require("mithril");
var cx = require("../utils/ClassSet.js");

var ScrollIntoView = require("../utils/ScrollIntoView.js");

var Dropdown = {};

Dropdown.instances = {};

Dropdown.controller = function(options) {
  options = options || {};

  this.open = m.prop(false);
  this.className = options.className || "";
  this.label = options.label;
  this.caret = _.isUndefined(options.caret) ? true : options.caret;

  var _this = this;
  this.toggle = function(e) {
    _this.open(!_this.open());
  };

  this.close = function() {
    _this.open(false);
  };

  this.id = _.uniqueId();
  Dropdown.instances[this.id] = this;
  this.onunload = function() {
    delete Dropdown.instances[_this.id];
  };

  this.contentConfig = function(el, isInitialized) {
    _this.contentEl = el;
    if (!isInitialized) {
      ScrollIntoView(el);
    }
  };

  this.buttonConfig = function(el, isInitialized) {
    _this.buttonEl = el;
  };
};

Dropdown.view = function(ctrl, content, label) {
  if (ctrl.open()) {
    var dropdownContent =
{content}
;
  }

  if (ctrl.caret) {
    var caret = ;
  }

  return (

      <button type="button" className="btn btn_subtle" onmousedown={ctrl.toggle} ontouchstart={ctrl.toggle} config={ctrl.buttonConfig}>
        {label || ctrl.label} {caret}
      </button>
      {dropdownContent}

  );
};

document.addEventListener("mousedown", closeDropdownsOnMousedown);
document.addEventListener("touchstart", closeDropdownsOnMousedown);

module.exports = Dropdown;

// helpers

function closeDropdownsOnMousedown(e) {
  _.each(Dropdown.instances, function(dropdown) {
    if (dropdown.open() && dropdown.buttonEl && dropdown.contentEl && !dropdown.buttonEl.contains(e.target) && !dropdown.contentEl.contains(e.target)) {
      dropdown.close();
    }
  });
  m.redraw();
}
<|endoftext|>