<commit_before>import Vue from 'vue'
import VueUIkit from '../src/index'
import { escape } from 'he'
import slug from 'slug'
import marked from 'marked'

Vue.use(VueUIkit)

const guid = () => {
    return Math.random().toString(36).substring(2, 15)
}
// Inspired by https://github.com/uikit/uikit-site
export function parse (markdown, cb) {
    const renderer = new marked.Renderer({ langPrefix: 'lang-' })
    const base = new marked.Renderer({ langPrefix: 'lang-' })
    let vm

    /* eslint-disable no-useless-escape */
    const example = code => {
        const id = guid()
        let template = code.match(/<template>(.|\n)*<\/template>/g)
        let data = code.match(/return\s+([^\}]+.)/)
        if (data) data = JSON.parse(data[1])

        vm = new Vue({
            template: `<div>${template}</div>`,
            data
        }).$mount()

        return `

Preview

Markup

</span

${escape(code)}

`
    }

    renderer.strong = text => text === 'Note' ? `<span class="uk-label">${text}</span>` : `<strong>${text}</strong>`
    renderer.list = text => `<ul class="uk-list uk-list-bulconst">${text}</ul>`
    renderer.link = (href, title, text) => href.match(/\.md/) ? base.link(href.replace(/.md(.*)/, '$1'), title, text) : base.link(href, title, text)
    renderer.code = (code, lang, escaped) => lang === 'example' ? example(code) : '
' + base.code(code, lang, escaped) + '
'
    renderer.hr = () => `<hr class="uk-margin-large">`
    renderer.table = (header, body) => `<div class="uk-overflow-auto"><table class="uk-table uk-table-divider"><thead>${header}</thead><tbody>${body}</tbody></table></div>`
    renderer.heading = (text, level) => `<h${level} id="${slug(text)}" class="tm-heading-fragment"><a href="#${slug(text)}">${text}</a></h${level}>`

    return [marked(markdown, { renderer }), vm]
}
<commit_msg>Change: Prepared json like string<commit_after>import Vue from 'vue'
import VueUIkit from '../src/index'
import { escape } from 'he'
import slug from 'slug'
import marked from 'marked'

Vue.use(VueUIkit)

const guid = () => {
    return Math.random().toString(36).substring(2, 15)
}
// Inspired by https://github.com/uikit/uikit-site
export function parse (markdown, cb) {
    const renderer = new marked.Renderer({ langPrefix: 'lang-' })
    const base = new marked.Renderer({ langPrefix: 'lang-' })
    let vm

    /* eslint-disable no-useless-escape */
    const example = code => {
        const id = guid()
        let template = code.match(/<template>(.|\n)*<\/template>/g)
        let data = code.match(/return\s+([^\}]+.)/)[1].replace(/(\w+[0-9]?)(?=:)/, '"$1"')
        if (data) data = JSON.parse(data)

        vm = new Vue({
            template: `<div>${template}</div>`,
            data
        }).$mount()

        return `

Preview

Markup

</span

${escape(code)}

`
    }

    renderer.strong = text => text === 'Note' ? `<span class="uk-label">${text}</span>` : `<strong>${text}</strong>`
    renderer.list = text => `<ul class="uk-list uk-list-bulconst">${text}</ul>`
    renderer.link = (href, title, text) => href.match(/\.md/) ? base.link(href.replace(/.md(.*)/, '$1'), title, text) : base.link(href, title, text)
    renderer.code = (code, lang, escaped) => lang === 'example' ? example(code) : '
' + base.code(code, lang, escaped) + '
'
    renderer.hr = () => `<hr class="uk-margin-large">`
    renderer.table = (header, body) => `<div class="uk-overflow-auto"><table class="uk-table uk-table-divider"><thead>${header}</thead><tbody>${body}</tbody></table></div>`
    renderer.heading = (text, level) => `<h${level} id="${slug(text)}" class="tm-heading-fragment"><a href="#${slug(text)}">${text}</a></h${level}>`

    return [marked(markdown, { renderer }), vm]
}
<|endoftext|>


<commit_before>'use strict';
/*----------------------------------------------------------------------------------------------*/
/* Obtained and modified from http://js.5sh.net/starttls.js on 8/18/2011.                       */
/*----------------------------------------------------------------------------------------------*/

var tls       = require('tls');
var constants = require('constants');
var crypto    = require('crypto');
var util      = require('util');
var net       = require('net');
var stream    = require('stream');
var log       = require('./logger');
var config    = require('./config');

// provides a common socket for attaching
// and detaching from either main socket, or crypto socket
function pluggableStream(socket) {
    stream.Stream.call(this);
    this.readable = this.writable = true;
    this._timeout = 0;
    this._keepalive = false;
    this._writeState = true;
    this._pending = [];
    this._pendingCallbacks = [];
    if (socket) this.attach(socket);
}

util.inherits(pluggableStream, stream.Stream);

pluggableStream.prototype.pause = function () {
    if (this.targetsocket.pause) {
        this.targetsocket.pause();
        this.readable = false;
    }
};

pluggableStream.prototype.resume = function () {
    if (this.targetsocket.resume) {
        this.readable = true;
        this.targetsocket.resume();
    }
};

pluggableStream.prototype.attach = function (socket) {
    var self = this;
    self.targetsocket = socket;
    self.targetsocket.on('data', function (data) {
        self.emit('data', data);
    });
    self.targetsocket.on('connect', function (a, b) {
        self.emit('connect', a, b);
    });
    self.targetsocket.on('secureConnection', function (a, b) {
        self.emit('secureConnection', a, b);
        self.emit('secure', a, b);
    });
    self.targetsocket.on('secure', function (a, b) {
        self.emit('secureConnection', a, b);
        self.emit('secure', a, b);
    });
    self.targetsocket.on('end', function () {
        self.writable = self.targetsocket.writable;
        self.emit('end');
    });
    self.targetsocket.on('close', function (had_error) {
        self.writable = self.targetsocket.writable;
        self.emit('close', had_error);
    });
    self.targetsocket.on('drain', function () {
        self.emit('drain');
    });
    self.targetsocket.on('error', function (exception) {
        self.writable = self.targetsocket.writable;
        self.emit('error', exception);
    });
    self.targetsocket.on('timeout', function () {
        self.emit('timeout');
    });
    if (self.targetsocket.remotePort) {
        self.remotePort = self.targetsocket.remotePort;
    }
    if (self.targetsocket.remoteAddress) {
        self.remoteAddress = self.targetsocket.remoteAddress;
    }
};

pluggableStream.prototype.clean = function (data) {
    if (this.targetsocket && this.targetsocket.removeAllListeners) {
        this.targetsocket.removeAllListeners('data');
        this.targetsocket.removeAllListeners('secureConnection');
        this.targetsocket.removeAllListeners('secure');
        this.targetsocket.removeAllListeners('end');
        this.targetsocket.removeAllListeners('close');
        this.targetsocket.removeAllListeners('error');
        this.targetsocket.removeAllListeners('drain');
    }
    this.targetsocket = {};
    this.targetsocket.write = function () {};
};

pluggableStream.prototype.write = function (data, encoding, callback) {
    if (this.targetsocket.write) {
        return this.targetsocket.write(data, encoding, callback);
    }
    return false;
};

pluggableStream.prototype.end = function (data, encoding) {
    if (this.targetsocket.end) {
        return this.targetsocket.end(data, encoding);
    }
};

pluggableStream.prototype.destroySoon = function () {
    if (this.targetsocket.destroySoon) {
        return this.targetsocket.destroySoon();
    }
};

pluggableStream.prototype.destroy = function () {
    if (this.targetsocket.destroy) {
        return this.targetsocket.destroy();
    }
};

pluggableStream.prototype.setKeepAlive = function (bool) {
    this._keepalive = bool;
    return this.targetsocket.setKeepAlive(bool);
};

pluggableStream.prototype.setNoDelay = function (/* true||false */) {
};

pluggableStream.prototype.setTimeout = function (timeout) {
    this._timeout = timeout;
    return this.targetsocket.setTimeout(timeout);
};

function pipe(pair, socket) {
    pair.encrypted.pipe(socket);
    socket.pipe(pair.encrypted);

    pair.fd = socket.fd;
    var cleartext = pair.cleartext;
    cleartext.socket = socket;
    cleartext.encrypted = pair.encrypted;
    cleartext.authorized = false;

    function onerror(e) {
        if (cleartext._controlReleased) {
            cleartext.emit('error', e);
        }
    }

    function onclose() {
        socket.removeListener('error', onerror);
        socket.removeListener('close', onclose);
    }

    socket.on('error', onerror);
    socket.on('close', onclose);

    return cleartext;
}

function createServer(cb) {
    var serv = net.createServer(function (cryptoSocket) {

        var socket = new pluggableStream(cryptoSocket);

        socket.upgrade = function (options, cb2) {
            log.logdebug('Upgrading to TLS');

            socket.clean();
            cryptoSocket.removeAllListeners('data');

            // Set SSL_OP_ALL for maximum compatibility with broken clients
            // See http://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
            if (!options) options = {};
            // TODO: bug in Node means we can't do this until it's fixed
            // options.secureOptions = constants.SSL_OP_ALL;

            // Setting secureProtocol to 'SSLv23_method' and secureOptions to
            // constants.SSL_OP_NO_SSLv3 are used to disable SSLv2 and SSLv3
            // protcol support.

            options.secureProtocol = options.secureProtocol || 'SSLv23_method';
            options.secureOptions  = options.secureOptions  ||
                constants.SSL_OP_NO_SSLv3;

            var requestCert = true;
            var rejectUnauthorized = false;
            if (options) {
                if (options.requestCert !== undefined) {
                    requestCert = options.requestCert;
                }
                if (options.rejectUnauthorized !== undefined) {
                    rejectUnauthorized = options.rejectUnauthorized;
                }
            }
            var sslcontext = (tls.createSecureContext || crypto.createCredentials)(options);

            // tls.createSecurePair(credentials, isServer, requestCert, rejectUnauthorized)
            var pair = tls.createSecurePair(sslcontext, true, requestCert, rejectUnauthorized);

            var cleartext = pipe(pair, cryptoSocket);

            pair.on('error', function(exception) {
                socket.emit('error', exception);
            });

            pair.on('secure', function() {
                var verifyError = (pair.ssl || pair._ssl).verifyError();

                log.logdebug('TLS secured.');
                if (verifyError) {
                    cleartext.authorized = false;
                    cleartext.authorizationError = verifyError;
                }
                else {
                    cleartext.authorized = true;
                }
                var cert = pair.cleartext.getPeerCertificate();
                if (pair.cleartext.getCipher) {
                    var cipher = pair.cleartext.getCipher();
                }
                socket.emit('secure');
                if (cb2) cb2(cleartext.authorized, verifyError, cert, cipher);
            });

            cleartext._controlReleased = true;

            socket.cleartext = cleartext;

            if (socket._timeout) {
                cleartext.setTimeout(socket._timeout);
            }

            cleartext.setKeepAlive(socket._keepalive);

            socket.attach(socket.cleartext);
        };

        cb(socket);
    });

    return serv;
}

if (require('semver').gt(process.version, '0.7.0')) {
    var _net_connect = function (options) {
        return net.connect(options);
    };
}
else {
    var _net_connect = function (options) {
        return net.connect(options.port, options.host);
    };
}

