<commit_before>/*
 * Author:
 *         Zhizhou Li <lzz@meteroi.com>
 *
 Copyright 2016 Meteroi
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
// call the packages we need
var pjson = require('./package.json');
var config = require('./config.json');
var path = require('path');
var events = require('events');
var log4js = require('log4js');
var http = require('http');
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var loadDir = require('./loaddir');
var module = loadDir(config.app_path);
var multer = require('multer');
var sockectio = require('socket.io');
var diffsync  = require('diffsync');
var tingodb = require('tingodb')();
var optimist = require('optimist');
var figlet = require('figlet');
var node_uuid = require('node-uuid');
var cron = require('cron').CronJob;
var List = require("collections/list");
var Set = require("collections/set");
var Map = require("collections/map");
require('tingyun');

var app = express(); // start express
var router = express.Router(); // start routee for express
var db = new tingodb.Db(config.db_path, {}); // embeded json database
var argv = optimist.argv; // argument object
var event = new events.EventEmitter(); //event
var uuid = node_uuid.v4();

log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file(config.log_path), 'server');
var logger = log4js.getLogger('server'); // start logging
logger.setLevel('INFO'); // Set the log level
if (argv.debug) logger.setLevel('DENUG'); // Set the log level

figlet('Openfpgaduino', function(err, data) {
    if (err) {
        return;
    }
    logger.info("\n" + data);
});

logger.info(pjson.name + " Version:" + pjson.version);
logger.info(pjson.description);
logger.info("Runing at Node Version:" + process.version);
logger.info("Write by:" + pjson.author);
logger.info("UUID", uuid);

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(bodyParser.text());
app.use(bodyParser.raw());
// configure app to use /page to store static files
app.use(express.static(__dirname + '/page'));
// configure app to use /uploads to store upload files
app.use(multer({
    dest: './uploads/'
}));

function parser_parameter(fun_str) {
    return fun_str.toString()
        .replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s))/mg, '') // remove spaces and comments
        .match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1] // get parameter
}

var port = argv.port || process.env.PORT || config.port; // set our port
var server = http.createServer(app);
var io = sockectio.listen(server);
var dataAdapter = new diffsync.InMemoryDataAdapter();
var diffSyncServer = new diffsync.Server(dataAdapter, io);

function loadmodule(module) {
    for (m in module) { // load all modules in apps

        var parameter = parser_parameter(module[m]);
        logger.debug('parameter is ' + parameter);
        eval('module[m]' + '(' + parameter + ')'); // dependency injection, inject the var the apps needs in it parameter
    }
}
if (argv.sim) {
    var mock = loadDir(config.mock_path);
    loadmodule(mock);
    var map = new Map(module).filter(function (value,index) {
        for (v in mock) {
            if(index == v) {
                logger.info("Replace real module "+v+" with mockup");
                return false;
            }
        }
        return true;
    });
    module = map.toArray();
    loadmodule(module);
} else {
    loadmodule(module);
}

function dynamicloadmodule(filename) {
    var name = path.basename(filename, '.js');
    var apppath = __dirname + '/' + config.app_path + filename;

    var script = "require(\'" + apppath + "\');"
    logger.debug("Dynamic load module");
    logger.debug(script);
    var ret = eval(script);
    var parameter = parser_parameter(ret)
    logger.debug('parameter is ' + parameter);
    script = "ret(" + parameter + ");";
    eval(script);
}

event.addListener('load', dynamicloadmodule);

server.listen(port);
logger.info("Restful API server run on port", port)<commit_msg>Debug info bug<commit_after>/*
 * Author:
 *         Zhizhou Li <lzz@meteroi.com>
 *
 Copyright 2016 Meteroi
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
// call the packages we need
var pjson = require('./package.json');
var config = require('./config.json');
var path = require('path');
var events = require('events');
var log4js = require('log4js');
var http = require('http');
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var loadDir = require('./loaddir');
var module = loadDir(config.app_path);
var multer = require('multer');
var sockectio = require('socket.io');
var diffsync  = require('diffsync');
var tingodb = require('tingodb')();
var optimist = require('optimist');
var figlet = require('figlet');
var node_uuid = require('node-uuid');
var cron = require('cron').CronJob;
var List = require("collections/list");
var Set = require("collections/set");
var Map = require("collections/map");
require('tingyun');

var app = express(); // start express
var router = express.Router(); // start routee for express
var db = new tingodb.Db(config.db_path, {}); // embeded json database
var argv = optimist.argv; // argument object
var event = new events.EventEmitter(); //event
var uuid = node_uuid.v4();

log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file(config.log_path), 'server');
var logger = log4js.getLogger('server'); // start logging
logger.setLevel('INFO'); // Set the log level
if (argv.debug) {
    logger.info("Set Log to Debug")
    logger.setLevel('DEBUG'); // Set the log level
}

figlet('Openfpgaduino', function(err, data) {
    if (err) {
        return;
    }
    logger.info("\n" + data);
});

logger.info(pjson.name + " Version:" + pjson.version);
logger.info(pjson.description);
logger.info("Runing at Node Version:" + process.version);
logger.info("Write by:" + pjson.author);
logger.info("UUID", uuid);

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(bodyParser.text());
app.use(bodyParser.raw());
// configure app to use /page to store static files
app.use(express.static(__dirname + '/page'));
// configure app to use /uploads to store upload files
app.use(multer({
    dest: './uploads/'
}));

function parser_parameter(fun_str) {
    return fun_str.toString()
        .replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s))/mg, '') // remove spaces and comments
        .match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1] // get parameter
}

var port = argv.port || process.env.PORT || config.port; // set our port
var server = http.createServer(app);
var io = sockectio.listen(server);
var dataAdapter = new diffsync.InMemoryDataAdapter();
var diffSyncServer = new diffsync.Server(dataAdapter, io);

function loadmodule(module) {
    for (m in module) { // load all modules in apps

        var parameter = parser_parameter(module[m]);
        logger.debug('parameter is ' + parameter);
        eval('module[m]' + '(' + parameter + ')'); // dependency injection, inject the var the apps needs in it parameter
    }
}
if (argv.sim) {
    var mock = loadDir(config.mock_path);
    loadmodule(mock);
    var map = new Map(module).filter(function (value,index) {
        for (v in mock) {
            if(index == v) {
                logger.info("Replace real module "+v+" with mockup");
                return false;
            }
        }
        return true;
    });
    module = map.toArray();
    loadmodule(module);
} else {
    loadmodule(module);
}

function dynamicloadmodule(filename) {
    var name = path.basename(filename, '.js');
    var apppath = __dirname + '/' + config.app_path + filename;

    var script = "require(\'" + apppath + "\');"
    logger.debug("Dynamic load module");
    logger.debug(script);
    var ret = eval(script);
    var parameter = parser_parameter(ret)
    logger.debug('parameter is ' + parameter);
    script = "ret(" + parameter + ");";
    eval(script);
}

event.addListener('load', dynamicloadmodule);

server.listen(port);
logger.info("Restful API server run on port", port)<|endoftext|>


<commit_before>/**
 * Ejemplo de servicio basado en Node.js para crear contenido dinámico para un bot.
 *
 */

// Puerto en el que escucha el servidor Node.js (lo obtiene de una variable de entorno y si no existe, el 3000)
const PORT = process.env.PORT || 3000;

// Importamos el framework Express y lo inicializamos
var express = require("express");
var app = express();

// El contenido de la carpeta public se muestra en la raíz del servidor
app.use(express.static(__dirname + "/public"));

/*
 GET /plazo/:fecha

 Ruta que calcula el número de días que faltan para una fecha

 Si el servidor se está ejecutando localmente:

 http://localhost:3000/plazo/2017-01-31T23:59:59.000Z

 Devuelve un objeto JSON con el formato:

 [{"text":"Faltan 59 días..."}]
 */
app.get("/plazo/:fecha", function (req, res) {

    // Obtener la fecha que llega en la URL
    var fecha_entrega = new Date(req.params.fecha);
    var ahora = new Date();

    // Algo no ha ido bien
    if (!fecha_entrega) {
        return res.status(400).send();
    }

    // http://stackoverflow.com/questions/2627473/how-to-calculate-the-number-of-days-between-two-dates-using-javascript
    var oneDay = 24 * 60 * 60 * 1000;
    var dias = Math.round(Math.abs((ahora.getTime() - fecha_entrega.getTime()) / (oneDay)));

    // Crear el objeto con la respuesta
    var respuesta = [
        {
            text: "Faltan " + dias + " días...",
        }
    ];

    // Devolver el objeto en formato JSON
    res.json(respuesta);
});

var request = require('request');

app.get("/temp", function (req, res) {

    var temperatura = 0;

    request('http://api.openweathermap.org/data/2.5/weather?lat=42.877976842874084&lon=-2.675943374633789&appid=5ce44fc1946c2700d5e6c648ccf1d3d7',
        function (error, response, data) {
            if (!error) {
                var response = JSON.parse(data);
                temperatura = response.main.temp;
                console.log(response.main);
                var celsius=5/9(temperatura-32);
            } else {
                celsius = 15; //temperatura por defecto
            }
            if (celsius < 10) {
                var respuesta = [
                {
                    text: "Nos encontramos a " + celsius + " grados de temperatura, hace un frio que pela",
                }
            ];
            }else if (celsius >10 && celsius < 20){

                var respuesta = [
                {
                    text: "Nos encontramos a " + celsius + " grados de temperatura, abrigate para no pasar frio ",
                }
            ];
            }else {
                var respuesta = [
                {
                    text: "Nos encontramos a " + celsius + " grados de temperatura, tomate una birrita que hace buena temperatura",
                }
            ];

            }

            // Devolver el objeto en formato JSON
            res.json(respuesta);

        });

});

// Arrancar el servidor y dejarlo a la espera
app.listen(PORT, function () {
    console.log("Servidor Express escuchando en el puerto " + PORT + "...");
});
<commit_msg>cambio<commit_after>/**
 * Ejemplo de servicio basado en Node.js para crear contenido dinámico para un bot.
 *
 */

// Puerto en el que escucha el servidor Node.js (lo obtiene de una variable de entorno y si no existe, el 3000)
const PORT = process.env.PORT || 3000;

// Importamos el framework Express y lo inicializamos
var express = require("express");
var app = express();

// El contenido de la carpeta public se muestra en la raíz del servidor
app.use(express.static(__dirname + "/public"));

