<commit_before>define(["avalon", "avalon.button"], function(avalon) {
    var defaults = {
        toggle: true,
        width: 300,
        minHeight: 150,
        height: "auto",
        minWidth: 150,
        close: avalon.noop,
        parent: "body",
        modal: false,
        autoOpen: true
    };
    //判定是否支持css position fixed
    var supportFixed = true;
    new function() {
        var test = document.createElement('div'),
                control = test.cloneNode(false),
                fake = false,
                root = document.body || (function() {
            fake = true;
            return document.documentElement.appendChild(document.createElement('body'));
        }());
        var oldCssText = root.style.cssText;
        root.style.cssText = 'padding:0;margin:0';
        test.style.cssText = 'position:fixed;top:42px';
        root.appendChild(test);
        root.appendChild(control);
        supportFixed = test.offsetTop !== control.offsetTop;
        root.removeChild(test);
        root.removeChild(control);
        root.style.cssText = oldCssText;
        if (fake) {
            document.documentElement.removeChild(root);
        }
    };
    //遮罩层
    var overlay = document.createElement("div");
    overlay.innerHTML = '

';
    overlay = overlay.firstChild;//全部dialog共用
    //判定是否支持css3 transform
    var transforms = {//IE9+ firefox3.5+ chrome4+ safari3.1+ opera10.5+
        "transform": "transform",
        "-moz-transform": "mozTransform",
        "-webkit-transform": "webkitTransform",
        "-ms-transform": "msTransform"
    }
    var cssText = "position:fixed; top:50%;left:50%;"
    var supportTransform = false;
    for (var i in transforms) {
        if (transforms[i] in overlay.style) {
            supportTransform = true;
            cssText += i + ":translateX(-50%) translateY(-50%);"
            break;
        }
    }

    avalon.ui.dialog = function(element, id, vmodels, opts) {
        var $element = avalon(element);
        var options = avalon.mix({}, defaults, opts, $element.data());
        options.toggle = !!options.autoOpen;
        if (!options.title) {
            options.title = element.title || " ";
        }
        if (typeof opts === "function") {
            options.close = opts;
        }
        var model;
        var dialog = avalon.parseHTML('

' +
                '{{title|html}}' +
                '<button ms-ui="button" type="button" data-primary="ui-icon-closethick" class="ui-dialog-titlebar-close" data-text="false" ms-click="close">close</button>
' +
                '

').firstChild;

        var parentNode = options.parent === "parent" ? element.parentNode : document.body;

        var full = false;
        $element.addClass("ui-dialog-content ui-widget-content");
        if (options.height === "auto") {
            var style = element.style;
            style.width = "auto";
            style.height = "auto";
            style.minHeight = element.clientHeight + "px";
        }
        element.removeAttribute("title");

        element.removeAttribute("ms-ui");//防止死循环
        element.parentNode.removeChild(element);
        model = avalon.define(id, function(vm) {
            vm.toggle = options.toggle;
            vm.title = options.title;
            vm.width = options.width;
            vm.height = options.height;
            vm.cssCenter = true;
            vm.close = function() {
                vm.toggle = false;
            };
            vm.$watch("toggle", function(v) {
                if (v === false) {
                    avalon.Array.remove(overlayInstances, options);
                    if (!overlayInstances.length) {
                        if (overlay.parentNode) {
                            overlay.parentNode.removeChild(overlay);
                        }
                    }
                } else {
                    resetCenter();
                }
            });
            vm.drag = function(event, data) {
                dialog.style.top = data.top + "px";
                dialog.style.left = data.left + "px";
            };
            vm.beforestart = function(event, data) {
                data.element = dialog;
                data.$element = avalon(dialog);

            };
        });
        function keepFocus() {
            function checkFocus() {
                var activeElement = document.activeElement,
                        isActive = dialog === activeElement || dialog.contains(activeElement);
                if (!isActive) {
                    if (dialog.querySelectorAll) {
                        var hasFocus = dialog.querySelectorAll("[autofocus]");
                        if (!hasFocus.length) {
                            hasFocus = dialog.querySelectorAll("[tabindex]");
                        }
                        if (!hasFocus.length) {
                            hasFocus = [dialog]
                        }
                        hasFocus[0].focus();
                    }
                }
            }
            checkFocus();
            avalon.nextTick(checkFocus);
        }

        function resetCenter() {
            if (full) {
                if (supportFixed) {
                    if (supportTransform) {
                        dialog.style.cssText = cssText
                    } else {
                        dialog.style.position = "fixed";
                        var l = (avalon(window).width() - dialog.offsetWidth) / 2;
                        var t = (avalon(window).height() - dialog.offsetHeight) / 2;
                        dialog.style.left = l + "px";
                        dialog.style.top = t + "px";
                    }
                } else {
                    dialog.style.setExpression('top', '( document.body.clientHeight - this.offsetHeight) / 2) + Math.max(document.documentElement.scrollTop,document.body.scrollTop) + "px"');
                    dialog.style.setExpression('left', '( document.body.clientWidth - this.offsetWidth / 2) +  Math.max(document.documentElement.scrollLeft,document.body.scrollLeft) + "px"');
                }
            } else {
                l = (avalon(parentNode).width() - dialog.offsetWidth) / 2;
                t = (avalon(parentNode).height() - dialog.offsetHeight) / 2;
                dialog.style.left = l + "px";
                dialog.style.top = t + "px";
            }

            keepFocus();
            if (options.modal) {
                parentNode.insertBefore(overlay, dialog);
                overlay.style.display = "block";
                avalon.Array.ensure(overlayInstances, options)
            }
        }

        avalon.ready(function() {
            parentNode.appendChild(dialog);
            dialog.appendChild(element);
            full = /body|html/i.test(dialog.offsetParent.tagName);
            if (full) {
                dialog.firstChild.setAttribute("data-containment", "window");//这是给ms-draggable组件用的
            }
            avalon.scan(dialog, [model].concat(vmodels));

            if (options.autoOpen) {
                avalon.nextTick(resetCenter);
            }
            if (full && supportTransform) {
                return
            }
            avalon(document.body).bind("scroll", function() {
                options.autoOpen && resetCenter();
            });
            avalon(window).bind("resize", function() {
                options.autoOpen && resetCenter();
            });
        });
        return model;
    }
    var overlayInstances = avalon.ui.dialog.overlayInstances = [];

    return avalon
})

//http://www.slipjs.com/jz.html<commit_msg>update avalon.dialog.js<commit_after>define(["avalon", "avalon.button"], function(avalon) {
    var defaults = {
        toggle: true,
        width: 300,
        minHeight: 150,
        height: "auto",
        minWidth: 150,
        close: avalon.noop,
        parent: "body",
        modal: false,
        autoOpen: true
    };
    //判定是否支持css position fixed
    var supportFixed = true;
    new function() {
        var test = document.createElement('div'),
                control = test.cloneNode(false),
                fake = false,
                root = document.body || (function() {
            fake = true;
            return document.documentElement.appendChild(document.createElement('body'));
        }());
        var oldCssText = root.style.cssText;
        root.style.cssText = 'padding:0;margin:0';
        test.style.cssText = 'position:fixed;top:42px';
        root.appendChild(test);
        root.appendChild(control);
        supportFixed = test.offsetTop !== control.offsetTop;
        root.removeChild(test);
        root.removeChild(control);
        root.style.cssText = oldCssText;
        if (fake) {
            document.documentElement.removeChild(root);
        }
    };
    //遮罩层
    var overlay = document.createElement("div");
    overlay.innerHTML = '

';
    overlay = overlay.firstChild;//全部dialog共用
    //判定是否支持css3 transform
    var transforms = {//IE9+ firefox3.5+ chrome4+ safari3.1+ opera10.5+
        "transform": "transform",
        "-moz-transform": "mozTransform",
        "-webkit-transform": "webkitTransform",
        "-ms-transform": "msTransform"
    }
    var cssText = "position:fixed; top:50%;left:50%;"
    var supportTransform = false;
    for (var i in transforms) {
        if (transforms[i] in overlay.style) {
            supportTransform = true;
            cssText += i + ":translateX(-50%) translateY(-50%);"
            break;
        }
    }

    avalon.ui.dialog = function(element, id, vmodels, opts) {
        var $element = avalon(element);
        var options = avalon.mix({}, defaults, opts, $element.data());
        options.toggle = !!options.autoOpen;
        if (!options.title) {
            options.title = element.title || " ";
        }
        if (typeof opts === "function") {
            options.close = opts;
        }
        var model;
        var dialog = avalon.parseHTML('

' +
                '{{title|html}}' +
                '<button ms-ui="button" type="button" data-primary="ui-icon-closethick" class="ui-dialog-titlebar-close" data-text="false" ms-click="close">close</button>
' +
                '

').firstChild;

        var parentNode = options.parent === "parent" ? element.parentNode : document.body;

        var full = false;
        $element.addClass("ui-dialog-content ui-widget-content");
        if (options.height === "auto") {
            var style = element.style;
            style.width = "auto";
            style.height = "auto";
            style.minHeight = element.clientHeight + "px";
        }
        element.removeAttribute("title");

        element.removeAttribute("ms-ui");//防止死循环
        element.parentNode.removeChild(element);
        model = avalon.define(id, function(vm) {
            vm.toggle = options.toggle;
            vm.title = options.title;
            vm.width = options.width;
            vm.height = options.height;
            vm.cssCenter = true;
            vm.close = function() {
                vm.toggle = false;
            };
            vm.$watch("toggle", function(v) {
                if (v === false) {
                    avalon.Array.remove(overlayInstances, options);
                    if (!overlayInstances.length) {
                        if (overlay.parentNode) {
                            overlay.parentNode.removeChild(overlay);
                        }
                    }
                } else {
                    resetCenter();
                }
            });
            vm.drag = function(event, data) {
                dialog.style.top = data.top + "px";
                dialog.style.left = data.left + "px";
            };
            vm.beforestart = function(event, data) {
                data.element = dialog;
                data.$element = avalon(dialog);

            };
        });
        function keepFocus() {
            function checkFocus() {
                var activeElement = document.activeElement,
                        isActive = dialog === activeElement || dialog.contains(activeElement);
                if (!isActive) {
                    if (dialog.querySelectorAll) {
                        var hasFocus = dialog.querySelectorAll("[autofocus]");
                        if (!hasFocus.length) {
                            hasFocus = dialog.querySelectorAll("[tabindex]");
                        }
                        if (!hasFocus.length) {
                            hasFocus = [dialog]
                        }
                        hasFocus[0].focus();
                    }
                }
            }
            checkFocus();
            avalon.nextTick(checkFocus);
        }

        function resetCenter() {
            if (full) {//如果是基于窗口垂直居中
                if (supportFixed) {
                    if (supportTransform) {// 如果是IE9-10或其他支持css3 transform的浏览器
                        dialog.style.cssText = cssText
                    } else {
                        dialog.style.position = "fixed";
                        var l = (avalon(window).width() - dialog.offsetWidth) / 2;
                        var t = (avalon(window).height() - dialog.offsetHeight) / 2;
                        dialog.style.left = l + "px";
                        dialog.style.top = t + "px";
                    }
                } else {//  如果是IE6，不支持fiexed，使用CSS表达式
                    dialog.style.setExpression('top', '( document.body.clientHeight - this.offsetHeight) / 2) + Math.max(document.documentElement.scrollTop,document.body.scrollTop) + "px"');
                    dialog.style.setExpression('left', '( document.body.clientWidth - this.offsetWidth / 2) +  Math.max(document.documentElement.scrollLeft,document.body.scrollLeft) + "px"');
                }
            } else {//基于父节点的垂直居中
                l = (avalon(parentNode).width() - dialog.offsetWidth) / 2;
                t = (avalon(parentNode).height() - dialog.offsetHeight) / 2;
                dialog.style.left = l + "px";
                dialog.style.top = t + "px";
            }

            keepFocus();
            if (options.modal) {
                parentNode.insertBefore(overlay, dialog);
                overlay.style.display = "block";
                avalon.Array.ensure(overlayInstances, options)
            }
        }

        avalon.ready(function() {
            parentNode.appendChild(dialog);
            dialog.appendChild(element);
            full = /body|html/i.test(dialog.offsetParent.tagName);
            if (full) {
                dialog.firstChild.setAttribute("data-containment", "window");//这是给ms-draggable组件用的
            }
            avalon.scan(dialog, [model].concat(vmodels));

            if (options.autoOpen) {
                avalon.nextTick(resetCenter);
            }
            if (full && supportTransform) {
                return
            }
            avalon(document.body).bind("scroll", function() {
                options.autoOpen && resetCenter();
            });
            avalon(window).bind("resize", function() {
                options.autoOpen && resetCenter();
            });
        });
        return model;
    }
    var overlayInstances = avalon.ui.dialog.overlayInstances = [];

    return avalon
})

