<commit_before>TestSuite.add(new YAHOO.tool.TestCase({

	test_AES128: function () {

		// Test vectors
		Crypto.AES._init([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]);
		Crypto.AES._encryptblock(block = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF], 0);
		Assert.areEqual("69c4e0d86a7b0430d8cdb78070b4c55a", Crypto.util.bytesToHex(block));

		// Test D(E(m)) == m
		Crypto.AES._encryptblock(block = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF], 0);
		Crypto.AES._decryptblock(block, 0);
		Assert.areEqual([0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF].toString(), block.toString());

		var key = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F";
		Assert.areEqual(data, Crypto.AES.decrypt(Crypto.AES.encrypt(data, key, { mode: Crypto.mode.CBC }), key, { mode: Crypto.mode.CBC }));
		Assert.areEqual(data, Crypto.AES.decrypt(Crypto.AES.encrypt(data, key), key));

	},

	test_AES192: function () {

		// Test vectors
		Crypto.AES._init([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17]);
		Crypto.AES._encryptblock(block = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF], 0);
		Assert.areEqual("dda97ca4864cdfe06eaf70a0ec0d7191", Crypto.util.bytesToHex(block));

		// Test D(E(m)) == m
		Crypto.AES._encryptblock(block = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF], 0);
		Crypto.AES._decryptblock(block, 0);
		Assert.areEqual([0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF].toString(), block.toString());

		var key = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17";
		Assert.areEqual(data, Crypto.AES.decrypt(Crypto.AES.encrypt(data, key, Crypto.mode.CBC), key, Crypto.mode.CBC));
		Assert.areEqual(data, Crypto.AES.decrypt(Crypto.AES.encrypt(data, key), key));

	},

	test_AES256: function () {

		// Test vectors
		Crypto.AES._init([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F]);
		Crypto.AES._encryptblock(block = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF], 0);
		Assert.areEqual("8ea2b7ca516745bfeafc49904b496089", Crypto.util.bytesToHex(block));

		// Test D(E(m)) == m
		Crypto.AES._encryptblock(block = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF], 0);
		Crypto.AES._decryptblock(block, 0);
		Assert.areEqual([0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF].toString(), block.toString());

		var key = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F";
		Assert.areEqual(data, Crypto.AES.decrypt(Crypto.AES.encrypt(data, key, Crypto.mode.CBC), key, Crypto.mode.CBC));
		Assert.areEqual(data, Crypto.AES.decrypt(Crypto.AES.encrypt(data, key), key));

		Assert.areEqual('Сообщение', Crypto.AES.decrypt(Crypto.AES.encrypt('Сообщение', 'Пароль'), 'Пароль'));

	}

}));
<commit_msg>Fixed test case encrypting/decrypting random data.<commit_after>TestSuite.add(new YAHOO.tool.TestCase({

	test_AES128: function () {

		// Test vectors
		Crypto.AES._init([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]);
		Crypto.AES._encryptblock(block = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF], 0);
		Assert.areEqual("69c4e0d86a7b0430d8cdb78070b4c55a", Crypto.util.bytesToHex(block));

		// Test D(E(m)) == m
		Crypto.AES._encryptblock(block = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF], 0);
		Crypto.AES._decryptblock(block, 0);
		Assert.areEqual([0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF].toString(), block.toString());

		var key = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F";
		Assert.areEqual(data, Crypto.AES.decrypt(Crypto.AES.encrypt(data.slice(0), key, { mode: Crypto.mode.CBC }), key, { mode: Crypto.mode.CBC, asBytes: true }).toString());
		Assert.areEqual(data, Crypto.AES.decrypt(Crypto.AES.encrypt(data.slice(0), key), key, { asBytes: true }).toString());

	},

	test_AES192: function () {

		// Test vectors
		Crypto.AES._init([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17]);
		Crypto.AES._encryptblock(block = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF], 0);
		Assert.areEqual("dda97ca4864cdfe06eaf70a0ec0d7191", Crypto.util.bytesToHex(block));

		// Test D(E(m)) == m
		Crypto.AES._encryptblock(block = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF], 0);
		Crypto.AES._decryptblock(block, 0);
		Assert.areEqual([0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF].toString(), block.toString());

		var key = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17";
		Assert.areEqual(data, Crypto.AES.decrypt(Crypto.AES.encrypt(data.slice(0), key, { mode: Crypto.mode.CBC }), key, { mode: Crypto.mode.CBC, asBytes: true }).toString());
		Assert.areEqual(data, Crypto.AES.decrypt(Crypto.AES.encrypt(data.slice(0), key), key, { asBytes: true }).toString());

	},

	test_AES256: function () {

		// Test vectors
		Crypto.AES._init([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F]);
		Crypto.AES._encryptblock(block = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF], 0);
		Assert.areEqual("8ea2b7ca516745bfeafc49904b496089", Crypto.util.bytesToHex(block));

		// Test D(E(m)) == m
		Crypto.AES._encryptblock(block = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF], 0);
		Crypto.AES._decryptblock(block, 0);
		Assert.areEqual([0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF].toString(), block.toString());

		var key = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F";
		Assert.areEqual(data, Crypto.AES.decrypt(Crypto.AES.encrypt(data.slice(0), key, { mode: Crypto.mode.CBC }), key, { mode: Crypto.mode.CBC, asBytes: true }).toString());
		Assert.areEqual(data, Crypto.AES.decrypt(Crypto.AES.encrypt(data.slice(0), key), key, { asBytes: true }).toString());

		Assert.areEqual('Сообщение', Crypto.AES.decrypt(Crypto.AES.encrypt('Сообщение', 'Пароль'), 'Пароль'));

	}

}));
<|endoftext|>