/*
 GET /plazo/:fecha

 Ruta que calcula el número de días que faltan para una fecha

 Si el servidor se está ejecutando localmente:

 http://localhost:3000/plazo/2017-01-31T23:59:59.000Z

 Devuelve un objeto JSON con el formato:

 [{"text":"Faltan 59 días..."}]
 */
app.get("/plazo/:fecha", function (req, res) {

    // Obtener la fecha que llega en la URL
    var fecha_entrega = new Date(req.params.fecha);
    var ahora = new Date();

    // Algo no ha ido bien
    if (!fecha_entrega) {
        return res.status(400).send();
    }

    // http://stackoverflow.com/questions/2627473/how-to-calculate-the-number-of-days-between-two-dates-using-javascript
    var oneDay = 24 * 60 * 60 * 1000;
    var dias = Math.round(Math.abs((ahora.getTime() - fecha_entrega.getTime()) / (oneDay)));

    // Crear el objeto con la respuesta
    var respuesta = [
        {
            text: "Faltan " + dias + " días...",
        }
    ];

    // Devolver el objeto en formato JSON
    res.json(respuesta);
});

var request = require('request');

app.get("/temp", function (req, res) {

    var temperatura = 0;

    request('http://api.openweathermap.org/data/2.5/weather?lat=42.877976842874084&lon=-2.675943374633789&appid=5ce44fc1946c2700d5e6c648ccf1d3d7',
        function (error, response, data) {
            if (!error) {
                var response = JSON.parse(data);
                temperatura = response.main.temp;
                console.log(response.main);
                var celsius=temperatura-32)/1,8;
            } else {
                celsius = 15; //temperatura por defecto
            }
            if (celsius < 10) {
                var respuesta = [
                {
                    text: "Nos encontramos a " + celsius + " grados de temperatura, hace un frio que pela",
                }
            ];
            }else if (celsius >10 && celsius < 20){

                var respuesta = [
                {
                    text: "Nos encontramos a " + celsius + " grados de temperatura, abrigate para no pasar frio ",
                }
            ];
            }else {
                var respuesta = [
                {
                    text: "Nos encontramos a " + celsius + " grados de temperatura, tomate una birrita que hace buena temperatura",
                }
            ];

            }

            // Devolver el objeto en formato JSON
            res.json(respuesta);

        });

});

// Arrancar el servidor y dejarlo a la espera
app.listen(PORT, function () {
    console.log("Servidor Express escuchando en el puerto " + PORT + "...");
});
<|endoftext|>


<commit_before>// Global prototypes & extensions
String.prototype.lines = function() { return this.split(/\r|\r\n|\n/); }
String.prototype.lineCount = function() { return this.lines().length; }
jQuery.extend(jQuery.expr[':'], {
  focus: "a == document.activeElement"
});

function getRhymes(word) {
  var rhymeURL = "http://rhymebrain.com/talk?function=getRhymes&maxResults=45&word=";

  $.ajax({
    type: 'GET',
    dataType: 'jsonp',
    jsonp: 'jsonp',
    url: (rhymeURL + word),
    success: function(response){
      var rhymes = '';
      var j = response.length;
      for (var i = 0;  i < j && i < 12; i++) {
        if(response[i].score > 260){
          rhymes+=''+response[i].word+'';
        }
      }
      console.log("rhyme: " + rhymes);
    }
  });

}

function getLineCount() {
  var numlines = 0;
  var text = $('.poetry-text').val().split('\n');

  $.each(text, function(){
    alert(getSyllableCount(this));
  });

}

function getSyllableCount(word) {
  if (word.length === 0)
    return 0;

  var syllableCount = 0,
  prefixSuffixCount = 0,
  wordPartCount = 0;

  // Prepare word - make lower case and remove non-word characters
  word = word.toLowerCase().replace(/[^a-z]/g,"");

  // Specific common exceptions that don't follow the rule set below are handled individually
  // Array of problem words (with word as key, syllable count as value)
  var problemWords = {
    "simile":   3,
    "forever":    3,
    "shoreline":  2
  };

  // Return if we've hit one of those...
  if (problemWords[word]) {
    return problemWords[word];
  }

  // These syllables would be counted as two but should be one
  var subSyllables = [
    /cial/,
    /tia/,
    /cius/,
    /cious/,
    /giu/,
    /ion/,
    /iou/,
    /sia$/,
    /[^aeiuoyt]{2,}ed$/,
    /.ely$/,
    /[cg]h?e[rsd]?$/,
    /rved?$/,
    /[aeiouy][dt]es?$/,
    /[aeiouy][^aeiouydt]e[rsd]?$/,
    /^[dr]e[aeiou][^aeiou]+$/, // Sorts out deal, deign etc
    /[aeiouy]rse$/ // Purse, hearse
  ];

  // These syllables would be counted as one but should be two
  var addSyllables = [
    /ia/,
    /riet/,
    /dien/,
    /iu/,
    /io/,
    /ii/,
    /[aeiouym]bl$/,
    /[aeiou]{3}/,
    /^mc/,
    /ism$/,
    /([^aeiouy])\1l$/,
    /[^l]lien/,
    /^coa[dglx]./,
    /[^gq]ua[^auieo]/,
    /dnt$/,
    /uity$/,
    /ie(r|st)$/
  ];

  // Single syllable prefixes and suffixes
  var prefixSuffix = [
    /^un/,
    /^fore/,
    /ly$/,
    /less$/,
    /ful$/,
    /ers?$/,
    /ings?$/
  ];

  // Remove prefixes and suffixes and count how many were taken
  prefixSuffix.forEach(function(regex) {
    if (word.match(regex)) {
      word = word.replace(regex,"");
      prefixSuffixCount ++;
    }
  });

  wordPartCount = word
    .split(/[^aeiouy]+/ig)
    .filter(function(wordPart) {
      return !!wordPart.replace(/\s+/ig,"").length;
    })
    .length;

  // Get preliminary syllable count...
  syllableCount = wordPartCount + prefixSuffixCount;

  // Some syllables do not follow normal rules - check for them
  subSyllables.forEach(function(syllable) {
    if (word.match(syllable)) {
      syllableCount --;
    }
  });

  addSyllables.forEach(function(syllable) {
    if (word.match(syllable)) {
      syllableCount ++;
    }
  });

  return syllableCount || 1;
}

// Given a cursor position & the string value of the input text area,
// return the line number on which the cursor in the text area resides.
function get_line(pos, text)
{
  var lines = text.lines();
  var count = 0;
  var i = 0;
  while (i < pos) {
    i+=lines[count].length+1;
    if (i > pos)
      break;
    count++;
  }
  return count;
}

// Given a line number, the number of syllables, and the string value of the
// syllable count div, return the updated text for the syllable count div.
// *This should be replaced by whatever is needed by the line counts..

$(window).keyup(function(event)
{
  if (!jQuery("textarea.poetry-text").is(":focus")) {
    return;
  }
  var text = jQuery("textarea.poetry-text").val();
  var syllable_area = "";
  var lines = text.lines();
  var iter;
  for (iter = 0; iter < lines.length; iter++) {
    var words = lines[iter].split(" ");
    var word_iter;
    var syllable_count = 0;
    for (word_iter = 0; word_iter < words.length; word_iter++)
      syllable_count+=getSyllableCount(words[word_iter]);
    syllable_area += syllable_count+"
";
  }
  $('div.syllable_counts').html(syllable_area);
  // var caret = jQuery("textarea.poetry-text")[0].selectionStart;
  // var line = get_line(caret, text);
  //if ($('#syllable_count span').length <= line)
  //$('#syllable_count span')[line].innerText = getSyllableCount(text)
});

<commit_msg>getRhymes now takes a callback<commit_after>// Global prototypes & extensions
String.prototype.lines = function() { return this.split(/\r|\r\n|\n/); };
String.prototype.lineCount = function() { return this.lines().length; };
jQuery.extend(jQuery.expr[':'], {
  focus: "a == document.activeElement"
});

function getRhymes(word, callback) {
  var rhymeURL = "http://rhymebrain.com/talk?function=getRhymes&maxResults=50&word=";

  $.ajax({
    type: 'GET',
    dataType: 'jsonp',
    jsonp: 'jsonp',
    url: (rhymeURL + word),
    success: function(response){
      var rhymes = [];
      var j = response.length;
      for (var i = 0;  i < j; i++) {
        if(response[i].score > 268){
          rhymes.push(response[i]);
        }
      }
      callback = callback || function(rhymewords){console.log(rhymewords);};
      callback(rhymes);
    }
  });
}
getRhymes("hello");

function getLineCount() {
  var numlines = 0;
  var text = $('.poetry-text').val().split('\n');

  $.each(text, function(){
    alert(getSyllableCount(this));
  });

}

function getSyllableCount(word) {
  if (word.length === 0){
    return 0;
  }

  var syllableCount = 0,
  prefixSuffixCount = 0,
  wordPartCount = 0;

  // Prepare word - make lower case and remove non-word characters
  word = word.toLowerCase().replace(/[^a-z]/g,"");

  // Specific common exceptions that don't follow the rule set below are handled individually
  // Array of problem words (with word as key, syllable count as value)
  var problemWords = {
    "simile":   3,
    "forever":    3,
    "shoreline":  2
  };

  // Return if we've hit one of those...
  if (problemWords[word]) {
    return problemWords[word];
  }

  // These syllables would be counted as two but should be one
  var subSyllables = [
    /cial/,
    /tia/,
    /cius/,
    /cious/,
    /giu/,
    /ion/,
    /iou/,
    /sia$/,
    /[^aeiuoyt]{2,}ed$/,
    /.ely$/,
    /[cg]h?e[rsd]?$/,
    /rved?$/,
    /[aeiouy][dt]es?$/,
    /[aeiouy][^aeiouydt]e[rsd]?$/,
    /^[dr]e[aeiou][^aeiou]+$/, // Sorts out deal, deign etc
    /[aeiouy]rse$/ // Purse, hearse
  ];

  // These syllables would be counted as one but should be two
  var addSyllables = [
    /ia/,
    /riet/,
    /dien/,
    /iu/,
    /io/,
    /ii/,
    /[aeiouym]bl$/,
    /[aeiou]{3}/,
    /^mc/,
    /ism$/,
    /([^aeiouy])\1l$/,
    /[^l]lien/,
    /^coa[dglx]./,
    /[^gq]ua[^auieo]/,
    /dnt$/,
    /uity$/,
    /ie(r|st)$/
  ];

  // Single syllable prefixes and suffixes
  var prefixSuffix = [
    /^un/,
    /^fore/,
    /ly$/,
    /less$/,
    /ful$/,
    /ers?$/,
    /ings?$/
  ];

  // Remove prefixes and suffixes and count how many were taken
  prefixSuffix.forEach(function(regex) {
    if (word.match(regex)) {
      word = word.replace(regex,"");
      prefixSuffixCount ++;
    }
  });

  wordPartCount = word
    .split(/[^aeiouy]+/ig)
    .filter(function(wordPart) {
      return !!wordPart.replace(/\s+/ig,"").length;
    })
    .length;

  // Get preliminary syllable count...
  syllableCount = wordPartCount + prefixSuffixCount;

  // Some syllables do not follow normal rules - check for them
  subSyllables.forEach(function(syllable) {
    if (word.match(syllable)) {
      syllableCount --;
    }
  });

  addSyllables.forEach(function(syllable) {
    if (word.match(syllable)) {
      syllableCount ++;
    }
  });

  return syllableCount || 1;
}

