text:
/**
 * Created by guy.kaufman on 25/03/2017.
 */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define('anyLogger',factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.AnyLogger = factory();
    }

}(this, function () {
    var loggers = {};
    var consts = {};
    var loggerCount = 0;
    var plugins = [];

    var defaultMessageFormatter = function(message, data) {
        if (data) {
            if (data.scope) {
                message = "[" + data.scope + "]" + message;
            }
            if (data.module) {
                message = "[" + data.module + "]" + message;
            }
            if (data.date) {
                message = "[" + data.date.toISOString() + "]" + message;
            }
        }
        return message;
    };

    // CreateConsoleHandler returns a window console handler object;
    var createConsoleHandler = function () {
        return {
            type: 'console',
            write: (typeof console === "undefined") ? function () { /* no console */ } :
                function (message, level) {
                    var handler;
                    if (level === consts.logLevels.WARN && console.warn) {
                        handler = console.warn;
                    } else if (level === consts.logLevels.ERROR && console.error) {
                        handler = console.error;
                    } else if (level === consts.logLevels.INFO && console.info) {
                        handler = console.info;
                    } else if (level === consts.logLevels.DEBUG && console.debug) {
                        handler = console.debug;
                    }
                    if (handler) {
                        handler.call(console, message, {noCollect: true});
                    }
                }
        };
    };

    var AnyLogger = function(config) {
        this.settings = {};
        this.handlers = [];
        this.capturedLogs = [];
        this.id = config.id;
        this.settings.captureLogsLimit = consts.defaultCaptureLogsLimit;
        var self = this;

        if (config.captureLogs)
        {
            if (config.captureLogsLimit)
            {
                this.captureLogsLimit(config.captureLogsLimit);
            };
            this.flushCapturedLogsOnLimit(config.flushCapturedLogsOnLimit);
            this.flushCapturedLogsOnError(config.flushCapturedLogsOnError);
            this.captureLogs(true);
        }
        if (config.logToConsole != false)
        {
            this.handlers.push(createConsoleHandler());
        }

        plugins.forEach(function(plugin)
        {
            plugin.create(self, config);
        });
        if (config.handlers)
        {
            config.handlers.forEach(self.addHandler.bind(self));
        }
        if (config.formatter)
        {
            this.formatter = config.formatter;
        }
        else if (config.useFormatter != false) {
            this.formatter = defaultMessageFormatter;
        }
        if (config.logLevel)
        {
            this.logLevel(config.logLevel);
        }
        else
        {
            this.logLevel(consts.defaultLogLevel);
        }
        if (config.module)
        {
            this.settings.module = config.module;
        }
        if (config.collect)
        {
            collect.call(this);
        }
    };

    var prototype = AnyLogger.prototype;

    // Changes the instance logging level and returns the logging level.
    prototype.logLevel = function (newLevel) {
        if (typeof newLevel === 'string' && newLevel.toUpperCase() in consts.logLevels) //case string as an input
        {
            this.settings.logLevel = consts.logLevels[newLevel.toUpperCase()];
        }
        else if (newLevel && newLevel.name in consts.logLevels) //case object as an input
        {
            this.settings.logLevel = consts.logLevels[newLevel.name];
        }
        return this.settings.logLevel ? this.settings.logLevel.name : null;
    };

    prototype.captureLogs = function(capture)
    {
        this.settings.captureLogs = capture;
    };

    prototype.captureLogsLimit = function(limit)
    {
        this.settings.captureLogsLimit = limit;
    };

    prototype.flushCapturedLogsOnLimit = function(flushCapturedLogsOnLimit)
    {
        this.settings.flushCapturedLogsOnLimit = flushCapturedLogsOnLimit;
    };

    prototype.flushCapturedLogsOnError = function (flushCapturedLogsOnError) {
        this.settings.flushCapturedLogsOnError = flushCapturedLogsOnError;
    };

    prototype.debug = function (message, data, cb) {
        return this.trigger(message, consts.logLevels.DEBUG, data, cb);
    };

    prototype.info = function (message, data, cb) {
        return this.trigger(message, consts.logLevels.INFO, data, cb);
    };

    prototype.warn = function (message, data, cb) {
        return this.trigger(message, consts.logLevels.WARN, data, cb);
    };

    prototype.error = function (message, data, cb) {
        return this.trigger(message, consts.logLevels.ERROR, data, cb);
    };

    prototype.trigger = function (message, level, data, cb) {
        var parsedData;
        parsedData = data || {};
        parsedData.module = parsedData.module || this.settings.module;
        parsedData.date = new Date();
        if (message && this.formatter)
        {
            message = this.formatter(message, parsedData);
        }
        if (this.settings.captureLogs)
        {
            if (this.settings.flushCapturedLogsOnError && level.value >= consts.logLevels.ERROR.value)
            {
                this.flushCapturedLogs(this.settings.flushCapturedLogsOnError.logLevel, this.settings.flushCapturedLogsOnError.handlerTypes);
            }
            else
            {
                this.capturedLogs.push({
                    message: message,
                    level: level,
                    data: parsedData
                });
                if (this.capturedLogs.length >= this.settings.captureLogsLimit)
                {
                    if (this.settings.flushCapturedLogsOnLimit)
                    {
                        this.flushCapturedLogs(this.settings.flushCapturedLogsOnLimit.logLevel, this.settings.flushCapturedLogsOnLimit.handlerTypes);
                    }
                    else {
                        this.capturedLogs.shift();
                    }
                }
            }

        }
        if (enabledFor.call(this,level))
        {
            if (this.handlers && this.handlers.constructor === Array) {
                this.handlers.forEach(function(handler)
                {
                    if (!isCollected(data) || handler.type != 'console') { //don't log to console messages that were collected from there.
                        write(handler, message, level, parsedData, cb);
                    }
                });
            }
        }
        else
		{
            if (cb){
            	cb(false);
			}
		}
    };

    prototype.getCapturedLogs = function()
    {
        return this.capturedLogs;
    };

    prototype.flushCapturedLogs = function(logLevel, handlerTypes, cb)
    {
    	var level;
    	var self = this;
    	var writeCount = 0;
        level = consts.logLevels[logLevel.toUpperCase()]
    	if (!level)
		{
            level = consts.defaultFlushLogLevel;
		}
        this.capturedLogs.forEach(function(log)
		{
            if (log.level.value >= level.value)
			{
                writeCount++;
                if (handlerTypes) {
                    handlerTypes.forEach(function (handlerType) {
                        write(self.getHandlerByType(handlerType), log.message, log.level, log.data);
                    });
                }
			}
        });
        this.capturedLogs = [];
        if (cb) {
            cb(writeCount);
        }

    };

    prototype.getHandlerByType = function (type) {
        var handlerRet;
        this.handlers.some(function (handler) {
            if (handler.type === type)
            {
                handlerRet = handler;
                return true;
            }
        });
        return handlerRet;
    };

    prototype.getHandlerTypes = function () {
        return this.handlers.map(function (handler) {
        	return handler.type;
        });
    };

    prototype.addHandler = function(handler)
    {
        if (typeof handler === 'function')
        {
            this.handlers.push({type: 'custom', write: handler});
        }
        else {
            this.handlers.push(handler);
        }
    };

    var write = function(handler, message, level, data, cb)
	{
	    if (!handler)
        {
            return;
        }
        if (handler.asyncWrite)
        {
            handler.asyncWrite(message, level, data, function(){if (cb){cb(true)};});
        }
        else
        {
            handler.write(message, level, data);
            if (cb){
                cb(true);
            }
        }
	};

    var collect = function() {
        var self = this;
        if (console.log) {
            var oldLog = console.log;
            console.log = function (message, data) {
                if (!data || !data.noCollect) {
                    self.trigger(message, consts.logLevels.DEBUG, {collected: true});
                }
                oldLog.apply(console, arguments);
            }
        }
        if (console.debug) {
            var oldDebug = console.debug;
            console.debug = function (message, data) {
                if (!data || !data.noCollect) {
                    self.trigger(message, consts.logLevels.DEBUG, {collected: true});
                }
                oldDebug.apply(console, arguments);
            }
        }
        if (console.info) {
            var oldInfo = console.info;
            console.info = function (message, data) {
                if (!data || !data.noCollect) {
                    self.trigger(message, consts.logLevels.INFO, {collected: true});
                }
                oldInfo.apply(console, arguments);
            }
        }
        if (console.warn)
        {
            var oldWarn = console.warn;
            console.warn = function(message, data){
                if (!data || !data.noCollect) {
                    self.trigger(message, consts.logLevels.WARN, {collected: true});
                }
                oldWarn.apply(console, arguments);
            }
        }
        if (console.error) {
            var oldError = console.error;
            console.error = function (message, data) {
                if (!data || !data.noCollect) {
                    self.trigger(message, consts.logLevels.ERROR, {collected: true});
                }
                oldError.apply(console, arguments);
            }
        }
        window.onerror = function (msg, url, lineNo, columnNo, error) {
            var message = [
                'Message: ' + msg,
                'URL: ' + url,
                'Line: ' + lineNo,
                'Column: ' + columnNo
            ];
            if (error && error.stack)
            {
                message.push('Stack: ' + error.stack);
            }
            message = message.join(' - ');
            self.trigger(message, consts.logLevels.ERROR, {collected: true});
        }
    };

    var isCollected = function(data)
    {
        return data && data.collected;
    };

    var enabledFor = function (level) {
        var logLevel = this.settings.logLevel;
        return level.value >= logLevel.value;
    };

    var create = function(config)
    {
        if (!config)
        {
            config = {id: 'logger' + loggerCount};
        }
        else if (!config.id)
        {
            config.id = 'logger' + loggerCount;
        }
        var logger = new AnyLogger(config);
        loggers[logger.id] = logger;
        loggerCount++;
        return logger;
    };

    var getLoggerById = function (id) {
        return loggers[id]
    };

    var addPlugin = function(plugin)
    {
        if (!plugin || typeof plugin.create != 'function')
        {
            return;
        }
        plugins.push(plugin);
    }

    consts.logLevels = {};
    consts.logLevels.DEBUG = {value: 1, name: 'DEBUG'};
    consts.logLevels.INFO = {value: 2, name: 'INFO'};
    consts.logLevels.WARN = {value: 4, name: 'WARN'};
    consts.logLevels.ERROR = {value: 5, name: 'ERROR'};
    consts.logLevels.FATAL = {value: 9, name: 'FATAL'};
    consts.logLevels.OFF = {value: 10, name: 'OFF'};
    consts.defaultLogLevel = consts.logLevels.OFF;
    consts.defaultFlushLogLevel = consts.logLevels.DEBUG;
    consts.defaultCaptureLogsLimit = 1000;

    return {
        create: create,
        getLoggerById: getLoggerById,
        consts: consts,
        addPlugin: addPlugin
    };
}));
/**
 * Created by guy.kaufman on 25/03/2017.
 */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define('htmlHandler',factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.HTMLHandler = factory();
    }

}(this, function () {
    var createHtmlHandler = function(anyLogger, settings)
    {
        if (!settings.logToHtml)
        {
            return;
        }
        var logContainer;
        var logTable;
        var logBody;
        var sortable;
        var order = 0;

        var createSortable = function()
        {
            // ** taken from 'https://github.com/HubSpot/sortable'
			// MIT License - Copyright (C) 2013 Adam Schwartz, http://adamschwartz.co
            // ** sortable.js content -- START
            var SELECTOR, addEventListener, clickEvents, numberRegExp, sortable, touchDevice, trimRegExp;

            SELECTOR = 'table[data-sortable]';

            numberRegExp = /^-?[£$¤]?[\d,.]+%?$/;

            trimRegExp = /^\s+|\s+$/g;

            clickEvents = ['click'];

            touchDevice = 'ontouchstart' in document.documentElement;

            if (touchDevice) {
                clickEvents.push('touchstart');
            }

            addEventListener = function(el, event, handler) {
                if (el.addEventListener != null) {
                    return el.addEventListener(event, handler, false);
                } else {
                    return el.attachEvent("on" + event, handler);
                }
            };

            sortable = {
                init: function(options) {
                    var table, tables, _i, _len, _results;
                    if (options == null) {
                        options = {};
                    }
                    if (options.selector == null) {
                        options.selector = SELECTOR;
                    }
                    tables = document.querySelectorAll(options.selector);
                    _results = [];
                    for (_i = 0, _len = tables.length; _i < _len; _i++) {
                        table = tables[_i];
                        _results.push(sortable.initTable(table));
                    }
                    return _results;
                },
                initTable: function(table) {
                    var i, th, ths, _i, _len, _ref;
                    if (((_ref = table.tHead) != null ? _ref.rows.length : void 0) !== 1) {
                        return;
                    }
                    if (table.getAttribute('data-sortable-initialized') === 'true') {
                        return;
                    }
                    table.setAttribute('data-sortable-initialized', 'true');
                    ths = table.querySelectorAll('th');
                    for (i = _i = 0, _len = ths.length; _i < _len; i = ++_i) {
                        th = ths[i];
                        if (th.getAttribute('data-sortable') !== 'false') {
                            sortable.setupClickableTH(table, th, i);
                        }
                    }
                    return table;
                },
                setupClickableTH: function(table, th, i) {
                    var eventName, onClick, type, _i, _len, _results;
                    type = sortable.getColumnType(table, i);
                    onClick = function(e) {
                        var compare, item, newSortedDirection, position, row, rowArray, sorted, sortedDirection, tBody, ths, value, _compare, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _m, _ref, _ref1;
                        if (e.handled !== true) {
                            e.handled = true;
                        } else {
                            return false;
                        }
                        sorted = this.getAttribute('data-sorted') === 'true';
                        sortedDirection = this.getAttribute('data-sorted-direction');
                        if (sorted) {
                            newSortedDirection = sortedDirection === 'ascending' ? 'descending' : 'ascending';
                        } else {
                            newSortedDirection = type.defaultSortDirection;
                        }
                        ths = this.parentNode.querySelectorAll('th');
                        for (_i = 0, _len = ths.length; _i < _len; _i++) {
                            th = ths[_i];
                            th.setAttribute('data-sorted', 'false');
                            th.removeAttribute('data-sorted-direction');
                        }
                        this.setAttribute('data-sorted', 'true');
                        this.setAttribute('data-sorted-direction', newSortedDirection);
                        tBody = table.tBodies[0];
                        rowArray = [];
                        if (!sorted) {
                            if (type.compare != null) {
                                _compare = type.compare;
                            } else {
                                _compare = function(a, b) {
                                    return b - a;
                                };
                            }
                            compare = function(a, b) {
                                if (a[0] === b[0]) {
                                    return a[2] - b[2];
                                }
                                if (type.reverse) {
                                    return _compare(b[0], a[0]);
                                } else {
                                    return _compare(a[0], b[0]);
                                }
                            };
                            _ref = tBody.rows;
                            for (position = _j = 0, _len1 = _ref.length; _j < _len1; position = ++_j) {
                                row = _ref[position];
                                value = sortable.getNodeValue(row.cells[i]);
                                if (type.comparator != null) {
                                    value = type.comparator(value);
                                }
                                rowArray.push([value, row, position]);
                            }
                            rowArray.sort(compare);
                            for (_k = 0, _len2 = rowArray.length; _k < _len2; _k++) {
                                row = rowArray[_k];
                                tBody.appendChild(row[1]);
                            }
                        } else {
                            _ref1 = tBody.rows;
                            for (_l = 0, _len3 = _ref1.length; _l < _len3; _l++) {
                                item = _ref1[_l];
                                rowArray.push(item);
                            }
                            rowArray.reverse();
                            for (_m = 0, _len4 = rowArray.length; _m < _len4; _m++) {
                                row = rowArray[_m];
                                tBody.appendChild(row);
                            }
                        }
                        if (typeof window['CustomEvent'] === 'function') {
                            return typeof table.dispatchEvent === "function" ? table.dispatchEvent(new CustomEvent('Sortable.sorted', {
                                bubbles: true
                            })) : void 0;
                        }
                    };
                    _results = [];
                    for (_i = 0, _len = clickEvents.length; _i < _len; _i++) {
                        eventName = clickEvents[_i];
                        _results.push(addEventListener(th, eventName, onClick));
                    }
                    return _results;
                },
                getColumnType: function(table, i) {
                    var row, specified, text, type, _i, _j, _len, _len1, _ref, _ref1, _ref2;
                    specified = (_ref = table.querySelectorAll('th')[i]) != null ? _ref.getAttribute('data-sortable-type') : void 0;
                    if (specified != null) {
                        return sortable.typesObject[specified];
                    }
                    _ref1 = table.tBodies[0].rows;
                    for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
                        row = _ref1[_i];
                        text = sortable.getNodeValue(row.cells[i]);
                        _ref2 = sortable.types;
                        for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
                            type = _ref2[_j];
                            if (type.match(text)) {
                                return type;
                            }
                        }
                    }
                    return sortable.typesObject.alpha;
                },
                getNodeValue: function(node) {
                    var dataValue;
                    if (!node) {
                        return '';
                    }
                    dataValue = node.getAttribute('data-value');
                    if (dataValue !== null) {
                        return dataValue;
                    }
                    if (typeof node.innerText !== 'undefined') {
                        return node.innerText.replace(trimRegExp, '');
                    }
                    return node.textContent.replace(trimRegExp, '');
                },
                setupTypes: function(types) {
                    var type, _i, _len, _results;
                    sortable.types = types;
                    sortable.typesObject = {};
                    _results = [];
                    for (_i = 0, _len = types.length; _i < _len; _i++) {
                        type = types[_i];
                        _results.push(sortable.typesObject[type.name] = type);
                    }
                    return _results;
                }
            };

            sortable.setupTypes([
                {
                    name: 'numeric',
                    defaultSortDirection: 'descending',
                    match: function(a) {
                        return a.match(numberRegExp);
                    },
                    comparator: function(a) {
                        return parseFloat(a.replace(/[^0-9.-]/g, ''), 10) || 0;
                    }
                }, {
                    name: 'date',
                    defaultSortDirection: 'ascending',
                    reverse: true,
                    match: function(a) {
                        return !isNaN(Date.parse(a));
                    },
                    comparator: function(a) {
                        return Date.parse(a) || 0;
                    }
                }, {
                    name: 'alpha',
                    defaultSortDirection: 'ascending',
                    match: function() {
                        return true;
                    },
                    compare: function(a, b) {
                        return a.localeCompare(b);
                    }
                }
            ]);
            return sortable;

            // ** sortable.js content -- END
        };

        var sortTable = function(column)
        {
            logTable.tHead.getElementsByTagName('th')[column].click();
        }

        var filterTable = function(filterValue)
        {
            var td;
            var remainedRowsCount = 0;
            var filter;
            if (typeof filterValue === 'string')
            {
                filter = filterValue;
            }
            else
            {
                var input = document.getElementById("log-table-filter");
                filter = input.value;
            }
            filter = filter.toUpperCase();
            var tr = logBody.getElementsByTagName("tr");

            // Loop through all table rows, and hide those who don't match the search query
            for (var i = 0; i < tr.length; i++) {
                td = tr[i].getElementsByTagName("td");
                for (var j = 0; j < td.length; j++) {
                    if (td[j]) {
                        if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
                            tr[i].style.display = "";
                            remainedRowsCount++;
                            break;
                        } else if (j ===  td.length - 1){
                            tr[i].style.display = "none";
                        }
                    }
                }
            }
            return remainedRowsCount;
        }

        var createTable = function()
        {
            var tableStyle = document.createElement('style');
            logContainer.appendChild(tableStyle);
            tableStyle.innerHTML =
                "#log-table{border-collapse: collapse; height: 100%; width: 100%; display: block;}" +
                ".log-table-row td{border: 1px solid black;} " +
                ".log-table-row:nth-child(even){background-color: #d3d3d3}" +
                ".log-table-row:hover {background-color: #ffffe0}" +
                ".log-table-header {background-color: #90ee90;}" +
                ".log-table-header th[data-sortable='false']{cursor: auto;}" +
                ".log-table-header th{border: 1px solid black; cursor: pointer;}" +
                ".log-table-header th[data-sorted='true']:after {visibility: visible;}" +
                ".log-table-header th[data-sorted-direction='descending']:after {border-top-color: inherit;margin-top: 8px;}" +
                ".log-table-header th[data-sorted-direction='ascending']:after {border-bottom-color: inherit;margin-top: 3px;}" +
                ".log-table-header th:after {content: ''; visibility: hidden;	display: inline-block; vertical-align: inherit; height: 0; width: 0; border-width: 5px;	border-style: solid; border-color: transparent;	margin-right: 1px; margin-left: 10px; float: right;}" +
                "#log-table-filter {font-size: 16px; padding: 5px 5px 5px 10px; border: 1px solid #ddd; margin: 0 0 12px 0;}" +
                "#log-table-clear {padding: 4px 32px; display: inline-block; cursor: pointer; font-size: 16px; margin: 0 16px 12px 0}"

            var logTableClear = document.createElement('button');
            logTableClear.innerHTML = 'Clear'
            logTableClear.setAttribute('id', 'log-table-clear');
            logTableClear.addEventListener("click", clearTable);
            logContainer.appendChild(logTableClear);

            var logTableFilter = document.createElement('input');
            logTableFilter.setAttribute('type', 'text');
            logTableFilter.setAttribute('id', 'log-table-filter');
            logTableFilter.setAttribute('placeholder', 'Filter');
            logTableFilter.addEventListener("keyup", filterTable);
            logContainer.appendChild(logTableFilter);

            logTable = document.createElement('table');
            logTable.id = "log-table";
            logTable.innerHTML = '<thead class="log-table-header"><tr><th>Order</th><th>Date</th><th>Module</th><th>Scope</th><th style="width:100%;">Message</th><th>Level</th></tr></thead><tbody class="log-table-body"></tbody>'
            logContainer.appendChild(logTable);
            logBody = logTable.tBodies[0];
            sortable = createSortable();
            sortable.initTable(logTable);
        }

        var clearTable = function()
        {
            order = 0;
            logBody.innerHTML = '';
        }

        var parseNotUndefined = function(str)
        {
            if (str)
            {
                return str;
            }
            return '';
        }

        var drawTableRow = function(module, scope, message, level, date)
        {
            var newRow = logBody.insertRow(-1);
            newRow.className = 'log-table-row';
            newRow.innerHTML = '<td>' + order + '</td><td>' + date.toLocaleString() + '</td><td>' + parseNotUndefined(module) + '</td><td>' + parseNotUndefined(scope) + '</td><td>' + parseNotUndefined(message) + '</td><td>' + level.name + '</td>';
            order++;
        }

        if (settings.logToHtml.container)
        {
            logContainer = settings.logToHtml.container;
        }
        else
        {
            logContainer = document.createElement('div');
            logContainer.style['width'] = '100%';
            logContainer.style['z-index'] = '9999999';
            document.body.appendChild(logContainer);
        }
        createTable();
        anyLogger.addHandler({
            type: 'html',
            write: function(message, level, data) {
                drawTableRow(data.module, data.scope, message, level, data.date)
            },
            sort: sortTable,
            filter: filterTable,
            clear: clearTable
        });
    };

    return {create: createHtmlHandler};

}));
/**
 * Created by guy.kaufman on 25/03/2017.
 */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define('serviceHandler',factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.ServiceHandler = factory();
    }

}(this, function () {
    var consts = {};

    var createServiceHandler = function (anyLogger, settings) {
        var _settings = {};
        var _logRows = [];
        var _interval;
        var _sentCount = 0;

        var initSettings = settings.logToService;

        if (!initSettings || !initSettings.loggingUrl)
        {
            return;
        }

        var init = function (initSettings) {
            if (!initSettings.headers)
            {
                _settings.headers = [consts.defaultServiceHeaders];
            }
            else if (initSettings.headers instanceof Array)
            {
                _settings.headers = initSettings.headers;
            }
            else {
                _settings.headers = [initSettings.headers];
            }

            if (initSettings.timeframe != undefined)
            {
                _settings.sendBy = 'timeframe';
                if (initSettings.timeframe > consts.minTimeframe)
                {
                    _settings.timeframe = initSettings.timeframe;
                }
                else {
                    _settings.timeframe = consts.minTimeframe;
                }
            }
            else {
                _settings.sendBy = 'batchSize';
            }

            if (initSettings.flushOnWindowClose || initSettings.flushOnWindowClose=== undefined)
            {
                flushOnWindowClose();
            }
            _settings.timeframe = _settings.timeframe * 60 * 1000; // convert to milliseconds
            _settings.loggingUrl = initSettings.loggingUrl;
            _settings.batchSize = initSettings.batchSize || consts.defaultBatchSize;
            _settings.timeout = initSettings.timeout || consts.defaultTimeout;
            _settings.requestParser = initSettings.requestParser;

            if (_settings.sendBy === 'timeframe')
            {
                _interval = setInterval(flush, _settings.timeframe, false);
            }
        }

        var writeRow = function(module, scope, message, level, date)
        {
            _logRows.push({
                message: message,
                level: level.name,
                module: module,
                scope: scope,
                date: date
            });
            if (_settings.sendBy === 'batchSize')
            {
                if (_logRows.length >= _settings.batchSize) {
                    send(_logRows);
                }
            }
        };

        var send = function(logRows) {
            if (logRows.length < 1)
            {
                return;
            }
            var xhr = new XMLHttpRequest();
            xhr.open('POST', _settings.loggingUrl, true);

            _settings.headers.forEach(function(header){
                xhr.setRequestHeader(
                    Object.keys(header)[0],
                    header[Object.keys(header)[0]]
                );
            });

            var data;
            if (_settings.requestParser)
            {
                data = JSON.stringify(_settings.requestParser(logRows));
            }
            else
            {
                data = JSON.stringify(logRows);
            }
            xhr.send(data);
            _logRows = [];
            _sentCount++;
        };

        var flush = function()
        {
            send(_logRows);
        }

        var destroy = function()
        {
            clearInterval(_interval);
        };

        var flushOnWindowClose = function()
        {
            window.onbeforeunload = function () {
                flush();
            };
        }

        init(initSettings);

        anyLogger.addHandler({
            type: 'service',
            write: function(message, level, data) {
                writeRow(data.module, data.scope, message, level, data.date)
            },
            flush: flush,
            rowsCount: function(){return _logRows.length;},
            sentCount: function(){return _sentCount;},
            destroy: destroy
        });
    };

    return {create: createServiceHandler};

    consts.defaultServiceHeaders = { 'Content-Type' : 'application/json' };
    consts.defaultTimeout = 2000;
    consts.defaultBatchSize = 1000;
    consts.minTimeframe = 0.1; //min of 6 sec for each send request

}));
/**
 * Created by guy.kaufman on 25/03/2017.
 */