<commit_before>(function(window, document) {
    "use strict";

    var WoopraScript = function(_src, _hook, _async) {
        this.scriptObject = false;
        this.src = _src;
        this.hook = _hook;
        this.async = _async;
    };

    WoopraScript.prototype.clear = function() {
        this.scriptObject.parentNode.removeChild(this.scriptObject);
    };

    WoopraScript.prototype.load = function() {
        var script = document.createElement('script'),
            ssc,
            _hook = this.hook;

        script.src=this.src;
        script.async=this.async;

        if (_hook) {
            if (typeof script.onreadystatechange !== 'undefined') {
                script.onreadystatechange = function() {
                    if (this.readyState === 'complete'|| this.readyState === 'loaded') {
                        setTimeout(_hook, 400);
                    }
                };
            }
            else {
                script.onload = function() {
                    setTimeout(function() {
                        _hook.apply();
                    }, 400);
                };
            }
        }

        ssc = document.getElementsByTagName('script')[0];
        ssc.parentNode.insertBefore(script, ssc);
    };

    var WoopraEvent = function(name, ce, cv, file) {
        this.name = name || 'unknown';
        this.ce = ce || {};
        this.cv = cv || {};
        this.file = file || 'ce';
        this.requestString = '';
        this.attachCampaignData();
    };

    WoopraEvent.prototype.attachCampaignData = function() {
        var vars = this.getUrlVars(),
            i,
            key,
            value,
            campaignKeys = ['source', 'medium', 'content', 'campaign', 'term'];

        for (i = 0; i < campaignKeys.length; i++) {
            key = campaignKeys[i];
            value = vars['utm_' + key] || vars['woo_' + key];

            if (typeof value !== 'undefined') {
                this.ce['woo_' + key] = value;
            }
        }
    };

    WoopraEvent.prototype.getUrlVars = function() {
        var vars = {};

        window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
            vars[key] = value;
        });
        return vars;
    };

    WoopraEvent.prototype.addProperty = function(key, value) {
        this.ce[key] = value;
    };

    WoopraEvent.prototype.serialize = function(v, prefix) {
        var i,
        itemKey;

        if (this.requestString.length > 4000 ||
            typeof v === 'undefined' ||
                typeof v === 'function') {
            return;
        }

        if (typeof v === 'string' ||
            typeof v === 'number' ||
                typeof v === 'boolean') {
            this.requestString += '&' + encodeURIComponent(prefix) +
            '=' + encodeURIComponent(v);
        return;
        }

        if (v instanceof Array) {
            for (i=0; i < v.length; i++) {
                this.serialize(v[i], prefix + '[' + i + ']');
            }
            return;
        }

        for (itemKey in v) {
            if (v.hasOwnProperty(itemKey)) {
                this.serialize(v[itemKey], prefix + '.' + itemKey);
            }
        }
    };

    WoopraEvent.prototype.fire = function(tracker) {
        var t = tracker,
            key,
            rd = t.getRequestData() || {};

        t.ensure();

        this.addProperty('name', this.name);
        this.requestString = '';

        for (key in rd) {
            if (rd.hasOwnProperty(key)){
                this.serialize(rd[key], key);
            }
        }
        for (key in this.cv) {
            if (this.cv.hasOwnProperty(key)){
                this.serialize(this.cv[key], 'cv_'+key);
            }
        }

        for (key in this.ce){
            if (this.ce.hasOwnProperty(key)){
                this.serialize(this.ce[key], 'ce_'+key);
            }
        }

        new WoopraScript(t.getEndpoint(this.file)+'?ra='+t.randomstring()+this.requestString, function(){}, true ).load();

    };

    var WoopraTracker = function() {
        this.chat = false;
        this.alias = '';
        this.vs = 0;
        this.props = {};
        this.cv = {};
        this.cs = {};
        this.pint = false;
        this.ctr = 0;
        this.version = 20;
        this.last_activity = new Date();
        this.idle = 0;
        this.inited = 0;
        this._loaded  =  false;
        this.initialize.apply(this, arguments);
    };

    WoopraTracker.prototype.initialize = function() {
        var i,
            a,
            _wpt = window._wpt,
            _this = this;

        this._setOptions();

        this._processQueue();
        this._loaded = true;
        this.ready.apply(this, arguments);
    };

    WoopraTracker.prototype.ready = function() {};

    WoopraTracker.prototype._processQueue = function() {
        var i, a,
            _wpt = window._wpt;

        if (_wpt && _wpt._e) {
            for (i = 0; i < _wpt._e.length; i++) {
                a = _wpt._e[i];
                this[_wpt._e[i][0]].apply(this, Array.prototype.slice.call(a, 1));
            }
        }
        window._wpt = this;
    };

    WoopraTracker.prototype._setOptions = function() {
        var t = this,
            exp = new Date();

        t.option('domain', window.location.hostname);
        t.option('cookie_name', 'wooTracker');
        t.option('cookie_domain', window.location.hostname);
        t.option('cookie_path', '/');
        exp.setDate(exp.getDate()+365);
        t.option('cookie_expire', exp);
        t.option('ping', true);
        t.option('ping_interval', 12000);
        t.option('idle_timeout', 300000);
        t.option('download_pause', 200);
        t.option('outgoing_pause', 400);
        t.option('download_tracking', true);
        t.option('outgoing_tracking', true);
    };

    WoopraTracker.prototype.ensure = function() {
        var t = this,
            name,
            _c;

        if (t.inited === 0) {
            t.inited = 1;

            name = t.option('cookie_name');
            _c = t.readcookie(name);
            if (!_c || _c.length <= 0) {
                _c = t.randomstring();
            }
            t.createcookie(name, _c);

            setInterval(function() {
                t.next();
            }, 1000);

            if (typeof document.attachEvent !== 'undefined') {
                document.attachEvent("onmousedown", function() {
                    t.clicked.apply(t, arguments);
                });
                document.attachEvent("onmousemove", function() {
                    t.moved.apply(t, arguments);
                });
                document.attachEvent("onkeydown", function() {
                    t.typed.apply(t, arguments);
                });
            } else {
                document.addEventListener("mousedown", function() {
                    t.clicked.apply(t, arguments);
                }, false);
                document.addEventListener("mousemove", function() {
                    t.moved.apply(t, arguments);
                }, false);
                document.addEventListener("keydown", function() {
                    t.typed.apply(t, arguments);
                }, false);
            }
        }
    };

    WoopraTracker.prototype.getEndpoint = function(file) {
        return window.location.protocol + '//www.woopra.com/track/' + file + '/';
    };

    WoopraTracker.prototype.sleep = function(millis) {
        var date = new Date(),
            curDate = new Date();

        while (curDate-date < millis) {
            curDate = new Date();
        }
    };

    WoopraTracker.prototype.randomstring = function() {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
            i,
            rnum,
            s = '';

        for (i = 0; i < 12; i++) {
            rnum = Math.floor(Math.random() * chars.length);
            s += chars.substring(rnum, rnum + 1);
        }

        return s;
    };

    WoopraTracker.prototype.readcookie = function(k) {
        var c = document.cookie + '',
            ind,
            ind1;

        ind = c.indexOf(k);
        if (ind === -1 || k === '') {
            return '';
        }

        ind1 = c.indexOf(';', ind);
        if (ind1 === -1) {
            ind1 = c.length;
        }

        return window.unescape(c.substring(ind + k.length + 1, ind1));
    };

    WoopraTracker.prototype.createcookie = function(k, v) {
        var t = this,
            cookieval;

        cookieval = k + '=' + v + '; ' + 'expires=' + t.option('cookie_expire') + ';' + 'path='+t.option('cookie_path')+';domain=.'+t.option('cookie_domain');
        document.cookie = cookieval;
    };

    WoopraTracker.prototype.getRequestData = function(){
        var t = this,
            r = {};

        r.alias = t.option('domain');
        r.cookie = t.readcookie(t.option('cookie_name'));
        r.meta = t.readcookie('wooMeta') || '';
        r.screen = window.screen.width + 'x' + window.screen.height;
        r.language = (window.navigator.browserLanguage || window.navigator.language || "");
        r.referer = document.referrer;
        r.idle = parseInt(t.idle/1000, 10) + '';

        if (t.vs === 2) {
            r.vs = 'w';
            t.vs = 0;
        } else {
            if (t.idle == 0) {
                r.vs = 'r';
            } else{
                r.vs = 'i';
            }
        }

        return r;
    };

    WoopraTracker.prototype.pageview = function(action, options) {
        var e = new WoopraEvent('pv', action, this.cv, 'visit');
        e.fire(this);
    };

    WoopraTracker.prototype.track = function(name, options) {
        var e=new WoopraEvent(name, options, this.cv, 'ce');
        e.fire(this);
    };

    WoopraTracker.prototype.option = function(k, v) {
        if (typeof v === 'undefined') {
            return this.props[k];
        }

        this.props[k] = v;
        return v;
    };

    WoopraTracker.prototype.visitor = function(name, value) {
        if (typeof name === 'string' && typeof value !== 'undefined') {
            this.cv[name] = value;
        }
        else if (typeof name === 'object') {
            this.cv = name;
        }
    };

    WoopraTracker.prototype.setDomain = function(domain) {
        this.option('domain', domain);
        this.option('cookie_domain', domain);
    };

    WoopraTracker.prototype.setIdleTimeout = function(timeout) {
        this.option('idle_timeout', timeout);
    };

    //compatibility with woopra.v2.js
    WoopraTracker.prototype.trackOld=function() {
        var title=((document.getElementsByTagName('title').length==0)?'':document.getElementsByTagName('title')[0].innerHTML);
        var e=new WoopraEvent('pv', {
            url:window.location.pathname,
            title:title
        }, woopraTracker.cv, 'visit');
        e.fire(this);
    };

    // XXX
    WoopraTracker.prototype.addVisitProperty = function(name, value) {
        this.cs[name] = value;
    };

    WoopraTracker.prototype.pingServer = function() {
        var e = new WoopraEvent('x', {}, this.cv, 'ping');
        e.fire(this);
    };

    WoopraTracker.prototype.typed = function(e) {
        this.vs = 2;
    };

    WoopraTracker.prototype.clicked=function(e) {
        var t = this;

        t.moved();

        var cElem = e.srcElement || e.target;
        while (typeof cElem !== 'undefined' && cElem !== null){
            if (cElem.tagNam === 'A') {
                break;
            }
            cElem = cElem.parentNode;
        }

        if (typeof cElem !== 'undefined' && cElem !== null){
            var link=cElem;
            var _download = link.pathname.match(/(?:doc|dmg|eps|jpg|jpeg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3|mp4|m4v)($|\&)/);
            var ev=false;
            if(t.option('download_tracking')){
                if(_download && (link.href.toString().indexOf('woopra-ns.com')<0)){
                    ev=new WoopraEvent('download', {url:link.href});
                    ev.addProperty('url',link.href);
                    ev.fire(this);
                    t.sleep(t.option('download_pause'));
                }
            }
            if (t.option('outgoing_tracking')) {
                if (!_download &&
                    link.hostname !== window.location.host &&
                    link.hostname.indexOf('javascript') === -1 &&
                    link.hostname !== '') {
                    ev = new WoopraEvent('outgoing', {url:link.href});
                    ev.fire(this);
                    t.sleep(t.option('outgoing_pause'));
                }
            }
        }
    };

    WoopraTracker.prototype.moved = function() {
        var t = this;
        t.last_activity = new Date();
        t.idle = 0;
    };

    WoopraTracker.prototype.next = function(){
        var t = this;

        //clocks every 1 second
        t.ctr++;

        if(t.ctr*1000 > t.option('ping_interval')){
            t.ctr=0;
            if(t.option('ping') && t.idle < t.option('idle_timeout')){
                //t.pingServer();
            }
        }

        var now=new Date();
        if(now-t.last_activity > 10000){
            t.idle=now-t.last_activity;
        }
    };

    var woopraTracker = new WoopraTracker();

}(window, document));

