<commit_before>userJailed = "";
gameServerAddress = "http://fusiongame.tk/";

function getAllStats() {
    var xhrStats = new XMLHttpRequest();
    var stats = "";
    var divContents = "";
    var isDiv = false;

    xhrStats.open("GET", "/stats.json", true);
    xhrStats.send();
    xhrStats.onreadystatechange = function() {
        if (xhrStats.readyState == 4 && xhrStats.status == 200) {
            stats = xhrStats.responseText;
            stats = JSON.parse(stats);
            if (document.getElementById("stats")) {
                isDiv = true;
                var statsDiv = document.getElementById("stats");
            }

            if(stats["roundName"] != null) {
                divContents += "

	Tabatud	Puude	Miinus	Skoor
";
                for(i in stats["teams"]) {
                    team = stats["teams"][i];
                    divContents += "
"+team["name"]+"	"+team["spotCount"]+"	"+team["touchCount"]+"	"+team["disloyality"]+"	"+team["score"]+"
";
                    for (i in team["players"]) {
                        player = team["players"][i];
                        divContents += "
"+player["name"]+"	"+player["spotCount"]+"	"+player["touchCount"]+"	"+player["disloyality"]+"	"+player["score"]+"
";
                    }
                }
                divContents += "
";
                divContents += "

";
                if (isDiv) {
                    statsDiv.innerHTML = divContents;
                }
            } else {
                if (isDiv) {
                    statsDiv.innerHTML = "";
                }
            }
        }
    }
}

function getAllEvents() {
    var xhrEvents = new XMLHttpRequest();
    var events = "";
    var divContents = "";
    var isDiv = false;

    if (document.getElementById("events")) {
        var eventsDiv = document.getElementById("events");
        isDiv = true;
    }

    xhrEvents.open("GET", "/events.json", true);
    xhrEvents.send();
    xhrEvents.onreadystatechange = function() {
        if (xhrEvents.readyState == 4 && xhrEvents.status == 200) {
            events = xhrEvents.responseText;
            events = JSON.parse(events);
            if("event" in events[0]) {
                console.log("No events to show");
                if (isDiv) {
                    eventsDiv.innerHTML = "";
                }
            } else {
                eventsDiv.innerHTML = divContents;
                for(i in events) {
                    event = events[i];
                    if (event["visible"] == "All") {
                        divContents += "
"+event["time"];
                        divContents += " "+event["text1"]["text"]+"";
                        divContents += " "+event["text2"]["text"]+"";
                        if (event["text3"]["text"] != null) {
                            divContents += " "+event["text3"]["text"]+"";
                        }
                        divContents += "
";
                    }
                }
                if (isDiv) {
                    eventsDiv.innerHTML = divContents;
                }
            }
        }
    }
}

function getRoundInfoBase(role) {
    var xhrRound = new XMLHttpRequest();
    var stats = "";
    var user = "";
    var divContents = "";
    var isDiv = false;

    if (document.getElementById("roundInfo")) {
        var roundDiv = document.getElementById("roundInfo");
        isDiv = true;
    }

    xhrRound.open("GET", "/stats.json", true);
    xhrRound.send();
    xhrRound.onreadystatechange = function() {
        if (xhrRound.readyState == 4 && xhrRound.status == 200) {
            stats = xhrRound.responseText;
            stats = JSON.parse(stats);
            if(stats["roundName"] != null) {
                divContents += "
Lahing \"" + stats["roundName"] + "\", Kasutaja: " + role + "
";
                if (isDiv) {
                    roundDiv.innerHTML = divContents;
                }
            }
        }
    }
}

function getStats() {
    var xhrStats = new XMLHttpRequest();
    var xhrPlayer = new XMLHttpRequest();
    var stats = "";
    var user = "";
    var divContents = "";
    var isDiv = false;

    xhrPlayer.open("GET", "/user", true);
    xhrPlayer.send();
    xhrPlayer.onreadystatechange = function() {
        if (xhrPlayer.readyState == 4 && xhrPlayer.status == 200) {
            user = xhrPlayer.responseText;
        }
    }

    xhrStats.open("GET", "/stats.json", true);
    xhrStats.send();
    xhrStats.onreadystatechange = function() {
        if (xhrStats.readyState == 4 && xhrStats.status == 200) {
            stats = xhrStats.responseText;
            stats = JSON.parse(stats);
            if (document.getElementById("stats")) {
                isDiv = true;
                var statsDiv = document.getElementById("stats");
            }

            if(stats["roundName"] != null) {
                divContents += "

	Tabatud	Puude	Miinus	Skoor
";
                for(i in stats["teams"]) {
                    team = stats["teams"][i];
                    divContents += "
"+team["name"]+"	"+team["spotCount"]+"	"+team["touchCount"]+"	"+team["disloyality"]+"	"+team["score"]+"
";
                }
                for(i in stats["teams"]) {
                    team = stats["teams"][i];
                    for (i in team["players"]) {
                        player = team["players"][i];
                        if (player["name"] == user) {
                            divContents += "
"+player["name"]+"	"+player["spotCount"]+"	"+player["touchCount"]+"	"+player["disloyality"]+"	"+player["score"]+"

";
                        }
                    }
                }
                for(i in stats["teamlessPlayers"]) {
                    player = stats["teamlessPlayers"][i];
                    if(player["name"] == user) {
                        divContents += "
"+player["name"]+"	"+player["spotCount"]+"	"+player["touchCount"]+"	"+player["disloyality"]+"	"+player["score"]+"

";
                    }
                }
                divContents += "

";
                if (isDiv) {
                    statsDiv.innerHTML = divContents;
                }
            } else {
                if (isDiv) {
                    statsDiv.innerHTML = "";
                }
            }
        }
    }
}

function getEvents() {
    var xhrEvents = new XMLHttpRequest();
    var xhrPlayer = new XMLHttpRequest();
    var xhrTeam = new XMLHttpRequest();
    var events = "";
    var user = "";
    var userTeam = "";
    var divContents = "";
    var isDiv = false;

    if (document.getElementById("events")) {
        var eventsDiv = document.getElementById("events");
        isDiv = true;
    }

    xhrPlayer.open("GET", "/user", true);
    xhrPlayer.send();
    xhrPlayer.onreadystatechange = function() {
        if (xhrPlayer.readyState == 4 && xhrPlayer.status == 200) {
            user = xhrPlayer.responseText;
        }
    }

    xhrTeam.open("GET", "/userTeam", true);
    xhrTeam.send();
    xhrTeam.onreadystatechange = function() {
        if (xhrTeam.readyState == 4 && xhrTeam.status == 200) {
            userTeam = xhrTeam.responseText;
        }
    }

    xhrEvents.open("GET", "/events.json", true);
    xhrEvents.send();
    xhrEvents.onreadystatechange = function() {
        if (xhrEvents.readyState == 4 && xhrEvents.status == 200) {
            events = xhrEvents.responseText;
            events = JSON.parse(events);
            if("event" in events[0]) {
                console.log("No events to show");
                if (isDiv) {
                    eventsDiv.innerHTML = "";
                }
            } else {
                for(i in events) {
                    event = events[i];
                    if (event["visible"] == "All" || (event["visible"] == "Sinised" && userTeam == "1") || (event["visible"] == "Punased" && userTeam == "2")) {
                        divContents += "
"+event["time"];
                        divContents += " "+event["text1"]["text"]+"";
                        divContents += " "+event["text2"]["text"]+"";
                        if (event["text3"]["text"] != null) {
                            divContents += " "+event["text3"]["text"]+"";
                        }
                        divContents += "
";
                    }
                }
                if (isDiv) {
                    eventsDiv.innerHTML = divContents;
                }
            }
        }
    }
}

function getRoundInfo() {
    var xhrRound = new XMLHttpRequest();
    var xhrPlayer = new XMLHttpRequest();
    var stats = "";
    var user = "";
    var divContents = "";
    var isDiv = false;

    if (document.getElementById("roundInfo")) {
        var roundDiv = document.getElementById("roundInfo");
        isDiv = true;
    }

    xhrPlayer.open("GET", "/user", true);
    xhrPlayer.send();
    xhrPlayer.onreadystatechange = function() {
        if (xhrPlayer.readyState == 4 && xhrPlayer.status == 200) {
            user = xhrPlayer.responseText;
        }
    }

    xhrRound.open("GET", "/stats.json", true);
    xhrRound.send();
    xhrRound.onreadystatechange = function() {
        if (xhrRound.readyState == 4 && xhrRound.status == 200) {
            stats = xhrRound.responseText;
            stats = JSON.parse(stats);
            if(stats["roundName"] != null) {
                divContents += "
Lahing \"" + stats["roundName"] + "\", mängija: " + user +"
";
                if (isDiv) {
                    roundDiv.innerHTML = divContents;
                }
            }
        }
    }
}

function timeToEnd() {
    var xhrTime = new XMLHttpRequest();
    currentDate = new Date();
    var isDiv = false;

    if (document.getElementById("roundInfo")) {
        var roundDiv = document.getElementById("roundInfo");
        isDiv = true;
    }

    xhrTime.open("GET", "/stats.json", true);
    xhrTime.send();
    xhrTime.onreadystatechange = function() {
        if (xhrTime.readyState == 4 && xhrTime.status == 200) {
            stats = xhrTime.responseText;
            stats = JSON.parse(stats);
            if(stats["roundName"] != null) {
                var ending = stats["roundEnd"];
                endTime = new Date(ending.substring(0,4),ending.substring(5,7),ending.substring(8,10),ending.substring(11,13),ending.substring(14,16),ending.substring(17,19));
                var timeDiv = document.getElementById("toEnd");
                var toEnd = new Date(endTime.getTime() - currentDate.getTime());
                var divContents = "Aega vooru lõpuni " + addZerobefore(toEnd.getUTCHours()) + ":" + addZerobefore(toEnd.getUTCMinutes()) + ":" + addZerobefore(toEnd.getUTCSeconds());
                if (isDiv) {
                    timeDiv.innerHTML = divContents;
                }
            }
        }
    }
}

function isJailed() {
    if (document.getElementById("isJailed")) {
        $.ajax({
            url: "isJailed"
        }).done(function(data) {
            userJailed = data;
        });
    }
}

function addZerobefore(number) {
    if(parseInt(number) < 10 && parseInt(number) > -10) {
        number = "0" + parseInt(number);
    }
    return number;
}
<commit_msg>Not hardcoded host name<commit_after>userJailed = "";
gameServerAddress = window.location.origin + "/";

function getAllStats() {
    var xhrStats = new XMLHttpRequest();
    var stats = "";
    var divContents = "";
    var isDiv = false;

    xhrStats.open("GET", "/stats.json", true);
    xhrStats.send();
    xhrStats.onreadystatechange = function() {
        if (xhrStats.readyState == 4 && xhrStats.status == 200) {
            stats = xhrStats.responseText;
            stats = JSON.parse(stats);
            if (document.getElementById("stats")) {
                isDiv = true;
                var statsDiv = document.getElementById("stats");
            }

            if(stats["roundName"] != null) {
                divContents += "

	Tabatud	Puude	Miinus	Skoor
";
                for(i in stats["teams"]) {
                    team = stats["teams"][i];
                    divContents += "
"+team["name"]+"	"+team["spotCount"]+"	"+team["touchCount"]+"	"+team["disloyality"]+"	"+team["score"]+"
";
                    for (i in team["players"]) {
                        player = team["players"][i];
                        divContents += "
"+player["name"]+"	"+player["spotCount"]+"	"+player["touchCount"]+"	"+player["disloyality"]+"	"+player["score"]+"
";
                    }
                }
                divContents += "
";
                divContents += "

";
                if (isDiv) {
                    statsDiv.innerHTML = divContents;
                }
            } else {
                if (isDiv) {
                    statsDiv.innerHTML = "";
                }
            }
        }
    }
}

function getAllEvents() {
    var xhrEvents = new XMLHttpRequest();
    var events = "";
    var divContents = "";
    var isDiv = false;

    if (document.getElementById("events")) {
        var eventsDiv = document.getElementById("events");
        isDiv = true;
    }

    xhrEvents.open("GET", "/events.json", true);
    xhrEvents.send();
    xhrEvents.onreadystatechange = function() {
        if (xhrEvents.readyState == 4 && xhrEvents.status == 200) {
            events = xhrEvents.responseText;
            events = JSON.parse(events);
            if("event" in events[0]) {
                console.log("No events to show");
                if (isDiv) {
                    eventsDiv.innerHTML = "";
                }
            } else {
                eventsDiv.innerHTML = divContents;
                for(i in events) {
                    event = events[i];
                    if (event["visible"] == "All") {
                        divContents += "
"+event["time"];
                        divContents += " "+event["text1"]["text"]+"";
                        divContents += " "+event["text2"]["text"]+"";
                        if (event["text3"]["text"] != null) {
                            divContents += " "+event["text3"]["text"]+"";
                        }
                        divContents += "
";
                    }
                }
                if (isDiv) {
                    eventsDiv.innerHTML = divContents;
                }
            }
        }
    }
}