//http://www.slipjs.com/jz.html<|endoftext|>


<commit_before>(function($, Vis) {
"use strict";

var busyDelay = 2500;

Vis.blocks['i-chart'] = {
    init: function(params) {
        var _this = this;

        _this.dimensions = {
            width: 0,
            height: 0
        };

        params = params || {};

        var colorScheme = params.colorScheme || {};
        _this.colorScheme = Vis.create(
            colorScheme,
            colorScheme.name || 'i-tango-color-scheme'
        );

        _this.content = {
            tAxes: params.tAxes || [],
            xAxes: params.xAxes || [],
            yAxes: params.yAxes || [],
            items: params.items || [],
            overlays: params.overlays || [],
            layers: []
        };
        _this._initContent();

        // _this.applySize();
        // _this.initResize();
    },

    initTAxis: function(tAxisNo) { /* override me */ },
    _initTAxis: function(tAxisNo) {
        var _this = this,
            tAxis = _this.content.tAxes[tAxisNo];

        tAxis.rangeProvider = Vis.create(
            tAxis.rangeProvider,
            tAxis.rangeProvider.name || 'undefined-t-range-provider'
        );

        _this.initTAxis(tAxisNo);

        tAxis.rangeProvider.on('update', function() {
            _this._updateTAxisRange(tAxisNo);
        });
        _this._updateTAxisRange(tAxisNo);
    },

    updateTAxisRange: function(tAxisNo) { /* override me */ },
    _updateTAxisRange: function(tAxisNo) {
        var _this = this,
            tAxis = _this.content.tAxes[tAxisNo],
            range = tAxis.rangeProvider.get(),
            scale = tAxis.scale || {},
            items = _this.content.items;

        _this.updateTAxisRange(tAxisNo);

        if (range.min == scale.inputMin && range.max == scale.inputMax) {
            return;
        }

        tAxis.scale = {
            inputMin: range.min,
            inputMax: range.max
        };

        _this.updateTAxisRange(tAxisNo);
    },

    initTAxes: function() { /* override me */ },
    _initTAxes: function() {
        var _this = this,
            tAxes = _this.content.tAxes;

        for (var tAxisNo = 0, l = tAxes.length; tAxisNo < l; ++tAxisNo) {
            _this._initTAxis(tAxisNo);
        }

        _this.initTAxes();
    },

    initXAxis: function(xAxisNo) { /* override me */ },
    _initXAxis: function(xAxisNo) {
        var _this = this,
            xAxis = _this.content.xAxes[xAxisNo],
            tAxes = _this.content.tAxes;

        var scale = xAxis.scale || {};
        xAxis.scale = Vis.create(
            scale,
            scale.name || 'i-scale-linear'
        );

        if (typeof xAxis.units === 'undefined') {
            xAxis.units = "";
        }

        if (xAxis.pos !== 'top' && xAxis.pos !== 'bottom') {
            xAxis.pos = 'bottom';
        }

        xAxis.tAxis = tAxes[xAxis.tAxisNo || 0] || Vis.error("No t-axis for x-axis #" + xAxisNo);

        if (typeof xAxis.rangeProvider.timeRangeProvider === 'undefined') {
            xAxis.rangeProvider.timeRangeProvider = xAxis.tAxis.rangeProvider;
        }
        xAxis.rangeProvider = Vis.create(
            xAxis.rangeProvider,
            xAxis.rangeProvider.name || 'undefined-x-range-provider'
        );

        if (typeof xAxis.processors === 'undefined') {
            xAxis.processors = [];
        }
        for (var i = 0, l = xAxis.processors.length; i < l; ++i) {
            var processor = xAxis.processors[i];
            processor.dimensions = _this.dimensions;
            processor.content = _this.content;
            xAxis.processors[i] = Vis.create(processor, processor.name);
        }

        _this.initXAxis(xAxisNo);

        xAxis.rangeProvider.on('update', function() {
            _this._updateXAxisRange(xAxisNo);
        });
        _this._updateXAxisRange(xAxisNo);
    },

    updateXAxisRange: function(xAxisNo) { /* override me */ },
    _updateXAxisRange: function(xAxisNo) {
        var _this = this,
            xAxis = _this.content.xAxes[xAxisNo],
            range = xAxis.rangeProvider.get(),
            scale = xAxis.scale;

        if (range.min == scale.inputMin && range.max == scale.inputMax) {
            return;
        }

        scale.input(range.min, range.max);

        _this.updateXAxisRange(xAxisNo);

        _this._renderXAxis(xAxisNo);
    },

    renderXAxis: function(xAxisNo, ticks) { /* override me */ },
    _renderXAxis: function(xAxisNo) {
        var _this = this,
            xAxis = this.content.xAxes[xAxisNo];

        xAxis.ticks = xAxis.scale.ticks(Math.floor(_this.dimensions.width / 65), xAxis.units);

        var ticks = Units.formatTicks(xAxis.ticks, xAxis.units, xAxis.scale);
        for (var i = 0, l = ticks.length; i < l; ++i) {
            var tick = ticks[i];
            tick.offset = Math.round(xAxis.scale.f(tick.tickValue));
        }

        _this.renderXAxis(xAxisNo, ticks);
    },

    initXAxes: function() { /* override me */ },
    _initXAxes: function() {
        var _this = this,
            xAxes = _this.content.xAxes;

        for (var xAxisNo = 0, l = xAxes.length; xAxisNo < l; ++xAxisNo) {
            _this._initXAxis(xAxisNo);
        }

        _this.initXAxes();
    },

    initYAxis: function(yAxisNo) { /* override me */ },
    _initYAxis: function(yAxisNo) {
        var _this = this,
            yAxis = _this.content.yAxes[yAxisNo];

        var scale = yAxis.scale || {};
        yAxis.scale = Vis.create(
            scale,
            scale.name || 'i-scale-linear'
        );

        if (typeof yAxis.units === 'undefined') {
            yAxis.units = "";
        }

        if (yAxis.pos !== 'left' && yAxis.pos !== 'right') {
            yAxis.pos = 'right';
        }

        yAxis.rangeProvider = Vis.create(
            yAxis.rangeProvider,
            yAxis.rangeProvider.name || 'undefined-y-range-provider'
        );

        if (typeof yAxis.processors === 'undefined') {
            yAxis.processors = [];
        }
        for (var i = 0, l = yAxis.processors.length; i < l; ++i) {
            var processor = yAxis.processors[i];
            processor.dimensions = _this.dimensions;
            processor.content = _this.content;
            yAxis.processors[i] = Vis.create(processor, processor.name);
        }

        _this.initXAxis(yAxisNo);

        yAxis.rangeProvider.on('update', function() {
            _this._updateYAxisRange(yAxisNo);
        });
        _this._updateYAxisRange(yAxisNo);
    },

    updateYAxisRange: function(yAxisNo) { /* override me */ },
    _updateYAxisRange: function(yAxisNo) {
        var _this = this,
            yAxis = _this.content.yAxes[yAxisNo],
            range = yAxis.rangeProvider.get(),
            scale = yAxis.scale;

        if (range.min == scale.inputMin && range.max == scale.inputMax) {
            return;
        }

        scale.input(range.min, range.max);

        _this.updateYAxisRange(yAxisNo);

        _this._renderYAxis(yAxisNo);
    },

    renderYAxis: function(yAxisNo, ticks) { /* override me */ },
    _renderYAxis: function(yAxisNo) {
        var _this = this,
            yAxis = this.content.yAxes[yAxisNo];

        yAxis.ticks = yAxis.scale.ticks(Math.floor(_this.dimensions.height / 40), yAxis.units);

        var ticks = Units.formatTicks(yAxis.ticks, yAxis.units, yAxis.scale);
        for (var i = 0, l = ticks.length; i < l; ++i) {
            var tick = ticks[i];
            tick.offset = _this.dimensions.height - Math.round(yAxis.scale.f(tick.tickValue)) - 1;
        }

        _this.renderYAxis(yAxisNo, ticks);
    },

    initYAxes: function() { /* override me */ },
    _initYAxes: function() {
        var _this = this,
            yAxes = _this.content.yAxes;

        for (var yAxisNo = 0, l = yAxes.length; yAxisNo < l; ++yAxisNo) {
            _this._initYAxis(yAxisNo);
        }

        _this.initYAxes();
    },

    _initItem: function(itemNo) {
        var _this = this,
            tAxes = _this.content.tAxes,
            xAxes = _this.content.xAxes,
            yAxes = _this.content.yAxes,
            item = _this.content.items[itemNo];

        if (typeof item.tAxisNo === 'undefined') {
            item.tAxisNo = 0;
        }
        item.tAxis = tAxes[item.tAxisNo] || Vis.error("No t-axis for item #" + itemNo);

        if (typeof item.xAxisNo === 'undefined') {
            item.xAxisNo = 0;
        }
        item.xAxis = xAxes[item.xAxisNo] || Vis.error("No x-axis for item #" + itemNo);

        if (typeof item.yAxisNo === 'undefined') {
            item.yAxisNo = 0;
        }
        item.yAxis = yAxes[item.yAxisNo] || Vis.error("No y-axis for item #" + itemNo);

        if (typeof item.color === 'undefined') {
            item.color = _this.colorScheme.get(itemNo);
        }

        if (typeof item.units === 'undefined') {
            item.units = "";
        }

        if (typeof item.dataProvider.timeRangeProvider === 'undefined') {
            item.dataProvider.timeRangeProvider = item.tAxis.rangeProvider;
        }
        item.dataProvider = Vis.create(
            item.dataProvider,
            item.dataProvider.name || 'undefined-item-data-provider'
        );
        item.dataProvider.on('update', function(e) {
            _this._updateItemData(itemNo);
        });

        if (!item.filters) {
            item.filters = [];
        }
        for (var i = 0, l = item.filters.length; i < l; ++i) {
            item.filters[i] = Vis.create(
                item.filters[i],
                item.filters[i].name
            );
        }

        item.on = function(action, callback) {
            $(item).on(action + '.vis', callback);
        };
        item.trigger = function(action) {
            $(item).trigger(action + '.vis');
        };

        item.renderData = {};

        _this._updateItemData(itemNo);
        // _requestItemData?
    },

    _updateItemData: function(itemNo) {
        var _this = this,
            item = _this.content.items[itemNo],
            filters = item.filters;

        item.rawData = item.dataProvider.get();

        var data = {};
        $.each(item.rawData, function(name, arr) {
            data[name] = arr.slice();
        });
        for (var i = 0, l = filters.length; i < l; ++i) {
            data = filters[i].run(item, data);
        }
        item.data = data;

        item.trigger('data');

        // override me
        this.render();
    },

    _initItems: function() {
        var _this = this,
            items = _this.content.items;

        for (var itemNo = 0, l = items.length; itemNo < l; ++itemNo) {
            _this._initItem(itemNo);
        }
    },

    initOverlay: function(overlayNo) { /* override me */ },
    _initOverlay: function(overlayNo) {
        var _this = this,
            overlays = _this.content.overlays,
            overlay = overlays[overlayNo];

        overlay.dimensions = _this.dimensions;
        overlay.content = _this.content;
        overlays[overlayNo] = Vis.create(
            overlay,
            overlay.name || 'undefined-overlay'
        );

        _this.initOverlay(overlayNo);
    },

    _initOverlays: function() {
        var _this = this,
            overlays = _this.content.overlays;

        for (var i = 0, l = overlays.length; i < l; ++i) {
            _this._initOverlay(i);
        }
    },

    initContent: function () { /* override me */ },
    _initContent: function () {
        this._initTAxes();
        this._initXAxes();
        this._initYAxes();
        this._initItems();
        this._initOverlays();

        this.initContent();
    },

    applySize: function () { /* override me */ },
    _applySize: function() {
        var _this = this,
            dim = _this.dimensions,
            xAxes = _this.content.xAxes,
            yAxes = _this.content.yAxes,
            i, l;

        for (i = 0, l = xAxes.length; i < l; ++i) {
            xAxes[i].scale.output(0, dim.width - 1);
        }

        for (i = 0, l = yAxes.length; i < l; ++i) {
            yAxes[i].scale.output(0, dim.height - 1);
        }

        _this.applySize();
    },

    initResize: function() {
        // override me
    },

    setYAxes: function(yAxes) {
        var _this = this;

        _this._destroyYAxes();
        _this.content.yAxes = yAxes;

        for (var yAxisNo = 0, l = yAxes.length; yAxisNo < l; ++yAxisNo) {
            _this._initYAxis(yAxisNo);
        }
        _this._initYAxes();

        _this._initState.yAxes = true;
        _this._updateInit();
    },

    setXAxes: function(xAxes) {
        var _this = this;

        _this._destroyXAxes();
        _this.content.xAxes = xAxes;

        for (var xAxisNo = 0, l = xAxes.length; xAxisNo < l; ++xAxisNo) {
            _this._initXAxis(xAxisNo);
        }
        _this._initXAxes();

        _this._initState.xAxes = true;
        _this._updateInit();
    },

    _updateItem: function(itemNo) {
        var _this = this,
            item = _this.content.items[itemNo];

        _this._updateItemData(item);
        item.ready = true;
        _this.renderItem(itemNo);
    },

    _requestItemData: function(item) {
        var _this = this,
            xAxis = _this.content.xAxes[item.xAxis || 0] || _this.content.xAxes[0];

        item.ready = false;
        item.dataProvider.range(xAxis.scale.inputMin, xAxis.scale.inputMax);
    },

    _runProcessors: function() {
        var _this = this,
            yAxes = _this.content.yAxes,
            items = _this.content.items;

        for (var yAxisNo = 0, l = yAxes.length; yAxisNo < l; ++yAxisNo) {
            var yAxis = yAxes[yAxisNo];

            var axisItems = [];
            for (var i = 0, m = items.length; i < m; ++i) {
                var item = items[i];
                if (item.yAxis != yAxisNo) continue;

                item.renderData = item.data;
                axisItems.push(item);
            }

            for (var i = 0, m = yAxis.processors.length; i < m; ++i) {
                yAxis.processors[i].run(axisItems);
            }

            var range = yAxis.rangeProvider.get(axisItems);
            _this._updateYAxisRange(yAxisNo, range);
        }
    },

    beforeRender: function() {
        this._runProcessors();

        // override me
    },

    afterRender: function() {
        // override me
    },

    renderItem: function(itemNo) {
        if (this._init != -1) {
            return;
        }

        this.render();
    }
};

})(jQuery, Vis);
<commit_msg>Init items before X and Y axes<commit_after>(function($, Vis) {
"use strict";

var busyDelay = 2500;

Vis.blocks['i-chart'] = {
    init: function(params) {
        var _this = this;

        _this.dimensions = {
            width: 0,
            height: 0
        };

        params = params || {};

        var colorScheme = params.colorScheme || {};
        _this.colorScheme = Vis.create(
            colorScheme,
            colorScheme.name || 'i-tango-color-scheme'
        );

        _this.content = {
            tAxes: params.tAxes || [],
            xAxes: params.xAxes || [],
            yAxes: params.yAxes || [],
            items: params.items || [],
            overlays: params.overlays || [],
            layers: []
        };
        _this._initContent();

        // _this.applySize();
        // _this.initResize();
    },

    initTAxis: function(tAxisNo) { /* override me */ },
    _initTAxis: function(tAxisNo) {
        var _this = this,
            tAxis = _this.content.tAxes[tAxisNo];

        tAxis.rangeProvider = Vis.create(
            tAxis.rangeProvider,
            tAxis.rangeProvider.name || 'undefined-t-range-provider'
        );

        _this.initTAxis(tAxisNo);

        tAxis.rangeProvider.on('update', function() {
            _this._updateTAxisRange(tAxisNo);
        });
        _this._updateTAxisRange(tAxisNo);
    },

    updateTAxisRange: function(tAxisNo) { /* override me */ },
    _updateTAxisRange: function(tAxisNo) {
        var _this = this,
            tAxis = _this.content.tAxes[tAxisNo],
            range = tAxis.rangeProvider.get(),
            scale = tAxis.scale || {},
            items = _this.content.items;

        _this.updateTAxisRange(tAxisNo);

        if (range.min == scale.inputMin && range.max == scale.inputMax) {
            return;
        }

        tAxis.scale = {
            inputMin: range.min,
            inputMax: range.max
        };

        _this.updateTAxisRange(tAxisNo);
    },

    initTAxes: function() { /* override me */ },
    _initTAxes: function() {
        var _this = this,
            tAxes = _this.content.tAxes;

        for (var tAxisNo = 0, l = tAxes.length; tAxisNo < l; ++tAxisNo) {
            _this._initTAxis(tAxisNo);
        }

        _this.initTAxes();
    },

    _initItem: function(itemNo) {
        var _this = this,
            tAxes = _this.content.tAxes,
            xAxes = _this.content.xAxes,
            yAxes = _this.content.yAxes,
            item = _this.content.items[itemNo];

        if (typeof item.tAxisNo === 'undefined') {
            item.tAxisNo = 0;
        }
        item.tAxis = tAxes[item.tAxisNo] || Vis.error("No t-axis for item #" + itemNo);

        if (typeof item.xAxisNo === 'undefined') {
            item.xAxisNo = 0;
        }
        item.xAxis = xAxes[item.xAxisNo] || Vis.error("No x-axis for item #" + itemNo);

        if (typeof item.yAxisNo === 'undefined') {
            item.yAxisNo = 0;
        }
        item.yAxis = yAxes[item.yAxisNo] || Vis.error("No y-axis for item #" + itemNo);

        if (typeof item.color === 'undefined') {
            item.color = _this.colorScheme.get(itemNo);
        }

        if (typeof item.units === 'undefined') {
            item.units = "";
        }

        if (typeof item.dataProvider.timeRangeProvider === 'undefined') {
            item.dataProvider.timeRangeProvider = item.tAxis.rangeProvider;
        }
        item.dataProvider = Vis.create(
            item.dataProvider,
            item.dataProvider.name || 'undefined-item-data-provider'
        );
        item.dataProvider.on('update', function(e) {
            _this._updateItemData(itemNo);
        });

        if (!item.filters) {
            item.filters = [];
        }
        for (var i = 0, l = item.filters.length; i < l; ++i) {
            item.filters[i] = Vis.create(
                item.filters[i],
                item.filters[i].name
            );
        }

        item.on = function(action, callback) {
            $(item).on(action + '.vis', callback);
        };
        item.trigger = function(action) {
            $(item).trigger(action + '.vis');
        };

        item.renderData = {};

        _this._updateItemData(itemNo);
        // _requestItemData?
    },

    _updateItemData: function(itemNo) {
        var _this = this,
            item = _this.content.items[itemNo],
            filters = item.filters;

        item.rawData = item.dataProvider.get();

        var data = {};
        $.each(item.rawData, function(name, arr) {
            data[name] = arr.slice();
        });
        for (var i = 0, l = filters.length; i < l; ++i) {
            data = filters[i].run(item, data);
        }
        item.data = data;

        item.trigger('data');

        // override me
        this.render();
    },

    _initItems: function() {
        var _this = this,
            items = _this.content.items;

        for (var itemNo = 0, l = items.length; itemNo < l; ++itemNo) {
            _this._initItem(itemNo);
        }
    },

    initXAxis: function(xAxisNo) { /* override me */ },
    _initXAxis: function(xAxisNo) {
        var _this = this,
            xAxis = _this.content.xAxes[xAxisNo],
            tAxes = _this.content.tAxes;

        var scale = xAxis.scale || {};
        xAxis.scale = Vis.create(
            scale,
            scale.name || 'i-scale-linear'
        );

        if (typeof xAxis.units === 'undefined') {
            xAxis.units = "";
        }

        if (xAxis.pos !== 'top' && xAxis.pos !== 'bottom') {
            xAxis.pos = 'bottom';
        }

        xAxis.tAxis = tAxes[xAxis.tAxisNo || 0] || Vis.error("No t-axis for x-axis #" + xAxisNo);

        if (typeof xAxis.rangeProvider.timeRangeProvider === 'undefined') {
            xAxis.rangeProvider.timeRangeProvider = xAxis.tAxis.rangeProvider;
        }
        xAxis.rangeProvider = Vis.create(
            xAxis.rangeProvider,
            xAxis.rangeProvider.name || 'undefined-x-range-provider'
        );

        if (typeof xAxis.processors === 'undefined') {
            xAxis.processors = [];
        }
        for (var i = 0, l = xAxis.processors.length; i < l; ++i) {
            var processor = xAxis.processors[i];
            processor.dimensions = _this.dimensions;
            processor.content = _this.content;
            xAxis.processors[i] = Vis.create(processor, processor.name);
        }

        _this.initXAxis(xAxisNo);

        xAxis.rangeProvider.on('update', function() {
            _this._updateXAxisRange(xAxisNo);
        });
        _this._updateXAxisRange(xAxisNo);
    },

    updateXAxisRange: function(xAxisNo) { /* override me */ },
    _updateXAxisRange: function(xAxisNo) {
        var _this = this,
            xAxis = _this.content.xAxes[xAxisNo],
            range = xAxis.rangeProvider.get(),
            scale = xAxis.scale;

        if (range.min == scale.inputMin && range.max == scale.inputMax) {
            return;
        }

        scale.input(range.min, range.max);

        _this.updateXAxisRange(xAxisNo);

        _this._renderXAxis(xAxisNo);
    },

    renderXAxis: function(xAxisNo, ticks) { /* override me */ },
    _renderXAxis: function(xAxisNo) {
        var _this = this,
            xAxis = this.content.xAxes[xAxisNo];

        xAxis.ticks = xAxis.scale.ticks(Math.floor(_this.dimensions.width / 65), xAxis.units);

        var ticks = Units.formatTicks(xAxis.ticks, xAxis.units, xAxis.scale);
        for (var i = 0, l = ticks.length; i < l; ++i) {
            var tick = ticks[i];
            tick.offset = Math.round(xAxis.scale.f(tick.tickValue));
        }

        _this.renderXAxis(xAxisNo, ticks);
    },

    initXAxes: function() { /* override me */ },
    _initXAxes: function() {
        var _this = this,
            xAxes = _this.content.xAxes;

        for (var xAxisNo = 0, l = xAxes.length; xAxisNo < l; ++xAxisNo) {
            _this._initXAxis(xAxisNo);
        }

        _this.initXAxes();
    },

    initYAxis: function(yAxisNo) { /* override me */ },
    _initYAxis: function(yAxisNo) {
        var _this = this,
            yAxis = _this.content.yAxes[yAxisNo];

        var scale = yAxis.scale || {};
        yAxis.scale = Vis.create(
            scale,
            scale.name || 'i-scale-linear'
        );

        if (typeof yAxis.units === 'undefined') {
            yAxis.units = "";
        }

        if (yAxis.pos !== 'left' && yAxis.pos !== 'right') {
            yAxis.pos = 'right';
        }

        yAxis.rangeProvider = Vis.create(
            yAxis.rangeProvider,
            yAxis.rangeProvider.name || 'undefined-y-range-provider'
        );

        if (typeof yAxis.processors === 'undefined') {
            yAxis.processors = [];
        }
        for (var i = 0, l = yAxis.processors.length; i < l; ++i) {
            var processor = yAxis.processors[i];
            processor.dimensions = _this.dimensions;
            processor.content = _this.content;
            yAxis.processors[i] = Vis.create(processor, processor.name);
        }

        _this.initXAxis(yAxisNo);

        yAxis.rangeProvider.on('update', function() {
            _this._updateYAxisRange(yAxisNo);
        });
        _this._updateYAxisRange(yAxisNo);
    },

    updateYAxisRange: function(yAxisNo) { /* override me */ },
    _updateYAxisRange: function(yAxisNo) {
        var _this = this,
            yAxis = _this.content.yAxes[yAxisNo],
            range = yAxis.rangeProvider.get(),
            scale = yAxis.scale;

        if (range.min == scale.inputMin && range.max == scale.inputMax) {
            return;
        }

        scale.input(range.min, range.max);

        _this.updateYAxisRange(yAxisNo);

        _this._renderYAxis(yAxisNo);
    },

    renderYAxis: function(yAxisNo, ticks) { /* override me */ },
    _renderYAxis: function(yAxisNo) {
        var _this = this,
            yAxis = this.content.yAxes[yAxisNo];

        yAxis.ticks = yAxis.scale.ticks(Math.floor(_this.dimensions.height / 40), yAxis.units);

        var ticks = Units.formatTicks(yAxis.ticks, yAxis.units, yAxis.scale);
        for (var i = 0, l = ticks.length; i < l; ++i) {
            var tick = ticks[i];
            tick.offset = _this.dimensions.height - Math.round(yAxis.scale.f(tick.tickValue)) - 1;
        }

        _this.renderYAxis(yAxisNo, ticks);
    },

    initYAxes: function() { /* override me */ },
    _initYAxes: function() {
        var _this = this,
            yAxes = _this.content.yAxes;

        for (var yAxisNo = 0, l = yAxes.length; yAxisNo < l; ++yAxisNo) {
            _this._initYAxis(yAxisNo);
        }

        _this.initYAxes();
    },

    initOverlay: function(overlayNo) { /* override me */ },
    _initOverlay: function(overlayNo) {
        var _this = this,
            overlays = _this.content.overlays,
            overlay = overlays[overlayNo];

        overlay.dimensions = _this.dimensions;
        overlay.content = _this.content;
        overlays[overlayNo] = Vis.create(
            overlay,
            overlay.name || 'undefined-overlay'
        );

        _this.initOverlay(overlayNo);
    },

    _initOverlays: function() {
        var _this = this,
            overlays = _this.content.overlays;

        for (var i = 0, l = overlays.length; i < l; ++i) {
            _this._initOverlay(i);
        }
    },

    initContent: function () { /* override me */ },
    _initContent: function () {
        this._initTAxes();
        this._initItems();
        this._initXAxes();
        this._initYAxes();
        this._initOverlays();

        this.initContent();
    },

    applySize: function () { /* override me */ },
    _applySize: function() {
        var _this = this,
            dim = _this.dimensions,
            xAxes = _this.content.xAxes,
            yAxes = _this.content.yAxes,
            i, l;

        for (i = 0, l = xAxes.length; i < l; ++i) {
            xAxes[i].scale.output(0, dim.width - 1);
        }

        for (i = 0, l = yAxes.length; i < l; ++i) {
            yAxes[i].scale.output(0, dim.height - 1);
        }

        _this.applySize();
    },

    initResize: function() {
        // override me
    },

    setYAxes: function(yAxes) {
        var _this = this;

        _this._destroyYAxes();
        _this.content.yAxes = yAxes;

        for (var yAxisNo = 0, l = yAxes.length; yAxisNo < l; ++yAxisNo) {
            _this._initYAxis(yAxisNo);
        }
        _this._initYAxes();

        _this._initState.yAxes = true;
        _this._updateInit();
    },

    setXAxes: function(xAxes) {
        var _this = this;

        _this._destroyXAxes();
        _this.content.xAxes = xAxes;

        for (var xAxisNo = 0, l = xAxes.length; xAxisNo < l; ++xAxisNo) {
            _this._initXAxis(xAxisNo);
        }
        _this._initXAxes();

        _this._initState.xAxes = true;
        _this._updateInit();
    },

    _updateItem: function(itemNo) {
        var _this = this,
            item = _this.content.items[itemNo];

        _this._updateItemData(item);
        item.ready = true;
        _this.renderItem(itemNo);
    },

    _requestItemData: function(item) {
        var _this = this,
            xAxis = _this.content.xAxes[item.xAxis || 0] || _this.content.xAxes[0];

        item.ready = false;
        item.dataProvider.range(xAxis.scale.inputMin, xAxis.scale.inputMax);
    },

    _runProcessors: function() {
        var _this = this,
            yAxes = _this.content.yAxes,
            items = _this.content.items;

        for (var yAxisNo = 0, l = yAxes.length; yAxisNo < l; ++yAxisNo) {
            var yAxis = yAxes[yAxisNo];

            var axisItems = [];
            for (var i = 0, m = items.length; i < m; ++i) {
                var item = items[i];
                if (item.yAxis != yAxisNo) continue;

                item.renderData = item.data;
                axisItems.push(item);
            }

            for (var i = 0, m = yAxis.processors.length; i < m; ++i) {
                yAxis.processors[i].run(axisItems);
            }

            var range = yAxis.rangeProvider.get(axisItems);
            _this._updateYAxisRange(yAxisNo, range);
        }
    },

    beforeRender: function() {
        this._runProcessors();

        // override me
    },

    afterRender: function() {
        // override me
    },

    renderItem: function(itemNo) {
        if (this._init != -1) {
            return;
        }

        this.render();
    }
};

})(jQuery, Vis);
<|endoftext|>