(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define('anyLoggerMax',['./anyLogger', './htmlHandler', './serviceHandler'], factory);
    } else if (typeof exports === 'object') {
        module.exports = factory();
    } else {
        root.AnyLoggerMax = factory(root.AnyLogger, root.HTMLHandler, root.ServiceHandler);
    }

}(this, function (anyLogger, htmlHandler, serviceHandler) {
    anyLogger.addPlugin(htmlHandler);
    anyLogger.addPlugin(serviceHandler);
    return anyLogger;
}));


text:
static Window *s_main_window;
static TextLayer *s_output_layer;
static Layer *s_selection_layer;
static Layer *s_canvas_layer;

static uint8_t rgb_values[3];
static char color_text_buffer[11];
static uint8_t channel_index;

static char* uint2str(uint8_t value) {
  switch(value) {
    case 0: return "00";
    case 1: return "01";
    case 2: return "10";
    case 3: return "11";
    default: return "XX";
  }
}

static void canvas_update_proc(Layer *layer, GContext *ctx) {
  GRect bounds = layer_get_bounds(layer);

  // Draw the color
  graphics_context_set_fill_color(ctx, (GColor8){
    .a = ALPHA,
    .r = rgb_values[R],
    .g = rgb_values[G],
    .b = rgb_values[B]
  });
  graphics_fill_rect(ctx, GRect(0, 0, bounds.size.w, bounds.size.h), 0, GCornerNone);
}