function getRoundInfoBase(role) {
    var xhrRound = new XMLHttpRequest();
    var stats = "";
    var user = "";
    var divContents = "";
    var isDiv = false;

    if (document.getElementById("roundInfo")) {
        var roundDiv = document.getElementById("roundInfo");
        isDiv = true;
    }

    xhrRound.open("GET", "/stats.json", true);
    xhrRound.send();
    xhrRound.onreadystatechange = function() {
        if (xhrRound.readyState == 4 && xhrRound.status == 200) {
            stats = xhrRound.responseText;
            stats = JSON.parse(stats);
            if(stats["roundName"] != null) {
                divContents += "
Lahing \"" + stats["roundName"] + "\", Kasutaja: " + role + "
";
                if (isDiv) {
                    roundDiv.innerHTML = divContents;
                }
            }
        }
    }
}

function getStats() {
    var xhrStats = new XMLHttpRequest();
    var xhrPlayer = new XMLHttpRequest();
    var stats = "";
    var user = "";
    var divContents = "";
    var isDiv = false;

    xhrPlayer.open("GET", "/user", true);
    xhrPlayer.send();
    xhrPlayer.onreadystatechange = function() {
        if (xhrPlayer.readyState == 4 && xhrPlayer.status == 200) {
            user = xhrPlayer.responseText;
        }
    }

    xhrStats.open("GET", "/stats.json", true);
    xhrStats.send();
    xhrStats.onreadystatechange = function() {
        if (xhrStats.readyState == 4 && xhrStats.status == 200) {
            stats = xhrStats.responseText;
            stats = JSON.parse(stats);
            if (document.getElementById("stats")) {
                isDiv = true;
                var statsDiv = document.getElementById("stats");
            }

            if(stats["roundName"] != null) {
                divContents += "

	Tabatud	Puude	Miinus	Skoor
";
                for(i in stats["teams"]) {
                    team = stats["teams"][i];
                    divContents += "
"+team["name"]+"	"+team["spotCount"]+"	"+team["touchCount"]+"	"+team["disloyality"]+"	"+team["score"]+"
";
                }
                for(i in stats["teams"]) {
                    team = stats["teams"][i];
                    for (i in team["players"]) {
                        player = team["players"][i];
                        if (player["name"] == user) {
                            divContents += "
"+player["name"]+"	"+player["spotCount"]+"	"+player["touchCount"]+"	"+player["disloyality"]+"	"+player["score"]+"

";
                        }
                    }
                }
                for(i in stats["teamlessPlayers"]) {
                    player = stats["teamlessPlayers"][i];
                    if(player["name"] == user) {
                        divContents += "
"+player["name"]+"	"+player["spotCount"]+"	"+player["touchCount"]+"	"+player["disloyality"]+"	"+player["score"]+"

";
                    }
                }
                divContents += "

";
                if (isDiv) {
                    statsDiv.innerHTML = divContents;
                }
            } else {
                if (isDiv) {
                    statsDiv.innerHTML = "";
                }
            }
        }
    }
}

function getEvents() {
    var xhrEvents = new XMLHttpRequest();
    var xhrPlayer = new XMLHttpRequest();
    var xhrTeam = new XMLHttpRequest();
    var events = "";
    var user = "";
    var userTeam = "";
    var divContents = "";
    var isDiv = false;

    if (document.getElementById("events")) {
        var eventsDiv = document.getElementById("events");
        isDiv = true;
    }

    xhrPlayer.open("GET", "/user", true);
    xhrPlayer.send();
    xhrPlayer.onreadystatechange = function() {
        if (xhrPlayer.readyState == 4 && xhrPlayer.status == 200) {
            user = xhrPlayer.responseText;
        }
    }

    xhrTeam.open("GET", "/userTeam", true);
    xhrTeam.send();
    xhrTeam.onreadystatechange = function() {
        if (xhrTeam.readyState == 4 && xhrTeam.status == 200) {
            userTeam = xhrTeam.responseText;
        }
    }

    xhrEvents.open("GET", "/events.json", true);
    xhrEvents.send();
    xhrEvents.onreadystatechange = function() {
        if (xhrEvents.readyState == 4 && xhrEvents.status == 200) {
            events = xhrEvents.responseText;
            events = JSON.parse(events);
            if("event" in events[0]) {
                console.log("No events to show");
                if (isDiv) {
                    eventsDiv.innerHTML = "";
                }
            } else {
                for(i in events) {
                    event = events[i];
                    if (event["visible"] == "All" || (event["visible"] == "Sinised" && userTeam == "1") || (event["visible"] == "Punased" && userTeam == "2")) {
                        divContents += "
"+event["time"];
                        divContents += " "+event["text1"]["text"]+"";
                        divContents += " "+event["text2"]["text"]+"";
                        if (event["text3"]["text"] != null) {
                            divContents += " "+event["text3"]["text"]+"";
                        }
                        divContents += "
";
                    }
                }
                if (isDiv) {
                    eventsDiv.innerHTML = divContents;
                }
            }
        }
    }
}

function getRoundInfo() {
    var xhrRound = new XMLHttpRequest();
    var xhrPlayer = new XMLHttpRequest();
    var stats = "";
    var user = "";
    var divContents = "";
    var isDiv = false;

    if (document.getElementById("roundInfo")) {
        var roundDiv = document.getElementById("roundInfo");
        isDiv = true;
    }

    xhrPlayer.open("GET", "/user", true);
    xhrPlayer.send();
    xhrPlayer.onreadystatechange = function() {
        if (xhrPlayer.readyState == 4 && xhrPlayer.status == 200) {
            user = xhrPlayer.responseText;
        }
    }

    xhrRound.open("GET", "/stats.json", true);
    xhrRound.send();
    xhrRound.onreadystatechange = function() {
        if (xhrRound.readyState == 4 && xhrRound.status == 200) {
            stats = xhrRound.responseText;
            stats = JSON.parse(stats);
            if(stats["roundName"] != null) {
                divContents += "
Lahing \"" + stats["roundName"] + "\", mängija: " + user +"
";
                if (isDiv) {
                    roundDiv.innerHTML = divContents;
                }
            }
        }
    }
}

function timeToEnd() {
    var xhrTime = new XMLHttpRequest();
    currentDate = new Date();
    var isDiv = false;

    if (document.getElementById("roundInfo")) {
        var roundDiv = document.getElementById("roundInfo");
        isDiv = true;
    }

    xhrTime.open("GET", "/stats.json", true);
    xhrTime.send();
    xhrTime.onreadystatechange = function() {
        if (xhrTime.readyState == 4 && xhrTime.status == 200) {
            stats = xhrTime.responseText;
            stats = JSON.parse(stats);
            if(stats["roundName"] != null) {
                var ending = stats["roundEnd"];
                endTime = new Date(ending.substring(0,4),ending.substring(5,7),ending.substring(8,10),ending.substring(11,13),ending.substring(14,16),ending.substring(17,19));
                var timeDiv = document.getElementById("toEnd");
                var toEnd = new Date(endTime.getTime() - currentDate.getTime());
                var divContents = "Aega vooru lõpuni " + addZerobefore(toEnd.getUTCHours()) + ":" + addZerobefore(toEnd.getUTCMinutes()) + ":" + addZerobefore(toEnd.getUTCSeconds());
                if (isDiv) {
                    timeDiv.innerHTML = divContents;
                }
            }
        }
    }
}

function isJailed() {
    if (document.getElementById("isJailed")) {
        $.ajax({
            url: "isJailed"
        }).done(function(data) {
            userJailed = data;
        });
    }
}

function addZerobefore(number) {
    if(parseInt(number) < 10 && parseInt(number) > -10) {
        number = "0" + parseInt(number);
    }
    return number;
}
<|endoftext|>


<commit_before>/* globals require */
/* jshint esversion: 6 */

const os = require('os');
const path = require('path');
const process = require('process');
const fs = require('fs');
const del = require('del');
const _ = require('lodash');
const mkdirp = require('mkdirp');
const gulp = require('gulp');
const help = require('gulp-help-four');
const gulpWatch = require('gulp-watch');
const livereload = require('gulp-livereload');
const connect = require('connect');
const serverStatic = require('serve-static');
const opn = require('opn');
const rename = require('gulp-rename');
const textTransform = require('gulp-text-simple');
const lazypipe = require('lazypipe');
const merge = require('merge-stream');
const mdproc = require('mdproc');
const mdinclude = require('mdinclude');
const mdquery = require('mdquery').transform;
<% if (needsGlob) { %>var glob = require('glob');
<% } if (needsDateFormat) { %>var dateFormat = require('dateformat');
<% } if (needsExec) { %>var exec = require('gulp-exec');
<% } %>
help(gulp, { hideEmpty: true });

const preProcess = textTransform(require('./config/preprocessing.js'));
const htmlPostProcess = textTransform(require('./config/html-postprocessing.js'));
var injectLiveReload = false;

function setTerminalTitle(title) {
	process.stdout.write(String.fromCharCode(27) + "]0;" + title + String.fromCharCode(7));
}

function loadConfig() {
	return JSON.parse(fs.readFileSync('./config/mdproc.json', 'utf8'));
}

function loadGraphs() {
	return JSON.parse(fs.readFileSync('./config/graphs.json', 'utf8'));
}

function runTask(taskFn) {
	taskFn(function () {});
}

function markdownPipeline(opt) {
	var cfg = loadConfig();
	return lazypipe()
		.pipe(mdinclude)
		.pipe(mdquery)
		.pipe(mdproc.references, { prefixCaption: opt.prefixCaption })
		.pipe(mdproc.badges)
		.pipe(preProcess, {cfg: cfg})
		();
}

function graphextract(prefixCaption, imgFormat, cb) {
	var graphs = loadGraphs();
	if (graphs.autograph.sources.length > 0) {
		var tasks = _.map(graphs.autograph.sources, function (g) {
			var opt = _.assign(
				{ imgFormat: imgFormat },
				g.options);
			return gulp.src(g.sourceFile)
				.pipe(markdownPipeline({ prefixCaption: prefixCaption }))
				.pipe(mdproc.autograph(opt))
				.pipe(rename({ basename: g.name }))
				.pipe(gulp.dest(graphs.autograph.target));
		});
		return merge(tasks);
	} else {
		cb();
	}
}

function dotex(prefixCaption, imgFormat, cb) {
	var graphs = loadGraphs();
	if (graphs.dotex.sources.length) {
		var tasks = _.map(graphs.dotex.sources, function (g) {
			var opt = _.assign(
				{ imgFormat: imgFormat },
				g.options);
			return gulp.src(g.sourceFile)
				.pipe(markdownPipeline({ prefixCaption: prefixCaption }))
				.pipe(mdproc.dotex(opt))
				.pipe(rename({ basename: g.name }))
				.pipe(gulp.dest(graphs.dotex.target));
		});
		return merge(tasks);
	} else {
		cb();
	}
}

function clean(cb) {
	var cfg = loadConfig();
	del.sync(cfg.target_dir);

	var graphs = loadGraphs();
	if (graphs.autograph.target) {
		del.sync(graphs.autograph.target);
	}
	if (graphs.dotex.target) {
		del.sync(graphs.dotex.target);
	}
	cb();
}

function copyImages() {
	var cfg = loadConfig();
	return gulp.src(cfg.image_files, { base: 'src' })
		.pipe(gulp.dest(cfg.target_dir));
}

function autographSvg(cb) { return graphextract(true, 'svg', cb); }
function dotexSvg(cb) { return dotex(true, 'svg', cb); }
const imagesSvg = gulp.parallel(autographSvg, dotexSvg);