<commit_before>const searchMembers = require("../../util/searchMembers");

const subcommands = {
    start: async function(ctx) {
        if (ctx.gcfg.trivia == ctx.channel.id && !ctx.client.trivia.channels.includes(ctx.channel.id)) {
            ctx.client.trivia.init(ctx.client, ctx.channel.id);
            return Promise.resolve();
        } else if (ctx.gcfg.trivia != 0 && ctx.gcfg.gtrivia != ctx.channel.id) {
            return ctx.send(ctx.strings.get("trivia_wrong_channel", ctx.gcfg.trivia));
        } else if (ctx.gcfg.trivia == 0 || ctx.gcfg.trivia == undefined) {
            return ctx.send(ctx.strings.get("trivia_no_channel", ctx.gcfg.prefix));
        }

        return Promise.resolve();
    },
    stop: async function(ctx) {
        if (ctx.client.trivia.channels.includes(ctx.channel.id)) {
            ctx.client.trivia.channels.splice(ctx.client.trivia.channels.indexOf(ctx.gcfg.trivia), 1);
            return ctx.success(ctx.strings.get("trivia_stopped"));
        }
    },
    top: async function(ctx) {
        let res;
        try {
            res = await ctx.client.pg.query("SELECT * FROM scores ORDER BY score DESC;");
        } catch (err) {
            console.error(err);
            return ctx.failure(ctx.strings.get("bot_generic_error"));
        }

        let msg = [];
        let rows = res.rows;
        if (ctx.options[0] == "all") {
            msg.push(ctx.strings.get("trivia_top_ten_bot"));
        } else {
            msg.push(ctx.strings.get("trivia_top_ten_server"));
            rows = rows.filter((row) => ctx.guild.members.get(row.id));
        }

        rows = rows.slice(0, 10);

        msg = msg.concat(rows.map((row) => {
            let user = ctx.client.users.find((user) => user.id == row.id);
            return `${user ? user.username : ctx.strings.get("trivia_unkown_user")}: ${row.score}`;
        }));

        return ctx.send(msg.join("\n"));
    },
    stats: async function(ctx) {
        let res;
        try {
            res = await ctx.client.pg.query("SELECT * FROM scores ORDER BY score DESC LIMIT 1;")
        } catch (err) {
            console.error(err);
            return ctx.failure(ctx.strings.get("bot_generic_error"));
        }

        let user = ctx.client.users.get(res.rows[0].id);

        return ctx.send([
            `**${ctx.strings.get("trivia_total_questions")}** ${ctx.client.trivia.questions.length}`,
            `**${ctx.strings.get("trivia_first_place")}** ${user ? user.username : ctx.strings.get("trivia_unkown_user")} - ${res.rows[0].score}`,
            `**${ctx.strings.get("trivia_concurrent_games")}** ${ctx.client.trivia.channels.length}`
        ].join("\n"));
    },
    points: async function(ctx) {
        let ID = ctx.author.id;

        if (ctx.options.length) {
            let result = await searchMembers(ctx.guild.members, ctx.options);
            if (result) ID = result.all[0];
        }

        let res;
        try {
            res = await ctx.client.pg.query("SELECT * FROM scores ORDER BY score DESC;");
        } catch (err) {
            console.error(err);
            return ctx.failure(ctx.strings.get("bot_generic_error"));
        }

        let user = ctx.client.users.get(ID);
        let row = res.rows.find((row) => row.id == ID);
        let guild = res.rows.filter((row) => ctx.guild.members.get(row.id));

        if (!row) {
            return ctx.send(ctx.strings.get("trivia_has_not_played", user.username));
        }

        let embed = {
            author: {
                name: user.username,
                icon_url: user.iconURL
            },
            description: [
                `**${ctx.strings.get("trivia_points")}** ${row.score}`,
                `**${ctx.strings.get("trivia_highest_streak")}** ${row.streak}`,
                `**${ctx.strings.get("trivia_server_rank")}** ${guild.indexOf(data) + 1}/${guild.length}`,
                `**${ctx.strings.get("trivia_global_rank")}** ${res.rows.indexOf(data) + 1}/${res.rows.length}`
            ].join("\n")
        }

        return ctx.embed(embed);
    }
}