// Given a cursor position & the string value of the input text area,
// return the line number on which the cursor in the text area resides.
function get_line(pos, text)
{
  var lines = text.lines();
  var count = 0;
  var i = 0;
  while (i < pos) {
    i+=lines[count].length+1;
    if (i > pos){
      break;
    }
    count++;
  }
  return count;
}

// Given a line number, the number of syllables, and the string value of the
// syllable count div, return the updated text for the syllable count div.
// *This should be replaced by whatever is needed by the line counts..

$(window).keyup(function(event)
{
  if (!jQuery("textarea.poetry-text").is(":focus")) {
    return;
  }
  var text = jQuery("textarea.poetry-text").val();
  var syllable_area = "";
  var lines = text.lines();
  var iter;
  for (iter = 0; iter < lines.length; iter++) {
    var words = lines[iter].split(" ");
    var word_iter;
    var syllable_count = 0;
    for (word_iter = 0; word_iter < words.length; word_iter++){
      syllable_count+=getSyllableCount(words[word_iter]);
    }
    syllable_area += syllable_count+"
";
  }
  $('div.syllable_counts').html(syllable_area);
  // var caret = jQuery("textarea.poetry-text")[0].selectionStart;
  // var line = get_line(caret, text);
  //if ($('#syllable_count span').length <= line)
  //$('#syllable_count span')[line].innerText = getSyllableCount(text)
});

<|endoftext|>


<commit_before>// cfs-image-resize
// MIT License ben@latenightsketches.com

// Prepare background worker process
var pkgdir = Npm.require('pkgdir');
var fork = Npm.require('child_process').fork;
var path = Npm.require('path');
var fs = Npm.require('fs');

var workerCode = Assets.getText('worker.js');
var workerFile =
  path.join(process.cwd(), 'imageResizeWorker.' + Random.id() + '.js');
fs.writeFileSync(workerFile, workerCode);

/*
Exported method for generating a CollectionFS transformWrite function
@param  options  object   Object containing paramaters for resize
@option width    integer  Output width in pixels, required
@option height   integer  Output height in pixels, required
@option format   string   Output image format. Default: image/png
@option quality  number   For image format image/jpeg, between 0-100
*/
resizeImageStream = function(options) {
  return function(fileObj, readStream, writeStream) {
    var chunks = [];

    readStream.on('readable', function() {
      // Save each incoming chunk of the read stream
      var chunk = readStream.read();
      chunks.push(chunk);
    });

    readStream.on('end', Meteor.bindEnvironment(function() {
      // Concatenate all of the chunks together to get the full input buffer
      var input = Buffer.concat(chunks);

      options.format = options.format || fileObj.original.type;

      var worker = fork(workerFile, [ pkgdir, JSON.stringify(options) ]);

      worker.send(input);

      worker.on('message', function(output) {
        writeStream.end(new Buffer(output));
        worker.kill();
      });
    }));
  }
}
<commit_msg>shouldn't push null chunk to chunks array<commit_after>// cfs-image-resize
// MIT License ben@latenightsketches.com

// Prepare background worker process
var pkgdir = Npm.require('pkgdir');
var fork = Npm.require('child_process').fork;
var path = Npm.require('path');
var fs = Npm.require('fs');

var workerCode = Assets.getText('worker.js');
var workerFile =
  path.join(process.cwd(), 'imageResizeWorker.' + Random.id() + '.js');
fs.writeFileSync(workerFile, workerCode);

/*
Exported method for generating a CollectionFS transformWrite function
@param  options  object   Object containing paramaters for resize
@option width    integer  Output width in pixels, required
@option height   integer  Output height in pixels, required
@option format   string   Output image format. Default: image/png
@option quality  number   For image format image/jpeg, between 0-100
*/
resizeImageStream = function(options) {
  return function(fileObj, readStream, writeStream) {
    var chunks = [];

    readStream.on('readable', function() {
      // Save each incoming chunk of the read stream
      var chunk = readStream.read();
      if (chunk) {
        chunks.push(chunk);
      }
    });

    readStream.on('end', Meteor.bindEnvironment(function() {
      // Concatenate all of the chunks together to get the full input buffer
      var input = Buffer.concat(chunks);

      options.format = options.format || fileObj.original.type;

      var worker = fork(workerFile, [ pkgdir, JSON.stringify(options) ]);

      worker.send(input);

      worker.on('message', function(output) {
        writeStream.end(new Buffer(output));
        worker.kill();
      });
    }));
  }
}
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var request = require('request');
var async = require('async');

var Event = require("./models/event.js");
var Athlete = require("./models/athlete.js");
var Race = require ("./models/race.js");

var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var ipaddress = process.env.OPENSHIFT_NODEJS_IP;
if (typeof ipaddress === "undefined") {
          //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
          //  allows us to run/test the app locally.
          console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
          ipaddress = "127.0.0.1";
};

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(__dirname+'/public'));

var client_id = "727dae7f";
var user_id = "afguzmans3%40gmail.com";
var user_pass = "c16975b43862ff2fe4537d7eee5566af7b80f9d5";
var hostname = "https://api.chronotrack.com:443";
var event_id = "22643";
var query_event = "/api/event/"+event_id+"?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass;
var query_users = "/api/event/"+event_id+"/entry?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass+"&size=1600&include_test_entries=true&elide_json=false;";
var query_result = "/api/event/"+event_id+"/results?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass+"&size=1600&include_test_entries=true&elide_json=false;";
var query_race = "/api/event/"+event_id+"/race?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass+"&page=1&size=50&include_not_wants_results=true";
//var query_result_by_race = "/api/race/"+race_id+"results?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass+"page=1&size=1600&mode=ctlive";

var event;
//Se registra el evento
function getEvent(){
    var url = hostname+query_event;
      request(url, function(err, resp, body) {
        body = JSON.parse(body);
        event = body.event;
        registerEvent(event);
      });
}
function registerEvent(event){
  //Registra el evento si no se ha registrado
  Event.find({},function(err,events){
    if(err){
      console.log("algo paso");
    }else{
        var newEvent = Event({
          id: event.event_id,
          name: event.event_name,
          description: event.event_description,
          country: event.location_country,
          startTime: new Date(Number(event.event_start_time)*1000),
          endTime: new Date(Number(event.event_end_time)*1000),
          siteURI: event.event_site_uri,
          organizationName: event.organization_name
        });
        newEvent.save(function(err){
          if(err){
            console.log("algo paso:" + err);
          }else{
          }
        });
    }
  });
}

//Se registran los atletas
var athletes = [];
function checkRepitedAthletes(arrayAthletes) {
  for(var i=0; i<arrayAthletes.length;i++){
    if(arrayAthletes[i]!=undefined){
      arrayAthletes[i].races = [];
      arrayAthletes[i].races.push(arrayAthletes[i].race_name);
      for(var j=i+1;j<arrayAthletes.length;j++){
        if(arrayAthletes[j]!=undefined && (arrayAthletes[i].entry_name == arrayAthletes[j].entry_name)){
          arrayAthletes[i].races.push(arrayAthletes[j].race_name);
          delete arrayAthletes[j];
        }
      }
    }
  }
}
function getAtletas(){
    var urls = hostname+query_users;
    // request module is used to process the chrotrack url and return the results in JSON format
     request(urls, function(err, resp, body) {
       body = JSON.parse(body);
       athletes = body.event_entry;
       checkRepitedAthletes(athletes);
       registerAthletes();
     });

}
function registerAthletes(){
  Athlete.find({},function(err,athls){
    if(err){
      console.log("algo paso");
    }else{
      if(athls.length==0){
        athletes.forEach(function(value,index){
          var newAthlete = Athlete({
            athlete_id: value.athlete_id,
            entry_name: value.entry_name,
            entry_status: value.entry_status,
            entry_bib: value.entry_bib,
            races: value.races,
            bracket_name: value.bracket_name
          });
          newAthlete.save(function(err){
            if(err){
              console.log("algo paso: " + err);
            }
          });
        });
      }
    }
  });
}

// Se registran las carreras
var races = [];
function getRace(){
var url = hostname+query_race;
      request(url, function(err, resp, body) {
        body = JSON.parse(body);
        races = body.event_race;
        registerRace(races);
      });
}
function registerRace(race){
   Race.find({},function(err,racs){
    if(err){
      console.log("algo paso");
    }else{
      if(racs.length==0){
        races.forEach(function(value,index){
          var newRace = Race({
            id: value.race_id,
            name: value.race_name,
            type: value.race_type,
            subType: value.race_subtype,
            distance: value.race_course_distance,
            distanceUnit: value.race_pref_distance_unit,
            plannedStartTime: new Date(Number(value.race_planned_start_time)*1000),
            plannedFinishTime: new Date(Number(value.race_planned_end_time)*1000),
            raceActualStartTime: new Date(Number(value.race_actual_end_time)*1000),
            raceActualFinishTime: new Date(Number(value.race_age_ref_time)*1000)
          });
          newRace.save(function(err){
            if(err){
              console.log("algo paso: " + err);
            }
          });
        });
      }
    }
  });
}

//funciones