function autographPng(cb) { return graphextract(true, 'png', cb); }
function dotexPng(cb) { return dotex(true, 'png', cb); }
const imagesPng = gulp.parallel(autographPng, dotexPng);
<% if (supportPdf) { %>
function autographPdf(cb) { return graphextract(false, 'pdf', cb); }
function dotexPdf(cb) { return dotex(true, 'pdf', cb); }
const imagesPdf = gulp.parallel(autographPdf, dotexPdf);
<% } %>
function html() {
	var cfg = loadConfig();
	cfg.injectLiveReload = injectLiveReload;
	return gulp.src(cfg.markdown_files)
		.pipe(markdownPipeline({ prefixCaption: true }))
		.pipe(mdproc.md2html(_.assign({ basePath: 'src' }, cfg.options, cfg.md2html_options)))
		.pipe(htmlPostProcess({cfg: cfg}))
		.pipe(gulp.dest(cfg.target_dir))
		.pipe(livereload());
}

function docx() {
	var cfg = loadConfig();
	return gulp.src(cfg.markdown_files)
		.pipe(markdownPipeline({ prefixCaption: true }))
		.pipe(mdproc.md2docx(_.assign({}, cfg.options, cfg.md2docx_options)))
		.pipe(gulp.dest(cfg.target_dir));
}
<% if (supportPdf) { %>
function tex() {
	var cfg = loadConfig();
	return gulp.src(cfg.markdown_files)
		.pipe(markdownPipeline({ prefixCaption: false }))
		.pipe(mdproc.md2tex(_.assign({}, cfg.options, cfg.md2tex_options || cfg.md2pdf_options)))
		.pipe(gulp.dest(cfg.target_dir));
}

function pdf() {
	var cfg = loadConfig();
	return gulp.src(cfg.markdown_files)
		.pipe(markdownPipeline({ prefixCaption: false }))
		.pipe(mdproc.md2pdf(_.assign({}, cfg.options, cfg.md2pdf_options)))
		.pipe(gulp.dest(cfg.target_dir));
}
<% } %>
const formatTasks = {
	'html': html,
	'docx': docx,
<% if (supportPdf) { %>	'tex': tex,
	'pdf': pdf
<% } %>};

const all =
	gulp.series(
		gulp.parallel(imagesSvg, imagesPng<% if (supportPdf) { %>, imagesPdf<% } %>),
		copyImages,
		gulp.series(html, docx<% if (supportPdf) { %>, tex, pdf<% } %>));

const autobuildTasks =
	_.map(loadConfig().default_formats,
		function(taskName) { return formatTasks[taskName]; });
const autobuild = _.spread(gulp.series)(autobuildTasks);

function openMainFile(cb) {
	const cfg = loadConfig();
	opn(path.resolve(path.join(process.cwd(), cfg.target_dir, cfg.main + '.html')),
		cfg.default_browser ? { app: cfg.default_browser } : undefined);
	cb();
}

function watch() {
	setTerminalTitle('MdProc watch - ' + __dirname);
	const cfg = loadConfig();
	return watch(cfg.watched_files,
		{ verbose: true, readDelay: 200 },
		function () {
			try {
				runTask(autobuild);
			} catch(err) {
				console.log('ERROR: ' + err.message);
			}
		});
}

function openLivereload(cb) {
	const cfg = loadConfig();
	opn('http://localhost:' + cfg.server_port + '/' + cfg.main + '.html',
		cfg.default_browser ? { app: cfg.default_browser } : undefined);
	cb();
}

function serve() {
	setTerminalTitle('MdProc serve - ' + __dirname);
	const cfg = loadConfig();
	injectLiveReload = true;
	runTask(html);
	const server = connect();
	server.use(serverStatic(cfg.target_dir));
	server.listen(cfg.server_port);
	livereload.listen({ port: cfg.livereload_port });
	setTimeout(function () { runTask(openLivereload); }, 1000);
	return gulpWatch(cfg.watched_files,
		{ verbose: true, readDelay: 200},
		function () {
			try {
				runTask(html);
			} catch(err) {
				console.log('ERROR: ' + err.message);
			}
		});
}

gulp.task('default', 'Build the output in the default formats', autobuild);
gulp.task('clean', 'Remove all generated output', clean);
gulp.task('copy-images', false, copyImages);
gulp.task('autograph:svg', false, autographSvg);
gulp.task('dotex:svg', false, dotexSvg);
gulp.task('images:svg', false, imagesSvg);
gulp.task('autograph:png', false, autographPng);
gulp.task('dotex:png', false, dotexPng);
gulp.task('images:png', false, imagesPng);
<% if (supportPdf) { %>gulp.task('autograph:pdf', false, autographPdf);
gulp.task('dotex:pdf', false, dotexPdf);
gulp.task('images:pdf', false, imagesPdf);
<% } %>gulp.task('html', 'Build the HTML output', gulp.series(imagesSvg, copyImages, html));
gulp.task('docx', 'Build the DOCX output', gulp.series(imagesPng, copyImages, docx));
<% if (supportPdf) { %>gulp.task('tex', 'Build the TeX output', gulp.series(imagesPdf, copyImages, tex));
gulp.task('pdf', 'Build the PDF output', gulp.series(imagesPdf, copyImages, pdf));
<% } %>gulp.task('all', 'Build the output in all formats', all);
gulp.task('autobuild', false, autobuild);
gulp.task('watch', 'Watch the source files and build automatically', gulp.series(autobuild, watch));
gulp.task('open-main-file', 'Show the HTML result of the main file in the default browser', openMainFile);
gulp.task('serve', 'Show HTML in default browser and refresh on changes', gulp.series(html, serve));
gulp.task('open-livereload', 'Show the livereload URL of the main file in the default browser', openLivereload);

<% if (projectType === 'Personal Log') { %>
function today(cb) {
	const now = new Date();
	const yearDir = path.join('src', 'log', dateFormat(now, 'yyyy'));
	const monthDir = path.join(yearDir, dateFormat(now, 'mm'));
	const entryFile = path.join(monthDir, dateFormat(now, 'yyyy-mm-dd') + '.md');
	const headline = '## ' + dateFormat('yyyy-mm-dd dddd') +
		' {#log_' + dateFormat('yyyy-mm-dd') + '}';
	const text = headline + os.EOL + os.EOL;
	mkdirp(monthDir, function (err) {
		if (err) {
			cb(err);
			return;
		}
		fs.stat(entryFile, function (err, stats) {
			if (err && err.code === 'ENOENT') {
				fs.writeFile(entryFile, text, 'utf8', cb);
			} else {
				cb(err);
			}
		});
	});
}
gulp.task('today', 'Create a new file for todays entries', today);
<% } %><commit_msg>run image generation before html compilation, optimize serve task<commit_after>/* globals require */
/* jshint esversion: 6 */

const os = require('os');
const path = require('path');
const process = require('process');
const fs = require('fs');
const del = require('del');
const _ = require('lodash');
const mkdirp = require('mkdirp');
const gulp = require('gulp');
const help = require('gulp-help-four');
const gulpWatch = require('gulp-watch');
const livereload = require('gulp-livereload');
const connect = require('connect');
const serverStatic = require('serve-static');
const opn = require('opn');
const rename = require('gulp-rename');
const textTransform = require('gulp-text-simple');
const lazypipe = require('lazypipe');
const merge = require('merge-stream');
const mdproc = require('mdproc');
const mdinclude = require('mdinclude');
const mdquery = require('mdquery').transform;
<% if (needsGlob) { %>var glob = require('glob');
<% } if (needsDateFormat) { %>var dateFormat = require('dateformat');
<% } if (needsExec) { %>var exec = require('gulp-exec');
<% } %>
help(gulp, { hideEmpty: true });

const preProcess = textTransform(require('./config/preprocessing.js'));
const htmlPostProcess = textTransform(require('./config/html-postprocessing.js'));
var injectLiveReload = false;

function setTerminalTitle(title) {
	process.stdout.write(String.fromCharCode(27) + "]0;" + title + String.fromCharCode(7));
}

function loadConfig() {
	return JSON.parse(fs.readFileSync('./config/mdproc.json', 'utf8'));
}

function loadGraphs() {
	return JSON.parse(fs.readFileSync('./config/graphs.json', 'utf8'));
}

function runTask(taskFn) {
	taskFn(function () {});
}

function markdownPipeline(opt) {
	var cfg = loadConfig();
	return lazypipe()
		.pipe(mdinclude)
		.pipe(mdquery)
		.pipe(mdproc.references, { prefixCaption: opt.prefixCaption })
		.pipe(mdproc.badges)
		.pipe(preProcess, {cfg: cfg})
		();
}

function graphextract(prefixCaption, imgFormat, cb) {
	var graphs = loadGraphs();
	if (graphs.autograph.sources.length > 0) {
		var tasks = _.map(graphs.autograph.sources, function (g) {
			var opt = _.assign(
				{ imgFormat: imgFormat },
				g.options);
			return gulp.src(g.sourceFile)
				.pipe(markdownPipeline({ prefixCaption: prefixCaption }))
				.pipe(mdproc.autograph(opt))
				.pipe(rename({ basename: g.name }))
				.pipe(gulp.dest(graphs.autograph.target));
		});
		return merge(tasks);
	} else {
		cb();
	}
}

function dotex(prefixCaption, imgFormat, cb) {
	var graphs = loadGraphs();
	if (graphs.dotex.sources.length) {
		var tasks = _.map(graphs.dotex.sources, function (g) {
			var opt = _.assign(
				{ imgFormat: imgFormat },
				g.options);
			return gulp.src(g.sourceFile)
				.pipe(markdownPipeline({ prefixCaption: prefixCaption }))
				.pipe(mdproc.dotex(opt))
				.pipe(rename({ basename: g.name }))
				.pipe(gulp.dest(graphs.dotex.target));
		});
		return merge(tasks);
	} else {
		cb();
	}
}

function clean(cb) {
	var cfg = loadConfig();
	del.sync(cfg.target_dir);

	var graphs = loadGraphs();
	if (graphs.autograph.target) {
		del.sync(graphs.autograph.target);
	}
	if (graphs.dotex.target) {
		del.sync(graphs.dotex.target);
	}
	cb();
}

function copyImages() {
	var cfg = loadConfig();
	return gulp.src(cfg.image_files, { base: 'src' })
		.pipe(gulp.dest(cfg.target_dir));
}

function autographSvg(cb) { return graphextract(true, 'svg', cb); }
function dotexSvg(cb) { return dotex(true, 'svg', cb); }
const imagesSvg = gulp.parallel(autographSvg, dotexSvg);

function autographPng(cb) { return graphextract(true, 'png', cb); }
function dotexPng(cb) { return dotex(true, 'png', cb); }
const imagesPng = gulp.parallel(autographPng, dotexPng);
<% if (supportPdf) { %>
function autographPdf(cb) { return graphextract(false, 'pdf', cb); }
function dotexPdf(cb) { return dotex(true, 'pdf', cb); }
const imagesPdf = gulp.parallel(autographPdf, dotexPdf);
<% } %>
function html() {
	var cfg = loadConfig();
	cfg.injectLiveReload = injectLiveReload;
	return gulp.src(cfg.markdown_files)
		.pipe(markdownPipeline({ prefixCaption: true }))
		.pipe(mdproc.md2html(_.assign({ basePath: 'src' }, cfg.options, cfg.md2html_options)))
		.pipe(htmlPostProcess({cfg: cfg}))
		.pipe(gulp.dest(cfg.target_dir))
		.pipe(livereload());
}

function docx() {
	var cfg = loadConfig();
	return gulp.src(cfg.markdown_files)
		.pipe(markdownPipeline({ prefixCaption: true }))
		.pipe(mdproc.md2docx(_.assign({}, cfg.options, cfg.md2docx_options)))
		.pipe(gulp.dest(cfg.target_dir));
}
<% if (supportPdf) { %>
function tex() {
	var cfg = loadConfig();
	return gulp.src(cfg.markdown_files)
		.pipe(markdownPipeline({ prefixCaption: false }))
		.pipe(mdproc.md2tex(_.assign({}, cfg.options, cfg.md2tex_options || cfg.md2pdf_options)))
		.pipe(gulp.dest(cfg.target_dir));
}

function pdf() {
	var cfg = loadConfig();
	return gulp.src(cfg.markdown_files)
		.pipe(markdownPipeline({ prefixCaption: false }))
		.pipe(mdproc.md2pdf(_.assign({}, cfg.options, cfg.md2pdf_options)))
		.pipe(gulp.dest(cfg.target_dir));
}
<% } %>
const formatTasks = {
	'html': gulp.series(imagesSvg, copyImages, html),
	'docx': gulp.series(imagesPng, copyImages, docx),
<% if (supportPdf) { %>	'tex': gulp.series(imagesPdf, copyImages, tex),
	'pdf': gulp.series(imagesPdf, copyImages, pdf)
<% } %>};