async function exec(ctx) {
    const subcommand = ctx.options[0];

    if (subcommands.hasOwnProperty(subcommand)) {
        ctx.options = ctx.options.slice(1);
        return subcommands[subcommand](ctx);
    } else {
        return ctx.send(ctx.strings.get("bot_available_subcommands", Object.keys(subcommands).map((cmd) => `\`${cmd}\``).join(", ")));
    }
}

module.exports = {
    name: "trivia",
    category: "fun",
    exec
};
<commit_msg>fix trivia points<commit_after>const searchMembers = require("../../util/searchMembers");

const subcommands = {
    start: async function(ctx) {
        if (ctx.gcfg.trivia == ctx.channel.id && !ctx.client.trivia.channels.includes(ctx.channel.id)) {
            ctx.client.trivia.init(ctx.client, ctx.channel.id);
            return Promise.resolve();
        } else if (ctx.gcfg.trivia != 0 && ctx.gcfg.gtrivia != ctx.channel.id) {
            return ctx.send(ctx.strings.get("trivia_wrong_channel", ctx.gcfg.trivia));
        } else if (ctx.gcfg.trivia == 0 || ctx.gcfg.trivia == undefined) {
            return ctx.send(ctx.strings.get("trivia_no_channel", ctx.gcfg.prefix));
        }

        return Promise.resolve();
    },
    stop: async function(ctx) {
        if (ctx.client.trivia.channels.includes(ctx.channel.id)) {
            ctx.client.trivia.channels.splice(ctx.client.trivia.channels.indexOf(ctx.gcfg.trivia), 1);
            return ctx.success(ctx.strings.get("trivia_stopped"));
        }
    },
    top: async function(ctx) {
        let res;
        try {
            res = await ctx.client.pg.query("SELECT * FROM scores ORDER BY score DESC;");
        } catch (err) {
            console.error(err);
            return ctx.failure(ctx.strings.get("bot_generic_error"));
        }

        let msg = [];
        let rows = res.rows;
        if (ctx.options[0] == "all") {
            msg.push(ctx.strings.get("trivia_top_ten_bot"));
        } else {
            msg.push(ctx.strings.get("trivia_top_ten_server"));
            rows = rows.filter((row) => ctx.guild.members.get(row.id));
        }

        rows = rows.slice(0, 10);

        msg = msg.concat(rows.map((row) => {
            let user = ctx.client.users.find((user) => user.id == row.id);
            return `${user ? user.username : ctx.strings.get("trivia_unkown_user")}: ${row.score}`;
        }));

        return ctx.send(msg.join("\n"));
    },
    stats: async function(ctx) {
        let res;
        try {
            res = await ctx.client.pg.query("SELECT * FROM scores ORDER BY score DESC LIMIT 1;")
        } catch (err) {
            console.error(err);
            return ctx.failure(ctx.strings.get("bot_generic_error"));
        }

        let user = ctx.client.users.get(res.rows[0].id);

        return ctx.send([
            `**${ctx.strings.get("trivia_total_questions")}** ${ctx.client.trivia.questions.length}`,
            `**${ctx.strings.get("trivia_first_place")}** ${user ? user.username : ctx.strings.get("trivia_unkown_user")} - ${res.rows[0].score}`,
            `**${ctx.strings.get("trivia_concurrent_games")}** ${ctx.client.trivia.channels.length}`
        ].join("\n"));
    },
    points: async function(ctx) {
        let ID = ctx.author.id;

        if (ctx.options.length) {
            let result = await searchMembers(ctx.guild.members, ctx.options);
            if (result) ID = result.all[0];
        }

        let res;
        try {
            res = await ctx.client.pg.query("SELECT * FROM scores ORDER BY score DESC;");
        } catch (err) {
            console.error(err);
            return ctx.failure(ctx.strings.get("bot_generic_error"));
        }

        let user = ctx.client.users.get(ID);
        let row = res.rows.find((row) => row.id == ID);
        let guild = res.rows.filter((row) => ctx.guild.members.get(row.id));

        if (!row) {
            return ctx.send(ctx.strings.get("trivia_has_not_played", user.username));
        }

        let embed = {
            author: {
                name: user.username,
                icon_url: user.iconURL
            },
            description: [
                `**${ctx.strings.get("trivia_points")}** ${row.score}`,
                `**${ctx.strings.get("trivia_highest_streak")}** ${row.streak}`,
                `**${ctx.strings.get("trivia_server_rank")}** ${guild.indexOf(row) + 1}/${guild.length}`,
                `**${ctx.strings.get("trivia_global_rank")}** ${res.rows.indexOf(row) + 1}/${res.rows.length}`
            ].join("\n")
        }

        return ctx.embed(embed);
    }
}