//overall standing
function overallStanding(bracket){
  var theBracket = bracket.replace(" ","%20")
  var query_results_total = "/api/event/"+event_id+"/results?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass+"&page=1&size=1600";
  var query_results_total_with_bracket = "/api/event/"+event_id+"/results?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass+"&page=1&size=1600&bracket="+theBracket;
  if(bracket=="overall"){
    console.log("entra al if bracket overall")
    var uri_crhono = hostname + query_results_total;
    request(uri_crhono,function(err,resp,body){
      body = JSON.parse(body);
      var theTotalResults = body.event_results;
      var JSONTosend = processTotalResult(theTotalResults);
      console.log(JSONTosend)
    });
  }else{
    var uri_crhono_bracket = hostname + query_results_total_with_bracket;
    request(uri_crhono_bracket,function(err,resp,body){
      body = JSON.parse(body);
      console.log(body.event_results);
      var theTotalResults = body.event_results;
      var JSONTosend = processTotalResult(theTotalResults);
    });
  }

}
function processTotalResult(theTotalResults){
  var secondJSON =[];
  for(var i=0; i<theTotalResults.length;i++){
    var theName = theTotalResults[i].results_first_name + " - " + theTotalResults[i].results_last_name;
    var search = searchAthleteInResults(secondJSON,theName);
    if(search.exists){
      var totalTime = secondJSON[search.index].time;
      var currentTime = theTotalResults[i].results_time_with_penalty;
      secondJSON[search.index].time = addTimes(totalTime,currentTime);
    }else{
      console.log("deberia entrar aqui 6 veces")
      var objectToAdd = {
        riders: theTotalResults[i].results_first_name + " - " + theTotalResults[i].results_last_name,
        riders_no: theTotalResults[i].results_bib,
        time: theTotalResults[i].results_time_with_penalty,
        gap: 0,
        bracket: theTotalResults[i].results_primary_bracket_name
      }
      secondJSON.push(objectToAdd);
    }
  }
  return secondJSON;
}
function searchAthleteInResults(theTotalResults,athleteName){
  var theReturn = {
    exists: false,
    index: -1
  };
  for(var i=0;i<theTotalResults.length;i++){
    var theName = theTotalResults[i].riders;
    if(theName==athleteName){
      console.log("deberia entrar alguna vez")
      theReturn =  {
        exists: true,
        index: i
      }
      break;
    }
  }
  return theReturn;
}
function addTimes(totalTime,currentTime){
  var newTotalTime = totalTime.replace(".0","");
  var newCurrentTime = currentTime.replace(".0","");
  console.log(newTotalTime);
  console.log(newCurrentTime)

  var totalParts = newTotalTime.split(":");
  var totalCurrent = newCurrentTime.split(":");

  var totalTimeToSeconds = (totalParts[0] * 60 * 60 ) + (totalParts[1] * 60) + (totalParts[2]);
  var totalCurrentToSecondos = (totalCurrent[0] * 60 * 60) + (totalCurrent[1] * 60) + (totalCurrent[2]);

  var addedTime = totalCurrentToSeconds + totalCurrentToSeconds;

  return msToHMS(addedTime);
}
var secondsToHMS = function (seconds){
    var h = Math.floor(seconds / 3600);
    var m = Math.floor(seconds % 3600 / 60);
    var s = Math.floor(seconds % 3600 % 60);
    return ((h > 0 ? h + ":" : "00:") + (m < 10 ? "0" : "") + m + ":" + (s < 10 ? "0" : "") + s);
}

//stage

function getStageStanding(id,res){
  var race_id = races[id].race_id;
  console.log(client_id)
  var query_result_by_race = "/api/race/"+race_id+"/results?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass+"&page=1&size=1600&mode=ctlive";
  var uri_crhono = hostname+query_result_by_race;
  request(uri_crhono,function(err,resp,body){
    body = JSON.parse(body);
    console.log(body.race_results)
    var theResults = body.race_results;
    var JSONToSend = processRaceResults(theResults);
    res.json(JSONToSend);
  });

}

function processRaceResults(theResults){
  var objectToSend = [];
  theResults.forEach(function(value,index){
    objectToSend[index] = {
      rank: theResults[index].results_rank,
      riders: theResults[index].results_first_name + " - " + theResults[index].results_last_name,
      riders_no: theResults[index].results_bib,
      time: theResults[index].results_time_with_penalty,
      bracket: theResults[index].results_primary_bracket_name
    }
  });
  return objectToSend;
}

//HTTP Get Call for the overall standing
app.get('/Overall', function(req, res) {
    console.log("Llego al Overall")
    var bracket = req.query.bracket;
    console.log("Este es el bracket que llega por el GET: " + bracket);
    overallStanding(bracket);
});

//HTTP Get call for the 7 stages
app.get('/Stage', function(req, res) {
    var index = req.query.id;
    console.log("Este es el id que llega por GET: " + index);
    getStageStanding(index - 1,res);

});

app.listen(port, ipaddress, function() {
  getEvent();
  getAtletas();
  getRace();
  console.log('%s: Node server started on %s:%d ...', Date(Date.now() ), ipaddress, port);
 });<commit_msg>Overall Standing. By s<commit_after>var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var request = require('request');
var async = require('async');

var Event = require("./models/event.js");
var Athlete = require("./models/athlete.js");
var Race = require ("./models/race.js");

var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var ipaddress = process.env.OPENSHIFT_NODEJS_IP;
if (typeof ipaddress === "undefined") {
          //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
          //  allows us to run/test the app locally.
          console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
          ipaddress = "127.0.0.1";
};

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(__dirname+'/public'));

var client_id = "727dae7f";
var user_id = "afguzmans3%40gmail.com";
var user_pass = "c16975b43862ff2fe4537d7eee5566af7b80f9d5";
var hostname = "https://api.chronotrack.com:443";
var event_id = "22643";
var query_event = "/api/event/"+event_id+"?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass;
var query_users = "/api/event/"+event_id+"/entry?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass+"&size=1600&include_test_entries=true&elide_json=false;";
var query_result = "/api/event/"+event_id+"/results?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass+"&size=1600&include_test_entries=true&elide_json=false;";
var query_race = "/api/event/"+event_id+"/race?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass+"&page=1&size=50&include_not_wants_results=true";
//var query_result_by_race = "/api/race/"+race_id+"results?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass+"page=1&size=1600&mode=ctlive";

var event;
//Se registra el evento
function getEvent(){
    var url = hostname+query_event;
      request(url, function(err, resp, body) {
        body = JSON.parse(body);
        event = body.event;
        registerEvent(event);
      });
}
function registerEvent(event){
  //Registra el evento si no se ha registrado
  Event.find({},function(err,events){
    if(err){
      console.log("algo paso");
    }else{
        var newEvent = Event({
          id: event.event_id,
          name: event.event_name,
          description: event.event_description,
          country: event.location_country,
          startTime: new Date(Number(event.event_start_time)*1000),
          endTime: new Date(Number(event.event_end_time)*1000),
          siteURI: event.event_site_uri,
          organizationName: event.organization_name
        });
        newEvent.save(function(err){
          if(err){
            console.log("algo paso:" + err);
          }else{
          }
        });
    }
  });
}

//Se registran los atletas
var athletes = [];
function checkRepitedAthletes(arrayAthletes) {
  for(var i=0; i<arrayAthletes.length;i++){
    if(arrayAthletes[i]!=undefined){
      arrayAthletes[i].races = [];
      arrayAthletes[i].races.push(arrayAthletes[i].race_name);
      for(var j=i+1;j<arrayAthletes.length;j++){
        if(arrayAthletes[j]!=undefined && (arrayAthletes[i].entry_name == arrayAthletes[j].entry_name)){
          arrayAthletes[i].races.push(arrayAthletes[j].race_name);
          delete arrayAthletes[j];
        }
      }
    }
  }
}
function getAtletas(){
    var urls = hostname+query_users;
    // request module is used to process the chrotrack url and return the results in JSON format
     request(urls, function(err, resp, body) {
       body = JSON.parse(body);
       athletes = body.event_entry;
       checkRepitedAthletes(athletes);
       registerAthletes();
     });

}
function registerAthletes(){
  Athlete.find({},function(err,athls){
    if(err){
      console.log("algo paso");
    }else{
      if(athls.length==0){
        athletes.forEach(function(value,index){
          var newAthlete = Athlete({
            athlete_id: value.athlete_id,
            entry_name: value.entry_name,
            entry_status: value.entry_status,
            entry_bib: value.entry_bib,
            races: value.races,
            bracket_name: value.bracket_name
          });
          newAthlete.save(function(err){
            if(err){
              console.log("algo paso: " + err);
            }
          });
        });
      }
    }
  });
}

// Se registran las carreras
var races = [];
function getRace(){
var url = hostname+query_race;
      request(url, function(err, resp, body) {
        body = JSON.parse(body);
        races = body.event_race;
        registerRace(races);
      });
}
function registerRace(race){
   Race.find({},function(err,racs){
    if(err){
      console.log("algo paso");
    }else{
      if(racs.length==0){
        races.forEach(function(value,index){
          var newRace = Race({
            id: value.race_id,
            name: value.race_name,
            type: value.race_type,
            subType: value.race_subtype,
            distance: value.race_course_distance,
            distanceUnit: value.race_pref_distance_unit,
            plannedStartTime: new Date(Number(value.race_planned_start_time)*1000),
            plannedFinishTime: new Date(Number(value.race_planned_end_time)*1000),
            raceActualStartTime: new Date(Number(value.race_actual_end_time)*1000),
            raceActualFinishTime: new Date(Number(value.race_age_ref_time)*1000)
          });
          newRace.save(function(err){
            if(err){
              console.log("algo paso: " + err);
            }
          });
        });
      }
    }
  });
}

//funciones