<commit_msg>Style fixes to tracker<commit_after>(function(window, document) {
    "use strict";

    var WoopraScript = function(_src, _hook, _async) {
        this.scriptObject = false;
        this.src = _src;
        this.hook = _hook;
        this.async = _async;
    };

    WoopraScript.prototype.clear = function() {
        this.scriptObject.parentNode.removeChild(this.scriptObject);
    };

    WoopraScript.prototype.load = function() {
        var script = document.createElement('script'),
            ssc,
            _hook = this.hook;

        script.src = this.src;
        script.async = this.async;

        if (_hook) {
            if (typeof script.onreadystatechange !== 'undefined') {
                script.onreadystatechange = function() {
                    if (this.readyState === 'complete'|| this.readyState === 'loaded') {
                        window.setTimeout(_hook, 400);
                    }
                };
            }
            else {
                script.onload = function() {
                    window.setTimeout(function() {
                        _hook.apply();
                    }, 400);
                };
            }
        }

        ssc = document.getElementsByTagName('script')[0];
        ssc.parentNode.insertBefore(script, ssc);
    };

    var WoopraEvent = function(name, ce, cv, file) {
        this.name = name || 'unknown';
        this.ce = ce || {};
        this.cv = cv || {};
        this.file = file || 'ce';
        this.requestString = '';
        this.attachCampaignData();
    };

    WoopraEvent.prototype.attachCampaignData = function() {
        var vars = this.getUrlVars(),
            i,
            key,
            value,
            campaignKeys = ['source', 'medium', 'content', 'campaign', 'term'];

        for (i = 0; i < campaignKeys.length; i++) {
            key = campaignKeys[i];
            value = vars['utm_' + key] || vars['woo_' + key];

            if (typeof value !== 'undefined') {
                this.ce['woo_' + key] = value;
            }
        }
    };

    WoopraEvent.prototype.getUrlVars = function() {
        var vars = {};

        window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
            vars[key] = value;
        });
        return vars;
    };

    WoopraEvent.prototype.addProperty = function(key, value) {
        this.ce[key] = value;
    };

    WoopraEvent.prototype.serialize = function(v, prefix) {
        var i,
            itemKey;

        if (this.requestString.length > 4000 ||
            typeof v === 'undefined' ||
            typeof v === 'function') {
            return;
        }

        if (typeof v === 'string' ||
            typeof v === 'number' ||
            typeof v === 'boolean') {
            this.requestString += '&' + encodeURIComponent(prefix) +
                                  '=' + encodeURIComponent(v);
            return;
        }

        if (v instanceof Array) {
            for (i=0; i < v.length; i++) {
                this.serialize(v[i], prefix + '[' + i + ']');
            }
            return;
        }

        for (itemKey in v) {
            if (v.hasOwnProperty(itemKey)) {
                this.serialize(v[itemKey], prefix + '.' + itemKey);
            }
        }
    };

    WoopraEvent.prototype.fire = function(tracker) {
        var t = tracker,
            key,
            rd = t.getRequestData() || {};

        t.ensure();

        this.addProperty('name', this.name);
        this.requestString = '';

        for (key in rd) {
            if (rd.hasOwnProperty(key)){
                this.serialize(rd[key], key);
            }
        }
        for (key in this.cv) {
            if (this.cv.hasOwnProperty(key)){
                this.serialize(this.cv[key], 'cv_'+key);
            }
        }

        for (key in this.ce){
            if (this.ce.hasOwnProperty(key)){
                this.serialize(this.ce[key], 'ce_'+key);
            }
        }

        new WoopraScript(t.getEndpoint(this.file)+'?ra='+t.randomstring()+this.requestString, function(){}, true ).load();

    };

    var WoopraTracker = function() {
        this.chat = false;
        this.alias = '';
        this.vs = 0;
        this.props = {};
        this.cv = {};
        this.cs = {};
        this.pint = false;
        this.ctr = 0;
        this.version = 20;
        this.last_activity = new Date();
        this.idle = 0;
        this.inited = 0;
        this._loaded  =  false;
        this.initialize.apply(this, arguments);
    };

    WoopraTracker.prototype.initialize = function() {
        var i,
            a,
            _wpt = window._wpt,
            _this = this;

        this._setOptions();

        this._processQueue();
        this._loaded = true;
        this.ready.apply(this, arguments);
    };

    WoopraTracker.prototype.ready = function() {};

    WoopraTracker.prototype._processQueue = function() {
        var i, a,
            _wpt = window._wpt;

        if (_wpt && _wpt._e) {
            for (i = 0; i < _wpt._e.length; i++) {
                a = _wpt._e[i];
                this[_wpt._e[i][0]].apply(this, Array.prototype.slice.call(a, 1));
            }
        }
        window._wpt = this;
    };

    WoopraTracker.prototype._setOptions = function() {
        var t = this,
            exp = new Date();

        t.option('domain', window.location.hostname);
        t.option('cookie_name', 'wooTracker');
        t.option('cookie_domain', window.location.hostname);
        t.option('cookie_path', '/');
        exp.setDate(exp.getDate()+365);
        t.option('cookie_expire', exp);
        t.option('ping', true);
        t.option('ping_interval', 12000);
        t.option('idle_timeout', 300000);
        t.option('download_pause', 200);
        t.option('outgoing_pause', 400);
        t.option('download_tracking', true);
        t.option('outgoing_tracking', true);
    };

    WoopraTracker.prototype.ensure = function() {
        var t = this,
            name,
            _c;

        if (t.inited === 0) {
            t.inited = 1;

            name = t.option('cookie_name');
            _c = t.readcookie(name);
            if (!_c || _c.length <= 0) {
                _c = t.randomstring();
            }
            t.createcookie(name, _c);

            setInterval(function() {
                t.next();
            }, 1000);

            if (typeof document.attachEvent !== 'undefined') {
                document.attachEvent("onmousedown", function() {
                    t.clicked.apply(t, arguments);
                });
                document.attachEvent("onmousemove", function() {
                    t.moved.apply(t, arguments);
                });
                document.attachEvent("onkeydown", function() {
                    t.typed.apply(t, arguments);
                });
            } else {
                document.addEventListener("mousedown", function() {
                    t.clicked.apply(t, arguments);
                }, false);
                document.addEventListener("mousemove", function() {
                    t.moved.apply(t, arguments);
                }, false);
                document.addEventListener("keydown", function() {
                    t.typed.apply(t, arguments);
                }, false);
            }
        }
    };

    WoopraTracker.prototype.getEndpoint = function(file) {
        return window.location.protocol + '//www.woopra.com/track/' + file + '/';
    };

    WoopraTracker.prototype.sleep = function(millis) {
        var date = new Date(),
            curDate = new Date();

        while (curDate-date < millis) {
            curDate = new Date();
        }
    };

    WoopraTracker.prototype.randomstring = function() {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
            i,
            rnum,
            s = '';

        for (i = 0; i < 12; i++) {
            rnum = Math.floor(Math.random() * chars.length);
            s += chars.substring(rnum, rnum + 1);
        }

        return s;
    };

    WoopraTracker.prototype.readcookie = function(k) {
        var c = document.cookie + '',
            ind,
            ind1;

        ind = c.indexOf(k);
        if (ind === -1 || k === '') {
            return '';
        }

        ind1 = c.indexOf(';', ind);
        if (ind1 === -1) {
            ind1 = c.length;
        }

        return window.unescape(c.substring(ind + k.length + 1, ind1));
    };

    WoopraTracker.prototype.createcookie = function(k, v) {
        var t = this,
            cookieval;

        cookieval = k + '=' + v + '; ' + 'expires=' + t.option('cookie_expire') + ';' + 'path='+t.option('cookie_path')+';domain=.'+t.option('cookie_domain');
        document.cookie = cookieval;
    };

    WoopraTracker.prototype.getRequestData = function(){
        var t = this,
            r = {};

        r.alias = t.option('domain');
        r.cookie = t.readcookie(t.option('cookie_name'));
        r.meta = t.readcookie('wooMeta') || '';
        r.screen = window.screen.width + 'x' + window.screen.height;
        r.language = (window.navigator.browserLanguage || window.navigator.language || "");
        r.referer = document.referrer;
        r.idle = parseInt(t.idle/1000, 10) + '';

        if (t.vs === 2) {
            r.vs = 'w';
            t.vs = 0;
        } else {
            if (t.idle == 0) {
                r.vs = 'r';
            } else{
                r.vs = 'i';
            }
        }

        return r;
    };

    WoopraTracker.prototype.pageview = function(action, options) {
        var e = new WoopraEvent('pv', action, this.cv, 'visit');
        e.fire(this);
    };

    WoopraTracker.prototype.track = function(name, options) {
        var e=new WoopraEvent(name, options, this.cv, 'ce');
        e.fire(this);
    };

    WoopraTracker.prototype.option = function(k, v) {
        if (typeof v === 'undefined') {
            return this.props[k];
        }

        this.props[k] = v;
        return v;
    };

    WoopraTracker.prototype.visitor = function(name, value) {
        if (typeof name === 'string' && typeof value !== 'undefined') {
            this.cv[name] = value;
        }
        else if (typeof name === 'object') {
            this.cv = name;
        }
    };

    WoopraTracker.prototype.setDomain = function(domain) {
        this.option('domain', domain);
        this.option('cookie_domain', domain);
    };

    WoopraTracker.prototype.setIdleTimeout = function(timeout) {
        this.option('idle_timeout', timeout);
    };

    //compatibility with woopra.v2.js
    WoopraTracker.prototype.trackOld=function() {
        var title=((document.getElementsByTagName('title').length==0)?'':document.getElementsByTagName('title')[0].innerHTML);
        var e=new WoopraEvent('pv', {
            url:window.location.pathname,
            title:title
        }, woopraTracker.cv, 'visit');
        e.fire(this);
    };

    // XXX
    WoopraTracker.prototype.addVisitProperty = function(name, value) {
        this.cs[name] = value;
    };

    WoopraTracker.prototype.pingServer = function() {
        var e = new WoopraEvent('x', {}, this.cv, 'ping');
        e.fire(this);
    };

    WoopraTracker.prototype.typed = function(e) {
        this.vs = 2;
    };

    WoopraTracker.prototype.clicked=function(e) {
        var t = this;

        t.moved();

        var cElem = e.srcElement || e.target;
        while (typeof cElem !== 'undefined' && cElem !== null){
            if (cElem.tagNam === 'A') {
                break;
            }
            cElem = cElem.parentNode;
        }

        if (typeof cElem !== 'undefined' && cElem !== null){
            var link=cElem;
            var _download = link.pathname.match(/(?:doc|dmg|eps|jpg|jpeg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3|mp4|m4v)($|\&)/);
            var ev=false;
            if(t.option('download_tracking')){
                if(_download && (link.href.toString().indexOf('woopra-ns.com')<0)){
                    ev=new WoopraEvent('download', {url:link.href});
                    ev.addProperty('url',link.href);
                    ev.fire(this);
                    t.sleep(t.option('download_pause'));
                }
            }
            if (t.option('outgoing_tracking')) {
                if (!_download &&
                    link.hostname !== window.location.host &&
                    link.hostname.indexOf('javascript') === -1 &&
                    link.hostname !== '') {
                    ev = new WoopraEvent('outgoing', {url:link.href});
                    ev.fire(this);
                    t.sleep(t.option('outgoing_pause'));
                }
            }
        }
    };

    WoopraTracker.prototype.moved = function() {
        var t = this;
        t.last_activity = new Date();
        t.idle = 0;
    };

    WoopraTracker.prototype.next = function(){
        var t = this;

        //clocks every 1 second
        t.ctr++;

        if(t.ctr*1000 > t.option('ping_interval')){
            t.ctr=0;
            if(t.option('ping') && t.idle < t.option('idle_timeout')){
                //t.pingServer();
            }
        }

        var now=new Date();
        if(now-t.last_activity > 10000){
            t.idle=now-t.last_activity;
        }
    };

    var woopraTracker = new WoopraTracker();

}(window, document));

<|endoftext|>


<commit_before>'use strict';

const fastGlob = require('fast-glob');
const fs = require('fs-extra');
const klaw = require('klaw');
const path = require('path');
const {bgWhite, cyan} = require('kleur/colors');
const {log} = require('../common/logging');
const {runReleaseJob} = require('./release-job');
const {Storage} = require('@google-cloud/storage');
const {timedExecOrDie} = require('../pr-check/utils');

/**
 * @fileoverview Script that uploads a release build.
 */

const jobName = 'upload-release.js';

const SRCS_DIR = '/tmp/restored-workspace/releases';
const DEST_DIR = '/tmp/release';
const ARTIFACT_FILE_NAME = '/tmp/release.tar.gz';

const PROGRESS_WIDTH = 40;

/**
 * Merge the outputs of the flavor (both module/nomodule) into the dest dir.
 * @param {string} flavor
 */
function mergeOutputs_(flavor) {
  for (const esm of fs.readdirSync(path.join(SRCS_DIR, flavor))) {
    log('Merging', cyan(flavor), 'flavor', cyan(esm), 'build');
    fs.copySync(path.join(SRCS_DIR, flavor, esm), DEST_DIR, {
      overwrite: true,
      filter: (src) => !src.endsWith('/files.txt'),
    });
  }
}

/**
 * Merge the files.txt files for the flavor's module/nomodule outputs.
 * @param {string} flavor
 */
function mergeFilesTxt_(flavor) {
  const /** @type Map<string, Set<string>> */ filesByRtv = new Map();

  const filesTxtPaths = fastGlob.sync(
    path.join(SRCS_DIR, flavor, '*/org-cdn/rtv/*/files.txt')
  );
  for (const filesTxtPath of filesTxtPaths) {
    // filesTxtPath is guaranteed to end with '/<15-digits-rtv>/files.txt', so
    // we can extract the RTV with simple negative start/end indexes.
    const rtv = filesTxtPath.slice(-25, -10);
    if (!filesByRtv.has(rtv)) {
      filesByRtv.set(rtv, new Set());
    }

    // Add all files in this module/nomodule directory's RTV to the set.
    fs.readFileSync(filesTxtPath, {encoding: 'utf-8'})
      .trim()
      .split('\n')
      .forEach((file) => {
        filesByRtv.get(rtv)?.add(file);
      });
  }

  filesByRtv.forEach((files, rtv) => {
    log('Writing merged', cyan('files.txt'), 'for RTV', cyan(rtv));
    fs.writeFileSync(
      path.join(DEST_DIR, '/org-cdn/rtv', rtv, 'files.txt'),
      [...files].sort().join('\n')
    );
  });
}

let printProgressReady = true;

/**
 * Logs file upload progress every 1 second.
 *
 * @param {number} totalFiles
 * @param {number} uploadedFiles
 */
function logProgress_(totalFiles, uploadedFiles) {
  const percentage = Math.round((uploadedFiles / totalFiles) * PROGRESS_WIDTH);
  if (printProgressReady || uploadedFiles === totalFiles) {
    log(
      '[' +
        bgWhite(' '.repeat(percentage)) +
        '.'.repeat(PROGRESS_WIDTH - percentage) +
        ']',
      cyan(uploadedFiles),
      '/',
      cyan(totalFiles)
    );

    printProgressReady = false;
    setTimeout(() => {
      printProgressReady = true;
    }, 1000);
  }
}

/**
 * Uploads release files to Google Cloud Storage.
 * @return {Promise<void>}
 */
async function uploadFiles_() {
  const {GCLOUD_SERVICE_KEY} = process.env;
  if (!GCLOUD_SERVICE_KEY) {
    throw new Error(
      'CircleCI job is missing the GCLOUD_SERVICE_KEY env variable'
    );
  }

  const credentials = JSON.parse(GCLOUD_SERVICE_KEY);
  if (
    !credentials.client_email ||
    !credentials.private_key ||
    !credentials.project_id
  ) {
    throw new Error(
      'GCLOUD_SERVICE_KEY is not a Google Cloud JSON service key'
    );
  }

  const storage = new Storage({credentials, projectId: credentials.project_id});
  const bucket = storage.bucket('org-cdn');

  let totalFiles = 0;
  for await (const {stats} of klaw(DEST_DIR)) {
    if (stats.isFile()) {
      totalFiles++;
    }
  }

  log('Uploading', cyan(totalFiles), 'files to storage:');
  const uploadsPromises = [];
  let uploadedFiles = 0;
  for await (const {path, stats} of klaw(DEST_DIR)) {
    if (stats.isFile()) {
      const destination = path.slice(DEST_DIR.length + 1);
      uploadsPromises.push(
        bucket.upload(path, {destination, resumable: false}).then(() => {
          logProgress_(totalFiles, ++uploadedFiles);
        })
      );
    }
  }

  await Promise.all(uploadsPromises);
  log('Finished uploading all files.');
}