function connect (port, host, cb) {
    var conn_options = {};
    if (typeof port === 'object') {
        conn_options = port;
        cb = host;
    }
    else {
        conn_options.port = port;
        conn_options.host = host;
    }

    var cryptoSocket = _net_connect(conn_options);

    var socket = new pluggableStream(cryptoSocket);

    socket.upgrade = function (options, cb2) {
        socket.clean();
        cryptoSocket.removeAllListeners('data');

        // Set SSL_OP_ALL for maximum compatibility with broken servers
        // See http://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
        if (!options) options = {};
        // TODO: bug in Node means we can't do this until it's fixed
        // options.secureOptions = constants.SSL_OP_ALL;

        options.secureProtocol = options.secureProtocol || 'SSLv23_method';
        options.secureOptions  = options.secureOptions  || constants.SSL_OP_NO_SSLv3;

        var sslcontext = (tls.createSecureContext || crypto.createCredentials)(options);

        // tls.createSecurePair([credentials], [isServer]);
        var pair = tls.createSecurePair(sslcontext, false);

        socket.pair = pair;

        var cleartext = pipe(pair, cryptoSocket);

        pair.on('error', function(exception) {
            socket.emit('error', exception);
        });

        pair.on('secure', function() {
            var verifyError = (pair.ssl || pair._ssl).verifyError();

            log.logdebug('client TLS secured.');
            if (verifyError) {
                cleartext.authorized = false;
                cleartext.authorizationError = verifyError;
            }
            else {
                cleartext.authorized = true;
            }
            var cert = pair.cleartext.getPeerCertificate();
            if (pair.cleartext.getCipher) {
                var cipher = pair.cleartext.getCipher();
            }

            if (cb2) cb2(cleartext.authorized, verifyError, cert, cipher);

            socket.emit('secure');
        });

        cleartext._controlReleased = true;
        socket.cleartext = cleartext;

        if (socket._timeout) {
            cleartext.setTimeout(socket._timeout);
        }

        cleartext.setKeepAlive(socket._keepalive);

        socket.attach(socket.cleartext);

        log.logdebug('client TLS upgrade in progress, awaiting secured.');
    };

    return (socket);
}

exports.load_tls_ini = function (cb) {
    var cfg = config.get('tls.ini', {
        booleans: [
            '+main.requestCert',
            '-main.rejectUnauthorized',
            '-redis.disable_for_failed_hosts',
        ]
    }, cb);

    if (!cfg.no_tls_hosts) {
        cfg.no_tls_hosts = {};
    }

    return cfg;
}

exports.connect = connect;
exports.createConnection = connect;
exports.Server = createServer;
exports.createServer = createServer;
<commit_msg>Fix outbound requesting cert and rejecting unauth<commit_after>'use strict';
/*----------------------------------------------------------------------------------------------*/
/* Obtained and modified from http://js.5sh.net/starttls.js on 8/18/2011.                       */
/*----------------------------------------------------------------------------------------------*/

var tls       = require('tls');
var constants = require('constants');
var crypto    = require('crypto');
var util      = require('util');
var net       = require('net');
var stream    = require('stream');
var log       = require('./logger');
var config    = require('./config');

// provides a common socket for attaching
// and detaching from either main socket, or crypto socket
function pluggableStream(socket) {
    stream.Stream.call(this);
    this.readable = this.writable = true;
    this._timeout = 0;
    this._keepalive = false;
    this._writeState = true;
    this._pending = [];
    this._pendingCallbacks = [];
    if (socket) this.attach(socket);
}

util.inherits(pluggableStream, stream.Stream);

pluggableStream.prototype.pause = function () {
    if (this.targetsocket.pause) {
        this.targetsocket.pause();
        this.readable = false;
    }
};

pluggableStream.prototype.resume = function () {
    if (this.targetsocket.resume) {
        this.readable = true;
        this.targetsocket.resume();
    }
};

pluggableStream.prototype.attach = function (socket) {
    var self = this;
    self.targetsocket = socket;
    self.targetsocket.on('data', function (data) {
        self.emit('data', data);
    });
    self.targetsocket.on('connect', function (a, b) {
        self.emit('connect', a, b);
    });
    self.targetsocket.on('secureConnection', function (a, b) {
        self.emit('secureConnection', a, b);
        self.emit('secure', a, b);
    });
    self.targetsocket.on('secure', function (a, b) {
        self.emit('secureConnection', a, b);
        self.emit('secure', a, b);
    });
    self.targetsocket.on('end', function () {
        self.writable = self.targetsocket.writable;
        self.emit('end');
    });
    self.targetsocket.on('close', function (had_error) {
        self.writable = self.targetsocket.writable;
        self.emit('close', had_error);
    });
    self.targetsocket.on('drain', function () {
        self.emit('drain');
    });
    self.targetsocket.on('error', function (exception) {
        self.writable = self.targetsocket.writable;
        self.emit('error', exception);
    });
    self.targetsocket.on('timeout', function () {
        self.emit('timeout');
    });
    if (self.targetsocket.remotePort) {
        self.remotePort = self.targetsocket.remotePort;
    }
    if (self.targetsocket.remoteAddress) {
        self.remoteAddress = self.targetsocket.remoteAddress;
    }
};

pluggableStream.prototype.clean = function (data) {
    if (this.targetsocket && this.targetsocket.removeAllListeners) {
        this.targetsocket.removeAllListeners('data');
        this.targetsocket.removeAllListeners('secureConnection');
        this.targetsocket.removeAllListeners('secure');
        this.targetsocket.removeAllListeners('end');
        this.targetsocket.removeAllListeners('close');
        this.targetsocket.removeAllListeners('error');
        this.targetsocket.removeAllListeners('drain');
    }
    this.targetsocket = {};
    this.targetsocket.write = function () {};
};

pluggableStream.prototype.write = function (data, encoding, callback) {
    if (this.targetsocket.write) {
        return this.targetsocket.write(data, encoding, callback);
    }
    return false;
};

pluggableStream.prototype.end = function (data, encoding) {
    if (this.targetsocket.end) {
        return this.targetsocket.end(data, encoding);
    }
};

pluggableStream.prototype.destroySoon = function () {
    if (this.targetsocket.destroySoon) {
        return this.targetsocket.destroySoon();
    }
};

pluggableStream.prototype.destroy = function () {
    if (this.targetsocket.destroy) {
        return this.targetsocket.destroy();
    }
};

pluggableStream.prototype.setKeepAlive = function (bool) {
    this._keepalive = bool;
    return this.targetsocket.setKeepAlive(bool);
};

pluggableStream.prototype.setNoDelay = function (/* true||false */) {
};

pluggableStream.prototype.setTimeout = function (timeout) {
    this._timeout = timeout;
    return this.targetsocket.setTimeout(timeout);
};

function pipe(pair, socket) {
    pair.encrypted.pipe(socket);
    socket.pipe(pair.encrypted);

    pair.fd = socket.fd;
    var cleartext = pair.cleartext;
    cleartext.socket = socket;
    cleartext.encrypted = pair.encrypted;
    cleartext.authorized = false;

    function onerror(e) {
        if (cleartext._controlReleased) {
            cleartext.emit('error', e);
        }
    }

    function onclose() {
        socket.removeListener('error', onerror);
        socket.removeListener('close', onclose);
    }

    socket.on('error', onerror);
    socket.on('close', onclose);

    return cleartext;
}

function createServer(cb) {
    var serv = net.createServer(function (cryptoSocket) {

        var socket = new pluggableStream(cryptoSocket);

        socket.upgrade = function (options, cb2) {
            log.logdebug('Upgrading to TLS');

            socket.clean();
            cryptoSocket.removeAllListeners('data');

            // Set SSL_OP_ALL for maximum compatibility with broken clients
            // See http://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
            if (!options) options = {};
            // TODO: bug in Node means we can't do this until it's fixed
            // options.secureOptions = constants.SSL_OP_ALL;

            // Setting secureProtocol to 'SSLv23_method' and secureOptions to
            // constants.SSL_OP_NO_SSLv3 are used to disable SSLv2 and SSLv3
            // protcol support.

            options.secureProtocol = options.secureProtocol || 'SSLv23_method';
            options.secureOptions  = options.secureOptions  ||
                constants.SSL_OP_NO_SSLv3;

            var requestCert = true;
            var rejectUnauthorized = false;
            if (options) {
                if (options.requestCert !== undefined) {
                    requestCert = options.requestCert;
                }
                if (options.rejectUnauthorized !== undefined) {
                    rejectUnauthorized = options.rejectUnauthorized;
                }
            }
            var sslcontext = (tls.createSecureContext || crypto.createCredentials)(options);

            // tls.createSecurePair(credentials, isServer, requestCert, rejectUnauthorized)
            var pair = tls.createSecurePair(sslcontext, true, requestCert, rejectUnauthorized);

            var cleartext = pipe(pair, cryptoSocket);

            pair.on('error', function(exception) {
                socket.emit('error', exception);
            });

            pair.on('secure', function() {
                var verifyError = (pair.ssl || pair._ssl).verifyError();

                log.logdebug('TLS secured.');
                if (verifyError) {
                    cleartext.authorized = false;
                    cleartext.authorizationError = verifyError;
                }
                else {
                    cleartext.authorized = true;
                }
                var cert = pair.cleartext.getPeerCertificate();
                if (pair.cleartext.getCipher) {
                    var cipher = pair.cleartext.getCipher();
                }
                socket.emit('secure');
                if (cb2) cb2(cleartext.authorized, verifyError, cert, cipher);
            });

            cleartext._controlReleased = true;

            socket.cleartext = cleartext;

            if (socket._timeout) {
                cleartext.setTimeout(socket._timeout);
            }

            cleartext.setKeepAlive(socket._keepalive);

            socket.attach(socket.cleartext);
        };

        cb(socket);
    });

    return serv;
}

if (require('semver').gt(process.version, '0.7.0')) {
    var _net_connect = function (options) {
        return net.connect(options);
    };
}
else {
    var _net_connect = function (options) {
        return net.connect(options.port, options.host);
    };
}

function connect (port, host, cb) {
    var conn_options = {};
    if (typeof port === 'object') {
        conn_options = port;
        cb = host;
    }
    else {
        conn_options.port = port;
        conn_options.host = host;
    }

    var cryptoSocket = _net_connect(conn_options);

    var socket = new pluggableStream(cryptoSocket);

    socket.upgrade = function (options, cb2) {
        socket.clean();
        cryptoSocket.removeAllListeners('data');

        // Set SSL_OP_ALL for maximum compatibility with broken servers
        // See http://www.openssl.org/docs/ssl/SSL_CTX_set_options.html
        if (!options) options = {};
        // TODO: bug in Node means we can't do this until it's fixed
        // options.secureOptions = constants.SSL_OP_ALL;

        options.secureProtocol = options.secureProtocol || 'SSLv23_method';
        options.secureOptions  = options.secureOptions  || constants.SSL_OP_NO_SSLv3;

        var requestCert = true;
        var rejectUnauthorized = false;
        if (options) {
            if (options.requestCert !== undefined) {
                requestCert = options.requestCert;
            }
            if (options.rejectUnauthorized !== undefined) {
                rejectUnauthorized = options.rejectUnauthorized;
            }
        }
        var sslcontext = (tls.createSecureContext || crypto.createCredentials)(options);

        // tls.createSecurePair([credentials], [isServer]);
        var pair = tls.createSecurePair(sslcontext, false, requestCert, rejectUnauthorized);

        socket.pair = pair;

        var cleartext = pipe(pair, cryptoSocket);

        pair.on('error', function(exception) {
            socket.emit('error', exception);
        });

        pair.on('secure', function() {
            var verifyError = (pair.ssl || pair._ssl).verifyError();

            log.logdebug('client TLS secured.');
            if (verifyError) {
                cleartext.authorized = false;
                cleartext.authorizationError = verifyError;
            }
            else {
                cleartext.authorized = true;
            }
            var cert = pair.cleartext.getPeerCertificate();
            if (pair.cleartext.getCipher) {
                var cipher = pair.cleartext.getCipher();
            }

            if (cb2) cb2(cleartext.authorized, verifyError, cert, cipher);

            socket.emit('secure');
        });

        cleartext._controlReleased = true;
        socket.cleartext = cleartext;

        if (socket._timeout) {
            cleartext.setTimeout(socket._timeout);
        }

        cleartext.setKeepAlive(socket._keepalive);

        socket.attach(socket.cleartext);

        log.logdebug('client TLS upgrade in progress, awaiting secured.');
    };

    return (socket);
}