//overall standing
function overallStanding(bracket,res){
  var theBracket = bracket.replace(" ","%20")
  var query_results_total = "/api/event/"+event_id+"/results?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass+"&page=1&size=1600";
  var query_results_total_with_bracket = "/api/event/"+event_id+"/results?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass+"&page=1&size=1600&bracket="+theBracket;
  if(bracket=="overall"){
    var uri_crhono = hostname + query_results_total;
    request(uri_crhono,function(err,resp,body){
      body = JSON.parse(body);
      var theTotalResults = body.event_results;
      var JSONToSend = processTotalResult(theTotalResults);
      bubbleSort(JSONToSend);
      res.json(JSONToSend);
      console.log(JSONToSend);
    });
  }else{
    var uri_crhono_bracket = hostname + query_results_total_with_bracket;
    request(uri_crhono_bracket,function(err,resp,body){
      body = JSON.parse(body);
      console.log(body.event_results);
      var theTotalResults = body.event_results;
      var JSONTosend = processTotalResult(theTotalResults);
      bubbleSort(JSONToSend);
      res.json(JSONToSend);
    });
  }

}
function processTotalResult(theTotalResults){
  var secondJSON =[];
  for(var i=0; i<theTotalResults.length;i++){
    var theName = theTotalResults[i].results_first_name + " - " + theTotalResults[i].results_last_name;
    var search = searchAthleteInResults(secondJSON,theName);
    if(search.exists){
      var totalTime = secondJSON[search.index].time;
      var currentTime = theTotalResults[i].results_time_with_penalty;
      secondJSON[search.index].time = addTimes(totalTime,currentTime);
    }else{
      var objectToAdd = {
        riders: theTotalResults[i].results_first_name + " - " + theTotalResults[i].results_last_name,
        riders_no: theTotalResults[i].results_bib,
        time: theTotalResults[i].results_time_with_penalty,
        gap: 0,
        bracket: theTotalResults[i].results_primary_bracket_name
      }
      secondJSON.push(objectToAdd);
    }
  }
  return secondJSON;
}
function searchAthleteInResults(theTotalResults,athleteName){
  var theReturn = {
    exists: false,
    index: -1
  };
  for(var i=0;i<theTotalResults.length;i++){
    var theName = theTotalResults[i].riders;
    if(theName==athleteName){
      theReturn =  {
        exists: true,
        index: i
      }
      break;
    }
  }
  return theReturn;
}
function bubbleSort(myArr){
  var size = myArr.length;
  for( var pass = 1; pass < size; pass++ ){ // outer loop
    for( var left = 0; left < (size - pass); left++){ // inner loop
      var right = left + 1;
      var first = HHMMSSToSeconds(myArr[left].time);
      var next = HHMMSSToSeconds(myArr[right].time);
      if( first > next ){
        myArr[left].time = secondsToHMS(next);
        myArr[right].time = secondsToHMS(first);
      }
    }
  }

  return myArr;
}
function HHMMSSToSeconds(time){

  console.log("Lo que entra al HHMMSSToSeconds: " + time)

  var timeSplit = time.split(":");
  return timeToSeconds = (+timeSplit[0]) * 60 * 60  + (+timeSplit[1]) * 60 + (+timeSplit[2]);

}
function addTimes(totalTime,currentTime){

  var newTotalTime = totalTime.replace(".0","");
  var newCurrentTime = currentTime.replace(".0","");

  console.log(newTotalTime);
  console.log(newCurrentTime);

  var totalTimeToSeconds = HHMMSSToSeconds(newTotalTime);
  var totalCurrentToSeconds = HHMMSSToSeconds(newCurrentTime);

  var addedTime = totalTimeToSeconds + totalCurrentToSeconds;

  return secondsToHMS(addedTime);
}
var secondsToHMS = function (seconds){
    var h = Math.floor(seconds / 3600);
    var m = Math.floor(seconds % 3600 / 60);
    var s = Math.floor(seconds % 3600 % 60);

    return ((h < 10 ? "0":"") + h + ":" + (m < 10 ? "0" : "") + m + ":" + (s < 10 ? "0" : "") + s);
}
function swap(myArr, indexOne, indexTwo){
  var tmpVal = myArr[indexOne];
  myArr[indexOne] = myArr[indexTwo];
  myArr[indexTwo] = tmpVal;
  return myArr;
}

//stage

function getStageStanding(id,res){
  var race_id = races[id].race_id;
  console.log(client_id)
  var query_result_by_race = "/api/race/"+race_id+"/results?format=json&client_id="+client_id+"&user_id="+user_id+"&user_pass="+user_pass+"&page=1&size=1600&mode=ctlive";
  var uri_crhono = hostname+query_result_by_race;
  request(uri_crhono,function(err,resp,body){
    body = JSON.parse(body);
    console.log(body.race_results)
    var theResults = body.race_results;
    var JSONToSend = processRaceResults(theResults);
    res.json(JSONToSend);
  });

}

function processRaceResults(theResults){
  var objectToSend = [];
  theResults.forEach(function(value,index){
    objectToSend[index] = {
      rank: theResults[index].results_rank,
      riders: theResults[index].results_first_name + " - " + theResults[index].results_last_name,
      riders_no: theResults[index].results_bib,
      time: theResults[index].results_time_with_penalty,
      bracket: theResults[index].results_primary_bracket_name
    }
  });
  return objectToSend;
}

//HTTP Get Call for the overall standing
app.get('/Overall', function(req, res) {
    console.log("Llego al Overall")
    var bracket = req.query.bracket;
    console.log("Este es el bracket que llega por el GET: " + bracket);
    overallStanding(bracket,res);
});

//HTTP Get call for the 7 stages
app.get('/Stage', function(req, res) {
    var index = req.query.id;
    console.log("Este es el id que llega por GET: " + index);
    getStageStanding(index - 1,res);

});

app.listen(port, ipaddress, function() {
  getEvent();
  getAtletas();
  getRace();
  console.log('%s: Node server started on %s:%d ...', Date(Date.now() ), ipaddress, port);
 });<|endoftext|>