static void selection_update_proc(Layer *layer, GContext *ctx) {
  graphics_context_set_fill_color(ctx, GColorBlack);
  graphics_fill_rect(ctx, layer_get_bounds(layer), 0, GCornerNone);
}

static void update_display() {
  // Update color
  layer_mark_dirty(s_canvas_layer);

  // Update string
  snprintf(color_text_buffer, sizeof(color_text_buffer), "0b11%s%s%s",
    uint2str(rgb_values[R]), uint2str(rgb_values[G]), uint2str(rgb_values[B]));
  text_layer_set_text(s_output_layer, color_text_buffer);

  // Selection box location
  switch(channel_index) {
    case R:
      layer_set_frame(s_selection_layer, GRect(62, 20, 18, 4));
      break;
    case G:
      layer_set_frame(s_selection_layer, GRect(80, 20, 18, 4));
      break;
    case B:
      layer_set_frame(s_selection_layer, GRect(98, 20, 18, 4));
      break;
    default: break;
  }
}

static void up_click_handler(ClickRecognizerRef recognizer, void *context) {
  if(rgb_values[channel_index] < CHANNEL_MAX) {
    rgb_values[channel_index]++;
  }

  update_display();
}

static void down_click_handler(ClickRecognizerRef recognizer, void *context) {
  if(rgb_values[channel_index] > 0) {
    rgb_values[channel_index]--;
  }

  update_display();
}