const all =
	gulp.series(
		gulp.parallel(imagesSvg, imagesPng<% if (supportPdf) { %>, imagesPdf<% } %>),
		copyImages,
		gulp.series(html, docx<% if (supportPdf) { %>, tex, pdf<% } %>));

const autobuildTasks =
	_.map(loadConfig().default_formats,
		function(taskName) { return formatTasks[taskName]; });
const autobuild = _.spread(gulp.series)(autobuildTasks);

function openMainFile(cb) {
	const cfg = loadConfig();
	opn(path.resolve(path.join(process.cwd(), cfg.target_dir, cfg.main + '.html')),
		cfg.default_browser ? { app: cfg.default_browser } : undefined);
	cb();
}

function watch() {
	setTerminalTitle('MdProc watch - ' + __dirname);
	const cfg = loadConfig();
	return watch(cfg.watched_files,
		{ verbose: true, readDelay: 200 },
		function () {
			try {
				runTask(autobuild);
			} catch(err) {
				console.log('ERROR: ' + err.message);
			}
		});
}

function openLivereload(cb) {
	const cfg = loadConfig();
	opn('http://localhost:' + cfg.server_port + '/' + cfg.main + '.html',
		cfg.default_browser ? { app: cfg.default_browser } : undefined);
	cb();
}

function serve() {
	setTerminalTitle('MdProc serve - ' + __dirname);
	const cfg = loadConfig();
	injectLiveReload = true;
	runTask(html);
	const server = connect();
	server.use(serverStatic(cfg.target_dir));
	server.listen(cfg.server_port);
	livereload.listen({ port: cfg.livereload_port });
	setTimeout(function () { runTask(openLivereload); }, 1000);
	return gulpWatch(cfg.watched_files,
		{ verbose: true, readDelay: 200},
		function () {
			try {
				runTask(gulp.series(imagesSvg, copyImages, html));
			} catch(err) {
				console.log('ERROR: ' + err.message);
			}
		});
}

gulp.task('default', 'Build the output in the default formats', autobuild);
gulp.task('clean', 'Remove all generated output', clean);
gulp.task('copy-images', false, copyImages);
gulp.task('autograph:svg', false, autographSvg);
gulp.task('dotex:svg', false, dotexSvg);
gulp.task('images:svg', false, imagesSvg);
gulp.task('autograph:png', false, autographPng);
gulp.task('dotex:png', false, dotexPng);
gulp.task('images:png', false, imagesPng);
<% if (supportPdf) { %>gulp.task('autograph:pdf', false, autographPdf);
gulp.task('dotex:pdf', false, dotexPdf);
gulp.task('images:pdf', false, imagesPdf);
<% } %>gulp.task('html', 'Build the HTML output', gulp.series(imagesSvg, copyImages, html));
gulp.task('docx', 'Build the DOCX output', gulp.series(imagesPng, copyImages, docx));
<% if (supportPdf) { %>gulp.task('tex', 'Build the TeX output', gulp.series(imagesPdf, copyImages, tex));
gulp.task('pdf', 'Build the PDF output', gulp.series(imagesPdf, copyImages, pdf));
<% } %>gulp.task('all', 'Build the output in all formats', all);
gulp.task('autobuild', false, autobuild);
gulp.task('watch', 'Watch the source files and build automatically', gulp.series(autobuild, watch));
gulp.task('open-main-file', 'Show the HTML result of the main file in the default browser', openMainFile);
gulp.task('open-livereload', 'Show the livereload URL of the main file in the default browser', openLivereload);
gulp.task('serve', 'Show HTML in default browser and refresh on changes', gulp.series(imagesSvg, copyImages, serve));

<% if (projectType === 'Personal Log') { %>
function today(cb) {
	const now = new Date();
	const yearDir = path.join('src', 'log', dateFormat(now, 'yyyy'));
	const monthDir = path.join(yearDir, dateFormat(now, 'mm'));
	const entryFile = path.join(monthDir, dateFormat(now, 'yyyy-mm-dd') + '.md');
	const headline = '## ' + dateFormat('yyyy-mm-dd dddd') +
		' {#log_' + dateFormat('yyyy-mm-dd') + '}';
	const text = headline + os.EOL + os.EOL;
	mkdirp(monthDir, function (err) {
		if (err) {
			cb(err);
			return;
		}
		fs.stat(entryFile, function (err, stats) {
			if (err && err.code === 'ENOENT') {
				fs.writeFile(entryFile, text, 'utf8', cb);
			} else {
				cb(err);
			}
		});
	});
}
gulp.task('today', 'Create a new file for todays entries', today);
<% } %><|endoftext|>


<commit_before>enyo.kind({
	name: "onyx.sample.MenuSample",
	classes: "onyx onyx-sample",
	components: [
		{classes: "onyx-sample-divider", content: "Menus in Toolbars"},
		{kind: "onyx.Toolbar", classes: "onyx-menu-toolbar", components: [
			{kind: "onyx.MenuDecorator", onSelect: "itemSelected", components: [
				{kind: "onyx.IconButton", src: "assets/menu-icon-bookmark.png"},
				{kind: "onyx.Menu", components: [
					{components: [
						{kind: "onyx.IconButton", src: "assets/menu-icon-bookmark.png"},
						{content: "Bookmarks"}
					]},
					{content: "Favorites"},
					{classes: "onyx-menu-divider"},
					{content: "Recents"},
				]}
			]},
			{kind: "onyx.MenuDecorator", onSelect: "itemSelected", components: [
				{content: "Bookmarks menu"},
				{kind: "onyx.Menu", components: [
					{components: [
						{kind: "onyx.IconButton", src: "assets/menu-icon-bookmark.png"},
						{content: "Bookmarks"}
					]},
					{content: "Favorites"},
					{classes: "onyx-menu-divider"},
					{content: "Recents"},
				]}
			]}
		]},
		{tag: "br"},
		{classes: "onyx-sample-divider", content: "Menus from Buttons"},
		{kind: "onyx.MenuDecorator", onSelect: "itemSelected", components: [
			{content: "Popup menu (floating)"},
			{kind: "onyx.Menu", floating: true, components: [
				{content: "1"},
				{content: "2"},
				{classes: "onyx-menu-divider"},
				{content: "3"},
			]}
		]},
		{tag: "br"},
		{kind: "onyx.MenuDecorator", onSelect: "itemSelected", components: [
			{content: "Scrolling Popup menu"},
			{kind: "onyx.Menu", components: [
				{name: "menuScroller", kind: "enyo.Scroller", defaultKind: "onyx.MenuItem", vertical: "auto", classes: "enyo-unselectable", maxHeight: "200px", strategyKind: "TouchScrollStrategy", components: [
					{content: "1"},
					{content: "2"},
					{classes: "onyx-menu-divider"},
					{content: "3"},
					{content: "4"},
					{content: "5"},
					{classes: "onyx-menu-divider"},
					{content: "6"},
					{content: "7"},
				]}
			]}
		]},
		{tag: "br"},
		{kind: "onyx.MenuDecorator", onSelect: "itemSelected", components: [
			{content: "Split Popup menu", kind: "onyx.Button", onActivate: "preventMenuActivate", style: "border-radius: 3px 0 0 3px;"},
			{content: "▾", allowHtml:true, style: "border-radius: 0 3px 3px 0;"},
			{kind: "onyx.Menu", components: [
				{content: "1"},
				{content: "2"},
				{classes: "onyx-menu-divider"},
				{content: "3"},
			]}
		]},
		{tag: "br"},
		{kind: "onyx.Groupbox", classes:"onyx-sample-result-box", components: [
			{kind: "onyx.GroupboxHeader", content: "Result"},
			{name:"menuSelection", classes:"onyx-sample-result", content:"No menu selection yet."}
		]}
	],
	create: function() {
		this.inherited(arguments);
	},
	showPopup: function(inSender) {
		var p = this.$[inSender.popup];
		if (p) {
			p.show();
		}
	},
	preventMenuActivate: function() {
		return true;
	},
	itemSelected: function(inSender, inEvent) {
		//Menu items send an onSelect event with a reference to themselves & any directly displayed content
		if (inEvent.originator.content){
			this.$.menuSelection.setContent(inEvent.originator.content + " Selected");
		} else if (inEvent.selected){
			//	Since some of the menu items do not have directly displayed content (they are kinds with subcomponents),
			//	we have to handle those items differently here.
			this.$.menuSelection.setContent(inEvent.selected.controlAtIndex(1).content + " Selected");
		}
	}
});
<commit_msg>fix for ENYO-715<commit_after>enyo.kind({
	name: "onyx.sample.MenuSample",
	classes: "onyx onyx-sample",
	components: [
		{classes: "onyx-sample-divider", content: "Menus in Toolbars"},
		{kind: "onyx.Toolbar", classes: "onyx-menu-toolbar", components: [
			{kind: "onyx.MenuDecorator", onSelect: "itemSelected", components: [
				{kind: "onyx.IconButton", src: "assets/menu-icon-bookmark.png"},
				{kind: "onyx.Menu", components: [
					{components: [
						{kind: "onyx.IconButton", src: "assets/menu-icon-bookmark.png"},
						{content: "Bookmarks"}
					]},
					{content: "Favorites"},
					{classes: "onyx-menu-divider"},
					{content: "Recents"},
				]}
			]},
			{kind: "onyx.MenuDecorator", onSelect: "itemSelected", components: [
				{content: "Bookmarks menu"},
				{kind: "onyx.Menu", components: [
					{components: [
						{kind: "onyx.IconButton", src: "assets/menu-icon-bookmark.png"},
						{content: "Bookmarks"}
					]},
					{content: "Favorites"},
					{classes: "onyx-menu-divider"},
					{content: "Recents"},
				]}
			]}
		]},
		{tag: "br"},
		{classes: "onyx-sample-divider", content: "Menus from Buttons"},
		{kind: "onyx.MenuDecorator", onSelect: "itemSelected", components: [
			{content: "Popup menu (floating)"},
			{kind: "onyx.Menu", floating: true, components: [
				{content: "1"},
				{content: "2"},
				{classes: "onyx-menu-divider"},
				{content: "3"},
			]}
		]},
		{tag: "br"},
		{kind: "onyx.MenuDecorator", onSelect: "itemSelected", components: [
			{content: "Scrolling Popup menu"},
			{kind: "onyx.Menu", components: [
				{name: "menuScroller", kind: "enyo.Scroller", defaultKind: "onyx.MenuItem", vertical: "auto", classes: "enyo-unselectable", maxHeight: "200px", strategyKind: "TouchScrollStrategy", components: [
					{content: "1"},
					{content: "2"},
					{classes: "onyx-menu-divider"},
					{content: "3"},
					{content: "4"},
					{content: "5"},
					{classes: "onyx-menu-divider"},
					{content: "6"},
					{content: "7"},
				]}
			]}
		]},
		{tag: "br"},
		{kind: "onyx.MenuDecorator", onSelect: "itemSelected", components: [
			{content: "Split Popup menu", kind: "onyx.Button", onActivate: "preventMenuActivate", style: "border-radius: 3px 0 0 3px;"},
			{content: "v", allowHtml:true, style: "border-radius: 0 3px 3px 0;"},
			{kind: "onyx.Menu", components: [
				{content: "1"},
				{content: "2"},
				{classes: "onyx-menu-divider"},
				{content: "3"},
			]}
		]},
		{tag: "br"},
		{kind: "onyx.Groupbox", classes:"onyx-sample-result-box", components: [
			{kind: "onyx.GroupboxHeader", content: "Result"},
			{name:"menuSelection", classes:"onyx-sample-result", content:"No menu selection yet."}
		]}
	],
	create: function() {
		this.inherited(arguments);
	},
	showPopup: function(inSender) {
		var p = this.$[inSender.popup];
		if (p) {
			p.show();
		}
	},
	preventMenuActivate: function() {
		return true;
	},
	itemSelected: function(inSender, inEvent) {
		//Menu items send an onSelect event with a reference to themselves & any directly displayed content
		if (inEvent.originator.content){
			this.$.menuSelection.setContent(inEvent.originator.content + " Selected");
		} else if (inEvent.selected){
			//	Since some of the menu items do not have directly displayed content (they are kinds with subcomponents),
			//	we have to handle those items differently here.
			this.$.menuSelection.setContent(inEvent.selected.controlAtIndex(1).content + " Selected");
		}
	}
});
<|endoftext|>


<commit_before>/* global, GF */

/////////////////////////////////////
//// 	Finding a String
/////////////////////////////////////