runReleaseJob(jobName, async () => {
  fs.ensureDirSync(DEST_DIR);

  for (const flavor of fs.readdirSync(SRCS_DIR)) {
    mergeOutputs_(flavor);
    mergeFilesTxt_(flavor);
  }

  await uploadFiles_();

  log('Archiving releases to', cyan(ARTIFACT_FILE_NAME));
  timedExecOrDie(`cd ${DEST_DIR} && tar -czf ${ARTIFACT_FILE_NAME} *`);
});
<commit_msg>Persist AMP version number between jobs in CircleCI release pipeline (#37394)<commit_after>'use strict';

const fastGlob = require('fast-glob');
const fs = require('fs-extra');
const klaw = require('klaw');
const path = require('path');
const {bgWhite, cyan} = require('kleur/colors');
const {log} = require('../common/logging');
const {runReleaseJob} = require('./release-job');
const {Storage} = require('@google-cloud/storage');
const {timedExecOrDie} = require('../pr-check/utils');

/**
 * @fileoverview Script that uploads a release build.
 */

const jobName = 'upload-release.js';

const SRCS_DIR = '/tmp/restored-workspace/releases';
const DEST_DIR = '/tmp/release';
const ARTIFACT_FILE_NAME = '/tmp/release.tar.gz';

const PROGRESS_WIDTH = 40;

/**
 * Merge the outputs of the flavor (both module/nomodule) into the dest dir.
 * @param {string} flavor
 */
function mergeOutputs_(flavor) {
  for (const esm of fs.readdirSync(path.join(SRCS_DIR, flavor))) {
    log('Merging', cyan(flavor), 'flavor', cyan(esm), 'build');
    fs.copySync(path.join(SRCS_DIR, flavor, esm), DEST_DIR, {
      overwrite: true,
      filter: (src) => !src.endsWith('/files.txt'),
    });
  }
}

/**
 * Merge the files.txt files for the flavor's module/nomodule outputs.
 * @param {string} flavor
 */
function mergeFilesTxt_(flavor) {
  const /** @type Map<string, Set<string>> */ filesByRtv = new Map();

  const filesTxtPaths = fastGlob.sync(
    path.join(SRCS_DIR, flavor, '*/org-cdn/rtv/*/files.txt')
  );
  for (const filesTxtPath of filesTxtPaths) {
    // filesTxtPath is guaranteed to end with '/<15-digits-rtv>/files.txt', so
    // we can extract the RTV with simple negative start/end indexes.
    const rtv = filesTxtPath.slice(-25, -10);
    if (!filesByRtv.has(rtv)) {
      filesByRtv.set(rtv, new Set());
    }

    // Add all files in this module/nomodule directory's RTV to the set.
    fs.readFileSync(filesTxtPath, {encoding: 'utf-8'})
      .trim()
      .split('\n')
      .forEach((file) => {
        filesByRtv.get(rtv)?.add(file);
      });
  }

  filesByRtv.forEach((files, rtv) => {
    log('Writing merged', cyan('files.txt'), 'for RTV', cyan(rtv));
    fs.writeFileSync(
      path.join(DEST_DIR, '/org-cdn/rtv', rtv, 'files.txt'),
      [...files].sort().join('\n')
    );
  });
}

let printProgressReady = true;

/**
 * Logs file upload progress every 1 second.
 *
 * @param {number} totalFiles
 * @param {number} uploadedFiles
 */
function logProgress_(totalFiles, uploadedFiles) {
  const percentage = Math.round((uploadedFiles / totalFiles) * PROGRESS_WIDTH);
  if (printProgressReady || uploadedFiles === totalFiles) {
    log(
      '[' +
        bgWhite(' '.repeat(percentage)) +
        '.'.repeat(PROGRESS_WIDTH - percentage) +
        ']',
      cyan(uploadedFiles),
      '/',
      cyan(totalFiles)
    );

    printProgressReady = false;
    setTimeout(() => {
      printProgressReady = true;
    }, 1000);
  }
}

/**
 * Uploads release files to Google Cloud Storage.
 * @return {Promise<void>}
 */
async function uploadFiles_() {
  const {GCLOUD_SERVICE_KEY} = process.env;
  if (!GCLOUD_SERVICE_KEY) {
    throw new Error(
      'CircleCI job is missing the GCLOUD_SERVICE_KEY env variable'
    );
  }

  const credentials = JSON.parse(GCLOUD_SERVICE_KEY);
  if (
    !credentials.client_email ||
    !credentials.private_key ||
    !credentials.project_id
  ) {
    throw new Error(
      'GCLOUD_SERVICE_KEY is not a Google Cloud JSON service key'
    );
  }

  const storage = new Storage({credentials, projectId: credentials.project_id});
  const bucket = storage.bucket('org-cdn');

  let totalFiles = 0;
  for await (const {stats} of klaw(DEST_DIR)) {
    if (stats.isFile()) {
      totalFiles++;
    }
  }

  log('Uploading', cyan(totalFiles), 'files to storage:');
  const uploadsPromises = [];
  let uploadedFiles = 0;
  for await (const {path, stats} of klaw(DEST_DIR)) {
    if (stats.isFile()) {
      const destination = path.slice(DEST_DIR.length + 1);
      uploadsPromises.push(
        bucket.upload(path, {destination, resumable: false}).then(() => {
          logProgress_(totalFiles, ++uploadedFiles);
        })
      );
    }
  }

  await Promise.all(uploadsPromises);
  log('Finished uploading all files.');
}

runReleaseJob(jobName, async () => {
  fs.ensureDirSync(DEST_DIR);

  for (const flavor of fs.readdirSync(SRCS_DIR)) {
    mergeOutputs_(flavor);
    mergeFilesTxt_(flavor);
  }

  await uploadFiles_();

  log('Archiving releases to', cyan(ARTIFACT_FILE_NAME));
  timedExecOrDie(`cd ${DEST_DIR} && tar -czf ${ARTIFACT_FILE_NAME} *`);

  log('Persisting AMP version number to workspace');
  const [versionsFile] = fastGlob.sync(
    path.join(DEST_DIR, 'org-cdn/rtv/01*/version.txt')
  );
  fs.copySync(versionsFile, '/tmp/workspace/AMP_VERSION');
});
<|endoftext|>


<commit_before>'use strict';//profile plugin by ~Richard
/*eslint no-restricted-modules: [0]*/
/*
**Added Dev , Flag and Vip Display in profile.js
**By Richard Adams
*/

let color = require('../config/color');
let moment = require('moment');
let geoip = require('geoip-ultralight');

let BR = '
';
let SPACE = ' ';
let profileColor = '#24678d';
let trainersprites = [1, 2, 101, 102, 169, 170, 265, 266, 168];

/**
 * Profile constructor.
 *
 * @param {Boolean} isOnline
 * @param {Object|String} user - if isOnline then Object else String
 * @param {String} image
 */
function Profile(isOnline, user, image) {
	this.isOnline = isOnline || false;
	this.user = user || null;
	this.image = image;

	this.username = Tools.escapeHTML(this.isOnline ? this.user.name : this.user);
	this.url = 'http://149.56.141.67';
}

/**
 * Create an bold html tag element.
 *
 * Example:
 * createFont('Hello World!');
 * => 'Hello World!'
 *
 * @param {String} color
 * @param {String} text
 * @return {String}
 */
function bold(text) {
	return '' + text + '';
}

/**
 * Create an font html tag element.
 *
 * Example:
 * createFont('Hello World!', 'blue');
 * => 'Hello World!'
 *
 * @param {String} color
 * @param {String} text
 * @return {String}
 */
function font(color, text) {
	return '' + text + '';
}

/**
 * Create an img tag element.
 *
 * Example:
 * createImg('phil.png');
 * => ''
 *
 * @param {String} link
 * @return {String}
 */
function img(link) {
	return '';
}

/**
 * Create a font html element wrap around by a bold html element.
 * Uses to `profileColor` as a color.
 * Adds a colon at the end of the text and a SPACE at the end of the element.
 *
 * Example:
 * label('Name');
 * => 'Name: '
 *
 * @param {String} text
 * @return {String}
 */
function label(text) {
	return bold(font(profileColor, text + ':')) + SPACE;
}

function currencyName(amount) {
	let name = " buck";
	return amount === 1 ? name : name + "s";
}

Profile.prototype.avatar = function () {
	if (this.isOnline) {
		if (typeof this.image === 'string') return img(this.url + ':' + Config.port + '/avatars/' + this.image);
		return img('http://play.pokemonshowdown.com/sprites/trainers/' + this.image + '.png');
	}
	for (let name in Config.customAvatars) {
		if (this.username === name) {
			return img(this.url + ':' + Config.port + '/avatars/' + Config.customAvatars[name]);
		}
	}
	let selectedSprite = trainersprites[Math.floor(Math.random() * trainersprites.length)];
	return img('http://play.pokemonshowdown.com/sprites/trainers/' + selectedSprite + '.png');
};

Profile.prototype.buttonAvatar = function () {
	let css = 'border:none;background:none;padding:0;float:left;';
	return '<button style="' + css + '" name="parseCommand" value="/user ' + this.username + '">' + this.avatar() + "</button>";
};

Profile.prototype.group = function () {
	if (this.isOnline && this.user.group === ' ') return label('Group') + 'Regular User';
	if (this.isOnline) return label('Group') + Config.groups[this.user.group].name;
	for (let name in Users.usergroups) {
		if (toId(this.username) === name) {
			return label('Group') + Config.groups[Users.usergroups[name].charAt(0)].name;
		}
	}
	return label('Group') + 'Regular User';
};

Profile.prototype.money = function (amount) {
	return label('Money') + amount + currencyName(amount);
};

Profile.prototype.name = function () {
	return label('Name') + bold(font(color(toId(this.username)), this.username));
};

Profile.prototype.seen = function (timeAgo) {
	if (this.isOnline) return label('Last Seen') + font('#ff9933', 'Currently Online');
	if (!timeAgo) return label('Last Seen') + 'Never';
	return label('Last Seen') + moment(timeAgo).fromNow();
};

Profile.prototype.vip = function (user) {
	if (isVip(user)) return font('#0066ff', '(Contributor)');
	return '';

};

Profile.prototype.dev = function (user) {
	if (isDev(user)) return font('#33cc33', '(Server Developer)');
	return '';

};

Profile.prototype.flag = function (user) {
	if (Users(user)) {
		let userFlag = geoip.lookupCountry(Users(user).latestIp);
		if (userFlag) {
			return '';
		}
	}
	return '';
};

Profile.prototype.show = function (callback) {
	let userid = toId(this.username);

	return this.buttonAvatar() +

		SPACE + this.name()  + SPACE + this.flag(userid) +  BR +
		SPACE + this.group() + SPACE + this.vip(userid) + this.dev(userid) + BR +
		SPACE + this.money(Db('money').get(userid, 0)) + BR +
		SPACE + this.seen(Db('seen').get(userid)) +
		'
';
};

exports.commands = {
	profile: function (target, room, user) {
		if (!this.runBroadcast()) return;
		if (target.length >= 19) return this.sendReply("Usernames are required to be less than 19 characters long.");
		let targetUser = this.targetUserOrSelf(target);
		let profile;
		if (!targetUser) {
			profile = new Profile(false, target);
		} else {
			profile = new Profile(true, targetUser, targetUser.avatar);
		}
		this.sendReplyBox(profile.show());
	},
	profilehelp: ["/profile -	Shows information regarding user's name, group, money, and when they were last seen."],
};
<commit_msg>Update profile.js<commit_after>'use strict';//profile plugin by ~Richard
/*eslint no-restricted-modules: [0]*/
/*
**Added Dev , Flag and Vip Display in profile.js
**By Richard Adams
*/

let color = require('../config/color');
let moment = require('moment');
let geoip = require('geoip-ultralight');

let BR = '
';
let SPACE = ' ';
let profileColor = '#24678d';
let trainersprites = [1, 2, 101, 102, 169, 170, 265, 266, 168];

/**
 * Profile constructor.
 *
 * @param {Boolean} isOnline
 * @param {Object|String} user - if isOnline then Object else String
 * @param {String} image
 */
function Profile(isOnline, user, image) {
	this.isOnline = isOnline || false;
	this.user = user || null;
	this.image = image;

	this.username = Tools.escapeHTML(this.isOnline ? this.user.name : this.user);
	this.url = 'http://149.56.141.67';
}

/**
 * Create an bold html tag element.
 *
 * Example:
 * createFont('Hello World!');
 * => 'Hello World!'
 *
 * @param {String} color
 * @param {String} text
 * @return {String}
 */
function bold(text) {
	return '' + text + '';
}

/**
 * Create an font html tag element.
 *
 * Example:
 * createFont('Hello World!', 'blue');
 * => 'Hello World!'
 *
 * @param {String} color
 * @param {String} text
 * @return {String}
 */
function font(color, text) {
	return '' + text + '';
}

/**
 * Create an img tag element.
 *
 * Example:
 * createImg('phil.png');
 * => ''
 *
 * @param {String} link
 * @return {String}
 */
function img(link) {
	return '';
}

/**
 * Create a font html element wrap around by a bold html element.
 * Uses to `profileColor` as a color.
 * Adds a colon at the end of the text and a SPACE at the end of the element.
 *
 * Example:
 * label('Name');
 * => 'Name: '
 *
 * @param {String} text
 * @return {String}
 */
function label(text) {
	return bold(font(profileColor, text + ':')) + SPACE;
}

function currencyName(amount) {
	let name = " buck";
	return amount === 1 ? name : name + "s";
}

Profile.prototype.avatar = function () {
	if (this.isOnline) {
		if (typeof this.image === 'string') return img(this.url + ':' + Config.port + '/avatars/' + this.image);
		return img('http://play.pokemonshowdown.com/sprites/trainers/' + this.image + '.png');
	}
	for (let name in Config.customAvatars) {
		if (this.username === name) {
			return img(this.url + ':' + Config.port + '/avatars/' + Config.customAvatars[name]);
		}
	}
	let selectedSprite = trainersprites[Math.floor(Math.random() * trainersprites.length)];
	return img('http://play.pokemonshowdown.com/sprites/trainers/' + selectedSprite + '.png');
};

Profile.prototype.buttonAvatar = function () {
	let css = 'border:none;background:none;padding:0;float:left;';
	return '<button style="' + css + '" name="parseCommand" value="/user ' + this.username + '">' + this.avatar() + "</button>";
};

Profile.prototype.group = function () {
	if (this.isOnline && this.user.group === ' ') return label('Group') + 'Regular User';
	if (this.isOnline) return label('Group') + Config.groups[this.user.group].name;
	for (let name in Users.usergroups) {
		if (toId(this.username) === name) {
			return label('Group') + Config.groups[Users.usergroups[name].charAt(0)].name;
		}
	}
	return label('Group') + 'Omega Ruby User';
};

Profile.prototype.money = function (amount) {
	return label('Money') + amount + currencyName(amount);
};

Profile.prototype.name = function () {
	return label('Name') + bold(font(color(toId(this.username)), this.username));
};

Profile.prototype.seen = function (timeAgo) {
	if (this.isOnline) return label('Last Seen') + font('#cc0000', 'Online Now!');
	if (!timeAgo) return label('Last Seen') + 'Never';
	return label('Last Seen') + moment(timeAgo).fromNow();
};

Profile.prototype.vip = function (user) {
	if (isVip(user)) return font('#0066ff', '(Contributor)');
	return '';

};

Profile.prototype.dev = function (user) {
	if (isDev(user)) return font('#33cc33', '(Server Developer)');
	return '';

};

Profile.prototype.flag = function (user) {
	if (Users(user)) {
		let userFlag = geoip.lookupCountry(Users(user).latestIp);
		if (userFlag) {
			return '';
		}
	}
	return '';
};

Profile.prototype.show = function (callback) {
	let userid = toId(this.username);

	return this.buttonAvatar() +

		SPACE + this.name()  + SPACE + this.flag(userid) +  BR +
		SPACE + this.group() + SPACE + this.vip(userid) + this.dev(userid) + BR +
		SPACE + this.money(Db('money').get(userid, 0)) + BR +
		SPACE + this.seen(Db('seen').get(userid)) +
		'
';
};

exports.commands = {
	profile: function (target, room, user) {
		if (!this.runBroadcast()) return;
		if (target.length >= 19) return this.sendReply("Usernames are required to be less than 19 characters long.");
		let targetUser = this.targetUserOrSelf(target);
		let profile;
		if (!targetUser) {
			profile = new Profile(false, target);
		} else {
			profile = new Profile(true, targetUser, targetUser.avatar);
		}
		this.sendReplyBox(profile.show());
	},
	profilehelp: ["/profile -	Shows information regarding user's name, group, money, and when they were last seen."],
};
<|endoftext|>


<commit_before>/*! check-more-types - v0.9.9
 homepage: https://github.com/kensho/check-more-types
 Copyright @ 2014 Kensho license: MIT */

!function(a){"use strict";function b(a){return"undefined"!=typeof a}function c(a,b){return a===b}function d(b){if(!a.array(b))return!1;if(!b.length)return!0;var c=b[0];return b.every(function(a){return a===c})}function e(a){return 0===a||1===a}function f(a){return"boolean"==typeof a}function g(a,b){return Boolean(a&&b&&"string"==typeof b&&"undefined"!=typeof a[b])}function h(b){return a.string(b)&&b.toLowerCase()===b}function i(b){return a.array(b)&&b.length>0}function j(b,c){var d=a.array(b)&&b.every(a.string);return d&&a.bool(c)&&c?b.every(a.lowerCase):d}function k(b,c){return a.array(b)&&b.every(function(b){return a.arrayOfStrings(b,c)})}function l(b,c){return a.verify.object(b,"missing object to check"),a.verify.object(c,"missing predicates object"),Object.keys(c).forEach(function(b){a.verify.fn(c[b],"not a predicate function for "+b)}),a.every(a.map(b,c))}function m(a,b){return l(b,a)}function n(b,c){a.verify.fn(b,"expected function that raises");try{b()}catch(d){return"undefined"==typeof c?!0:"function"==typeof c?c(d):!1}return!1}function o(a){return""===a}function p(a){var b="string"==typeof a||Array.isArray(a);return b?!a.length:a instanceof Object?!Object.keys(a).length:!1}function q(a){var b="string"==typeof a||Array.isArray(a);return b?a.length:a instanceof Object?Object.keys(a).length:!0}function r(b){return a.number(b)&&b>=0&&1>=b}function s(b){return a.string(b)&&t.test(b)}if(!a){if("undefined"==typeof require)throw new Error("Cannot find check-types library, has it been loaded?");a=require("check-types")}var t=/^#(?:[0-9a-fA-F]{3}){1,2}$/;if(!a.defend){var u=function(b,c,d){a.verify.fn(b,"expected a function"),a.verify.array(c,"expected list of predicates"),a.verify.defined(d,"missing args");var e=0,f=0,g=c.length;for(e=0;g>e;e+=1){var h=c[e];if(a.fn(h)){if(!h.call(null,d[f])){var i="Argument "+(f+1)+": "+d[f]+" does not pass predicate";throw a.unemptyString(c[e+1])&&(i+=": "+c[e+1]),new Error(i)}f+=1}}return b.apply(null,d)};a.defend=function(a){var b=Array.prototype.slice.call(arguments,1);return function(){return u(a,b,arguments)}}}a.mixin||(a.mixin=function(b,c){function d(b,c,d){a.verify.object(b,"missing object"),a.verify.unemptyString(c,"missing name"),a.verify.fn(d,"missing function"),b[c]||(b[c]=d)}function e(b){return function(){return!a.defined(arguments[0])||a.nulled(arguments[0])?!0:b.apply(null,arguments)}}function f(a){return function(){return!a.apply(null,arguments)}}function g(b,c){return function(){var d;if(b.apply(null,arguments)===!1)throw d=arguments[arguments.length-1],new Error(a.unemptyString(d)?d:c)}}a.verify.fn(b,"expected predicate function"),a.unemptyString(c)||(c=b.name),a.verify.unemptyString(c,"predicate function missing name\n"+b.toString()),d(a,c,b),d(a.maybe,c,e(b)),d(a.not,c,f(b)),d(a.verify,c,g(b,c+" failed"))});var v={defined:b,same:c,allSame:d,bit:e,bool:f,has:g,lowerCase:h,unemptyArray:i,arrayOfStrings:j,arrayOfArraysOfStrings:k,all:l,schema:m,raises:n,empty:p,emptyString:o,unempty:q,unit:r,hexRgb:s};Object.keys(v).forEach(function(b){a.mixin(v[b],b)}),"object"==typeof module&&(module.exports=a)}("object"==typeof window?window.check:global.check);<commit_msg>minified<commit_after>/*! check-more-types - v0.9.9
 homepage: https://github.com/kensho/check-more-types
 Copyright @ 2014 Kensho license: MIT */

!function(a){"use strict";function b(a){return"undefined"!=typeof a}function c(a,b){return a===b}function d(b){if(!a.array(b))return!1;if(!b.length)return!0;var c=b[0];return b.every(function(a){return a===c})}function e(a){return 0===a||1===a}function f(a){return"boolean"==typeof a}function g(a,b){return Boolean(a&&b&&"string"==typeof b&&"undefined"!=typeof a[b])}function h(b){return a.string(b)&&b.toLowerCase()===b}function i(b){return a.array(b)&&b.length>0}function j(b,c){var d=a.array(b)&&b.every(a.string);return d&&a.bool(c)&&c?b.every(a.lowerCase):d}function k(b,c){return a.array(b)&&b.every(function(b){return a.arrayOfStrings(b,c)})}function l(b,c){return a.verify.object(b,"missing object to check"),a.verify.object(c,"missing predicates object"),Object.keys(c).forEach(function(b){a.verify.fn(c[b],"not a predicate function for "+b)}),a.every(a.map(b,c))}function m(a,b){return l(b,a)}function n(b,c){a.verify.fn(b,"expected function that raises");try{b()}catch(d){return"undefined"==typeof c?!0:"function"==typeof c?c(d):!1}return!1}function o(a){return""===a}function p(a){var b="string"==typeof a||Array.isArray(a);return b?!a.length:a instanceof Object?!Object.keys(a).length:!1}function q(a){var b="string"==typeof a||Array.isArray(a);return b?a.length:a instanceof Object?Object.keys(a).length:!0}function r(b){return a.number(b)&&b>=0&&1>=b}function s(b){return a.string(b)&&t.test(b)}if(!a){if("undefined"==typeof require)throw new Error("Cannot find check-types library, has it been loaded?");a=require("check-types")}var t=/^#(?:[0-9a-fA-F]{3}){1,2}$/;if(!a.defend){var u=function(b,c,d){a.verify.fn(b,"expected a function"),a.verify.array(c,"expected list of predicates"),a.verify.defined(d,"missing args");var e=0,f=0,g=c.length;for(e=0;g>e;e+=1){var h=c[e];if(a.fn(h)){if(!h.call(null,d[f])){var i="Argument "+(f+1)+": "+d[f]+" does not pass predicate";throw a.unemptyString(c[e+1])&&(i+=": "+c[e+1]),new Error(i)}f+=1}}return b.apply(null,d)};a.defend=function(a){var b=Array.prototype.slice.call(arguments,1);return function(){return u(a,b,arguments)}}}a.mixin||(a.mixin=function(b,c){function d(b,c,d){a.verify.object(b,"missing object"),a.verify.unemptyString(c,"missing name"),a.verify.fn(d,"missing function"),b[c]||(b[c]=d)}function e(b){return function(){return!a.defined(arguments[0])||a.nulled(arguments[0])?!0:b.apply(null,arguments)}}function f(a){return function(){return!a.apply(null,arguments)}}function g(b,c){return function(){var d;if(b.apply(null,arguments)===!1)throw d=arguments[arguments.length-1],new Error(a.unemptyString(d)?d:c)}}a.verify.fn(b,"expected predicate function"),a.unemptyString(c)||(c=b.name),a.verify.unemptyString(c,"predicate function missing name\n"+b.toString()),d(a,c,b),d(a.maybe,c,e(b)),d(a.not,c,f(b)),d(a.verify,c,g(b,c+" failed"))}),a.then||(a.then=function(a,b){return function(){return a?b.apply(null,arguments):void 0}});var v={defined:b,same:c,allSame:d,bit:e,bool:f,has:g,lowerCase:h,unemptyArray:i,arrayOfStrings:j,arrayOfArraysOfStrings:k,all:l,schema:m,raises:n,empty:p,emptyString:o,unempty:q,unit:r,hexRgb:s};Object.keys(v).forEach(function(b){a.mixin(v[b],b)}),"object"==typeof module&&(module.exports=a)}("object"==typeof window?window.check:global.check);<|endoftext|>


<commit_before>/*

Wordradar.js | A Pure Javascript library to display content reading time

The MIT License (MIT)

Copyright (c) 2014 Ali Gajani (http://www.aligajani.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

window.onload=function(){
var words = document.getElementById('word_radar').innerHTML;
var count = words.split(' ').length;
var average = 275;

var reading = function (count) {
    var readingSeconds = (count * 60) / average;

    if (readingSeconds <60) {
        return (Math.round(readingSeconds)+" seconds");
    } else if (readingSeconds >60) {
        var readingMinutes = readingSeconds/60;
        return (Math.round(readingMinutes)+" minutes");
    } else {
        return false;
    }

}
document.getElementById('word_radar_time').innerHTML=reading(count);
};<commit_msg>Fifth<commit_after>/*

Wordradar.js | A Pure Javascript library to display content reading time

The MIT License (MIT)

Copyright (c) 2014 Ali Gajani (http://www.aligajani.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

window.onload=function(){
var words = document.getElementById('word_radar').innerHTML;
var count = words.split(' ').length;
var average = 150;

var reading = function (count) {
    var readingSeconds = (count * 60) / average;

    if (readingSeconds <60) {
        return (Math.round(readingSeconds)+" seconds");
    } else if (readingSeconds >60) {
        var readingMinutes = readingSeconds/60;
        return (Math.round(readingMinutes)+" minutes");
    } else {
        return false;
    }

}
document.getElementById('word_radar_time').innerHTML=reading(count);
};<|endoftext|>


<commit_before>// -*- indent-tabs-mode: nil; js2-basic-offset: 2 -*-

var SelectQuery = require('../../select-query').SelectQuery;
var IndexField = require('../../database').IndexField;

var dummyRid = '000000000000000000000000000000000000000000000000000000000000000';

function formatFacets(data) {
  var drilldownRecords = data.slice(1);

  return drilldownRecords.map(function(drilldownRecord, index) {
    return formatFacet(drilldownRecord);
  });
}

function formatFacet(drilldownRecord) {
  var columnList = drilldownRecord[1];
  var columnNames = columnList.map(function(column) {
    return column[0];
  });

  var constraintEntries = drilldownRecord.slice(2);
  var constraints = constraintEntries.map(function(record) {
    var object = {};
    columnNames.forEach(function(columnName, index) {
      object[columnName] = record[index];
    });
    return {value: object._key, count: object._nsubrecs};
  });

  return {constraints: constraints};
}

function formatSelectResults(data, selectQuery) {
  var columnList = data[0][1];
  var columnNames = columnList.map(function(column) {
    return column[0];
  });

  var records = data[0].slice(2);
  var results = records.map(function(record) {
    var result = {};
    var data = {};

    columnNames.forEach(function(columnName, index) {
      // bind internal "_key" column to the "id"
      if (columnName == '_key') {
        result.id = record[index];
        return;
      }
      // don't expose any internal column
      if (columnName[0] == '_') return;

      var fieldName = IndexField.toFieldName(columnName);
      if (Array.isArray(record[index])) {
        // vector column
        data[fieldName] = record[index];
      } else {
        // scalar column
        data[fieldName] = [record[index]];
      }
    });

    emptyReturnFields.forEach(function(fieldName) {
      data[fieldName] = [];
    });

    if (selectQuery.returnFields.length)
      result.data = data;

    return result;
  });
  return results;
}

function select(context, selectQuery, callback) {
  if (selectQuery.noResult) {
    callback(null, [], 0, []);
    return;
  }
  context.command('select', selectQuery.selectOptions, function(error, data) {
    if (error) {
      callback(error);
    } else {
      var numFoundRecords = data[0][0][0];
      callback(
        null,
        formatSelectResults(data, selectQuery),
        numFoundRecords,
        formatFacets(data)
      );
    }
  });
}

function createResultBody(options) {
  var info = {
    rid:           dummyRid,
    'time-ms':     options.elapsedTime || 0,
    'cpu-time-ms': 0 // TODO
  };
  return {
    rank: '-text_relevance', // FIXME
    'match-expr': options.matchExpression,
    hits: {
      found: options.found,
      start: options.start,
      hit:   options.hit
    },
    info: info
  };
}

function createErrorBody(options) {
  var messages = [];
  if (options.messages) {
    messages = options.messages;
  } else {
    messages.push({
      severity: 'fatal',
      code:     '',
      message:  options.message || ''
    });
  }
  return {
    error:         'info',
    rid:           options.rid,
    'time-ms':     options.elapsedTime || 0,
    'cpu-time-ms': 0, // TODO
    messages:      messages
  };
}

exports.createHandler = function(context) {
  return function(request, response) {
    var startedAt = new Date();

    var selectQuery;
    try {
      selectQuery = new SelectQuery(request, context);
    } catch(error) {
      var errorData = { rid: dummyRid };
      if (error.message == 'validation error') {
        errorData.messages = [error.data];
      } else {
        errorData.message = 'Invalid ' + error.queryType + ' value: ' + (error.message || error) + error.stack;
      }
      var body = createErrorBody(errorData);
      return response.send(body, 400);
    }

    select(context, selectQuery,
      function(error, data, numFoundRecords, facets) {
        var finishedAt = new Date();
        var elapsedTime = finishedAt.getTime() - startedAt.getTime();
        if (error) {
          var body = createErrorBody({
            rid:         dummyRid,
            message:     error.message,
            elapsedTime: elapsedTime
          });
          return response.send(body, 400); // TODO
        }
        var result = createResultBody({
          matchExpression: selectQuery.matchExpression,
          found:           numFoundRecords,
          start:           selectQuery.start,
          hit:             data,
          elapsedTime:     elapsedTime
        });
        if (selectQuery.facets && selectQuery.facets.length) {
          var facetsObject = {};
          facets.forEach(function(facet, index) {
            var facetName = selectQuery.facets[index];
            facetsObject[facetName] = facet;
          });
          result.facets = facetsObject;
        }
        response.json(result);
      }
    );
  };
};
<commit_msg>Fix missing prefix<commit_after>// -*- indent-tabs-mode: nil; js2-basic-offset: 2 -*-

var SelectQuery = require('../../select-query').SelectQuery;
var IndexField = require('../../database').IndexField;

var dummyRid = '000000000000000000000000000000000000000000000000000000000000000';

function formatFacets(data) {
  var drilldownRecords = data.slice(1);

  return drilldownRecords.map(function(drilldownRecord, index) {
    return formatFacet(drilldownRecord);
  });
}

function formatFacet(drilldownRecord) {
  var columnList = drilldownRecord[1];
  var columnNames = columnList.map(function(column) {
    return column[0];
  });

  var constraintEntries = drilldownRecord.slice(2);
  var constraints = constraintEntries.map(function(record) {
    var object = {};
    columnNames.forEach(function(columnName, index) {
      object[columnName] = record[index];
    });
    return {value: object._key, count: object._nsubrecs};
  });

  return {constraints: constraints};
}

function formatSelectResults(data, selectQuery) {
  var columnList = data[0][1];
  var columnNames = columnList.map(function(column) {
    return column[0];
  });

  var records = data[0].slice(2);
  var results = records.map(function(record) {
    var result = {};
    var data = {};

    columnNames.forEach(function(columnName, index) {
      // bind internal "_key" column to the "id"
      if (columnName == '_key') {
        result.id = record[index];
        return;
      }
      // don't expose any internal column
      if (columnName[0] == '_') return;

      var fieldName = IndexField.toFieldName(columnName);
      if (Array.isArray(record[index])) {
        // vector column
        data[fieldName] = record[index];
      } else {
        // scalar column
        data[fieldName] = [record[index]];
      }
    });

    selectQuery.emptyReturnFields.forEach(function(fieldName) {
      data[fieldName] = [];
    });

    if (selectQuery.returnFields.length)
      result.data = data;

    return result;
  });
  return results;
}

function select(context, selectQuery, callback) {
  if (selectQuery.noResult) {
    callback(null, [], 0, []);
    return;
  }
  context.command('select', selectQuery.selectOptions, function(error, data) {
    if (error) {
      callback(error);
    } else {
      var numFoundRecords = data[0][0][0];
      callback(
        null,
        formatSelectResults(data, selectQuery),
        numFoundRecords,
        formatFacets(data)
      );
    }
  });
}

function createResultBody(options) {
  var info = {
    rid:           dummyRid,
    'time-ms':     options.elapsedTime || 0,
    'cpu-time-ms': 0 // TODO
  };
  return {
    rank: '-text_relevance', // FIXME
    'match-expr': options.matchExpression,
    hits: {
      found: options.found,
      start: options.start,
      hit:   options.hit
    },
    info: info
  };
}

function createErrorBody(options) {
  var messages = [];
  if (options.messages) {
    messages = options.messages;
  } else {
    messages.push({
      severity: 'fatal',
      code:     '',
      message:  options.message || ''
    });
  }
  return {
    error:         'info',
    rid:           options.rid,
    'time-ms':     options.elapsedTime || 0,
    'cpu-time-ms': 0, // TODO
    messages:      messages
  };
}

exports.createHandler = function(context) {
  return function(request, response) {
    var startedAt = new Date();

    var selectQuery;
    try {
      selectQuery = new SelectQuery(request, context);
    } catch(error) {
      var errorData = { rid: dummyRid };
      if (error.message == 'validation error') {
        errorData.messages = [error.data];
      } else {
        errorData.message = 'Invalid ' + error.queryType + ' value: ' + (error.message || error) + error.stack;
      }
      var body = createErrorBody(errorData);
      return response.send(body, 400);
    }

    select(context, selectQuery,
      function(error, data, numFoundRecords, facets) {
        var finishedAt = new Date();
        var elapsedTime = finishedAt.getTime() - startedAt.getTime();
        if (error) {
          var body = createErrorBody({
            rid:         dummyRid,
            message:     error.message,
            elapsedTime: elapsedTime
          });
          return response.send(body, 400); // TODO
        }
        var result = createResultBody({
          matchExpression: selectQuery.matchExpression,
          found:           numFoundRecords,
          start:           selectQuery.start,
          hit:             data,
          elapsedTime:     elapsedTime
        });
        if (selectQuery.facets && selectQuery.facets.length) {
          var facetsObject = {};
          facets.forEach(function(facet, index) {
            var facetName = selectQuery.facets[index];
            facetsObject[facetName] = facet;
          });
          result.facets = facetsObject;
        }
        response.json(result);
      }
    );
  };
};
<|endoftext|>


<commit_before>'use babel';
const MDWwrap = require('./mdwrap');

const cb = fn => {
  let editor = atom.workspace.getActiveTextEditor();
  let clipboard = atom.clipboard.read();

  try {
    return this.mdwrap[fn](editor, clipboard);
  } catch (err) {
    return atom.notifications.addError(err.message, {
      dismissable: true,
      detail: clipboard,
      icon: 'zap'
    });
  }
};

module.exports = {
  config: {},
  activate: () => {
    this.mdwrap = new MDWwrap();

    this.command = atom.commands.add('atom-text-editor', {
      'atom-markdown-wrapper:paste': cb.bind(this, 'paste'),
      'atom-markdown-wrapper:image': cb.bind(this, 'image'),
      'atom-markdown-wrapper:bold': cb.bind(this, 'bold'),
      'atom-markdown-wrapper:italic': cb.bind(this, 'italic'),
      'atom-markdown-wrapper:strikethrough': cb.bind(this, 'strikethrough')
    });

    return this.command;
  },
  deactivate: () => {
    this.command.dispose();

    return this.mdwrap.destroy();
  }
};
<commit_msg>Fix paste link/image<commit_after>'use babel';
const MDWwrap = require('./mdwrap');

const cb = fn => {
  let editor = atom.workspace.getActiveTextEditor();
  let selection = editor.getSelectedText();
  let clipboard = atom.clipboard.read();

  try {
    return this.mdwrap[fn](editor, selection, clipboard);
  } catch (err) {
    return atom.notifications.addError(err.message, {
      dismissable: true,
      detail: clipboard,
      icon: 'zap'
    });
  }
};

module.exports = {
  config: {},
  activate: () => {
    this.mdwrap = new MDWwrap();

    this.command = atom.commands.add('atom-text-editor', {
      'atom-markdown-wrapper:paste': cb.bind(this, 'paste'),
      'atom-markdown-wrapper:image': cb.bind(this, 'image'),
      'atom-markdown-wrapper:bold': cb.bind(this, 'bold'),
      'atom-markdown-wrapper:italic': cb.bind(this, 'italic'),
      'atom-markdown-wrapper:strikethrough': cb.bind(this, 'strikethrough')
    });

    return this.command;
  },
  deactivate: () => {
    this.command.dispose();

    return this.mdwrap.destroy();
  }
};
<|endoftext|>


<commit_before>/* global describe, it */

'use strict';

(function () {

  var expect = require('chai').expect;

  var Required = require('../src/required');
  var Arg = require('../src/arg');

  describe('required.js', function () {

    it('should construct an Required', function () {
      var child = Arg('foo');
      var node = Required(child);

      expect(node).to.be.ok;
      expect(node).to.eql({
        _type: 'required',
        children: [child]
      });

      expect(node.children[0]).to.equal(child);
    });

  });

})();
<commit_msg>Test required errors<commit_after>/* global describe, it */

'use strict';

(function () {

  var expect = require('chai').expect;

  var Required = require('../src/required');
  var Arg = require('../src/arg');

  describe('required.js', function () {

    it('should construct an Required', function () {
      var child = Arg('foo');
      var node = Required(child);

      expect(node).to.be.ok;
      expect(node).to.eql({
        _type: 'required',
        children: [child]
      });

      expect(node.children[0]).to.equal(child);
    });

    it('should throw an error if no children are supplied', function () {
      var anError = /child/i;

      expect(Required).to.throw(anError);
    });

    it('should throw an error if more than one children are supplied', function () {
      var anError = /child/i;
      var child1 = Arg('foo');
      var child2 = Arg('bar');
      var boundRequired = Required.bind(null, child1, child2);

      expect(boundRequired).to.throw(anError);
    });

  });

})();
<|endoftext|>


<commit_before>if (document.URL.split(/\//g).length - 1 == 4) {
  var githubRepo = document.URL.split('/')[4];
  var githubUser = document.URL.split('/')[3];

  generateGeoPatternBackground(githubRepo);
  createAndInsertCompareLink();
  moveCreateNewFile();
  moveBranchListing();

  [
    '.octicon-repo:before',
    '.author > a > span',
    '.path-divider',
    '.js-repo-home-link',
    '.fork-flag > .text > a',
    '.fork-flag'
  ].forEach(whiteOut);

  // White text doesn't look good with the gold background
  if ($('.repo-label > span').text() == 'public')
    $('.repo-label > span').css('color', 'white');

  [
    '.subscription',
    '.overall-summary',
    $('div.tooltipped-s').attr('aria-label', 'Show language statistics'),
    '.breadcrumb > .repo-root',
    '.breadcrumb > .separator',
    '.sunken-menu-separator',
    '.in-mid-page'
  ].forEach(remove)
}

function generateGeoPatternBackground(githubRepo) {
  var pattern = GeoPattern.generate(githubRepo);

  $('.pagehead').css(
    {
    'border-bottom': 'none',
    'padding': '2.5% 0',
    'background-image': pattern.toDataUrl()
    }
  );
}

function createAndInsertCompareLink() {
  var $compareLink = $('.file-navigation > a')
                      .removeClass()
                      .addClass('tooltipped tooltipped-n')
                      .css({
                        'color':'white',
                        'font-size': '15px',
                        'padding-right': '20px'
                        })
                      .append('compare');
  $('.file-navigation > a').remove();

  $listEl = $('
').append($compareLink);
  $('.pagehead-actions').prepend($listEl);
}

function moveCreateNewFile() {
  $createNewFile = $('.js-new-blob-form').css('color', 'white');
  $divider = $("/");

  $divider.insertAfter('.entry-title > strong');
  $createNewFile.insertAfter('.new-github');
  $('.js-new-blob-submit').css({'color': 'white', 'padding-left': '5px'});
}

function moveBranchListing() {
  $buttonContainer = $('.select-menu').last();
  $buttonContainer.children().find('i').remove();

  // Clear out uneeded button styles
  $buttonContainer
                .children().first()
                .css({
                  'color': 'white',
                  'background': 'none',
                  'text-shadow': 'none',
                  'border': 'none',
                  'font-weight': 'normal',
                  'font-size': '15px'
                });

  $listEl = $('
').append($buttonContainer);
  $('.pagehead-actions').prepend($listEl);
}

function remove(element, index, array) { $(element).remove(); };
function whiteOut(element, index, array) { $(element).css('color', 'white') };
<commit_msg>fixed repo icon for now<commit_after>if (document.URL.split(/\//g).length - 1 == 4) {
  var githubRepo = document.URL.split('/')[4];
  var githubUser = document.URL.split('/')[3];

  generateGeoPatternBackground(githubRepo);
  createAndInsertCompareLink();
  moveCreateNewFile();
  moveBranchListing();

  [
    '.octicon-repo:before',
    '.author > a > span',
    '.path-divider',
    '.js-repo-home-link',
    '.fork-flag > .text > a',
    '.fork-flag'
  ].forEach(whiteOut);

  if ($('.repo-label > span').text() == 'public') {
    $('.repo-label > span').css('color', 'white');

    // Definitely not doing this right
    $('head').prepend("");
  }

  [
    '.subscription',
    '.overall-summary',
    $('div.tooltipped-s').attr('aria-label', 'Show language statistics'),
    '.breadcrumb > .repo-root',
    '.breadcrumb > .separator',
    '.sunken-menu-separator',
    '.in-mid-page'
  ].forEach(remove)
}

function generateGeoPatternBackground(githubRepo) {
  var pattern = GeoPattern.generate(githubRepo);

  $('.pagehead').css(
    {
    'border-bottom': 'none',
    'padding': '2.5% 0',
    'background-image': pattern.toDataUrl()
    }
  );
}

function createAndInsertCompareLink() {
  var $compareLink = $('.file-navigation > a')
                      .removeClass()
                      .addClass('tooltipped tooltipped-n')
                      .css({
                        'color':'white',
                        'font-size': '15px',
                        'padding-right': '20px'
                        })
                      .append('compare');
  $('.file-navigation > a').remove();

  $listEl = $('
').append($compareLink);
  $('.pagehead-actions').prepend($listEl);
}

function moveCreateNewFile() {
  $createNewFile = $('.js-new-blob-form').css('color', 'white');
  $divider = $("/");

  $divider.insertAfter('.entry-title > strong');
  $createNewFile.insertAfter('.new-github');
  $('.js-new-blob-submit').css({'color': 'white', 'padding-left': '5px'});
}

function moveBranchListing() {
  $buttonContainer = $('.select-menu').last();
  $buttonContainer.children().find('i').remove();

  // Clear out uneeded button styles
  $buttonContainer
                .children().first()
                .css({
                  'color': 'white',
                  'background': 'none',
                  'text-shadow': 'none',
                  'border': 'none',
                  'font-weight': 'normal',
                  'font-size': '15px'
                });

  $listEl = $('
').append($buttonContainer);
  $('.pagehead-actions').prepend($listEl);
}

function remove(element, index, array) { $(element).remove(); };
function whiteOut(element, index, array) { $(element).css('color', 'white') };
<|endoftext|>


<commit_before>var creep_salvager = {

    /** @param {Creep} creep **/
    run: function(creep) {
        if (creep.ticksToLive <= creep.memory.deathWarn && creep.memory.priority != 'labWorkerNearDeath') {
            creep.memory.priority = 'labWorkerNearDeath';
        }

        var newTarget = false;
        var foundObject = findTarget(creep, 0);
        if (!foundObject) {
            //Idle
            if (!creep.pos.isNearTo(creep.room.controller)) {
                creep.travelTo(creep.room.controller);
            }
            return;
        } else if (foundObject) {
            if (creep.memory.targetType == 0) {
                if (Object.keys(foundObject.store).length > 1) {
                    if (creep.withdraw(foundObject, Object.keys(foundObject.store)[1]) == ERR_NOT_IN_RANGE) {
                        creep.travelTo(foundObject);
                    }
                } else {
                    var withdrawResult = creep.withdraw(foundObject, Object.keys(foundObject.store)[0])
                    if (withdrawResult == ERR_NOT_IN_RANGE) {
                        creep.travelTo(foundObject);
                    } else if (withdrawResult == OK) {
                        creep.memory.lastTargetId = creep.memory.targetId;
                        creep.memory.targetId = undefined;
                        creep.memory.targetType = undefined;
                        foundObject = findTarget(creep, _.sum(foundObject.store));
                        newTarget = true;
                    }
                }
            } else if (creep.memory.targetType == 1) {
                var pickupResult = creep.pickup(foundObject);
                if (pickupResult == ERR_NOT_IN_RANGE) {
                    creep.travelTo(foundObject);
                } else if (pickupResult == OK) {
                    creep.memory.lastTargetId = creep.memory.targetId;
                    creep.memory.targetId = undefined;
                    creep.memory.targetType = undefined;
                    foundObject = findTarget(creep, foundObject.amount);
                    newTarget = true;
                }
            } else if (creep.memory.targetType == 2) {
                if (Object.keys(creep.carry).length > 1) {
                    if (creep.transfer(foundObject, Object.keys(creep.carry)[1]) == ERR_NOT_IN_RANGE) {
                        creep.travelTo(foundObject);
                    }
                } else {
                    var transferResult = creep.transfer(foundObject, Object.keys(creep.carry)[0]);
                    if (transferResult == ERR_NOT_IN_RANGE) {
                        creep.travelTo(foundObject);
                    } else if (transferResult == OK) {
                        creep.memory.targetId = undefined;
                        creep.memory.targetType = undefined;
                        foundObject = findTarget(creep, -_.sum(creep.carry));
                        newTarget = true;
                    }
                }
            }
        }
        //travel to new target...or don't if it doesn't exist
        if (newTarget) {
            if (!foundObject) {
                //Idle
                creep.travelTo(creep.room.controller);
                return;
            } else {
                creep.travelTo(foundObject);
            }
        }
    }
};

function findTarget(creep, amountWithdrawn) {
    var returnObject = undefined;
    if (creep.memory.targetId) {
        returnObject = Game.getObjectById(creep.memory.targetId);
        if (returnObject) {
            if (creep.memory.targetType == 0) {
                if (Object.keys(returnObject.store).length) {
                    return returnObject;
                } else {
                    creep.memory.targetId = undefined;
                    creep.memory.targetType = undefined;
                    returnObject = undefined;
                }
            } else if (creep.memory.targetType == 2 && _.sum(creep.carry) == 0) {
                creep.memory.targetId = undefined;
                creep.memory.targetType = undefined;
                returnObject = undefined;
            } else {
                //Dropped resource wouldn't exist if it expired
                return returnObject;
            }
        }
    }

    if ((_.sum(creep.carry) + amountWithdrawn) < creep.carryCapacity) {
        if (creep.memory.lastTargetId) {
            returnObject = creep.pos.findClosestByRange(FIND_TOMBSTONES, {
                filter: (thisTombstone) => (_.sum(thisTombstone.store) > 0 && thisTombstone.id != creep.memory.lastTargetId)
            });
        } else {
            returnObject = creep.pos.findClosestByRange(FIND_TOMBSTONES, {
                filter: (thisTombstone) => (_.sum(thisTombstone.store) > 0)
            });
        }
        if (returnObject) {
            creep.memory.targetId = returnObject.id;
            creep.memory.targetType = 0;
            creep.memory.lastTargetId = undefined;
            return returnObject;
        } else {
            if (creep.memory.lastTargetId) {
                returnObject = creep.pos.findClosestByRange(FIND_DROPPED_RESOURCES, {
                    filter: (thisResource) => (thisResource.id != creep.memory.lastTargetId)
                });
            } else {
                returnObject = creep.pos.findClosestByRange(FIND_DROPPED_RESOURCES);
            }
            if (returnObject) {
                creep.memory.targetId = returnObject.id;
                creep.memory.targetType = 1;
                creep.memory.lastTargetId = undefined;
                return returnObject;
            }
        }
    }

    creep.memory.lastTargetId = undefined;

    if ((!returnObject && (_.sum(creep.carry) + amountWithdrawn) > 0 || (_.sum(creep.carry) + amountWithdrawn) >= creep.carryCapacity) && creep.room.storage) {
        creep.memory.targetId = creep.room.storage.id;
        creep.memory.targetType = 2;
        return creep.room.storage;
    }

    return undefined;
}

module.exports = creep_salvager;<commit_msg>Keep it all in house<commit_after>var creep_salvager = {

    /** @param {Creep} creep **/
    run: function(creep) {
        if (creep.ticksToLive <= creep.memory.deathWarn && creep.memory.priority != 'labWorkerNearDeath') {
            creep.memory.priority = 'labWorkerNearDeath';
        }

        var newTarget = false;
        var foundObject = findTarget(creep, 0);
        if (!foundObject) {
            //Idle
            if (!creep.pos.isNearTo(creep.room.controller)) {
                creep.travelTo(creep.room.controller, {
                    maxRooms: 1,
                    ignoreRoads: true
                });
            }
            return;
        } else if (foundObject) {
            if (creep.memory.targetType == 0) {
                if (Object.keys(foundObject.store).length > 1) {
                    if (creep.withdraw(foundObject, Object.keys(foundObject.store)[1]) == ERR_NOT_IN_RANGE) {
                        creep.travelTo(foundObject, {
                            maxRooms: 1
                        });
                    }
                } else {
                    var withdrawResult = creep.withdraw(foundObject, Object.keys(foundObject.store)[0])
                    if (withdrawResult == ERR_NOT_IN_RANGE) {
                        creep.travelTo(foundObject, {
                            maxRooms: 1
                        });
                    } else if (withdrawResult == OK) {
                        creep.memory.lastTargetId = creep.memory.targetId;
                        creep.memory.targetId = undefined;
                        creep.memory.targetType = undefined;
                        foundObject = findTarget(creep, _.sum(foundObject.store));
                        newTarget = true;
                    }
                }
            } else if (creep.memory.targetType == 1) {
                var pickupResult = creep.pickup(foundObject);
                if (pickupResult == ERR_NOT_IN_RANGE) {
                    creep.travelTo(foundObject, {
                        maxRooms: 1
                    });
                } else if (pickupResult == OK) {
                    creep.memory.lastTargetId = creep.memory.targetId;
                    creep.memory.targetId = undefined;
                    creep.memory.targetType = undefined;
                    foundObject = findTarget(creep, foundObject.amount);
                    newTarget = true;
                }
            } else if (creep.memory.targetType == 2) {
                if (Object.keys(creep.carry).length > 1) {
                    if (creep.transfer(foundObject, Object.keys(creep.carry)[1]) == ERR_NOT_IN_RANGE) {
                        creep.travelTo(foundObject, {
                            maxRooms: 1
                        });
                    }
                } else {
                    var transferResult = creep.transfer(foundObject, Object.keys(creep.carry)[0]);
                    if (transferResult == ERR_NOT_IN_RANGE) {
                        creep.travelTo(foundObject, {
                            maxRooms: 1
                        });
                    } else if (transferResult == OK) {
                        creep.memory.targetId = undefined;
                        creep.memory.targetType = undefined;
                        foundObject = findTarget(creep, -_.sum(creep.carry));
                        newTarget = true;
                    }
                }
            }
        }
        //travel to new target...or don't if it doesn't exist
        if (newTarget) {
            if (!foundObject) {
                //Idle
                creep.travelTo(creep.room.controller, {
                    maxRooms: 1,
                    ignoreRoads: true
                });
                return;
            } else {
                creep.travelTo(foundObject, {
                    maxRooms: 1
                });
            }
        }
    }
};

function findTarget(creep, amountWithdrawn) {
    var returnObject = undefined;
    if (creep.memory.targetId) {
        returnObject = Game.getObjectById(creep.memory.targetId);
        if (returnObject) {
            if (creep.memory.targetType == 0) {
                if (Object.keys(returnObject.store).length) {
                    return returnObject;
                } else {
                    creep.memory.targetId = undefined;
                    creep.memory.targetType = undefined;
                    returnObject = undefined;
                }
            } else if (creep.memory.targetType == 2 && _.sum(creep.carry) == 0) {
                creep.memory.targetId = undefined;
                creep.memory.targetType = undefined;
                returnObject = undefined;
            } else {
                //Dropped resource wouldn't exist if it expired
                return returnObject;
            }
        }
    }

    if ((_.sum(creep.carry) + amountWithdrawn) < creep.carryCapacity) {
        if (creep.memory.lastTargetId) {
            returnObject = creep.pos.findClosestByRange(FIND_TOMBSTONES, {
                filter: (thisTombstone) => (_.sum(thisTombstone.store) > 0 && thisTombstone.id != creep.memory.lastTargetId)
            });
        } else {
            returnObject = creep.pos.findClosestByRange(FIND_TOMBSTONES, {
                filter: (thisTombstone) => (_.sum(thisTombstone.store) > 0)
            });
        }
        if (returnObject) {
            creep.memory.targetId = returnObject.id;
            creep.memory.targetType = 0;
            creep.memory.lastTargetId = undefined;
            return returnObject;
        } else {
            if (creep.memory.lastTargetId) {
                returnObject = creep.pos.findClosestByRange(FIND_DROPPED_RESOURCES, {
                    filter: (thisResource) => (thisResource.id != creep.memory.lastTargetId)
                });
            } else {
                returnObject = creep.pos.findClosestByRange(FIND_DROPPED_RESOURCES);
            }
            if (returnObject) {
                creep.memory.targetId = returnObject.id;
                creep.memory.targetType = 1;
                creep.memory.lastTargetId = undefined;
                return returnObject;
            }
        }
    }

    creep.memory.lastTargetId = undefined;

    if ((!returnObject && (_.sum(creep.carry) + amountWithdrawn) > 0 || (_.sum(creep.carry) + amountWithdrawn) >= creep.carryCapacity) && creep.room.storage) {
        creep.memory.targetId = creep.room.storage.id;
        creep.memory.targetType = 2;
        return creep.room.storage;
    }

    return undefined;
}

module.exports = creep_salvager;<|endoftext|>


<commit_before>$(document).ready(function() {
	$('.numpad').find('.btn').on('click', function() {
		var num = $(this).text();
		var inputVoto = $('#numero-voto');
		var numVoto = inputVoto.val();

		if (numVoto.length < 2) {
			inputVoto.val(numVoto + num);
		}
	});
});<commit_msg>criado objeto Eleicao e Numpad<commit_after>var Numpad = function () {
	this.MAX_LENGTH = 5;
};

Numpad.prototype.putNumber = function () {
		const MAX_LENGTH = 5;
		var num = $(this).text();
		var inputVoto = $('#numero-voto');
		var numVoto = inputVoto.val();

		if (numVoto.length < MAX_LENGTH) {
			inputVoto.val(numVoto + num);
		}
};

var Eleicao = function () {
	this.candicato = null;
};

Eleicao.prototype.getCandidato = function () {

};

Eleicao.prototype.prepararCard = function (candidato) {

	var imgCandidato = 'data:image/gif;base64,R0lGODlhAQABAIABAAJ12AAAACwAAAAAAQABAAACAkQBADs=';
	var descCandidato = 'Miniatura genérica';

	if (candidato.image != null) {
		descCandidato = 'Foto do ' + candidato.nome;
		imgCandidato = candidato.image;
	}

	var candidatoCard = '
' +
							'' +
							'
' + candidato.nome +'
' +
						'
';

	return $(candidatoCard);
};

Eleicao.prototype.verificarNumeroDoCandidato = function (evt) {
	var input = $(evt.target);
	var candidato = this.getCandidato( input.val() );

	if (candidato != null) {
		var card = Eleicoes.prepararCard( candidato );
	}
};

$(document).ready(function() {
	 $('[data-toggle="tooltip"]').tooltip();

	$('.numpad').find('.btn').on('click', Numpad.putNumber);

	$('#numero-voto').on('keyup', Eleicao.verificarNumeroDoCandidato);
});<|endoftext|>