<commit_before>/*
    ------------------
    Initialize Variables
    ------------------
*/

//Constants
const VERSION = 1.5;
const BOOT_TIME = new Date();
const WH_TIME = 0; //What hour Writing Hour should start at, in UTC
const ADMIN_URL = "http://localhost:8000/Admins.txt"; //URL to pull admin list from
const ADMINS = []; //Will be filled with Admin data from file

//Control variables
var CommandsLoaded = false;
var adminAliases = [];

//Writing Hour variables
var WHSwitch = 0;

/*
    -------------------
    Arbitrary functions
    -------------------
*/

function randomNumber(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

function startWW(length, KeyWord) {
    setTimeout(function() {
        NumWWs--;
        if (!IsSleeping) {
            postMessage("[b]Word War " + (KeyWord? "'" + KeyWord + "' " : "") + "ends.[/b] How did you do?");
        }
    }, length * 60000);
}

function parseAdmins(str) {
    str = str.split(/\r?\n/);
    for (var i in str) {
        if (str.hasOwnProperty(i)) {
            str[i] = str[i].split(",")[1];
        }
    }
    return str;
}

function parseArgs(str) {
    var out = [];

    if (str.match(/".*?"/)) {
        var delim = false;
        var arg = "";
        for (var char in str) {
            if (str[char] == "\"") {
                delim = !delim;
                if (arg) {
                    out.push(arg);
                    arg = "";
                }
            } else if (str[char] == " " && !delim) {
                if (arg) {
                    out.push(arg);
                    arg = "";
                }
            } else {
                arg += str[char];
            }
        }
        if (arg) {
            out.push(arg);
        }
    } else {
        out = str.split(/\s/);
    }

    return out;
}

function stringify(object) {
    return JSON.stringify(object);
}

function parse(string) {
    return JSON.parse(string);
}

function setStorage(key, content) {
    window.localStorage[key] = content;
}

function getStorage(key) {
    return window.localStorage[key];
}

function removeStorage(key) {
    var oldItem = getStorage(key);
    window.localStorage.removeItem(key);
    return oldItem;
}

function reloadCommands() {
    CommandScript.remove();
    CommandsLoaded = false;

    Commands = undefined;
    UserCommands = undefined;
    ADMIN_COMMANDS = undefined;
    var TalosCommands = makeElement('script', {'type':'text/javascript',
                                           'src': MAIN_URL + 'Commands.js',
                                           'onload':'CommandsLoaded = true',
                                           'id':'CommandScript'});
    document.head.appendChild(TalosCommands);
}

function readFile(file) {
    return new Promise(function(resolve, reject) {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function () {
            if(rawFile.readyState === 4) {
                if(rawFile.status === 200 || rawFile.status === 0) {
                    var allText = rawFile.responseText;
                    resolve(allText);
                } else {
                    reject();
                }
            } else {
                reject();
            }
        };
        rawFile.send(null);
    });
}

function getAdminNames() {
    getVisitorData(["Alias","UID"]).then(function(visitorData) {
        adminAliases = [];
        for (var i = 0; i < visitorData.length; i++) {
            var visitor = visitorData[i];
            if (visitor[1] == "(Email hidden)") {
                continue;
            }
            if (visitor[1][0] == "\"") {
                visitor[1] =  visitor[1].substr(1,visitor[1].length-2);
            }
            for (var j = 0; j < ADMINS.length; j++) {
                if (ADMINS[j] == visitor[1]) {
                    adminAliases.push(visitor[0]);
                }
            }
        }
    });
}

/*
    -------------------
    Main loop functions
    -------------------
*/

function writingHour() {
    var d = new Date();

    if (d.getUTCHours() == (WH_TIME === 0 ? 23 : WH_TIME - 1)  && d.getUTCMinutes() == 50 && WHSwitch === 0) {
        postMessage("[b][Alert][/b] 10 minutes until WH!");
        WHSwitch++;
    } else if (d.getUTCHours() == (WH_TIME === 0 ? 23 : WH_TIME - 1) && d.getUTCMinutes() == 55 && WHSwitch == 1) {
        postMessage("[b][Alert][/b] 5 minutes until WH!");
        WHSwitch++;
    } else if (d.getUTCHours() == WH_TIME && d.getUTCMinutes() === 0 && WHSwitch == 2) {
        postMessage("[b]Writing Hour begins![/b] Time to write, good luck!");
        setTimeout(function(){closeChat();}, 1000);
        WHSwitch++;
    } else if (d.getUTCHours() == (WH_TIME == 23 ? 0 : WH_TIME + 1) && d.getUTCMinutes() === 0 && WHSwitch == 3) {
        setTimeout(function() {postMessage("[b]Writing Hour is over.[/b]");}, 500);
        setTimeout(function(){openChat();}, 1000);
        WHSwitch = 0;
    }
}

function readChat() {
    if (!elementByID(messageContainer) ||
            !elementByID(messageTable) ||
            !elementByID(messageTable).children ||
            elementByID(messageTable).firstChild.innerHTML != "Previous messages parsed (press ESC to re-parse page)") {
        return;
    }
    try {
        var Messages = elementByID(messageTable).children;
        for (var i = 1; i < Messages.length; i++) {
            try {
                var Message = Messages[i].childNodes;
                if(!Message[1] || !Message[1].data) {
                    continue;
                }

                var text = Message[1].data;

                if (text.match(/^: \^\w/)) {
                    var User = Message[0].innerText;
                    var Command = /\^(\w+)/.exec(text)[1];
                    var Args = text.substr(Command.length + 3).match(/([^\s"]+)|"(.+?)"/g);

                    if (Args === null) {
                        Args = [];
                    }

                    var isAdmin = false;
                    for (var U in adminAliases) {
                        if (User == adminAliases[U]) {
                            isAdmin = true;
                            break;
                        }
                    }

                    //console.log(Command + " | " + /*FirstArgs + " |*/ "\"" + Args + "\"");

                    if (window.ADMIN_COMMANDS[Command] && isAdmin) {
                        log.warn("Admin command " + Command + " called by " + User);
                        log.debug("With arguments \"" + Args + "\"");
                        window.ADMIN_COMMANDS[Command](Args, User);
                    } else if (IsSleeping == 1) {
                        break;
                    } else if (window.ADMIN_COMMANDS[Command] && !isAdmin) {
                        log.warn("Admin command " + Command + " ignored from " + User);
                        log.debug("With arguments \"" + Args + "\"");
                        postMessage("Sorry, that command is Admin only, and I don't recognize you!");
                    } else if (window.UserCommands[Command]){
                        log.info("User command " + Command + " called by " + User);
                        log.debug("With arguments \"" + Args + "\"");
                        window.UserCommands[Command](Args, User);
                    } else if (window.Commands[Command]) {
                        log.info("Command " + Command + " called by " + User);
                        log.debug("With arguments \"" + Args + "\"");
                        window.Commands[Command](Args);
                    } else {
                        log.debug("Failed to parse " + Command);
                        postMessage("Sorry, I don't understand that. May I suggest ^help?");
                    }
                }
            } catch (Exception) {}
        }
    } finally {
        elementByID(messageTable).innerHTML = '
Previous messages parsed (press ESC to re-parse page)
\n';
        window[isCleared] = false;
    }
}

function readPMs() {
    var Popup = elementByID(popup);
    var PMSearch = new RegExp('.+>(.+)<\/em>.+' + textBox + '">\\^(\\w+)[\\W]?(?:\\s(.+))?(?:<\/div><p)');
    if (Popup.innerHTML.match(PMSearch)) {
        var User = RegExp.$1;
        var Command = RegExp.$2;
        var Args = parseArgs(RegExp.$3);
        var isAdmin = false;
        for (var U in adminAliases) {
            if (User == adminAliases[U]) {
                isAdmin = true;
                break;
            }
        }

        if (window.ADMIN_COMMANDS[Command] && isAdmin) {
            log.warn("Admin command " + Command + " called by " + User + " via PM");
            log.debug("With arguments \"" + Args + "\"");
            window.ADMIN_COMMANDS[Command](Args);
        } else if (IsSleeping == 1 || (WHSwitch >= 3 && !isAdmin)) {
            closePopup();
            return;
        } else if (window.ADMIN_COMMANDS[Command] && !isAdmin) {
            log.warn("Admin command " + Command + " ignored from " + User + " via PM");
            log.debug("With arguments \"" + Args + "\"");
            privateMessage(User, "Sorry, that command is Admin only, and I don't recognize you!");
        } else if (window.UserCommands[Command]) {
            log.info("User command " + Command + " called by " + User + " via PM");
            log.debug("With arguments \"" + Args + "\"");
            window.UserCommands[Command](Args, User);
        } else if (window.Commands[Command]) {
            log.info("Command " + Command + " called by " + User + " via PM");
            log.debug("With arguments \"" + Args + "\"");
            window.Commands[Command](Args);
        } else {
            log.debug("Failed to parse " + Command + " via PM");
            privateMessage(User, "Sorry, I don't understand that. May I suggest ^help?");
        }
    } else if (Popup.style.display === "") {
        closePopup();
    }
}

function mainLoop() {
    //writingHour();
    if (CommandsLoaded) {
        readChat();
        readPMs();
    }
}

function talosStart() {
    log.debug("Talos Starting");

    readFile(ADMIN_URL).then(function(fileText){
        parseAdmins(fileText).forEach(function(item) {ADMINS.push(item);});
        Object.freeze(ADMINS);
        getAdminNames();
    });

    elementByID(messageTable).innerHTML = '
Previous messages parsed (press ESC to re-parse page)
\n';
    window[isCleared] = false;
    setInterval(function() {mainLoop();}, 1000);
    setInterval(function() {window[timeoutTimer] = new Date().getTime(); getAdminNames();}, 1000*60*10);
}
<commit_msg>Logging some stuff for debug<commit_after>/*
    --------------------
    Initialize Variables
    --------------------
*/

//Constants
const VERSION = 1.6; //Current Version. Increment upon major changes to structure or functionality.
const BOOT_TIME = new Date(); //Exact time of Talos boot, used to determine uptime.
const WH_TIME = 0; //What hour Writing Hour should start at, in UTC
const ADMIN_URL = "http://localhost:8000/Admins.txt"; //URL to pull admin list from
const ADMINS = []; //Will be filled with Admin data from file

//Control variables
var CommandsLoaded = false; //So that commands are not run while the Commands script is not yet loaded.
var adminAliases = []; //Current usernames of admins in chat. Will be filled by getAdminNames.

//Writing Hour variables
var WHSwitch = 0; //Used by WH function to determine what point it is at of its function.

/*
    -------------------
    Arbitrary functions
    -------------------
*/

/**
 * Returns a random number that is in the range of [min, max).
 * @param {int} min minimum value, inclusive
 * @param {int} max maximum value, exclusive
 * @returns {int} random number between those two values
 */
function randomNumber(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

/**
 * Starts a WW of the specified length with the specified keyword. WW ends itself after length has elapsed.
 * @param {float} length Length of the WW, in minutes
 * @param {String} keyword Keyword for the WW, a string that is used as an identifier for the start and end
 */
function startWW(length, KeyWord) {
    setTimeout(function() {
        NumWWs--;
        if (!IsSleeping) {
            postMessage("[b]Word War " + (KeyWord? "'" + KeyWord + "' " : "") + "ends.[/b] How did you do?");
        }
    }, length * 60000);
}

/**
 * Given the admin file as a string, converts it into a list of the admin's IDs. File is a CSV file in the form
 * <Nickname>,<User ID>
 * @param {String} str String form of the admin file.
 * @returns {Array} Chatzy Admin IDs
 */
function parseAdmins(str) {
    str = str.split(/\r?\n/);
    for (var i in str) {
        if (str.hasOwnProperty(i)) {
            str[i] = str[i].split(",")[1];
        }
    }
    return str;
}

/**
 * Parse a string of arguments into a list of strings. Split on spaces, except inside quotes.
 * @param {String} str String of arguments to parse
 * @returns {Array} Arguments as strings, quotations stripped
 */
function parseArgs(str) {
    var out = [];

    if (str.match(/".*?"/)) {
        var delim = false;
        var arg = "";
        for (var char in str) {
            if (str[char] == "\"") {
                delim = !delim;
                if (arg) {
                    out.push(arg);
                    arg = "";
                }
            } else if (str[char] == " " && !delim) {
                if (arg) {
                    out.push(arg);
                    arg = "";
                }
            } else {
                arg += str[char];
            }
        }
        if (arg) {
            out.push(arg);
        }
    } else {
        out = str.split(/\s/);
    }

    return out;
}

/**
 * Simply a wrap for the JSON stringify function
 * @param {Object} object Object to turn into a String
 * @returns {String} string form of the object
 */
function stringify(object) {
    return JSON.stringify(object);
}

/**
 * A wrap for the JSON parse function
 * @param {String} string String to turn into an Object
 * @returns {Object} Object form of the input string
 */
function parse(string) {
    return JSON.parse(string);
}

/**
 * Sets the localStorage value for the given key and content
 * @param {String} key Key value within which to store the content
 * @param content Value to store in the key.
 */
function setStorage(key, content) {
    window.localStorage[key] = content;
}

/**
 * Returns the value of a specific key from the localStorage.
 * @param {String} key Key value to retrieve
 * @returns {String} Value of whatever was stored at that key location. undefined if nonextant.
 */
function getStorage(key) {
    return window.localStorage[key];
}

/**
 * Removes the specified key entirely from the localStorage
 * @param {String} key Key to remove from storage
 * @returns {String} Whatever was previously stored in localStorage.
 */
function removeStorage(key) {
    var oldItem = getStorage(key);
    window.localStorage.removeItem(key);
    return oldItem;
}

/**
 * Nulls out the Commands script variables, removes the script from the DOM, and reloads it.
 */
function reloadCommands() {
    CommandScript.remove();
    CommandsLoaded = false;

    Commands = undefined;
    UserCommands = undefined;
    ADMIN_COMMANDS = undefined;
    var TalosCommands = makeElement('script', {'type':'text/javascript',
                                           'src': MAIN_URL + 'Commands.js',
                                           'onload':'CommandsLoaded = true',
                                           'id':'CommandScript'});
    document.head.appendChild(TalosCommands);
}

/**
 * Retrieves a file over HTTP, from a given URL or address.
 * @param {String} file Full URL link of file to retrieve.
 * @returns {Promise} A promise for the text of the file. Will resolve on succesfull retrieval, reject otherwise.
 */
function readFile(file) {
    return new Promise(function(resolve, reject) {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function () {
            if(rawFile.readyState === 4) {
                if(rawFile.status === 200 || rawFile.status === 0) {
                    var allText = rawFile.responseText;
                    resolve(allText);
                } else {
                    reject();
                }
            } else {
                reject();
            }
        };
        rawFile.send(null);
    });
}

/**
 * Empties out the adminAliases variable, then fills it with the current in-chat usernames of all admins.
 */
function getAdminNames() {
    getVisitorData(["Alias","UID"]).then(function(visitorData) {
        adminAliases = [];
        for (var i = 0; i < visitorData.length; i++) {
            var visitor = visitorData[i];
            if (visitor[1] == "(Email hidden)") {
                continue;
            }
            if (visitor[1][0] == "\"") {
                visitor[1] =  visitor[1].substr(1,visitor[1].length-2);
            }
            for (var j = 0; j < ADMINS.length; j++) {
                if (ADMINS[j] == visitor[1]) {
                    adminAliases.push(visitor[0]);
                }
            }
        }
    });
}

/*
    -------------------
    Main loop functions
    -------------------
*/

/**
 * Time based function that will run writing hour, at the hour specified by WH_TIME.
 */
function writingHour() {
    var d = new Date();

    if (d.getUTCHours() == (WH_TIME === 0 ? 23 : WH_TIME - 1)  && d.getUTCMinutes() == 50 && WHSwitch === 0) {
        postMessage("[b][Alert][/b] 10 minutes until WH!");
        WHSwitch++;
    } else if (d.getUTCHours() == (WH_TIME === 0 ? 23 : WH_TIME - 1) && d.getUTCMinutes() == 55 && WHSwitch == 1) {
        postMessage("[b][Alert][/b] 5 minutes until WH!");
        WHSwitch++;
    } else if (d.getUTCHours() == WH_TIME && d.getUTCMinutes() === 0 && WHSwitch == 2) {
        postMessage("[b]Writing Hour begins![/b] Time to write, good luck!");
        setTimeout(function(){closeChat();}, 1000);
        WHSwitch++;
    } else if (d.getUTCHours() == (WH_TIME == 23 ? 0 : WH_TIME + 1) && d.getUTCMinutes() === 0 && WHSwitch == 3) {
        setTimeout(function() {postMessage("[b]Writing Hour is over.[/b]");}, 500);
        setTimeout(function(){openChat();}, 1000);
        WHSwitch = 0;
    }
}

/**
 * Function that reads chat. Will parse chat as a list of HTML strings, and iterate through them.
 * Looks for commands of the form
 * ^<Command> <arg1> "<arg3>" ...
 * And passes those on to the ADMIN_COMMANDS, UserCommands, or Commands dict in that precedence.
 */
function readChat() {
    console.log(!elementByID(messageContainer) + " " +
                !elementByID(messageTable) + " " +
                !elementByID(messageTable).children + " " +
                elementByID(messageTable).firstChild.innerHTML != "Previous messages parsed (press ESC to re-parse page)");
    if (!elementByID(messageContainer) ||
            !elementByID(messageTable) ||
            !elementByID(messageTable).children ||
            elementByID(messageTable).firstChild.innerHTML != "Previous messages parsed (press ESC to re-parse page)") {
        return;
    }
    try {
        var Messages = elementByID(messageTable).children;
        for (var i = 1; i < Messages.length; i++) {
            try {
                var Message = Messages[i].childNodes;
                if(!Message[1] || !Message[1].data) {
                    continue;
                }

                var text = Message[1].data;

                if (text.match(/^: \^\w/)) {
                    var User = Message[0].innerText;
                    var Command = /\^(\w+)/.exec(text)[1];
                    var Args = text.substr(Command.length + 3).match(/([^\s"]+)|"(.+?)"/g);

                    if (Args === null) {
                        Args = [];
                    }

                    var isAdmin = false;
                    for (var U in adminAliases) {
                        if (User == adminAliases[U]) {
                            isAdmin = true;
                            break;
                        }
                    }

                    //console.log(Command + " | " + /*FirstArgs + " |*/ "\"" + Args + "\"");

                    if (window.ADMIN_COMMANDS[Command] && isAdmin) {
                        log.warn("Admin command " + Command + " called by " + User);
                        log.debug("With arguments \"" + Args + "\"");
                        window.ADMIN_COMMANDS[Command](Args, User);
                    } else if (IsSleeping == 1) {
                        break;
                    } else if (window.ADMIN_COMMANDS[Command] && !isAdmin) {
                        log.warn("Admin command " + Command + " ignored from " + User);
                        log.debug("With arguments \"" + Args + "\"");
                        postMessage("Sorry, that command is Admin only, and I don't recognize you!");
                    } else if (window.UserCommands[Command]){
                        log.info("User command " + Command + " called by " + User);
                        log.debug("With arguments \"" + Args + "\"");
                        window.UserCommands[Command](Args, User);
                    } else if (window.Commands[Command]) {
                        log.info("Command " + Command + " called by " + User);
                        log.debug("With arguments \"" + Args + "\"");
                        window.Commands[Command](Args);
                    } else {
                        log.debug("Failed to parse " + Command);
                        postMessage("Sorry, I don't understand that. May I suggest ^help?");
                    }
                }
            } catch (Exception) {}
        }
    } finally {
        elementByID(messageTable).innerHTML = '
Previous messages parsed (press ESC to re-parse page)
\n';
        window[isCleared] = false;
    }
}

/**
 * Reads received PMs, using the same command format as used for read chat messsages.
 */
function readPMs() {
    var Popup = elementByID(popup);
    var PMSearch = new RegExp('.+>(.+)<\/em>.+' + textBox + '">\\^(\\w+)[\\W]?(?:\\s(.+))?(?:<\/div><p)');
    if (Popup.innerHTML.match(PMSearch)) {
        var User = RegExp.$1;
        var Command = RegExp.$2;
        var Args = parseArgs(RegExp.$3);
        var isAdmin = false;
        for (var U in adminAliases) {
            if (User == adminAliases[U]) {
                isAdmin = true;
                break;
            }
        }

        if (window.ADMIN_COMMANDS[Command] && isAdmin) {
            log.warn("Admin command " + Command + " called by " + User + " via PM");
            log.debug("With arguments \"" + Args + "\"");
            window.ADMIN_COMMANDS[Command](Args);
        } else if (IsSleeping == 1 || (WHSwitch >= 3 && !isAdmin)) {
            closePopup();
            return;
        } else if (window.ADMIN_COMMANDS[Command] && !isAdmin) {
            log.warn("Admin command " + Command + " ignored from " + User + " via PM");
            log.debug("With arguments \"" + Args + "\"");
            privateMessage(User, "Sorry, that command is Admin only, and I don't recognize you!");
        } else if (window.UserCommands[Command]) {
            log.info("User command " + Command + " called by " + User + " via PM");
            log.debug("With arguments \"" + Args + "\"");
            window.UserCommands[Command](Args, User);
        } else if (window.Commands[Command]) {
            log.info("Command " + Command + " called by " + User + " via PM");
            log.debug("With arguments \"" + Args + "\"");
            window.Commands[Command](Args);
        } else {
            log.debug("Failed to parse " + Command + " via PM");
            privateMessage(User, "Sorry, I don't understand that. May I suggest ^help?");
        }
    } else if (Popup.style.display === "") {
        closePopup();
    }
}

/**
 * Primary running loop of Talos. This will be called once per second by default, and in turn should
 * call helper functions to perform actual operations.
 */
function mainLoop() {
    //writingHour();
    if (CommandsLoaded) {
        readChat();
        readPMs();
    }
}

/**
 * Starts Talos. Reads in admin file and turns it to names, sets up chat for readChat, and spins off the
 * mainLoop as well as a process to periodically reset the timeout and get the admin names again.
 */
function talosStart() {
    log.debug("Talos Starting");

    readFile(ADMIN_URL).then(function(fileText){
        parseAdmins(fileText).forEach(function(item) {ADMINS.push(item);});
        Object.freeze(ADMINS);
        getAdminNames();
    });

    elementByID(messageTable).innerHTML = '
Previous messages parsed (press ESC to re-parse page)
\n';
    window[isCleared] = false;
    setInterval(function() {mainLoop();}, 1000);
    setInterval(function() {window[timeoutTimer] = new Date().getTime(); getAdminNames();}, 1000*60*10);
}
<|endoftext|>


<commit_before>STAN = {
    compile: function(_template_) {
        var ms, result = _template_.toString()
            .replace(/function\s+([\d\w_]+)\s*\(\s*\)\s*{([\S\s]+)}/,'(function $1(){$2})()')
            .replace(/(\w+)(?:\[['"]([^\]]*)['"]\])?\.(e|b)\s*[\n;}]/g, function(m,t,x,e){ return "r+='<" + (e=="b"?"":"/") + t + " " + (x||'') + ">';" })
            .replace(/(\w+)(?:\[['"]([^\]]*)['"]\])?\.(.+)\.(\w+)\s*[\n;}]/g, function(m,s,x,b,e){
                if(s==e) {return "r+='<" + s + " " + (x||'') + ">'+(" + b + ")+'</" + e + ">';"} else return m })
            .replace(/([\n;{]\s*)(\w+)(\s*[\n;}])/g, "$1r+='<$2/>'$3;")
        while (ms = result.match(/partial\([_\w\d\.]+/g)) {
            for (var i=0; i< ms.length; i++) {
                var tn = ms[i].replace('partial(','')
                result = result.replace(tn, STAN.compile(eval(tn)).replace('})()','})'))
            }
        }
        return result
    },
    run: function(result, context, escape) {
        var r = "", raw = function(t){r+=t;return t}
        if (escape !== false) {
            var div = document.createElement('div')
            div.appendChild(document.createTextNode(JSON.stringify(context)))
            context = JSON.parse(div.innerHTML)
        }
        function partial(fn, ctx) {
            var oldCtx = context
            context = ctx; fn(); context = oldCtx
        }
        return eval(result), r
    }
}<commit_msg>STAN - support js functions inside of 'attributes' declaration<commit_after>STAN = {
    compile: function(_template_) {
        var ms, result = _template_.toString()
            .replace(/function\s+([\d\w_]+)\s*\(\s*\)\s*{([\S\s]+)}/,'(function $1(){$2})()')
            .replace(/(\w+)(?:\[(['"]?[^\]]*?['"]?)\])?\.(e|b)\s*[\n;}]/g, function(m,t,x,e){
                return "r+='<" + (e=="b"?"":"/") + t + " '+(" + (x||'""') + ")+'>';" })
            .replace(/(\w+)(?:\[(['"]?[^\]]*?['"]?)\])?\.(.+)\.(\w+)\s*[\n;}]/g, function(m,s,x,b,e){
                if(s==e) {return "r+='<" + s + " '+(" + (x||'""') + ")+'>'+(" + b + ")+'</" + e + ">';"} else return m })
            .replace(/([\n;{]\s*)(\w+)(\s*[\n;}])/g, "$1r+='<$2/>'$3;")
        while (ms = result.match(/partial\([_\w\d\.]+/g)) {
            for (var i=0; i< ms.length; i++) {
                var tn = ms[i].replace('partial(','')
                result = result.replace(tn, STAN.compile(eval(tn)).replace('})()','})'))
            }
        }
        return result
    },
    run: function(result, context, escape) {
        var r = "", raw = function(t){r+=t;return t}
        if (escape !== false) {
            var div = document.createElement('div')
            div.appendChild(document.createTextNode(JSON.stringify(context)))
            context = JSON.parse(div.innerHTML)
        }
        function partial(fn, ctx) {
            var oldCtx = context; context = ctx; fn(); context = oldCtx
        }
        return eval(result), r
    }
}<|endoftext|>


<commit_before>var starjs = {
	correct: function(message, allowMultipleCorrections = false, allowLongCorrections = false) {
		var correction = message[1];
		correction = correction.split("*");
		var words = message[0].split(" ");

		if (message[1].split(" ").length > words.length) {
			return false;
		}

		if (!allowLongCorrections) {
			if (message[1].split(" ").length > 4) {
				return false; // disallow long corrections
			}
		}

		var modifiedText = false;
		for (var i = words.length; i--;) {

			if (this.soundex(words[i]) == this.soundex(correction)) {
				words[i] = correction;
				modifiedText = true;
				if (!allowMultipleCorrections) {
					break;
				}
			}

		}
		if (modifiedText) {
			return words.join(" ");
		} else {
			return false;
		}

	},
	soundex: function(str) {
		str = str.toString();
		str = str.toUpperCase();
		str = str.split('');

		var firstLetter = str[0];

		// convert letters to numeric code
		for (var i = 0; i < str.length; i++) {
			switch (str[i]) {

				case 'B':
				case 'F':
				case 'P':
				case 'V':
					str[i] = '1';
					break;

				case 'C':
				case 'G':
				case 'J':
				case 'K':
				case 'Q':
				case 'S':
				case 'X':
				case 'Z':
					str[i] = '2';
					break;

				case 'D':
				case 'T':
					str[i] = '3';
					break;

				case 'L':
					str[i] = '4';
					break;

				case 'M':
				case 'N':
					str[i] = '5';
					break;

				case 'R':
					str[i] = '6';
					break;

				default:
					str[i] = '0';
					break;
			}
		}

		// remove duplicates
		var output = firstLetter;
		for (var i = 1; i < str.length; i++)
			if (str[i] != str[i-1] && str[i] != '0')
				output += str[i];

		// pad with 0's or truncate
		output = output + "0000";
		return output.substring(0, 4);
	}

};

module.exports = starjs;
<commit_msg>Reduce threshold for replacement length<commit_after>var starjs = {
	correct: function(message, allowMultipleCorrections = false, allowLongCorrections = false) {
		var correction = message[1];
		var words = message[0].split(" ");

		if (correction.split(" ").length - 2 > words.length) {
			console.log("Filter 1");
			return false;
		}

		correction = correction.split("*");
		if (!allowLongCorrections) {
			if (message[1].split(" ").length > 4) {
				console.log("Triggered filter 2");
				return false; // disallow long corrections
			}
		}

		var modifiedText = false;
		for (var i = words.length; i--;) {

			if (this.soundex(words[i]) == this.soundex(correction)) {
				words[i] = correction;
				modifiedText = true;
				if (!allowMultipleCorrections) {
					break;
				}
			}

		}
		if (modifiedText) {
			return words.join(" ");
		} else {
			console.log("Star.js: could not find suitable replacement.")
			return false;
		}

	},
	soundex: function(str) {
		str = str.toString();
		str = str.toUpperCase();
		str = str.split('');

		var firstLetter = str[0];

		// convert letters to numeric code
		for (var i = 0; i < str.length; i++) {
			switch (str[i]) {

				case 'B':
				case 'F':
				case 'P':
				case 'V':
					str[i] = '1';
					break;

				case 'C':
				case 'G':
				case 'J':
				case 'K':
				case 'Q':
				case 'S':
				case 'X':
				case 'Z':
					str[i] = '2';
					break;

				case 'D':
				case 'T':
					str[i] = '3';
					break;

				case 'L':
					str[i] = '4';
					break;

				case 'M':
				case 'N':
					str[i] = '5';
					break;

				case 'R':
					str[i] = '6';
					break;

				default:
					str[i] = '0';
					break;
			}
		}

		// remove duplicates
		var output = firstLetter;
		for (var i = 1; i < str.length; i++)
			if (str[i] != str[i-1] && str[i] != '0')
				output += str[i];

		// pad with 0's or truncate
		output = output + "0000";
		return output.substring(0, 4);
	}

};

module.exports = starjs;
<|endoftext|>


<commit_before>import Webiny from 'Webiny';
import Header from './Header';
import Footer from './Footer';
import Body from './Body';
import styles from '../styles.css';

const mountedDialogs = [];

function getShownDialog(id = null) {
    return _.find(mountedDialogs, item => item.state.isShown === true && item.id !== id);
}

class Dialog extends Webiny.Ui.Component {

    constructor(props) {
        super(props);
        this.id = _.uniqueId('modal-');

        this.state = {
            isShown: false,
            isDialogShown: false
        };

        this.modalShowDuration = 800;
        this.modalHideDuration = 250;
        this.backdropShowDuration = 100;
        this.backdropHideDuration = 200;

        this.animating = false;
        this.clickStartedOnBackdrop = false;
        if (!document.querySelector(props.modalContainerTag)) {
            document.body.appendChild(document.createElement(props.modalContainerTag));
        }

        this.modalContainer = document.querySelector(props.modalContainerTag);

        this.bindMethods('show,hide,isAnimating,bindHandlers,unbindHandlers,prepareChildren,prepareChild,animationFinish');
    }

    componentWillUpdate(nextProps, nextState) {
        super.componentWillUpdate(nextProps, nextState);
        const currentDialog = getShownDialog();
        const {dynamics} = this.props;

        // Hide currently visible dialog but do not unmount it
        if (currentDialog && currentDialog.id !== this.id && nextState.isShown) {
            const container = $(currentDialog.modalContainer);
            const dialog = container.find('[data-role="dialog"]');
            const backdrop = container.find('[data-role="backdrop"]');

            dynamics.animate(dialog[0], {
                opacity: 0,
                translateY: -100
            }, {
                type: dynamics.easeOut,
                duration: this.modalHideDuration,
                complete: () => {
                    // Need to hide .modal to let mouse events through
                    dialog.closest('[data-role="modal"]').hide();
                    // Remove transform so next time we animate, we start from scratch, with no transformations applied
                    dialog.css('transform', '');
                }
            });

            dynamics.animate(backdrop[0], {
                opacity: 0
            }, {
                type: dynamics.easeOut,
                duration: this.backdropHideDuration
            });
        }
    }

    componentDidUpdate(prevProps, prevState) {
        super.componentDidUpdate(prevProps, prevState);
        if (this.isShown()) {
            ReactDOM.render(this.props.renderDialog.call(this), this.modalContainer);
            $(this.modalContainer).find('[data-role="modal"]').focus();
            this.bindHandlers();
        } else if (prevState.isShown && !this.isShown()) {
            this.unbindHandlers();
            ReactDOM.unmountComponentAtNode(this.modalContainer);
        }
    }

    componentDidMount() {
        super.componentDidMount();
        mountedDialogs.push(this);
    }

    componentWillUnmount() {
        super.componentWillUnmount();
        this.unbindHandlers();
        mountedDialogs.splice(_.findIndex(mountedDialogs, {id: this.id}), 1);
        ReactDOM.unmountComponentAtNode(this.modalContainer);
    }

    shouldComponentUpdate(nextProps, nextState) {
        return !_.isEqual(nextProps, this.props) || !_.isEqual(nextState, this.state);
    }

    bindHandlers() {
        this.unbindHandlers();
        const namespace = '.' + this.id;
        $(this.props.modalContainerTag).on('keyup' + namespace, '[data-role="modal"]', e => {
            // Listen for ESC button
            if (e.keyCode === 27 && !this.animating && this.props.closeOnClick) {
                Promise.resolve(this.props.onCancel()).then(this.hide);
            }
        }).on('mousedown' + namespace, '[data-role="modal"]', e => {
            // Catch backdrop click
            if ($(e.target).attr('data-role') === 'modal') {
                this.clickStartedOnBackdrop = true;
            }
        }).on('click' + namespace, '[data-role="modal"]', () => {
            if (this.clickStartedOnBackdrop && this.props.closeOnClick) {
                Promise.resolve(this.props.onCancel()).then(this.hide);
            }
            this.clickStartedOnBackdrop = false;
        });
    }

    unbindHandlers() {
        $(this.props.modalContainerTag).off('.' + this.id);
    }

    hide() {
        if (!this.state.isDialogShown || this.animating) {
            return Promise.resolve(true);
        }

        this.animating = true;
        return Promise.resolve(this.props.onHide()).then(() => {
            return new Promise(resolve => {
                this.hideResolve = resolve;
                this.setState({
                    isDialogShown: false
                });
            });
        });
    }

    show() {
        // This shows the modal container element in case it was previously hidden by another dialog
        this.props.onShow();

        if (this.isShown()) {
            // Animate previously hidden dialog
            return new Promise(resolve => {
                const {dynamics} = this.props;
                this.animating = true;
                const prevContainer = $(this.modalContainer);
                const prevDialog = prevContainer.find('[data-role="dialog"]');
                const prevBackdrop = prevContainer.find('[data-role="backdrop"]');
                prevDialog.closest('[data-role="modal"]').show();
                dynamics.animate(prevDialog[0], {
                    opacity: 1,
                    translateY: 50
                }, {
                    type: dynamics.spring,
                    duration: this.modalShowDuration,
                    complete: () => {
                        prevDialog.closest('[data-role="modal"]').focus();
                        this.animating = false;
                        resolve();
                    }
                });

                dynamics.animate(prevBackdrop[0], {
                    opacity: 0.8
                }, {
                    type: dynamics.easeIn,
                    duration: this.backdropShowDuration
                });
            });
        }

        return new Promise(resolve => {
            // If showing previously visually hidden modal - resolve promise
            if (this.isShown()) {
                return resolve();
            }

            this.setState({
                isShown: true
            }, () => {
                // Now we are supposed to show dialog with animation
                this.animating = true;
                const show = () => {
                    this.setState({
                        isDialogShown: true
                    }, () => {
                        this.props.onShown();
                        resolve();
                    });
                };

                // If there was a previous dialog (eg: hidden with ClickConfirm), let the animation finish and show new dialog with delay
                if (getShownDialog(this.id)) {
                    setTimeout(show, 250);
                } else {
                    // No previous dialog was opened - we can safely show our new dialog
                    show();
                }
            });
        });
    }

    isShown() {
        return this.state.isShown;
    }

    isAnimating() {
        return this.animating;
    }

    prepareChild(child) {
        if (typeof child !== 'object' || child === null) {
            return child;
        }

        if (_.find([Header, Body, Footer], c => Webiny.isElementOfType(child, c))) {
            const props = {dialog: this};
            if (Webiny.isElementOfType(child, Header)) {
                props['onClose'] = this.hide;
            }
            return React.cloneElement(child, props);
        }

        if (child.props.children) {
            return React.cloneElement(child, _.omit(child.props, ['ref', 'key']), this.prepareChildren(child.props.children));
        }
        return child;
    }

    prepareChildren(children) {
        if (typeof children !== 'object' || children === null) {
            return children;
        }
        return React.Children.map(children, this.prepareChild);
    }

    animationFinish(isDialogShown) {
        this.animating = false;
        if (!isDialogShown) {
            this.setState({isShown: false}, this.props.onHidden);
            this.hideResolve && this.hideResolve();
        }
    }
}

Dialog.defaultProps = {
    wide: false,
    onHide: _.noop,
    onHidden: _.noop,
    onShow: _.noop,
    onShown: _.noop,
    onCancel: _.noop, // Called when dialog is closed using ESC or backdrop click
    closeOnClick: true,
    modalContainerTag: 'webiny-modal',
    style: {},
    renderDialog() {
        const {Animate, styles} = this.props;
        const className = this.classSet(styles.modal, (this.props.wide && styles.wide));
        let content = this.props.children;
        if (_.isFunction(content)) {
            content = content.call(this, this);
        }
        return (

                <Animate
                    trigger={this.state.isDialogShown}
                    show={{opacity: 0.8, duration: this.backdropShowDuration, ease: 'easeIn'}}
                    hide={{opacity: 0, duration: this.backdropHideDuration, ease: 'easeOut'}}>

                </Animate>

                    <Animate
                        trigger={this.state.isDialogShown}
                        onFinish={this.animationFinish}
                        show={{translateY: 50, ease: 'spring', duration: this.modalShowDuration}}
                        hide={{translateY: -100, ease: 'easeOut', opacity: 0, duration: this.modalHideDuration}}>

                            {this.prepareChildren(content)}

                    </Animate>

        );
    },
    renderer() {
        return null;
    }
};

export default Webiny.createComponent(Dialog, {
    styles,
    modules: ['Animate', {dynamics: () => import('dynamics.js')}],
    api: ['show', 'hide', 'isShown', 'isAnimating']
});<commit_msg>Updated default modal show animation.<commit_after>import Webiny from 'Webiny';
import Header from './Header';
import Footer from './Footer';
import Body from './Body';
import styles from '../styles.css';

const mountedDialogs = [];

function getShownDialog(id = null) {
    return _.find(mountedDialogs, item => item.state.isShown === true && item.id !== id);
}

class Dialog extends Webiny.Ui.Component {

    constructor(props) {
        super(props);
        this.id = _.uniqueId('modal-');

        this.state = {
            isShown: false,
            isDialogShown: false
        };

        this.modalShowDuration = 500;
        this.modalHideDuration = 250;
        this.backdropShowDuration = 100;
        this.backdropHideDuration = 200;

        this.animating = false;
        this.clickStartedOnBackdrop = false;
        if (!document.querySelector(props.modalContainerTag)) {
            document.body.appendChild(document.createElement(props.modalContainerTag));
        }

        this.modalContainer = document.querySelector(props.modalContainerTag);

        this.bindMethods('show,hide,isAnimating,bindHandlers,unbindHandlers,prepareChildren,prepareChild,animationFinish');
    }

    componentWillUpdate(nextProps, nextState) {
        super.componentWillUpdate(nextProps, nextState);
        const currentDialog = getShownDialog();
        const {dynamics} = this.props;

        // Hide currently visible dialog but do not unmount it
        if (currentDialog && currentDialog.id !== this.id && nextState.isShown) {
            const container = $(currentDialog.modalContainer);
            const dialog = container.find('[data-role="dialog"]');
            const backdrop = container.find('[data-role="backdrop"]');

            dynamics.animate(dialog[0], {
                opacity: 0,
                translateY: -100
            }, {
                type: dynamics.easeOut,
                duration: this.modalHideDuration,
                complete: () => {
                    // Need to hide .modal to let mouse events through
                    dialog.closest('[data-role="modal"]').hide();
                    // Remove transform so next time we animate, we start from scratch, with no transformations applied
                    dialog.css('transform', '');
                }
            });

            dynamics.animate(backdrop[0], {
                opacity: 0
            }, {
                type: dynamics.easeOut,
                duration: this.backdropHideDuration
            });
        }
    }

    componentDidUpdate(prevProps, prevState) {
        super.componentDidUpdate(prevProps, prevState);
        if (this.isShown()) {
            ReactDOM.render(this.props.renderDialog.call(this), this.modalContainer);
            $(this.modalContainer).find('[data-role="modal"]').focus();
            this.bindHandlers();
        } else if (prevState.isShown && !this.isShown()) {
            this.unbindHandlers();
            ReactDOM.unmountComponentAtNode(this.modalContainer);
        }
    }

    componentDidMount() {
        super.componentDidMount();
        mountedDialogs.push(this);
    }

    componentWillUnmount() {
        super.componentWillUnmount();
        this.unbindHandlers();
        mountedDialogs.splice(_.findIndex(mountedDialogs, {id: this.id}), 1);
        ReactDOM.unmountComponentAtNode(this.modalContainer);
    }

    shouldComponentUpdate(nextProps, nextState) {
        return !_.isEqual(nextProps, this.props) || !_.isEqual(nextState, this.state);
    }

    bindHandlers() {
        this.unbindHandlers();
        const namespace = '.' + this.id;
        $(this.props.modalContainerTag).on('keyup' + namespace, '[data-role="modal"]', e => {
            // Listen for ESC button
            if (e.keyCode === 27 && !this.animating && this.props.closeOnClick) {
                Promise.resolve(this.props.onCancel()).then(this.hide);
            }
        }).on('mousedown' + namespace, '[data-role="modal"]', e => {
            // Catch backdrop click
            if ($(e.target).attr('data-role') === 'modal') {
                this.clickStartedOnBackdrop = true;
            }
        }).on('click' + namespace, '[data-role="modal"]', () => {
            if (this.clickStartedOnBackdrop && this.props.closeOnClick) {
                Promise.resolve(this.props.onCancel()).then(this.hide);
            }
            this.clickStartedOnBackdrop = false;
        });
    }

    unbindHandlers() {
        $(this.props.modalContainerTag).off('.' + this.id);
    }

    hide() {
        if (!this.state.isDialogShown || this.animating) {
            return Promise.resolve(true);
        }

        this.animating = true;
        return Promise.resolve(this.props.onHide()).then(() => {
            return new Promise(resolve => {
                this.hideResolve = resolve;
                this.setState({
                    isDialogShown: false
                });
            });
        });
    }

    show() {
        // This shows the modal container element in case it was previously hidden by another dialog
        this.props.onShow();

        if (this.isShown()) {
            // Animate previously hidden dialog
            return new Promise(resolve => {
                const {dynamics} = this.props;
                this.animating = true;
                const prevContainer = $(this.modalContainer);
                const prevDialog = prevContainer.find('[data-role="dialog"]');
                const prevBackdrop = prevContainer.find('[data-role="backdrop"]');
                prevDialog.closest('[data-role="modal"]').show();
                dynamics.animate(prevDialog[0], {
                    opacity: 1,
                    translateY: 50
                }, {
                    type: dynamics.spring,
                    duration: this.modalShowDuration,
                    complete: () => {
                        prevDialog.closest('[data-role="modal"]').focus();
                        this.animating = false;
                        resolve();
                    }
                });

                dynamics.animate(prevBackdrop[0], {
                    opacity: 0.8
                }, {
                    type: dynamics.easeIn,
                    duration: this.backdropShowDuration
                });
            });
        }

        return new Promise(resolve => {
            // If showing previously visually hidden modal - resolve promise
            if (this.isShown()) {
                return resolve();
            }

            this.setState({
                isShown: true
            }, () => {
                // Now we are supposed to show dialog with animation
                this.animating = true;
                const show = () => {
                    this.setState({
                        isDialogShown: true
                    }, () => {
                        this.props.onShown();
                        resolve();
                    });
                };

                // If there was a previous dialog (eg: hidden with ClickConfirm), let the animation finish and show new dialog with delay
                if (getShownDialog(this.id)) {
                    setTimeout(show, 250);
                } else {
                    // No previous dialog was opened - we can safely show our new dialog
                    show();
                }
            });
        });
    }

    isShown() {
        return this.state.isShown;
    }

    isAnimating() {
        return this.animating;
    }

    prepareChild(child) {
        if (typeof child !== 'object' || child === null) {
            return child;
        }

        if (_.find([Header, Body, Footer], c => Webiny.isElementOfType(child, c))) {
            const props = {dialog: this};
            if (Webiny.isElementOfType(child, Header)) {
                props['onClose'] = this.hide;
            }
            return React.cloneElement(child, props);
        }

        if (child.props.children) {
            return React.cloneElement(child, _.omit(child.props, ['ref', 'key']), this.prepareChildren(child.props.children));
        }
        return child;
    }

    prepareChildren(children) {
        if (typeof children !== 'object' || children === null) {
            return children;
        }
        return React.Children.map(children, this.prepareChild);
    }

    animationFinish(isDialogShown) {
        this.animating = false;
        if (!isDialogShown) {
            this.setState({isShown: false}, this.props.onHidden);
            this.hideResolve && this.hideResolve();
        }
    }
}

Dialog.defaultProps = {
    wide: false,
    onHide: _.noop,
    onHidden: _.noop,
    onShow: _.noop,
    onShown: _.noop,
    onCancel: _.noop, // Called when dialog is closed using ESC or backdrop click
    closeOnClick: true,
    modalContainerTag: 'webiny-modal',
    style: {},
    renderDialog() {
        const {Animate, styles} = this.props;
        const className = this.classSet(styles.modal, (this.props.wide && styles.wide));
        let content = this.props.children;
        if (_.isFunction(content)) {
            content = content.call(this, this);
        }
        return (

                <Animate
                    trigger={this.state.isDialogShown}
                    show={{opacity: 0.8, duration: this.backdropShowDuration, ease: 'easeIn'}}
                    hide={{opacity: 0, duration: this.backdropHideDuration, ease: 'easeOut'}}>

                </Animate>

                    <Animate
                        trigger={this.state.isDialogShown}
                        onFinish={this.animationFinish}
                        show={{translateY: 50, ease: 'spring', duration: this.modalShowDuration, frequency: 50, friction: 300}}
                        hide={{translateY: -100, ease: 'easeOut', opacity: 0, duration: this.modalHideDuration}}>

                            {this.prepareChildren(content)}

                    </Animate>

        );
    },
    renderer() {
        return null;
    }
};

export default Webiny.createComponent(Dialog, {
    styles,
    modules: ['Animate', {dynamics: () => import('dynamics.js')}],
    api: ['show', 'hide', 'isShown', 'isAnimating']
});<|endoftext|>


<commit_before>alert("hola mundo");
<commit_msg>Modificacion de texto original<commit_after>alert("EDITADO");
<|endoftext|>


<commit_before>// Created: 10/07/2006
// Updated: 10/19/2006

// handler
// Handles all of the user's actions and delegates tasks to other classes.
// Also keeps track of global information.
var REST_CANVAS = 1;
var DRAW_CANVAS = 2;
var SELECTED_CANVAS = 3;
var QUERY_CANVAS = 4;

// Global variable indicating which canvas is active:
var active_canvas = REST_CANVAS;

function handler() {

    // *******************************************
    // Public methods:
    // *******************************************

    // Handles when the user presses the delete button in response to
    // the "What is this object?" popup bubble.
    this.WhatIsThisObjectDeleteButton = function () {
      submission_edited = 0;
      this.QueryToRest();
    };

    // Submits the object label in response to the edit/delete popup bubble.
    this.SubmitEditLabel = function () {
      submission_edited = 1;
      var anno = select_anno;

      // object name
      old_name = LMgetObjectField(LM_xml,anno.anno_id,'name');
      if(document.getElementById('objEnter')) new_name = RemoveSpecialChars(document.getElementById('objEnter').value);
      else new_name = RemoveSpecialChars(adjust_objEnter);

      var re = /[a-zA-Z0-9]/;
      if(!re.test(new_name)) {
	alert('Please enter an object name');
	return;
      }

      if (use_attributes) {
	// occlusion field
	if (document.getElementById('occluded')) new_occluded = RemoveSpecialChars(document.getElementById('occluded').value);
	else new_occluded = RemoveSpecialChars(adjust_occluded);

	// attributes field
	if(document.getElementById('attributes')) new_attributes = RemoveSpecialChars(document.getElementById('attributes').value);
	else new_attributes = RemoveSpecialChars(adjust_attributes);
      }

      StopEditEvent();

      // Insert data to write to logfile:
      if(editedControlPoints) InsertServerLogData('cpts_modified');
      else InsertServerLogData('cpts_not_modified');

      // Object index:
      var obj_ndx = anno.anno_id;

      // Pointer to object:
      var curr_obj = $(LM_xml).children("annotation").children("object").eq(obj_ndx);

      // Set fields:
      curr_obj.children("name").text(new_name);
      if(curr_obj.children("automatic").length > 0) curr_obj.children("automatic").text("0");

      // Insert attributes (and create field if it is not there):
      if(curr_obj.children("attributes").length>0) curr_obj.children("attributes").text(new_attributes);
      else curr_obj.append("<attributes>" + new_attributes + "</attributes>");

      if(curr_obj.children("occluded").length>0) curr_obj.children("occluded").text(new_occluded);
      else curr_obj.append("<occluded>" + new_occluded + "</occluded>");

      if(editedControlPoints) {
	for(var jj=0; jj < AllAnnotations[obj_ndx].GetPtsX().length; jj++) {
	  curr_obj.children("polygon").children("pt").eq(jj).children("x").text(AllAnnotations[obj_ndx].GetPtsX()[jj]);
	  curr_obj.children("polygon").children("pt").eq(jj).children("y").text(AllAnnotations[obj_ndx].GetPtsY()[jj]);
	}
      }

      // Write XML to server:
      WriteXML(SubmitXmlUrl,LM_xml,function(){return;});

      // Refresh object list:
      if(view_ObjList) {
	RenderObjectList();
	ChangeLinkColorFG(anno.GetAnnoID());
      }
    };

    // Handles when the user presses the delete button in response to
    // the edit popup bubble.
    this.EditBubbleDeleteButton = function () {
        var idx = select_anno.GetAnnoID();

        if((IsUserAnonymous() || (!IsCreator(select_anno.GetUsername()))) && (!IsUserAdmin()) && (idx<num_orig_anno) && !action_DeleteExistingObjects) {
            alert('You do not have permission to delete this polygon');
            return;
        }

        if(idx>=num_orig_anno) {
            global_count--;
        }

        submission_edited = 0;

        // Insert data for server logfile:
        old_name = LMgetObjectField(LM_xml,select_anno.anno_id,'name');
        new_name = old_name;
        WriteLogMsg('*Deleting_object');
        InsertServerLogData('cpts_not_modified');

        // Set <deleted> in LM_xml:
        $(LM_xml).children("annotation").children("object").eq(idx).children("deleted").text('1');

        // Remove all the part dependencies for the deleted object
        removeAllParts(idx);

        // Write XML to server:
        WriteXML(SubmitXmlUrl,LM_xml,function(){return;});

	// Refresh object list:
        if(view_ObjList) RenderObjectList();

        unselectObjects(); // Perhaps this should go elsewhere...
        StopEditEvent();
    };

    // Handles when the user clicks on the link for an annotation.
    this.AnnotationLinkClick = function (idx) {
      if(active_canvas==REST_CANVAS) StartEditEvent(idx,null);
      else if(active_canvas==SELECTED_CANVAS) {
	var anno_id = select_anno.GetAnnoID();
	if(edit_popup_open && (idx==anno_id)) StopEditEvent();
      }
    };

    // Handles when the user moves the mouse over an annotation link.
    this.AnnotationLinkMouseOver = function (a) {
        if(active_canvas!=SELECTED_CANVAS) selectObject(a);
    };

    // Handles when the user moves the mouse away from an annotation link.
    this.AnnotationLinkMouseOut = function () {
        if(active_canvas!=SELECTED_CANVAS) unselectObjects();
    };

    // Handles when the user moves the mouse over a polygon on the drawing
    // canvas.
    this.CanvasMouseMove = function (event,pp) {
        var x = GetEventPosX(event);
        var y = GetEventPosY(event);
        if(IsNearPolygon(x,y,pp)) selectObject(pp);
        else unselectObjects();
    };

    // Submits the object label in response to the "What is this object?"
    // popup bubble. THIS FUNCTION IS A MESS!!!!
    this.SubmitQuery = function () {
      var nn;
      var anno;

      // If the attributes are active, read the fields.
      if (use_attributes) {
	// get attributes (is the field exists)
	if(document.getElementById('attributes')) new_attributes = RemoveSpecialChars(document.getElementById('attributes').value);
	else new_attributes = "";

	// get occlusion field (is the field exists)
	if (document.getElementById('occluded')) new_occluded = RemoveSpecialChars(document.getElementById('occluded').value);
	else new_occluded = "";
      }

      if((object_choices!='...') && (object_choices.length==1)) {
	nn = RemoveSpecialChars(object_choices[0]);
	active_canvas = REST_CANVAS;

	// Move draw canvas to the back:
	document.getElementById('draw_canvas').style.zIndex = -2;
	document.getElementById('draw_canvas_div').style.zIndex = -2;

	// Remove polygon from the draw canvas:
	var anno = null;
	if(draw_anno) {
	  draw_anno.DeletePolygon();
	  anno = draw_anno;
	  draw_anno = null;
	}
      }
      else {
	nn = RemoveSpecialChars(document.getElementById('objEnter').value);
	anno = this.QueryToRest();
      }

      var re = /[a-zA-Z0-9]/;
      if(!re.test(nn)) {
	alert('Please enter an object name');
	return;
      }

      // Update old and new object names for logfile:
      new_name = nn;
      old_name = nn;

      submission_edited = 0;
      global_count++;

      // Insert data for server logfile:
      InsertServerLogData('cpts_not_modified');

      // Insert data into XML:
      var html_str = '<object>';
      html_str += '<name>' + new_name + '</name>';
      html_str += '<deleted>0</deleted>';
      html_str += '<verified>0</verified>';
      if(use_attributes) {
	html_str += '<occluded>' + new_occluded + '</occluded>';
	html_str += '<attributes>' + new_attributes + '</attributes>';
      }
      html_str += '<parts><hasparts></hasparts><ispartof></ispartof></parts>';
      var ts = GetTimeStamp();
      if(ts.length==20) html_str += '<date>' + ts + '</date>';
      html_str += '<id>' + anno.anno_id + '</id>';

      if(anno.GetType() == 1) {
	/*************************************************************/
	/*************************************************************/
	// Scribble: Add annotation to LM_xml:
	html_str += '<segm>';
	html_str += '<username>' + username + '</username>';

	html_str += '<box>';
	html_str += '<xmin>' + anno.GetPtsX()[0] + '</xmin>';
	html_str += '<ymin>' + anno.GetPtsY()[0] + '</ymin>';
	html_str += '<xmax>' + anno.GetPtsX()[1] + '</xmax>';
	html_str += '<ymax>' + anno.GetPtsY()[2] + '</ymax>';
	html_str += '</box>';

	html_str += '<mask>'+ anno.GetImName()+'</mask>';

	html_str += '<scribbles>';
	html_str += '<xmin>' + anno.GetCornerLX() + '</xmin>';
	html_str += '<ymin>' + anno.GetCornerLY() + '</ymin>';
	html_str += '<xmax>' + anno.GetCornerRX() + '</xmax>';
	html_str += '<ymax>' + anno.GetCornerRY() + '</ymax>';
	html_str += '<scribble_name>'+ anno.GetScribbleName()+'</scribble_name>';
	html_str += '</scribbles>';

	html_str += '</segm>';
	html_str += '</object>';
	$(LM_xml).children("annotation").append($(html_str));
	/*************************************************************/
	/*************************************************************/
      }
      else {
	html_str += '<polygon>';
	html_str += '<username>' + username + '</username>';
	for(var jj=0; jj < anno.GetPtsX().length; jj++) {
	  html_str += '<pt>';
	  html_str += '<x>' + anno.GetPtsX()[jj] + '</x>';
	  html_str += '<y>' + anno.GetPtsY()[jj] + '</y>';
	  html_str += '</pt>';
	}
	html_str += '</polygon>';
	html_str += '</object>';
	$(LM_xml).children("annotation").append($(html_str));
      }

      AllAnnotations.push(anno);

      if(!anno.GetDeleted()||view_Deleted) {
	main_canvas.AttachAnnotation(anno);
	main_canvas.RenderAnnotations();
      }

      /*************************************************************/
      /*************************************************************/
      // Scribble: Clean scribbles.
      if(anno.GetType() == 1) {
	scribble_canvas.cleanscribbles();
	scribble_canvas.scribble_image = "";
	scribble_canvas.colorseg = Math.floor(Math.random()*14);
      }
      /*************************************************************/
      /*************************************************************/

      // Write XML to server:
      WriteXML(SubmitXmlUrl,LM_xml,function(){return;});

      if(view_ObjList) RenderObjectList();

      var m = main_image.GetFileInfo().GetMode();
      if(m=='mt') {
	document.getElementById('object_name').value=new_name;
	document.getElementById('number_objects').value=global_count;
	document.getElementById('LMurl').value = LMbaseurl + '?collection=LabelMe&mode=i&folder=' + main_image.GetFileInfo().GetDirName() + '&image=' + main_image.GetFileInfo().GetImName();
	if(global_count >= mt_N) document.getElementById('mt_submit').disabled=false;
      }
    };

    // Handles when we wish to change from "query" to "rest".
    this.QueryToRest = function () {
        active_canvas = REST_CANVAS;

	// Move query canvas to the back:
	document.getElementById('query_canvas').style.zIndex = -2;
	document.getElementById('query_canvas_div').style.zIndex = -2;

	// Remove polygon from the query canvas:
	if(query_anno) query_anno.DeletePolygon();
	var anno = query_anno;
	query_anno = null;

	CloseQueryPopup();
	main_image.ScrollbarsOn();

        return anno;
    };

    // Handles when the user presses a key while interacting with the tool.
    this.KeyPress = function (event) {
        // Delete event: 46 - delete key; 8 - backspace key
        if(((event.keyCode==46) || (event.keyCode==8)) && !wait_for_input && !edit_popup_open && !username_flag) {
            // Determine whether we are deleting a complete or partially
            // complete polygon.
            if(!main_handler.EraseSegment()) DeleteSelectedPolygon();
        }
        // 27 - Esc key
        // Close edit popup if it is open.
        if(event.keyCode==27 && edit_popup_open) StopEditEvent();
    };

    // Handles when the user erases a segment.
    this.EraseSegment = function () {
        if(draw_anno && !draw_anno.DeleteLastControlPoint()) {
            submission_edited = 0;
            StopDrawEvent();
        }
        return draw_anno;
    };

    // *******************************************
    // Private methods:
    // *******************************************

}
<commit_msg>render only last drawn annotation, i.e. do not refresh all annotations<commit_after>// Created: 10/07/2006
// Updated: 10/19/2006

// handler
// Handles all of the user's actions and delegates tasks to other classes.
// Also keeps track of global information.
var REST_CANVAS = 1;
var DRAW_CANVAS = 2;
var SELECTED_CANVAS = 3;
var QUERY_CANVAS = 4;

// Global variable indicating which canvas is active:
var active_canvas = REST_CANVAS;

function handler() {

    // *******************************************
    // Public methods:
    // *******************************************

    // Handles when the user presses the delete button in response to
    // the "What is this object?" popup bubble.
    this.WhatIsThisObjectDeleteButton = function () {
      submission_edited = 0;
      this.QueryToRest();
    };

    // Submits the object label in response to the edit/delete popup bubble.
    this.SubmitEditLabel = function () {
      submission_edited = 1;
      var anno = select_anno;

      // object name
      old_name = LMgetObjectField(LM_xml,anno.anno_id,'name');
      if(document.getElementById('objEnter')) new_name = RemoveSpecialChars(document.getElementById('objEnter').value);
      else new_name = RemoveSpecialChars(adjust_objEnter);

      var re = /[a-zA-Z0-9]/;
      if(!re.test(new_name)) {
	alert('Please enter an object name');
	return;
      }

      if (use_attributes) {
	// occlusion field
	if (document.getElementById('occluded')) new_occluded = RemoveSpecialChars(document.getElementById('occluded').value);
	else new_occluded = RemoveSpecialChars(adjust_occluded);

	// attributes field
	if(document.getElementById('attributes')) new_attributes = RemoveSpecialChars(document.getElementById('attributes').value);
	else new_attributes = RemoveSpecialChars(adjust_attributes);
      }

      StopEditEvent();

      // Insert data to write to logfile:
      if(editedControlPoints) InsertServerLogData('cpts_modified');
      else InsertServerLogData('cpts_not_modified');

      // Object index:
      var obj_ndx = anno.anno_id;

      // Pointer to object:
      var curr_obj = $(LM_xml).children("annotation").children("object").eq(obj_ndx);

      // Set fields:
      curr_obj.children("name").text(new_name);
      if(curr_obj.children("automatic").length > 0) curr_obj.children("automatic").text("0");

      // Insert attributes (and create field if it is not there):
      if(curr_obj.children("attributes").length>0) curr_obj.children("attributes").text(new_attributes);
      else curr_obj.append("<attributes>" + new_attributes + "</attributes>");

      if(curr_obj.children("occluded").length>0) curr_obj.children("occluded").text(new_occluded);
      else curr_obj.append("<occluded>" + new_occluded + "</occluded>");

      if(editedControlPoints) {
	for(var jj=0; jj < AllAnnotations[obj_ndx].GetPtsX().length; jj++) {
	  curr_obj.children("polygon").children("pt").eq(jj).children("x").text(AllAnnotations[obj_ndx].GetPtsX()[jj]);
	  curr_obj.children("polygon").children("pt").eq(jj).children("y").text(AllAnnotations[obj_ndx].GetPtsY()[jj]);
	}
      }

      // Write XML to server:
      WriteXML(SubmitXmlUrl,LM_xml,function(){return;});

      // Refresh object list:
      if(view_ObjList) {
	RenderObjectList();
	ChangeLinkColorFG(anno.GetAnnoID());
      }
    };

    // Handles when the user presses the delete button in response to
    // the edit popup bubble.
    this.EditBubbleDeleteButton = function () {
        var idx = select_anno.GetAnnoID();

        if((IsUserAnonymous() || (!IsCreator(select_anno.GetUsername()))) && (!IsUserAdmin()) && (idx<num_orig_anno) && !action_DeleteExistingObjects) {
            alert('You do not have permission to delete this polygon');
            return;
        }

        if(idx>=num_orig_anno) {
            global_count--;
        }

        submission_edited = 0;

        // Insert data for server logfile:
        old_name = LMgetObjectField(LM_xml,select_anno.anno_id,'name');
        new_name = old_name;
        WriteLogMsg('*Deleting_object');
        InsertServerLogData('cpts_not_modified');

        // Set <deleted> in LM_xml:
        $(LM_xml).children("annotation").children("object").eq(idx).children("deleted").text('1');

        // Remove all the part dependencies for the deleted object
        removeAllParts(idx);

        // Write XML to server:
        WriteXML(SubmitXmlUrl,LM_xml,function(){return;});

	// Refresh object list:
        if(view_ObjList) RenderObjectList();

        unselectObjects(); // Perhaps this should go elsewhere...
        StopEditEvent();
    };

    // Handles when the user clicks on the link for an annotation.
    this.AnnotationLinkClick = function (idx) {
      if(active_canvas==REST_CANVAS) StartEditEvent(idx,null);
      else if(active_canvas==SELECTED_CANVAS) {
	var anno_id = select_anno.GetAnnoID();
	if(edit_popup_open && (idx==anno_id)) StopEditEvent();
      }
    };

    // Handles when the user moves the mouse over an annotation link.
    this.AnnotationLinkMouseOver = function (a) {
        if(active_canvas!=SELECTED_CANVAS) selectObject(a);
    };

    // Handles when the user moves the mouse away from an annotation link.
    this.AnnotationLinkMouseOut = function () {
        if(active_canvas!=SELECTED_CANVAS) unselectObjects();
    };

    // Handles when the user moves the mouse over a polygon on the drawing
    // canvas.
    this.CanvasMouseMove = function (event,pp) {
        var x = GetEventPosX(event);
        var y = GetEventPosY(event);
        if(IsNearPolygon(x,y,pp)) selectObject(pp);
        else unselectObjects();
    };

    // Submits the object label in response to the "What is this object?"
    // popup bubble. THIS FUNCTION IS A MESS!!!!
    this.SubmitQuery = function () {
      var nn;
      var anno;

      // If the attributes are active, read the fields.
      if (use_attributes) {
	// get attributes (is the field exists)
	if(document.getElementById('attributes')) new_attributes = RemoveSpecialChars(document.getElementById('attributes').value);
	else new_attributes = "";

	// get occlusion field (is the field exists)
	if (document.getElementById('occluded')) new_occluded = RemoveSpecialChars(document.getElementById('occluded').value);
	else new_occluded = "";
      }

      if((object_choices!='...') && (object_choices.length==1)) {
	nn = RemoveSpecialChars(object_choices[0]);
	active_canvas = REST_CANVAS;

	// Move draw canvas to the back:
	document.getElementById('draw_canvas').style.zIndex = -2;
	document.getElementById('draw_canvas_div').style.zIndex = -2;

	// Remove polygon from the draw canvas:
	var anno = null;
	if(draw_anno) {
	  draw_anno.DeletePolygon();
	  anno = draw_anno;
	  draw_anno = null;
	}
      }
      else {
	nn = RemoveSpecialChars(document.getElementById('objEnter').value);
	anno = this.QueryToRest();
      }

      var re = /[a-zA-Z0-9]/;
      if(!re.test(nn)) {
	alert('Please enter an object name');
	return;
      }

      // Update old and new object names for logfile:
      new_name = nn;
      old_name = nn;

      submission_edited = 0;
      global_count++;

      // Insert data for server logfile:
      InsertServerLogData('cpts_not_modified');

      // Insert data into XML:
      var html_str = '<object>';
      html_str += '<name>' + new_name + '</name>';
      html_str += '<deleted>0</deleted>';
      html_str += '<verified>0</verified>';
      if(use_attributes) {
	html_str += '<occluded>' + new_occluded + '</occluded>';
	html_str += '<attributes>' + new_attributes + '</attributes>';
      }
      html_str += '<parts><hasparts></hasparts><ispartof></ispartof></parts>';
      var ts = GetTimeStamp();
      if(ts.length==20) html_str += '<date>' + ts + '</date>';
      html_str += '<id>' + anno.anno_id + '</id>';

      if(anno.GetType() == 1) {
	/*************************************************************/
	/*************************************************************/
	// Scribble: Add annotation to LM_xml:
	html_str += '<segm>';
	html_str += '<username>' + username + '</username>';

	html_str += '<box>';
	html_str += '<xmin>' + anno.GetPtsX()[0] + '</xmin>';
	html_str += '<ymin>' + anno.GetPtsY()[0] + '</ymin>';
	html_str += '<xmax>' + anno.GetPtsX()[1] + '</xmax>';
	html_str += '<ymax>' + anno.GetPtsY()[2] + '</ymax>';
	html_str += '</box>';

	html_str += '<mask>'+ anno.GetImName()+'</mask>';

	html_str += '<scribbles>';
	html_str += '<xmin>' + anno.GetCornerLX() + '</xmin>';
	html_str += '<ymin>' + anno.GetCornerLY() + '</ymin>';
	html_str += '<xmax>' + anno.GetCornerRX() + '</xmax>';
	html_str += '<ymax>' + anno.GetCornerRY() + '</ymax>';
	html_str += '<scribble_name>'+ anno.GetScribbleName()+'</scribble_name>';
	html_str += '</scribbles>';

	html_str += '</segm>';
	html_str += '</object>';
	$(LM_xml).children("annotation").append($(html_str));
	/*************************************************************/
	/*************************************************************/
      }
      else {
	html_str += '<polygon>';
	html_str += '<username>' + username + '</username>';
	for(var jj=0; jj < anno.GetPtsX().length; jj++) {
	  html_str += '<pt>';
	  html_str += '<x>' + anno.GetPtsX()[jj] + '</x>';
	  html_str += '<y>' + anno.GetPtsY()[jj] + '</y>';
	  html_str += '</pt>';
	}
	html_str += '</polygon>';
	html_str += '</object>';
	$(LM_xml).children("annotation").append($(html_str));
      }

      AllAnnotations.push(anno);

      if(!anno.GetDeleted()||view_Deleted) {
	main_canvas.AttachAnnotation(anno);
	anno.RenderAnnotation('rest');
      }

      /*************************************************************/
      /*************************************************************/
      // Scribble: Clean scribbles.
      if(anno.GetType() == 1) {
	scribble_canvas.cleanscribbles();
	scribble_canvas.scribble_image = "";
	scribble_canvas.colorseg = Math.floor(Math.random()*14);
      }
      /*************************************************************/
      /*************************************************************/

      // Write XML to server:
      WriteXML(SubmitXmlUrl,LM_xml,function(){return;});

      if(view_ObjList) RenderObjectList();

      var m = main_image.GetFileInfo().GetMode();
      if(m=='mt') {
	document.getElementById('object_name').value=new_name;
	document.getElementById('number_objects').value=global_count;
	document.getElementById('LMurl').value = LMbaseurl + '?collection=LabelMe&mode=i&folder=' + main_image.GetFileInfo().GetDirName() + '&image=' + main_image.GetFileInfo().GetImName();
	if(global_count >= mt_N) document.getElementById('mt_submit').disabled=false;
      }
    };

    // Handles when we wish to change from "query" to "rest".
    this.QueryToRest = function () {
        active_canvas = REST_CANVAS;

	// Move query canvas to the back:
	document.getElementById('query_canvas').style.zIndex = -2;
	document.getElementById('query_canvas_div').style.zIndex = -2;

	// Remove polygon from the query canvas:
	if(query_anno) query_anno.DeletePolygon();
	var anno = query_anno;
	query_anno = null;

	CloseQueryPopup();
	main_image.ScrollbarsOn();

        return anno;
    };

    // Handles when the user presses a key while interacting with the tool.
    this.KeyPress = function (event) {
        // Delete event: 46 - delete key; 8 - backspace key
        if(((event.keyCode==46) || (event.keyCode==8)) && !wait_for_input && !edit_popup_open && !username_flag) {
            // Determine whether we are deleting a complete or partially
            // complete polygon.
            if(!main_handler.EraseSegment()) DeleteSelectedPolygon();
        }
        // 27 - Esc key
        // Close edit popup if it is open.
        if(event.keyCode==27 && edit_popup_open) StopEditEvent();
    };

    // Handles when the user erases a segment.
    this.EraseSegment = function () {
        if(draw_anno && !draw_anno.DeleteLastControlPoint()) {
            submission_edited = 0;
            StopDrawEvent();
        }
        return draw_anno;
    };

    // *******************************************
    // Private methods:
    // *******************************************

}
<|endoftext|>


<commit_before>var app = angular.module('demo', ['pxConfig', 'px-data-grid']);

app.config(function(pxConfig) {

    // Definir language da lib numeral.js
    // http://numeraljs.com/
    numeral.language('pt-br');
    // Definir locale da lib moment.js
    // http://momentjs.com/docs/
    moment.locale('pt-BR');
});

app.controller('DataGridCtrl', ['$scope', '$locale', function($scope, $locale) {
    /**
     * Controle da listagem
     * Note que a propriedade 'control' da directive px-data-grid é igual a 'dgExemplo'
     * Exemplo: <px-data-grid px-control='dgExemplo'>
     * @type {Object}
     */
    $scope.dgExemploControl = {};

    /**
     * Inicializa listagem
     * @return {Void}
     */
    $scope.dgExemploInit = function() {
        /**
         * Configurações da listagem
         * - fields: Colunas da listagem
         * @type {Object}
         */
        $scope.dgExemploConfig = {
            url: 'data.json',
            fields: [{
                link: true,
                linkId: 'sampleIcon',
                title: '',
                class: 'material-icons',
                icon: 'done',
                value: ''
            }, {
                title: 'Nº',
                field: 'id',
                type: 'int'
            }, {
                title: 'Nome',
                field: 'nome',
                type: 'varchar'
            }, {
                title: 'CPF',
                field: 'cpf',
                type: 'varchar',
                stringMask: '###.###.###-##'
            }, {
                title: 'Data',
                field: 'data',
                type: 'date',
                moment: 'dddd - DD/MM/YYYY'
            }, {
                link: true,
                class: 'fa fa-battery-empty',
                icon: '',
                title: 'Label Function',
                field: 'bateria',
                type: 'numeric',
                label: 'bateria',
                align: 'center'
            }, {
                title: 'Status',
                field: 'status',
                type: 'numeric',
                label: 'status',
                align: 'center'
            }]
        };

        $scope.dgExemploLabel = function(event) {
            if (event.item.label === 'bateria') {
                event.item.class = 'fa fa-battery-' + event.data.bateria;
            } else if (event.item.label === 'status') {
                if (event.data.status === 1) {
                    event.data.status = 'ATIVO';
                } else {
                    event.data.status = 'PENDENTE';
                }
            }

            return event;
        };

        $scope.getData = function() {
            $scope.dgExemploControl.getData();
        };

        $scope.countRow = 1;
        $scope.addDataRow = function() {

            $scope.dgExemploControl.addDataRow({
                'id': $scope.countRow++,
                'nome': 'Nome ' + Math.floor((Math.random() * 100000) + 1),
                'cpf': Math.floor((Math.random() * 10000000000) + 1000000000),
                'data': new Date(),
                'bateria': Math.floor((Math.random() * 4) + 1),
                'status': Math.floor((Math.random() * 2))
            })

        };

        $scope.removeRow = function() {
            $scope.dgExemploControl.removeRow('.selected');
        };

        $scope.itemClick = function(event) {
            if (event.itemClick.linkId === 'sampleIcon') {
                alert('Você clicou no ícone');
            }
        };
    }
}]);<commit_msg>feat(demo): atualizar demo<commit_after>var app = angular.module('demo', ['pxConfig', 'px-data-grid']);

app.config(function(pxConfig) {

    // Definir language da lib numeral.js
    // http://numeraljs.com/
    numeral.language('pt-br');
    // Definir locale da lib moment.js
    // http://momentjs.com/docs/
    moment.locale('pt-BR');
});

app.controller('DataGridCtrl', ['$scope', '$locale', function($scope, $locale) {
    /**
     * Controle da listagem
     * Note que a propriedade 'control' da directive px-data-grid é igual a 'dgExemplo'
     * Exemplo: <px-data-grid px-control='dgExemplo'>
     * @type {Object}
     */
    $scope.dgExemploControl = {};

    /**
     * Configurações da listagem
     * - fields: Colunas da listagem
     * @type {Object}
     */
    $scope.dgExemploConfig = {
        url: 'data.json',
        fields: [{
            link: true,
            linkId: 'sampleIcon',
            title: '',
            class: 'material-icons',
            icon: 'done',
            value: '',
            align: 'center'
        }, {
            title: 'Nº',
            field: 'id',
            type: 'int'
        }, {
            title: 'Nome',
            field: 'nome',
            type: 'varchar'
        }, {
            title: 'CPF',
            field: 'cpf',
            type: 'varchar',
            stringMask: '###.###.###-##'
        }, {
            title: 'Data',
            field: 'data',
            type: 'date',
            moment: 'dddd - DD/MM/YYYY'
        }, {
            class: 'fa fa-battery-empty',
            icon: '',
            title: 'Label Function',
            field: 'bateria',
            type: 'numeric',
            label: 'bateria',
            align: 'center'
        }, {
            title: 'Status',
            field: 'status',
            type: 'numeric',
            label: 'status',
            align: 'center'
        }]
    };

    $scope.dgExemploLabel = function(event) {
        if (event.item.label === 'bateria') {
            event.item.class = 'fa fa-battery-' + event.data.bateria;
        } else if (event.item.label === 'status') {
            if (event.data.status === 1) {
                event.data.status = 'ATIVO';
            } else {
                event.data.status = 'PENDENTE';
            }
        }

        return event;
    };

    $scope.getData = function() {
        $scope.dgExemploControl.getData();
    };

    $scope.countRow = 105;
    $scope.addDataRow = function() {
        $scope.dgExemploControl.addDataRow({
            'id': $scope.countRow++,
            'nome': 'Nome ' + Math.floor((Math.random() * 100000) + 1),
            'cpf': Math.floor((Math.random() * 10000000000) + 1000000000),
            'data': new Date(),
            'bateria': Math.floor((Math.random() * 4) + 1),
            'status': Math.floor((Math.random() * 2))
        })
    };

    $scope.removeRow = function() {
        $scope.dgExemploControl.removeRow('.selected');
    };

    $scope.itemClick = function(event) {
        if (event.itemClick.linkId === 'sampleIcon') {
            console.info('itemClick', event);
            alert('Você clicou no ícone');
        }
    };

    /**
     * Evento inicializar
     * @return {Void}
     */
    $scope.dgExemploInit = function() {
        $scope.dgExemploControl.getData();
    }
}]);<|endoftext|>


<commit_before>var N = 1000;

function bench() {
console.log('finished');

function test1() {
  var startTime = Date.now();
  var node = foam.u2.Element.create({nodeName: 'UL'});     // Create a
 node
  for ( var i = 0 ; i < N ; i++ )
    node.start('li').add("1text" + i).end();                // Append an

  node.write(document);
  console.log('U2 (pre)', Date.now() - startTime);
}

function test2() {
  var startTime = Date.now();
  var node = foam.u2.Element.create({nodeName: 'UL'});     // Create a
 node
  node.write(document);
  for ( var i = 0 ; i < N ; i++ )
    node.start('li').add("2text" + i).end();                // Append an

  console.log('U2 (post)', Date.now() - startTime);
}

function test3() {
  var startTime = Date.now();
  var node = document.createElement("UL");               // Create a
 node
  for ( var i = 0 ; i < N ; i++ ) {
    var li = document.createElement("LI")
    li.appendChild(document.createTextNode("3text" + i)); // Append an

    node.appendChild(li);
  }
  document.body.appendChild(node);
  console.log('DOM (pre)', Date.now() - startTime);
}

function test4() {
  var startTime = Date.now();
  var node = document.createElement("UL");               // Create a
 node
  document.body.appendChild(node);
  for ( var i = 0 ; i < N ; i++ ) {
    var li = document.createElement("LI")
    li.appendChild(document.createTextNode("4text" + i)); // Append an

    node.appendChild(li);
  }
  console.log('DOM (post)', Date.now() - startTime);
}

function test5() {
  var startTime = Date.now();
  var node = '
';
  for ( var i = 0 ; i < N ; i++ ) {
    node = node + '
5text' + i + '
'
  }
  node = node + '
';
  document.body.outerHTML = node;
  console.log('outerHTML', Date.now() - startTime);
}

function test6() {
  var v = foam.u2.DefaultValidator.create();

  var startTime = Date.now();
  for ( var i = 0 ; i < N ; i++ ) {
    v.sanitizeText('6text' + i);
  }
  console.log('sanitize', Date.now() - startTime);
}

function allTests() {
  test1();
  //test2();
  test3();
  //test4();
  // test5();
  // test6();
  console.log('\n');
}

allTests();
allTests();
allTests();

console.profile('p1');
test1();
console.profileEnd();
}
<commit_msg>Prevent from running in node.js.<commit_after>
// Prevent from running in node.js
if ( globalThis.window ) {

var N = 1000;

console.log('started');

function test1() {
  var startTime = performance.now();
  var node = foam.u2.Element.create({nodeName: 'UL'});     // Create a
 node
  for ( var i = 0 ; i < N ; i++ )
    node.start('li').setID(null).add("1text" + i).end();                // Append an

  node.write(document);
  console.log('U2 (pre)', performance.now() - startTime);
}

function test2() {
  var startTime = performance.now();
  var node = foam.u2.Element.create({nodeName: 'UL'});     // Create a
 node
  node.write(document);
  for ( var i = 0 ; i < N ; i++ )
    node.start('li').add("2text" + i).end();                // Append an

  console.log('U2 (post)', performance.now() - startTime);
}

function test3() {
  var startTime = performance.now();
  var node = document.createElement("UL");               // Create a
 node
  for ( var i = 0 ; i < N ; i++ ) {
    var li = document.createElement("LI")
    li.appendChild(document.createTextNode("3text" + i)); // Append an

    node.appendChild(li);
  }
  document.body.appendChild(node);
  console.log('DOM (pre)', performance.now() - startTime);
}

function test4() {
  var startTime = performance.now();
  var node = document.createElement("UL");               // Create a
 node
  document.body.appendChild(node);
  for ( var i = 0 ; i < N ; i++ ) {
    var li = document.createElement("LI")
    li.appendChild(document.createTextNode("4text" + i)); // Append an

    node.appendChild(li);
  }
  console.log('DOM (post)', performance.now() - startTime);
}

function test5() {
  var startTime = performance.now();
  var node = '
';
  for ( var i = 0 ; i < N ; i++ ) {
    node = node + '
5text' + i + '
'
  }
  node = node + '
';
  document.body.outerHTML = node;
  console.log('outerHTML', performance.now() - startTime);
}

function test6() {
  var v = foam.u2.DefaultValidator.create();

  var startTime = performance.now();
  for ( var i = 0 ; i < N ; i++ ) {
    v.sanitizeText('6text' + i);
  }
  console.log('sanitize', performance.now() - startTime);
}

function allTests() {
  test1();
  //test2();
  test3();
  //test4();
  // test5();
  // test6();
  console.log('\n');
}

allTests();
allTests();
allTests();

console.profile('p1');
test1();
console.profileEnd();

}
<|endoftext|>


<commit_before>import { urlencoded, json } from 'body-parser'
import cookieParser from 'cookie-parser'
// import cors from 'cors'
import express from 'express'
import mongoose from 'mongoose'
import { Nuxt, Builder } from 'nuxt'

import config from '../../nuxt.config'
import apiRoutes from './api'

const app = express()

// Global middleware
// only allow http://127.0.0.1:3000 and http://localhost:3000
// only allow process.env.API_URL, process.env.SERVER_API_URL, and process.env.PAGE_URL
// app.use(cors({
//   origin: process.env.NOW_URL // fix this.
// }))
app.use(urlencoded({ extended: false }))
app.use(json())
app.use(cookieParser())

// Import API Routes
app.use('/api', apiRoutes)

config.dev = !(process.env.NODE_ENV === 'production')

// Init Nuxt.js
const nuxt = new Nuxt(config)

// Build only in dev mode
if (config.dev) {
  const builder = new Builder(nuxt)
  builder.build()
}

// Give nuxt middleware to express
app.use(nuxt.render)

// setup the database connection
mongoose.Promise = global.Promise
mongoose.connect(process.env.DB_URL)

app.listen(process.env.PORT, process.env.HOST, err => {
  if (err) { console.log(err) }
  console.log(`Server listening on http://${process.env.HOST}:${process.env.PORT}`)
})

export default app
<commit_msg>Fix for new mongodb version warning<commit_after>import { urlencoded, json } from 'body-parser'
import cookieParser from 'cookie-parser'
// import cors from 'cors'
import express from 'express'
import mongoose from 'mongoose'
import { Nuxt, Builder } from 'nuxt'

import config from '../../nuxt.config'
import apiRoutes from './api'

const app = express()

// Global middleware
// only allow http://127.0.0.1:3000 and http://localhost:3000
// only allow process.env.API_URL, process.env.SERVER_API_URL, and process.env.PAGE_URL
// app.use(cors({
//   origin: process.env.NOW_URL // fix this.
// }))
app.use(urlencoded({ extended: false }))
app.use(json())
app.use(cookieParser())

// Import API Routes
app.use('/api', apiRoutes)

config.dev = !(process.env.NODE_ENV === 'production')

// Init Nuxt.js
const nuxt = new Nuxt(config)

// Build only in dev mode
if (config.dev) {
  const builder = new Builder(nuxt)
  builder.build()
}

// Give nuxt middleware to express
app.use(nuxt.render)

// setup the database connection
mongoose.Promise = global.Promise
mongoose.connect(process.env.DB_URL, { useMongoClient: true })

app.listen(process.env.PORT, process.env.HOST, err => {
  if (err) { console.log(err) }
  console.log(`Server listening on http://${process.env.HOST}:${process.env.PORT}`)
})

export default app
<|endoftext|>


<commit_before>'use strict';

angular.module('users').controller('AuthenticationController', ['$scope', '$state', '$http', '$location', '$window', '$timeout', 'Authentication',
  function ($scope, $state, $http, $location, $window, $timeout, Authentication) {
    $scope.authentication = Authentication;

    // Get an eventual error defined in the URL query string:
    $scope.error = $location.search().err;

    //// If user is signed in then redirect back home
    //if ($scope.authentication.user) {
    //  $location.path('/');
    //}

    $scope.signup = function (isValid) {
      $scope.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'userForm');

        return false;
      }

      $http.post('/api/auth/signup', $scope.credentials).success(function (response) {
        // If successful we assign the response to the global user model

        $scope.authentication.user = response;

        // And redirect to the previous or home page

        // $state.go('home');
        $location.path('/');
        $scope.$apply();
        // $scope.changeLocation('/settings/picture');

      }).error(function (response) {
        $scope.error = response.message;
      });
    };

    //be sure to inject $scope and $location
    $scope.changeLocation = function (url, forceReload) {
      $scope = $scope || angular.element(document).scope();
      if (forceReload || $scope.$$phase) {
        window.location = url;
      }
      else {
        //only use this if you want to replace the history stack
        //$location.path(url).replace();

        //this this if you want to change the URL and add it to the history stack
        $location.path(url);
        $scope.$apply();
      }
    };

    $scope.signin = function (isValid) {
      $scope.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'userForm');

        return false;
      }

      $http.post('/api/auth/signin', $scope.credentials).success(function (response) {
        // If successful we assign the response to the global user model
        $scope.authentication.user = response;

        $scope.authentication.user.imageURL  = '/modules/users/client/img/profile/saveme-placeholder.png';

        // And redirect to the previous or home page
        $state.go($state.previous.state.name || 'home', $state.previous.params);
      }).error(function (response) {
        $scope.error = response.message;
      });

    };

    // OAuth provider request
    $scope.callOauthProvider = function (url) {
      if ($state.previous && $state.previous.href) {
        url += '?redirect_to=' + encodeURIComponent($state.previous.href);
      }

      // Effectively call OAuth authentication route:
      $window.location.href = url;
    };
  }
]);
<commit_msg>Registration fixed.<commit_after>'use strict';

angular.module('users').controller('AuthenticationController', ['$scope', '$state', '$http', '$location', '$window', '$timeout', 'Authentication',
  function ($scope, $state, $http, $location, $window, $timeout, Authentication) {
    $scope.authentication = Authentication;

    // Get an eventual error defined in the URL query string:
    $scope.error = $location.search().err;

    //// If user is signed in then redirect back home
    //if ($scope.authentication.user) {
    //  $location.path('/');
    //}

    $scope.signup = function (isValid) {
      $scope.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'userForm');

        return false;
      }

      $http.post('/api/auth/signup', $scope.credentials).success(function (response) {
        // If successful we assign the response to the global user model

        $scope.authentication.user = response;

        // And redirect to the previous or home page

        document.location.href = "/";

      }).error(function (response) {
        $scope.error = response.message;
      });
    };

    //be sure to inject $scope and $location
    $scope.changeLocation = function (url, forceReload) {
      $scope = $scope || angular.element(document).scope();
      if (forceReload || $scope.$$phase) {
        window.location = url;
      }
      else {
        //only use this if you want to replace the history stack
        //$location.path(url).replace();

        //this this if you want to change the URL and add it to the history stack
        $location.path(url);
        $scope.$apply();
      }
    };

    $scope.signin = function (isValid) {
      $scope.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'userForm');

        return false;
      }

      $http.post('/api/auth/signin', $scope.credentials).success(function (response) {
        // If successful we assign the response to the global user model
        $scope.authentication.user = response;

        $scope.authentication.user.imageURL  = '/modules/users/client/img/profile/saveme-placeholder.png';

        // And redirect to the previous or home page
        $state.go($state.previous.state.name || 'home', $state.previous.params);
      }).error(function (response) {
        $scope.error = response.message;
      });

    };

    // OAuth provider request
    $scope.callOauthProvider = function (url) {
      if ($state.previous && $state.previous.href) {
        url += '?redirect_to=' + encodeURIComponent($state.previous.href);
      }

      // Effectively call OAuth authentication route:
      $window.location.href = url;
    };
  }
]);
<|endoftext|>