exports.load_tls_ini = function (cb) {
    var cfg = config.get('tls.ini', {
        booleans: [
            '+main.requestCert',
            '-main.rejectUnauthorized',
            '-redis.disable_for_failed_hosts',
        ]
    }, cb);

    if (!cfg.no_tls_hosts) {
        cfg.no_tls_hosts = {};
    }

    return cfg;
}

exports.connect = connect;
exports.createConnection = connect;
exports.Server = createServer;
exports.createServer = createServer;
<|endoftext|>


<commit_before>'use strict';

function canvas_draw(){
    canvas_buffer.clearRect(
      0,
      0,
      canvas_width,
      canvas_height
    );

    draw_logic();

    if(canvas_menu){
        canvas_buffer.save();

        canvas_buffer.fillStyle = '#111';
        canvas_buffer.fillRect(
          canvas_x - 125,
          canvas_y - 50,
          250,
          100
        );

        canvas_buffer.fillStyle = '#fff';
        canvas_buffer.font = canvas_fonts['medium'];
        canvas_buffer.textAlign = 'center';
        canvas_buffer.textBaseline = 'middle';
        canvas_buffer.fillText(
          canvas_resume,
          canvas_x,
          canvas_y - 25
        );
        canvas_buffer.fillText(
          canvas_quit,
          canvas_x,
          canvas_y + 25
        );

        canvas_buffer.restore();
    }

    canvas_canvas.clearRect(
      0,
      0,
      canvas_width,
      canvas_height
    );
    canvas_canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );
}

function canvas_drawloop(){
    canvas_draw();
    canvas_animationFrame = window.requestAnimationFrame(canvas_drawloop);
}

// Required args: vertices
// Optional args: properties, style, type
function canvas_draw_path(args){
    args = core_args({
      'args': args,
      'defaults': {
        'properties': {},
        'style': canvas_style,
        'type': 'lineTo',
      },
    });

    canvas_buffer.beginPath();
    for(var vertex in args['vertices']){
        canvas_buffer[args['vertices'][vertex]['type'] || args['type']](
          args['vertices'][vertex]['x'],
          args['vertices'][vertex]['y'],
          args['vertices'][vertex]['radius'],
          args['vertices'][vertex]['startAngle'],
          args['vertices'][vertex]['endAngle'],
          args['vertices'][vertex]['antiClockwise']
        );
    }
    canvas_buffer.closePath();

    for(var property in args['properties']){
        canvas_buffer[property] = args['properties'][property];
    }

    canvas_buffer[args['style']]();
}

// Required args: stops
// Optional args: height, width, x, y
function canvas_gradient(args){
    args = core_args({
      'args': args,
      'defaults': {
        'height': 0,
        'width': 0,
        'x': 0,
        'y': 0,
      },
    });

    var gradient = canvas_buffer.createLinearGradient(
      args['x'],
      args['y'],
      args['width'],
      args['height']
    );
    for(var step in args['steps']){
        gradient.addColorStop(
          args['steps'][step]['offset'] || 0,
          args['steps'][step]['color'] || '#000'
        );
    }
    return gradient;
}

function canvas_init(){
    canvas_resize();
    canvas_setmode({
      'mode': 0,
    });
}

function canvas_menu_quit(){
    if(canvas_menu){
        canvas_setmode({
          'mode': 0,
        });
    }
}

function canvas_menu_toggle(){
    canvas_menu = !canvas_menu;
}

function canvas_resize(){
    if(canvas_mode <= 0){
        return;
    }

    canvas_height = window.innerHeight;
    document.getElementById('buffer').height = canvas_height;
    document.getElementById('canvas').height = canvas_height;
    canvas_y = canvas_height / 2;

    canvas_width = window.innerWidth;
    document.getElementById('buffer').width = canvas_width;
    document.getElementById('canvas').width = canvas_width;
    canvas_x = canvas_width / 2;

    canvas_buffer.font = canvas_fonts['medium'];

    core_call({
      'todo': 'resize_logic',
    });
}

// Required args: mode
// Optional args: newgame
function canvas_setmode(args){
    args = core_args({
      'args': args,
      'defaults': {
        'newgame': false,
      },
    });

    window.cancelAnimationFrame(canvas_animationFrame);
    window.clearInterval(canvas_interval);

    canvas_menu = false;
    canvas_mode = args['mode'];

    if(core_type({
      'var': 'setmode_logic',
      'type': 'function',
    })){
        setmode_logic(args['newgame']);

    }else{
        canvas_mode = 1;
        args['newgame'] = true;
    }

    // Main menu mode.
    if(canvas_mode === 0){
        canvas_buffer = 0;
        canvas_canvas = 0;
        return;
    }

    // Simulation modes.
    if(args['newgame']){
        var properties = '';

        if(!canvas_oncontextmenu){
            properties = ' oncontextmenu="return false" ';
        }

        document.body.innerHTML =
          '<canvas id=canvas' + properties + '></canvas><canvas id=buffer></canvas>';

        canvas_buffer = document.getElementById('buffer').getContext('2d');
        canvas_canvas = document.getElementById('canvas').getContext('2d');

        canvas_resize();
    }

    core_call({
      'args': canvas_mode,
      'todo': 'load_level',
    });

    canvas_animationFrame = window.requestAnimationFrame(canvas_drawloop);

    if(core_type({
      'var': 'logic',
      'type': 'function',
    })){
        canvas_interval = window.setInterval(
          logic,
          canvas_interval_ms
        );
    }
}

var canvas_animationFrame = 0;
var canvas_buffer = 0;
var canvas_canvas = 0;
var canvas_fonts = {
  'big': '300% monospace',
  'medium': '200% monospace',
  'small': '100% monospace',
};
var canvas_height = 0;
var canvas_interval = 0;
var canvas_interval_ms = 25;
var canvas_menu = false;
var canvas_mode = 0;
var canvas_oncontextmenu = true;
var canvas_quit = 'Q = Main Menu';
var canvas_resume = 'ESC = Resume';
var canvas_style = 'fill';
var canvas_width = 0;
var canvas_x = 0;
var canvas_y = 0;

window.onresize = canvas_resize;
<commit_msg>renamed steps to stops<commit_after>'use strict';

function canvas_draw(){
    canvas_buffer.clearRect(
      0,
      0,
      canvas_width,
      canvas_height
    );

    draw_logic();

    if(canvas_menu){
        canvas_buffer.save();

        canvas_buffer.fillStyle = '#111';
        canvas_buffer.fillRect(
          canvas_x - 125,
          canvas_y - 50,
          250,
          100
        );

        canvas_buffer.fillStyle = '#fff';
        canvas_buffer.font = canvas_fonts['medium'];
        canvas_buffer.textAlign = 'center';
        canvas_buffer.textBaseline = 'middle';
        canvas_buffer.fillText(
          canvas_resume,
          canvas_x,
          canvas_y - 25
        );
        canvas_buffer.fillText(
          canvas_quit,
          canvas_x,
          canvas_y + 25
        );

        canvas_buffer.restore();
    }

    canvas_canvas.clearRect(
      0,
      0,
      canvas_width,
      canvas_height
    );
    canvas_canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );
}

function canvas_drawloop(){
    canvas_draw();
    canvas_animationFrame = window.requestAnimationFrame(canvas_drawloop);
}

// Required args: vertices
// Optional args: properties, style, type
function canvas_draw_path(args){
    args = core_args({
      'args': args,
      'defaults': {
        'properties': {},
        'style': canvas_style,
        'type': 'lineTo',
      },
    });

    canvas_buffer.beginPath();
    for(var vertex in args['vertices']){
        canvas_buffer[args['vertices'][vertex]['type'] || args['type']](
          args['vertices'][vertex]['x'],
          args['vertices'][vertex]['y'],
          args['vertices'][vertex]['radius'],
          args['vertices'][vertex]['startAngle'],
          args['vertices'][vertex]['endAngle'],
          args['vertices'][vertex]['antiClockwise']
        );
    }
    canvas_buffer.closePath();

    for(var property in args['properties']){
        canvas_buffer[property] = args['properties'][property];
    }

    canvas_buffer[args['style']]();
}

// Required args: stops
// Optional args: height, width, x, y
function canvas_gradient(args){
    args = core_args({
      'args': args,
      'defaults': {
        'height': 0,
        'width': 0,
        'x': 0,
        'y': 0,
      },
    });

    var gradient = canvas_buffer.createLinearGradient(
      args['x'],
      args['y'],
      args['width'],
      args['height']
    );
    for(var step in args['stops']){
        gradient.addColorStop(
          args['stops'][step]['offset'] || 0,
          args['stops'][step]['color'] || '#000'
        );
    }
    return gradient;
}

function canvas_init(){
    canvas_resize();
    canvas_setmode({
      'mode': 0,
    });
}

function canvas_menu_quit(){
    if(canvas_menu){
        canvas_setmode({
          'mode': 0,
        });
    }
}

function canvas_menu_toggle(){
    canvas_menu = !canvas_menu;
}

function canvas_resize(){
    if(canvas_mode <= 0){
        return;
    }

    canvas_height = window.innerHeight;
    document.getElementById('buffer').height = canvas_height;
    document.getElementById('canvas').height = canvas_height;
    canvas_y = canvas_height / 2;

    canvas_width = window.innerWidth;
    document.getElementById('buffer').width = canvas_width;
    document.getElementById('canvas').width = canvas_width;
    canvas_x = canvas_width / 2;

    canvas_buffer.font = canvas_fonts['medium'];

    core_call({
      'todo': 'resize_logic',
    });
}

// Required args: mode
// Optional args: newgame
function canvas_setmode(args){
    args = core_args({
      'args': args,
      'defaults': {
        'newgame': false,
      },
    });

    window.cancelAnimationFrame(canvas_animationFrame);
    window.clearInterval(canvas_interval);

    canvas_menu = false;
    canvas_mode = args['mode'];

    if(core_type({
      'var': 'setmode_logic',
      'type': 'function',
    })){
        setmode_logic(args['newgame']);

    }else{
        canvas_mode = 1;
        args['newgame'] = true;
    }

    // Main menu mode.
    if(canvas_mode === 0){
        canvas_buffer = 0;
        canvas_canvas = 0;
        return;
    }

    // Simulation modes.
    if(args['newgame']){
        var properties = '';

        if(!canvas_oncontextmenu){
            properties = ' oncontextmenu="return false" ';
        }

        document.body.innerHTML =
          '<canvas id=canvas' + properties + '></canvas><canvas id=buffer></canvas>';

        canvas_buffer = document.getElementById('buffer').getContext('2d');
        canvas_canvas = document.getElementById('canvas').getContext('2d');

        canvas_resize();
    }

    core_call({
      'args': canvas_mode,
      'todo': 'load_level',
    });

    canvas_animationFrame = window.requestAnimationFrame(canvas_drawloop);

    if(core_type({
      'var': 'logic',
      'type': 'function',
    })){
        canvas_interval = window.setInterval(
          logic,
          canvas_interval_ms
        );
    }
}

var canvas_animationFrame = 0;
var canvas_buffer = 0;
var canvas_canvas = 0;
var canvas_fonts = {
  'big': '300% monospace',
  'medium': '200% monospace',
  'small': '100% monospace',
};
var canvas_height = 0;
var canvas_interval = 0;
var canvas_interval_ms = 25;
var canvas_menu = false;
var canvas_mode = 0;
var canvas_oncontextmenu = true;
var canvas_quit = 'Q = Main Menu';
var canvas_resume = 'ESC = Resume';
var canvas_style = 'fill';
var canvas_width = 0;
var canvas_x = 0;
var canvas_y = 0;

window.onresize = canvas_resize;
<|endoftext|>


<commit_before>#!/usr/bin/env node

// 2. tm-monitor.js. Given a list of query strings in a file named
//    monitor-strings, searches the
//    latest TMOG (Trademark On-Line Gazette) to see if any new
//    applications have popped up. The output is placed into a
//    directory called "TMOG-Reports," with output from each TMOG
//    placed in a file named "TMOG-<date>-results".
//    Note that node 0.11 or higher is required for execSync.