<commit_before>/* Project: Bootstrap Growl - v2.0.0 | Author: Mouse0270 aka Robert McIntosh | License: MIT License | Website: https://github.com/mouse0270/bootstrap-growl */
(function($,window,document,undefined){var pluginName="growl",dataKey="plugin_"+pluginName,defaults={element:"body",type:"info",allow_dismiss:true,placement:{from:"top",align:"right"},offset:20,spacing:10,z_index:1031,delay:5E3,timer:1E3,url_target:"_blank",mouse_over:false,animate:{"in":"animated fadeInDown",out:"animated fadeOutUp"},icon_type:"class",template:'
<button type="button" class="close" data-growl="dismiss">×Close</button>
'};
var setDefaults=function(element,options){defaults=$.extend(true,{},defaults,options)},Plugin=function(element,content,options){var content={content:{message:typeof content=="object"?content.message:content,title:content.title?content.title:null,icon:content.icon?content.icon:null,url:content.url?content.url:null}};options=$.extend(true,{},content,options);this.settings=$.extend(true,{},defaults,options);plugin=this;init(options,this.settings,plugin);this.$template=$template},init=function(options,
settings,plugin){var base={settings:settings,$element:$(settings.element),template:settings.template};$template=buildGrowl(base);addContent($template,base.settings);placement($template,base.settings);bindControls($template,base.settings,plugin)},buildGrowl=function(base){var $template=$(base.settings.template);$template.addClass("alert-"+base.settings.type);$template.attr("data-growl-position",base.settings.placement.from+"-"+base.settings.placement.align);$template.find('[data-growl="dismiss"]').css("display",
"none");if(base.settings.allow_dismiss)$template.find('[data-growl="dismiss"]').css("display","inline-block");return $template},addContent=function($template,settings){$template.find('[data-growl="dismiss"]').css({"position":"absolute","top":"5px","right":"10px","z-index":settings.z_index-1>=1?settings.z_index-1:1});if(settings.content.icon)if(settings.icon_type.toLowerCase()=="class")$template.find('[data-growl="icon"]').addClass(settings.content.icon);else if($template.find('[data-growl="icon"]').is("img"))$template.find('[data-growl="icon"]').attr("src",
settings.content.icon);else $template.find('[data-growl="icon"]').append('');if(settings.content.title)$template.find('[data-growl="title"]').html(settings.content.title);if(settings.content.message)$template.find('[data-growl="message"]').html(settings.content.message);if(settings.content.url){$template.find('[data-growl="url"]').attr("href",settings.content.url).attr("target",settings.url_target);$template.find('[data-growl="url"]').css({"position":"absolute",
"top":"0px","left":"0px","width":"100%","height":"100%","z-index":settings.z_index-2>=1?settings.z_index-2:1})}},placement=function($template,settings){var offsetAmt=settings.offset,gCSS={"position":settings.element==="body"?"fixed":"absolute","margin":0,"z-index":settings.z_index,"display":"inline-block"};$('[data-growl-position="'+settings.placement.from+"-"+settings.placement.align+'"]').each(function(){return offsetAmt=Math.max(offsetAmt,parseInt($(this).css(settings.placement.from))+$(this).outerHeight()+
settings.spacing)});gCSS[settings.placement.from]=offsetAmt+"px";$template.css(gCSS);$(settings.element).append($template);switch(settings.placement.align){case "center":$template.css({"left":"50%","marginLeft":-($template.outerWidth()/2)+"px"});break;case "left":$template.css("left",settings.offset+"px");break;case "right":$template.css("right",settings.offset+"px");break}$template.addClass("growl-animated")},bindControls=function($template,settings,plugin){$template.addClass(settings.animate["in"]);
$template.find('[data-growl="dismiss"]').on("click",function(){plugin.close()});if(settings.delay>=1){$template.data("growl-delay",settings.delay);var timer=setInterval(function(){var delay=parseInt($template.data("growl-delay"))-settings.timer;if(!$template.is(":hover")&&settings.mouse_over=="pause"||settings.mouse_over!="pause")$template.data("growl-delay",delay);console.log(delay);if(delay<=0){clearInterval(timer);plugin.close()}},settings.timer)}};Plugin.prototype={update:function(command,update){switch(command){case "icon":if(this.settings.icon_type.toLowerCase()==
"class"){this.$template.find('[data-growl="icon"]').removeClass(this.settings.content.icon);this.$template.find('[data-growl="icon"]').addClass(update)}else if(this.$template.find('[data-growl="icon"]').is("img"))this.$template.find('[data-growl="icon"]');else this.$template.find('[data-growl="icon"]').find("img").attr().attr("src",update);break;case "url":this.$template.find('[data-growl="url"]').attr("href",update);break;case "type":this.$template.removeClass("alert-"+this.settings.type);this.$template.addClass("alert-"+
update);break;default:this.$template.find('[data-growl="'+command+'"]').html(update)}return this},close:function(){this.$template.addClass(this.settings.animate.out);var settings=this.settings,posX=this.$template.css(settings.placement.from);this.$template.nextAll('[data-growl-position="'+this.settings.placement.from+"-"+this.settings.placement.align+'"]').each(function(){$(this).css(settings.placement.from,posX);posX=parseInt(posX)+settings.spacing+$(this).outerHeight()});this.$template.one("webkitAnimationEnd oanimationend msAnimationEnd animationend",
function(event){$(this).remove()});return this}};$.growl=function(content,options){if(content==false){setDefaults(this,options);return false}var plugin=new Plugin(this,content,options);return plugin}})(jQuery,window,document);
<commit_msg>Update bootstrap-growl.min.js<commit_after>/* Project: Bootstrap Growl - v2.0.0a1 | Author: Mouse0270 aka Robert McIntosh | License: MIT License | Website: https://github.com/mouse0270/bootstrap-growl */
(function(e,t,n,r){var i="growl",s="plugin_"+i,o={element:"body",type:"info",allow_dismiss:true,placement:{from:"top",align:"right"},offset:20,spacing:10,z_index:1031,delay:5e3,timer:1e3,url_target:"_blank",mouse_over:false,animate:{"in":"animated fadeInDown",out:"animated fadeOutUp"},icon_type:"class",template:'
<button type="button" class="close" data-growl="dismiss">×Close</button>
'};var u=function(t,n){o=e.extend(true,{},o,n)},a=function(t,n,r){var n={content:{message:typeof n=="object"?n.message:n,title:n.title?n.title:null,icon:n.icon?n.icon:null,url:n.url?n.url:null}};r=e.extend(true,{},n,r);this.settings=e.extend(true,{},o,r);plugin=this;f(r,this.settings,plugin);this.$template=$template},f=function(t,n,r){var i={settings:n,$element:e(n.element),template:n.template};$template=l(i);c($template,i.settings);h($template,i.settings);p($template,i.settings,r)},l=function(t){var n=e(t.settings.template);n.addClass("alert-"+t.settings.type);n.attr("data-growl-position",t.settings.placement.from+"-"+t.settings.placement.align);n.find('[data-growl="dismiss"]').css("display","none");if(t.settings.allow_dismiss){n.find('[data-growl="dismiss"]').css("display","inline-block")}return n},c=function(e,t){e.find('[data-growl="dismiss"]').css({position:"absolute",top:"5px",right:"10px","z-index":t.z_index-1>=1?t.z_index-1:1});if(t.content.icon){if(t.icon_type.toLowerCase()=="class"){e.find('[data-growl="icon"]').addClass(t.content.icon)}else{if(e.find('[data-growl="icon"]').is("img")){e.find('[data-growl="icon"]').attr("src",t.content.icon)}else{e.find('[data-growl="icon"]').append('')}}}if(t.content.title){e.find('[data-growl="title"]').html(t.content.title)}if(t.content.message){e.find('[data-growl="message"]').html(t.content.message)}if(t.content.url){e.find('[data-growl="url"]').attr("href",t.content.url).attr("target",t.url_target);e.find('[data-growl="url"]').css({position:"absolute",top:"0px",left:"0px",width:"100%",height:"100%","z-index":t.z_index-2>=1?t.z_index-2:1})}},h=function(t,n){var r=n.offset,i={position:n.element==="body"?"fixed":"absolute",margin:0,"z-index":n.z_index,display:"inline-block"};e('[data-growl-position="'+n.placement.from+"-"+n.placement.align+'"]').each(function(){return r=Math.max(r,parseInt(e(this).css(n.placement.from))+e(this).outerHeight()+n.spacing)});i[n.placement.from]=r+"px";t.css(i);e(n.element).append(t);switch(n.placement.align){case"center":t.css({left:"50%",marginLeft:-(t.outerWidth()/2)+"px"});break;case"left":t.css("left",n.offset+"px");break;case"right":t.css("right",n.offset+"px");break}t.addClass("growl-animated")},p=function(e,t,n){e.addClass(t.animate.in);e.find('[data-growl="dismiss"]').on("click",function(){n.close()});if(t.delay>=1){e.data("growl-delay",t.delay);var r=setInterval(function(){var i=parseInt(e.data("growl-delay"))-t.timer;if(!e.is(":hover")&&t.mouse_over=="pause"||t.mouse_over!="pause"){e.data("growl-delay",i)}console.log(i);if(i<=0){clearInterval(r);n.close()}},t.timer)}};a.prototype={update:function(e,t){switch(e){case"icon":if(this.settings.icon_type.toLowerCase()=="class"){this.$template.find('[data-growl="icon"]').removeClass(this.settings.content.icon);this.$template.find('[data-growl="icon"]').addClass(t)}else{if(this.$template.find('[data-growl="icon"]').is("img")){this.$template.find('[data-growl="icon"]')}else{this.$template.find('[data-growl="icon"]').find("img").attr().attr("src",t)}}break;case"url":this.$template.find('[data-growl="url"]').attr("href",t);break;case"type":this.$template.removeClass("alert-"+this.settings.type);this.$template.addClass("alert-"+t);break;default:this.$template.find('[data-growl="'+e+'"]').html(t)}return this},close:function(){this.$template.addClass(this.settings.animate.out);var t=this.settings,n=this.$template.css(t.placement.from);this.$template.nextAll('[data-growl-position="'+this.settings.placement.from+"-"+this.settings.placement.align+'"]').each(function(){e(this).css(t.placement.from,n);n=parseInt(n)+t.spacing+e(this).outerHeight()});this.$template.one("webkitAnimationEnd oanimationend msAnimationEnd animationend",function(t){e(this).remove()});return this}};e.growl=function(e,t){if(e==false){u(this,t);return false}var n=new a(this,e,t);return n}})(jQuery,window,document)
<|endoftext|>


<commit_before>/**
 * Created by Robin on 3/15/2016.
 */

var http = require('http'),
    socket = require('socket.io'),
    fileSystem = require('fs'),
    path = require('path'),
    server = http.createServer(requestListener),
    port = process.env.PORT || 8000;

server.listen(port);
console.log("Listening on port", port);

function requestListener(request, response) {
    switch (request.method) {
        case "GET":
            urlRequest(request.url, response);
            break;
        case "POST":
            joinRoom(request, response);
            break;
    }
}

function joinRoom(request, response) {
    request.on("data", function (data) {
        var roomNr = data.toString().split('=')[1];
        if (game[roomNr] == null || game[roomNr].player2 === undefined) {
            // console.log(game[roomNr]);
            urlRequest("/", response);
        }
    });
}

function urlRequest(url, response) {
    var filePath = "";
    switch (url) {
        case "/":
        case "/index":
        case "/index.html":
            filePath = "app/index.html";
            break;
        default:
            filePath = "app" + url;
            break;
    }

    fileSystem.exists(filePath, function (exists) {
        if (exists) {
            fileSystem.readFile(filePath, function (error, content) {
                if (error) {
                    response.writeHead(500);
                    response.end();
                } else {
                    var ext = url.split(".")[1];
                    if (ext !== undefined) {
                        response.writeHead(200, {"Content-Type": "text/" + ext});
                    } else {
                        response.writeHead(200, {"Content-Type": "text/html"});
                    }
                    response.end(content, "utf-8");
                }
            });
        } else {
            response.writeHead(404);
            response.end();
        }
    });
}

var ios = socket.listen(server);
var game = {
    0: null,
    1: null,
    2: null
};

function sendToOtherPlayer(sender, updateType, objectToSend, roomNumber, socket) {
    // console.log("Sender: ", sender, " UpdateType: ", updateType, " Current game: ", game);
    // console.log(objectToSend);
    if(game[roomNumber] !== null) {
        var receiverId = (game[roomNumber].player1 !== undefined && game[roomNumber].player1 !== null &&
        game[roomNumber].player1.id !== sender)             // Check if the sender is not player1
            ? game[roomNumber].player1.id                                       // if so, the receiver is player1.
            : ((game[roomNumber].player2 !== undefined)                         // Else, if player2 is not undefined
            ? game[roomNumber].player2.id                                       // the receiver is player2
            : undefined);                                                       // if player2 is undefined, set var to undefined

        if (receiverId !== undefined)                                           // If the receiver is undefined, we don't have to send an update
            socket.broadcast.to(receiverId).emit(updateType, objectToSend);
    }
}

ios.sockets.on("connection", function (socket) {

    socket.send(socket.id);

    socket.on("disconnecting", function (data) {
        var room = game[data.roomNumber];
        if (data.player.id === room.player1.id)
            room.player1 = undefined;
        else if (data.player.id === room.player2.id)
            room.player2 = undefined;

        // console.log(room);
        if(room.player1 === undefined && room.player2 === undefined)
            game[data.roomNumber] = null;
        sendToOtherPlayer(socket.id, "playerdisconnectmessage", room, data.roomNumber, socket);
        // socket.broadcast.emit("playerdisconnectmessage", data);
    });

    socket.on("clientmessage", function (data) {
        // console.log(data);
        game[data.roomNumber] = data.instance;
        sendToOtherPlayer(socket.id, "servermessage", data, data.roomNumber, socket);
        // socket.broadcast.emit("servermessage", data);
    });

    socket.on("playerupdate", function (data) {
        var targetRoom = game[data.roomNumber],
            updatedPlayer;
        if(targetRoom !== null) {
            if (targetRoom.player1 !== undefined && targetRoom.player1.id === data.player.id)
                updatedPlayer = targetRoom.player1;
            else if (targetRoom.player2 !== undefined && targetRoom.player2.id === data.player.id)
                updatedPlayer = targetRoom.player2;

            // console.log(data);
            if (updatedPlayer !== undefined) {
                updatedPlayer.position = data.player.position;
                sendToOtherPlayer(data.player.id, "playerupdatemessage", targetRoom, data.roomNumber, socket);
            }
        }
        // console.log(data);

        // socket.broadcast.emit("updatemessage", {"roomNumber": data.roomNumber, "instance": targetRoom});
    });

    socket.on("ballupdate", function (data) {
        // console.log(data.position);
        // game[data.roomNumber]
        // console.log(game);
        if (game[data.roomNumber] !== null && game[data.roomNumber].projectile !== undefined && game[data.roomNumber].projectile.x !== undefined && game[data.roomNumber].projectile.y !== undefined) {
            game[data.roomNumber].projectile.x = data.projectile.x;
            game[data.roomNumber].projectile.y = data.projectile.y;
        }
        sendToOtherPlayer(socket.id, "ballupdatemessage", data, data.roomNumber, socket);
    });

    socket.on("newplayer", function (data) {
        // console.log("Player connected: ", socket.id);
        if (ios.sockets.connected[socket.id]) {
            console.log("New player wants to join room nr: ", data);
            console.log("sending info to new player...");

            ios.sockets.connected[socket.id].emit("servernewplayer", {"id": socket.id, "instance": game[data]});
        }
    });

});<commit_msg>Added restriction on joining a new game<commit_after>/**
 * Created by Robin on 3/15/2016.
 */

var http = require('http'),
    socket = require('socket.io'),
    fileSystem = require('fs'),
    path = require('path'),
    server = http.createServer(requestListener),
    port = process.env.PORT || 8000;

server.listen(port);
console.log("Listening on port", port);

function requestListener(request, response) {
    switch (request.method) {
        case "GET":
            urlRequest(request.url, response);
            break;
        case "POST":
            joinRoom(request, response);
            break;
    }
}

function joinRoom(request, response) {
    request.on("data", function (data) {
        var roomNr = data.toString().split('=')[1];
        if (game[roomNr] == null || game[roomNr].player2 === undefined) {
            // console.log(game[roomNr]);
            urlRequest("/", response);
        }
    });
}

function urlRequest(url, response) {
    var filePath = "";
    switch (url) {
        case "/":
        case "/index":
        case "/index.html":
            filePath = "app/index.html";
            break;
        default:
            filePath = "app" + url;
            break;
    }

    fileSystem.exists(filePath, function (exists) {
        if (exists) {
            fileSystem.readFile(filePath, function (error, content) {
                if (error) {
                    response.writeHead(500);
                    response.end();
                } else {
                    var ext = url.split(".")[1];
                    if (ext !== undefined) {
                        response.writeHead(200, {"Content-Type": "text/" + ext});
                    } else {
                        response.writeHead(200, {"Content-Type": "text/html"});
                    }
                    response.end(content, "utf-8");
                }
            });
        } else {
            response.writeHead(404);
            response.end();
        }
    });
}

var ios = socket.listen(server);
var game = {
    0: null,
    1: null,
    2: null
};

function sendToOtherPlayer(sender, updateType, objectToSend, roomNumber, socket) {
    // console.log("Sender: ", sender, " UpdateType: ", updateType, " Current game: ", game);
    // console.log(objectToSend);
    if(game[roomNumber] !== null) {
        var receiverId = (game[roomNumber].player1 !== undefined && game[roomNumber].player1 !== null &&
        game[roomNumber].player1.id !== sender)             // Check if the sender is not player1
            ? game[roomNumber].player1.id                                       // if so, the receiver is player1.
            : ((game[roomNumber].player2 !== undefined)                         // Else, if player2 is not undefined
            ? game[roomNumber].player2.id                                       // the receiver is player2
            : undefined);                                                       // if player2 is undefined, set var to undefined

        if (receiverId !== undefined)                                           // If the receiver is undefined, we don't have to send an update
            socket.broadcast.to(receiverId).emit(updateType, objectToSend);
    }
}

ios.sockets.on("connection", function (socket) {

    socket.send(socket.id);

    socket.on("disconnecting", function (data) {
        var room = game[data.roomNumber];
        if (data.player.id === room.player1.id)
            room.player1 = undefined;
        else if (data.player.id === room.player2.id)
            room.player2 = undefined;

        // console.log(room);
        if(room.player1 === undefined && room.player2 === undefined)
            game[data.roomNumber] = null;
        sendToOtherPlayer(socket.id, "playerdisconnectmessage", room, data.roomNumber, socket);
        // socket.broadcast.emit("playerdisconnectmessage", data);
    });

    socket.on("clientmessage", function (data) {
        // console.log(data);
        game[data.roomNumber] = data.instance;
        sendToOtherPlayer(socket.id, "servermessage", data, data.roomNumber, socket);
        // socket.broadcast.emit("servermessage", data);
    });

    socket.on("playerupdate", function (data) {
        var targetRoom = game[data.roomNumber],
            updatedPlayer;
        if(targetRoom !== null) {
            if (targetRoom.player1 !== undefined && targetRoom.player1.id === data.player.id)
                updatedPlayer = targetRoom.player1;
            else if (targetRoom.player2 !== undefined && targetRoom.player2.id === data.player.id)
                updatedPlayer = targetRoom.player2;

            // console.log(data);
            if (updatedPlayer !== undefined) {
                updatedPlayer.position = data.player.position;
                sendToOtherPlayer(data.player.id, "playerupdatemessage", targetRoom, data.roomNumber, socket);
            }
        }
        // console.log(data);

        // socket.broadcast.emit("updatemessage", {"roomNumber": data.roomNumber, "instance": targetRoom});
    });

    socket.on("ballupdate", function (data) {
        // console.log(data.position);
        // game[data.roomNumber]
        // console.log(game);
        if (game[data.roomNumber] !== null && game[data.roomNumber].projectile !== undefined && game[data.roomNumber].projectile.x !== undefined && game[data.roomNumber].projectile.y !== undefined) {
            game[data.roomNumber].projectile.x = data.projectile.x;
            game[data.roomNumber].projectile.y = data.projectile.y;
        }
        sendToOtherPlayer(socket.id, "ballupdatemessage", data, data.roomNumber, socket);
    });

    socket.on("newplayer", function (data) {
        // console.log("Player connected: ", socket.id);
        if (ios.sockets.connected[socket.id]) {
            if(game[data] === null || (game[data].player1 === undefined || game[data].player2 === undefined)) {
                console.log("New player wants to join room nr: ", data);
                console.log("sending info to new player...");

                ios.sockets.connected[socket.id].emit("servernewplayer", {"id": socket.id, "instance": game[data]});
            }
        }
    });

});<|endoftext|>


<commit_before>/* ==========================================================
 * bootstrap-maxlength.js v1.3.4
 * ==========================================================
 *
 * 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 ($) {
    "use strict";
    /*jslint browser:true*/
    /*global  $*/
    $.fn.extend({
        maxlength: function (options, callback) {

            var documentBody = $('body'),
                defaults = {
                    alwaysShow: false, // if true the indicator it's always shown.
                    threshold: 10, // Represents how many chars left are needed to show up the counter
                    warningClass: "badge badge-success",
                    limitReachedClass: "badge badge-important",
                    separator: ' / ',
                    preText: '',
                    postText: '',
                    placement: 'bottom',
                    validate: false // if the browser doesn't support the maxlength attribute, attempt to type more than
                          // the indicated chars, will be prevented.
                };

            if ($.isFunction(options) && !callback) {
                callback = options;
                options = {};
            }
            options = $.extend(defaults, options);

          /**
          * Return the length of the specified input.
          *
          * @param input
          * @return {number}
          */
            function inputLength(input) {
                var text = input.val(),
                    matches = text.match(/\n/g),
                    breaks = matches ? matches.length : 0;
                return input.val().length + breaks;
            }

          /**
           * Return true if the indicator should be showing up.
           *
           * @param input
           * @param thereshold
           * @param maxlength
           * @return {number}
           */
            function charsLeftThreshold(input, thereshold, maxlength) {
                var output = false;
                if (!options.alwaysShow && (maxlength - inputLength(input) > thereshold)) {
                    output = true;
                }
                return output;
            }

          /**
           * Returns how many chars are left to complete the fill up of the form.
           *
           * @param input
           * @param maxlength
           * @return {number}
           */
            function remainingChars(input, maxlength) {
                var length = maxlength - inputLength(input);
                return length;
            }

          /**
           * When called displays the indicator.
           *
           * @param indicator
           */
            function showRemaining(indicator) {
                indicator.css({
                    display: 'block'
                });
            }

          /**
           * When called shows the indicator.
           *
           * @param indicator
           */
            function hideRemaining(indicator) {
                indicator.css({
                    display: 'none'
                });
            }

           /**
           * This function updates the value in the indicator
           *
           * @param maxlengthIndicator
           * @return String
           */
            function updateMaxLengthHTML(maxLengthThisInput, typedChars) {
                var output = '';
                if (options.preText) {
                    output += options.preText;
                }
                output = output + typedChars + options.separator + maxLengthThisInput;
                if (options.postText) {
                    output += options.postText;
                }
                return output;
            }

          /**
           * This function updates the value of the counter in the indicator.
           * Wants as parameters: the number of remaining chars, the element currently managed,
           * the maxLength for the current input and the indicator generated for it.
           *
           * @param remaining
           * @param currentInput
           * @param maxLengthCurrentInput
           * @param maxLengthIndicator
           */
            function manageRemainingVisibility(remaining, currentInput, maxLengthCurrentInput, maxLengthIndicator) {
                maxLengthIndicator.html(updateMaxLengthHTML(maxLengthCurrentInput, remaining));

                if (remaining > 0) {
                    if (charsLeftThreshold(currentInput, options.threshold, maxLengthCurrentInput)) {
                        showRemaining(maxLengthIndicator.removeClass(options.limitReachedClass).addClass(options.warningClass));
                    } else {
                        hideRemaining(maxLengthIndicator);
                    }
                } else {
                    showRemaining(maxLengthIndicator.removeClass(options.warningClass).addClass(options.limitReachedClass));
                }
            }

          /**
           * This function returns an object containing all the
           * informations about the position of the current input
           *
           *  @param currentInput
           *  @return object {bottom height left right top  width}
           *
           */
            function getPosition(currentInput) {
                var el = currentInput[0];
                return $.extend({}, (typeof el.getBoundingClientRect === 'function') ? el.getBoundingClientRect() : {
                    width: el.offsetWidth,
                    height: el.offsetHeight
                }, currentInput.offset());
            }

          /**
           *  This function places the maxLengthIndicator at the
           *  top / bottom / left / right of the currentInput
           *
           *  @param currentInput
           *  @param maxLengthIndicator
           *  @return null
           *
           */
            function place(currentInput, maxLengthIndicator) {
                var pos = getPosition(currentInput),
                    offset = currentInput.offset(),
                    inputOuter = currentInput.outerWidth(),
                    outerWidth = maxLengthIndicator.outerWidth(),
                    actualWidth = maxLengthIndicator.width(),
                    actualHeight = maxLengthIndicator.height();

                switch (options.placement) {
                case 'bottom':
                    maxLengthIndicator.css({top: offset.top + pos.height, left: offset.left + pos.width / 2 - actualWidth / 2});
                    break;
                case 'top':
                    maxLengthIndicator.css({top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2});
                    break;
                case 'left':
                    maxLengthIndicator.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth});
                    break;
                case 'right':
                    maxLengthIndicator.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width});
                    break;
                case 'bottom-right':
                    maxLengthIndicator.css({top: pos.top + pos.height, left: pos.left + pos.width});
                    break;
                case 'top-right':
                    maxLengthIndicator.css({top: offset.top - actualHeight, left: offset.left + inputOuter});
                    break;
                case 'top-left':
                    maxLengthIndicator.css({top: offset.top - actualHeight, left: offset.left - outerWidth});
                    break;
                case 'bottom-left':
                    maxLengthIndicator.css({top: offset.top + currentInput.outerHeight(), left: offset.left - outerWidth});
                    break;
                case 'centered-right':
                    maxLengthIndicator.css({top: offset.top + (actualHeight / 2), left: offset.left + inputOuter - outerWidth - 3});
                    break;
                }
            }

            /**
             *  This function retrieves the maximum length of currentInput
             *
             *  @param currentInput
             *  @return {number}
             *
             */
            function getMaxLength(currentInput) {
                return currentInput.attr('maxlength') || currentInput.attr('size');
            }

            return this.each(function() {

                var currentInput = $(this),
                    maxLengthCurrentInput = getMaxLength(currentInput),
                    maxLengthIndicator = $('').css({
                        display: 'none',
                        position: 'absolute',
                        whiteSpace: 'nowrap',
                        zIndex: 999
                    }).html(updateMaxLengthHTML(maxLengthCurrentInput, '0'));

                documentBody.append(maxLengthIndicator);

                currentInput.focus(function() {
                    var remaining = remainingChars(currentInput, maxLengthCurrentInput = getMaxLength(currentInput));
                    maxLengthIndicator.css({
                        zIndex: 99999
                    });

                    manageRemainingVisibility(remaining, currentInput, maxLengthCurrentInput, maxLengthIndicator);
                    place(currentInput, maxLengthIndicator);
                });

                currentInput.blur(function() {
                    maxLengthIndicator.css('display', 'none');
                });

                currentInput.keyup(function() {
                    var remaining = remainingChars(currentInput, maxLengthCurrentInput = getMaxLength(currentInput)),
                        output = true;
                    if (options.validate && remaining < 0) {
                        output = false;
                    } else {
                        manageRemainingVisibility(remaining, currentInput, maxLengthCurrentInput, maxLengthIndicator);
                    }
                    return output;
                });
                currentInput.keydown(function(event) {
                    var remaining = remainingChars(currentInput, maxLengthCurrentInput = getMaxLength(currentInput));
                    if (remaining <= 0 && (event.keyCode !== 46 && event.keyCode !== 8)) {
                        return false;
                    }
                });
            });
        }
    });
}(jQuery));
<commit_msg>Fixed reversed outputs<commit_after>/* ==========================================================
 * bootstrap-maxlength.js v1.3.4
 * ==========================================================
 *
 * 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 ($) {
    "use strict";
    /*jslint browser:true*/
    /*global  $*/
    $.fn.extend({
        maxlength: function (options, callback) {

            var documentBody = $('body'),
                defaults = {
                    alwaysShow: false, // if true the indicator it's always shown.
                    threshold: 10, // Represents how many chars left are needed to show up the counter
                    warningClass: "badge badge-success",
                    limitReachedClass: "badge badge-important",
                    separator: ' / ',
                    preText: '',
                    postText: '',
                    placement: 'bottom',
                    validate: false // if the browser doesn't support the maxlength attribute, attempt to type more than
                          // the indicated chars, will be prevented.
                };

            if ($.isFunction(options) && !callback) {
                callback = options;
                options = {};
            }
            options = $.extend(defaults, options);

          /**
          * Return the length of the specified input.
          *
          * @param input
          * @return {number}
          */
            function inputLength(input) {
                var text = input.val(),
                    matches = text.match(/\n/g),
                    breaks = matches ? matches.length : 0;
                return input.val().length + breaks;
            }

          /**
           * Return true if the indicator should be showing up.
           *
           * @param input
           * @param thereshold
           * @param maxlength
           * @return {number}
           */
            function charsLeftThreshold(input, thereshold, maxlength) {
                var output = true;
                if (!options.alwaysShow && (maxlength - inputLength(input) > thereshold)) {
                    output = false;
                }
                return output;
            }

          /**
           * Returns how many chars are left to complete the fill up of the form.
           *
           * @param input
           * @param maxlength
           * @return {number}
           */
            function remainingChars(input, maxlength) {
                var length = maxlength - inputLength(input);
                return length;
            }

          /**
           * When called displays the indicator.
           *
           * @param indicator
           */
            function showRemaining(indicator) {
                indicator.css({
                    display: 'block'
                });
            }

          /**
           * When called shows the indicator.
           *
           * @param indicator
           */
            function hideRemaining(indicator) {
                indicator.css({
                    display: 'none'
                });
            }

           /**
           * This function updates the value in the indicator
           *
           * @param maxlengthIndicator
           * @return String
           */
            function updateMaxLengthHTML(maxLengthThisInput, typedChars) {
                var output = '';
                if (options.preText) {
                    output += options.preText;
                }
                output = output + typedChars + options.separator + maxLengthThisInput;
                if (options.postText) {
                    output += options.postText;
                }
                return output;
            }

          /**
           * This function updates the value of the counter in the indicator.
           * Wants as parameters: the number of remaining chars, the element currently managed,
           * the maxLength for the current input and the indicator generated for it.
           *
           * @param remaining
           * @param currentInput
           * @param maxLengthCurrentInput
           * @param maxLengthIndicator
           */
            function manageRemainingVisibility(remaining, currentInput, maxLengthCurrentInput, maxLengthIndicator) {
                maxLengthIndicator.html(updateMaxLengthHTML(maxLengthCurrentInput, remaining));

                if (remaining > 0) {
                    if (charsLeftThreshold(currentInput, options.threshold, maxLengthCurrentInput)) {
                        showRemaining(maxLengthIndicator.removeClass(options.limitReachedClass).addClass(options.warningClass));
                    } else {
                        hideRemaining(maxLengthIndicator);
                    }
                } else {
                    showRemaining(maxLengthIndicator.removeClass(options.warningClass).addClass(options.limitReachedClass));
                }
            }

          /**
           * This function returns an object containing all the
           * informations about the position of the current input
           *
           *  @param currentInput
           *  @return object {bottom height left right top  width}
           *
           */
            function getPosition(currentInput) {
                var el = currentInput[0];
                return $.extend({}, (typeof el.getBoundingClientRect === 'function') ? el.getBoundingClientRect() : {
                    width: el.offsetWidth,
                    height: el.offsetHeight
                }, currentInput.offset());
            }

          /**
           *  This function places the maxLengthIndicator at the
           *  top / bottom / left / right of the currentInput
           *
           *  @param currentInput
           *  @param maxLengthIndicator
           *  @return null
           *
           */
            function place(currentInput, maxLengthIndicator) {
                var pos = getPosition(currentInput),
                    offset = currentInput.offset(),
                    inputOuter = currentInput.outerWidth(),
                    outerWidth = maxLengthIndicator.outerWidth(),
                    actualWidth = maxLengthIndicator.width(),
                    actualHeight = maxLengthIndicator.height();

                switch (options.placement) {
                case 'bottom':
                    maxLengthIndicator.css({top: offset.top + pos.height, left: offset.left + pos.width / 2 - actualWidth / 2});
                    break;
                case 'top':
                    maxLengthIndicator.css({top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2});
                    break;
                case 'left':
                    maxLengthIndicator.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth});
                    break;
                case 'right':
                    maxLengthIndicator.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width});
                    break;
                case 'bottom-right':
                    maxLengthIndicator.css({top: pos.top + pos.height, left: pos.left + pos.width});
                    break;
                case 'top-right':
                    maxLengthIndicator.css({top: offset.top - actualHeight, left: offset.left + inputOuter});
                    break;
                case 'top-left':
                    maxLengthIndicator.css({top: offset.top - actualHeight, left: offset.left - outerWidth});
                    break;
                case 'bottom-left':
                    maxLengthIndicator.css({top: offset.top + currentInput.outerHeight(), left: offset.left - outerWidth});
                    break;
                case 'centered-right':
                    maxLengthIndicator.css({top: offset.top + (actualHeight / 2), left: offset.left + inputOuter - outerWidth - 3});
                    break;
                }
            }

            /**
             *  This function retrieves the maximum length of currentInput
             *
             *  @param currentInput
             *  @return {number}
             *
             */
            function getMaxLength(currentInput) {
                return currentInput.attr('maxlength') || currentInput.attr('size');
            }

            return this.each(function() {

                var currentInput = $(this),
                    maxLengthCurrentInput = getMaxLength(currentInput),
                    maxLengthIndicator = $('').css({
                        display: 'none',
                        position: 'absolute',
                        whiteSpace: 'nowrap',
                        zIndex: 999
                    }).html(updateMaxLengthHTML(maxLengthCurrentInput, '0'));

                documentBody.append(maxLengthIndicator);

                currentInput.focus(function() {
                    var remaining = remainingChars(currentInput, maxLengthCurrentInput = getMaxLength(currentInput));
                    maxLengthIndicator.css({
                        zIndex: 99999
                    });

                    manageRemainingVisibility(remaining, currentInput, maxLengthCurrentInput, maxLengthIndicator);
                    place(currentInput, maxLengthIndicator);
                });

                currentInput.blur(function() {
                    maxLengthIndicator.css('display', 'none');
                });

                currentInput.keyup(function() {
                    var remaining = remainingChars(currentInput, maxLengthCurrentInput = getMaxLength(currentInput)),
                        output = true;
                    if (options.validate && remaining < 0) {
                        output = false;
                    } else {
                        manageRemainingVisibility(remaining, currentInput, maxLengthCurrentInput, maxLengthIndicator);
                    }
                    return output;
                });
                currentInput.keydown(function(event) {
                    var remaining = remainingChars(currentInput, maxLengthCurrentInput = getMaxLength(currentInput));
                    if (remaining <= 0 && (event.keyCode !== 46 && event.keyCode !== 8)) {
                        return false;
                    }
                });
            });
        }
    });
}(jQuery));
<|endoftext|>