async function exec(ctx) {
    const subcommand = ctx.options[0];

    if (subcommands.hasOwnProperty(subcommand)) {
        ctx.options = ctx.options.slice(1);
        return subcommands[subcommand](ctx);
    } else {
        return ctx.send(ctx.strings.get("bot_available_subcommands", Object.keys(subcommands).map((cmd) => `\`${cmd}\``).join(", ")));
    }
}

module.exports = {
    name: "trivia",
    category: "fun",
    exec
};
<|endoftext|>


<commit_before>module.exports = {

  data: {
    title: 'Star Wars Episode IV A New Hope',
    description: 'Info about what makes this cut interesting',

    //Can be used to validate you have the same copy?
    uuid: 'torrent-hash-here',

    //Give your cut a rating
    rating: 'PG'
  },

  times: [
    { start: '00:00:00', end: '00:03:48' }
    , { start: '00:03:52', end: '00:03:56' }
    , { start: '00:04:01', end: '00:04:03' }
    , { start: '00:04:13', end: '00:04:17' }
    , { start: '00:04:24', end: '00:05:32' }
    , { start: '00:06:05', end: '00:06:26' }
    , { start: '00:06:28', end: '00:07:28' }
      //vader confronts pricess
    , { start: '00:07:28', end: '00:08:10' }
    , { start: '00:08:29', end: '00:13:58' }
    , { start: '00:14:09', end: '00:14:33' }
    , { start: '00:14:47', end: '00:18:11' }
      //right before sandperson scares the shit out of c3p0
    , { start: '00:18:14', end: '00:28:54' }
    , { start: '00:29:34', end: '00:34:25' }
    , { start: '00:34:34', end: '00:36:01' }
    , { start: '00:36:54', end: '00:37:00' }
    , { start: '00:38:05', end: '00:38:09' }
    //skip evil conference of admirals, lack of faith disturbing,
    //the whole dead jawas, lukes family
    , { start: '00:40:55', end: '00:41:00' }
    //cantina
    , { start: '00:42:28', end: '00:46:35' }
    , { start: '00:47:19', end: '00:49:58' }
    //skip greedo :|
    , { start: '00:51:13', end: '00:51:19' }
    , { start: '00:52:14', end: '00:52:40' }
    , { start: '00:54:13', end: '00:57:17' }
    , { start: '00:59:13', end: '01:02:43' }
    , { start: '01:03:45', end: '01:11:00' }

    , { start: '01:11:57', end: '01:14:02' }
    , { start: '01:15:11', end: '01:17:13' }
    , { start: '01:17:40', end: '01:18:13' }
    , { start: '01:18:15', end: '01:18:41' }
    , { start: '01:19:01', end: '01:19:36' }
    //exit the garbage compactor
    , { start: '01:25:00', end: '01:25:50' }

    , { start: '01:26:25', end: '01:27:22' }
    , { start: '01:27:50', end: '01:28:22' }
    , { start: '01:28:41', end: '01:28:54' }
    , { start: '01:29:07', end: '01:29:55' }
    //start obi v dv
    , { start: '01:29:56', end: '01:31:28' }
    , { start: '01:31:29', end: '01:31:44' }
    //lightsaber
    , { start: '01:31:45', end: '01:31:55' }

    , { start: '01:31:56', end: '01:32:17' }

    //death of obiwanskipped, escape from DS
    , { start: '01:32:18', end: '01:32:22' }
    , { start: '01:33:37', end: '01:33:47' }
    // , { start: '01:32:23', end: '01:34:01' }

    // tie fight vs MF
    , { start: '01:34:02', end: '01:36:30' }

    , { start: '01:38:07', end: '01:38:30' }
    , { start: '01:38:31', end: '01:41:15' }
    , { start: '01:41:25', end: '01:41:35' }
    , { start: '01:43:10', end: '01:45:07' }

    //begin assault on DS
    , { start: '01:45:22', end: '01:47:19' }
    , { start: '01:47:38', end: '01:48:11' }
    , { start: '01:48:13', end: '01:50:40' }
    , { start: '01:51:42', end: '01:52:40' }
    , { start: '01:52:54', end: '01:53:20' }
    , { start: '01:53:34', end: '01:55:05' }
    , { start: '01:55:14', end: '02:04:39' }

  ]

};<commit_msg>remove kill<commit_after>module.exports = {

  data: {
    title: 'Star Wars Episode IV A New Hope',
    description: 'Info about what makes this cut interesting',

    //Can be used to validate you have the same copy?
    uuid: 'torrent-hash-here',

    //Give your cut a rating
    rating: 'PG'
  },

  times: [
    { start: '00:00:00', end: '00:03:48' }
    , { start: '00:03:52', end: '00:03:56' }
    , { start: '00:04:01', end: '00:04:03' }
    , { start: '00:04:13', end: '00:04:17' }
    , { start: '00:04:24', end: '00:05:32' }
    , { start: '00:06:05', end: '00:06:26' }
    , { start: '00:06:28', end: '00:07:28' }
      //vader confronts pricess
    , { start: '00:07:28', end: '00:08:10' }
    , { start: '00:08:29', end: '00:13:58' }
    , { start: '00:14:09', end: '00:14:33' }
    , { start: '00:14:47', end: '00:18:11' }
      //right before sandperson scares the shit out of c3p0
    , { start: '00:18:14', end: '00:28:54' }
    , { start: '00:29:34', end: '00:34:25' }
    , { start: '00:34:34', end: '00:36:01' }
    , { start: '00:36:54', end: '00:37:00' }
    , { start: '00:38:05', end: '00:38:09' }
    //skip evil conference of admirals, lack of faith disturbing,
    //the whole dead jawas, lukes family
    , { start: '00:40:55', end: '00:41:00' }
    //cantina
    , { start: '00:42:28', end: '00:46:35' }
    , { start: '00:47:19', end: '00:49:58' }
    //skip greedo :|
    , { start: '00:51:13', end: '00:51:19' }
    , { start: '00:52:14', end: '00:52:40' }
    , { start: '00:54:13', end: '00:57:17' }
    , { start: '00:59:13', end: '01:02:43' }
    , { start: '01:03:45', end: '01:08:44' }
    , { start: '01:08:51', end: '01:11:00' }

    , { start: '01:11:57', end: '01:14:02' }
    , { start: '01:15:11', end: '01:17:13' }
    , { start: '01:17:40', end: '01:18:13' }
    , { start: '01:18:15', end: '01:18:41' }
    , { start: '01:19:01', end: '01:19:36' }
    //exit the garbage compactor
    , { start: '01:25:00', end: '01:25:50' }

    , { start: '01:26:25', end: '01:27:22' }
    , { start: '01:27:50', end: '01:28:22' }
    , { start: '01:28:41', end: '01:28:54' }
    , { start: '01:29:07', end: '01:29:55' }
    //start obi v dv
    , { start: '01:29:56', end: '01:31:28' }
    , { start: '01:31:29', end: '01:31:44' }
    //lightsaber
    , { start: '01:31:45', end: '01:31:55' }

    , { start: '01:31:56', end: '01:32:17' }

    //death of obiwanskipped, escape from DS
    , { start: '01:32:18', end: '01:32:22' }
    , { start: '01:33:37', end: '01:33:47' }
    // , { start: '01:32:23', end: '01:34:01' }

    // tie fight vs MF
    , { start: '01:34:02', end: '01:36:30' }

    , { start: '01:38:07', end: '01:38:30' }
    , { start: '01:38:31', end: '01:41:15' }
    , { start: '01:41:25', end: '01:41:35' }
    , { start: '01:43:10', end: '01:45:07' }

    //begin assault on DS
    , { start: '01:45:22', end: '01:47:19' }
    , { start: '01:47:38', end: '01:48:11' }
    , { start: '01:48:13', end: '01:50:40' }
    , { start: '01:51:42', end: '01:52:40' }
    , { start: '01:52:54', end: '01:53:20' }
    , { start: '01:53:34', end: '01:55:05' }
    , { start: '01:55:14', end: '02:04:39' }

  ]

};<|endoftext|>