static void select_click_handler(ClickRecognizerRef recognizer, void *context) {
  // Cycle selected channel
  channel_index++;
  if(channel_index == CHANNEL_MAX) {
    channel_index = R;
  }

  update_display();
}

static void click_config_provider(void *context) {
  window_single_click_subscribe(BUTTON_ID_UP, up_click_handler);
  window_single_click_subscribe(BUTTON_ID_DOWN, down_click_handler);
  window_single_click_subscribe(BUTTON_ID_SELECT, select_click_handler);
}

static void main_window_load(Window *window) {
  Layer *window_layer = window_get_root_layer(window);
  GRect window_bounds = layer_get_bounds(window_layer);

  s_canvas_layer = layer_create(GRect(0, 0, window_bounds.size.w, window_bounds.size.h));
  layer_set_update_proc(s_canvas_layer, canvas_update_proc);
  layer_add_child(window_layer, s_canvas_layer);

  s_output_layer = text_layer_create(GRect(0, -6, window_bounds.size.w, 30));
  text_layer_set_text_color(s_output_layer, GColorBlack);
  text_layer_set_background_color(s_output_layer, GColorWhite);
  text_layer_set_text_alignment(s_output_layer, GTextAlignmentCenter);
  text_layer_set_font(s_output_layer, fonts_get_system_font(FONT_KEY_GOTHIC_24));
  layer_add_child(window_layer, text_layer_get_layer(s_output_layer));

  s_selection_layer = layer_create(GRect(0, 0, 0, 0));
  layer_set_update_proc(s_selection_layer, selection_update_proc);
  layer_add_child(window_layer, s_selection_layer);
}

static void main_window_unload(Window *window) {
  text_layer_destroy(s_output_layer);
  layer_destroy(s_canvas_layer);
  layer_destroy(s_selection_layer);
}

static void init() {
  s_main_window = window_create();
#ifdef PBL_SDK_2
  window_set_fullscreen(s_main_window, true);
#endif
  window_set_click_config_provider(s_main_window, click_config_provider);
  window_set_window_handlers(s_main_window, (WindowHandlers) {
    .load = main_window_load,
    .unload = main_window_unload,
  });
  window_stack_push(s_main_window, true);

  // First color
  rgb_values[R] = 0;
  rgb_values[G] = 0;
  rgb_values[B] = 0;
  update_display();
}

static void deinit() {
  window_destroy(s_main_window);
}

int main() {
  init();
  app_event_loop();
  deinit();
}

redpajama_set_name: RedPajamaGithub


text:
package org.simpleflatmapper.reflect.test.setter;

import org.junit.Test;
import org.simpleflatmapper.reflect.ReflectionService;
import org.simpleflatmapper.reflect.TypeAffinity;
import org.simpleflatmapper.reflect.meta.ClassMeta;
import org.simpleflatmapper.reflect.meta.DefaultPropertyNameMatcher;
import org.simpleflatmapper.reflect.meta.PropertyFinder;
import org.simpleflatmapper.reflect.meta.PropertyMeta;
import org.simpleflatmapper.reflect.meta.SubPropertyMeta;
import org.simpleflatmapper.reflect.setter.AppendCollectionSetter;
import org.simpleflatmapper.util.Predicate;
import org.simpleflatmapper.util.TypeReference;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class Issue451Test {

    @Test
    public void testPropertyFinderAndAppendSetter() {

        ClassMeta<List<Foo>> classMeta = ReflectionService.newInstance().getClassMeta(new TypeReference<List<Foo>>() {
        }.getType());

        PropertyFinder.PropertyFilter predicate = PropertyFinder.PropertyFilter.trueFilter();

        PropertyFinder<List<Foo>> finder = classMeta.newPropertyFinder();

        SubPropertyMeta f = (SubPropertyMeta)finder.findProperty(DefaultPropertyNameMatcher.of("b_f"), new Object[0], (TypeAffinity)null, predicate);
        assertNotNull(f);
        SubPropertyMeta n = (SubPropertyMeta)finder.findProperty(DefaultPropertyNameMatcher.of("b_n"), new Object[0], (TypeAffinity)null, predicate);

        assertEquals(AppendCollectionSetter.class, n.getOwnerProperty().getSetter().getClass());

    }

    public static class Foo {
        public int f;
        public String n;
    }
}


text:
package com.zuehlke.carrera.javapilot.services;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import com.zuehlke.carrera.javapilot.akka.JavaPilotActor;
import com.zuehlke.carrera.javapilot.config.PilotProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;

/**
 * Manages the carrera pilot instance.
 */
@Service
@EnableScheduling
public class PilotService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PilotService.class);

    private final PilotProperties settings;

    private final ActorSystem system;
    private final ActorRef pilotActor;
    private final String endPointUrl;

    @Autowired
    public PilotService(PilotProperties settings, EndpointService endpointService,
                        SimulatorService simulatorService ){
        this.settings = settings;
        this.endPointUrl = endpointService.getHttpEndpoint();
        system = ActorSystem.create(settings.getName());
        pilotActor = system.actorOf(JavaPilotActor.props(settings));

        // Simulator learns about the pilot
        simulatorService.registerPilot(pilotActor);

        // Pilot learns about the simulator
        pilotActor.tell(new PilotToRaceTrackConnector(simulatorService.getSystem()), ActorRef.noSender());
    }

    //@PostConstruct
    public void connectToRelay () {
        PilotToRelayConnection pilotToRelayConnection = new PilotToRelayStompConnection(
                settings.getRelayUrl(),
                settings.getName(),
                "admin",
                "admin",
                (startMessage) -> pilotActor.tell(startMessage, pilotActor),
                (stopMessage) -> pilotActor.tell(stopMessage, pilotActor),
                (sensorEvent) -> pilotActor.tell(sensorEvent, pilotActor),
                (velocityMessage) -> pilotActor.tell(velocityMessage, pilotActor),
                (penaltyMessage) -> pilotActor.tell(penaltyMessage, pilotActor));

        pilotActor.tell(pilotToRelayConnection, ActorRef.noSender());
    }

    @Scheduled(fixedRate = 2000)
    public void ensureConnection() {
        pilotActor.tell("ENSURE_CONNECTION", ActorRef.noSender());
    }

    @Scheduled(fixedRate = 1000)
    public void announce() {
        pilotActor.tell(new EndpointAnnouncement(endPointUrl), ActorRef.noSender());
    }

    @PreDestroy
    public void shutdown () {
        LOGGER.info("Shutting down the actor system.");
        system.shutdown();

    }

    public void registerConnection(PilotToRelayConnection pilot) {
        if ( pilot != null ) {
            pilotActor.tell(pilot, ActorRef.noSender());
        }
    }

    public ActorRef getPilotActor() {
        return pilotActor;
    }
}


text:
import argparse
import logging
import numpy as np
import os
import random
import socket
import torch

from gtd.io import save_stdout
from gtd.utils import Config
from strategic_exploration.hrl.training_run import HRLTrainingRuns
from os.path import abspath, dirname, join

# CONFIGS ARE MERGED IN THE FOLLOWING ORDER:
# 1. configs in args.config_paths, from left to right
# 2. task config
# 3. config_strings

arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-c', '--check_commit', default='strict')
arg_parser.add_argument('-d', '--description', default='None.')
arg_parser.add_argument('-n', '--name', default='unnamed')
arg_parser.add_argument('-r', '--seed', default=0, type=int)
arg_parser.add_argument('-x', '--reward_configs', action='append', default=[])
arg_parser.add_argument('config_paths', nargs='+')
args = arg_parser.parse_args()

random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)

# create run
runs = HRLTrainingRuns(check_commit=(args.check_commit == 'strict'))

config_paths = args.config_paths
if len(config_paths) == 1 and config_paths[0].isdigit():
  configs = [Config.from_file(p) for p in args.reward_configs]
  run = runs.clone(int(config_paths[0]), configs, args.name)
