<commit_before>/// <reference path="Scripts/jquery-2.0.3.js" />
/// <reference path="Scripts/jQuery.tmpl.js" />
/// <reference path="Scripts/jquery.cookie.js" />
/// <reference path="Scripts/moment.min.js" />
/// <reference path="Scripts/marked.js" />

/*jshint evil:true, bitwise:false*/
(function ($, window, emoji, marked, hljs, linkify, moment, languageResources) {
    "use strict";

    var markdownOptions = {
        highlight: function(code) {
            return hljs.highlightAuto(code).value;
        },
        tables: false,
        breaks: true,
        sanitize: true
    };

    function processMarkdown(src) {
        function noop() { }
        noop.exec = noop;

        // process inline markdown elements using custom lexer rules
        var inlineLexer = new marked.InlineLexer([], markdownOptions);

        inlineLexer.rules.link = noop;

        return inlineLexer.output(src);
    }

    // getting the browser's name for use in isMobile
    var nav = navigator.userAgent || navigator.vendor || window.opera;

    // checking to see if the current device is a mobile device
    // and storing the result for repeated use
    var isMobile = /android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(nav) ||
                   /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(nav.substr(0, 4));

    function padZero(s) {
        s = s.toString();
        if (s.length === 1) {
            return "0" + s;
        }
        return s;
    }

    function guidGenerator() {
        var S4 = function () {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        };
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }

    $.fn.isNearTheEnd = function () {
        if (typeof this[0] === 'undefined') {
            return false;
        }
        // Because of some weird bug in Chrome, sometimes the scroll stops at
        // bottom-1. I'm just going to approximate here to hopefully handle most
        // cases where it gets buggy. I don't think anyone will complain about
        // 10 pixels.
        return this[0].scrollTop + this.height() >= this[0].scrollHeight - 10;
    };

    $.fn.expandableContent = function () {
        // These are selectors to various rich content that may increase the
        // scrollable area after they were initially appended
        var selectors = ['img:not(.gravatar)'];

        return this.find(selectors.join(','));
    };

    // REVIEW: is it safe to assume we do not need to strip tags before decoding?
    function decodeHtml(html) {
        // should we strip tags before running this?
        // obligatory link to SO http://stackoverflow.com/questions/1147359/how-to-decode-html-entities-using-jquery
        // is it safe to assume bad html has been removed before we've reached this function call?
        return $("
").html(html).text();
    }

    function encodeHtml(html) {
        // html still emits double quotes so we need to replace these entities to use them in attributes.
        return $("
").text(html).html().replace(/\"/g, """);
    }

    function format(formatString) {
        var formatArgs = arguments;
        return formatString.replace(/{(?:[0-9]+)}/g, function (match) {
            return formatArgs[parseInt(match.substr(1, match.length - 2), 10) + 1];
        });
    }

    function getLanguageResource(languageResourceKey) {
        var args = Array.prototype.slice.call(arguments, 0);
        args[0] = languageResources[languageResourceKey];
        return format.apply(null, args);
    }

    String.prototype.fromJsonDate = function () {
        return new Date(moment(this.toString()).valueOf());
    };

    Date.prototype.formatDate = function () {
        var m = this.getMonth() + 1,
            d = this.getDate(),
            y = this.getFullYear();

        return m + "/" + d + "/" + y;
    };

    Date.prototype.formatTime = function (showAp) {
        var ap,
            hr = this.getHours();

        if (hr < 12) {
            ap = "AM";
        }
        else {
            ap = "PM";
        }

        if (hr === 0) {
            hr = 12;
        }

        if (hr > 12) {
            hr = hr - 12;
        }

        var mins = padZero(this.getMinutes());
        var seconds = padZero(this.getSeconds());
        return hr + ":" + mins + ":" + seconds + (showAp ? " " + ap : "");
    };

    // returns the date portion only (strips time)
    Date.prototype.toDate = function () {
        return new Date(this.getFullYear(), this.getMonth(), this.getDate());
    };

    // returns difference (this - d) in days
    Date.prototype.diffDays = function (d) {
        var t1 = this.getTime(),
            t2 = d.getTime();

        return parseInt((t1 - t2) / (24 * 3600 * 1000), 10);
    };

    // adds a certain number of days to a Date object
    Date.prototype.addDays = function (days) {
        return new Date(this.getTime() + 1000 * 3600 * 24 * days);
    };

    function processContent(content, templates, roomCache) {
        content = content || '';

        var hasNewline = content.indexOf('\n') !== -1;

        if (hasNewline) {
            // Multiline detection
            return $('
').append(templates.multiline.tmpl({ content: content })).html();
        } else {
            // Emoji
            content = utility.parseEmojis(content);

            // Convert markdown
            content = processMarkdown(content);

            // Transform emoji to html
            content = utility.transformEmojis(content);

            // Create rooms links, only if we actually have a room cache
            if (roomCache) {
                content = content.replace(/#([A-Za-z0-9-_]{1,30}\w*)/g, function (m) {
                    var roomName = m.substr(1);

                    if (roomCache[roomName.toUpperCase()]) {
                        return '' + m + '';
                    }
                    return m;
                });
            }

            // Convert normal links
            content = linkify(content, {
                callback: function (text, href) {
                    return href ? '' + text + '' : text;
                }
            });

            return content;
        }
    }

    var utility = {
        trim: function (value, length) {
            if (value.length > length) {
                return value.substr(0, length - 3) + '...';
            }
            return value;
        },
        randomUniqueId: function (prefix) {
            var n = Math.floor(Math.random() * 100);
            while ($("#" + prefix + n.toString()).length > 0) {
                n = Math.Floor(Math.random() * 100);
            }
            return prefix + n;
        },
        markdownToHtml: function (content) {
            var transformer = marked.parse;
            return (transformer(content, markdownOptions));
        },
        isMobile: isMobile,
        parseEmojis: function (content) {
            var parser = new emoji.Parser().parse;
            return (parser(content));
        },
        transformEmojis: function (content) {
            var transformToHtml = new emoji.Parser().transformToHtml;
            return (transformToHtml(content));
        },
        decodeHtml: decodeHtml,
        encodeHtml: encodeHtml,
        newId: guidGenerator,
        processContent: processContent,
        format: format,
        getLanguageResource: getLanguageResource
    };

    if (!window.chat) {
        window.chat = {};
    }

    window.chat.utility = utility;

})(window.jQuery, window, window.Emoji, window.marked, window.hljs, window.linkify, window.moment, window.languageResources);
<commit_msg>Forgot to enable GFM<commit_after>/// <reference path="Scripts/jquery-2.0.3.js" />
/// <reference path="Scripts/jQuery.tmpl.js" />
/// <reference path="Scripts/jquery.cookie.js" />
/// <reference path="Scripts/moment.min.js" />
/// <reference path="Scripts/marked.js" />

/*jshint evil:true, bitwise:false*/
(function ($, window, emoji, marked, hljs, linkify, moment, languageResources) {
    "use strict";

    var markdownOptions = {
        highlight: function(code) {
            return hljs.highlightAuto(code).value;
        },
        tables: false,
        breaks: true,
        sanitize: true,
        gfm: true
    };

    function processMarkdown(src) {
        function noop() { }
        noop.exec = noop;

        // process inline markdown elements using custom lexer rules
        var inlineLexer = new marked.InlineLexer([], markdownOptions);

        inlineLexer.rules.link = noop;

        return inlineLexer.output(src);
    }

    // getting the browser's name for use in isMobile
    var nav = navigator.userAgent || navigator.vendor || window.opera;

    // checking to see if the current device is a mobile device
    // and storing the result for repeated use
    var isMobile = /android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(nav) ||
                   /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(nav.substr(0, 4));

    function padZero(s) {
        s = s.toString();
        if (s.length === 1) {
            return "0" + s;
        }
        return s;
    }

    function guidGenerator() {
        var S4 = function () {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        };
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }

    $.fn.isNearTheEnd = function () {
        if (typeof this[0] === 'undefined') {
            return false;
        }
        // Because of some weird bug in Chrome, sometimes the scroll stops at
        // bottom-1. I'm just going to approximate here to hopefully handle most
        // cases where it gets buggy. I don't think anyone will complain about
        // 10 pixels.
        return this[0].scrollTop + this.height() >= this[0].scrollHeight - 10;
    };

    $.fn.expandableContent = function () {
        // These are selectors to various rich content that may increase the
        // scrollable area after they were initially appended
        var selectors = ['img:not(.gravatar)'];

        return this.find(selectors.join(','));
    };

    // REVIEW: is it safe to assume we do not need to strip tags before decoding?
    function decodeHtml(html) {
        // should we strip tags before running this?
        // obligatory link to SO http://stackoverflow.com/questions/1147359/how-to-decode-html-entities-using-jquery
        // is it safe to assume bad html has been removed before we've reached this function call?
        return $("
").html(html).text();
    }

    function encodeHtml(html) {
        // html still emits double quotes so we need to replace these entities to use them in attributes.
        return $("
").text(html).html().replace(/\"/g, """);
    }

    function format(formatString) {
        var formatArgs = arguments;
        return formatString.replace(/{(?:[0-9]+)}/g, function (match) {
            return formatArgs[parseInt(match.substr(1, match.length - 2), 10) + 1];
        });
    }

    function getLanguageResource(languageResourceKey) {
        var args = Array.prototype.slice.call(arguments, 0);
        args[0] = languageResources[languageResourceKey];
        return format.apply(null, args);
    }

    String.prototype.fromJsonDate = function () {
        return new Date(moment(this.toString()).valueOf());
    };

    Date.prototype.formatDate = function () {
        var m = this.getMonth() + 1,
            d = this.getDate(),
            y = this.getFullYear();

        return m + "/" + d + "/" + y;
    };

    Date.prototype.formatTime = function (showAp) {
        var ap,
            hr = this.getHours();

        if (hr < 12) {
            ap = "AM";
        }
        else {
            ap = "PM";
        }

        if (hr === 0) {
            hr = 12;
        }

        if (hr > 12) {
            hr = hr - 12;
        }

        var mins = padZero(this.getMinutes());
        var seconds = padZero(this.getSeconds());
        return hr + ":" + mins + ":" + seconds + (showAp ? " " + ap : "");
    };

    // returns the date portion only (strips time)
    Date.prototype.toDate = function () {
        return new Date(this.getFullYear(), this.getMonth(), this.getDate());
    };

    // returns difference (this - d) in days
    Date.prototype.diffDays = function (d) {
        var t1 = this.getTime(),
            t2 = d.getTime();

        return parseInt((t1 - t2) / (24 * 3600 * 1000), 10);
    };

    // adds a certain number of days to a Date object
    Date.prototype.addDays = function (days) {
        return new Date(this.getTime() + 1000 * 3600 * 24 * days);
    };

    function processContent(content, templates, roomCache) {
        content = content || '';

        var hasNewline = content.indexOf('\n') !== -1;

        if (hasNewline) {
            // Multiline detection
            return $('
').append(templates.multiline.tmpl({ content: content })).html();
        } else {
            // Emoji
            content = utility.parseEmojis(content);

            // Convert markdown
            content = processMarkdown(content);

            // Transform emoji to html
            content = utility.transformEmojis(content);

            // Create rooms links, only if we actually have a room cache
            if (roomCache) {
                content = content.replace(/#([A-Za-z0-9-_]{1,30}\w*)/g, function (m) {
                    var roomName = m.substr(1);

                    if (roomCache[roomName.toUpperCase()]) {
                        return '' + m + '';
                    }
                    return m;
                });
            }

            // Convert normal links
            content = linkify(content, {
                callback: function (text, href) {
                    return href ? '' + text + '' : text;
                }
            });

            return content;
        }
    }

    var utility = {
        trim: function (value, length) {
            if (value.length > length) {
                return value.substr(0, length - 3) + '...';
            }
            return value;
        },
        randomUniqueId: function (prefix) {
            var n = Math.floor(Math.random() * 100);
            while ($("#" + prefix + n.toString()).length > 0) {
                n = Math.Floor(Math.random() * 100);
            }
            return prefix + n;
        },
        markdownToHtml: function (content) {
            var transformer = marked.parse;
            return (transformer(content, markdownOptions));
        },
        isMobile: isMobile,
        parseEmojis: function (content) {
            var parser = new emoji.Parser().parse;
            return (parser(content));
        },
        transformEmojis: function (content) {
            var transformToHtml = new emoji.Parser().transformToHtml;
            return (transformToHtml(content));
        },
        decodeHtml: decodeHtml,
        encodeHtml: encodeHtml,
        newId: guidGenerator,
        processContent: processContent,
        format: format,
        getLanguageResource: getLanguageResource
    };

    if (!window.chat) {
        window.chat = {};
    }

    window.chat.utility = utility;

})(window.jQuery, window, window.Emoji, window.marked, window.hljs, window.linkify, window.moment, window.languageResources);
<|endoftext|>


<commit_before>module.exports = function (context, input) {

    const RxHttpRequest = require("@akanass/rx-http-request").RxHR;

    const url = process.env['POST_URL'];

    const options = {
        auth: {
            user: process.env['POST_USERNAME'],
            pass: process.env['POST_PASSWORD']
        },
        headers: {
            'User-Agent': process.env['POST_USER_AGENT']
        },
        qs: {
            code: process.env['POST_CODE']
        },
        body: {
            some: 'payload'
        },
        timeout: 2000,
        json: true // Automatically stringifies the body to JSON
    };

    context.log('JavaScript manually triggered function called with input:', input);

    RxHttpRequest.post(url, options).subscribe(
        result => context.log('onNext: %s', result.body),
        error => context.log('onError: %s', error),
        () => context.done()
    );

    context.log('Synchronous part done');

};<commit_msg> print code and body<commit_after>module.exports = function (context, input) {

    const RxHttpRequest = require("@akanass/rx-http-request").RxHR;

    const url = process.env['POST_URL'];

    const options = {
        auth: {
            user: process.env['POST_USERNAME'],
            pass: process.env['POST_PASSWORD']
        },
        headers: {
            'User-Agent': process.env['POST_USER_AGENT']
        },
        qs: {
            code: process.env['POST_CODE']
        },
        body: {
            some: 'payload'
        },
        timeout: 2000,
        json: true // Automatically stringifies the body to JSON
    };

    context.log('JavaScript manually triggered function called with input:', input);

    RxHttpRequest.post(url, options).subscribe(
        result => context.log('body: %s, code: %s', result.body, result.response.statusCode),
        error => context.log('onError: %s', error),
        () => context.done()
    );

    context.log('Synchronous part done');

};<|endoftext|>


<commit_before>Kwf.onContentReady(function(el, param) {
    if (!param.newRender) return false;
    Ext.select('.kwcForm', true, el).each(function(form) {
        if (!form.kwcForm) {
            form.kwcForm = new Kwc.Form.Component(form);
        }
    });
});
Ext.ns('Kwc.Form');
Kwc.Form.Component = function(form)
{
    this.addEvents('submitSuccess');
    this.el = form;
    var config = form.parent().down('.config', true);
    if (!config) return;
    config = Ext.decode(config.value);
    if (!config) return;
    this.config = config;

    this.fields = [];
    form.select('.kwfField', true).each(function(fieldEl) {
        var classes = fieldEl.dom.className.split(' ');
        var fieldConstructor = false;
        classes.each(function (c) {
            if (Kwf.FrontendForm.fields[c]) {
                fieldConstructor = Kwf.FrontendForm.fields[c];
            }
        }, this);
        if (fieldConstructor) {
            var field = new fieldConstructor(fieldEl);
            this.fields.push(field);
        }
    }, this);

    if (this.config.hideForValue) {
        this.config.hideForValue.each(function(hideForValue) {
            var field = this.findField(hideForValue.field);
            field.on('change', function(v, f) {
                if (v == hideForValue.value) {
                    this.findField(hideForValue.hide).hide();
                } else {
                    this.findField(hideForValue.hide).show();
                }
            }, this);

            //initialize on startup
            if (field.getValue() == hideForValue.value) {
                this.findField(hideForValue.hide).hide();
            }
        }, this);
    }

    var button = form.child('form button.submit');
    if (button) {
        button.on('click', this.onSubmit, this);
    }
};
Ext.extend(Kwc.Form.Component, Ext.util.Observable, {
    findField: function(fieldName) {
        var ret = null;
        this.fields.each(function(f) {
            if (f.getFieldName() == fieldName) {
                ret = f;
                return true;
            }
        }, this);
        return ret;
    },
    onSubmit: function(e) {
        if (this.dontUseAjaxRequest) return;

        var button = this.el.child('.button');
        button.down('.saving').show();
        button.down('.submit').hide();

        Ext.Ajax.request({
            url: this.config.controllerUrl + '/json-save',
            ignoreErrors: true,
            params: {
                componentId: this.config.componentId
            },
            form: this.el.down('form'),
            failure: function() {
                //on failure try a plain old post of the form
                this.dontUseAjaxRequest = true; //avoid endless recursion
                button.down('.submit').dom.click();
            },
            success: function(response, options, r) {

                var hasErrors = false;

                // remove and set error classes for fields
                this.fields.each(function(field) {
                    field.hideError();
                }, this);
                for(var fieldName in r.errorFields) {
                    var field = this.findField(fieldName);
                    field.showError(r.errorFields[fieldName]);
                    hasErrors= true;
                }

                // remove and add error messages
                var error = this.el.parent().down('.webFormError');
                if (error) error.remove();

                if (r.errorMessages && r.errorMessages.length) {
                    hasErrors= true;
                    var html = '
';
                    html += '
' + r.errorPlaceholder + ':
';
                    html += '
';
                    for (var i=0; i<r.errorMessages.length; i++) {
                        html += '
' + r.errorMessages[i] + '
';
                    }
                    html += '
';
                    html += '
';
                    this.el.parent().createChild(html, form);
                }

                // show success content
                if (r.successContent) {
                    this.el.parent().createChild(r.successContent);
                    this.el.remove();
                } else if (r.successUrl) {
                    document.location.href = r.successUrl;
                }

                if (!r.successUrl) {
                    button.down('.saving').hide();
                    button.down('.submit').show();
                }

                if (!hasErrors) {
                    this.fireEvent('submitSuccess', this, r);
                }
            },
            scope: this
        });

        e.stopEvent();
    }
});<commit_msg>call onContentReady for success content<commit_after>Kwf.onContentReady(function(el, param) {
    if (!param.newRender) return false;
    Ext.select('.kwcForm', true, el).each(function(form) {
        if (!form.kwcForm) {
            form.kwcForm = new Kwc.Form.Component(form);
        }
    });
});
Ext.ns('Kwc.Form');
Kwc.Form.Component = function(form)
{
    this.addEvents('submitSuccess');
    this.el = form;
    var config = form.parent().down('.config', true);
    if (!config) return;
    config = Ext.decode(config.value);
    if (!config) return;
    this.config = config;

    this.fields = [];
    form.select('.kwfField', true).each(function(fieldEl) {
        var classes = fieldEl.dom.className.split(' ');
        var fieldConstructor = false;
        classes.each(function (c) {
            if (Kwf.FrontendForm.fields[c]) {
                fieldConstructor = Kwf.FrontendForm.fields[c];
            }
        }, this);
        if (fieldConstructor) {
            var field = new fieldConstructor(fieldEl);
            this.fields.push(field);
        }
    }, this);

    if (this.config.hideForValue) {
        this.config.hideForValue.each(function(hideForValue) {
            var field = this.findField(hideForValue.field);
            field.on('change', function(v, f) {
                if (v == hideForValue.value) {
                    this.findField(hideForValue.hide).hide();
                } else {
                    this.findField(hideForValue.hide).show();
                }
            }, this);

            //initialize on startup
            if (field.getValue() == hideForValue.value) {
                this.findField(hideForValue.hide).hide();
            }
        }, this);
    }

    var button = form.child('form button.submit');
    if (button) {
        button.on('click', this.onSubmit, this);
    }
};
Ext.extend(Kwc.Form.Component, Ext.util.Observable, {
    findField: function(fieldName) {
        var ret = null;
        this.fields.each(function(f) {
            if (f.getFieldName() == fieldName) {
                ret = f;
                return true;
            }
        }, this);
        return ret;
    },
    onSubmit: function(e) {
        if (this.dontUseAjaxRequest) return;

        var button = this.el.child('.button');
        button.down('.saving').show();
        button.down('.submit').hide();

        Ext.Ajax.request({
            url: this.config.controllerUrl + '/json-save',
            ignoreErrors: true,
            params: {
                componentId: this.config.componentId
            },
            form: this.el.down('form'),
            failure: function() {
                //on failure try a plain old post of the form
                this.dontUseAjaxRequest = true; //avoid endless recursion
                button.down('.submit').dom.click();
            },
            success: function(response, options, r) {

                var hasErrors = false;

                // remove and set error classes for fields
                this.fields.each(function(field) {
                    field.hideError();
                }, this);
                for(var fieldName in r.errorFields) {
                    var field = this.findField(fieldName);
                    field.showError(r.errorFields[fieldName]);
                    hasErrors= true;
                }

                // remove and add error messages
                var error = this.el.parent().down('.webFormError');
                if (error) error.remove();

                if (r.errorMessages && r.errorMessages.length) {
                    hasErrors= true;
                    var html = '
';
                    html += '
' + r.errorPlaceholder + ':
';
                    html += '
';
                    for (var i=0; i<r.errorMessages.length; i++) {
                        html += '
' + r.errorMessages[i] + '
';
                    }
                    html += '
';
                    html += '
';
                    this.el.parent().createChild(html, form);
                }

                // show success content
                if (r.successContent) {
                    var el = this.el.parent().createChild(r.successContent);
                    this.el.remove();
                    Kwf.callOnContentReady(el.dom, {newRender: true});
                } else if (r.successUrl) {
                    document.location.href = r.successUrl;
                }

                if (!r.successUrl) {
                    button.down('.saving').hide();
                    button.down('.submit').show();
                }

                if (!hasErrors) {
                    this.fireEvent('submitSuccess', this, r);
                }
            },
            scope: this
        });

        e.stopEvent();
    }
});<|endoftext|>


<commit_before>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var request = require("request");
var redis = require("redis");
var scale = require("./scale.js");

//Setup Redis
client = redis.createClient();
client.on("error", function (err) {
    console.log("Error " + err);
});

//var connectedServers = {}
var serverQueue = []

http.listen(3000, function(){
    console.log('listening on *:3000');
});

//Returns the IP of the next server in the round-robin
function nextServer(){
    var ip = serverQueue.shift();
    if(ip !== undefined){
        serverQueue.push(ip);
    }

    return ip;
}

var cpuUsages = []
var time = 0;
var recordingInterval = 1000 * 10;
var endtime = 7440000;
var training = false;
var recording = false;
var ended = false;
var keyPrefix = training ? "training:" : "testing:";

//Clear data from previous runs
client.keys(keyPrefix + "*", function(err, keys){
    keys.forEach(function(key){
        client.del(key);
    });
    console.log("Flushed Keys");
});

var requests = 0;
var serverResponses = {};

function startRecordingUsage() {
    scale.emitTrainingData(client, io);
    var recordUsage = setInterval(function(){
        if(!ended){
            var count = cpuUsages.length;
            if(count == 0){
                return;
            }

            var sum = 0;
            while(cpuUsages.length > 0){
                sum += cpuUsages.pop();
            }

            var average = sum / count;

            console.log(JSON.stringify({ip: "Average",
            usage: average.toString()}));

            io.emit('cpu-ip', JSON.stringify({ip: "Average",
            usage: average.toString()}));

            time += recordingInterval;

            client.set(keyPrefix + time, average, redis.print);
            client.set(keyPrefix + "requests:" + time, requests, function(){
                scale.emitTestData(client, time, io);
            });

            if(!training){
                setTimeout(function() {
                    scale.scale(client, time + 1000 * 10, io, average);
                }, recordingInterval - (1000 * 3));
            }

            for (var server in serverResponses) {
                if (serverResponses.hasOwnProperty(server)) {
                    client.set(keyPrefix + "responses:" + server + ":" + time, serverResponses[server])
                }
            }

            requests = 0;
            serverResponses = {};

            if(time > endtime){
                ended = true;
            }

        }

    }, recordingInterval);
}

function removeFromServerList(ip){
    var index = serverQueue.indexOf(ip);
    if(index > -1){
        serverQueue.splice(index, 1);
    }
}

io.on('connection', function(socket){
    console.log(socket.request.connection._peername.address);
    var ip = socket.request.connection._peername.address;

    socket.on('cpu-usage', function(msg){
        if(serverQueue.indexOf(ip) === -1){
            serverQueue.push(ip);
        }

        if(recording){
            cpuUsages.push(msg);
        }
    });

    socket.on('scale-instructions-req', function(msg){
        scale.scale(client, time + 1000 * 10, io);
    });

    socket.on('shutdown', function(){
        console.log('Shutdown Request Received');
        removeFromServerList(ip);
        socket.emit('shutdown-complete', "");
    });

    socket.on('disconnect', function(){
        //Call again incase of unexpected shutdown
        removeFromServerList(ip);
    });
});

app.get('/', function(req, res){
    if(!recording){
        recording = true;
        startRecordingUsage();
    }

    requests++;

    var server = nextServer();
    request("http://" + server + ":3005" , function(error, response, body) {
        res.write("You were served by " + server + "\n")
        res.end(body);

        if(serverResponses[server] === undefined){
            serverResponses[server] = 1;
        }
        else {
            serverResponses[server]++;
        }
    });
});
<commit_msg>Add time to response<commit_after>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var request = require("request");
var redis = require("redis");
var scale = require("./scale.js");

//Setup Redis
client = redis.createClient();
client.on("error", function (err) {
    console.log("Error " + err);
});

//var connectedServers = {}
var serverQueue = []

http.listen(3000, function(){
    console.log('listening on *:3000');
});

//Returns the IP of the next server in the round-robin
function nextServer(){
    var ip = serverQueue.shift();
    if(ip !== undefined){
        serverQueue.push(ip);
    }

    return ip;
}

var cpuUsages = []
var time = 0;
var recordingInterval = 1000 * 10;
var endtime = 7440000;
var training = false;
var recording = false;
var ended = false;
var keyPrefix = training ? "training:" : "testing:";

//Clear data from previous runs
client.keys(keyPrefix + "*", function(err, keys){
    keys.forEach(function(key){
        client.del(key);
    });
    console.log("Flushed Keys");
});

var requests = 0;
var serverResponses = {};

function startRecordingUsage() {
    scale.emitTrainingData(client, io);
    var recordUsage = setInterval(function(){
        if(!ended){
            var count = cpuUsages.length;
            if(count == 0){
                return;
            }

            var sum = 0;
            while(cpuUsages.length > 0){
                sum += cpuUsages.pop();
            }

            var average = sum / count;

            console.log(JSON.stringify({ip: "Average",
            usage: average.toString()}));

            io.emit('cpu-ip', JSON.stringify({ip: "Average",
            usage: average.toString()}));

            time += recordingInterval;

            client.set(keyPrefix + time, average, redis.print);
            client.set(keyPrefix + "requests:" + time, requests, function(){
                scale.emitTestData(client, time, io);
            });

            if(!training){
                setTimeout(function() {
                    scale.scale(client, time + 1000 * 10, io, average);
                }, recordingInterval - (1000 * 3));
            }

            for (var server in serverResponses) {
                if (serverResponses.hasOwnProperty(server)) {
                    client.set(keyPrefix + "responses:" + server + ":" + time, serverResponses[server])
                }
            }

            requests = 0;
            serverResponses = {};

            if(time > endtime){
                ended = true;
            }

        }

    }, recordingInterval);
}

function removeFromServerList(ip){
    var index = serverQueue.indexOf(ip);
    if(index > -1){
        serverQueue.splice(index, 1);
    }
}

io.on('connection', function(socket){
    console.log(socket.request.connection._peername.address);
    var ip = socket.request.connection._peername.address;

    socket.on('cpu-usage', function(msg){
        if(serverQueue.indexOf(ip) === -1){
            serverQueue.push(ip);
        }

        if(recording){
            cpuUsages.push(msg);
        }
    });

    socket.on('scale-instructions-req', function(msg){
        scale.scale(client, time + 1000 * 10, io);
    });

    socket.on('shutdown', function(){
        console.log('Shutdown Request Received');
        removeFromServerList(ip);
        socket.emit('shutdown-complete', "");
    });

    socket.on('disconnect', function(){
        //Call again incase of unexpected shutdown
        removeFromServerList(ip);
    });
});

app.get('/', function(req, res){
    if(!recording){
        recording = true;
        startRecordingUsage();
    }

    //Count the amount of requests received
    requests++;

    var server = nextServer();
    request("http://" + server + ":3005" , function(error, response, body) {
        res.end(JSON.Stringify({"time": time, "response": response}));

        if(serverResponses[server] === undefined){
            serverResponses[server] = 1;
        }
        else {
            serverResponses[server]++;
        }
    });
});
<|endoftext|>


<commit_before>/* global Log, Module, moment, config */
/* Magic Mirror
 * Module: MMM-NetworkScanner
 *
 * By Ian Perrin http://ianperrin.com
 * MIT Licensed.
 */

 Module.register("MMM-NetworkScanner",{

     // Default module config.
    defaults: {
        devices: [],                    // an array of device objects e.g. { macAddress: "aa:bb:cc:11:22:33", name: "DEVICE-NAME", icon: "FONT-AWESOME-ICON"}
        showUnknown: true,              // shows devices found on the network even if not specified in the 'devices' option
        showOffline: true,              // shows devices specified in the 'devices' option even when offline
        keepAlive: 180,                 // how long (in seconds) a device should be considered 'alive' since it was last found on the network
        updateInterval: 10,             // how often (in seconds) the module should scan the network
        residentList: { residents: ['Me'],
                        home: {notification: 'REMOTE_ACTION', payload: {action: 'MONITORON'}},
                        out:  {notification: 'REMOTE_ACTION', payload: {action: 'MONITOROFF'}},
                       }// Command for entering
    },

    // Subclass start method.
    start: function() {
        Log.info("Starting module: " + this.name);
        this.occupied = true;
        moment.locale(config.language);
        this.scanNetwork();
    },

    // Subclass getStyles method.
    getStyles: function() {
        return ['font-awesome.css'];
    },

    // Subclass getScripts method.
    getScripts: function() {
        return ["moment.js"];
    },

    // Subclass socketNotificationReceived method.
    socketNotificationReceived: function(notification, payload) {
        Log.info(this.name + " received a notification: " + notification);

        if (notification === 'MAC_ADDRESSES')
        {
            // No action if data is the same
            if (JSON.stringify(this.networkDevices) === JSON.stringify(payload))  {
                return;
            }

            // Build device status list
            this.networkDevices = [];
            for (var i = 0; i < payload.length - 1; i++) {

                var device = this.getDeviceByMacAddress(payload[i]);
                if (device) {
                    device.online = true;
                    device.lastSeen = moment();
                    this.networkDevices.push(device);
                }
            }

            // Add offline known devices
            if (this.config.showOffline) {
                for (var d = 0; d < this.config.devices.length; d++) {
                    var device = this.config.devices[d];

                    for(var n = 0; n < this.networkDevices.length; n++){
                        if( this.networkDevices[n].macAddress.toUpperCase() === device.macAddress.toUpperCase()) {
                            n = -1;
                            break;
                        }
                    }

                    if (n != -1) {
                        if (device.lastSeen) {
                            device.online = (moment().diff(device.lastSeen, 'seconds') < this.config.keepAlive);
                            Log.info (this.name + " is keeping alive " + device.name + ". Last seen " + device.lastSeen.fromNow());
                        } else {
                            device.online = false;
                        }
                        this.networkDevices.push(device);
                    }
                }
            }

            // Sort list by known device names, then unknown device mac addresses
            this.networkDevices.sort(function(a, b) {
                var stringA = (a.name ? "_" + a.name : a.macAddress);
                var stringB = (b.name ? "_" + b.name : b.macAddress);

                return stringA.localeCompare(stringB);
            });

            // bjn send updates if no residents are home
            // Send notification if user status has changed
            if (this.config.residentList.residents.length > 0) {
//               console.log("There is a residents list");
               var updatedOccupied = false;
               var residentsList = this.config.residentList
//               for (var i=0; i < residentsList.residents.length; i++) {}
//               console.log(residentsList.residents)
//               console.log("People currently home:");
//               console.log(this.networkDevices);

               Array.prototype.contains = function(element){
                  return this.indexOf(element) > -1;
               };

               var anyoneHome = 0;

               for (var i=0; i<this.networkDevices.length; i++) {
                  device = this.networkDevices[i];
//                  console.log(device)
                  var resident = residentsList.residents.contains(device.name);
//                  console.log("Device found in list of residents");
//                  console.log(device.name, " is a resident: ", resident);
                  if (resident) {
                     anyoneHome = anyoneHome + device.online;
                  };
               }

               console.log("# people home: ",anyoneHome)

               if (anyoneHome > 0) {
//                  console.log("Someone is home")
                  if (this.occupied==false) {
                     console.log("Someone has come home")
                     var command = residentsList.home;
                     this.sendNotification(command.notification, command.payload);
                     this.occupied=true;
                  };
               } else {
//                  console.log("No residents are home")
                  if (this.occupied==true) {
                     console.log("Everyone has left home");
                     var command = residentsList.out;
                     this.sendNotification(command.notification, command.payload);
                     this.occupied=false;
                  };
               };

            };

            this.updateDom();
        }
    },

    // Override dom generator.
    getDom: function() {
        //Log.info(this.name + " is updating the DOM");
        var wrapper = document.createElement("div");
        wrapper.classList.add("small");

        // Display a loading message
        if (!this.networkDevices) {
            wrapper.innerHTML = this.translate("LOADING");
            return wrapper;
        }

        // Display device status
        var deviceList = document.createElement("ul");
        deviceList.classList.add("fa-ul");
        for (var i = 0; i < this.networkDevices.length; i++) {
            var device = this.networkDevices[i];
            if (device) {

                // device list item
                var deviceItem = document.createElement("li");
                var deviceOnline = (device.online ? "bright" : "dimmed");
                deviceItem.classList.add(deviceOnline);

                // Icon
                var icon =  document.createElement("i");
                icon.classList.add("fa-li", "fa", "fa-" + (device.icon ? device.icon : "question"));
                deviceItem.appendChild(icon);

                // Name
                deviceItem.innerHTML += (device.name ? device.name: device.macAddress) ;

                deviceList.appendChild(deviceItem);

            } else {
                Log.info("Online, but ignoring: '" + this.networkDevices[i] + "'");
            }
        }
        if(deviceList.hasChildNodes()) {
            wrapper.appendChild(deviceList);
        } else {
            // Display no devices online message
            wrapper.innerHTML = this.translate("NO DEVICES ONLINE");
        }

        return wrapper;
    },

    scanNetwork: function() {
        var self = this;
        this.sendSocketNotification('SCAN_NETWORK');
        setInterval(function() {
            self.sendSocketNotification('SCAN_NETWORK');
        }, this.config.updateInterval * 1000);
    },

    getDeviceByMacAddress: function(macAddress) {

        // Find first device with matching macAddress
        for (var i = 0; i < this.config.devices.length; i++) {
            var device = this.config.devices[i];
            if (macAddress.toUpperCase() === device.macAddress.toUpperCase()){
                return device;
            }
        }

        // Return macAddress (if showing unknown) or null
        if (this.config.showUnknown) {
            return {macAddress: macAddress};
        } else {
            return null;
        }
    },

    sendNotifications: function() {
      console.log(this.networkDevices)
    }

});
<commit_msg>Changed to arrive and depart options<commit_after>/* global Log, Module, moment, config */
/* Magic Mirror
 * Module: MMM-NetworkScanner
 *
 * By Ian Perrin http://ianperrin.com
 * MIT Licensed.
 */

 Module.register("MMM-NetworkScanner",{

     // Default module config.
    defaults: {
        devices: [],                    // an array of device objects e.g. { macAddress: "aa:bb:cc:11:22:33", name: "DEVICE-NAME", icon: "FONT-AWESOME-ICON"}
        showUnknown: true,              // shows devices found on the network even if not specified in the 'devices' option
        showOffline: true,              // shows devices specified in the 'devices' option even when offline
        keepAlive: 180,                 // how long (in seconds) a device should be considered 'alive' since it was last found on the network
        updateInterval: 10,             // how often (in seconds) the module should scan the network
        residentList: { residents: ['Me'],
                        arrive: {notification: 'REMOTE_ACTION', payload: {action: 'MONITORON'}},
                        dapart:  {notification: 'REMOTE_ACTION', payload: {action: 'MONITOROFF'}},
                       }// Command for entering
    },

    // Subclass start method.
    start: function() {
        Log.info("Starting module: " + this.name);
        this.occupied = true;
        moment.locale(config.language);
        this.scanNetwork();
    },

    // Subclass getStyles method.
    getStyles: function() {
        return ['font-awesome.css'];
    },

    // Subclass getScripts method.
    getScripts: function() {
        return ["moment.js"];
    },

    // Subclass socketNotificationReceived method.
    socketNotificationReceived: function(notification, payload) {
        Log.info(this.name + " received a notification: " + notification);

        if (notification === 'MAC_ADDRESSES')
        {
            // No action if data is the same
            if (JSON.stringify(this.networkDevices) === JSON.stringify(payload))  {
                return;
            }

            // Build device status list
            this.networkDevices = [];
            for (var i = 0; i < payload.length - 1; i++) {

                var device = this.getDeviceByMacAddress(payload[i]);
                if (device) {
                    device.online = true;
                    device.lastSeen = moment();
                    this.networkDevices.push(device);
                }
            }

            // Add offline known devices
            if (this.config.showOffline) {
                for (var d = 0; d < this.config.devices.length; d++) {
                    var device = this.config.devices[d];

                    for(var n = 0; n < this.networkDevices.length; n++){
                        if( this.networkDevices[n].macAddress.toUpperCase() === device.macAddress.toUpperCase()) {
                            n = -1;
                            break;
                        }
                    }

                    if (n != -1) {
                        if (device.lastSeen) {
                            device.online = (moment().diff(device.lastSeen, 'seconds') < this.config.keepAlive);
                            Log.info (this.name + " is keeping alive " + device.name + ". Last seen " + device.lastSeen.fromNow());
                        } else {
                            device.online = false;
                        }
                        this.networkDevices.push(device);
                    }
                }
            }

            // Sort list by known device names, then unknown device mac addresses
            this.networkDevices.sort(function(a, b) {
                var stringA = (a.name ? "_" + a.name : a.macAddress);
                var stringB = (b.name ? "_" + b.name : b.macAddress);

                return stringA.localeCompare(stringB);
            });

            // bjn send updates if no residents are home
            // Send notification if user status has changed
            if (this.config.residentList.residents.length > 0) {
//               console.log("There is a residents list");
               var updatedOccupied = false;
               var residentsList = this.config.residentList
//               for (var i=0; i < residentsList.residents.length; i++) {}
//               console.log(residentsList.residents)
//               console.log("People currently home:");
//               console.log(this.networkDevices);

               Array.prototype.contains = function(element){
                  return this.indexOf(element) > -1;
               };

               var anyoneHome = 0;

               for (var i=0; i<this.networkDevices.length; i++) {
                  device = this.networkDevices[i];
//                  console.log(device)
                  var resident = residentsList.residents.contains(device.name);
//                  console.log("Device found in list of residents");
//                  console.log(device.name, " is a resident: ", resident);
                  if (resident) {
                     anyoneHome = anyoneHome + device.online;
                  };
               }

               console.log("# people home: ",anyoneHome)

               if (anyoneHome > 0) {
//                  console.log("Someone is home")
                  if (this.occupied==false) {
                     console.log("Someone has come home")
                     var command = residentsList.arrive;
                     this.sendNotification(command.notification, command.payload);
                     this.occupied=true;
                  };
               } else {
//                  console.log("No residents are home")
                  if (this.occupied==true) {
                     console.log("Everyone has left home");
                     var command = residentsList.depart;
                     this.sendNotification(command.notification, command.payload);
                     this.occupied=false;
                  };
               };

            };

            this.updateDom();
        }
    },

    // Override dom generator.
    getDom: function() {
        //Log.info(this.name + " is updating the DOM");
        var wrapper = document.createElement("div");
        wrapper.classList.add("small");

        // Display a loading message
        if (!this.networkDevices) {
            wrapper.innerHTML = this.translate("LOADING");
            return wrapper;
        }

        // Display device status
        var deviceList = document.createElement("ul");
        deviceList.classList.add("fa-ul");
        for (var i = 0; i < this.networkDevices.length; i++) {
            var device = this.networkDevices[i];
            if (device) {

                // device list item
                var deviceItem = document.createElement("li");
                var deviceOnline = (device.online ? "bright" : "dimmed");
                deviceItem.classList.add(deviceOnline);

                // Icon
                var icon =  document.createElement("i");
                icon.classList.add("fa-li", "fa", "fa-" + (device.icon ? device.icon : "question"));
                deviceItem.appendChild(icon);

                // Name
                deviceItem.innerHTML += (device.name ? device.name: device.macAddress) ;

                deviceList.appendChild(deviceItem);

            } else {
                Log.info("Online, but ignoring: '" + this.networkDevices[i] + "'");
            }
        }
        if(deviceList.hasChildNodes()) {
            wrapper.appendChild(deviceList);
        } else {
            // Display no devices online message
            wrapper.innerHTML = this.translate("NO DEVICES ONLINE");
        }

        return wrapper;
    },

    scanNetwork: function() {
        var self = this;
        this.sendSocketNotification('SCAN_NETWORK');
        setInterval(function() {
            self.sendSocketNotification('SCAN_NETWORK');
        }, this.config.updateInterval * 1000);
    },

    getDeviceByMacAddress: function(macAddress) {

        // Find first device with matching macAddress
        for (var i = 0; i < this.config.devices.length; i++) {
            var device = this.config.devices[i];
            if (macAddress.toUpperCase() === device.macAddress.toUpperCase()){
                return device;
            }
        }

        // Return macAddress (if showing unknown) or null
        if (this.config.showUnknown) {
            return {macAddress: macAddress};
        } else {
            return null;
        }
    },

    sendNotifications: function() {
      console.log(this.networkDevices)
    }

});
<|endoftext|>


<commit_before>import React from "react";
import TableProvider from "components/TableProvider";
import Table from "components/bs4/Table";
import Actions from "components/Actions";
import CDeleteLink from "components/CDeleteLink";
import CEditLink from "components/CEditLink";
import CNewBtn from "components/CNewBtn";
import PageHeader from "components/bs4/PageHeader";
import {Button} from "react-bootstrap4";
import app from "app";

export default class extends React.Component {
  handleClick = (reload) => {
    app.post(app.url('admin/wechat-groups/sync-from-wechat'))
      .then(ret => $.msg(ret, () => reload()));
  };

  render() {
    window.app = app;

    return <>
      <TableProvider>
        {({reload}) => <>
          <PageHeader>

              {wei.hasWechatGroup && <Button variant="secondary" onClick={this.handleClick.bind(this, reload)}>
                从微信同步分组
              </Button>}
              {' '}
              <CNewBtn/>

            {wei.page.controllerTitle}
          </PageHeader>

 cell > 0 ? '已同步' : '未同步',
              },
              {
                text: '操作',
                formatter: (cell, row) => <Actions>
                  <CEditLink id={row.id}/>
                  <CDeleteLink id={row.id}/>
                </Actions>
              },
            ]}
          />
        </>}
      </TableProvider>
    </>;
  }
}
<commit_msg>feat: 更新分组同步逻辑<commit_after>import React from "react";
import TableProvider from "components/TableProvider";
import Table from "components/bs4/Table";
import Actions from "components/Actions";
import CDeleteLink from "components/CDeleteLink";
import CEditLink from "components/CEditLink";
import CNewBtn from "components/CNewBtn";
import PageHeader from "components/bs4/PageHeader";
import {Button} from "react-bootstrap4";
import app from "app";
import axios from 'axios';