<commit_before>var componentEvent = require('kwf/component-event');
var cookies = require('js-cookie');

var CookieOpt = {};

CookieOpt.getDefaultOpt = function() {
    return 'in'; // TODO get from baseProperty
};

CookieOpt.isSetOpt = function() {
    return !!cookies.get('cookieOpt');
};

CookieOpt.getOpt = function() {
    if (CookieOpt.isSetOpt()) {
        return cookies.get('cookieOpt');
    } else {
        return CookieOpt.getDefaultOpt();
    }
};

CookieOpt.setOpt = function(value) {
    var opt = cookies.get('cookieOpt');
    cookies.set('cookieOpt', value, { expires: 3*365 });
    if (opt != value) {
        componentEvent.trigger('cookieOptChanged', value);
    }
};

CookieOpt.onOptChange = function(callback) {
    componentEvent.on('cookieOptChange', callback);
};

module.exports = CookieOpt;
<commit_msg>Fix typo<commit_after>var componentEvent = require('kwf/component-event');
var cookies = require('js-cookie');

var CookieOpt = {};

CookieOpt.getDefaultOpt = function() {
    return 'in'; // TODO get from baseProperty
};

CookieOpt.isSetOpt = function() {
    return !!cookies.get('cookieOpt');
};

CookieOpt.getOpt = function() {
    if (CookieOpt.isSetOpt()) {
        return cookies.get('cookieOpt');
    } else {
        return CookieOpt.getDefaultOpt();
    }
};

CookieOpt.setOpt = function(value) {
    var opt = cookies.get('cookieOpt');
    cookies.set('cookieOpt', value, { expires: 3*365 });
    if (opt != value) {
        componentEvent.trigger('cookieOptChanged', value);
    }
};

CookieOpt.onOptChange = function(callback) {
    componentEvent.on('cookieOptChanged', callback);
};

module.exports = CookieOpt;
<|endoftext|>


<commit_before>import React from 'react'
import Helmet from 'react-helmet'
import InlineSVG from 'svg-inline-react'
import classNames from 'classnames'

const BoxPage = ({
  icon,
  title,
  subtitle,
  metaTitle,
  children,
  inverse,
  expanded,
  ogImage,
  ogDecription,
}) => {
  const metaData = [
    {
      property: 'og:title',
      content: `${metaTitle || title} - JSConf Iceland 2018`,
    },
    {
      name: 'twitter:title',
      content: `${metaTitle || title} - JSConf Iceland 2018`,
    },
  ]

  if (typeof ogImage !== 'undefined') {
    metaData.push(
      {
        property: 'og:image',
        content: ogImage,
      },
      {
        name: 'twitter:image',
        content: ogImage,
      }
    )
  }

  if (typeof ogDecription !== 'undefined') {
    metaData.push(
      { property: 'og:description', content: ogDecription },
      { name: 'twitter:description', content: ogDecription }
    )
  }

  return (

      <Helmet title={metaTitle || title} meta={metaData} />

          {icon && (

              <InlineSVG src={icon} />

          )}

{title}

        {subtitle &&
{subtitle}
}
        {expanded ? (
          children
        ) : (

              {children}

        )}

  )
}

BoxPage.propTypes = {
  icon: React.PropTypes.string,
  title: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.node,
  ]),
  inverse: React.PropTypes.bool,
  expanded: React.PropTypes.bool,
  metaTitle: React.PropTypes.string,
  children: React.PropTypes.node,
  subtitle: React.PropTypes.node,
}

export default BoxPage
<commit_msg>Add missing proptypes<commit_after>import React from 'react'
import Helmet from 'react-helmet'
import InlineSVG from 'svg-inline-react'
import classNames from 'classnames'

const BoxPage = ({
  icon,
  title,
  subtitle,
  metaTitle,
  children,
  inverse,
  expanded,
  ogImage,
  ogDecription,
}) => {
  const metaData = [
    {
      property: 'og:title',
      content: `${metaTitle || title} - JSConf Iceland 2018`,
    },
    {
      name: 'twitter:title',
      content: `${metaTitle || title} - JSConf Iceland 2018`,
    },
  ]

  if (typeof ogImage !== 'undefined') {
    metaData.push(
      {
        property: 'og:image',
        content: ogImage,
      },
      {
        name: 'twitter:image',
        content: ogImage,
      }
    )
  }

  if (typeof ogDecription !== 'undefined') {
    metaData.push(
      { property: 'og:description', content: ogDecription },
      { name: 'twitter:description', content: ogDecription }
    )
  }

  return (

      <Helmet title={metaTitle || title} meta={metaData} />

          {icon && (

              <InlineSVG src={icon} />

          )}

{title}

        {subtitle &&
{subtitle}
}
        {expanded ? (
          children
        ) : (

              {children}

        )}

  )
}

BoxPage.propTypes = {
  icon: React.PropTypes.string,
  title: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.node,
  ]),
  inverse: React.PropTypes.bool,
  expanded: React.PropTypes.bool,
  metaTitle: React.PropTypes.string,
  children: React.PropTypes.node,
  subtitle: React.PropTypes.node,
  ogImage: React.PropTypes.string,
  ogDecription: React.PropTypes.string,
}

export default BoxPage
<|endoftext|>