else:
  # new run according to configs
  configs = [Config.from_file(p) for p in config_paths]

  # merge all configs together
  config = Config.merge(configs)  # later configs overwrite earlier configs
  run = runs.new(config, name=args.name)  # new run from config

  run.metadata['description'] = args.description
  run.metadata['name'] = args.name

run.metadata['host'] = socket.gethostname()

# start training
run.workspace.add_file('stdout', 'stdout.txt')
run.workspace.add_file('stderr', 'stderr.txt')

with save_stdout(run.workspace.root):
  try:
    run.train()
  finally:
    run.close()


text:
package ru.job4j.musicCourt.dao;

public class ExceptionDAO extends Exception {

    public ExceptionDAO() {
        super();
    }

    public ExceptionDAO(String message) {
        super(message);
    }

    public ExceptionDAO(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
namespace {
// Rather than sending all import items over IPC at once we chunk them into
// separate requests.  This avoids the case of a large import causing
// oversized IPC messages.
const int kNumBookmarksToSend = 100;
const int kNumHistoryRowsToSend = 100;
const int kNumFaviconsToSend = 100;
}

ExternalProcessImporterBridge::ExternalProcessImporterBridge(
    const DictionaryValue& localized_strings,
    IPC::Sender* sender,
    base::TaskRunner* task_runner)
    : sender_(sender),
      task_runner_(task_runner) {
  // Bridge needs to make its own copy because OS 10.6 autoreleases the
  // localized_strings value that is passed in (see http://crbug.com/46003 ).
  localized_strings_.reset(localized_strings.DeepCopy());
}

void ExternalProcessImporterBridge::AddBookmarks(
    const std::vector<ProfileWriter::BookmarkEntry>& bookmarks,
    const string16& first_folder_name) {
  Send(new ProfileImportProcessHostMsg_NotifyBookmarksImportStart(
      first_folder_name, bookmarks.size()));

  std::vector<ProfileWriter::BookmarkEntry>::const_iterator it;
  for (it = bookmarks.begin(); it < bookmarks.end();
       it = it + kNumBookmarksToSend) {
    std::vector<ProfileWriter::BookmarkEntry> bookmark_group;
    std::vector<ProfileWriter::BookmarkEntry>::const_iterator end_group =
        it + kNumBookmarksToSend < bookmarks.end() ?
        it + kNumBookmarksToSend : bookmarks.end();
    bookmark_group.assign(it, end_group);

    Send(new ProfileImportProcessHostMsg_NotifyBookmarksImportGroup(
        bookmark_group));
  }
}

void ExternalProcessImporterBridge::AddHomePage(const GURL& home_page) {
  NOTIMPLEMENTED();
}

#if defined(OS_WIN)
void ExternalProcessImporterBridge::AddIE7PasswordInfo(
    const IE7PasswordInfo& password_info) {
  NOTIMPLEMENTED();
}
#endif

void ExternalProcessImporterBridge::SetFavicons(
    const std::vector<history::ImportedFaviconUsage>& favicons) {
  Send(new ProfileImportProcessHostMsg_NotifyFaviconsImportStart(
    favicons.size()));

  std::vector<history::ImportedFaviconUsage>::const_iterator it;
  for (it = favicons.begin(); it < favicons.end();
       it = it + kNumFaviconsToSend) {
    std::vector<history::ImportedFaviconUsage> favicons_group;
    std::vector<history::ImportedFaviconUsage>::const_iterator end_group =
        std::min(it + kNumFaviconsToSend, favicons.end());
    favicons_group.assign(it, end_group);

  Send(new ProfileImportProcessHostMsg_NotifyFaviconsImportGroup(
      favicons_group));
  }
}

void ExternalProcessImporterBridge::SetHistoryItems(
    const history::URLRows& rows,
    history::VisitSource visit_source) {
  Send(new ProfileImportProcessHostMsg_NotifyHistoryImportStart(rows.size()));

  history::URLRows::const_iterator it;
  for (it = rows.begin(); it < rows.end();
       it = it + kNumHistoryRowsToSend) {
    history::URLRows row_group;
    history::URLRows::const_iterator end_group =
        it + kNumHistoryRowsToSend < rows.end() ?
        it + kNumHistoryRowsToSend : rows.end();
    row_group.assign(it, end_group);

    Send(new ProfileImportProcessHostMsg_NotifyHistoryImportGroup(row_group,
         visit_source));
  }
}

void ExternalProcessImporterBridge::SetKeywords(
    const std::vector<TemplateURL*>& template_urls,
    bool unique_on_host_and_path) {
  Send(new ProfileImportProcessHostMsg_NotifyKeywordsReady(template_urls,
      unique_on_host_and_path));
  STLDeleteContainerPointers(template_urls.begin(), template_urls.end());
}

void ExternalProcessImporterBridge::SetPasswordForm(
    const content::PasswordForm& form) {
  Send(new ProfileImportProcessHostMsg_NotifyPasswordFormReady(form));
}

void ExternalProcessImporterBridge::NotifyStarted() {
  Send(new ProfileImportProcessHostMsg_Import_Started());
}

void ExternalProcessImporterBridge::NotifyItemStarted(
    importer::ImportItem item) {
  Send(new ProfileImportProcessHostMsg_ImportItem_Started(item));
}

void ExternalProcessImporterBridge::NotifyItemEnded(importer::ImportItem item) {
  Send(new ProfileImportProcessHostMsg_ImportItem_Finished(item));
}

void ExternalProcessImporterBridge::NotifyEnded() {
  // The internal process detects import end when all items have been received.
}

string16 ExternalProcessImporterBridge::GetLocalizedString(int message_id) {
  string16 message;
  localized_strings_->GetString(base::IntToString(message_id), &message);
  return message;
}

ExternalProcessImporterBridge::~ExternalProcessImporterBridge() {}

void ExternalProcessImporterBridge::Send(IPC::Message* message) {
  task_runner_->PostTask(
      FROM_HERE,
      base::Bind(&ExternalProcessImporterBridge::SendInternal,
                 this, message));
}

void ExternalProcessImporterBridge::SendInternal(IPC::Message* message) {
  DCHECK(task_runner_->RunsTasksOnCurrentThread());
  sender_->Send(message);
}


text:
import java.util.*;

class WrongBounds {
  class LL<T> extends ArrayList<List<T>> {}
  class Wrap<T extends List<List<?>>> extends ArrayList<T> {}
  class Wrong<T extends LL<?>> extends Wrap<T> {} // error
}


text:
@class ReaderContentView;
@class ReaderContentPage;
@class ReaderContentThumb;

@protocol ReaderContentViewDelegate <NSObject>

@required // Delegate protocols

- (void)contentView:(ReaderContentView *)contentView touchesBegan:(NSSet *)touches;

@end

@interface ReaderContentView : UIScrollView

@property (nonatomic, weak, readwrite) id <ReaderContentViewDelegate> message;

- (instancetype)initWithFrame:(CGRect)frame fileURL:(NSURL *)fileURL page:(NSUInteger)page password:(NSString *)phrase;
- (instancetype)initWithFrame:(CGRect)frame fileURL:(NSURL *)fileURL page:(NSUInteger)page password:(NSString *)phrase doublePage:(BOOL)doublePage;

- (void)showPageThumb:(NSURL *)fileURL page:(NSInteger)page password:(NSString *)phrase guid:(NSString *)guid;

- (id)processSingleTap:(UITapGestureRecognizer *)recognizer;

- (void)zoomIncrement:(UITapGestureRecognizer *)recognizer;
- (void)zoomDecrement:(UITapGestureRecognizer *)recognizer;
- (void)zoomResetAnimated:(BOOL)animated;

@end

#pragma mark -

//
//	ReaderContentThumb class interface
//

@interface ReaderContentThumb : ReaderThumbView

@end


text:
@implementation RNAppHub

RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(initAppHubWithServer:(NSString *) rootURL applicationID:(NSString *) applicationID) {
    [AppHub setRootURL:rootURL];
    [AppHub setApplicationID:applicationID];
    [AppHub buildManager].automaticPollingEnabled = NO; // control polling build in JS
}

RCT_EXPORT_METHOD(initAppHub:(NSString *) applicationID) {
    [AppHub setApplicationID:applicationID];
    [AppHub buildManager].automaticPollingEnabled = NO; // control polling build in JS
}

RCT_EXPORT_METHOD(setRootURL:(NSString *) rootURL) {
    [AppHub setRootURL:rootURL];
}

RCT_EXPORT_METHOD(setAutomaticPollingEnabled:(BOOL) toggle) {
    [AppHub buildManager].automaticPollingEnabled = toggle;
}

RCT_EXPORT_METHOD(setApplicationID:(NSString *) applicationID) {
    [AppHub setApplicationID:applicationID];
}

RCT_REMAP_METHOD(fetchBuild,
                 resolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject) {

    AHReachability *reachability = [[AppHub sharedManager] reachability];

    if (([reachability isReachableViaWiFi] || ([reachability isReachableViaWWAN] && [AppHub buildManager].cellularDownloadsEnabled)) &&
        [AppHub applicationID]) {
            AHBuild *cachedBuild = [AppHub buildManager].currentBuild;

            [[AppHub buildManager] fetchBuildWithCompletionHandler:^(AHBuild *result, NSError *error) {
                // If the `result` AHBuild is not nil, then it is guaranteed
                // to be the most up-to-date build of the app.
                if (result != nil) {
                    resolve(@[cachedBuild.identifier, result.identifier, result.buildDescription]);
                } else {
                    NSError *error =
                    reject(@"fetchError", @"Cannot fetch builds", error);
                }
            }];
    } else {
        reject(@"fetchError", @"Network not under right condition", nil);
    }
}

@end


text:
set enable_nestloop=false;
DELETE FROM foo USING BAR WHERE foo.a = bar.a AND (bar.a = 10 or bar.a = 40000 or bar.a = 20000);


text:
This is a school project for my Simulation class.

The goal of the class is to learn how to  model and simulate systems, so for
this I choose to do a basic simulation of how packets are sent through networks.

My work is based greatly on the "Networking Tutorial" by Ben Eater on YouTube.
Great tutorial!
https://www.youtube.com/playlist?list=PLowKtXNTBypH19whXTVoG3oKSuOcw_XeW

Due to the amount of time available to complete the project we are keeping it
as simple as posible.


text:
// |reftest| skip-if(!xulRuntime.shell||Android) slow -- no results reported.
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//-----------------------------------------------------------------------------
var BUGNUMBER = 336409;
var summary = 'Integer overflow in js_obj_toSource';
var actual = 'No Crash';
var expect = 'No Crash';

printBugNumber(BUGNUMBER);
printStatus (summary);

expectExitCode(0);
expectExitCode(5);

function createString(n)
{
  var l = n*1024*1024;
  var r = 'r';

  while (r.length < l)
  {
    r = r + r;
  }
  return r;
}

try
{
  var n = 64;
  printStatus('Creating ' + n + 'MB string');
  var r = createString(n);
  printStatus('Done. length = ' + r.length);
  printStatus('Creating object');
  var o = {f1: r, f2: r, f3: r,f4: r,f5: r, f6: r, f7: r, f8: r,f9: r};
  printStatus('object.toSource()');
  var rr = o.toSource();
  printStatus('Done.');
}
catch(ex)
{
  expect = 'InternalError: allocation size overflow';
  actual = ex + '';
  print(actual);
}

reportCompare(expect, actual, summary);


text: Monitor IO Queues in TSAR architecture


text:
@interface UIView (TYAutoLayout)

- (void)addConstraintToView:(UIView *)view edageInset:(UIEdgeInsets)edageInset;

- (void)addConstarintWithView:(UIView *)view topView:(UIView *)topView leftView:(UIView *)leftView
                   bottomView:(UIView *)bottomView rightView:(UIView *)rightView edageInset:(UIEdgeInsets)edageInset;

- (void)addConstarintWithLeftView:(UIView *)leftView toRightView:(UIView *)rightView constarint:(CGFloat)constarint;

- (NSLayoutConstraint *)addConstarintWithTopView:(UIView *)topView toBottomView:(UIView *)bottomView constarint:(CGFloat)constarint;

- (void)addConstarintWidth:(CGFloat)width height:(CGFloat)height;

- (void)addConstarintEqualWithView:(UIView *)view widthToView:(UIView *)wView heightToView:(UIView *)hView;

- (NSLayoutConstraint *)addConstraintCenterYToView:(UIView *)yView constant:(CGFloat)constant;

- (void)addConstraintCenterXToView:(UIView *)xView CenterYToView:(UIView *)yView;

- (void)removeConstraintWithAttribte:(NSLayoutAttribute)attr;

- (void)removeConstraintWithView:(UIView *)view attribte:(NSLayoutAttribute)attr;

- (void)removeAllConstraints;

@end


text: ![infrastructure](docs/infrastructure-diagram.jpg)


text:
function Evolution() {

    var self = this;

    self.grid = null;

    self.create = function(grid) {
        self.grid = grid;
        self.addCellNeighbours();
    };

    self.addCellNeighbours = function() {
        self.grid.callAll(function(cell) {
            var nb = self.grid.cellNeighbours(cell.x, cell.y);
            var nbAlive = nb.reduce(function(previous, cell) {
                 return previous + (cell.alive ? 1 : 0);
            }, 0);
            cell.setNeighbours(nb);
            cell.setNeighboursAliveCount(nbAlive);
        });
    };

    self.analyse = function(strategy) {
        var commands = [];
        self.grid.callAll(function(cell) {
            var command = strategy(cell);
            if (command) {
                commands.push(command);
            }
        });
        return commands;
    };

    self.update = function(commands) {
        commands.forEach(function(cell) {
            switch(cell.action) {
                case 'D':
                    cell.die();
                    break;

                case 'S':
                    cell.spawn();
                    break;

                case 'L':
                    break;

                default:
                    throw new Error("Illegal command: " + cell.action);
            }
        });
    };
};


text:
void export (void)
{
    char *home = getenv("HOME");//path to home folder
    char fileName[] = {"R_functions.R"};
    char path[] = {"Desktop/"};
    char output[Max];
    char heapIn[Max];
    char heapOut[Max];
    char heapfy[Max];
    char xAxis[Max];
    char queueIn[Max];
    char queueOut[Max];
    char diffIn[Max];
    char diffOut[Max];
    char inRange[Max];
    char outRange[Max];
    char diffRange[Max];
    char heapfyRange[Max];
    char yAxis[Max];

    snprintf(output, sizeof(output)/sizeof(char), "%s/%s%s", home, path, fileName);

    FILE *file = fopen(output, "w");

    //heapIn
    sprintf(heapIn, "heapIn<-c(%lld,%lld,%lld,%lld,%lld);", _individualHpEnqueueAccess[0], _individualHpEnqueueAccess[1], _individualHpEnqueueAccess[2], _individualHpEnqueueAccess[3], _individualHpEnqueueAccess[4]);
    //heapOut
    sprintf(heapOut, "heapOut<-c(%lld,%lld,%lld,%lld,%lld);", _individualHpDequeueAcess[0], _individualHpDequeueAcess[1], _individualHpDequeueAcess[2], _individualHpDequeueAcess[3], _individualHpDequeueAcess[4]);
    //heapfy
    sprintf(heapfy, "heapfy<-c(%lld,%lld,%lld,%lld,%lld);", _individualHpHeapfyAcess[0], _individualHpHeapfyAcess[1], _individualHpHeapfyAcess[2], _individualHpHeapfyAcess[3], _individualHpHeapfyAcess[4]);
    //xAxis
    sprintf(xAxis, "xAxis<-c(%d,%d,%d,%d,%d);", cases[0], cases[1], cases[2], cases[3], cases[4]);
    //queueIn
    sprintf(queueIn, "queueIn<-c(%lld,%lld,%lld,%lld,%lld);", _individualPriorityQueueEnqueueAccess[0], _individualPriorityQueueEnqueueAccess[1], _individualPriorityQueueEnqueueAccess[2], _individualPriorityQueueEnqueueAccess[3], _individualPriorityQueueEnqueueAccess[4]);
    //queueOut
    sprintf(queueOut, "queueOut<-c(%lld,%lld,%lld,%lld,%lld);", _individualPriorityQueueDequeueAcess[0], _individualPriorityQueueDequeueAcess[1], _individualPriorityQueueDequeueAcess[2], _individualPriorityQueueDequeueAcess[3], _individualPriorityQueueDequeueAcess[4]);
    //diffIn
    long long int diff10 = _individualPriorityQueueEnqueueAccess[0] - (_individualHpEnqueueAccess[0] + _individualHpHeapfyAcess[0]);
    long long int diff100 = _individualPriorityQueueEnqueueAccess[1] - (_individualHpEnqueueAccess[1] + _individualHpHeapfyAcess[1]);
    long long int diff1000 = _individualPriorityQueueEnqueueAccess[2] - (_individualHpEnqueueAccess[2] + _individualHpHeapfyAcess[2]);
    long long int diff10000 = _individualPriorityQueueEnqueueAccess[3] - (_individualHpEnqueueAccess[3] + _individualHpHeapfyAcess[3]);
    long long int diff100000 = _individualPriorityQueueEnqueueAccess[4] - (_individualHpEnqueueAccess[4] + _individualHpHeapfyAcess[4]);
    sprintf(diffIn, "diffIn<-c(%lld,%lld,%lld,%lld,%lld);", diff10, diff100, diff1000, diff10000, diff100000);
    //diffOut
    diff10 = _individualPriorityQueueDequeueAcess[0] - _individualHpDequeueAcess[0];
    diff100 = _individualPriorityQueueDequeueAcess[1] - _individualHpDequeueAcess[1];
    diff1000 = _individualPriorityQueueDequeueAcess[2] - _individualHpDequeueAcess[2];
    diff10000 = _individualPriorityQueueDequeueAcess[3] - _individualHpDequeueAcess[3];
    diff100000 = _individualPriorityQueueDequeueAcess[4] - _individualHpDequeueAcess[4];
    sprintf(diffOut, "diffOut<-c(%lld,%lld,%lld,%lld,%lld);", diff10, diff100, diff1000, diff10000, diff100000);
    //inRange
    sprintf(inRange, "inRange<-range(0, heapIn, queueIn);");
    //outRange
    sprintf(outRange, "outRange<-range(0, heapOut, queueOut);");
    //diffRange
    sprintf(diffRange, "diffRange<-range(0, diffIn, diffOut);");
    //heapfyRange
    sprintf(heapfyRange, "heapfyRange<-range(0,heapfy);");

    //objects definition
    char objects[Max*20];
    sprintf(objects, "%s%s%s%s%s%s%s%s%s%s%s%s", heapIn, heapOut, heapfy, xAxis, queueIn, queueOut, diffIn, diffOut, inRange, outRange, diffRange, heapfyRange);

    //enqueue graph
    char enqueuePlot[Max];
    sprintf(enqueuePlot, "plot(heapIn,type=%co%c,col=%cblue%c,ylim=inRange,ann=FALSE,axes=FALSE);", 34, 34, 34, 34);
    char enqueueTitle[Max*3];
    sprintf(enqueueTitle, "title(main=%cEnqueueing%c,col.main=%cblack%c,font.main=4);title(xlab=%cnumber of objects%c,col.lab=rgb(0,0.5,0));title(ylab=%cn of processes%c,col.lab=rgb(0,0.5,0));", 34, 34, 34, 34, 34, 34, 34, 34);
    char enqueueLines[Max];
    sprintf(enqueueLines, "lines(queueIn,type=%co%c,pch=22,lty=2,col=%cred%c);", 34, 34, 34, 34);
    char enqueueAxis[Max];
    sprintf(enqueueAxis, "axis(1,at=1:5,lab=xAxis);axis(2,las=1,at=inRange);");
    char enqueueLegend[Max];
    sprintf(enqueueLegend, "legend(1,inRange[2],c(%cheap%c,%cqueue%c),cex=0.8,col=c(%cblue%c,%cred%c),pch=21:22,lty=1:2);", 34, 34, 34, 34, 34, 34, 34, 34);
    char enqueueGraph[Max*20+(sizeof(objects)/sizeof(char))];
    sprintf(enqueueGraph, "%s%s%s%s%s%sbox();", objects, enqueuePlot, enqueueTitle, enqueueLines, enqueueAxis, enqueueLegend);

    fprintf(file, "%s\n", enqueueGraph);

    //dequeue graph
    char dequeuePlot[Max];
    sprintf(dequeuePlot, "plot(heapOut,type=%co%c,col=%cblue%c,ylim=outRange,ann=FALSE,axes=FALSE);",34, 34, 34, 34);
    char dequeueTitle[Max*3];
    sprintf(dequeueTitle, "title(main=%cdequeueing%c,col.main=%cblack%c,font.main=4);title(xlab=%cnumber of objects%c,col.lab=rgb(0,0.5,0));title(ylab=%cnumber of processes%c,col.lab=rgb(0,0.5,0));", 34, 34, 34, 34, 34, 34, 34, 34);
    char dequeueLines[Max];
    sprintf(dequeueLines, "lines(queueOut,type=%co%c,pch=22,lty=2,col=%cred%c);", 34, 34, 34, 34);
    char dequeueAxis[Max];
    sprintf(dequeueAxis, "axis(1,at=1:5,lab=xAxis);axis(2,las=1,at=outRange);");
    char dequeueLegend[Max];
    sprintf(dequeueLegend, "legend(1,outRange[2],c(%cheap%c,%cqueue%c),cex=0.8,col=c(%cblue%c,%cred%c),pch=21:22,lty=1:2);", 34, 34, 34, 34, 34, 34, 34, 34);
    char dequeueGraph[Max*20+(sizeof(objects)/sizeof(char))];
    sprintf(dequeueGraph, "%s%s%s%s%s%sbox()", objects, dequeuePlot, dequeueTitle, dequeueLines, dequeueAxis, dequeueLegend);

    fprintf(file, "%s\n", dequeueGraph);

    //heapfy graph
    char heapfyPlot[Max];
    sprintf(heapfyPlot, "plot(heapfy,type=%co%c,col=%cgreen%c,ylim=heapfyRange,ann=FALSE,axes=FALSE);", 34, 34, 34, 34);
    char heapfyTitle[Max*3];
    sprintf(heapfyTitle, "title(main=%cHeapfy%c,col.main=%cblack%c,font.main=4);title(xlab=%cnumber of objects%c,col.lab=rgb(0,0.5,0));title(ylab=%cnumber of processes%c,col.lab=rgb(0,0.5,0));", 34, 34, 34, 34, 34, 34, 34, 34);
    char heapfyAxis[Max];
    sprintf(heapfyAxis, "axis(1,at=1:5,lab=xAxis);axis(2,las=1,at=heapfyRange);");
    char heapfyGraph[Max*10+(sizeof(objects)/sizeof(char))];
    sprintf(heapfyGraph, "%s%s%s%sbox();", objects, heapfyPlot, heapfyTitle, heapfyAxis);

    fprintf(file, "%s\n", heapfyGraph);

    //diff graph
    char diffPlot[Max];
    sprintf(diffPlot, "plot(diffIn,type=%co%c,col=%cblue%c,ylim=diffRange,ann=FALSE,axes=FALSE);",34, 34, 34, 34);
    char diffTitle[Max*3];
    sprintf(diffTitle, "title(main=%cheap advantage%c,col.main=%cblack%c,font.main=4);title(xlab=%cnumber of objects%c,col.lab=rgb(0,0.5,0));title(ylab=%cprocesses advantage%c,col.lab=rgb(0,0.5,0));", 34, 34, 34, 34, 34, 34, 34, 34);
    char diffAxis[Max];
    sprintf(diffAxis, "axis(1,at=1:5,lab=xAxis);axis(2,las=1,at=diffRange);");
    char diffGraph[Max*10+(sizeof(objects)/sizeof(char))];
    sprintf(diffGraph, "%s%s%s%sbox();", objects, diffPlot, diffTitle, diffAxis);

    fprintf(file, "%s\n", diffGraph);

    fclose(file);

    char cd[Max];
    sprintf(cd, "cd %s/%s", home, path);
    char RCALL[Max];
    sprintf(RCALL, "%s;Rscript %s",cd, fileName);
    system(RCALL);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight.Command;
using MobileRcp.Core.BaseTypes;
using MobileRcp.Core.Definitions.Factories;
using MobileRcp.Core.Models;

namespace MobileRcp.Core.ViewModels
{
    //Review: I would place this class in Prabez.MobileRcp.Application.Authorization.ViewModels
    public class AuthorizationCompletedViewModel : ViewModelWithParameter<AuthorizedModel>
    {
        private readonly ICoreFactory _coreFactory;

        private string _endMessage;
        public string EndMessage
        {
            get { return _endMessage; }
            set { Set(() => EndMessage, ref _endMessage, value); }
        }

        public RelayCommand EndAuthorizationCommand { get; private set; }
        public RelayCommand ShowWorktimeCommand { get; private set; }
        public RelayCommand ShowLeaveStatsCommand { get; private set; }

        public AuthorizationCompletedViewModel(ICoreFactory coreFactory) : base(coreFactory)
        {
            _coreFactory = coreFactory;

            EndAuthorizationCommand = new RelayCommand(coreFactory.GetCoreNavigationService().GoToQrCodeGetter);
            ShowWorktimeCommand = new RelayCommand(() => coreFactory.GetCoreNavigationService().GoToWorktimeStats(ViewModelParameter));
            ShowLeaveStatsCommand = new RelayCommand(() => coreFactory.GetCoreNavigationService().GoToLeaveStats(ViewModelParameter));
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<TITLE>Invalid Man Page</TITLE>

Invalid Man Page

The requested file setitimer.2 is not a valid (unformatted) man page.


text:
num_args takes in 5.1 byte code and extracts the number of arguments
from its function header.
--]]--

function int(t)
	return t:byte(1)+t:byte(2)*0x100+t:byte(3)*0x10000+t:byte(4)*0x1000000
end

function num_args(func)
	local dump = string.dump(func)
	local offset, cursor = int(dump:sub(13)), offset + 26
	--Get the params and var flag (whether there's a ... in the param)
	return dump:sub(cursor):byte(), dump:sub(cursor+1):byte()
end

-- Usage:
num_args(function(a,b,c,d, ...) end) -- return 4, 7

-- Python styled string format operator
local gm = debug.getmetatable("")

gm.__mod=function(self, other)
    if type(other) ~= "table" then other = {other} end
    for i,v in ipairs(other) do other[i] = tostring(v) end
    return self:format(unpack(other))
end

print([===[
    blah blah %s, (%d %d)
]===]%{"blah", num_args(int)})

--[=[--
table.maxn is deprecated, use # instead.
--]=]--
print(table.maxn{1,2,[4]=4,[8]=8) -- outputs 8 instead of 2

print(5 --[[ blah ]])


text:
import {$, activePage} from './dollar.js'
import {AudioLoader} from './audioloader.js'

export function Soundboard (config) {
  this.config = config

  // Grab audio urls relative to site url
  var urls = []
  for (var i = 0; i < config.rows.length; ++i) {
    for (var j = 0; j < config.rows[i].sounds.length; ++j) {
      var thisSound = config.rows[i].sounds[j]
      urls.push(config.siteURL + '/' + thisSound.url)
    }
  }

  // Configure the audio loader
  this.loader = new AudioLoader(urls, config.continuous_playback, config.loop_playback)
  this.loader.load()

  // Configure play buttons:
  var play = function (i) {
    this.loader.play(i)
  }.bind(this)

  activePage('.soundboard-play').each(function (i) {
    $(this).on('click', function (i) {
      play(i)
    }.bind(null, i))
  })

  activePage('.soundboard-stop').on('click', this.loader.stop.bind(this.loader))

  activePage('.next').on('click', this.loader.stop.bind(this.loader))

  activePage('.back').on('click', function () {
    this.loader.stop(true)

    if (this.config.back_button_can_exit_test) { window.history.back() }
  }.bind(this))
}


text:
namespace Evidyon {
namespace Network {
namespace Packet {

struct ActorSyncData;

class SlowSyncPacketEncoder : public PacketEncoder {
public:
  // initializes the encoder
  SlowSyncPacketEncoder();
  void reset();
  void setTimeSinceLastSync(double time_since_last_sync);

  // will flush (send & renew) packet if full
  void add(ActorSyncData* actor_data, NetworkPeer* destination);

  // sends the packet if it has data
  void dispatch(NetworkPeer* destination);

private:
  unsigned int actors_;
  float time_since_last_sync_;
};

}
}
}

#endif


text:
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** @author  John Miller
 *  @version 1.2
 *  @date    Tue Jul 21 13:35:37 EDT 2015
 *  @see     LICENSE (MIT style license file).
 */

package scalation

//import language.implicitConversions

//import scalation.linalgebra.VectorD

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `graphalytics` package contains classes, traits and objects for graph
 *  analytics on Trees, DAGs and Directed Graphs.  It provides an implicit
 *  conversion when needed for converting doubles to vectors.
 */
package object graphalytics
{
    //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /*  Implicit conversion from 'Double' to 'VectorD' for cases when TLable
     *  is a vector.
     *  @param d  the double to connvert to a vector
     */
//  implicit def double2VectorD (d: Double): VectorD = VectorD (d)

} // graphalytics package object


text:
using Anarian.Enumerators;
using Anarian.Interfaces;
using Anarian.Helpers;
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Anarian.DataStructures.ScreenEffects
{
    public enum FadeStatus
    {
        None,
        FadingToContent,
        FadingIn
    }

    public class Fade : IScreenEffect, IRenderable
    {
        #region Fields/Properties
        ProgressStatus m_progressStatus;
        public ProgressStatus Progress { get { return m_progressStatus; } set { m_progressStatus = value; } }

        FadeStatus m_fadeStatus;
        public FadeStatus FadeStatus { get { return m_fadeStatus; } protected set { m_fadeStatus = value; } }

        float m_fadePercentage;
        public float FadePercentage { get { return m_fadePercentage; } protected set { m_fadePercentage = value; } }

        float m_fadeRate;
        public float FadeRate { get { return m_fadeRate; } set { m_fadeRate = value; } }

        public readonly float MinimumFade = 0.0f;
        public readonly float MaximumFade = 1.0f;

        Texture2D m_fadeTexture;
        public Texture2D FadeTexture { get { return m_fadeTexture; } set { m_fadeTexture = value; } }

        Color m_fadeColour;
        public Color FadeColour { get { return m_fadeColour; } set { m_fadeColour = value; } }

        private Rectangle m_screenRect;
        #endregion

        public event EventHandler ProgressTick;
        public event EventHandler Completed;

        public bool Active { get; set; }

        public Fade(GraphicsDevice graphicsDevice, Color solidColour, float fadeRate = 0.003f)
        {
            Active = true;

            m_progressStatus = ProgressStatus.None;
            m_fadeStatus = ScreenEffects.FadeStatus.FadingToContent;
            m_fadeRate = fadeRate;
            m_fadePercentage = MinimumFade;

            ChangeFadeColor(graphicsDevice, solidColour);
        }

        public Fade(Texture2D texture, float fadeRate = 0.003f)
        {
            Active = true;

            m_progressStatus = ProgressStatus.None;
            m_fadeStatus = ScreenEffects.FadeStatus.FadingToContent;
            m_fadeRate = fadeRate;
            m_fadePercentage = MinimumFade;

            m_fadeTexture = texture;
            m_fadeColour = Color.White;
        }

        #region Interface Implimentation
        void IScreenEffect.PreformEffect(GameTime gameTime) { ApplyEffect(gameTime); }
        void IScreenEffect.Draw(GameTime gameTime, SpriteBatch spriteBatch) { Draw(gameTime, spriteBatch); }
        ProgressStatus IScreenEffect.Progress { get { return Progress; } set { Progress = value; } }

        void IRenderable.Draw(GameTime gameTime, SpriteBatch spriteBatch, GraphicsDevice graphics, ICamera camera) { Draw(gameTime, spriteBatch); }
        #endregion

        #region Helper Methods
        public void ChangeFadeStatus(FadeStatus fadeStaus)
        {
            m_fadeStatus = fadeStaus;

            switch (fadeStaus) {
                case FadeStatus.None:
                    Progress = ProgressStatus.Completed;
                    break;
                case FadeStatus.FadingToContent:
                case FadeStatus.FadingIn:
                default:
                    Progress = ProgressStatus.NotStarted;
                    break;
            }
        }

        public void ChangeWithoutFade(FadeStatus fadeStatus)
        {
            m_fadeStatus = fadeStatus;
            Progress = ProgressStatus.Completed;

            switch (m_fadeStatus) {
                case FadeStatus.FadingToContent: m_fadePercentage = 0.0f; break;
                case FadeStatus.FadingIn: m_fadePercentage = 1.0f; break;
            }

            if (Completed != null)
                Completed(this, null);
        }

        public void ChangeFadeColor(GraphicsDevice graphicsDevice, Color colour)
        {
            m_fadeColour = colour;
            m_screenRect = graphicsDevice.Viewport.GetViewportRectangle();

            m_fadeTexture = m_fadeColour.CreateTextureFromSolidColor(graphicsDevice, 1, 1);
        }
        #endregion

        public void ApplyEffect(GameTime gameTime)
        {
            if (m_progressStatus == ProgressStatus.None) return;
            if (m_progressStatus == ProgressStatus.Completed) return;
            if (m_fadeStatus == FadeStatus.None) return;

            switch (m_fadeStatus) {
                case FadeStatus.FadingToContent:    m_fadePercentage -= m_fadeRate * gameTime.DeltaTime();  break;
                case FadeStatus.FadingIn:           m_fadePercentage += m_fadeRate * gameTime.DeltaTime();  break;
            }

            m_fadePercentage = MathHelper.Clamp(m_fadePercentage, MinimumFade, MaximumFade);
            if (m_fadePercentage <= MinimumFade || m_fadePercentage >= MaximumFade)
            {
                m_progressStatus = ProgressStatus.Completed;

                if (Completed != null)
                    Completed(this, null);
            }
            else {
                m_progressStatus = ProgressStatus.InProgress;

                if (ProgressTick != null)
                    ProgressTick(this, null);
            }
        }

        public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
        {
            if (!Active) return;

            try
            {
                spriteBatch.Begin();
                spriteBatch.Draw(m_fadeTexture, m_screenRect, m_fadeColour * m_fadePercentage);
            }
            catch (Exception) { }

            try
            {
                spriteBatch.End();
            }
            catch (Exception) { }
        }

        public override string ToString()
        {
            return "Progress: " + m_progressStatus.ToString() + " | " +
                   "FadeStatus: " + m_fadeStatus.ToString() + " | " +
                   "FadePercentage: " + m_fadePercentage + " | " +
                   "FadeRate: " + m_fadeRate + " | " +
                   "Colour: " + m_fadeColour.ToString();
        }
    }
}


text:
"""
.. currentmodule:: __init__.py
.. moduleauthor:: Pat Daburu <pat@daburu.net>

Let's test the hashing module!
"""


text:
var cs = require('./data/cs.js');
var denies = require('./data/denies.js');
var heroKills = require('./data/herokills.js');
var runes = require('./data/runes.js');

var _ = require('underscore');

var convertSeconds = function(number) {
  var realTime = number / 30;
  var mins = Math.floor( realTime / 60 );
  var secs = Math.floor( realTime % 60 );
  return mins + ":" + secs;
}

module.exports = {
  countLastHits: function(heroName) {
    var count = 0;
    var total = 0;
    var lastHitsOverTime = [[],[]];
    var heroLastHits = _.filter(cs, function(entry) {return entry.hero === heroName});
    for (var i = 0; i < heroLastHits.length; i++) {
      count++;
      if (count >= Math.round(heroLastHits.length / 12) || i === heroLastHits.length - 1) {
        total += count;
        lastHitsOverTime[1].push(total);
        lastHitsOverTime[0].push(convertSeconds(heroLastHits[i].time));
        count = 0;
      }
    }
    return lastHitsOverTime;
  },
  countDenies: function(heroName) {
    var count = 0;
    var total = 0;
    var deniesOverTime = [[0],[0]];
    var heroDenies = _.filter(denies, function(entry) {return entry.hero === heroName});
    for (var i = 0; i < heroDenies.length; i++) {
      count++;
      if (count >= Math.round(heroDenies.length / 10) || i === heroDenies.length - 1) {
        total += count;
        deniesOverTime[1].push(total);
        deniesOverTime[0].push(convertSeconds(heroDenies[i].time));
        count = 0;
      }
    }
    return deniesOverTime;
  },
  countKda: function(heroName) {
    var kills = 0;
    var deaths = 0;
    var assists = 0;
    var kda = {};
    for (var i = 0; i < heroKills.length; i++) {
      if (heroKills[i].killer === heroName) {
        kda.kills = ++kills;
      }
      if (heroKills[i].dead === heroName) {
        kda.deaths = ++deaths;
      }
      if (_.contains(heroKills[i].assists, heroName)) {
        kda.assists = ++assists;
      };
    }
    return kda;
  },
  countRunes: function() {
    var runeControl = {};
    for (var i = 0; i < runes.length; i++) {
      if (!runeControl[runes[i].hero]) {
        runeControl[runes[i].hero] = 1;
      } else {
        runeControl[runes[i].hero]++;
      }
    }
    return runeControl;
  }
};