/*
 * Here we will be using Genev to find the string contained in ourString"
 * The code here is just a variation of the helloWorld.js code
 */

var ourString = 'Some string...';

// Our CHROMO_STRUCTURE
var chromosome = { // holds weights from 0 to 1
  genes: {}
};

// We'll give it a gene for each letter in the string
for (var i = 0; i < ourString.length; i += 1) {
  var geneCode = 'gene' + i; // some unique gene key
  chromosome.genes[geneCode] = 0; // set it to some val
}

/** Our fitness function
 * Returns a score for the chromosome
 * Needs to calculate how fit the chromosome is,
 * The higher the score, the more fit the chromosome.
 */
var fitfunc = function(genes) {
  // every character matched will increment the score by 1
  var property, score = 0, i = 0;
  // lucky for us this loops the same order we initalized chromosome (and genes is the same), so: gene1, gene2.. and so on
  for (property in genes) {
    var geneChar = String.fromCharCode(Math.floor(genes[property] * 255)); // This is the char we get from the weight
    if (ourString.charAt(i) === geneChar) {
      score += 1;
    }
    i += 1; // the property corresponds with the character in ith position
  }
  return score; // 0 - ourString.length, each correct char is 1 point
};

var printReadable = function(population) {
  console.log('Generation #' + population[0].generation);
  for (var i = 0; i < 1; i += 1) {
    var string = '';
    var property;
    for (property in population[i].genes) {
      var geneChar = String.fromCharCode(Math.floor(population[i].genes[property] * 255));
      string += geneChar;
    }
    console.log('#' + i + ' ' + string);
  }
};

var onNewGen = function(pop) {
  printReadable(pop);
};

/** Some option changes (defaults are lame)
 * Increased generations and mutation probability
 */
var options = {
  maxGenerations: 1000,
  mutationProb: 0.1382005272898823, // 13% mutation
  maxPopulation: 251,
  numToSelect: 37,
  exitScore: ourString.length, // The highest score possible is the length of our string
  onNewGen: onNewGen
};

/** Our genev object initialized with our CHROMO_STRUCTURE */
var findString = GF(chromosome, options);

/* Init it with your own population or it will generate random ones */
findString.initPopulation(); // generates random population

// Population before evolving
printReadable(findString.getPopulation());

findString.evolve(options, fitfunc); // you can also pass in the options here again.

// Population after evolving
printReadable(findString.getPopulation());
/* Some extra notes

*/<commit_msg>Update docs<commit_after>/* global, GF */

/////////////////////////////////////
//// 	Finding a String
/////////////////////////////////////

/*
 * Here we will be using Genev to find the string contained in ourString"
 * The code here is just a variation of the helloWorld.js code
 */

var ourString = 'Some string...';

// Our CHROMO_STRUCTURE
var chromosome = { // holds weights from 0 to 1
  genes: {}
};

// We'll give it a gene for each letter in the string
for (var i = 0; i < ourString.length; i += 1) {
  var geneCode = 'gene' + i; // some unique gene key
  chromosome.genes[geneCode] = 0; // set it to some val
}

/** Our fitness function
 * Returns a score for the chromosome
 * Needs to calculate how fit the chromosome is,
 * The higher the score, the more fit the chromosome.
 */
var fitfunc = function(genes) {
  // every character matched will increment the score by 1
  var property, score = 0, i = 0;
  // lucky for us this loops the same order we initalized chromosome (and genes is the same), so: gene1, gene2.. and so on
  for (property in genes) {
    var geneChar = String.fromCharCode(Math.floor(genes[property] * 255)); // This is the char we get from the weight
    if (ourString.charAt(i) === geneChar) {
      score += 1;
    }
    i += 1; // the property corresponds with the character in ith position
  }
  return score; // 0 to ourString.length, each correct char is 1 point
};

var printReadable = function(population) {
  console.log('Generation #' + population[0].generation);
  for (var i = 0; i < 1; i += 1) {
    var string = '';
    var property;
    for (property in population[i].genes) {
      var geneChar = String.fromCharCode(Math.floor(population[i].genes[property] * 255));
      string += geneChar;
    }
    console.log('#' + i + ' ' + string);
  }
};

var onNewGen = function(pop) {
  printReadable(pop);
};

/** Some option changes (defaults are lame)
 * Increased generations and mutation probability
 */
var options = {
  maxGenerations: 1000,
  mutationProb: 0.1382005272898823, // 13% mutation
  maxPopulation: 251,
  numToSelect: 37,
  exitScore: ourString.length, // The highest score possible is the length of our string
  onNewGen: onNewGen
};

/** Our genev object initialized with our CHROMO_STRUCTURE */
var findString = GF(chromosome, options);

/* Init it with your own population or it will generate random ones */
findString.initPopulation(); // generates random population

// Population before evolving
printReadable(findString.getPopulation());

findString.evolve(options, fitfunc); // you can also pass in the options here again.

// Population after evolving
printReadable(findString.getPopulation());
/* Some extra notes

*/
<|endoftext|>


<commit_before>var message = '';

function log(msg) {
  message = message + msg + '
';
  document.getElementById('logs').innerHTML = message;
}

function testSteamAPI() {
  var os = require('os');
  var greenworks = require('../../greenworks.js');
  if (!greenworks) {
    log('Greenworks not support for ' + os.platform() + ' platform');
  } else {
    if (!greenworks.initAPI()) {
      log('Error on initializing steam API.');
    } else {
      log('Steam API initialized successfully.');

      log('Cloud enabled: ' + greenworks.isCloudEnabled());
      log('Cloud enabled for user: ' + greenworks.isCloudEnabledForUser());

      greenworks.on('activated', function(is_active) { log('receive activated: '+is_active); });
      greenworks.on('steam-servers-connected', function() { log('connected'); });
      greenworks.on('steam-servers-disconnected', function() { log('disconnected'); });
      greenworks.on('steam-server-connect-failure', function() { log('connected failure'); });
      greenworks.on('steam-shutdown', function() { log('shutdown'); });

      greenworks.saveTextToFile('test_file.txt', 'test_content',
          function() { log('Save text to file successfully'); },
          function(err) { log('Failed on saving text to file'); });

      greenworks.readTextFromFile('test_file.txt', function(message) {
          log('Read text from file successfully.'); }, function(err) {
          log('Failed on reading text from file'); });

      greenworks.getCloudQuota(
          function(quota, used) { log('Getting cloud quota successfully: '+used+' of '+quota) },
          function(err) { log('Failed on getting cloud quota.') });

      greenworks.activateAchievement('achievement',
          function() { log('Activating achievement successfully'); },
          function(err) { log('Failed on activating achievement.'); });

      greenworks.getNumberOfPlayers(
          function(a) { log("Number of players " + a) },
          function(err) { log ('Failed on getting number of players'); });
    }
  }
}

document.addEventListener('DOMContentLoaded', function() { testSteamAPI() });

var fps = 30;
function forceRefresh() {
  // this function updates the renderer at a given frame rate, even if the user is idle.
  // without this function, the Steam overlay would feel like "frozen".
  setTimeout(function() {
    document.getElementById("forceRefresh").getContext("2d").clearRect(0, 0, 1, 1);
    window.requestAnimationFrame(forceRefresh);
  }, 1000 / fps);
}

<commit_msg>Fixed another error in nw.js sample<commit_after>var message = '';

function log(msg) {
  message = message + msg + '
';
  document.getElementById('logs').innerHTML = message;
}

function testSteamAPI() {
  var os = require('os');
  var greenworks = require('../../greenworks.js');
  if (!greenworks) {
    log('Greenworks not support for ' + os.platform() + ' platform');
  } else {
    if (!greenworks.initAPI()) {
      log('Error on initializing steam API.');
    } else {
      log('Steam API initialized successfully.');

      log('Cloud enabled: ' + greenworks.isCloudEnabled());
      log('Cloud enabled for user: ' + greenworks.isCloudEnabledForUser());

      greenworks.on('game-overlay-activated', function(is_active) { log('overlay active: '+is_active); });
      greenworks.on('steam-servers-connected', function() { log('connected'); });
      greenworks.on('steam-servers-disconnected', function() { log('disconnected'); });
      greenworks.on('steam-server-connect-failure', function() { log('connected failure'); });
      greenworks.on('steam-shutdown', function() { log('shutdown'); });

      greenworks.saveTextToFile('test_file.txt', 'test_content',
          function() { log('Save text to file successfully'); },
          function(err) { log('Failed on saving text to file'); });

      greenworks.readTextFromFile('test_file.txt', function(message) {
          log('Read text from file successfully.'); }, function(err) {
          log('Failed on reading text from file'); });

      greenworks.getCloudQuota(
          function(quota, used) { log('Getting cloud quota successfully: '+used+' of '+quota) },
          function(err) { log('Failed on getting cloud quota.') });

      greenworks.activateAchievement('achievement',
          function() { log('Activating achievement successfully'); },
          function(err) { log('Failed on activating achievement.'); });

      greenworks.getNumberOfPlayers(
          function(a) { log("Number of players " + a) },
          function(err) { log ('Failed on getting number of players'); });
    }
  }
}

document.addEventListener('DOMContentLoaded', function() { testSteamAPI() });

var fps = 30;
function forceRefresh() {
  // this function updates the renderer at a given frame rate, even if the user is idle.
  // without this function, the Steam overlay would feel like "frozen".
  setTimeout(function() {
    document.getElementById("forceRefresh").getContext("2d").clearRect(0, 0, 1, 1);
    window.requestAnimationFrame(forceRefresh);
  }, 1000 / fps);
}

<|endoftext|>


<commit_before>var thecallr = require('thecallr');

try {
	// initialize instance Thecallr
	// set your credentials or an Exception will raise
	var tc = new thecallr.api("login", "password");

	// Basic example
	// Example to send a SMS
	// 1. "call" method: each parameter of the method as an argument
	tc.call("sms.send", "THECALLR", "+33123456789", "Hello, world", {
		flash_message: false
	})
		.success(function(data) {
			console.log("Response:", data);
		})
		.error(function(error) {
			console.error("\nError:", error.message);
			console.error("Code:", error.code);
			console.error("Data:", error.data);
		});

	// 2. "send" method: parameter of the method is an array
	var my_array = ["THECALLR", "+33123456789", "Hello, world", {
		"flash_message": false
	}];
	tc.send("sms.send", my_array)
		.success(function(data) {
			console.log("Response 2:", data);
		})
		.error(function(error) {
			console.error("\nError:", error.message);
			console.error("Code:", error.code);
			console.error("Data:", error.data);
		});
}
catch (e) {
	console.error("Fatal error");
	console.error(e);
}
<commit_msg>Update sample<commit_after>var callr = require('callr');

try {
	// initialize instance Callr
	// set your credentials or an Exception will raise
	var api = new callr.api('login', 'password');

	// Basic example
	// Example to send a SMS
	// 1. "call" method: each parameter of the method as an argument

	var options = {
		flash_message: false,
	};

	api.call('sms.send', 'CALLR', '+33123456789', 'Hello, world', options).success(function(data) {
		console.log('Response:', data);
	}).error(function(error) {
		console.error("\nError:", error.message);
		console.error('Code:', error.code);
		console.error('Data:', error.data);
	});

	// 2. "send" method: parameter of the method is an array
	var my_array = ['CALLR', '+33123456789', 'Hello, world', options];

	api.send('sms.send', my_array).success(function(data) {
		console.log('Response 2:', data);
	}).error(function(error) {
		console.error("\nError:", error.message);
		console.error('Code:', error.code);
		console.error('Data:', error.data);
	});
}
catch (e) {
	console.error('Fatal error');
	console.error(e);
}
<|endoftext|>


<commit_before>var G = 6.67408 * Math.pow(10, -11); // m^3 kg^-1 s^-2

// An enum of available levels of logging.
var loglevels = {
  critical: {name: 'critical', value: 0},
  error: {name: 'error', value: 1},
  warn: {name: 'warn', value: 2},
  debug: {name: 'debug', value: 3},
  info: {name: 'info', value: 4},
  trace: {name: 'trace', value: 5}
};
// The default level of logging.  Set this to null to avoid logging entirely.
var loglevel = loglevels.warn;
var log = function(level, message) {
  // Log a message.
  //
  // Args:
  //  level: A member of loglevels.
  //  message: A message to log.
  if (loglevel === null) return;
  var l = loglevels[level];
  if (l.value <= loglevel.value) console.log('[' + loglevel.name + ']');
};