var queriesArray, tmogDate;
var i, j, jsonResultsArray, tmogOutput, tmogOutputStr;

var INPUTFILE = "monitor-queries";
var OUTPUTPATH = "TMOG-Reports";

var fs = require('fs');
var child_process = require('child_process');

// Open data file and create list of strings.
// Note that this array is not validated or cleaned.
queriesArray = fs.readFileSync(INPUTFILE, 'utf-8');
queriesArray = queriesArray.split('\n');

// Check to see if tmogDate was handed in as a command line argument
if (process.argv.indexOf("--tmogDate") != -1) {
	// Set tmogDate to the handed-in argument
	tmogDate = process.argv[process.argv.indexOf("--tmogDate")+1];
} else {
	// Get date of most recent TMOG, which comes out Tuesdays
	tmogDate = child_process.execSync('date -v-tuesday "+%G-%m-%d"');
}
tmogDate = tmogDate.toString().trim();
tmogDate = tmogDate.replace(/[^-0-9]/gi, '');

// Get results for each query string.
jsonResultsArray = [];
tmogOutput = [];
for (i=0; i<queriesArray.length; i++) {
//	console.log("Looping\n");
	queriesArray[i] = queriesArray[i].replace(/#.*/, ""); // Skip comments
	queriesArray[i] = queriesArray[i].trim();
	if (queriesArray[i].length < 1) {
		continue;
	}

	var curlResults = child_process.execSync("curl '" + "https://tmog.uspto.gov/eOG/search/all/info.json?searchBy=" + queriesArray[i] + "&searchIn=MARK_TEXT%2COWNER%2CMARK_DESC%2CGS_DESC%2CADD_STM%2CDOCKET_NR%2CSERIAL_NR%2CREG_NR&issues=" + tmogDate + "&pubReason=OPPOSITION&limit=2000&orderBy=SERIAL_NR&order=ASC" + "'");
	if (curlResults.length > 1) {
		jsonResultsArray[i] = eval("results = " + curlResults.toString());
	} else {
		jsonResultsArray[i] = "";
//		console.log("jsonResultsArray has length 0")
	}
//	console.log(jsonResultsArray[i]);

	// Pretty-print to buffer
	// Loop over results in the received JSON array
	for (j=0; j < jsonResultsArray[i].totalCount; j++) {
		if (jsonResultsArray[i] == "") { continue; }
		tmogOutput[i] +=
			"
" +
			"" + queriesArray[i] + "	" +
			"" + "" + jsonResultsArray[i].cases[j].seriaNum + "	" +
			"" + jsonResultsArray[i].cases[j].publicationDate + "	" +
			"" + jsonResultsArray[i].cases[j].markText + "	" +
			"" + jsonResultsArray[i].cases[j].currentOwner + "	" +
			"
";
//		console.log(i);
//		console.log(j);
//		console.log(tmogOutput[i]);
	}
}

// console.log("Reaching output buffer portion\n");

// Fill output buffer
tmogOutputStr = "<!DOCTYPE html>
Trademark Gazette publications as of " + tmogDate + "

  Query 	 TM serial no.	 Date of publication	 Trademark text	 Current owner
 ";
for (i=0; i<queriesArray.length; i++) { if (tmogOutput[i]) { tmogOutputStr += tmogOutput[i]; } }
tmogOutputStr += "
  ";
tmogOutputStr = tmogOutputStr.replace(/undefined/gm, "");

// Output to file
fs.writeFileSync(OUTPUTPATH + "/TMOG-" + tmogDate + "-results.html", tmogOutputStr);
<commit_msg><commit_after>#!/usr/bin/env node

// 2. tm-monitor.js. Given a list of query strings in a file named
//    monitor-strings, searches the
//    latest TMOG (Trademark On-Line Gazette) to see if any new
//    applications have popped up. The output is placed into a
//    directory called "TMOG-Reports," with output from each TMOG
//    placed in a file named "TMOG-<date>-results".
//    Note that node 0.11 or higher is required for execSync.

var queriesArray, tmogDate;
var i, j, jsonResultsArray, tmogOutput, tmogOutputStr;

var INPUTFILE = "monitor-queries";
var OUTPUTPATH = "TMOG-Reports";

var fs = require('fs');
var child_process = require('child_process');

// Open data file and create list of strings.
// Note that this array is not validated or cleaned.
queriesArray = fs.readFileSync(INPUTFILE, 'utf-8');
queriesArray = queriesArray.split('\n');

// Check to see if tmogDate was handed in as a command line argument
if (process.argv.indexOf("--tmogDate") != -1) {
	// Set tmogDate to the handed-in argument
	tmogDate = process.argv[process.argv.indexOf("--tmogDate")+1];
} else {
	// Get date of most recent TMOG, which comes out Tuesdays
	tmogDate = child_process.execSync('date -v-tuesday "+%G-%m-%d"');
}
tmogDate = tmogDate.toString().trim();
tmogDate = tmogDate.replace(/[^-0-9]/gi, '');

// Get results for each query string.
jsonResultsArray = [];
tmogOutput = [];
for (i=0; i<queriesArray.length; i++) {
//	console.log("Looping\n");
	queriesArray[i] = queriesArray[i].replace(/#.*/, ""); // Skip comments
	queriesArray[i] = queriesArray[i].trim();
	if (queriesArray[i].length < 1) {
		continue;
	}

	var curlResults = child_process.execSync("curl '" + "https://tmog.uspto.gov/eOG/search/all/info.json?searchBy=" + queriesArray[i] + "&searchIn=MARK_TEXT%2COWNER%2CMARK_DESC%2CGS_DESC%2CADD_STM%2CDOCKET_NR%2CSERIAL_NR%2CREG_NR&issues=" + tmogDate + "&pubReason=OPPOSITION&limit=2000&orderBy=SERIAL_NR&order=ASC" + "'");
	if (curlResults.length > 1) {
		jsonResultsArray[i] = eval("results = " + curlResults.toString());
	} else {
		jsonResultsArray[i] = "";
//		console.log("jsonResultsArray has length 0")
	}
//	console.log(jsonResultsArray[i]);

	// Pretty-print to buffer
	// Loop over results in the received JSON array
	for (j=0; j < jsonResultsArray[i].totalCount; j++) {
		if (jsonResultsArray[i] == "") { continue; }
		tmogOutput[i] +=
			"
" +
			"" + queriesArray[i] + "	" +
			"" + "" + jsonResultsArray[i].cases[j].serialNum + "	" +
			"" + jsonResultsArray[i].cases[j].publicationDate + "	" +
			"" + jsonResultsArray[i].cases[j].markText + "	" +
			"" + jsonResultsArray[i].cases[j].currentOwner + "	" +
			"
";
//		console.log(i);
//		console.log(j);
//		console.log(tmogOutput[i]);
	}
}

// console.log("Reaching output buffer portion\n");

// Fill output buffer
tmogOutputStr = "<!DOCTYPE html>
Trademark Gazette publications as of " + tmogDate + "

  Query 	 TM serial no.	 Date of publication	 Trademark text	 Current owner
 ";
for (i=0; i<queriesArray.length; i++) { if (tmogOutput[i]) { tmogOutputStr += tmogOutput[i]; } }
tmogOutputStr += "
  ";
tmogOutputStr = tmogOutputStr.replace(/undefined/gm, "");

// Output to file
fs.writeFileSync(OUTPUTPATH + "/TMOG-" + tmogDate + "-results.html", tmogOutputStr);
<|endoftext|>


<commit_before>export { OwnerArray };

import * as Pool from "../Pool.js";
import { Array as Recyclable_Array } from "./Recyclable_Array.js";

/**
 * Similar to Recyclable_Array but it owns its contents (which are instances of Recyclable.Base). It will release its contents
 * (by calling their .disposeResources_and_recycleToPool()) in .disposeResources().
 *
 *
 * Note: The behavior of this class's constructor (and .setAsConstructor()) is different from original Array (and Recyclable.Array).
 *
 *   - Original Array (and Recyclable.Array):
 *
 *     - If there is only one argument, it is viewed as the length of the newly created array.
 *
 *   - This Recyclable.OwnerArray:
 *
 *     - Even if there is only one argument, all arguments always are viewed as the contents the newly created array.
 *         The reason is for convenient and for avoiding un-initialized element object.
 *
 *
 */
class OwnerArray extends Recyclable_Array {

  /**
   * Used as default Recyclable.OwnerArray provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Recyclable.OwnerArray.Pool", OwnerArray, OwnerArray.setAsConstructor );

  /**
   * Every element of restArgs should be instance of ChannelPartInfo (even if restArgs has only one element).
   *
   * Note: This behavior is different from original Array which will views the argement is length (not element) if only one argument
   *       is given.
   */
  constructor( ...restArgs ) {
    super( restArgs.length );
    OwnerArray.setAsConstructor_self.call( this, restArgs );
  }

  /**
   * Every element of restArgs should be instance of ChannelPartInfo (even if restArgs has only one element).
   *
   * Note: This behavior is different from original Array which will views the argement is length (not element) if only one argument
   *       is given.
   *
   * @override
   */
  static setAsConstructor( ...restArgs ) {
    super.setAsConstructor( restArgs.length );
    OwnerArray.setAsConstructor_self.call( this, restArgs );
    return this;
  }

  /** @override */
  static setAsConstructor_self( objectArray ) {
    for ( let i = 0; i < objectArray.length; ++i ) {
      this[ i ] = objectArray[ i ];
    }
  }

  /** @override */
  disposeResources() {

    // Release all contents since they are owned by this OwnerArray.
    for ( let i = 0; i < this.length; ++i ) {
      let object = this[ i ];
      if ( object instanceof Recyclable.Base ) {
        object.disposeResources_and_recycleToPool();
        this[ i ] = null; // So that it will not become dangling object (since it has already been recycled).
      }
    }

    super.disposeResources();
  }

}

<commit_msg>Update Recyclable_OwnerArray.js<commit_after>export { OwnerArray };

import * as Pool from "../Pool.js";
import { Base } from "./Recyclable_Base.js";
import { Array as Recyclable_Array } from "./Recyclable_Array.js";

/**
 * Similar to Recyclable_Array but it owns its contents (which are instances of Recyclable.Base). It will release its contents
 * (by calling their .disposeResources_and_recycleToPool()) in .disposeResources().
 *
 *
 * Note: The behavior of this class's constructor (and .setAsConstructor()) is different from original Array (and Recyclable.Array).
 *
 *   - Original Array (and Recyclable.Array):
 *
 *     - If there is only one argument, it is viewed as the length of the newly created array.
 *
 *   - This Recyclable.OwnerArray:
 *
 *     - Even if there is only one argument, all arguments always are viewed as the contents the newly created array.
 *         The reason is for convenient and for avoiding un-initialized element object.
 *
 *
 */
class OwnerArray extends Recyclable_Array {

  /**
   * Used as default Recyclable.OwnerArray provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Recyclable.OwnerArray.Pool", OwnerArray, OwnerArray.setAsConstructor );

  /**
   * Every element of restArgs should be instance of ChannelPartInfo (even if restArgs has only one element).
   *
   * Note: This behavior is different from original Array which will views the argement is length (not element) if only one argument
   *       is given.
   */
  constructor( ...restArgs ) {
    super( restArgs.length );
    OwnerArray.setAsConstructor_self.call( this, restArgs );
  }

  /**
   * Every element of restArgs should be instance of ChannelPartInfo (even if restArgs has only one element).
   *
   * Note: This behavior is different from original Array which will views the argement is length (not element) if only one argument
   *       is given.
   *
   * @override
   */
  static setAsConstructor( ...restArgs ) {
    super.setAsConstructor( restArgs.length );
    OwnerArray.setAsConstructor_self.call( this, restArgs );
    return this;
  }

  /** @override */
  static setAsConstructor_self( objectArray ) {
    for ( let i = 0; i < objectArray.length; ++i ) {
      this[ i ] = objectArray[ i ];
    }
  }

  /** @override */
  disposeResources() {

    // Release all contents since they are owned by this OwnerArray.
    for ( let i = 0; i < this.length; ++i ) {
      let object = this[ i ];
      if ( object ) {
        // Note: ( object instanceof Base ) does not work here because Recyclable.Base is not a class definition (in fact, it is a
        //       function return a class definition). So check whether .disposeResources_and_recycleToPool() exists instead.
        //
        if ( object.disposeResources_and_recycleToPool instanceof Function ) {
          object.disposeResources_and_recycleToPool();
          this[ i ] = null; // So that it will not become dangling object (since it has already been recycled).
        }
      }
    }

    super.disposeResources();
  }

}

<|endoftext|>


<commit_before>var Coffee = {
  api: 'http://draug.online.ntnu.no/coffee.txt',
  msgNoPots: 'Ingen kanner i dag',
  msgNoCoffee: 'Kaffen har ikke blitt satt på',
  msgFormatError: 'Feil i kaffeformat',
  msgConnectionError: 'Frakoblet fra kaffeknappen',
  msgComforting: 'Det er sikkert kaffe!',

  debugCoffee: 0,
  debugCoffeeString: "200\n1. March 14:28:371",

  get: function(callback) {
    if (callback == undefined) {
      console.log('ERROR: Callback is required. In the callback you should insert the results into the DOM.');
      return;
    }

    // Receives the status for the coffee pot
    var self = this;
    $.ajax({
      url: self.api,
      success: function(data) {

        // If coffee debugging is enabled
        if (self.debugCoffee) {
          data = self.debugCoffeeString;
        }

        try {
          // Split into pot number and age of last pot
          var pieces = data.split("\n");
          var pots = pieces[0];
          var ageString = pieces[1];

          // Get now
          var now = new Date();

          // Figure out which date the coffee was made
          var dateObject = ageString.match(/\d+\. [a-zA-Z]+/); // Operas JS-engine makes an object instead of a string
          var dateString = String(dateObject);
          dateString = dateString.replace('.', ''); // Remove period
          dateString = dateString + ', ' + now.getFullYear();
          var coffeeDate = new Date(dateString);

          // Check if the coffee pots were made today
          if (coffeeDate.getDate() == now.getDate()) {

            // Calulate the age of the last pot better
            var coffeeTime = String(ageString.match(/\d+:\d+:\d+/)).split(':');
            var then = new Date(now.getFullYear(), now.getMonth(), now.getDate(), coffeeTime[0], coffeeTime[1]);
            var one_minute = 1000 * 60;

            // Calculate difference between the two dates, and convert to minutes
            var diff = Math.floor(( now.getTime() - then.getTime() ) / one_minute);

            // Create a proper time string from all the minutes
            var age;
            if (-1 <= diff && diff <= 9) {
              age = 'Kaffen ble nettopp laget';
            }
            else if (10 <= diff && diff <= 59) {
              age = 'Kaffen ble laget for '+diff+' min siden';
            }
            else if (60 <= diff) {
              age = 'Kaffen ble laget kl '+coffeeTime[0]+':'+coffeeTime[1];
            }
            else {
              age = 'Har noen laget kaffe i fremtiden?!'
            }

            // Make pots-string
            pots = (pots=='0'?'Ingen kanner':pots=='1'?'1 kanne':pots+' kanner') + ' i dag';

            // Call it back
            callback(pots, age);
          }
          else {
            // Coffee was not made today
            var coffee = '';
            callback(self.msgNoPots, self.msgNoCoffee);
          }
        } catch (err) {
          if (DEBUG) console.log('ERROR: Coffee format is wrong.');
          callback(self.msgFormatError, self.msgComforting);
        }
      },
      error: function(jqXHR, text, err) {
        if (DEBUG) console.log('ERROR: Failed to get coffee pot status.');
        callback(self.msgConnectionError, self.msgComforting);
      },
    });
  },

  getPots: function(callback) {
    // Function used by background process to determine when a new coffee pot is cooking
    if (callback == undefined) {
      console.log('ERROR: Callback is required. In the callback you should insert the results into the DOM.');
      return;
    }
    var self = this;
    $.ajax({
      url: self.api,
      success: function(data) {
        try {
          // Split into pot number and age of last pot
          var pieces = data.split("\n");
          var pots = pieces[0];
          var ageString = pieces[1];

          // Get now
          var now = new Date();

          // Check if the coffee pots were made today
          var coffeeDate = new Date(ageString.match(/\d+\. [a-zA-Z]+/));
          if (coffeeDate.getDate() == now.getDate()) {
            callback(pots);
          }
          else {
            callback(0);
          }
        } catch (err) {
          if (DEBUG) console.log('ERROR: Failed to parse coffee status.');
          callback(0);
        }
      },
      error: function(jqXHR, text, err) {
        if (DEBUG) console.log('ERROR: Failed to get coffee pot status.');
        callback(0);
      },
    });
  },

  showNotification: function(pots) {
    // Amount of pots currently not used
    Browser.createNotification('subscription.html');
  },

}
<commit_msg>coffee: switching to dev API<commit_after>var Coffee = {
  api: 'http://draug.online.ntnu.no/coffee_dev.txt',
  msgNoPots: 'Ingen kanner i dag',
  msgNoCoffee: 'Kaffen har ikke blitt satt på',
  msgFormatError: 'Feil i kaffeformat',
  msgConnectionError: 'Frakoblet fra kaffeknappen',
  msgComforting: 'Det er sikkert kaffe!',

  debugCoffee: 0,
  debugCoffeeString: "200\n1. March 14:28:371",

  get: function(callback) {
    if (callback == undefined) {
      console.log('ERROR: Callback is required. In the callback you should insert the results into the DOM.');
      return;
    }

    // Receives the status for the coffee pot
    var self = this;
    $.ajax({
      url: self.api,
      success: function(data) {

        // If coffee debugging is enabled
        if (self.debugCoffee) {
          data = self.debugCoffeeString;
        }

        try {
          // Split into pot number and age of last pot
          var pieces = data.split("\n");
          var pots = pieces[0];
          var ageString = pieces[1];

          // Get now
          var now = new Date();

          // Figure out which date the coffee was made
          var dateObject = ageString.match(/\d+\. [a-zA-Z]+/); // Operas JS-engine makes an object instead of a string
          var dateString = String(dateObject);
          dateString = dateString.replace('.', ''); // Remove period
          dateString = dateString + ', ' + now.getFullYear();
          var coffeeDate = new Date(dateString);

          // Check if the coffee pots were made today
          if (coffeeDate.getDate() == now.getDate()) {

            // Calulate the age of the last pot better
            var coffeeTime = String(ageString.match(/\d+:\d+:\d+/)).split(':');
            var then = new Date(now.getFullYear(), now.getMonth(), now.getDate(), coffeeTime[0], coffeeTime[1]);
            var one_minute = 1000 * 60;

            // Calculate difference between the two dates, and convert to minutes
            var diff = Math.floor(( now.getTime() - then.getTime() ) / one_minute);

            // Create a proper time string from all the minutes
            var age;
            if (-1 <= diff && diff <= 9) {
              age = 'Kaffen ble nettopp laget';
            }
            else if (10 <= diff && diff <= 59) {
              age = 'Kaffen ble laget for '+diff+' min siden';
            }
            else if (60 <= diff) {
              age = 'Kaffen ble laget kl '+coffeeTime[0]+':'+coffeeTime[1];
            }
            else {
              age = 'Har noen laget kaffe i fremtiden?!'
            }

            // Make pots-string
            pots = (pots=='0'?'Ingen kanner':pots=='1'?'1 kanne':pots+' kanner') + ' i dag';

            // Call it back
            callback(pots, age);
          }
          else {
            // Coffee was not made today
            var coffee = '';
            callback(self.msgNoPots, self.msgNoCoffee);
          }
        } catch (err) {
          if (DEBUG) console.log('ERROR: Coffee format is wrong.');
          callback(self.msgFormatError, self.msgComforting);
        }
      },
      error: function(jqXHR, text, err) {
        if (DEBUG) console.log('ERROR: Failed to get coffee pot status.');
        callback(self.msgConnectionError, self.msgComforting);
      },
    });
  },

  getPots: function(callback) {
    // Function used by background process to determine when a new coffee pot is cooking
    if (callback == undefined) {
      console.log('ERROR: Callback is required. In the callback you should insert the results into the DOM.');
      return;
    }
    var self = this;
    $.ajax({
      url: self.api,
      success: function(data) {
        try {
          // Split into pot number and age of last pot
          var pieces = data.split("\n");
          var pots = pieces[0];
          var ageString = pieces[1];

          // Get now
          var now = new Date();

          // Check if the coffee pots were made today
          var coffeeDate = new Date(ageString.match(/\d+\. [a-zA-Z]+/));
          if (coffeeDate.getDate() == now.getDate()) {
            callback(pots);
          }
          else {
            callback(0);
          }
        } catch (err) {
          if (DEBUG) console.log('ERROR: Failed to parse coffee status.');
          callback(0);
        }
      },
      error: function(jqXHR, text, err) {
        if (DEBUG) console.log('ERROR: Failed to get coffee pot status.');
        callback(0);
      },
    });
  },

  showNotification: function(pots) {
    // Amount of pots currently not used
    Browser.createNotification('subscription.html');
  },

}
<|endoftext|>


<commit_before>
function copyAssetAttrs(obj) {
    // copy the form values of the previous Asset to the new subform,
    // excluding the file input.
    var oldersib = $(obj).prev();
    var formelselector = "fieldset div.form-row:not(div[class~='file']) input, fieldset div.form-row:not(div[class~='file']) select, fieldset div.form-row:not(div[class~='file']) textarea";

    if ($(oldersib).is("div.dynamic-asset_set")) {
        var oldersib_formels = $(oldersib).find(formelselector);
        $.each($(obj).find(formelselector), function(key, el) {
            el.value = oldersib_formels[key].value;
        });
    }
}

function buildAssetAccordion() {
    var outer = $('#asset_set-group');
    // first need to wrap Asset fieldsets in an extra div
    $(outer).find('div.dynamic-asset_set').each(
        function(){
            if ($(this).find('div.accordionwrapper').length==0) {
                $(this).find('fieldset').wrapAll("
");
            }
            // have to move the delete checkbox since accordion header eats
            // all of the click events
            $(this).find('span.delete').prependTo($(this).find('.accordionwrapper'));

        }
    );

    // check for error notices
    var error_divs = $(outer).find('div.errors');
    var num_panels = $(outer).find('div.dynamic-asset_set').length

    $(outer).accordion({
        header: '.dynamic-asset_set h3',
        collapsible: false,
        active: ($(error_divs).length) ? num_panels-1 : false,
        change: function(e, ui) {
            // force a redraw of the map after it has gone offscreen
            // as inactive accordion pane.
            map = maps[ui.options.active];
            google.maps.event.trigger(map, 'resize');
            map.setZoom(map.getZoom());
            map.setCenter(map.marker.getPosition());

        }});
}

$(document).bind("DOMNodeInserted", function(e) {
    //console.log(e);
    var element = e.target;
    if ($(element).is('div.dynamic-asset_set')) {
        copyAssetAttrs(e.target);
        hideMediaDisplay();
        setLocationMaps();
        $(e.relatedNode).accordion("destroy");
        buildAssetAccordion();
        num_panels = $(e.relatedNode).find('div.dynamic-asset_set').length;
        $(e.relatedNode).accordion("option","active",num_panels-1);

    }
});

$(document).ready(function() {
    // move initial select assets field below inlines
    var select_assets = $("div.form-row.assets");
    $(select_assets).insertAfter($('#asset_set-group'));
    // make it an accordion with a new header
    $(select_assets).wrapAll("
");
    $(select_assets).before('
Select assets from list
');
    $('div#select_assets_wrapper').accordion({
        header: 'h2',
        collapsible: true,
        active: false,
    });

    // set up accordion on Assets
    buildAssetAccordion();
});

<commit_msg>Fix copying of project, lat, lon, tags from latest Asset to newly added inline Asset on Envelope admin.... somehow this commit shows up in GitHub but the file got reverted<commit_after>
var next_tags_inserted_gets_copied_vals = false;
var asset_set_selector = "div.dynamic-asset_set";

function copyAssetAttrs(obj) {
    // copy the form values of the previous Asset to the new subform,
    // excluding the file input.
    var older_sib = $(obj).prev();

    //copy tags separately, otherwise the number of DOM elements in the older
    //sibling is different and throws off our $.each loop
    var form_el_selector = "fieldset div.form-row:not(div[class~='file']) input:not([id*='searchbox']):not([id*='tags']), fieldset div.form-row:not(div[class~='file']) select:not([id*='tags']), fieldset div.form-row:not(div[class~='file']) textarea";

    if ($(older_sib).is(asset_set_selector)) {
        var older_sib_formels = $(older_sib).find(form_el_selector);
        $.each($(obj).find(form_el_selector), function(key, el) {
            el.value = older_sib_formels[key].value;
        });
    }

}

function copyTagsValuesFromOlderSibling(obj) {
    var tags_on_selector = "select[id*='tags_to']";
    var asset_set = $(obj).closest(asset_set_selector);
    var prev_asset_set = $(asset_set).prevAll(asset_set_selector).first();
    var this_tags_on_el = $(obj).find(tags_on_selector);
    var older_tags_on_el = $(prev_asset_set).find(tags_on_selector);
    var older_options = $(older_tags_on_el).find('option');
    $(older_options).each( function() {
        //console.log("copying option:"+this+" into "+obj.id);
        $(obj).append($("<option/>", {
                'value': this.value, 'text': this.text}));
    });

    // $.each($(this_tags_on_el).find('option'), function(key, el) {
    //     el.value = older_options[key].value;
    // })
}

function buildAssetAccordion() {
    var outer = $('#asset_set-group');
    // first need to wrap Asset fieldsets in an extra div
    $(outer).find(asset_set_selector).each(
        function(){
            if ($(this).find('div.accordionwrapper').length==0) {
                $(this).find('fieldset').wrapAll("
");
            }
            // have to move the delete checkbox since accordion header eats
            // all of the click events
            $(this).find('span.delete').prependTo($(this).find('.accordionwrapper'));

        }
    );

    // check for error notices
    var error_divs = $(outer).find('div.errors');
    var num_panels = $(outer).find(asset_set_selector).length

    $(outer).accordion({
        header: '.dynamic-asset_set h3',
        collapsible: false,
        active: ($(error_divs).length) ? num_panels-1 : false,
        change: function(e, ui) {
            // force a redraw of the map after it has gone offscreen
            // as inactive accordion pane.
            map = maps[ui.options.active];
            google.maps.event.trigger(map, 'resize');
            map.setZoom(map.getZoom());
            map.setCenter(map.marker.getPosition());

        }});
}

$(document).bind("DOMNodeInserted", function(e) {
    //console.log(e);
    var element = e.target;
    if ($(element).is(asset_set_selector)) {

        // when the tags_to select is inserted into DOM, then copy the tags from
        // the older sibling.
        next_tags_inserted_gets_copied_vals = true;
        //console.log('copy asset form values now for: '+ e.target.id);
        copyAssetAttrs(e.target);
        hideMediaDisplay();
        setLocationMaps();
        $(e.relatedNode).accordion("destroy");
        buildAssetAccordion();
        num_panels = $(e.relatedNode).find(asset_set_selector).length;
        $(e.relatedNode).accordion("option","active",num_panels-1);

    }
    // handle copying of select tags to new Asset
    else if ($(element).is("select[id*='tags_to']")) {
        if (next_tags_inserted_gets_copied_vals) {
            console.log('copy tags now for: '+ e.target.id);
            copyTagsValuesFromOlderSibling(e.target);
            next_tags_inserted_gets_copied_vals = false;
        }
    }
});

$(document).ready(function() {
    // move initial select assets field below inlines
    var select_assets = $("div.form-row.assets");
    $(select_assets).insertAfter($('#asset_set-group'));
    // make it an accordion with a new header
    $(select_assets).wrapAll("
");
    $(select_assets).before('
Select assets from list
');
    $('div#select_assets_wrapper').accordion({
        header: 'h2',
        collapsible: true,
        active: false,
    });

    // set up accordion on Assets
    buildAssetAccordion();
});

<|endoftext|>


<commit_before>Markers = new Meteor.Collection('markers');

if (Meteor.isClient) {
  Template.map.rendered = function() {
  L.Icon.Default.imagePath = 'packages/bevanhunt_leaflet/images';

  var map = L.map('map', {
    doubleClickZoom: false
  }).setView([45, -93.2], 12);

  L.tileLayer.provider('MapQuestOpen.OSM').addTo(map);

  var drawnItems = L.featureGroup().addTo(map);

  map.addControl(new L.Control.Draw({
      draw: {
        polyline: false,
				polygon: false,
				circle: false,
				rectangle: false
      },
			edit: {
			  featureGroup: drawnItems,
			  edit: false,
			  remove: false
			}
		}));

		map.on('draw:created', function(event) {
			var layer = event.layer;
			console.log(event.layer);
			console.log(event.layerType);
			Markers.insert({type: event.layerType, latlng: event.layer._latlng});
		});

		map.on('draw:deleted', function(event) {
			var layer = event.layer;
			console.log(event.layer);
			console.log(event.layerType);
		});

  var query = Markers.find();
  query.observe({
    added: function (document) {
      var marker = L.marker(document.latlng).addTo(drawnItems)
        .on('click', function(event) {
          console.log(marker);
        });
    },
    removed: function (oldDocument) {
      layers = map._layers;
      var key, val;
      for (key in layers) {
        val = layers[key];
        if (val._latlng) {
          if (val._latlng.lat === oldDocument.latlng.lat && val._latlng.lng === oldDocument.latlng.lng) {
            map.removeLayer(val);
          }
        }
      }
    }
  });
};

$(function() {
  $(document).ready( function(){
  $('#map').css({height: $(window).height() + 'px'});
});
$(window).resize(function(){$('#map').css({height: $(window).height() + 'px'});});
});
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}
<commit_msg>re-enabling edit/delete<commit_after>Markers = new Meteor.Collection('markers');

if (Meteor.isClient) {
  Template.map.rendered = function() {
  L.Icon.Default.imagePath = 'packages/bevanhunt_leaflet/images';

  var map = L.map('map', {
    doubleClickZoom: false
  }).setView([45, -93.2], 12);

  L.tileLayer.provider('MapQuestOpen.OSM').addTo(map);

  var drawnItems = L.featureGroup().addTo(map);

  map.addControl(new L.Control.Draw({
      draw: {
        polyline: false,
				polygon: false,
				circle: false,
				rectangle: false
      },
			edit: {
			  featureGroup: drawnItems
			}
		}));

		map.on('draw:created', function(event) {
			var layer = event.layer;
			console.log(event.layer);
			console.log(event.layerType);
			Markers.insert({type: event.layerType, latlng: event.layer._latlng});
		});

		map.on('draw:deleted', function(event) {
			var layer = event.layer;
			console.log(event.layer);
			console.log(event.layerType);
		});

  var query = Markers.find();
  query.observe({
    added: function (document) {
      var marker = L.marker(document.latlng).addTo(drawnItems)
        .on('click', function(event) {
          console.log(marker);
        });
    },
    removed: function (oldDocument) {
      layers = map._layers;
      var key, val;
      for (key in layers) {
        val = layers[key];
        if (val._latlng) {
          if (val._latlng.lat === oldDocument.latlng.lat && val._latlng.lng === oldDocument.latlng.lng) {
            map.removeLayer(val);
          }
        }
      }
    }
  });
};

$(function() {
  $(document).ready( function(){
  $('#map').css({height: $(window).height() + 'px'});
});
$(window).resize(function(){$('#map').css({height: $(window).height() + 'px'});});
});
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}
<|endoftext|>


<commit_before>/**
 * Execute it like this:
 * $ mongo -u rultor -p ... ds037688.mongolab.com:37688/pulses rultor-users/src/main/mongo/normalize.js
 */

/**
 * Convert PULSE into COORDINATES.
 */
db.stands.find({coordinates: {"$exists": false}}).forEach(
    function(item) {
        var pulse = item.pulse;
        var owner;
        var rule;
        var scheduled;
        if (/^urn:/.test(pulse)) {
            // urn:facebook:1531296526:rultor-on-commit:2013-08-28T18:05:00Z
            var parts = pulse.split(":");
            owner = [parts[0], parts[1], parts[2]].join(":");
            rule = parts[3];
            scheduled = [parts[4], parts[5], parts[6]].join(":");
        } else if (pulse.indexOf(" ") !== -1) {
            // 2013-08-29T19:25:00Z urn:facebook:1531296526 rultor-on-commit
            var parts = pulse.split(" ");
            owner = parts[1];
            rule = parts[2];
            scheduled = parts[0];
        } else if (/^2013/.test(pulse)) {
            // 2013-08-28T20:35:00Z:urn:facebook:1531296526:rultor-on-commit
            var parts = pulse.split(":");
            owner = [parts[3], parts[4], parts[5]].join(":");
            rule = parts[6];
            scheduled = [parts[0], parts[1], parts[2]].join(":");
        } else {
            print("unrecognized format: " + pulse);
            return;
        }
        db.stands.update(
            { "_id": item._id },
            {
                "$set": {
                    "coordinates": {
                        "owner": owner,
                        "rule": rule,
                        "scheduled": scheduled
                    }
                }
            }
        );
        print("changed " + pulse + " to {owner:" + owner + ", rule:" + rule + ", scheduled:" + scheduled + "}");
    }
);

/**
 * Convert plain-text tags to objects.
 */
db.stands.find({tags: {"$exists": true}}).forEach(
    function(item) {
        var pulse = item.pulse;
        var tags = new Array();
        pulse.tags.forEach(
            function(tag) {
                if (typeof tag === 'string') {
                    tags.push(
                        {
                            "label": tag,
                            "level": "INFO",
                            "data": "{}",
                            "markdown": ""
                        }
                    );
                } else {
                    tags.push(tag);
                }
            }
        );
        db.stands.update(
            { "_id": item._id },
            {
                "$set": {
                    "tags": tags
                }
            }
        );
        print("converted " + tags.length + " tag(s) in " + pulse.coordinates.rule);
    }
);
<commit_msg>#201 normalize.js fixed<commit_after>/**
 * Execute it like this:
 * $ mongo -u rultor -p ... ds037688.mongolab.com:37688/pulses rultor-users/src/main/mongo/normalize.js
 */

/**
 * Convert PULSE into COORDINATES.
 */
db.stands.find({coordinates: {"$exists": false}}).forEach(
    function(item) {
        var pulse = item.pulse;
        var owner;
        var rule;
        var scheduled;
        if (/^urn:/.test(pulse)) {
            // urn:facebook:1531296526:rultor-on-commit:2013-08-28T18:05:00Z
            var parts = pulse.split(":");
            owner = [parts[0], parts[1], parts[2]].join(":");
            rule = parts[3];
            scheduled = [parts[4], parts[5], parts[6]].join(":");
        } else if (pulse.indexOf(" ") !== -1) {
            // 2013-08-29T19:25:00Z urn:facebook:1531296526 rultor-on-commit
            var parts = pulse.split(" ");
            owner = parts[1];
            rule = parts[2];
            scheduled = parts[0];
        } else if (/^2013/.test(pulse)) {
            // 2013-08-28T20:35:00Z:urn:facebook:1531296526:rultor-on-commit
            var parts = pulse.split(":");
            owner = [parts[3], parts[4], parts[5]].join(":");
            rule = parts[6];
            scheduled = [parts[0], parts[1], parts[2]].join(":");
        } else {
            print("unrecognized format: " + pulse);
            return;
        }
        db.stands.update(
            { "_id": item._id },
            {
                "$set": {
                    "coordinates": {
                        "owner": owner,
                        "rule": rule,
                        "scheduled": scheduled
                    }
                }
            }
        );
        print("changed " + pulse + " to {owner:" + owner + ", rule:" + rule + ", scheduled:" + scheduled + "}");
    }
);

/**
 * Convert plain-text tags to objects.
 */
db.stands.find({tags: {"$exists": true}}).forEach(
    function(item) {
        var tags = new Array();
        item.tags.forEach(
            function(tag) {
                if (typeof tag === 'string') {
                    tags.push(
                        {
                            "label": tag,
                            "level": "INFO",
                            "data": "{}",
                            "markdown": ""
                        }
                    );
                } else {
                    tags.push(tag);
                }
            }
        );
        db.stands.update(
            { "_id": item._id },
            {
                "$set": {
                    "tags": tags
                }
            }
        );
        print("converted " + tags.length + " tag(s) in " + item.coordinates.rule);
    }
);
<|endoftext|>


<commit_before>String.prototype.contains = function(it) { return this.indexOf(it) != -1; };

function strStartsWith(str, prefix) {
    return str.indexOf(prefix) === 0;
}

$(document).ready(function () {

	if ($(".postingMode").length == 0) //outside thread
	{
		addThreadHider();
		addThreadExpander();
		hideThreads();
	} else { //in thread
		addThreadUpdater();
	}

	addStylechanger();
	addBacklinks();
	addPostpreview();
	addQuotelinks();
	addImgExpand();

});

function addThreadUpdater()
{

}

function addQuotelinks()
{
	$(".quotePost").click(function () {
		try {
			event.preventDefault();
			var id = $(this).attr("id").substr(1);
			var textarea = $("#postForm textarea[name='com']")[0];
			$(textarea).val($(textarea).val()+'>>'+id+'\n');
		} catch (ex) {

		}
	});
}

function addStylechanger()
{
	$("#stylechangerDiv").css("display", "block");
	$("link[rel='alternate stylesheet']").each(function () {
		$("#stylechanger").append("<option value='"+$(this).attr("href")+"'>"+$(this).attr("title")+"</option>");
	});
	$("#stylechanger").change(function (e) {
		$("#switch").attr("href", e.target.options[e.target.selectedIndex].value);
		$.cookie("style", absolutizeURI(window.location.href, e.target.options[e.target.selectedIndex].value), {expires: 31, path: '/'});
	});

	if (typeof $.cookie("style") !== "undefined")
	{
		$("#switch").attr("href", $.cookie("style"));
	}
}

function addPostpreview()
{
	$("body").append('

');
	$(".quotelink").hover(function () {
		showPostPreview(this);
	}, function () {
		hidePostPreview(this);
	}
	);
}

function addBacklinks()
{
	$(".postMessage").each(function () {

		$(this).append('

');

	});
	$(".quotelink:not(cross)").each(function () {
		var hr = $(this).attr("href");
		var postid = hr.substr(hr.indexOf('#')+2);
		//here
		try {

		if ($("#bl"+postid).html() == "")
		{
			$("#bl"+postid).append("
");
		}
		$("#bl"+postid).append(">>"+$(this).parent(".postMessage").attr("id").substr(1)+" ");
		} catch(ex) {

		}
	});
}

function addThreadExpander()
{

	$(".thread").each(function () {
		$('[+]').insertAfter($("div#"+$(this).attr("id")+" > span.summary")).click(function () {
			var tid = "#"+$(this).attr("id").substr(1);
			var href = absolutizeURI(window.location.href, $(tid).find(".replylink").attr("href"));
			$.ajax({
			type: 'get',
			url: href,
			success: function(data, textStatus, xhr){
				var html = xhr.responseText;
				var nodes = $.parseHTML( html );
				$(tid).html($(tid, nodes).html());
				$('[-]').appendTo($(tid+" div.op div.postInfo")).click(function () {
					var id = $(this).attr("id").substr(2);
					thread_toggle(id);
				});
				$('   [Reply] ').insertAfter($(tid+" div.op span.postNum"));
				$(tid).find("a").each( function () { if ($(this).attr("href") !== null) { $(this).attr("href", absolutizeURI(href, $(this).attr("href"))); } } );
				$(tid).find("img").each( function () { $(this).attr("src", absolutizeURI(href, $(this).attr("src")));  } );
				addBacklinks();
				addPostpreview();

				}
			});
		});
	});
}

function addThreadHider()
{
	$(".op .postInfo").each(function () {
		var id = $(this).attr("id").substr(2);
		$(this).append(' [-]');
	});

	$(".hider").click(function () {
		var id = $(this).attr("id").substr(2);
		thread_toggle(id);
	});
}

function showPostPreview( el )
{
	var href = $(el).attr("href").split("#");
	var curl = window.location.href.split("#");
	curl = curl[0];
	href = absolutizeURI(curl, href[0]);
	if (href == curl)
	{
		var hr = $(el).attr("href");
		var postid = hr.substr(hr.indexOf('#'));
		$("#quote-preview").html($(postid).html());
		var off = $( el ).offset();
		off.left = off.left + $(el).width();
		off.top = off.top - $("#quote-preview").height()/2
		$("#quote-preview").css("display", "block");
				$("#quote-preview").find("a").each( function () { if ($(this).attr("href") !== null) { $(this).attr("href", absolutizeURI(href, $(this).attr("href"))); } } );
				$("#quote-preview").find("img").each( function () { $(this).attr("src", absolutizeURI(href, $(this).attr("src")));  } );
		$("#quote-preview").offset(off);
	} else {
		$.ajax({
			type: 'get',
			url: href,
			success: function(data, textStatus, xhr){
				var html = xhr.responseText;
				var nodes = $.parseHTML( html );
				var hr = $(el).attr("href");
				var postid = hr.substr(hr.indexOf('#'));
				$("#quote-preview").html($(postid, nodes).html());
				var off = $( el ).offset();
				off.left = off.left + $(el).width();
				off.top = off.top - $("#quote-preview").height()/2
				$("#quote-preview").css("display", "block");
				$("#quote-preview").find("a").each( function () { if ($(this).attr("href") !== null) { $(this).attr("href", absolutizeURI(href, $(this).attr("href"))); } } );
				$("#quote-preview").find("img").each( function () { $(this).attr("src", absolutizeURI(href, $(this).attr("src")));  } );
				$("#quote-preview").offset(off);
			}
		});
	}
}

function hidePostPreview( el )
{

	$("#quote-preview").css("display", "none");
	$("#quote-preview").offset({top: "0px", left: "0px"});
	$("#quote-preview").html("");

}

function hideThreads()
{
	$.each(document.cookie.split(/; */), function()  {
		var splitCookie = this.split('=');
		// name is splitCookie[0], value is splitCookie[1]
		if (strStartsWith(splitCookie[0], "h_"))
		{
			var id = splitCookie[0].substr(2);
			if (splitCookie[1] == 1)
			{
				hideThread(id);
			}
		}
	});
}

function hideThread(id)
{
	$("#pc"+id+" .file").css("display", "none");
	$("#m"+id).css("display", "none");
	$("#et"+id).css("display", "none");
	$("#t"+id).find(".replyContainer").css("display", "none");
	$("#t"+id).find("span.summary").css("display", "none");
	$("#ht"+id).html("[+]");
}

function showThread(id)
{
	$("#pc"+id+" .file").css("display", "block");
	$("#m"+id).css("display", "block");
	$("#et"+id).css("display", "inline");
	$("#t"+id).find(".replyContainer").css("display", "block");
	$("#t"+id).find("span.summary").css("display", "inline");
	$("#ht"+id).html("[-]");
}

function thread_toggle(id)
{
	if (typeof $.cookie("h_"+id) === "undefined")
	{
		$.cookie("h_"+id, 1, {expires: 31});
		hideThread(id);
	} else {
		if ($.cookie("h_"+id) == 1)
		{

			$.cookie("h_"+id, 0, {expires: 31});
			showThread(id);
		} else {
			$.cookie("h_"+id, 1, {expires: 31});
			hideThread(id);
		}
	}
}

function addImgExpand()
{
	$(".fileThumb").click(function (e) {
		imgExpand($(this).parent());
		e.preventDefault();
	});
}

function imgExpand(element)
{
	$(element).children(".fileThumb").css("opacity", "0.7");
	var id = $(element).attr("id");
	$(element).append("");
	$("#x"+id).bind("load", function () {
		var iw = $('body').innerWidth();
		$(element).children(".fileThumb").css("opacity", "").css("display", "none");
		$(this).css("display", "");
		$(this).css("width", Math.max($(this).width, (iw-40))+"px");
		$(this).css("height", "auto");
		$(this).css("max-width", "auto");
		$(this).css("max-height", "auto");
		addZoom(this);
	});
}

function imgThumbnail(element)
{
	$(element).siblings(".fileThumb").css("display", "");
	$(element).remove();
}

var targetImageWidth = 0;
var targetDiagonal = 0;
var targetDragging = false;
function addZoom(img) {
	$(img).mousedown(function(e) {
		if (e.button == 0) {
			targetImageWidth = $(this).width();
			var rc = e.target.getBoundingClientRect();
			var p = Math.pow;
			var dragSize = p(p(e.clientX-rc.left, 2)+p(e.clientY-rc.top, 2), .5);
			targetDiagonal = Math.round(dragSize);
			targetDragging = false;
			e.preventDefault();
		}
	});
	$(img).mousemove(function(e) {
		if (targetDiagonal){
			var rc = e.target.getBoundingClientRect();
			var p = Math.pow;
			var dragSize = p(p(e.clientX-rc.left, 2)+p(e.clientY-rc.top, 2), .5);
			var newDiagonal = Math.round(dragSize);
			var oldDiagonal = targetDiagonal;
			var imageWidth = targetImageWidth;
			var newWidth = Math.max(250, newDiagonal/oldDiagonal*imageWidth)+'px';
			$(this).css("width", newWidth);
			$(this).css("maxWidth", newWidth);

			$(this).css("maxHeight", "");
			$(this).css("height", "auto");

			targetDragging = true;
		}
	});
	$(img).mouseout(function(e) {
		targetDiagonal = 0;
	});
	$(img).mouseup(function(e) {
		if (targetDiagonal) {
			var rc = e.target.getBoundingClientRect();
			var p = Math.pow;
			var dragSize = p(p(e.clientX-rc.left, 2)+p(e.clientY-rc.top, 2), .5);
			var newDiagonal = Math.round(dragSize);
			var oldDiagonal = targetDiagonal;
			var imageWidth = targetImageWidth;
			var newWidth = Math.max(250, newDiagonal/oldDiagonal*imageWidth)+'px';
			//$(this).width(newWidth);
			$(this).css("width", newWidth);
			$(this).css("maxWidth", newWidth);

		}
	});
	$(img).click(function(e) {
		targetDiagonal = 0;
		if (targetDragging) {
			targetDragging = false;
			e.preventDefault();
			return false;
		}
	});

	$(img).dblclick(function (e) {
		imgThumbnail(this);
	});
}

/*
 * ==============================
 * | URI manipulation functions |
 * ==============================
 */
function parseURI(url) {
  var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
  // authority = '//' + user + ':' + pass '@' + hostname + ':' port
  return (m ? {
    href     : m[0] || '',
    protocol : m[1] || '',
    authority: m[2] || '',
    host     : m[3] || '',
    hostname : m[4] || '',
    port     : m[5] || '',
    pathname : m[6] || '',
    search   : m[7] || '',
    hash     : m[8] || ''
  } : null);
}

function absolutizeURI(base, href) {// RFC 3986

  function removeDotSegments(input) {
    var output = [];
    input.replace(/^(\.\.?(\/|$))+/, '')
         .replace(/\/(\.(\/|$))+/g, '/')
         .replace(/\/\.\.$/, '/../')
         .replace(/\/?[^\/]*/g, function (p) {
      if (p === '/..') {
        output.pop();
      } else {
        output.push(p);
      }
    });
    return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
  }

  href = parseURI(href || '');
  base = parseURI(base || '');

  return !href || !base ? null : (href.protocol || base.protocol) +
         (href.protocol || href.authority ? href.authority : base.authority) +
         removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +
         (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
         href.hash;
}<commit_msg>Javascripts [FIXED!]<commit_after>String.prototype.contains = function(it) { return this.indexOf(it) != -1; };

function strStartsWith(str, prefix) {
    return str.indexOf(prefix) === 0;
}

$(document).ready(function () {

	if ($(".postingMode").length == 0) //outside thread
	{
		addThreadHider();
		addThreadExpander();
		hideThreads();
	} else { //in thread
		addThreadUpdater();
	}

	addStylechanger();
	addBacklinks("body");
	addPostpreview("body");
	addImgExpand("body");
	addQuotelinks();

});

function addThreadUpdater()
{

}

function addQuotelinks()
{
	$(".quotePost").click(function () {
		try {
			event.preventDefault();
			var id = $(this).attr("id").substr(1);
			var textarea = $("#postForm textarea[name='com']")[0];
			$(textarea).val($(textarea).val()+'>>'+id+'\n');
		} catch (ex) {

		}
	});
}

function addStylechanger()
{
	$("#stylechangerDiv").css("display", "block");
	$("link[rel='alternate stylesheet']").each(function () {
		$("#stylechanger").append("<option value='"+$(this).attr("href")+"'>"+$(this).attr("title")+"</option>");
	});
	$("#stylechanger").change(function (e) {
		$("#switch").attr("href", e.target.options[e.target.selectedIndex].value);
		$.cookie("style", absolutizeURI(window.location.href, e.target.options[e.target.selectedIndex].value), {expires: 31, path: '/'});
	});

	if (typeof $.cookie("style") !== "undefined")
	{
		$("#switch").attr("href", $.cookie("style"));
	}
}

function addPostpreview(parent)
{
	$("body").append('

');
	$(parent).find(".quotelink").hover(function () {
		showPostPreview(this);
	}, function () {
		hidePostPreview(this);
	}
	);
}

function addBacklinks(parent)
{
	$(parent).find(".postMessage").each(function () {

		$(this).append('

');

	});
	$(".quotelink:not(cross)").each(function () {
		var hr = $(this).attr("href");
		var postid = hr.substr(hr.indexOf('#')+2);
		//here
		try {

		if ($("#bl"+postid).html() == "")
		{
			$("#bl"+postid).append("
");
		}
		$("#bl"+postid).append(">>"+$(this).parent(".postMessage").attr("id").substr(1)+" ");
		} catch(ex) {

		}
	});
}

function addThreadExpander()
{

	$(".thread").each(function () {
		$('[+]').insertAfter($("div#"+$(this).attr("id")+" > span.summary")).click(function () {
			var tid = "#"+$(this).attr("id").substr(1);
			var href = absolutizeURI(window.location.href, $(tid).find(".replylink").attr("href"));
			$.ajax({
			type: 'get',
			url: href,
			success: function(data, textStatus, xhr){
				var html = xhr.responseText;
				var nodes = $.parseHTML( html );
				$(tid).html($(tid, nodes).html());
				$('[-]').appendTo($(tid+" div.op div.postInfo")).click(function () {
					var id = $(this).attr("id").substr(2);
					thread_toggle(id);
				});
				$('   [Reply] ').insertAfter($(tid+" div.op span.postNum"));
				$(tid).find("a").each( function () { if ($(this).attr("href") !== null) { $(this).attr("href", absolutizeURI(href, $(this).attr("href"))); } } );
				$(tid).find("img").each( function () { $(this).attr("src", absolutizeURI(href, $(this).attr("src")));  } );

				addBacklinks(tid);
				addPostpreview(tid);
				addImgExpand(tid);

				}
			});
		});
	});
}

function addThreadHider()
{
	$(".op .postInfo").each(function () {
		var id = $(this).attr("id").substr(2);
		$(this).append(' [-]');
	});

	$(".hider").click(function () {
		var id = $(this).attr("id").substr(2);
		thread_toggle(id);
	});
}

function showPostPreview( el )
{
	var href = $(el).attr("href").split("#");
	var curl = window.location.href.split("#");
	curl = curl[0];
	href = absolutizeURI(curl, href[0]);
	if (href == curl)
	{
		var hr = $(el).attr("href");
		var postid = hr.substr(hr.indexOf('#'));
		$("#quote-preview").html($(postid).html());
		var off = $( el ).offset();
		off.left = off.left + $(el).width();
		off.top = off.top - $("#quote-preview").height()/2
		$("#quote-preview").css("display", "block");
				$("#quote-preview").find("a").each( function () { if ($(this).attr("href") !== null) { $(this).attr("href", absolutizeURI(href, $(this).attr("href"))); } } );
				$("#quote-preview").find("img").each( function () { $(this).attr("src", absolutizeURI(href, $(this).attr("src")));  } );
		$("#quote-preview").offset(off);
	} else {
		$.ajax({
			type: 'get',
			url: href,
			success: function(data, textStatus, xhr){
				var html = xhr.responseText;
				var nodes = $.parseHTML( html );
				var hr = $(el).attr("href");
				var postid = hr.substr(hr.indexOf('#'));
				$("#quote-preview").html($(postid, nodes).html());
				var off = $( el ).offset();
				off.left = off.left + $(el).width();
				off.top = off.top - $("#quote-preview").height()/2
				$("#quote-preview").css("display", "block");
				$("#quote-preview").find("a").each( function () { if ($(this).attr("href") !== null) { $(this).attr("href", absolutizeURI(href, $(this).attr("href"))); } } );
				$("#quote-preview").find("img").each( function () { $(this).attr("src", absolutizeURI(href, $(this).attr("src")));  } );
				$("#quote-preview").offset(off);
			}
		});
	}
}

function hidePostPreview( el )
{

	$("#quote-preview").css("display", "none");
	$("#quote-preview").offset({top: "0px", left: "0px"});
	$("#quote-preview").html("");

}

function hideThreads()
{
	$.each(document.cookie.split(/; */), function()  {
		var splitCookie = this.split('=');
		// name is splitCookie[0], value is splitCookie[1]
		if (strStartsWith(splitCookie[0], "h_"))
		{
			var id = splitCookie[0].substr(2);
			if (splitCookie[1] == 1)
			{
				hideThread(id);
			}
		}
	});
}

function hideThread(id)
{
	$("#pc"+id+" .file").css("display", "none");
	$("#m"+id).css("display", "none");
	$("#et"+id).css("display", "none");
	$("#t"+id).find(".replyContainer").css("display", "none");
	$("#t"+id).find("span.summary").css("display", "none");
	$("#ht"+id).html("[+]");
}

function showThread(id)
{
	$("#pc"+id+" .file").css("display", "block");
	$("#m"+id).css("display", "block");
	$("#et"+id).css("display", "inline");
	$("#t"+id).find(".replyContainer").css("display", "block");
	$("#t"+id).find("span.summary").css("display", "inline");
	$("#ht"+id).html("[-]");
}

function thread_toggle(id)
{
	if (typeof $.cookie("h_"+id) === "undefined")
	{
		$.cookie("h_"+id, 1, {expires: 31});
		hideThread(id);
	} else {
		if ($.cookie("h_"+id) == 1)
		{

			$.cookie("h_"+id, 0, {expires: 31});
			showThread(id);
		} else {
			$.cookie("h_"+id, 1, {expires: 31});
			hideThread(id);
		}
	}
}

function addImgExpand(parent)
{
	$(parent).find(".fileThumb").click(function (e) {
		imgExpand($(this).parent());
		e.preventDefault();
	});
}

function imgExpand(element)
{
	$(element).children(".fileThumb").css("opacity", "0.7");
	var id = $(element).attr("id");
	$(element).append("");
	$("#x"+id).bind("load", function () {
		var iw = $('body').innerWidth();
		$(element).children(".fileThumb").css("opacity", "").css("display", "none");
		$(this).css("display", "");
		var newWidth = Math.min($(this).width(), (iw-100));
		$(this).css("width", newWidth+"px");
		$(this).css("max-width", newWidth+"px");
		$(this).css("height", "auto");
		$(this).css("max-height", "auto");
		addZoom(this);
	});
	$("#x"+id).bind("error", function () {
		$(element).children(".fileThumb").css("opacity", "");
		$(this).remove();
	});
}

function imgThumbnail(element)
{
	$(element).siblings(".fileThumb").css("display", "");
	$(element).remove();
}

var targetImageWidth = 0;
var targetDiagonal = 0;
var targetDragging = false;
function addZoom(img) {
	$(img).mousedown(function(e) {
		if (e.button == 0) {
			targetImageWidth = $(this).width();
			var rc = e.target.getBoundingClientRect();
			var p = Math.pow;
			var dragSize = p(p(e.clientX-rc.left, 2)+p(e.clientY-rc.top, 2), .5);
			targetDiagonal = Math.round(dragSize);
			targetDragging = false;
			e.preventDefault();
		}
	});
	$(img).mousemove(function(e) {
		if (targetDiagonal){
			var rc = e.target.getBoundingClientRect();
			var p = Math.pow;
			var dragSize = p(p(e.clientX-rc.left, 2)+p(e.clientY-rc.top, 2), .5);
			var newDiagonal = Math.round(dragSize);
			var oldDiagonal = targetDiagonal;
			var imageWidth = targetImageWidth;
			var newWidth = Math.max(250, newDiagonal/oldDiagonal*imageWidth)+'px';
			$(this).css("width", newWidth);
			$(this).css("maxWidth", newWidth);

			$(this).css("maxHeight", "");
			$(this).css("height", "auto");

			targetDragging = true;
		}
	});
	$(img).mouseout(function(e) {
		targetDiagonal = 0;
	});
	$(img).mouseup(function(e) {
		if (targetDiagonal) {
			var rc = e.target.getBoundingClientRect();
			var p = Math.pow;
			var dragSize = p(p(e.clientX-rc.left, 2)+p(e.clientY-rc.top, 2), .5);
			var newDiagonal = Math.round(dragSize);
			var oldDiagonal = targetDiagonal;
			var imageWidth = targetImageWidth;
			var newWidth = Math.max(250, newDiagonal/oldDiagonal*imageWidth)+'px';
			//$(this).width(newWidth);
			$(this).css("width", newWidth);
			$(this).css("maxWidth", newWidth);

		}
	});
	$(img).click(function(e) {
		targetDiagonal = 0;
		if (targetDragging) {
			targetDragging = false;
			e.preventDefault();
			return false;
		}
	});

	$(img).dblclick(function (e) {
		imgThumbnail(this);
	});
}

/*
 * ==============================
 * | URI manipulation functions |
 * ==============================
 */
function parseURI(url) {
  var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
  // authority = '//' + user + ':' + pass '@' + hostname + ':' port
  return (m ? {
    href     : m[0] || '',
    protocol : m[1] || '',
    authority: m[2] || '',
    host     : m[3] || '',
    hostname : m[4] || '',
    port     : m[5] || '',
    pathname : m[6] || '',
    search   : m[7] || '',
    hash     : m[8] || ''
  } : null);
}

function absolutizeURI(base, href) {// RFC 3986

  function removeDotSegments(input) {
    var output = [];
    input.replace(/^(\.\.?(\/|$))+/, '')
         .replace(/\/(\.(\/|$))+/g, '/')
         .replace(/\/\.\.$/, '/../')
         .replace(/\/?[^\/]*/g, function (p) {
      if (p === '/..') {
        output.pop();
      } else {
        output.push(p);
      }
    });
    return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
  }

  href = parseURI(href || '');
  base = parseURI(base || '');

  return !href || !base ? null : (href.protocol || base.protocol) +
         (href.protocol || href.authority ? href.authority : base.authority) +
         removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +
         (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
         href.hash;
}<|endoftext|>