export default class extends React.Component {
  handleClick = (api) => {
    axios.post(app.url('admin/wechat-groups/sync-from-wechat'), {}, {loading: true})
      .then(({data}) => app.ret(data, api.reload));
  };

  render() {
    return <>
      <TableProvider>
        {api => <>
          <PageHeader>

              {wei.hasWechatGroup && <Button variant="secondary" onClick={this.handleClick.bind(this, api)}>
                从微信同步分组
              </Button>}
              {' '}
              <CNewBtn/>

            {wei.page.controllerTitle}
          </PageHeader>

 cell > 0 ? '已同步' : '未同步',
              },
              {
                text: '操作',
                formatter: (cell, row) => <Actions>
                  <CEditLink id={row.id}/>
                  <CDeleteLink id={row.id}/>
                </Actions>
              },
            ]}
          />
        </>}
      </TableProvider>
    </>;
  }
}
<|endoftext|>


<commit_before>define(function () {

    function RunQuery (bezl, queryName) {

        switch (queryName) {
            case "Orders":
                bezl.vars.loading = true;

                // Pull in the accounts list for the logged in user
                bezl.dataService.add('Orders','brdb','sales-rep-queries','ExecuteQuery', {
                    "QueryName": "OrderInquiry",
                    "Parameters": [
                        { "Key": "StartDate", "Value": bezl.vars.startDate || "01/01/1900"},
                        { "Key": "EndDate", "Value": bezl.vars.endDate || "01/01/2100"},
                        { "Key": "CustID", "Value": bezl.vars.selectedAccount.ID || ""},
                        { "Key": "Company", "Value": 'All' }
                    ] },0);
                break;
            default:
                break;
        }
    }

    function Select(bezl, Order) {
        // Mark the selected customer as selected
        for (var i = 0; i < bezl.vars.Orders.length; i++) {
            if (bezl.vars.Orders[i].OrderNum == Order.OrderNum) {
                bezl.vars.Orders[i].Selected = !bezl.vars.Orders[i].Selected;

                if (bezl.vars.Orders[i].Selected) {
                    localStorage.setItem('selectedOrder', JSON.stringify(bezl.vars.Orders[i]));
                    $('.panel').trigger('selectedOrder', [bezl.vars.Orders[i]]);
                } else {
                    localStorage.setItem('selectedOrder', '');
                    $('.panel').trigger('selectedOrder', [{}]);
                }

            } else {
                bezl.vars.Orders[i].Selected = false;
            }
        };
    }

    function Filter(bezl) {
        // Filter, will hide the table rows that do not match filter
        var tr, td;
        tr = document.getElementById("orderList").getElementsByTagName("tr");

        // Loop through all rows
        for(var i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[0];

            if(td) {
                if(bezl.vars.filter.toUpperCase() == "ALL")
                {
                    tr[i].style.display = "";
                } else if(td.children[0].children[4].innerHTML.toUpperCase().indexOf(bezl.vars.filter.toUpperCase()) > -1){
                    tr[i].style.display = "";
                }
                else {
                    tr[i].style.display = "none";
                }
            }
        }

    }

    function Sort(bezl, sortColumn) {

        // If the previous sort column was picked, make it the opposite sort
        if (bezl.vars.sortCol == sortColumn) {
            if (bezl.vars.sort == "desc") {
                bezl.vars.sort = "asc";
            } else {
                bezl.vars.sort = "desc";
            }
        } else {
            bezl.vars.sort = "asc";
        }

        // Store the sort column so the UI can reflect it
        bezl.vars.sortCol = sortColumn;

        // Test for numeric sort columns, otherwise sort alphabetic
        if ( sortColumn == "PoNum" || sortColumn == "OrderAmt" || sortColumn == "OrderNum") {
            if (bezl.vars.sort == "asc") {
                bezl.vars.Orders.sort(function (a, b) {
                    var A = a[sortColumn] || Number.MAX_SAFE_INTEGER;
                    var B = b[sortColumn] || Number.MAX_SAFE_INTEGER;
                    return A - B;
                });
            } else {
                bezl.vars.Orders.sort(function (a, b) {
                    var A = a[sortColumn] || Number.MAX_SAFE_INTEGER;
                    var B = b[sortColumn] || Number.MAX_SAFE_INTEGER;
                    return B - A;
                });
            }
        } else if (sortColumn == "OrderDate" ) {
            if (bezl.vars.sort == "asc") {
                bezl.vars.Orders.sort(function (a, b) {
                    var A = Date.parse(a[sortColumn]) || Number.MAX_SAFE_INTEGER;
                    var B = Date.parse(b[sortColumn]) || Number.MAX_SAFE_INTEGER;
                    return A - B;
                });
            } else {
                bezl.vars.Orders.sort(function (a, b) {
                    var A = Date.parse(a[sortColumn]) || Number.MAX_SAFE_INTEGER * -1;
                    var B = Date.parse(b[sortColumn]) || Number.MAX_SAFE_INTEGER * -1;
                    return B - A;
                });
            }
        } else {
            if (bezl.vars.sort == "asc") {
                bezl.vars.Orders.sort(function(a, b) {
                    var A = a[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    var B = b[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    if (A < B) {
                        return -1;
                    }
                    if (A > B) {
                        return 1;
                    }

                    // names must be equal
                    return 0;
                });
            } else {
                bezl.vars.Orders.sort(function(a, b) {
                    var A = a[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    var B = b[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    if (A > B) {
                        return -1;
                    }
                    if (A < B) {
                        return 1;
                    }

                    // names must be equal
                    return 0;
                });
            }
        }
    }

    function InnerSort(bezl, sortColumn) {

        // If the previous sort column was picked, make it the opposite sort
        if (bezl.vars.sortCol == sortColumn) {
            if (bezl.vars.sortInner == "desc") {
                bezl.vars.sortInner = "asc";
            } else {
                bezl.vars.sortInner = "desc";
            }
        } else {
            bezl.vars.sortInner = "asc";
        }

        // Store the sort column so the UI can reflect it
        bezl.vars.sortCol = sortColumn;

        // Test for numeric sort columns, otherwise sort alphabetic
        if (sortColumn == "LineNum" || sortColumn == "PartNum" || sortColumn == "InvoiceQty" || sortColumn == "ExtPrice" || sortColumn == "ShippedQty" || sortColumn == "UnitPrice") {
            if (bezl.vars.sortInner == "asc") {
                bezl.vars.Orders.sort(function (a, b) {
                    var A = a[sortColumn] || Number.MAX_SAFE_INTEGER;
                    var B = b[sortColumn] || Number.MAX_SAFE_INTEGER;
                    return A - B;
                });
            } else {
                bezl.vars.Orders.sort(function (a, b) {
                    var A = a[sortColumn] || Number.MAX_SAFE_INTEGER;
                    var B = b[sortColumn] || Number.MAX_SAFE_INTEGER;
                    return B - A;
                });
            }
        } else {
            if (bezl.vars.sortInner == "asc") {
                bezl.vars.Orders.sort(function(a, b) {
                    var A = a[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    var B = b[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    if (A < B) {
                        return -1;
                    }
                    if (A > B) {
                        return 1;
                    }

                    // names must be equal
                    return 0;
                });
            } else {
                bezl.vars.Orders.sort(function(a, b) {
                    var A = a[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    var B = b[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    if (A > B) {
                        return -1;
                    }
                    if (A < B) {
                        return 1;
                    }

                    // names must be equal
                    return 0;
                });
            }
        }
    }

    return {
        runQuery: RunQuery,
        select: Select,
        filter: Filter,
        sort: Sort,
        innerSort: InnerSort
    }
});<commit_msg>OrderInquiry, sorting issue with zeros<commit_after>define(function () {

    function RunQuery (bezl, queryName) {

        switch (queryName) {
            case "Orders":
                bezl.vars.loading = true;

                // Pull in the accounts list for the logged in user
                bezl.dataService.add('Orders','brdb','sales-rep-queries','ExecuteQuery', {
                    "QueryName": "OrderInquiry",
                    "Parameters": [
                        { "Key": "StartDate", "Value": bezl.vars.startDate || "01/01/1900"},
                        { "Key": "EndDate", "Value": bezl.vars.endDate || "01/01/2100"},
                        { "Key": "CustID", "Value": bezl.vars.selectedAccount.ID || ""},
                        { "Key": "Company", "Value": 'All' }
                    ] },0);
                break;
            default:
                break;
        }
    }

    function Select(bezl, Order) {
        // Mark the selected customer as selected
        for (var i = 0; i < bezl.vars.Orders.length; i++) {
            if (bezl.vars.Orders[i].OrderNum == Order.OrderNum) {
                bezl.vars.Orders[i].Selected = !bezl.vars.Orders[i].Selected;

                if (bezl.vars.Orders[i].Selected) {
                    localStorage.setItem('selectedOrder', JSON.stringify(bezl.vars.Orders[i]));
                    $('.panel').trigger('selectedOrder', [bezl.vars.Orders[i]]);
                } else {
                    localStorage.setItem('selectedOrder', '');
                    $('.panel').trigger('selectedOrder', [{}]);
                }

            } else {
                bezl.vars.Orders[i].Selected = false;
            }
        };
    }

    function Filter(bezl) {
        // Filter, will hide the table rows that do not match filter
        var tr, td;
        tr = document.getElementById("orderList").getElementsByTagName("tr");

        // Loop through all rows
        for(var i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[0];

            if(td) {
                if(bezl.vars.filter.toUpperCase() == "ALL")
                {
                    tr[i].style.display = "";
                } else if(td.children[0].children[4].innerHTML.toUpperCase().indexOf(bezl.vars.filter.toUpperCase()) > -1){
                    tr[i].style.display = "";
                }
                else {
                    tr[i].style.display = "none";
                }
            }
        }

    }

    function Sort(bezl, sortColumn) {

        // If the previous sort column was picked, make it the opposite sort
        if (bezl.vars.sortCol == sortColumn) {
            if (bezl.vars.sort == "desc") {
                bezl.vars.sort = "asc";
            } else {
                bezl.vars.sort = "desc";
            }
        } else {
            bezl.vars.sort = "asc";
        }

        // Store the sort column so the UI can reflect it
        bezl.vars.sortCol = sortColumn;

        // Test for numeric sort columns, otherwise sort alphabetic
        if ( sortColumn == "PoNum" || sortColumn == "OrderAmt" || sortColumn == "OrderNum") {
            if (bezl.vars.sort == "asc") {
                bezl.vars.Orders.sort(function (a, b) {
                    var A = a[sortColumn];
                    var B = b[sortColumn];
                    return A - B;
                });
            } else {
                bezl.vars.Orders.sort(function (a, b) {
                    var A = a[sortColumn];
                    var B = b[sortColumn];
                    return B - A;
                });
            }
        } else if (sortColumn == "OrderDate" ) {
            if (bezl.vars.sort == "asc") {
                bezl.vars.Orders.sort(function (a, b) {
                    var A = Date.parse(a[sortColumn]) || Number.MAX_SAFE_INTEGER;
                    var B = Date.parse(b[sortColumn]) || Number.MAX_SAFE_INTEGER;
                    return A - B;
                });
            } else {
                bezl.vars.Orders.sort(function (a, b) {
                    var A = Date.parse(a[sortColumn]) || Number.MAX_SAFE_INTEGER * -1;
                    var B = Date.parse(b[sortColumn]) || Number.MAX_SAFE_INTEGER * -1;
                    return B - A;
                });
            }
        } else {
            if (bezl.vars.sort == "asc") {
                bezl.vars.Orders.sort(function(a, b) {
                    var A = a[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    var B = b[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    if (A < B) {
                        return -1;
                    }
                    if (A > B) {
                        return 1;
                    }

                    // names must be equal
                    return 0;
                });
            } else {
                bezl.vars.Orders.sort(function(a, b) {
                    var A = a[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    var B = b[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    if (A > B) {
                        return -1;
                    }
                    if (A < B) {
                        return 1;
                    }

                    // names must be equal
                    return 0;
                });
            }
        }
    }

    function InnerSort(bezl, sortColumn) {

        // If the previous sort column was picked, make it the opposite sort
        if (bezl.vars.sortCol == sortColumn) {
            if (bezl.vars.sortInner == "desc") {
                bezl.vars.sortInner = "asc";
            } else {
                bezl.vars.sortInner = "desc";
            }
        } else {
            bezl.vars.sortInner = "asc";
        }

        // Store the sort column so the UI can reflect it
        bezl.vars.sortCol = sortColumn;

        // Test for numeric sort columns, otherwise sort alphabetic
        if (sortColumn == "LineNum" || sortColumn == "PartNum" || sortColumn == "InvoiceQty" || sortColumn == "ExtPrice" || sortColumn == "ShippedQty" || sortColumn == "UnitPrice") {
            if (bezl.vars.sortInner == "asc") {
                bezl.vars.Orders.sort(function (a, b) {
                    var A = a[sortColumn] || Number.MAX_SAFE_INTEGER;
                    var B = b[sortColumn] || Number.MAX_SAFE_INTEGER;
                    return A - B;
                });
            } else {
                bezl.vars.Orders.sort(function (a, b) {
                    var A = a[sortColumn] || Number.MAX_SAFE_INTEGER;
                    var B = b[sortColumn] || Number.MAX_SAFE_INTEGER;
                    return B - A;
                });
            }
        } else {
            if (bezl.vars.sortInner == "asc") {
                bezl.vars.Orders.sort(function(a, b) {
                    var A = a[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    var B = b[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    if (A < B) {
                        return -1;
                    }
                    if (A > B) {
                        return 1;
                    }

                    // names must be equal
                    return 0;
                });
            } else {
                bezl.vars.Orders.sort(function(a, b) {
                    var A = a[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    var B = b[sortColumn] .toUpperCase(); // ignore upper and lowercase
                    if (A > B) {
                        return -1;
                    }
                    if (A < B) {
                        return 1;
                    }

                    // names must be equal
                    return 0;
                });
            }
        }
    }

    return {
        runQuery: RunQuery,
        select: Select,
        filter: Filter,
        sort: Sort,
        innerSort: InnerSort
    }
});<|endoftext|>


<commit_before>// --------------- POST EFFECT DEFINITION --------------- //
/**
 * @class
 * @name OutlineEffect
 * @classdesc Applies an outline effect on input render target
 * @description Creates new instance of the post effect.
 * @augments pc.PostEffect
 * @param {pc.GraphicsDevice} graphicsDevice - The graphics device of the application.
 * @param {number} thickness - The thickness for the outline effect passed here to be used as a constant in shader.
 * @property {pc.Texture} texture The outline texture to use.
 * @property {pc.Color} color The outline color.
 */
function OutlineEffect(graphicsDevice, thickness) {
    pc.PostEffect.call(this, graphicsDevice);

    this.shader = new pc.Shader(graphicsDevice, {
        attributes: {
            aPosition: pc.SEMANTIC_POSITION
        },
        vshader: [
            "attribute vec2 aPosition;",
            "",
            "varying vec2 vUv0;",
            "",
            "void main(void)",
            "{",
            "    gl_Position = vec4(aPosition, 0.0, 1.0);",
            "    vUv0 = (aPosition.xy + 1.0) * 0.5;",
            "}"
        ].join("\n"),
        fshader: [
            "precision " + graphicsDevice.precision + " float;",
            "",
            "#define THICKNESS " + (thickness ? thickness.toFixed(0) : 1),
            "uniform float uWidth;",
            "uniform float uHeight;",
            "uniform vec4 uOutlineCol;",
            "uniform sampler2D uColorBuffer;",
            "uniform sampler2D uOutlineTex;",
            "",
            "varying vec2 vUv0;",
            "",
            "void main(void)",
            "{",
            "    vec4 texel1 = texture2D(uColorBuffer, vUv0);",
            "    float sample0 = texture2D(uOutlineTex, vUv0).a;",
            "    float outline = 0.0;",
            "    if (sample0==0.0)",
            "    {",
            "        for (int x=-THICKNESS;x<=THICKNESS;x++)",
            "        {",
            "            for (int y=-THICKNESS;y<=THICKNESS;y++)",
            "            {    ",
            "                float sample=texture2D(uOutlineTex, vUv0+vec2(float(x)/uWidth, float(y)/uHeight)).a;",
            "                if (sample>0.0)",
            "                {",
            "                    outline=1.0;",
            "                }",
            "            }",
            "        } ",
            "    }",
            "    gl_FragColor = mix(texel1, uOutlineCol, outline * uOutlineCol.a);",
            "}"
        ].join("\n")
    });

    // Uniforms
    this.color = new pc.Color(1, 1, 1, 1);
    this.texture = new pc.Texture(graphicsDevice);
    this.texture.name = 'pe-outline';
}

OutlineEffect.prototype = Object.create(pc.PostEffect.prototype);
OutlineEffect.prototype.constructor = OutlineEffect;

Object.assign(OutlineEffect.prototype, {
    render: function (inputTarget, outputTarget, rect) {
        var device = this.device;
        var scope = device.scope;

        scope.resolve("uWidth").setValue(inputTarget.width);
        scope.resolve("uHeight").setValue(inputTarget.height);
        scope.resolve("uOutlineCol").setValue(this.color.data);
        scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer);
        scope.resolve("uOutlineTex").setValue(this.texture);
        pc.drawFullscreenQuad(device, outputTarget, this.vertexBuffer, this.shader, rect);
    }
});

// ----------------- SCRIPT DEFINITION ------------------ //
var Outline = pc.createScript('outline');

Outline.attributes.add('color', {
    type: 'rgb',
    default: [0.5, 0.5, 0.5],
    title: 'Color'
});

Outline.attributes.add("thickness", {
    type: "number",
    default: 1.0,
    min: 1.0,
    max: 10,
    precision: 0,
    title: "Thickness",
    description: "Note: Changing the thickness requires reloading the effect."
});

Outline.attributes.add('texture', {
    type: 'asset',
    assetType: 'texture',
    title: 'Texture'
});

Outline.prototype.initialize = function () {
    this.effect = new OutlineEffect(this.app.graphicsDevice, this.thickness);
    this.effect.color = this.color;
    this.effect.texture = this.texture.resource;

    var queue = this.entity.camera.postEffects;

    queue.addEffect(this.effect);

    this.on('state', function (enabled) {
        if (enabled) {
            queue.addEffect(this.effect);
        } else {
            queue.removeEffect(this.effect);
        }
    });

    this.on('destroy', function () {
        queue.removeEffect(this.effect);
    });

    this.on('attr:color', function (value) {
        this.effect.color = value;
    }, this);

    this.on('attr:texture', function (value) {
        this.effect.texture = value ? value.resource : null;
    }, this);
};
<commit_msg>Remove deprecated method from outline effect (#2847)<commit_after>// --------------- POST EFFECT DEFINITION --------------- //
/**
 * @class
 * @name OutlineEffect
 * @classdesc Applies an outline effect on input render target
 * @description Creates new instance of the post effect.
 * @augments pc.PostEffect
 * @param {pc.GraphicsDevice} graphicsDevice - The graphics device of the application.
 * @param {number} thickness - The thickness for the outline effect passed here to be used as a constant in shader.
 * @property {pc.Texture} texture The outline texture to use.
 * @property {pc.Color} color The outline color.
 */
function OutlineEffect(graphicsDevice, thickness) {
    pc.PostEffect.call(this, graphicsDevice);

    this.shader = new pc.Shader(graphicsDevice, {
        attributes: {
            aPosition: pc.SEMANTIC_POSITION
        },
        vshader: [
            "attribute vec2 aPosition;",
            "",
            "varying vec2 vUv0;",
            "",
            "void main(void)",
            "{",
            "    gl_Position = vec4(aPosition, 0.0, 1.0);",
            "    vUv0 = (aPosition.xy + 1.0) * 0.5;",
            "}"
        ].join("\n"),
        fshader: [
            "precision " + graphicsDevice.precision + " float;",
            "",
            "#define THICKNESS " + (thickness ? thickness.toFixed(0) : 1),
            "uniform float uWidth;",
            "uniform float uHeight;",
            "uniform vec4 uOutlineCol;",
            "uniform sampler2D uColorBuffer;",
            "uniform sampler2D uOutlineTex;",
            "",
            "varying vec2 vUv0;",
            "",
            "void main(void)",
            "{",
            "    vec4 texel1 = texture2D(uColorBuffer, vUv0);",
            "    float sample0 = texture2D(uOutlineTex, vUv0).a;",
            "    float outline = 0.0;",
            "    if (sample0==0.0)",
            "    {",
            "        for (int x=-THICKNESS;x<=THICKNESS;x++)",
            "        {",
            "            for (int y=-THICKNESS;y<=THICKNESS;y++)",
            "            {    ",
            "                float sample=texture2D(uOutlineTex, vUv0+vec2(float(x)/uWidth, float(y)/uHeight)).a;",
            "                if (sample>0.0)",
            "                {",
            "                    outline=1.0;",
            "                }",
            "            }",
            "        } ",
            "    }",
            "    gl_FragColor = mix(texel1, uOutlineCol, outline * uOutlineCol.a);",
            "}"
        ].join("\n")
    });

    // Uniforms
    this.color = new pc.Color(1, 1, 1, 1);
    this.texture = new pc.Texture(graphicsDevice);
    this.texture.name = 'pe-outline';
    this._colorData = new Float32Array(4);
}

OutlineEffect.prototype = Object.create(pc.PostEffect.prototype);
OutlineEffect.prototype.constructor = OutlineEffect;

Object.assign(OutlineEffect.prototype, {
    render: function (inputTarget, outputTarget, rect) {
        var device = this.device;
        var scope = device.scope;

        this._colorData[0] = this.color.r;
        this._colorData[1] = this.color.g;
        this._colorData[2] = this.color.b;
        this._colorData[3] = this.color.a;

        scope.resolve("uWidth").setValue(inputTarget.width);
        scope.resolve("uHeight").setValue(inputTarget.height);
        scope.resolve("uOutlineCol").setValue(this._colorData);
        scope.resolve("uColorBuffer").setValue(inputTarget.colorBuffer);
        scope.resolve("uOutlineTex").setValue(this.texture);
        pc.drawFullscreenQuad(device, outputTarget, this.vertexBuffer, this.shader, rect);
    }
});

// ----------------- SCRIPT DEFINITION ------------------ //
var Outline = pc.createScript('outline');

Outline.attributes.add('color', {
    type: 'rgb',
    default: [0.5, 0.5, 0.5],
    title: 'Color'
});

Outline.attributes.add("thickness", {
    type: "number",
    default: 1.0,
    min: 1.0,
    max: 10,
    precision: 0,
    title: "Thickness",
    description: "Note: Changing the thickness requires reloading the effect."
});

Outline.attributes.add('texture', {
    type: 'asset',
    assetType: 'texture',
    title: 'Texture'
});

Outline.prototype.initialize = function () {
    this.effect = new OutlineEffect(this.app.graphicsDevice, this.thickness);
    this.effect.color = this.color;
    this.effect.texture = this.texture.resource;

    var queue = this.entity.camera.postEffects;

    queue.addEffect(this.effect);

    this.on('state', function (enabled) {
        if (enabled) {
            queue.addEffect(this.effect);
        } else {
            queue.removeEffect(this.effect);
        }
    });

    this.on('destroy', function () {
        queue.removeEffect(this.effect);
    });

    this.on('attr:color', function (value) {
        this.effect.color = value;
    }, this);

    this.on('attr:texture', function (value) {
        this.effect.texture = value ? value.resource : null;
    }, this);
};
<|endoftext|>


<commit_before>var TEMPLATE_EXECUTE_RESPONSE_MARKUP = '\

 \

 \

 \

 \

 \
					Identifier${identifier}
 \

 \
					Title${title}
 \

 \

 \

 \

 \

 \
					Created on ${creationTime}
 \

 \

 \

 \

';

var TEMPLATE_EXECUTE_RESPONSE_EXTENSION_MARKUP_DOWNLOAD = '\

 \
			${key}download
 \

';

var TEMPLATE_EXECUTE_RESPONSE_EXTENSION_MARKUP_IMAGE = '\

 \
			${key}
 \
			 \

';

var TEMPLATE_EXECUTE_RESPONSE_EXTENSION_MARKUP_VALUE = '\

 \
			${key}${value}
 \

';

var TEMPLATE_EXECUTE_RESPONSE_STATUS_NORMAL_MARKUP = '\

 \
			Status${status} \

';

var TEMPLATE_EXECUTE_RESPONSE_STATUS_FAILED_MARKUP = '\

 \
			Status${status} \

 \

 \
			Message${message} \

';

var ExecuteResponse = BaseResponse.extend({

	resolveProcessOutputs : function(processOutputs) {
		var outputs = processOutputs.getElementsByTagNameNS(WPS_100_NAMESPACE, "Output");

		var array = new Array(outputs.length);
		for (var i = 0; i < outputs.length; i++) {
			var element = outputs[i];
			var identifier = element.getElementsByTagNameNS(OWS_11_NAMESPACE, "Identifier");
			var title = element.getElementsByTagNameNS(OWS_11_NAMESPACE, "Title");
			var reference = element.getElementsByTagNameNS(WPS_100_NAMESPACE, "Reference");
			var data = element.getElementsByTagNameNS(WPS_100_NAMESPACE, "Data");
			var value;
			var valueType = null;
			if (reference && reference.length > 0) { // create link from reference
				value = reference[0].getAttribute("href");
				array[i] = {
						key : jQuery(identifier).text(),
						title: jQuery(title).text(),
						value : value,
						ref: true
				};
			}
			else {
				if(data && data.length > 0) { // show inline values
					value = "", valueType = "";
					// each data child element
					jQuery(data).children().each(function(key, val) {
						var $val = jQuery(val);
						value += $val.text();
						valueType += $val.attr("dataType");
					});
				}
				else {
					value = "n/a";
				}

				array[i] = {
						key : jQuery(identifier).text(),
						title: jQuery(title).text(),
						value : value,
						valueType: valueType,
						ref: false
				};
			}
		}

		var result = {outputs : array};

		return result;
	},

	createMarkup : function() {
		var process = this.xmlResponse.getElementsByTagNameNS(WPS_100_NAMESPACE, "Process");
		var status = this.xmlResponse.getElementsByTagNameNS(WPS_100_NAMESPACE, "Status");
		var reference = this.xmlResponse.getElementsByTagNameNS(WPS_100_NAMESPACE, "Reference");
		var complexData = this.xmlResponse.getElementsByTagNameNS(WPS_100_NAMESPACE, "ComplexData");

		var mimetype = null;

		if(reference && reference[0]){
		    mimetype = reference[0].getAttribute('mimeType');
		}else if(complexData && complexData[0]){
		    mimetype = complexData[0].getAttribute('mimeType');
		}

		var properties = null;
		var extensions = {};
		var statusText = null;
		var statusMessage = null;
		var processFailed = false;

		if (process && process[0] && status && status[0]) {
			var identifier = jQuery(process[0].getElementsByTagNameNS(OWS_11_NAMESPACE, "Identifier")).text();
			var title = jQuery(process[0].getElementsByTagNameNS(OWS_11_NAMESPACE, "Title")).text();

			var accepted = status[0].getElementsByTagNameNS(WPS_100_NAMESPACE, "ProcessAccepted");
			if (accepted && accepted.length > 0) {
				statusText = jQuery(accepted).text();
			}
			if (!statusText) {
				var started = status[0].getElementsByTagNameNS(WPS_100_NAMESPACE, "ProcessStarted");
				if (started && started.length > 0) {
					var percent = started[0].getAttribute("percentCompleted");
					statusText = "Process started (" + percent + " % complete)";
				}
			}
			//process paused
			if (!statusText) {
				var paused = status[0].getElementsByTagNameNS(WPS_100_NAMESPACE, "ProcessPaused");
				if (paused && paused.length > 0) {
					statusText = "Process paused";
				}
			}
			if (!statusText) {
				var succeeded = status[0].getElementsByTagNameNS(WPS_100_NAMESPACE, "ProcessSucceeded");
				if (succeeded && succeeded.length > 0) {
					statusText = "Process succeeded";
					var processOutputs = this.xmlResponse.getElementsByTagNameNS(WPS_100_NAMESPACE, "ProcessOutputs");
					if (processOutputs && processOutputs.length > 0) {
						extensions = jQuery.extend(this.resolveProcessOutputs(processOutputs[0]), extensions);
					}
				}
			}
			//process failed
			if (!statusText) {
				var failed = status[0].getElementsByTagNameNS(WPS_100_NAMESPACE, "ProcessFailed");
				if (failed && failed.length > 0) {
					statusText = "Process failed";

					exceptionText = status[0].getElementsByTagNameNS(OWS_11_NAMESPACE, "ExceptionText");
					if(exceptionText) {
						statusMessage = exceptionText.item(0).innerHTML;
						//TODO display more than one exception text
					}
					processFailed = true;
				}
			}

			var time = status[0].getAttribute("creationTime");
			if (time) {
			    var d = new Date(time);
			    time = d.toLocaleString();
			}

			var updateSwitch;
			if (this.originalRequest.updateSwitch) {
				updateSwitch = '';
			}
			else {
				updateSwitch = 'display:none';
			}

			properties = {
					identifier : identifier,
					title : title,
					creationTime : time,
					updateSwitchEnabled : updateSwitch
			};
		}

		var statusLocation = this.xmlResponse.documentElement.getAttribute("statusLocation");
		/*
		 * Make this updateable and NOT execute two times.
		 */
		if (statusLocation) {
			this.originalRequest.settings.url = statusLocation;
			//this.originalRequest = new GetRequest(this.originalRequest.settings);

			var getSettings = {
				url : this.originalRequest.settings.url,
				requestType : this.originalRequest.settings.requestType,
				type : "GET"
			};

			this.originalRequest = new GetRequest(getSettings);
		}

		var template;
		if (USER_TEMPLATE_EXECUTE_RESPONSE_MARKUP != null) {
			template = USER_TEMPLATE_EXECUTE_RESPONSE_MARKUP;
		}
		else {
			template = TEMPLATE_EXECUTE_RESPONSE_MARKUP;
		}

		var result = jQuery.tmpl(template, properties);

		//insert status entry depending on normal status (started, accepted, paused, succeeded) or failed status
		var statusDiv = result.children('#wps-execute-response-status');
		var statusList = statusDiv.children('#wps-execute-response-list');

		statusProperties = {
			status: statusText,
			message: statusMessage
		};

		if(!processFailed){
			jQuery.tmpl(TEMPLATE_EXECUTE_RESPONSE_STATUS_NORMAL_MARKUP, statusProperties).appendTo(statusList);
		}else{
			jQuery.tmpl(TEMPLATE_EXECUTE_RESPONSE_STATUS_FAILED_MARKUP, statusProperties).appendTo(statusList);
		}

		if (extensions && !jQuery.isEmptyObject(extensions)) {
			var extensionDiv = result.children('#wps-execute-response-extension');
			if (extensions.outputs) {
				jQuery(extensions.outputs).each(function(key, value) {
						if(value.ref == true) {
							jQuery.tmpl(TEMPLATE_EXECUTE_RESPONSE_EXTENSION_MARKUP_DOWNLOAD, value).appendTo(extensionDiv);
						}else {
						    if(isImageMimetype(mimetype) && wps.isShowImages()){
						        //get the image from the url
			                    properties = {
			                            key : value.key,
			                		    mimetype : mimetype,
			                		    value : value.value
			                    };
			                    jQuery.tmpl(TEMPLATE_EXECUTE_RESPONSE_EXTENSION_MARKUP_IMAGE, properties).appendTo(extensionDiv);

						    }else{
							    jQuery.tmpl(TEMPLATE_EXECUTE_RESPONSE_EXTENSION_MARKUP_VALUE, value).appendTo(extensionDiv);
						    }
						}
					});
			}
		}

		return result;
	}

});
<commit_msg>Fix mime type allocation<commit_after>var TEMPLATE_EXECUTE_RESPONSE_MARKUP = '\

 \

 \

 \

 \

 \
					Identifier${identifier}
 \

 \
					Title${title}
 \

 \

 \

 \

 \

 \
					Created on ${creationTime}
 \

 \

 \

 \

';

var TEMPLATE_EXECUTE_RESPONSE_EXTENSION_MARKUP_DOWNLOAD = '\

 \
			${key}download
 \

';

var TEMPLATE_EXECUTE_RESPONSE_EXTENSION_MARKUP_IMAGE = '\

 \
			${key}
 \
			 \

';

var TEMPLATE_EXECUTE_RESPONSE_EXTENSION_MARKUP_VALUE = '\

 \
			${key}${value}
 \

';

var TEMPLATE_EXECUTE_RESPONSE_STATUS_NORMAL_MARKUP = '\

 \
			Status${status} \

';

var TEMPLATE_EXECUTE_RESPONSE_STATUS_FAILED_MARKUP = '\

 \
			Status${status} \

 \

 \
			Message${message} \

';

var ExecuteResponse = BaseResponse.extend({

	resolveProcessOutputs : function(processOutputs) {
		var outputs = processOutputs.getElementsByTagNameNS(WPS_100_NAMESPACE, "Output");

		var array = new Array(outputs.length);
		for (var i = 0; i < outputs.length; i++) {
			var element = outputs[i];
			var identifier = element.getElementsByTagNameNS(OWS_11_NAMESPACE, "Identifier");
			var title = element.getElementsByTagNameNS(OWS_11_NAMESPACE, "Title");
			var reference = element.getElementsByTagNameNS(WPS_100_NAMESPACE, "Reference");
			var data = element.getElementsByTagNameNS(WPS_100_NAMESPACE, "Data");
			var value;
			var mimetype;
			var valueType = null;
			if (reference && reference.length > 0) { // create link from reference
				value = reference[0].getAttribute("href");
				mimetype = reference[0].getAttribute('mimeType');
				array[i] = {
						key : jQuery(identifier).text(),
						title: jQuery(title).text(),
						value : value,
						ref: true,
						mimetype : mimetype
				};
			}
			else {
				if(data && data.length > 0) { // show inline values
					value = "", valueType = "";
					// each data child element
					jQuery(data).children().each(function(key, val) {
						var $val = jQuery(val);
						value += $val.text();
						valueType += $val.attr("dataType");
					});
				}
				else {
					value = "n/a";
				}
				var complexData = element.getElementsByTagNameNS(WPS_100_NAMESPACE, "ComplexData");
				if(complexData) {
				    mimetype = complexData[0].getAttribute('mimeType');
				}

				array[i] = {
						key : jQuery(identifier).text(),
						title: jQuery(title).text(),
						value : value,
						valueType: valueType,
						ref: false,
						mimetype : mimetype
				};
			}
		}

		var result = {outputs : array};

		return result;
	},

	createMarkup : function() {
		var process = this.xmlResponse.getElementsByTagNameNS(WPS_100_NAMESPACE, "Process");
		var status = this.xmlResponse.getElementsByTagNameNS(WPS_100_NAMESPACE, "Status");
		var reference = this.xmlResponse.getElementsByTagNameNS(WPS_100_NAMESPACE, "Reference");
		var complexData = this.xmlResponse.getElementsByTagNameNS(WPS_100_NAMESPACE, "ComplexData");

		var properties = null;
		var extensions = {};
		var statusText = null;
		var statusMessage = null;
		var processFailed = false;

		if (process && process[0] && status && status[0]) {
			var identifier = jQuery(process[0].getElementsByTagNameNS(OWS_11_NAMESPACE, "Identifier")).text();
			var title = jQuery(process[0].getElementsByTagNameNS(OWS_11_NAMESPACE, "Title")).text();

			var accepted = status[0].getElementsByTagNameNS(WPS_100_NAMESPACE, "ProcessAccepted");
			if (accepted && accepted.length > 0) {
				statusText = jQuery(accepted).text();
			}
			if (!statusText) {
				var started = status[0].getElementsByTagNameNS(WPS_100_NAMESPACE, "ProcessStarted");
				if (started && started.length > 0) {
					var percent = started[0].getAttribute("percentCompleted");
					statusText = "Process started (" + percent + " % complete)";
				}
			}
			//process paused
			if (!statusText) {
				var paused = status[0].getElementsByTagNameNS(WPS_100_NAMESPACE, "ProcessPaused");
				if (paused && paused.length > 0) {
					statusText = "Process paused";
				}
			}
			if (!statusText) {
				var succeeded = status[0].getElementsByTagNameNS(WPS_100_NAMESPACE, "ProcessSucceeded");
				if (succeeded && succeeded.length > 0) {
					statusText = "Process succeeded";
					var processOutputs = this.xmlResponse.getElementsByTagNameNS(WPS_100_NAMESPACE, "ProcessOutputs");
					if (processOutputs && processOutputs.length > 0) {
						extensions = jQuery.extend(this.resolveProcessOutputs(processOutputs[0]), extensions);
					}
				}
			}
			//process failed
			if (!statusText) {
				var failed = status[0].getElementsByTagNameNS(WPS_100_NAMESPACE, "ProcessFailed");
				if (failed && failed.length > 0) {
					statusText = "Process failed";

					exceptionText = status[0].getElementsByTagNameNS(OWS_11_NAMESPACE, "ExceptionText");
					if(exceptionText) {
						statusMessage = exceptionText.item(0).innerHTML;
						//TODO display more than one exception text
					}
					processFailed = true;
				}
			}

			var time = status[0].getAttribute("creationTime");
			if (time) {
			    var d = new Date(time);
			    time = d.toLocaleString();
			}

			var updateSwitch;
			if (this.originalRequest.updateSwitch) {
				updateSwitch = '';
			}
			else {
				updateSwitch = 'display:none';
			}

			properties = {
					identifier : identifier,
					title : title,
					creationTime : time,
					updateSwitchEnabled : updateSwitch
			};
		}

		var statusLocation = this.xmlResponse.documentElement.getAttribute("statusLocation");
		/*
		 * Make this updateable and NOT execute two times.
		 */
		if (statusLocation) {
			this.originalRequest.settings.url = statusLocation;
			//this.originalRequest = new GetRequest(this.originalRequest.settings);

			var getSettings = {
				url : this.originalRequest.settings.url,
				requestType : this.originalRequest.settings.requestType,
				type : "GET"
			};

			this.originalRequest = new GetRequest(getSettings);
		}

		var template;
		if (USER_TEMPLATE_EXECUTE_RESPONSE_MARKUP != null) {
			template = USER_TEMPLATE_EXECUTE_RESPONSE_MARKUP;
		}
		else {
			template = TEMPLATE_EXECUTE_RESPONSE_MARKUP;
		}

		var result = jQuery.tmpl(template, properties);

		//insert status entry depending on normal status (started, accepted, paused, succeeded) or failed status
		var statusDiv = result.children('#wps-execute-response-status');
		var statusList = statusDiv.children('#wps-execute-response-list');

		statusProperties = {
			status: statusText,
			message: statusMessage
		};

		if(!processFailed){
			jQuery.tmpl(TEMPLATE_EXECUTE_RESPONSE_STATUS_NORMAL_MARKUP, statusProperties).appendTo(statusList);
		}else{
			jQuery.tmpl(TEMPLATE_EXECUTE_RESPONSE_STATUS_FAILED_MARKUP, statusProperties).appendTo(statusList);
		}

		if (extensions && !jQuery.isEmptyObject(extensions)) {
			var extensionDiv = result.children('#wps-execute-response-extension');
			if (extensions.outputs) {
				jQuery(extensions.outputs).each(function(key, value) {
						if(value.ref == true) {
							jQuery.tmpl(TEMPLATE_EXECUTE_RESPONSE_EXTENSION_MARKUP_DOWNLOAD, value).appendTo(extensionDiv);
						}else {
						    var mimetype = value.mimetype;
						    if(isImageMimetype(mimetype) && wps.isShowImages()){
						        //get the image from the url
			                    properties = {
			                            key : value.key,
			                		    mimetype : mimetype,
			                		    value : value.value
			                    };
			                    jQuery.tmpl(TEMPLATE_EXECUTE_RESPONSE_EXTENSION_MARKUP_IMAGE, properties).appendTo(extensionDiv);

						    }else{
							    jQuery.tmpl(TEMPLATE_EXECUTE_RESPONSE_EXTENSION_MARKUP_VALUE, value).appendTo(extensionDiv);
						    }
						}
					});
			}
		}

		return result;
	}

});
<|endoftext|>