var State = function(x, v, a, m) {
  // A state of a body in the simulation.
  var self = this;

  // The position (m).
  self.x = x || new Vector([0, 0]);
  // The velocity (m s^-1).
  self.v = v || new Vector([0, 0]);
  // The acceleration (m s^-2).
  self.a = a || new Vector([0, 0]);
  // The mass (kg).
  self.m = m || 0;

  self.hash = function() {
    // Generate a hash of the state for use in caching.
    //
    // Returns:
    //  A hash of the state.
    return '[' + self.x.hash() + ',' + self.v.hash() + ',' + self.a.hash() + ',' + self.m + ']';
  };

  // A cache of get_force calculations.
  self._forces = {};
  self.get_force = function(other) {
    // Get the force on this state by another.
    //
    // This function is cached for each value of other.  In addition, this
    // function sets the cache on other.
    //
    // Args:
    //  other: Another body instance.
    //
    // Returns:
    //  The gravitational force vector of other applied on this state.
    var r;
    var f;
    var hash;
    var other_hash = other.hash();

    if (self._forces[other_hash] === undefined) {
      hash = self.hash();
      r = other.x.subtract(self.x);
      f = r.unit().multiply(
        -1 * G * self.mass * other.mass /
        Math.pow(r.magnitude(), 2)); // (kg m s^-2)

      self._forces[other_hash] = f;
      // Every action has an equal and opposite reaction.
      other._forces[hash] = f.multiply(-1)
    }
    return self._forces[other_hash];
  };
};

var Body = function() {
  // A planetary body.
  //
  // Args:
  //  state: The initial state of the body.
  var self = this;

  // A list of states.
  self.states = [];

  self.set_state = function(state) {
    // Set the state of the body.
    //
    // Args:
    //  state: A State instance.
    //
    // Returns:
    //  self
    self.states.push(state);
    return self;
  };

  self.get_state = function() {
    // Get the current state of the body.
    //
    // Returns:
    //  The last State in the body's history.
    return self.states[self.states.length - 1];
  };

  self.get_force = function(other) {
    // Get the force on this object by another.
    //
    // Args:
    //  other: Another body instance.
    //
    // Returns:
    //  The gravitational force vector of other applied on this body.
    return self.current_state().get_force(other.current_state())
  };
};

var Simulation = function() {
  // An N-body simulation.
  var self = this;

  // The bodies of the simulation.
  self.bodies = [];

  // The size of the simulation timestep (s).
  self.step_size = .5;

  self.add_body = function(body) {
    // Add a body to the simulation.
    //
    // Args:
    //  body: A Body instance.
    //
    // Returns:
    //  self
    self.bodies.push(body);
    return self;
  };

  self.step = function() {
    // Generate the next step in the simulation and apply it.
    //
    // TODO: Add a half-step velocity calculation.
    // TODO: Add collision detection.
    //
    // Returns:
    //  self
    var i, j;
    var x, a, f;
    var old_state, new_state;
    var new_xs = [];
    var new_states = [];

    // Create a list of new states for each body in self.bodies.  And
    //  calculate their new position.
    for (i = 0; i < self.bodies.length; i++) {
      old_state = self.bodies[i].get_state();

      // Velocity verlet.
      // x = x + vt + .5at^2
      x = old_state.x
        .add(old_state.v.multiply(self.step_size))
        .add(old_state.a.multiply(.5 * Math.pow(self.step_size, 2)));

      // Initially create the state with just the new position.
      new_states.push(new State(x))
    }

    // Calculate the new velocity from the states created above.
    // This looks like it is O(n^2).  However, because State.get_force is
    //  cached (and reverse-cached), it's actually O(n log(n)).
    for (i = 0; i < new_states.length; i++) {
      old_state = self.bodies[i].get_state();
      new_state = new_states[i];

      // Calculate an force vector as the sum of the gravity due to every other
      //  body in the simulation.
      f = new Vector([0, 0]);
      for (j = 0; j < new_states.length; i++) {
        if (i != j)
          f = f.add(new_state.get_force(new_states[j]));
      }
      a = f.divide(state.m);

      // Velocity verlet.
      new_state.a = a;
      new_state.m = old_state.m;
      // v = v + .5(old_a + a)t
      new_state.v = old_state.v
        .add(new_state.a
          .add(old_state.a)
          .multiply(.5 * self.step_size));
    }

    // Set the new states.
    for (i = 0; i < self.bodies.length; i++) {
      self.bodies[i].set_state(new_states[i]);
    }

    return self;
  };
};
<commit_msg>Add a limit to the size of body states.<commit_after>var G = 6.67408 * Math.pow(10, -11); // m^3 kg^-1 s^-2

// An enum of available levels of logging.
var loglevels = {
  critical: {name: 'critical', value: 0},
  error: {name: 'error', value: 1},
  warn: {name: 'warn', value: 2},
  debug: {name: 'debug', value: 3},
  info: {name: 'info', value: 4},
  trace: {name: 'trace', value: 5}
};
// The default level of logging.  Set this to null to avoid logging entirely.
var loglevel = loglevels.warn;
var log = function(level, message) {
  // Log a message.
  //
  // Args:
  //  level: A member of loglevels.
  //  message: A message to log.
  if (loglevel === null) return;
  var l = loglevels[level];
  if (l.value <= loglevel.value) console.log('[' + loglevel.name + ']');
};

var State = function(x, v, a, m) {
  // A state of a body in the simulation.
  var self = this;

  // The position (m).
  self.x = x || new Vector([0, 0]);
  // The velocity (m s^-1).
  self.v = v || new Vector([0, 0]);
  // The acceleration (m s^-2).
  self.a = a || new Vector([0, 0]);
  // The mass (kg).
  self.m = m || 0;

  self.hash = function() {
    // Generate a hash of the state for use in caching.
    //
    // Returns:
    //  A hash of the state.
    return '[' + self.x.hash() + ',' + self.v.hash() + ',' + self.a.hash() + ',' + self.m + ']';
  };

  // A cache of get_force calculations.
  self._forces = {};
  self.get_force = function(other) {
    // Get the force on this state by another.
    //
    // This function is cached for each value of other.  In addition, this
    // function sets the cache on other.
    //
    // Args:
    //  other: Another body instance.
    //
    // Returns:
    //  The gravitational force vector of other applied on this state.
    var r;
    var f;
    var hash;
    var other_hash = other.hash();

    if (self._forces[other_hash] === undefined) {
      hash = self.hash();
      r = other.x.subtract(self.x);
      f = r.unit().multiply(
        -1 * G * self.mass * other.mass /
        Math.pow(r.magnitude(), 2)); // (kg m s^-2)

      self._forces[other_hash] = f;
      // Every action has an equal and opposite reaction.
      other._forces[hash] = f.multiply(-1)
    }
    return self._forces[other_hash];
  };
};

var Body = function() {
  // A planetary body.
  //
  // Args:
  //  state: The initial state of the body.
  var self = this;

  // A list of states.
  self.states = [];

  self.set_state = function(state) {
    // Set the state of the body.
    //
    // Args:
    //  state: A State instance.
    //
    // Returns:
    //  self
    if (self.states.length > 5)
      self.states = self.states.slice(
        self.states.length - 5,
        self.states.length);
    self.states.push(state);
    return self;
  };

  self.get_state = function() {
    // Get the current state of the body.
    //
    // Returns:
    //  The last State in the body's history.
    return self.states[self.states.length - 1];
  };

  self.get_force = function(other) {
    // Get the force on this object by another.
    //
    // Args:
    //  other: Another body instance.
    //
    // Returns:
    //  The gravitational force vector of other applied on this body.
    return self.current_state().get_force(other.current_state())
  };
};

var Simulation = function() {
  // An N-body simulation.
  var self = this;

  // The bodies of the simulation.
  self.bodies = [];

  // The size of the simulation timestep (s).
  self.step_size = .5;

  self.add_body = function(body) {
    // Add a body to the simulation.
    //
    // Args:
    //  body: A Body instance.
    //
    // Returns:
    //  self
    self.bodies.push(body);
    return self;
  };

  self.step = function() {
    // Generate the next step in the simulation and apply it.
    //
    // TODO: Add a half-step velocity calculation.
    // TODO: Add collision detection.
    //
    // Returns:
    //  self
    var i, j;
    var x, a, f;
    var old_state, new_state;
    var new_xs = [];
    var new_states = [];

    // Create a list of new states for each body in self.bodies.  And
    //  calculate their new position.
    for (i = 0; i < self.bodies.length; i++) {
      old_state = self.bodies[i].get_state();

      // Velocity verlet.
      // x = x + vt + .5at^2
      x = old_state.x
        .add(old_state.v.multiply(self.step_size))
        .add(old_state.a.multiply(.5 * Math.pow(self.step_size, 2)));

      // Initially create the state with just the new position.
      new_states.push(new State(x))
    }

    // Calculate the new velocity from the states created above.
    // This looks like it is O(n^2).  However, because State.get_force is
    //  cached (and reverse-cached), it's actually O(n log(n)).
    for (i = 0; i < new_states.length; i++) {
      old_state = self.bodies[i].get_state();
      new_state = new_states[i];

      // Calculate an force vector as the sum of the gravity due to every other
      //  body in the simulation.
      f = new Vector([0, 0]);
      for (j = 0; j < new_states.length; j++) {
        if (i != j)
          f = f.add(new_state.get_force(new_states[j]));
      }
      a = f.divide(old_state.m);

      // Velocity verlet.
      new_state.a = a;
      new_state.m = old_state.m;
      // v = v + .5(old_a + a)t
      new_state.v = old_state.v
        .add(new_state.a
          .add(old_state.a)
          .multiply(.5 * self.step_size));
    }

    // Set the new states.
    for (i = 0; i < self.bodies.length; i++) {
      self.bodies[i].set_state(new_states[i]);
    }

    return self;
  };
};
<|endoftext|>


<commit_before>var sys		= require('sys');
var http	= require('http');
var assert	= require('assert');

var probe = function(apps_suffix, host, port, method_name, success_cb, failure_cb){
	var path	= "/neoip_"+apps_suffix+"_appdetect_jsrest.js?method_name="+method_name;
	var client	= http.createClient(port, host);
	// bind error cases at the socket level
	// - REPORT: to report bug, "error" is reported twice
	// - REPORT: "error" is not in the doc
	// - REPORT: is there a parameter to this callback, it doesnt seems to be
	if(failure_cb){
		// KLUDGE: workaround because node.js report twice the error
		var reported	= false;
		client.addListener("error"	, function(had_error){
			if( !reported )	failure_cb(had_error)
			reported	= true;
		});
	}
	//if(failure_cb)	client.addListener("error"	, failure_cb);
	//if(failure_cb)	client.addListener("timeout"	, failure_cb);
	var request	= client.request('GET', path, {'host': host});
	request.addListener('response', function(response){
		sys.puts('STATUS: ' + response.statusCode);
		sys.puts('HEADERS: ' + JSON.stringify(response.headers));
		// Handle faillure at http level
		if(response.statusCode != 200){
			if(failure_cb)	failure_cb(new Error("http statuscode="+response.statuscode));
			return
		}
		response.setEncoding('utf8');
		response.addListener('data', function( reply_json ){
			sys.puts('BODY: ' + reply_json);
			// TODO: make this jsrest.js able to answer jsonp.
			// - if obj_id=present, then use it to define the variable
			// - if callback=present, then use it to support jsonp
			// - if none is present, just reply the json
			// TODO: fix json. the keys of the object MUST have double-quotes
			//chunk	= 'neoip_xdomrpc_script_reply_var_123 = {"fault": null, "returned_val": "0.0.1"};';
			// REPORT: JSON.parse(' {};'); hangs in node-console
			// get data from the chunk
			//var reply_json	= chunk.match(/=(.*);/)[1];
			var reply_data	= JSON.parse(reply_json);
			sys.puts('bla='+sys.inspect(reply_data));
			var returned_val= reply_data['returned_val'];
			success_cb(returned_val);
		});
	});
	request.end();
};

/**
 * Constant informations about applications
*/
var app_infos	= {
	"oload": {
		"port_beg": 4550,
		"port_end": 4553
	},
	"casto": {
		"port_beg": 4560,
		"port_end": 4563
	},
	"casti": {
		"port_beg": 4570,
		"port_end": 4573
	}
};