<commit_before>/**
 * Copyright 2014 Nicholas Humfrey
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

var http = require('http');
var util = require("util");
var express = require("express");
var nopt = require("nopt");
var path = require("path");
var fs = require("fs");
var mqtt = require('mqtt');

// Middleware
var bodyParser = require('body-parser');
var errorhandler = require('errorhandler');
var morgan  = require('morgan');

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(morgan());

// development only
if (process.env.NODE_ENV === 'development') {
  app.use(errorhandler());
}

var knownOpts = {
    "settings":[path],
    "v": Boolean,
    "help": Boolean
};
var shortHands = {
    "s":["--settings"],
    "?":["--help"]
};
nopt.invalidHandler = function(k,v,t) {
    console.log(k,v,t);
}

var parsedArgs = nopt(knownOpts,shortHands,process.argv,2)

if (parsedArgs.help) {
    console.log("Marquette");
    console.log("Usage: node marquette.js [-v] [-?] [--settings settings.js]");
    console.log("");
    console.log("Options:");
    console.log("  -s, --settings FILE  use specified settings file");
    console.log("  -v                   enable verbose output");
    console.log("  -?, --help           show usage");
    process.exit();
}

var settingsFile = parsedArgs.settings || "./settings";
try {
    var settings = require(settingsFile);
} catch(err) {
    if (err.code == 'MODULE_NOT_FOUND') {
        console.log("Unable to load settings file "+settingsFile);
    } else {
        console.log(err);
    }
    process.exit();
}

if (parsedArgs.v) {
    settings.verbose = true;
}

settings.uiHost = settings.uiHost||"0.0.0.0";
settings.uiPort = settings.uiPort||1890;
settings.mqttHost = settings.mqttHost||"127.0.0.1";
settings.mqttPort = settings.mqttPort||1883;

process.on('uncaughtException',function(err) {
    util.log('[marquette] Uncaught Exception:');
    util.log(err.stack);
    process.exit(1);
});

process.on('SIGINT', function () {
    process.exit();
});

browsers = [];
topics = {};
tiles = require('./tiles.json');

// Connect to the MQTT sever
client = mqtt.createClient(settings.mqttPort, settings.mqttHost);
tiles.forEach(function(tile) {
    if (tile.subscribe_topic) {
        client.subscribe(tile.subscribe_topic);
    }
});

// When a message is received from the MQTT server, pass it on to the browsers
client.on('message', function(topic, payload) {
    console.log("Received MQTT: "+payload);
    topics[topic] = payload;

    browsers.forEach(function(res) {
        console.log("  informing browser: "+res);
        res.write("data: " + JSON.stringify({topic:topic, payload:payload}) + "\n\n");
    });
});

// Send a ping every 20 seconds to the browsers to keep the HTTP connections open
setInterval(function() {
    browsers.forEach(function(res) {
        res.write(": ping\n\n");
    });
}, 20000);

app.get('/tiles', function(req, res) {
    res.send(tiles);
});

// FIXME: this should be a PUT
app.post('/tiles', function(req, res) {
    fs.writeFile('tiles.json', JSON.stringify(req.body, null, 4), function(err) {
        if(err) {
          console.log(err);
          res.status(500).send(err);
        } else {
          res.status(204).end();
        }
    });
});

app.get('/update-stream', function(req, res) {
    req.socket.setNoDelay(true);
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache'
    });
    res.write(":\n");

    browsers.push(res);

    req.on("close", function() {
        index = browsers.indexOf(req);
        browsers.splice(index, 1);
    });
});

app.get('/topics', function(req, res) {
  res.send(topics);
});

app.get('/topics/*', function(req, res) {
    var topic = req.params[0];
    res.type('text/plain');
    if (topic in topics) {
        res.status(200).send(topics[topic]);
    } else {
        res.status(404).send('Topic Not Found');
    }
});

app.post('/topics/*', function(req, res) {
    var topic = req.params[0];
    console.log("Publishing: '"+req.body.payload+"' to '"+topic+"'");
    client.publish(topic, req.body.payload);
    res.status(204).end();
});

// Serve a static file, if it exists
app.use(express.static(path.join(__dirname, 'public')));

var server = http.createServer(app)
server.listen(settings.uiPort, settings.uiHost, function(){
    console.log('Express server listening on port ' + settings.uiPort);
});
<commit_msg>Send stored topic values when browser first connects<commit_after>/**
 * Copyright 2014 Nicholas Humfrey
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

var http = require('http');
var util = require("util");
var express = require("express");
var nopt = require("nopt");
var path = require("path");
var fs = require("fs");
var mqtt = require('mqtt');

// Middleware
var bodyParser = require('body-parser');
var errorhandler = require('errorhandler');
var morgan  = require('morgan');

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(morgan());

// development only
if (process.env.NODE_ENV === 'development') {
  app.use(errorhandler());
}

var knownOpts = {
    "settings":[path],
    "v": Boolean,
    "help": Boolean
};
var shortHands = {
    "s":["--settings"],
    "?":["--help"]
};
nopt.invalidHandler = function(k,v,t) {
    console.log(k,v,t);
}

var parsedArgs = nopt(knownOpts,shortHands,process.argv,2)

if (parsedArgs.help) {
    console.log("Marquette");
    console.log("Usage: node marquette.js [-v] [-?] [--settings settings.js]");
    console.log("");
    console.log("Options:");
    console.log("  -s, --settings FILE  use specified settings file");
    console.log("  -v                   enable verbose output");
    console.log("  -?, --help           show usage");
    process.exit();
}

var settingsFile = parsedArgs.settings || "./settings";
try {
    var settings = require(settingsFile);
} catch(err) {
    if (err.code == 'MODULE_NOT_FOUND') {
        console.log("Unable to load settings file "+settingsFile);
    } else {
        console.log(err);
    }
    process.exit();
}

if (parsedArgs.v) {
    settings.verbose = true;
}

settings.uiHost = settings.uiHost||"0.0.0.0";
settings.uiPort = settings.uiPort||1890;
settings.mqttHost = settings.mqttHost||"127.0.0.1";
settings.mqttPort = settings.mqttPort||1883;

process.on('uncaughtException',function(err) {
    util.log('[marquette] Uncaught Exception:');
    util.log(err.stack);
    process.exit(1);
});

process.on('SIGINT', function () {
    process.exit();
});

browsers = [];
topics = {};
tiles = require('./tiles.json');

// Connect to the MQTT sever
client = mqtt.createClient(settings.mqttPort, settings.mqttHost);
tiles.forEach(function(tile) {
    if (tile.subscribe_topic) {
        client.subscribe(tile.subscribe_topic);
    }
});

// When a message is received from the MQTT server, pass it on to the browsers
client.on('message', function(topic, payload) {
    console.log("Received MQTT: "+payload);
    topics[topic] = payload;

    browsers.forEach(function(res) {
        console.log("  informing browser: "+res);
        res.write("data: " + JSON.stringify({topic:topic, payload:payload}) + "\n\n");
    });
});

// Send a ping every 20 seconds to the browsers to keep the HTTP connections open
setInterval(function() {
    browsers.forEach(function(res) {
        res.write(": ping\n\n");
    });
}, 20000);

app.get('/tiles', function(req, res) {
    res.send(tiles);
});

// FIXME: this should be a PUT
app.post('/tiles', function(req, res) {
    fs.writeFile('tiles.json', JSON.stringify(req.body, null, 4), function(err) {
        if(err) {
          console.log(err);
          res.status(500).send(err);
        } else {
          res.status(204).end();
        }
    });
});

app.get('/update-stream', function(req, res) {
    req.socket.setNoDelay(true);
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache'
    });
    res.write(":\n");

    browsers.push(res);

    Object.keys(topics).forEach(function(key) {
        res.write("data: " + JSON.stringify({topic:key, payload:topics[key]}) + "\n\n");
    });

    req.on("close", function() {
        index = browsers.indexOf(req);
        browsers.splice(index, 1);
    });
});

app.get('/topics', function(req, res) {
  res.send(topics);
});

app.get('/topics/*', function(req, res) {
    var topic = req.params[0];
    res.type('text/plain');
    if (topic in topics) {
        res.status(200).send(topics[topic]);
    } else {
        res.status(404).send('Topic Not Found');
    }
});

app.post('/topics/*', function(req, res) {
    var topic = req.params[0];
    console.log("Publishing: '"+req.body.payload+"' to '"+topic+"'");
    client.publish(topic, req.body.payload);
    res.status(204).end();
});

// Serve a static file, if it exists
app.use(express.static(path.join(__dirname, 'public')));

var server = http.createServer(app)
server.listen(settings.uiPort, settings.uiHost, function(){
    console.log('Express server listening on port ' + settings.uiPort);
});
<|endoftext|>


<commit_before>var gTestMenu =
  {
    NUM_CELLS: 250,
    DISPLAY_TIME: 4600,
    FADE_OUT_TIME: 400
  };

gTestMenu.init = function () {
  gTestMenu.reset ();
  gTestMenu.text = "";
  gTestMenu.backupText = "";
  var tape = d3.select (".tape-field");
  gTestMenu.showPlaceholder = true;
  for (var i = 0; i < gTestMenu.NUM_CELLS; i++) {
    tape.append ("input")
      .attr ("type", "text")
      .classed ("tape-char", true)
      .attr ("name", "tapeChar[]")
      .attr ("maxlength", 1)
      .attr ("readonly", "readonly")
      .on ("click", gTestMenu.allowInput);
  }
  d3.select (".tape-char-input")
    .attr ("maxlength", gTestMenu.NUM_CELLS)
    .on ("keydown", function () {
      if (d3.event.keyCode == 13) {
        gTestMenu.disallowInput ();
        gTestMenu.run ();
      }
    });

  gTestMenu.disallowInput ();
};

gTestMenu.reset = function () {
  gTestMenu.setRunning (false);
  d3.select (".tape-char-input").node ().value = gTestMenu.backupText || "";
  d3.selectAll (".current-tape-char")
    .classed ("current-tape-char", false);
  d3.selectAll (".current-tape-char-solid")
    .classed ("current-tape-char-solid", false);
  gTestMenu.disallowInput ();
  gTape.reset ();
};

gTestMenu.allowInput = function () {
  gTestMenu.showPlaceholder = false;
  gTestMenu.reset ();
  d3.select (".tape-char-input").node ().value = gTestMenu.backupText;

  d3.selectAll (".tape-char")
    .style ("display", "none");

  d3.select (".tape-char-input")
    .style ("display", "inline")
    .each (function () { this.focus (); });
};

gTestMenu.disallowInput = function (text) {
  if (gTestMenu.backupText != intersection (d3.select (".tape-char-input").node ().value, gGraph.charSet)) {
     gTestMenu.backupText = d3.select (".tape-char-input").node ().value;
     var legal = intersection (gTestMenu.backupText, gGraph.charSet)
    if (gTestMenu.backupText.length != legal.length) {
      gErrorMenu.displayError ("Removing characters that aren't in the alphabet.");
    }
    gTestMenu.backupText = legal;
  }
  gTestMenu.text = text == undefined ? gTestMenu.backupText : text;

  var displayString = "Click to enter a test";
  d3.selectAll (".tape-char")
    .style ("display", "inline")
    .style ("color", gTestMenu.showPlaceholder ? "#bbb" : "#fff")
    .each (function (junk, i) {
      var text = gTestMenu.showPlaceholder ? displayString : gTestMenu.text;
      this.value = i < text.length ? text[i] : "";
    });

  d3.select (".tape-char-input")
    .style ("display", "none");
};

gTestMenu.unsetTransitions = function () {
  var missing = [];
  if (gGraph.mode == gGraph.DFA) {
    var graph = gGraph.save ();
    var table = gSimulator.convert (graph);
    for (var nodeId in table) {
      var hasMissing = false;
      for (var character in table[nodeId]) {
        hasMissing |= table[nodeId][character].length == 0;
      }
      if (hasMissing) {
        missing.push (gNodes.nodes[gNodes.getNodeIndex (nodeId)].name);
      }
    }
  }
  return missing;
};

gTestMenu.runTests = function () {
  var unset = gTestMenu.unsetTransitions ();
  if (gNodes.initial == null) {
    gErrorMenu.displayError ("This automaton doesn't have a start state.");
  } else if (unset.length != 0) {
    gErrorMenu.displayError ("The following states have undefined transitions: " + unset.join (", "));
  } else {
    gModalMenu.open ("testing");
  }
};

gTestMenu.setRunning = function (running) {
  if (running) {
    d3.selectAll (".running")
      .style ("display", "inline");
    d3.select (".runButton").text ("Restart");
  } else {
    d3.selectAll (".running")
      .style ("display", "none");
    d3.select (".runButton").text ("Start");
  }
};

gTestMenu.run = function () {
  gTestMenu.reset ();
  var unset = gTestMenu.unsetTransitions ();
  if (gNodes.initial == null) {
    gErrorMenu.displayError ("This automaton doesn't have a start state.");
  } else if (unset.length != 0) {
    gErrorMenu.displayError ("The following states have undefined transitions: " + unset.join (", "));
  } else {
    gTestMenu.setRunning (true);
    gTape.show ();
    gTape.run ();
  }
};

gTestMenu.end = function () {
  gTestMenu.setRunning (false);
  d3.selectAll (".current-tape-char")
    .classed ("current-tape-char", false);
  d3.selectAll (".current-tape-char-solid")
    .classed ("current-tape-char-solid", false);
  gTestMenu.disallowInput ();
  gTape.hide ();
};

gTestMenu.step = function () {
  var unset = gTestMenu.unsetTransitions ();
  if (gNodes.initial == null) {
    gErrorMenu.displayError ("No initial node is set");
  } else if (unset.length != 0) {
    gErrorMenu.displayError ("The following nodes have undefined transitions: " + unset.join (", "));
  } else {
    gTape.show ();
    gTape.step ();
  }
};
<commit_msg>Update test.js<commit_after>var gTestMenu =
  {
    NUM_CELLS: 250,
    DISPLAY_TIME: 4600,
    FADE_OUT_TIME: 400
  };

gTestMenu.init = function () {
  gTestMenu.reset ();
  gTestMenu.text = "";
  gTestMenu.backupText = "";
  var tape = d3.select (".tape-field");
  gTestMenu.showPlaceholder = true;
  for (var i = 0; i < gTestMenu.NUM_CELLS; i++) {
    tape.append ("input")
      .attr ("type", "text")
      .classed ("tape-char", true)
      .attr ("name", "tapeChar[]")
      .attr ("maxlength", 1)
      .attr ("readonly", "readonly")
      .on ("click", gTestMenu.allowInput);
  }
  d3.select (".tape-char-input")
    .attr ("maxlength", gTestMenu.NUM_CELLS)
    .on ("keydown", function () {
      if (d3.event.keyCode == 13) {
        gTestMenu.disallowInput ();
        gTestMenu.run ();
      }
    });

  gTestMenu.disallowInput ();
};

gTestMenu.reset = function () {
  gTestMenu.setRunning (false);
  d3.select (".tape-char-input").node ().value = gTestMenu.backupText || "";
  d3.selectAll (".current-tape-char")
    .classed ("current-tape-char", false);
  d3.selectAll (".current-tape-char-solid")
    .classed ("current-tape-char-solid", false);
  gTestMenu.disallowInput ();
  gTape.reset ();
};

gTestMenu.allowInput = function () {
  gTestMenu.showPlaceholder = false;
  gTestMenu.reset ();
  d3.select (".tape-char-input").node ().value = gTestMenu.backupText;

  d3.selectAll (".tape-char")
    .style ("display", "none");

  d3.select (".tape-char-input")
    .style ("display", "inline")
    .each (function () { this.focus (); });
};

gTestMenu.disallowInput = function (text) {
  if (gTestMenu.backupText != intersection (d3.select (".tape-char-input").node ().value, gGraph.charSet)) {
     gTestMenu.backupText = d3.select (".tape-char-input").node ().value;
     var legal = intersection (gTestMenu.backupText, gGraph.charSet)
    if (gTestMenu.backupText.length != legal.length) {
      gErrorMenu.displayError ("Removing characters that aren't in the alphabet.");
    }
    gTestMenu.backupText = legal;
  }
  gTestMenu.text = text == undefined ? gTestMenu.backupText : text;

  var displayString = "Click to enter a test";
  d3.selectAll (".tape-char")
    .style ("display", "inline")
    .style ("color", gTestMenu.showPlaceholder ? "#bbb" : "#fff")
    .each (function (junk, i) {
      var text = gTestMenu.showPlaceholder ? displayString : gTestMenu.text;
      this.value = i < text.length ? text[i] : "";
    });

  d3.select (".tape-char-input")
    .style ("display", "none");
};

gTestMenu.unsetTransitions = function () {
  var missing = [];
  if (gGraph.mode == gGraph.DFA) {
    var graph = gGraph.save ();
    var table = gSimulator.convert (graph);
    for (var nodeId in table) {
      var hasMissing = false;
      for (var character in table[nodeId]) {
        hasMissing |= table[nodeId][character].length == 0;
      }
      if (hasMissing) {
        missing.push (gNodes.nodes[gNodes.getNodeIndex (nodeId)].name);
      }
    }
  }
  return missing;
};

gTestMenu.runTests = function () {
  var unset = gTestMenu.unsetTransitions ();
  if (gNodes.initial == null) {
    gErrorMenu.displayError ("This automaton doesn't have a start state.");
  } else if (unset.length != 0) {
    gErrorMenu.displayError ("The following states have undefined transitions: " + unset.join (", "));
  } else {
    gModalMenu.open ("testing");
  }
};

gTestMenu.setRunning = function (running) {
  if (running) {
    d3.selectAll (".running")
      .style ("display", "inline");
    d3.select (".runButton").text ("Restart");
  } else {
    d3.selectAll (".running")
      .style ("display", "none");
    d3.select (".runButton").text ("Start");
  }
};

gTestMenu.run = function () {
  var unset = gTestMenu.unsetTransitions ();
  if (gNodes.initial == null) {
    gErrorMenu.displayError ("This automaton doesn't have a start state.");
  } else if (unset.length != 0) {
    gErrorMenu.displayError ("The following states have undefined transitions: " + unset.join (", "));
  } else {
    gTestMenu.showPlaceholder = false;
    gTestMenu.reset ();
    gTestMenu.setRunning (true);
    gTape.show ();
    gTape.run ();
  }
};

gTestMenu.end = function () {
  gTestMenu.setRunning (false);
  d3.selectAll (".current-tape-char")
    .classed ("current-tape-char", false);
  d3.selectAll (".current-tape-char-solid")
    .classed ("current-tape-char-solid", false);
  gTestMenu.disallowInput ();
  gTape.hide ();
};

gTestMenu.step = function () {
  var unset = gTestMenu.unsetTransitions ();
  if (gNodes.initial == null) {
    gErrorMenu.displayError ("No initial node is set");
  } else if (unset.length != 0) {
    gErrorMenu.displayError ("The following nodes have undefined transitions: " + unset.join (", "));
  } else {
    gTape.show ();
    gTape.step ();
  }
};
<|endoftext|>


<commit_before>'use strict';

var postcss = require('postcss');
var symbolyzers = [
    'polygon',
    'line',
    'marker',
    'shield',
    'text'
];

module.exports = function (cartoCss) {
    return postcss()
        .use(postcssCartocssMigrator())
        .process(cartoCss)
        .css;
};

var postcssCartocssMigrator = postcss.plugin('postcss-cartocss-migrator', function (options) {
    options = options || {};
    return function (css) {
        css.walkRules(function (rule) {
            symbolyzers.forEach(function (symbolizer) {
                setClipDefaultToTrue(rule, symbolizer);

                if (symbolizer === 'polygon') {
                    setPatternAlignmentDefaultToLocal(rule, symbolizer);
                }
            });
        });
    };
});

function setClipDefaultToTrue(rule, symbolizer) {
    var property = [symbolizer, 'clip'].join('-');

    if (hasPropertySymbolyzer(rule, symbolizer) && !hasPropertyAlreadyDefined(rule, property)) {
        var clipDecl = postcss.decl({ prop: property, value: true });
        rule.append(clipDecl);
    }
}

function setPatternAlignmentDefaultToLocal(rule, symbolizer) {
    var property = [symbolizer, 'pattern-aligment'].join('-');

    if (hasPropertySymbolyzer(rule, symbolizer) && !hasPropertyAlreadyDefined(rule, property)) {
        var patternAlignmentDecl = postcss.decl({ prop: property, value: 'local' });
        rule.append(patternAlignmentDecl);
    }
}

function hasPropertyAlreadyDefined(rule, property) {
    var hasPropertyAlreadyDefined = false;

    rule.walkDecls(function (decl) {
        if (decl.prop === property) {
            hasPropertyAlreadyDefined = true;
        }
    });

    return hasPropertyAlreadyDefined;
}

function hasPropertySymbolyzer(rule, symbolyzer) {
    var hasPropertySymbolyzer = false;

    rule.walkDecls(function (decl) {
        var property = decl.prop;

        if (property.indexOf(symbolyzer) === 0) {
            hasPropertySymbolyzer = true;
        }
    });

    return hasPropertySymbolyzer;
}
<commit_msg>Use generic function to set default values to properties<commit_after>'use strict';

var postcss = require('postcss');
var symbolyzers = [
    'polygon',
    'line',
    'marker',
    'shield',
    'text'
];

module.exports = function (cartoCss) {
    return postcss()
        .use(postcssCartocssMigrator())
        .process(cartoCss)
        .css;
};

var postcssCartocssMigrator = postcss.plugin('postcss-cartocss-migrator', function (options) {
    options = options || {};
    return function (css) {
        css.walkRules(function (rule) {
            symbolyzers.forEach(function (symbolizer) {
                setPropertyToDefault(rule, symbolizer, 'clip', true);
            });

            setPropertyToDefault(rule, 'polygon', 'pattern-aligment', 'local');
        });
    };
});

function setPropertyToDefault(rule, symbolizer, propSuffix, defaultValue) {
    var property = [symbolizer, propSuffix].join('-');

    if (hasPropertySymbolyzer(rule, symbolizer) && !hasPropertyAlreadyDefined(rule, property)) {
        var patternAlignmentDecl = postcss.decl({ prop: property, value: defaultValue });
        rule.append(patternAlignmentDecl);
    }
}

function hasPropertyAlreadyDefined(rule, property) {
    var hasPropertyAlreadyDefined = false;

    rule.walkDecls(function (decl) {
        if (decl.prop === property) {
            hasPropertyAlreadyDefined = true;
        }
    });

    return hasPropertyAlreadyDefined;
}

function hasPropertySymbolyzer(rule, symbolyzer) {
    var hasPropertySymbolyzer = false;

    rule.walkDecls(function (decl) {
        var property = decl.prop;

        if (property.indexOf(symbolyzer) === 0) {
            hasPropertySymbolyzer = true;
        }
    });

    return hasPropertySymbolyzer;
}
<|endoftext|>


<commit_before>'use strict';

describe('tmdb Factory', function() {
  var TmdbFactory, httpBackend;
  var baseUrl = 'http://localhost:3000/';
  var configUrl = baseUrl + 'configs';
  var config = {
    configs: [{
      images: {
        base_url: 'http://image.tmdb.org/t/p/', // jshint ignore:line
        secure_base_url: 'https://image.tmdb.org/t/p/', // jshint ignore:line
        backdrop_sizes: ['w300', 'w780', 'w1280', 'original'], // jshint ignore:line
        logo_sizes: ['w45', 'w92', 'w154', 'w185', 'w300', 'w500', 'original'], // jshint ignore:line
        poster_sizes: ['w92', 'w154', 'w185', 'w342', 'w500', 'w780', 'original'], // jshint ignore:line
        profile_sizes: ['w45', 'w185', 'h632', 'original'], // jshint ignore:line
        still_sizes: ['w92', 'w185', 'w300', 'original'] // jshint ignore:line
      }
    }]
  };

  beforeEach(module('polyflix'));

  beforeEach(inject(function($injector) {
    httpBackend = $injector.get('$httpBackend');
    httpBackend.whenGET(configUrl).respond(
      JSON.stringify(config)
    );
  }));

  beforeEach(inject(function(_TmdbFactory_) {
    TmdbFactory = _TmdbFactory_;
  }));

  afterEach(function() {
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
  });

  describe('call config', function() {
    it('config should exist', function() {
      expect(TmdbFactory.configuration).toEqual(undefined);
      httpBackend.expectGET(configUrl);
      TmdbFactory.config();
      httpBackend.flush();
      var objectImages = TmdbFactory.configuration.$object[0].images;
      var configImages = config.configs[0].images;
      expect(objectImages).toEqual(configImages);
    });
  });
});<commit_msg>Add test for all movies<commit_after>'use strict';

describe('tmdb Factory', function() {
  var TmdbFactory, httpBackend;
  var baseUrl = 'http://localhost:3000/';
  var configUrl = baseUrl + 'configs';
  var config = {
    configs: [{
      images: {
        base_url: 'http://image.tmdb.org/t/p/', // jshint ignore:line
        secure_base_url: 'https://image.tmdb.org/t/p/', // jshint ignore:line
        backdrop_sizes: ['w300', 'w780', 'w1280', 'original'], // jshint ignore:line
        logo_sizes: ['w45', 'w92', 'w154', 'w185', 'w300', 'w500', 'original'], // jshint ignore:line
        poster_sizes: ['w92', 'w154', 'w185', 'w342', 'w500', 'w780', 'original'], // jshint ignore:line
        profile_sizes: ['w45', 'w185', 'h632', 'original'], // jshint ignore:line
        still_sizes: ['w92', 'w185', 'w300', 'original'] // jshint ignore:line
      }
    }]
  };
  var allMoviesUrl = baseUrl + 'movies';
  var allMovies = {
    movies: [{
      title: 'Fight Club',
      themoviedbid: 550,
      id: 1,
      createdAt: '2015-02-13T05:44:34.000Z',
      updatedAt: '2015-02-13T05:44:34.000Z'
    }, {
      title: 'Guardians of the Galaxy',
      themoviedbid: 118340,
      id: 5,
      createdAt: '2015-02-13T06:19:29.000Z',
      updatedAt: '2015-02-13T06:19:29.000Z'
    }]
  };

  beforeEach(module('polyflix'));

  beforeEach(inject(function($injector) {
    httpBackend = $injector.get('$httpBackend');
    httpBackend.whenGET(configUrl).respond(
      JSON.stringify(config)
    );
    httpBackend.whenGET(allMoviesUrl).respond(
      JSON.stringify(allMovies)
    );
  }));

  beforeEach(inject(function(_TmdbFactory_) {
    TmdbFactory = _TmdbFactory_;
  }));

  afterEach(function() {
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
  });

  describe('call config', function() {
    it('config should exist', function() {
      expect(TmdbFactory.configuration).toEqual(undefined);
      httpBackend.expectGET(configUrl);
      TmdbFactory.config();
      httpBackend.flush();
      var actualConfigImages = TmdbFactory.configuration.$object[0].images;
      var expectedConfigImages = config.configs[0].images;
      expect(actualConfigImages).toEqual(expectedConfigImages);
    });
  });

  describe('call all movies', function() {
    it('movies should exist', function() {
      httpBackend.expectGET(allMoviesUrl);
      var movies = TmdbFactory.all('movies');
      httpBackend.flush();
      var actualMovies = movies.$object;
      var expectedMovies = allMovies.movies;
      expect(actualMovies[0].title).toEqual(expectedMovies[0].title);
      expect(actualMovies[0].themoviedbid).toEqual(expectedMovies[0].themoviedbid);
      expect(actualMovies[0].id).toEqual(expectedMovies[0].id);
      expect(actualMovies[0].createdAt).toEqual(expectedMovies[0].createdAt);
      expect(actualMovies[0].updatedAt).toEqual(expectedMovies[0].updatedAt);
      expect(actualMovies[1].title).toEqual(expectedMovies[1].title);
      expect(actualMovies[1].themoviedbid).toEqual(expectedMovies[1].themoviedbid);
      expect(actualMovies[1].id).toEqual(expectedMovies[1].id);
      expect(actualMovies[1].createdAt).toEqual(expectedMovies[1].createdAt);
      expect(actualMovies[1].updatedAt).toEqual(expectedMovies[1].updatedAt);
    });
  });
});<|endoftext|>