/**
 *
 * @param {String} app_suffix the neoip application suffix
 * @param {function} callback called to notify the result to the caller callback(version, strerror)
*/
exports.discover_app	= function(app_suffix, success_cb, failure_cb){
	// sanity check
	assert.ok(success_cb);
	assert.ok(app_suffix == "oload" || app_suffix == "casti" || app_suffix == "casto");
	// get info from app_infos
	var port_beg	= app_infos[app_suffix]["port_beg"];
	var port_end	= app_infos[app_suffix]["port_end"];
	var port_cur	= port_beg;
	// define the callbacks
	var probe_succ_cb	= function(version){
		sys.puts("found version "+version+" port_cur="+port_cur);
		var root_url	= "http://127.0.0.1:"+port_cur;
		success_cb(root_url, version);
	};
	var probe_fail_cb	= function(had_error){
		sys.puts('not found port_cur='+port_cur);
		if(port_cur == port_end){
			// report "not found" when all port has been tested
			if( failure_cb )	failure_cb("not found");
		}else{
			// test the next port
			port_cur++;
			probe(app_suffix, "127.0.0.1", port_cur, "probe_apps", probe_succ_cb, probe_fail_cb);
		}
	};
	// start the probbing
	probe(app_suffix, "127.0.0.1", port_cur, "probe_apps", probe_succ_cb, probe_fail_cb);
}
<commit_msg>neoip.js: removed debug log 	modified:   neoip.js<commit_after>var sys		= require('sys');
var http	= require('http');
var assert	= require('assert');

var probe = function(apps_suffix, host, port, method_name, success_cb, failure_cb){
	var path	= "/neoip_"+apps_suffix+"_appdetect_jsrest.js?method_name="+method_name;
	var client	= http.createClient(port, host);
	// bind error cases at the socket level
	// - REPORT: to report bug, "error" is reported twice
	// - REPORT: "error" is not in the doc
	// - REPORT: is there a parameter to this callback, it doesnt seems to be
	if(failure_cb){
		// KLUDGE: workaround because node.js report twice the error
		var reported	= false;
		client.addListener("error"	, function(had_error){
			if( !reported )	failure_cb(had_error)
			reported	= true;
		});
	}
	//if(failure_cb)	client.addListener("error"	, failure_cb);
	//if(failure_cb)	client.addListener("timeout"	, failure_cb);
	var request	= client.request('GET', path, {'host': host});
	request.addListener('response', function(response){
		//sys.puts('STATUS: ' + response.statusCode);
		//sys.puts('HEADERS: ' + JSON.stringify(response.headers));
		// Handle faillure at http level
		if(response.statusCode != 200){
			if(failure_cb)	failure_cb(new Error("http statuscode="+response.statuscode));
			return
		}
		response.setEncoding('utf8');
		response.addListener('data', function( reply_json ){
			//sys.puts('BODY: ' + reply_json);
			// TODO: make this jsrest.js able to answer jsonp.
			// - if obj_id=present, then use it to define the variable
			// - if callback=present, then use it to support jsonp
			// - if none is present, just reply the json
			// TODO: fix json. the keys of the object MUST have double-quotes
			//chunk	= 'neoip_xdomrpc_script_reply_var_123 = {"fault": null, "returned_val": "0.0.1"};';
			// REPORT: JSON.parse(' {};'); hangs in node-console
			// get data from the chunk
			//var reply_json	= chunk.match(/=(.*);/)[1];
			var reply_data	= JSON.parse(reply_json);
			//sys.puts('bla='+sys.inspect(reply_data));
			var returned_val= reply_data['returned_val'];
			success_cb(returned_val);
		});
	});
	request.end();
};

/**
 * Constant informations about applications
*/
var app_infos	= {
	"oload": {
		"port_beg": 4550,
		"port_end": 4553
	},
	"casto": {
		"port_beg": 4560,
		"port_end": 4563
	},
	"casti": {
		"port_beg": 4570,
		"port_end": 4573
	}
};

/**
 *
 * @param {String} app_suffix the neoip application suffix
 * @param {function} callback called to notify the result to the caller callback(version, strerror)
*/
exports.discover_app	= function(app_suffix, success_cb, failure_cb){
	// sanity check
	assert.ok(success_cb);
	assert.ok(app_suffix == "oload" || app_suffix == "casti" || app_suffix == "casto");
	// get info from app_infos
	var port_beg	= app_infos[app_suffix]["port_beg"];
	var port_end	= app_infos[app_suffix]["port_end"];
	var port_cur	= port_beg;
	// define the callbacks
	var probe_succ_cb	= function(version){
		//sys.puts("found version "+version+" port_cur="+port_cur);
		var root_url	= "http://127.0.0.1:"+port_cur;
		success_cb(root_url, version);
	};
	var probe_fail_cb	= function(had_error){
		//sys.puts('not found port_cur='+port_cur);
		if(port_cur == port_end){
			// report "not found" when all port has been tested
			if( failure_cb )	failure_cb("not found");
		}else{
			// test the next port
			port_cur++;
			probe(app_suffix, "127.0.0.1", port_cur, "probe_apps", probe_succ_cb, probe_fail_cb);
		}
	};
	// start the probbing
	probe(app_suffix, "127.0.0.1", port_cur, "probe_apps", probe_succ_cb, probe_fail_cb);
}
<|endoftext|>


<commit_before>(function() {
	'use strict';
	var i18n = 'i18n';
	var has_i18n_config = typeof _i18n_config === 'object';

	var timeUnitScale = [
		31536000000, // y
		2592000000, // month
		86400000, // d
		3600000, // h
		60000, // min
		1000, // s
		1, // ms
		0.001 // µs
	];

	function s_formatter(text, values, statusVariable) {
		var args = [text].concat(values);
		var count = -1;

		function getRules() {
			return statusVariable.currentLocale.formatRules;
		}

		function buildX0(nb) {
			var result = [];
			nb = +nb;

			if (!nb) {
				return '';
			}

			while (result.length < nb) {
				result.push('0');
			}

			return result.join('');
		}

		function stringReplacement(value, variation) {
			if (typeof value === 'undefined') {
				value = 'undefined';
			} else {
				value = value.toString();
			}

			if (variation) {
				if (variation.indexOf('case') !== -1) {
					value = value.toLowerCase();
				} else if (variation.indexOf('CASE') !== -1) {
					value = value.toUpperCase();
				} else if (variation.indexOf('Case') !== -1) {
					value = value.charAt(0).toUpperCase() + value.slice(1).toLowerCase();
				} else if (variation.indexOf('CasE') !== -1) {
					value = value.charAt(0).toUpperCase() + value.slice(1);
				}
			}

			return value;
		}

		function getNumber(value, variation) {
			var splitValue, nb, status;

			nb = Number(value);

			splitValue = nb.toString().split('.');

			status = {
				number: nb,
				integer: splitValue[0],
				decimal: splitValue[1]
			};

			if (variation) {
				variation.forEach(function(code) {
					var nb = parseInt(code.slice(1), 10);

					if (isNaN(nb)) {
						return;
					}

					switch(code.charAt(0)) {
						case '.':
							if (status.decimal && (status.decimal.length > nb || status.decimal.charAt(status.decimal.length-1) === '0')) {
								status.decimal = (Math.round(('0.'+status.decimal) * Math.pow(10, nb)) / Math.pow(10, nb)).toString().slice(2);
							}
							break;
						case 'p':
							if (status.integer.length < nb) {
								status.integer = buildX0(nb - status.integer.length) + status.integer;
							}
							break;
						case 'd':
							if (!status.decimal) {
								status.decimal = '';
							}
							if (status.decimal.length < nb) {
								status.decimal += buildX0(nb - status.decimal.length);
							}
							break;
					}
				});
			}

			return status;
		}

		function rawNumber(origValue, variation) {
			var status = getNumber(origValue, variation);
			var result = [status.integer];

			if (status.decimal) {
				result.push('.', status.decimal);
			}

			return result.join('');
		}

		function prettyNumber(origValue, variation, isInteger) {
			var status = getNumber(origValue, variation);
			var integer = status.integer;
			var rules = getRules().number;
			var thousandSeparator = rules.thousandSeparator;
			var decimalSeparator = rules.decimalSeparator;
			var value;

			value = integer.replace(/(\d)(?=(?:\d{3})+$)/g, '$1' + thousandSeparator);

			if (!isInteger && status.decimal) {
				value = [value, decimalSeparator, status.decimal].join('');
			}

			return value;
		}

		function shortNumber(origValue, variation) {
			var value, computeValue, i, sign, suffix;

			origValue = Number(origValue);
			sign = origValue < 0;
			computeValue = Math.abs(origValue);

			if (!isFinite(computeValue)) {
				return computeValue;
			}

			/* default number of rounded decimal is 3 */
			if (!variation) {
				variation = ['.3'];
			} else if (variation.every(function(v) {
				return v.indexOf('.') !== 0
			})) {
				variation.unshift('.3');
			}

			/* special case: 0 should be display like single digit (as 1) */
			if (origValue === 0) {
				computeValue = 1;
			}

			suffix = getRules().number.SIsuffix;
			i = 0;
			do {
				value = computeValue / suffix[i].multiple;
			} while(++i < suffix.length && value < 1);
			i--;

			if (origValue === 0) {
				value = 0;
			}

			if (sign) {
				value = -value;
			}

			return prettyNumber(value, variation) + suffix[i].suffix;
		}

		function expNumber(origValue, variation) {
			var value, splitValue, status, expSep, result;

			value = Number(origValue).toExponential();
			splitValue = value.split('e');
			status = getNumber(splitValue[0], variation);

			if (!isFinite(status.number)) {
				return status.number;
			}

			expSep = getRules().number.exponentialSeparator;

			result = [status.integer];

			if (status.decimal) {
				result.push('.', status.decimal);
			}
			result.push(expSep, splitValue[1]);

			return result.join('');
		}

		function getTimeUnitIndex(unit) {
			var index = {
				'y': 0,
				'month': 1,
				'M': 1,
				'd': 2,
				'h': 3,
				'min': 4,
				'm': 4,
				's': 5,
				'ms': 6,
				'i': 6,
				'µs': 7,
				'µ': 7
			}[unit];

			if (typeof index === 'undefined') {
				return -1;
			}
			return index;
		}

		function getTimestamp(value, variation) {
			var unit, code, index, multiplier;

			if (variation instanceof Array) {
				code = variation.filter(function(v) {
					return v.indexOf('u:') === 0;
				})[0];
			}

			if (code) {
				unit = code.substr(2);
			} else {
				unit = 'ms';
			}

			index = getTimeUnitIndex(unit);
			multiplier = timeUnitScale[index];
			if (!multiplier) {
				return value;
			}

			return value * multiplier;
		}

		function duration(origValue, variation) {
			var microTs, timeUnit, durationScale, durationValue, defaultFormat, format, code;
			var maxUnit = -1;
			var minUnit = Infinity;
			var limit = 0;

			timeUnit = getRules().duration;
			durationScale = [
				['$y', 'y', true],
				['$M', 'month', true],
				['$d', 'd', true],
				['$h', 'h', true],
				['$m', 'min', true],
				['$s', 's', true],
				['$i', 'ms', true],
				['$µ', 'µs', true]
			];
			durationValue = [];
			defaultFormat = [];

			function activateUnit(str) {
				var codes = str.match(/\$./g) || [];
				var maxUnit = Infinity;

				durationScale.forEach(function(code) {
					code[2] = codes.indexOf(code[0]) !== -1;
				});
			}

			microTs = getTimestamp(origValue, variation) * 1000;

			if (variation) {
				/* output format */
				code = variation.filter(function(v) {
					return v.indexOf('f:"') === 0;
				})[0];
				if (code) {
					format = code.slice(3, -1);
					activateUnit(format);
				}

				/* output format inner$ */
				code = variation.filter(function(v) {
					return v.indexOf('f:$"') === 0;
				})[0];
				if (code) {
					format = code.slice(4, -1).replace(/([yMdhmsiµ$])/g, '$$$1');
					activateUnit(format);
				}

				/* min unit */
				code = variation.filter(function(v) {
					return v.indexOf('min:') === 0;
				})[0];
				if (code) {
					minUnit = getTimeUnitIndex(code.substr(4));
				}

				/* max unit */
				code = variation.filter(function(v) {
					return v.indexOf('max:') === 0;
				})[0];
				if (code) {
					maxUnit = getTimeUnitIndex(code.substr(4));
				}

				/* max number display value */
				code = variation.filter(function(v) {
					return v.indexOf('n:') === 0;
				})[0];
				if (code) {
					limit = parseInt(code.substr(2), 10);
					if (maxUnit >= 0 && maxUnit + limit > minUnit) {
						minUnit = maxUnit + limit -1;
						limit = 0;
					}
				}
			}

			/* compute best value for each unit */
			timeUnitScale.forEach(function(scale, index) {
				scale *= 1000; //To convert in µs
				var chunk = Math.floor(microTs / scale);
				var code = durationScale[index];

				if (!code[2] || index < maxUnit || index > minUnit) {
					durationValue.push(0);
					return;
				}
				if (chunk && limit) {
					minUnit = index + limit -1;
					limit = 0;
				}

				microTs -= chunk * scale;
				durationValue.push(chunk);

				if (chunk) {
					defaultFormat.push(code[0] + timeUnit[code[1]]);
				}
			});

			format = format ? format : defaultFormat.join(' ');

			format = format.replace(/\$([yMdhmsiµ$])/g, function(pattern, code) {
				var index = 'yMdhmsiµ'.indexOf(code);

				if (index === -1) {
					if (code === '$') {
						return code;
					} else {
						return pattern
					}
				}

				return prettyNumber(durationValue[index], [], true);
			});

			return format;
		}

		function replacement(pattern, arg, variation, kind) {
			var value;

			count++;

			if (!arg) {
				value = values[count];
			} else {
				arg = arg.slice(1, -1);
				if (/\d+/.test(arg)) {
					value = values[parseInt(arg, 10) - 1];
				} else {
					arg = arg.split('.');
					value = arg.reduce(function(obj, property) {
						if (typeof obj !== 'undefined') {
							obj = obj[property];
						}

						return obj;
					}, values[0]);
				}
			}

			if (variation) {
				variation = variation.slice(1, -1).split(',').map(function(v) {
					return v.trim();
				});
			}

			switch(kind) {
				case 's':
					return stringReplacement(value, variation);
				case 'f':
					return rawNumber(value, variation);
				case 'd':
					return prettyNumber(value, variation);
				case 'D':
					return shortNumber(value, variation);
				case 'i':
					return prettyNumber(value, variation, true);
				case 'e':
					return expNumber(value, variation);
				case 't':
					return duration(value, variation);
				case '%':
					return '%';
			}
		}

		text = text.replace(/%(\([^\)]+\))?(\{[^\}]*\})?([%dDefist])/g, replacement);
		return text;
	}

	if ((!has_i18n_config && !self[i18n]) || (has_i18n_config && _i18n_config.doNotLoadFormatter)) {
		self.s_formatter = s_formatter;
	} else {
		if (has_i18n_config && _i18n_config.alias) {
			i18n = _i18n_config.alias;
		}

		self[i18n].loadFormatter(s_formatter, 100);
	}
})();
<commit_msg>fix useless variables<commit_after>(function() {
	'use strict';
	var i18n = 'i18n';
	var has_i18n_config = typeof _i18n_config === 'object';

	var timeUnitScale = [
		31536000000, // y
		2592000000, // month
		86400000, // d
		3600000, // h
		60000, // min
		1000, // s
		1, // ms
		0.001 // µs
	];

	function s_formatter(text, values, statusVariable) {
		var count = -1;

		function getRules() {
			return statusVariable.currentLocale.formatRules;
		}

		function buildX0(nb) {
			var result = [];
			nb = +nb;

			if (!nb) {
				return '';
			}

			while (result.length < nb) {
				result.push('0');
			}

			return result.join('');
		}

		function stringReplacement(value, variation) {
			if (typeof value === 'undefined') {
				value = 'undefined';
			} else {
				value = value.toString();
			}

			if (variation) {
				if (variation.indexOf('case') !== -1) {
					value = value.toLowerCase();
				} else if (variation.indexOf('CASE') !== -1) {
					value = value.toUpperCase();
				} else if (variation.indexOf('Case') !== -1) {
					value = value.charAt(0).toUpperCase() + value.slice(1).toLowerCase();
				} else if (variation.indexOf('CasE') !== -1) {
					value = value.charAt(0).toUpperCase() + value.slice(1);
				}
			}

			return value;
		}

		function getNumber(value, variation) {
			var splitValue, nb, status;

			nb = Number(value);

			splitValue = nb.toString().split('.');

			status = {
				number: nb,
				integer: splitValue[0],
				decimal: splitValue[1]
			};

			if (variation) {
				variation.forEach(function(code) {
					var nb = parseInt(code.slice(1), 10);

					if (isNaN(nb)) {
						return;
					}

					switch(code.charAt(0)) {
						case '.':
							if (status.decimal && (status.decimal.length > nb || status.decimal.charAt(status.decimal.length-1) === '0')) {
								status.decimal = (Math.round(('0.'+status.decimal) * Math.pow(10, nb)) / Math.pow(10, nb)).toString().slice(2);
							}
							break;
						case 'p':
							if (status.integer.length < nb) {
								status.integer = buildX0(nb - status.integer.length) + status.integer;
							}
							break;
						case 'd':
							if (!status.decimal) {
								status.decimal = '';
							}
							if (status.decimal.length < nb) {
								status.decimal += buildX0(nb - status.decimal.length);
							}
							break;
					}
				});
			}

			return status;
		}

		function rawNumber(origValue, variation) {
			var status = getNumber(origValue, variation);
			var result = [status.integer];

			if (status.decimal) {
				result.push('.', status.decimal);
			}

			return result.join('');
		}

		function prettyNumber(origValue, variation, isInteger) {
			var status = getNumber(origValue, variation);
			var integer = status.integer;
			var rules = getRules().number;
			var thousandSeparator = rules.thousandSeparator;
			var decimalSeparator = rules.decimalSeparator;
			var value;

			value = integer.replace(/(\d)(?=(?:\d{3})+$)/g, '$1' + thousandSeparator);

			if (!isInteger && status.decimal) {
				value = [value, decimalSeparator, status.decimal].join('');
			}

			return value;
		}

		function shortNumber(origValue, variation) {
			var value, computeValue, i, sign, suffix;

			origValue = Number(origValue);
			sign = origValue < 0;
			computeValue = Math.abs(origValue);

			if (!isFinite(computeValue)) {
				return computeValue;
			}

			/* default number of rounded decimal is 3 */
			if (!variation) {
				variation = ['.3'];
			} else if (variation.every(function(v) {
				return v.indexOf('.') !== 0
			})) {
				variation.unshift('.3');
			}

			/* special case: 0 should be display like single digit (as 1) */
			if (origValue === 0) {
				computeValue = 1;
			}

			suffix = getRules().number.SIsuffix;
			i = 0;
			do {
				value = computeValue / suffix[i].multiple;
			} while(++i < suffix.length && value < 1);
			i--;

			if (origValue === 0) {
				value = 0;
			}

			if (sign) {
				value = -value;
			}

			return prettyNumber(value, variation) + suffix[i].suffix;
		}

		function expNumber(origValue, variation) {
			var value, splitValue, status, expSep, result;

			value = Number(origValue).toExponential();
			splitValue = value.split('e');
			status = getNumber(splitValue[0], variation);

			if (!isFinite(status.number)) {
				return status.number;
			}

			expSep = getRules().number.exponentialSeparator;

			result = [status.integer];

			if (status.decimal) {
				result.push('.', status.decimal);
			}
			result.push(expSep, splitValue[1]);

			return result.join('');
		}

		function getTimeUnitIndex(unit) {
			var index = {
				'y': 0,
				'month': 1,
				'M': 1,
				'd': 2,
				'h': 3,
				'min': 4,
				'm': 4,
				's': 5,
				'ms': 6,
				'i': 6,
				'µs': 7,
				'µ': 7
			}[unit];

			if (typeof index === 'undefined') {
				return -1;
			}
			return index;
		}

		function getTimestamp(value, variation) {
			var unit, code, index, multiplier;

			if (variation instanceof Array) {
				code = variation.filter(function(v) {
					return v.indexOf('u:') === 0;
				})[0];
			}

			if (code) {
				unit = code.substr(2);
			} else {
				unit = 'ms';
			}

			index = getTimeUnitIndex(unit);
			multiplier = timeUnitScale[index];
			if (!multiplier) {
				return value;
			}

			return value * multiplier;
		}

		function duration(origValue, variation) {
			var microTs, timeUnit, durationScale, durationValue, defaultFormat, format, code;
			var maxUnit = -1;
			var minUnit = Infinity;
			var limit = 0;

			timeUnit = getRules().duration;
			durationScale = [
				['$y', 'y', true],
				['$M', 'month', true],
				['$d', 'd', true],
				['$h', 'h', true],
				['$m', 'min', true],
				['$s', 's', true],
				['$i', 'ms', true],
				['$µ', 'µs', true]
			];
			durationValue = [];
			defaultFormat = [];

			function activateUnit(str) {
				var codes = str.match(/\$./g) || [];

				durationScale.forEach(function(code) {
					code[2] = codes.indexOf(code[0]) !== -1;
				});
			}

			microTs = getTimestamp(origValue, variation) * 1000;

			if (variation) {
				/* output format */
				code = variation.filter(function(v) {
					return v.indexOf('f:"') === 0;
				})[0];
				if (code) {
					format = code.slice(3, -1);
					activateUnit(format);
				}

				/* output format inner$ */
				code = variation.filter(function(v) {
					return v.indexOf('f:$"') === 0;
				})[0];
				if (code) {
					format = code.slice(4, -1).replace(/([yMdhmsiµ$])/g, '$$$1');
					activateUnit(format);
				}

				/* min unit */
				code = variation.filter(function(v) {
					return v.indexOf('min:') === 0;
				})[0];
				if (code) {
					minUnit = getTimeUnitIndex(code.substr(4));
				}

				/* max unit */
				code = variation.filter(function(v) {
					return v.indexOf('max:') === 0;
				})[0];
				if (code) {
					maxUnit = getTimeUnitIndex(code.substr(4));
				}

				/* max number display value */
				code = variation.filter(function(v) {
					return v.indexOf('n:') === 0;
				})[0];
				if (code) {
					limit = parseInt(code.substr(2), 10);
					if (maxUnit >= 0 && maxUnit + limit > minUnit) {
						minUnit = maxUnit + limit -1;
						limit = 0;
					}
				}
			}

			/* compute best value for each unit */
			timeUnitScale.forEach(function(scale, index) {
				scale *= 1000; //To convert in µs
				var chunk = Math.floor(microTs / scale);
				var code = durationScale[index];

				if (!code[2] || index < maxUnit || index > minUnit) {
					durationValue.push(0);
					return;
				}
				if (chunk && limit) {
					minUnit = index + limit -1;
					limit = 0;
				}

				microTs -= chunk * scale;
				durationValue.push(chunk);

				if (chunk) {
					defaultFormat.push(code[0] + timeUnit[code[1]]);
				}
			});

			format = format ? format : defaultFormat.join(' ');

			format = format.replace(/\$([yMdhmsiµ$])/g, function(pattern, code) {
				var index = 'yMdhmsiµ'.indexOf(code);

				if (index === -1) {
					if (code === '$') {
						return code;
					} else {
						return pattern
					}
				}

				return prettyNumber(durationValue[index], [], true);
			});

			return format;
		}

		function replacement(pattern, arg, variation, kind) {
			var value;

			count++;

			if (!arg) {
				value = values[count];
			} else {
				arg = arg.slice(1, -1);
				if (/\d+/.test(arg)) {
					value = values[parseInt(arg, 10) - 1];
				} else {
					arg = arg.split('.');
					value = arg.reduce(function(obj, property) {
						if (typeof obj !== 'undefined') {
							obj = obj[property];
						}

						return obj;
					}, values[0]);
				}
			}

			if (variation) {
				variation = variation.slice(1, -1).split(',').map(function(v) {
					return v.trim();
				});
			}

			switch(kind) {
				case 's':
					return stringReplacement(value, variation);
				case 'f':
					return rawNumber(value, variation);
				case 'd':
					return prettyNumber(value, variation);
				case 'D':
					return shortNumber(value, variation);
				case 'i':
					return prettyNumber(value, variation, true);
				case 'e':
					return expNumber(value, variation);
				case 't':
					return duration(value, variation);
				case '%':
					return '%';
			}
		}

		text = text.replace(/%(\([^\)]+\))?(\{[^\}]*\})?([%dDefist])/g, replacement);
		return text;
	}

	if ((!has_i18n_config && !self[i18n]) || (has_i18n_config && _i18n_config.doNotLoadFormatter)) {
		self.s_formatter = s_formatter;
	} else {
		if (has_i18n_config && _i18n_config.alias) {
			i18n = _i18n_config.alias;
		}

		self[i18n].loadFormatter(s_formatter, 100);
	}
})();
<|endoftext|>