<commit_before>/*
 * PiCard
 * Copyright (c) 2013 Tim De Pauw <http://timdp.github.com/>
 * Released under the MIT License
 */

var PiCard = (function() {
    var opt = {
        axisWidth:          1,
        plotPadding:        10,
        labelMargin:        10,
        plotMarkerSize:     6,
        plotMarkerWidth:    1,
        maxPieRadius:       20,
        startAngle:         -90,
        clockwise:          true,
        drawAllPlotMarkers: false,
        dotScale:           "quad",
        legendFormat:       "{0} ({1})",
        fontFamily:         "Verdana, Arial, Helvetica, sans-serif",
        fontSize:           12,
        activeOpacity:      1.0,
        inactiveOpacity:    0.2,
        axisColor:          "#666",
        plotMarkerColor:    "#999",
        axisLabelColor:     "#666",
        pieColors:          [
            "#C90", "#0C9", "#90C", "#9C0", "#09C", "#C09",
            "#C00", "#0C0", "#00C", "#099", "#909", "#990",
            "#C66", "#6C6", "#66C", "#999"
        ]
    };

    var loc = {
        dayNames:           [ "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN" ],
        summaryTitle:       "Summary",
        summaryLabel:       "Commits:",
        loadingText:        "Loading …",
        loadingFailedText:  "Failed to load data. Reload to try again.",
        thousandsSeparator: ","
    };

    var createChart = function(data, target) {
        var users = sortUserNames(data);
        var userColors = getUserColors(users);
        var measure = getMeasurements();
        var layers = createLayers(data, userColors, measure);
        var legend = createLegend(users, data, userColors, layers);

        var containerID = target.attr("id") + "-container";
        var container = $("<div>").attr("id", containerID);
        target.empty();
        target
            .append(legend)
            .append(container);

        createStage(containerID, layers, measure);
    };

    var sortUserNames = function(data) {
        var users = [];
        $.each(data, function(user, perDay) {
            users.push(user);
        });
        users.sort();
        return users;
    };

    var createStage = function(containerID, layers, measure) {
        var stage = new Kinetic.Stage({
            container: containerID,
            width:     measure.width,
            height:    measure.height
        });
        stage.add(layers.plotArea);
        $.each(layers.plots, function(user, plot) {
            stage.add(plot);
        });
        stage.add(layers.axes);
        return stage;
    };

    var createLayers = function(data, userColors, measure) {
        var totals = calculateTotals(data);
        var plots = {};
        $.each(userColors, function(user, color) {
            plots[user] = new Kinetic.Layer();
            plots[user].setOpacity(opt.activeOpacity);
        });
        createPlots(plots, totals, data, userColors, measure);
        var plotArea = createPlotArea(totals, measure);
        var axes = createAxes(measure);
        return {
            plotArea: plotArea,
            plots:    plots,
            axes:     axes
        };
    };

    var createLegend = function(users, data, userColors, layers) {
        var userTotals = {};
        var grandTotal = 0;
        $.each(data, function(user, perDay) {
            var total = 0;
            $.each(perDay, function(d, perHour) {
                $.each(perHour, function(h, amount) {
                    total += amount;
                });
            });
            userTotals[user] = total;
            grandTotal += total;
        });
        var legend = $("<div/>")
            .attr("class", "picard-legend")
            .append($("<span/>")
                .attr("class", "picard-legend-label")
                .text(loc.summaryLabel + " " + formatNumber(grandTotal)));
        $.each(users, function(i, user) {
            var strings = [ user, formatNumber(userTotals[user]) ];
            var code = opt.legendFormat.replace(
                /\{([0-9]+)\}/g,
                function(m0, m1) {
                    return strings[parseInt(m1, 10)];
                });
            legend.append(" ");
            legend.append($("<span>")
                .attr("class", "picard-legend-item")
                .css("color", userColors[user])
                .mouseover({ user: user, layers: layers }, setActive)
                .mouseout({ user: null, layers: layers }, setActive)
                .html(code));
        });
        return legend;
    };

    var setActive = function(event) {
        var user = event.data.user;
        var plots = event.data.layers.plots;
        var plotArea = event.data.layers.plotArea;
        $.each(plots, function(u, plot) {
            setOpacity(plot, (user === null || user == u)
                ? opt.activeOpacity : opt.inactiveOpacity);
        });
        setOpacity(plotArea, (user === null)
            ? opt.activeOpacity : opt.inactiveOpacity);
    };

    var setOpacity = function(layer, opacity) {
        if (layer.getOpacity() != opacity) {
            layer.setOpacity(opacity);
            layer.draw();
        }
    };

    var createPlotArea = function(totals, measure) {
        var plotArea = new Kinetic.Layer();
        var x0 = measure.yLabelWidth + opt.labelMargin + opt.axisWidth
            + opt.plotPadding + opt.maxPieRadius;
        var y = opt.plotPadding + opt.maxPieRadius;
        var s = opt.plotMarkerSize / 2;
        for (var d = 0; d < 7; d++) {
            var x = x0;
            for (var h = 0; h < 24; h++) {
                if (opt.drawAllPlotMarkers || !totals[d][h]) {
                    plotArea.add(new Kinetic.Line({
                        points:      [ x - s, y, x + s, y ],
                        stroke:      opt.plotMarkerColor,
                        strokeWidth: opt.plotMarkerWidth
                    }));
                    plotArea.add(new Kinetic.Line({
                        points:      [ x, y - s, x, y + s ],
                        stroke:      opt.plotMarkerColor,
                        strokeWidth: opt.plotMarkerWidth
                    }));
                }
                x += opt.maxPieRadius * 2;
            }
            y += opt.maxPieRadius * 2;
        }
        return plotArea;
    };

    var createPlots = function(plots, totals, data, userColors, measure) {
        var max = getMaximum(totals);
        var x0 = measure.yLabelWidth + opt.labelMargin + opt.axisWidth
            + opt.plotPadding + opt.maxPieRadius;
        var y = opt.plotPadding + opt.maxPieRadius;
        for (var d = 0; d < 7; d++) {
            var x = x0;
            for (var h = 0; h < 24; h++) {
                if (totals[d] && totals[d][h]) {
                    plotPie(d, h, data, totals, max, plots, x, y, userColors);
                }
                x += opt.maxPieRadius * 2;
            }
            y += opt.maxPieRadius * 2;
        }
    };

    var plotPie = function(d, h, data, totals, max, plots, x, y, userColors) {
        var total = totals[d][h];
        var ratio = getRatio(total, max);
        if (ratio <= 0) {
            return;
        }
        var radius = ratio * opt.maxPieRadius;
        var angle = (opt.startAngle === null)
            ? Math.random() * 360 : opt.startAngle;
        $.each(data, function(user, perDay) {
            if (perDay[d] && perDay[d][h]) {
                var degrees = 360 * (perDay[d][h] / total);
                if (opt.clockWise) {
                    degrees = -degrees;
                }
                var wedge = new Kinetic.Wedge({
                    x:           x,
                    y:           y,
                    radius:      radius,
                    rotationDeg: angle,
                    angleDeg:    degrees,
                    fill:        userColors[user]
                });
                plots[user].add(wedge);
                angle += degrees;
            }
        });
    };

    var getRatio = function(value, max) {
        if (value <= 0) {
            return 0;
        }
        var transform = (opt.scale == "quad") ? Math.sqrt
            : (opt.scale == "log") ? Math.log
            : function(n) { return n; };
        return transform(value) / transform(max);
    };

    var createAxes = function(measure) {
        var axes = new Kinetic.Layer();
        createXAxis(axes, measure);
        createYAxis(axes, measure);
        return axes;
    }

    var createXAxis = function(axes, measure) {
        axes.add(new Kinetic.Line({
            points:      [
                measure.yLabelWidth + opt.labelMargin,
                measure.plotHeight + opt.axisWidth / 2,
                measure.width,
                measure.plotHeight + opt.axisWidth / 2
            ],
            stroke:      opt.axisColor,
            strokeWidth: opt.axisWidth
        }));
        var x = measure.yLabelWidth + opt.labelMargin + opt.axisWidth
            + opt.plotPadding + opt.maxPieRadius;
        var y = measure.plotHeight + opt.axisWidth + opt.labelMargin;
        for (var h = 0; h < 24; h++) {
            var text = createText((h < 10) ? "0" + h : h,
                x, y, opt.axisLabelColor);
            text.setOffset({
                x: text.getWidth() / 2
            });
            axes.add(text);
            x += opt.maxPieRadius * 2;
        }
    };

    var createYAxis = function(axes, measure) {
        axes.add(new Kinetic.Line({
            points:      [
                measure.yLabelWidth + opt.labelMargin + opt.axisWidth / 2,
                0,
                measure.yLabelWidth + opt.labelMargin + opt.axisWidth / 2,
                measure.plotHeight + opt.axisWidth
            ],
            stroke:      opt.axisColor,
            strokeWidth: opt.axisWidth
        }));
        var x = measure.yLabelWidth;
        var y = opt.plotPadding + opt.maxPieRadius - measure.labelHeight / 2;
        for (var d = 0; d < 7; d++) {
            var text = createText(loc.dayNames[d],
                x, y, opt.axisLabelColor);
            text.setOffset({
                x: text.getWidth()
            });
            axes.add(text);
            y += opt.maxPieRadius * 2;
        }
    };

    var getUserColors = function(users) {
        var userColors = {};
        for (var i = 0; i < users.length; i++) {
            userColors[users[i]] = opt.pieColors[i % opt.pieColors.length];
        }
        return userColors;
    };

    var calculateTotals = function(data) {
        var totals = [];
        for (var d = 0; d < 7; d++) {
            var dayTotals = [];
            for (var h = 0; h < 24; h++) {
                dayTotals[h] = 0;
                $.each(data, function(user, perDay) {
                    if (perDay[d] && perDay[d][h]) {
                        dayTotals[h] += perDay[d][h];
                    }
                });
            }
            totals[d] = dayTotals;
        }
        return totals;
    };

    var getMaximum = function(totals) {
        var max = 0;
        for (var d = 0; d < 7; d++) {
            for (var h = 0; h < 24; h++) {
                if (totals[d] && totals[d][h]) {
                    max = Math.max(max, totals[d][h]);
                }
            }
        }
        return max;
    };

    var getMeasurements = function() {
        var yLabelWidth = 0;
        for (var d = 0; d < 7; d++) {
            var text = createText(loc.dayNames[d], 0, 0, "black");
            yLabelWidth = Math.max(yLabelWidth, text.getWidth());
        }
        var labelHeight = createText("X", 0, 0, "black").getHeight();

        var plotWidth = opt.plotPadding + opt.maxPieRadius * 2 * 24
            + opt.plotPadding;
        var plotHeight = opt.plotPadding + opt.maxPieRadius * 2 * 7
            + opt.plotPadding;
        var width = yLabelWidth + opt.labelMargin + opt.axisWidth + plotWidth;
        var height = plotHeight + opt.axisWidth + opt.labelMargin + labelHeight;

        return {
            width:       width,
            height:      height,
            plotWidth:   plotWidth,
            plotHeight:  plotHeight,
            yLabelWidth: yLabelWidth,
            labelHeight: labelHeight
        };
    };

    var createText = function(text, x, y, color) {
        return new Kinetic.Text({
            text:       text,
            fontFamily: opt.fontFamily,
            fontSize:   opt.fontSize,
            fill:       color,
            x:          x,
            y:          y
        });
    };

    var processQueue = function(queue, summaryData) {
        if (queue.length) {
            var entry = queue.shift();
            $.ajax(entry.url)
                .done(function(data) {
                    createChart(data, entry.target);
                    updateSummary(entry.name, data, summaryData);
                })
                .fail(function(xhr, stat, err) {
                    entry.target.text(loc.loadingFailedText);
                })
                .always(function() {
                    processQueue(queue, summaryData);
                });
        } else {
            createChart(summaryData, $("#picard-tab-summary"));
        }
    };

    var updateSummary = function(name, data, summaryData) {
        summaryData[name] = {};
        for (var d = 0; d < 7; d++) {
            var dayData = {};
            for (var h = 0; h < 24; h++) {
                dayData[h] = 0;
            }
            summaryData[name][d] = dayData;
        }
        $.each(data, function(user, perDay) {
            $.each(perDay, function(d, perHour) {
                $.each(perHour, function(h, amount) {
                    summaryData[name][d][h] += amount;
                });
            });
        });
    };

    var formatNumber = function(number) {
        number = "" + number;
        var re = /^([0-9]+)([0-9]{3})$/;
        var match = true;
        while (match) {
            match = false;
            number = number.replace(re, function(m0, m1, m2) {
                match = true;
                return m1 + loc.thousandsSeparator + m2;
            });
        }
        return number;
    };

    var initialize = function(container, sources) {
        var queue = [];
        container.empty();
        var tabList = $("<ul/>");
        container.append(tabList);
        var tabID = "picard-tab-summary";
        var tab = addTab(loc.summaryTitle, tabID, tabList, container);
        for (var i = 0; i < sources.length; i++) {
            var tabName = sources[i].name;
            var tabID = "picard-tab-" + i;
            var tab = addTab(tabName, tabID, tabList, container);
            queue.push({
                name:   tabName,
                url:    sources[i].url,
                target: tab
            });
        }
        container.tabs();
        var summaryData = {};
        processQueue(queue, summaryData);
    };

    var addTab = function(tabName, tabID, tabList, container) {
        tabList.append($("<li/>")
            .append($("<a/>")
                .attr("href", "#" + tabID).text(tabName)));
        var tab = $("<div/>").attr("id", tabID).addClass("picard-tab")
            .text(loc.loadingText);
        container.append(tab);
        return tab;
    };

    return {
        options:    opt,
        locale:     loc,
        initialize: initialize
    };
})();
<commit_msg>Adding optional .users key to impose user list order<commit_after>/*
 * PiCard
 * Copyright (c) 2013 Tim De Pauw <http://timdp.github.com/>
 * Released under the MIT License
 */

var PiCard = (function() {
    var opt = {
        axisWidth:          1,
        plotPadding:        10,
        labelMargin:        10,
        plotMarkerSize:     6,
        plotMarkerWidth:    1,
        maxPieRadius:       20,
        startAngle:         -90,
        clockwise:          true,
        drawAllPlotMarkers: false,
        dotScale:           "quad",
        legendFormat:       "{0} ({1})",
        fontFamily:         "Verdana, Arial, Helvetica, sans-serif",
        fontSize:           12,
        activeOpacity:      1.0,
        inactiveOpacity:    0.2,
        axisColor:          "#666",
        plotMarkerColor:    "#999",
        axisLabelColor:     "#666",
        pieColors:          [
            "#C90", "#0C9", "#90C", "#9C0", "#09C", "#C09",
            "#C00", "#0C0", "#00C", "#099", "#909", "#990",
            "#C66", "#6C6", "#66C", "#999"
        ],
        usersKey:           ".users"
    };

    var loc = {
        dayNames:           [ "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN" ],
        summaryTitle:       "Summary",
        summaryLabel:       "Commits:",
        loadingText:        "Loading …",
        loadingFailedText:  "Failed to load data. Reload to try again.",
        thousandsSeparator: ","
    };

    var createChart = function(data, target) {
        var users;
        if (opt.usersKey !== undefined && opt.usersKey in data) {
            users = data[opt.usersKey];
            delete data[opt.usersKey];
        } else {
            users = sortUserNames(data);
        }
        var userColors = getUserColors(users);
        var measure = getMeasurements();
        var layers = createLayers(data, userColors, measure);
        var legend = createLegend(users, data, userColors, layers);

        var containerID = target.attr("id") + "-container";
        var container = $("<div>").attr("id", containerID);
        target.empty();
        target
            .append(legend)
            .append(container);

        createStage(containerID, layers, measure);
    };

    var sortUserNames = function(data) {
        var users = [];
        $.each(data, function(user, perDay) {
            users.push(user);
        });
        users.sort();
        return users;
    };

    var createStage = function(containerID, layers, measure) {
        var stage = new Kinetic.Stage({
            container: containerID,
            width:     measure.width,
            height:    measure.height
        });
        stage.add(layers.plotArea);
        $.each(layers.plots, function(user, plot) {
            stage.add(plot);
        });
        stage.add(layers.axes);
        return stage;
    };

    var createLayers = function(data, userColors, measure) {
        var totals = calculateTotals(data);
        var plots = {};
        $.each(userColors, function(user, color) {
            plots[user] = new Kinetic.Layer();
            plots[user].setOpacity(opt.activeOpacity);
        });
        createPlots(plots, totals, data, userColors, measure);
        var plotArea = createPlotArea(totals, measure);
        var axes = createAxes(measure);
        return {
            plotArea: plotArea,
            plots:    plots,
            axes:     axes
        };
    };

    var createLegend = function(users, data, userColors, layers) {
        var userTotals = {};
        var grandTotal = 0;
        $.each(data, function(user, perDay) {
            var total = 0;
            $.each(perDay, function(d, perHour) {
                $.each(perHour, function(h, amount) {
                    total += amount;
                });
            });
            userTotals[user] = total;
            grandTotal += total;
        });
        var legend = $("<div/>")
            .attr("class", "picard-legend")
            .append($("<span/>")
                .attr("class", "picard-legend-label")
                .text(loc.summaryLabel + " " + formatNumber(grandTotal)));
        $.each(users, function(i, user) {
            var strings = [ user, formatNumber(userTotals[user]) ];
            var code = opt.legendFormat.replace(
                /\{([0-9]+)\}/g,
                function(m0, m1) {
                    return strings[parseInt(m1, 10)];
                });
            legend.append(" ");
            legend.append($("<span>")
                .attr("class", "picard-legend-item")
                .css("color", userColors[user])
                .mouseover({ user: user, layers: layers }, setActive)
                .mouseout({ user: null, layers: layers }, setActive)
                .html(code));
        });
        return legend;
    };

    var setActive = function(event) {
        var user = event.data.user;
        var plots = event.data.layers.plots;
        var plotArea = event.data.layers.plotArea;
        $.each(plots, function(u, plot) {
            setOpacity(plot, (user === null || user == u)
                ? opt.activeOpacity : opt.inactiveOpacity);
        });
        setOpacity(plotArea, (user === null)
            ? opt.activeOpacity : opt.inactiveOpacity);
    };

    var setOpacity = function(layer, opacity) {
        if (layer.getOpacity() != opacity) {
            layer.setOpacity(opacity);
            layer.draw();
        }
    };

    var createPlotArea = function(totals, measure) {
        var plotArea = new Kinetic.Layer();
        var x0 = measure.yLabelWidth + opt.labelMargin + opt.axisWidth
            + opt.plotPadding + opt.maxPieRadius;
        var y = opt.plotPadding + opt.maxPieRadius;
        var s = opt.plotMarkerSize / 2;
        for (var d = 0; d < 7; d++) {
            var x = x0;
            for (var h = 0; h < 24; h++) {
                if (opt.drawAllPlotMarkers || !totals[d][h]) {
                    plotArea.add(new Kinetic.Line({
                        points:      [ x - s, y, x + s, y ],
                        stroke:      opt.plotMarkerColor,
                        strokeWidth: opt.plotMarkerWidth
                    }));
                    plotArea.add(new Kinetic.Line({
                        points:      [ x, y - s, x, y + s ],
                        stroke:      opt.plotMarkerColor,
                        strokeWidth: opt.plotMarkerWidth
                    }));
                }
                x += opt.maxPieRadius * 2;
            }
            y += opt.maxPieRadius * 2;
        }
        return plotArea;
    };

    var createPlots = function(plots, totals, data, userColors, measure) {
        var max = getMaximum(totals);
        var x0 = measure.yLabelWidth + opt.labelMargin + opt.axisWidth
            + opt.plotPadding + opt.maxPieRadius;
        var y = opt.plotPadding + opt.maxPieRadius;
        for (var d = 0; d < 7; d++) {
            var x = x0;
            for (var h = 0; h < 24; h++) {
                if (totals[d] && totals[d][h]) {
                    plotPie(d, h, data, totals, max, plots, x, y, userColors);
                }
                x += opt.maxPieRadius * 2;
            }
            y += opt.maxPieRadius * 2;
        }
    };

    var plotPie = function(d, h, data, totals, max, plots, x, y, userColors) {
        var total = totals[d][h];
        var ratio = getRatio(total, max);
        if (ratio <= 0) {
            return;
        }
        var radius = ratio * opt.maxPieRadius;
        var angle = (opt.startAngle === null)
            ? Math.random() * 360 : opt.startAngle;
        $.each(data, function(user, perDay) {
            if (perDay[d] && perDay[d][h]) {
                var degrees = 360 * (perDay[d][h] / total);
                if (opt.clockWise) {
                    degrees = -degrees;
                }
                var wedge = new Kinetic.Wedge({
                    x:           x,
                    y:           y,
                    radius:      radius,
                    rotationDeg: angle,
                    angleDeg:    degrees,
                    fill:        userColors[user]
                });
                plots[user].add(wedge);
                angle += degrees;
            }
        });
    };

    var getRatio = function(value, max) {
        if (value <= 0) {
            return 0;
        }
        var transform = (opt.scale == "quad") ? Math.sqrt
            : (opt.scale == "log") ? Math.log
            : function(n) { return n; };
        return transform(value) / transform(max);
    };

    var createAxes = function(measure) {
        var axes = new Kinetic.Layer();
        createXAxis(axes, measure);
        createYAxis(axes, measure);
        return axes;
    }

    var createXAxis = function(axes, measure) {
        axes.add(new Kinetic.Line({
            points:      [
                measure.yLabelWidth + opt.labelMargin,
                measure.plotHeight + opt.axisWidth / 2,
                measure.width,
                measure.plotHeight + opt.axisWidth / 2
            ],
            stroke:      opt.axisColor,
            strokeWidth: opt.axisWidth
        }));
        var x = measure.yLabelWidth + opt.labelMargin + opt.axisWidth
            + opt.plotPadding + opt.maxPieRadius;
        var y = measure.plotHeight + opt.axisWidth + opt.labelMargin;
        for (var h = 0; h < 24; h++) {
            var text = createText((h < 10) ? "0" + h : h,
                x, y, opt.axisLabelColor);
            text.setOffset({
                x: text.getWidth() / 2
            });
            axes.add(text);
            x += opt.maxPieRadius * 2;
        }
    };

    var createYAxis = function(axes, measure) {
        axes.add(new Kinetic.Line({
            points:      [
                measure.yLabelWidth + opt.labelMargin + opt.axisWidth / 2,
                0,
                measure.yLabelWidth + opt.labelMargin + opt.axisWidth / 2,
                measure.plotHeight + opt.axisWidth
            ],
            stroke:      opt.axisColor,
            strokeWidth: opt.axisWidth
        }));
        var x = measure.yLabelWidth;
        var y = opt.plotPadding + opt.maxPieRadius - measure.labelHeight / 2;
        for (var d = 0; d < 7; d++) {
            var text = createText(loc.dayNames[d],
                x, y, opt.axisLabelColor);
            text.setOffset({
                x: text.getWidth()
            });
            axes.add(text);
            y += opt.maxPieRadius * 2;
        }
    };

    var getUserColors = function(users) {
        var userColors = {};
        for (var i = 0; i < users.length; i++) {
            userColors[users[i]] = opt.pieColors[i % opt.pieColors.length];
        }
        return userColors;
    };

    var calculateTotals = function(data) {
        var totals = [];
        for (var d = 0; d < 7; d++) {
            var dayTotals = [];
            for (var h = 0; h < 24; h++) {
                dayTotals[h] = 0;
                $.each(data, function(user, perDay) {
                    if (perDay[d] && perDay[d][h]) {
                        dayTotals[h] += perDay[d][h];
                    }
                });
            }
            totals[d] = dayTotals;
        }
        return totals;
    };

    var getMaximum = function(totals) {
        var max = 0;
        for (var d = 0; d < 7; d++) {
            for (var h = 0; h < 24; h++) {
                if (totals[d] && totals[d][h]) {
                    max = Math.max(max, totals[d][h]);
                }
            }
        }
        return max;
    };

    var getMeasurements = function() {
        var yLabelWidth = 0;
        for (var d = 0; d < 7; d++) {
            var text = createText(loc.dayNames[d], 0, 0, "black");
            yLabelWidth = Math.max(yLabelWidth, text.getWidth());
        }
        var labelHeight = createText("X", 0, 0, "black").getHeight();

        var plotWidth = opt.plotPadding + opt.maxPieRadius * 2 * 24
            + opt.plotPadding;
        var plotHeight = opt.plotPadding + opt.maxPieRadius * 2 * 7
            + opt.plotPadding;
        var width = yLabelWidth + opt.labelMargin + opt.axisWidth + plotWidth;
        var height = plotHeight + opt.axisWidth + opt.labelMargin + labelHeight;

        return {
            width:       width,
            height:      height,
            plotWidth:   plotWidth,
            plotHeight:  plotHeight,
            yLabelWidth: yLabelWidth,
            labelHeight: labelHeight
        };
    };

    var createText = function(text, x, y, color) {
        return new Kinetic.Text({
            text:       text,
            fontFamily: opt.fontFamily,
            fontSize:   opt.fontSize,
            fill:       color,
            x:          x,
            y:          y
        });
    };

    var processQueue = function(queue, summaryData) {
        if (queue.length) {
            var entry = queue.shift();
            $.ajax(entry.url)
                .done(function(data) {
                    createChart(data, entry.target);
                    updateSummary(entry.name, data, summaryData);
                })
                .fail(function(xhr, stat, err) {
                    entry.target.text(loc.loadingFailedText);
                })
                .always(function() {
                    processQueue(queue, summaryData);
                });
        } else {
            createChart(summaryData, $("#picard-tab-summary"));
        }
    };

    var updateSummary = function(name, data, summaryData) {
        summaryData[name] = {};
        for (var d = 0; d < 7; d++) {
            var dayData = {};
            for (var h = 0; h < 24; h++) {
                dayData[h] = 0;
            }
            summaryData[name][d] = dayData;
        }
        $.each(data, function(user, perDay) {
            $.each(perDay, function(d, perHour) {
                $.each(perHour, function(h, amount) {
                    summaryData[name][d][h] += amount;
                });
            });
        });
    };

    var formatNumber = function(number) {
        number = "" + number;
        var re = /^([0-9]+)([0-9]{3})$/;
        var match = true;
        while (match) {
            match = false;
            number = number.replace(re, function(m0, m1, m2) {
                match = true;
                return m1 + loc.thousandsSeparator + m2;
            });
        }
        return number;
    };

    var initialize = function(container, sources) {
        var queue = [];
        container.empty();
        var tabList = $("<ul/>");
        container.append(tabList);
        var tabID = "picard-tab-summary";
        var tab = addTab(loc.summaryTitle, tabID, tabList, container);
        for (var i = 0; i < sources.length; i++) {
            var tabName = sources[i].name;
            var tabID = "picard-tab-" + i;
            var tab = addTab(tabName, tabID, tabList, container);
            queue.push({
                name:   tabName,
                url:    sources[i].url,
                target: tab
            });
        }
        container.tabs();
        var summaryData = {};
        processQueue(queue, summaryData);
    };

    var addTab = function(tabName, tabID, tabList, container) {
        tabList.append($("<li/>")
            .append($("<a/>")
                .attr("href", "#" + tabID).text(tabName)));
        var tab = $("<div/>").attr("id", tabID).addClass("picard-tab")
            .text(loc.loadingText);
        container.append(tab);
        return tab;
    };

    return {
        options:    opt,
        locale:     loc,
        initialize: initialize
    };
})();
<|endoftext|>


<commit_before>var alexa = require('alexa-app');
var request = require('request-promise');
var express = require('express');

var express_app = express();

var app = new alexa.app('connect');
app.express({ expressApp: express_app, checkCert:false });

app.intent('PlayIntent', {
    "utterances": [
        "play",
        "resume",
        "continue"
    ]
},
    function (req, res) {
        request.put("https://api.spotify.com/v1/me/player/play").auth(null, null, true, req.sessionDetails.accessToken);
        res.say('Playing');
    }
);

app.intent('PauseIntent', {
    "utterances": [
        "pause"
    ]
},
    function (req, res) {
        request.put("https://api.spotify.com/v1/me/player/pause").auth(null, null, true, req.sessionDetails.accessToken);
        res.say('Paused');
    }
);

app.intent('GetDevicesIntent', {
    "utterances": [
        "devices",
        "list"
    ]
},
    function (req, res) {
        return request.get({
            url: "https://api.spotify.com/v1/me/player/devices",
            auth: {
                "bearer": req.sessionDetails.accessToken
            },
            json: true
        })
            .then(function (body) {
                var devices = body.devices || [];
                var deviceNames = [];
                res.say("I found these devices:");
                for (var i = 0; i < devices.length; i++) {
                    deviceNames.push(devices[i].name);
                }
                res.say(deviceNames.slice(0, deviceNames.length - 1).join(', ') + ", and " + deviceNames.slice(-1));
            })
            .catch(function (err) {
                console.error('error:', err.message);
            });
    }
);

app.intent('DevicePlayIntent', {
    "slots": {
        "NUMBER": "AMAZON.NUMBER"
    },
    "utterances": [
        "play on {NUMBER}",
        "play on number {NUMBER}",
        "play on device {NUMBER}",
        "play on device number {NUMBER}"
    ]
},
    function (req, res) {
        return request.get({
            url: "https://api.spotify.com/v1/me/player/devices",
            auth: {
                "bearer": req.sessionDetails.accessToken
            },
            json: true
        })
            .then(function (body) {
                var devices = body.devices || [];
                var deviceNames = [];
                res.reprompt("Which device should I play on?");
                for (var i = 0; i < devices.length; i++) {
                    deviceNames.push((i + 1) + ". " + devices[i].name);
                }
                res.say(deviceNames.slice(0, deviceNames.length - 1).join(', ') + ", or " + deviceNames.slice(-1));
            })
            .catch(function (err) {
                console.error('error:', err.message);
            });
    }
);

express_app.use(express.static(__dirname));
express_app.get('/', function (req, res) {
    res.redirect('https://github.com/thorpelawrence/alexa-spotify-connect');
});

var port = process.env.PORT || 8888;
console.log("Listening on port " + port);
express_app.listen(port);

module.exports = app;
<commit_msg>Use session data for devices<commit_after>var alexa = require('alexa-app');
var request = require('request-promise');
var express = require('express');

var express_app = express();

var app = new alexa.app('connect');
app.express({ expressApp: express_app });

app.intent('PlayIntent', {
    "utterances": [
        "play",
        "resume",
        "continue"
    ]
},
    function (req, res) {
        request.put("https://api.spotify.com/v1/me/player/play").auth(null, null, true, req.sessionDetails.accessToken);
        res.say('Playing');
    }
);

app.intent('PauseIntent', {
    "utterances": [
        "pause"
    ]
},
    function (req, res) {
        request.put("https://api.spotify.com/v1/me/player/pause").auth(null, null, true, req.sessionDetails.accessToken);
        res.say('Paused');
    }
);

app.intent('GetDevicesIntent', {
    "utterances": [
        "devices",
        "list"
    ]
},
    function (req, res) {
        return request.get({
            url: "https://api.spotify.com/v1/me/player/devices",
            auth: {
                "bearer": req.sessionDetails.accessToken
            },
            json: true
        })
            .then(function (body) {
                var devices = body.devices || [];
                var deviceNames = [];
                res.say("I found these devices:");
                for (var i = 0; i < devices.length; i++) {
                    deviceNames.push((i + 1) + ". " + devices[i].name);
                    devices[i].number = (i + 1);
                }
                res.say(deviceNames.slice(0, deviceNames.length - 1).join(', ') + ", and " + deviceNames.slice(-1));
                req.getSession().set("devices", devices);
            })
            .catch(function (err) {
                console.error('error:', err.message);
            });
    }
);

app.intent('DevicePlayIntent', {
    "slots": {
        "NUMBER": "AMAZON.NUMBER"
    },
    "utterances": [
        "play on {NUMBER}",
        "play on number {NUMBER}",
        "play on device {NUMBER}",
        "play on device number {NUMBER}"
    ]
},
    function (req, res) {
        if (request.slot("NUMBER")) {
            var number = request.slot("NUMBER");
            var devices = req.getSession().get("devices");
            res.say("Device " + number + ": " + devices);
        }
    });

express_app.use(express.static(__dirname));
express_app.get('/', function (req, res) {
    res.redirect('https://github.com/thorpelawrence/alexa-spotify-connect');
});

var port = process.env.PORT || 8888;
console.log("Listening on port " + port);
express_app.listen(port);

module.exports = app;
<|endoftext|>


<commit_before>document.getElementById("ayuda").setAttribute("aria-current", "page");

var aside = document.getElementById("complementario");
var h5 = document.createElement("H5");
var t = document.createTextNode("Formulario para obtener información sobre complementos en GitHub");
h5.appendChild(t);
aside.appendChild(h5);
var form = document.createElement("FORM");
form.setAttribute("role", "form");
var p = document.createElement("P");
var label = document.createElement("LABEL");
label.setAttribute("for", "repo");
t = document.createTextNode("cuenta/repositorio de GitHub");
label.appendChild(t);
var input = document.createElement("INPUT");
input.setAttribute("type", "text");
input.setAttribute("id", "repo");
input.setAttribute("name", "repo");
input.setAttribute("placeholder", "example: nvdaes/emoticons")
label.appendChild(input);
var submit = document.createElement("INPUT");
submit.setAttribute("id", "submit");
submit.setAttribute("type", "button");
submit.setAttribute("value", "Consultar descargas de última versión");
p.appendChild(label);
form.appendChild(p);
form.appendChild(submit);
aside.appendChild(form);

$(document).ready(function () {
	$("#submit").click(function () {
		$.getJSON("https://api.github.com/repos/" + input.value + "/releases/latest", function(json) {
			var assetName = json.assets[0].name;
			var downloadCount = json.assets[0].download_count;
			alert(assetName + " " + downloadCount);
		});
	});
});

<commit_msg>Remove h5 for debugging<commit_after>document.getElementById("ayuda").setAttribute("aria-current", "page");

var aside = document.getElementById("complementario");
/*
var h5 = document.createElement("H5");
var t = document.createTextNode("Formulario para obtener información sobre complementos en GitHub");
h5.appendChild(t);
aside.appendChild(h5);
*/
var form = document.createElement("FORM");
form.setAttribute("role", "form");
var p = document.createElement("P");
var label = document.createElement("LABEL");
label.setAttribute("for", "repo");
t = document.createTextNode("cuenta/repositorio de GitHub");
label.appendChild(t);
var input = document.createElement("INPUT");
input.setAttribute("type", "text");
input.setAttribute("id", "repo");
input.setAttribute("name", "repo");
input.setAttribute("placeholder", "example: nvdaes/emoticons");
label.appendChild(input);
var submit = document.createElement("INPUT");
submit.setAttribute("id", "submit");
submit.setAttribute("type", "button");
submit.setAttribute("value", "Consultar descargas de última versión");
p.appendChild(label);
form.appendChild(p);
form.appendChild(submit);
aside.appendChild(form);

$(document).ready(function () {
	$("#submit").click(function () {
		$.getJSON("https://api.github.com/repos/" + input.value + "/releases/latest", function(json) {
			var assetName = json.assets[0].name;
			var downloadCount = json.assets[0].download_count;
			alert(assetName + " " + downloadCount);
		});
	});
});

<|endoftext|>


<commit_before>'use strict';

var titleize = require('titleize');
var chalk = require('chalk');
var Registry = require('npm-registry');
var npm = new Registry({ retries: 4 });

var utils = require('./utils');
var inArray = require('in-array');
var errorHandler = require('./errorHandler');

var NPM_CARTRIDGE_TASK_KEYWORD = 'cartridge-task';

var _cartridgeTaskModules;
var _promptOptions = [];
var _log;

var promptOptionsApi = {};

promptOptionsApi.setup = function(options) {
	_log = utils.getLogInstance(options);
}

promptOptionsApi.getNewCommandPromptOptions = function() {
	_log.debug('');
	_log.debug('Getting prompt options data');

	return Promise.all([getCartridgeTaskModulesFromNpm(), getCartridgeDefaultModulesFromNpm()])
		.then(formatDefaultModules)
		.then(setPromptOptionsData)
		.catch(function(err) {
			errorHandler(err)
		})
}

function getCartridgeTaskModulesFromNpm() {

	return new Promise(function(resolve, reject) {

		_log.debug('Getting cartridge task modules from npm registry');

		npm.packages.keyword(NPM_CARTRIDGE_TASK_KEYWORD, function(err, data) {
			if(err) errorHandler(err);

			_cartridgeTaskModules = formatModuleData(data);

			resolve(data);
		});

	})
}

function getCartridgeDefaultModulesFromNpm() {

	return new Promise(function(resolve, reject) {

		_log.debug('Getting cartridge task modules from npm registry');

		npm.packages.keyword('cartridge-module', function(err, data) {
			if(err) errorHandler(err);

			_cartridgeTaskModules = formatModuleData(data);

			resolve(data);
		});

	})
}

/**
 * Go through all modules and combine the name and description into one key.
 * @param  {Array} moduleData Module data from npm registry
 * @return {Array}            Formatted module data
 */
function formatModuleData(moduleData) {
	return moduleData.map(function(module) {
	   var formattedModule = {};
	   formattedModule.name = ' ' + module.name + ' - ' + module.description;
	   return formattedModule;
	})
}

function formatDefaultModules(data) {
	return new Promise(function(resolve, reject) {

		var moduleList = data[0];
		var defaultModuleList = data[1];
		var moduleAlreadyChecked = [];

		moduleList.push({
			name: 'module-1'
		})

		moduleList.push({
			name: 'module-2'
		})

		moduleList.push({
			name: 'module-3'
		})

		moduleList.push({
			name: 'module-4'
		})

		//---------------------------------

		defaultModuleList.push({
			name: 'module-2'
		})

		defaultModuleList.push({
			name: 'module-4'
		})

		for (var i = 0; i < defaultModuleList.length; i++) {
		    for (var j = 0; j < moduleList.length; j++) {
		    	var defaultModuleName = defaultModuleList[i].name;
		    	var moduleName = moduleList[j].name;
		    	var isDefault = defaultModuleName === moduleName;

		    	if(!inArray(moduleAlreadyChecked, moduleName) && defaultModuleName === moduleName) {
		        	moduleList[j].checked = true;
		        	moduleAlreadyChecked.push(moduleName);
		    	}
		    }
		}

		resolve(moduleList);
	})
}

function setPromptOptionsData(moduleList) {

	_log.debug('Setting prompt options data');

	_promptOptions.push(getProjectTypePromptOptions());
	_promptOptions.push(getProjectNamePromptOptions());
	_promptOptions.push(getProjectAuthorPromptOptions());
	_promptOptions.push(getProjectDescriptionPromptOptions());
	_promptOptions.push(getCartridgeModulesPromptOptions(moduleList));
	_promptOptions.push(getUserConfirmCopyPromptOptions());

	return Promise.resolve(_promptOptions);
}

function getCartridgeModulesPromptOptions(moduleData) {
	return {
		type: 'checkbox',
		name: 'cartridgeModules',
		message: 'What modules would you like included?',
		choices: moduleData,
		// choices: _cartridgeTaskModules,
		filter: extractModuleNames
	}
}

function extractModuleNames(values) {
	var moduleNames = [];

	values.forEach(function (value) {
		var regex = /\s([^\s]+)\s.*/g;
		var matches = regex.exec(value);
		moduleNames.push(matches[1]);
	});

	return moduleNames;
}

function getProjectTypePromptOptions() {
	return {
		type: 'list',
		name: 'projectType',
		message: 'What is the project type?',
		choices: [
			'Dot NET',
			'Static Website'
		]
	}
}

function getProjectNamePromptOptions() {
	return {
		type: 'input',
		name: 'projectName',
		message: 'What is the project name?',
		validate: function(value) { return inputNotEmpty(value, 'Project Name'); },
	}
}

function getProjectAuthorPromptOptions() {
	return {
		type: 'input',
		name: 'projectAuthor',
		message: 'Who is the author of the project?',
		validate: function(value) { return inputNotEmpty(value, 'Author'); },
		filter: function(value) { return titleize(value); }
	}
}

function getProjectDescriptionPromptOptions() {
	return {
		type: 'input',
		name: 'projectDescription',
		message: 'What is the project description?',
		default: function () { return ''; }
	}
}

function getUserConfirmCopyPromptOptions() {
	return {
		type: 'confirm',
		name: 'isOkToCopyFiles',
		message: 'Ready to start setup! Press enter to confirm',
		default: true
	}
}

function inputNotEmpty(value, fieldName) {
	var isValid = (value !== '');

	return (isValid) ? true : fieldName + ' cannot be empty' ;
}

module.exports = promptOptionsApi;<commit_msg>refactor: Add npm default module into 'constant'. Naming tweaks<commit_after>'use strict';

var titleize = require('titleize');
var chalk = require('chalk');
var Registry = require('npm-registry');
var npm = new Registry({ retries: 4 });

var utils = require('./utils');
var inArray = require('in-array');
var errorHandler = require('./errorHandler');

var NPM_CARTRIDGE_TASK_KEYWORD = 'cartridge-task';
var NPM_CARTRIDGE_DEFAULT_KEYWORD = 'cartridge-module';

var _cartridgeTaskModules;
var _promptOptions = [];
var _log;

var promptOptionsApi = {};

promptOptionsApi.setup = function(options) {
	_log = utils.getLogInstance(options);
}

promptOptionsApi.getNewCommandPromptOptions = function() {
	_log.debug('');
	_log.debug('Getting prompt options data');

	return Promise.all([getCartridgeTaskModulesFromNpm(), getCartridgeDefaultModulesFromNpm()])
		.then(parseDefaultModuleData)
		.then(formatModuleData)
		.then(setPromptOptionsData)
		.catch(function(err) {
			errorHandler(err)
		})
}

function getCartridgeTaskModulesFromNpm() {

	return new Promise(function(resolve, reject) {

		_log.debug('Getting cartridge task modules from npm registry');

		npm.packages.keyword(NPM_CARTRIDGE_TASK_KEYWORD, function(err, data) {
			if(err) errorHandler(err);

			_cartridgeTaskModules = formatModuleData(data);

			resolve(data);
		});

	})
}

function getCartridgeDefaultModulesFromNpm() {

	return new Promise(function(resolve, reject) {

		_log.debug('Getting cartridge task modules from npm registry');

		npm.packages.keyword(NPM_CARTRIDGE_DEFAULT_KEYWORD, function(err, data) {
			if(err) errorHandler(err);

			_cartridgeTaskModules = formatModuleData(data);

			resolve(data);
		});

	})
}

/**
 * Go through all modules and combine the name and description into one key.
 * @param  {Array} moduleData Module data from npm registry
 * @return {Array}            Formatted module data
 */
function formatModuleData(moduleData) {

	var formattedData = moduleData.map(function(module) {
	   var formattedModule = {};

	   formattedModule.name = ' ' + module.name + ((module.description) ? ' - ' + module.description : '') ;
	   formattedModule.checked = module.checked || false;

	   return formattedModule;
	})

	return Promise.resolve(formattedData)
}

function parseDefaultModuleData(data) {
	return new Promise(function(resolve, reject) {

		var moduleList = data[0];
		var defaultModuleList = data[1];
		var moduleAlreadyChecked = [];

		moduleList.push({
			name: 'module-1'
		})

		moduleList.push({
			name: 'module-2'
		})

		moduleList.push({
			name: 'module-3'
		})

		moduleList.push({
			name: 'module-4'
		})

		//---------------------------------

		defaultModuleList.push({
			name: 'module-2'
		})

		defaultModuleList.push({
			name: 'module-4'
		})

		for (var i = 0; i < defaultModuleList.length; i++) {
		    for (var j = 0; j < moduleList.length; j++) {
		    	var defaultModuleName = defaultModuleList[i].name;
		    	var moduleName = moduleList[j].name;
		    	var isDefault = defaultModuleName === moduleName;

		    	if(!inArray(moduleAlreadyChecked, moduleName) && defaultModuleName === moduleName) {
		        	moduleList[j].checked = true;
		        	moduleAlreadyChecked.push(moduleName);
		    	}
		    }
		}

		resolve(moduleList);
	})
}

function setPromptOptionsData(moduleList) {

	_log.debug('Setting prompt options data');

	_promptOptions.push(getProjectTypePromptOptions());
	_promptOptions.push(getProjectNamePromptOptions());
	_promptOptions.push(getProjectAuthorPromptOptions());
	_promptOptions.push(getProjectDescriptionPromptOptions());
	_promptOptions.push(getCartridgeModulesPromptOptions(moduleList));
	_promptOptions.push(getUserConfirmCopyPromptOptions());

	return Promise.resolve(_promptOptions);
}

function getCartridgeModulesPromptOptions(moduleData) {
	return {
		type: 'checkbox',
		name: 'cartridgeModules',
		message: 'What modules would you like included?',
		choices: moduleData,
		filter: extractModuleNames
	}
}

function extractModuleNames(values) {
	var moduleNames = [];

	values.forEach(function (value) {
		var regex = /\s([^\s]+)\s.*/g;
		var matches = regex.exec(value);
		moduleNames.push(matches[1]);
	});

	return moduleNames;
}

function getProjectTypePromptOptions() {
	return {
		type: 'list',
		name: 'projectType',
		message: 'What is the project type?',
		choices: [
			'Dot NET',
			'Static Website'
		]
	}
}

function getProjectNamePromptOptions() {
	return {
		type: 'input',
		name: 'projectName',
		message: 'What is the project name?',
		validate: function(value) { return inputNotEmpty(value, 'Project Name'); },
	}
}

function getProjectAuthorPromptOptions() {
	return {
		type: 'input',
		name: 'projectAuthor',
		message: 'Who is the author of the project?',
		validate: function(value) { return inputNotEmpty(value, 'Author'); },
		filter: function(value) { return titleize(value); }
	}
}

function getProjectDescriptionPromptOptions() {
	return {
		type: 'input',
		name: 'projectDescription',
		message: 'What is the project description?',
		default: function () { return ''; }
	}
}

function getUserConfirmCopyPromptOptions() {
	return {
		type: 'confirm',
		name: 'isOkToCopyFiles',
		message: 'Ready to start setup! Press enter to confirm',
		default: true
	}
}

function inputNotEmpty(value, fieldName) {
	var isValid = (value !== '');

	return (isValid) ? true : fieldName + ' cannot be empty' ;
}

module.exports = promptOptionsApi;<|endoftext|>


<commit_before>import Composite from './Composite';
import NativeObject from '../NativeObject';

export default class RefreshComposite extends Composite {

  get _nativeType() {
    return 'tabris.RefreshComposite';
  }

  _listen(name, listening) {
    if (name === 'refresh') {
      this._nativeListen(name, listening);
    } else {
      super._listen(name, listening);
    }
  }

}

NativeObject.defineProperties(RefreshComposite.prototype, {

  refreshEnabled: {
    type: 'boolean',
    default: false
  },
  refreshIndicator: {
    type: 'boolean',
    nocache: true
  },
  refreshMessage: {
    type: 'string',
    default: ''
  }

});
<commit_msg>Make refreshEnabled true by default on RefreshComposite<commit_after>import Composite from './Composite';
import NativeObject from '../NativeObject';

export default class RefreshComposite extends Composite {

  get _nativeType() {
    return 'tabris.RefreshComposite';
  }

  _listen(name, listening) {
    if (name === 'refresh') {
      this._nativeListen(name, listening);
    } else {
      super._listen(name, listening);
    }
  }

}

NativeObject.defineProperties(RefreshComposite.prototype, {

  refreshEnabled: {
    type: 'boolean',
    default: true
  },
  refreshIndicator: {
    type: 'boolean',
    nocache: true
  },
  refreshMessage: {
    type: 'string',
    default: ''
  }

});
<|endoftext|>


<commit_before>import Application from '../app';
import config from '../config/environment';
import { setApplication, setResolver } from '@ember/test-helpers';
import { start } from 'ember-qunit';
import resolver from './helpers/resolver';
import TestLoader from 'ember-cli-test-loader/test-support';

// optionally override TestLoader.prototype.shouldLoadModule
TestLoader.prototype.shouldLoadModule = (moduleName) =>
    moduleName.includes("Coty-test") ||
    moduleName.includes("Duba-AlternativaCondicional-test") ||
    moduleName.includes("Duba-PrimerosProgramas-test") ||
    moduleName.includes("Duba-Repeticion-test") ||
    moduleName.includes("Lita-AlternativaCondicional-test") ||
    moduleName.includes("Lita-PrimerosProgramas-test") ||
    moduleName.includes("Lita-Repeticion-test") ||
    moduleName.includes("TotoEscritor-test") ||
    moduleName.includes("TotoLector-test") ||
    moduleName.includes("AlienTocaBoton-test") ||
    moduleName.includes("BlockIDGeneration-test") ||
    moduleName.includes("BlocksGallery-test") ||
    moduleName.includes("DibujandoFiguras-test") ||
    moduleName.includes("ElAlienYLasTuercas-test") ||
    moduleName.includes("ElCangrejoAguafiestas-test") ||
    moduleName.includes("ElDetectiveChaparro-test") ||
    moduleName.includes("ElGatoEnLaCalle-test") ||
    moduleName.includes("ElMarcianoEnElDesierto-test") ||
    moduleName.includes("ElMonoCuentaDeNuevo-test") ||
    moduleName.includes("ElMonoQueSabeContar-test") ||
    moduleName.includes("ElMonoYLasBananas-test") ||
    moduleName.includes("ElPlanetaDeNano-test") ||
    moduleName.includes("ElRecolectorDeEstrellas-test") ||
    moduleName.includes("ElSuperViaje-test") ||
    moduleName.includes("FutbolDeRobots-test") ||
    moduleName.includes("InstalandoJuegos-test") ||
    moduleName.includes("LaberintoConQueso-test") ||
    moduleName.includes("LaberintoCorto-test") ||
    moduleName.includes("LaberintoLargo-test") ||
    moduleName.includes("LaEleccionDelMono-test") ||
    moduleName.includes("LaFiestaDeDracula-test") ||
    moduleName.includes("LaGranAventuraDelMarEncantado-test") ||
    moduleName.includes("MariaLaComeSandias-test") ||
    moduleName.includes("NoMeCansoDeSaltar-test") ||
    moduleName.includes("PrendiendoLasCompus-test") ||
    moduleName.includes("PrendiendoLasCompuesParametrizado-test") ||
    moduleName.includes("PrendiendoLasFogatas-test") ||
    moduleName.includes("ReparandoLaNave-test") ||
    moduleName.includes("SalvandoLaNavidad-test") ||
    moduleName.includes("SuperTito1-test") ||
    moduleName.includes("SuperTito2-test") ||
    moduleName.includes("TitoCuadrado-test") ||
    moduleName.includes("TitoEnciendeLasLuces-test") ||
    moduleName.includes("TitoRecargado-test") ||
    moduleName.includes("TresNaranjas-test") ||
    moduleName.includes("Casilla-test") ||
    moduleName.includes("Cuadricula-test") ||
    moduleName.includes("CuadriculaEsparsa-test") ||
    moduleName.includes("Estado-test") ||
    moduleName.includes("ImagenesPreCarga-test") ||
    moduleName.includes("Interactuar-test") ||
    moduleName.includes("StatePattern-test") ||
    moduleName.includes("modal-ayuda-test") ||
    moduleName.includes("modal-title-test") ||
    moduleName.includes("pilas-acerca-de-test") ||
    moduleName.includes("pilas-botones-zoom-test") ||
    moduleName.includes("pilas-canvas-test") ||
    moduleName.includes("pilas-cargando-test") ||
    moduleName.includes("pilas-desafio-test") ||
    moduleName.includes("pilas-editor-test") ||
    moduleName.includes("pilas-header-test") ||
    moduleName.includes("pilas-libro-test") ||
    moduleName.includes("pilas-spinner-test") ||
    moduleName.includes("pilas-notificador-test") ||
    moduleName.includes("pilas-toggle-test") ||
    moduleName.includes("pilasweb-actores-test") ||
    moduleName.includes("pilas-blockly-test") ||
    moduleName.includes("acercade-test") ||
    moduleName.includes("desafios-test") ||
    moduleName.includes("principal-test") ||
    moduleName.includes("pilas-blockly-test") ||
    moduleName.includes("pilas-editor-test") ||
    moduleName.includes("pilas-solution-file-test") ||
    moduleName.includes("acercade-test") ||
    moduleName.includes("test-test") ||
    moduleName.includes("desafio-test") ||
    moduleName.includes("libro-test") ||
    moduleName.includes("acercade-test") ||
    moduleName.includes("desafio-test") ||
    moduleName.includes("index-test") ||
    moduleName.includes("libros-test") ||
    moduleName.includes("blocks-gallery-test") ||
    moduleName.includes("highlighter-test") ||
    moduleName.includes("notificador-test") ||
    moduleName.includes("pilas-test") ||
    moduleName.includes("zoom-test") ||
    moduleName.includes("puede-ingresar-en-actividades-test");

setResolver(resolver);
setApplication(Application.create(config.APP));
start();<commit_msg>all test load with test loader<commit_after>import Application from '../app';
import config from '../config/environment';
import { setApplication, setResolver } from '@ember/test-helpers';
import { start } from 'ember-qunit';
import resolver from './helpers/resolver';
import TestLoader from 'ember-cli-test-loader/test-support';

TestLoader.load();

setResolver(resolver);
setApplication(Application.create(config.APP));
start();<|endoftext|>


<commit_before>(function (jQuery) {
    return jQuery.widget("Liip.hallolink", {
        options: {
            editable: null,
            toolbar: null,
            uuid: "link",
            link: true,
            image: true,
            relatedUrl: false,
            defaultUrl: 'http://',
            dialog: 'link',
            dialogOpts: {
                autoOpen: false,
                width: 500,
                height: 195,
                title: "Enter Link",
                modal: true,
                resizable: false,
                draggable: false,
                dialogClass: 'hallolink-dialog'
            }
        },

        _create: function () {
            var buttonize, buttonset, dialog, dialogId, dialogSubmitCb, urlInput, widget;
            var _this = this;
            widget = this;
            dialogId = "" + this.options.dialog + "-dialog";
            dialog = jQuery("

Insert URL

Suggested URLs

Related URLs

<form action=\"#\" method=\"post\" class=\"linkForm\"><input class=\"name\" type=\"text\" name=\"name\" value=\"Homepage Name\" /><input class=\"url\" type=\"text\" name=\"url\" value=\"" + this.options.defaultUrl + "\" /><input type=\"submit\" id=\"addlinkButton\" value=\"Insert\" /></form>

");
            urlInput = jQuery('input[name=url]', dialog).focus(function (e) {
                return this.select();
            });

            nameInput = jQuery('input[name=name]', dialog).focus(function(e) {
                return this.select();
            });

            // show or hide tab panels
            jQuery('#link-dialog .nav li').live('click', function () {
                jQuery('.' + dialogId + '-tab').each(function () {
                    return jQuery(this).hide();
                });
                id = jQuery(this).attr('id');
                jQuery('#' + id + '-content').show();
                return jQuery("#" + dialogId + "-tab-activeIndicator").css("margin-left", jQuery(this).position().left + (jQuery(this).width() / 2));
            });

            // Action when user clicks on a suggested link
            jQuery('#'+ this.options.uuid + '-tab-suggested-content li a, #'+ this.options.uuid + '-tab-related-content li a').live('click', function (event) {
                event.preventDefault();
                if (widget.lastSelection.toString() === '') {
                    jQuery('input[name=name]', dialog).val(jQuery(this).text());
                }
                jQuery('input[name=url]', dialog).val(this.href);
                dialog.find('form').trigger('submit');
                jQuery('#link-dialog .nav li').first().trigger('click');
            });

            // if user clicks on the suggestet links tab
            jQuery('#' + this.options.uuid + '-tab-suggested').live('click', function () {
                var container = jQuery('#' + _this.options.uuid + "-tab-suggested-content ul");
                container.empty().append('

');

                var articleTags = _this.prepareTags(_this.getReferenceByTags());

                if(articleTags.length > 0) {
                    var vie = new VIE();
                    vie.use(new vie.DBPediaService({
                        url : "http://dev.iks-project.eu/stanbolfull",
                        proxyDisabled: true
                        }));

                        jQuery(articleTags).each(function () {
                            var that = this;
                            vie.load({
                                entity: this + ""
                                }).
                                using('dbpedia').
                                execute().
                                fail(function(e){
                                    alert("Test");
                                    console.log(e);
                                }).
                                done(function(entity) {
                                    jQuery(entity).each(function () {
                                        var data = this;
                                        if (this.attributes) {
                                            data = this.attributes; // different Stanbol version
                                        }
                                        var url = data['<http://xmlns.com/foaf/0.1/primaryTopic>'] || data['<http://xmlns.com/foaf/0.1/homepage>'] || data['<http://xmlns.com/foaf/0.1/page>'] || null;
                                        if (url) {
                                            url = url.substring(1, url.length - 1);
                                            if (container.children('li.loader').size() == 1) {
                                                container.empty();
                                            }
                                            container.append('
' + _this.tagLabel(that + "") + '
');
                                        }
                                    });
                                });
                        });
                }
                else {
                    container.empty();
                    container.append('
No results found, please make sure you have some article tags set.
');
                }
            });

            // if user clicks on the related links tab
            jQuery('#' + this.options.uuid + '-tab-related').live('click', function () {
                var container = jQuery('#' + _this.options.uuid + "-tab-related-content ul");
                container.empty().append('

');
                var articleTags = _this.getReferenceByTags();

                return jQuery.ajax({
                    type: "GET",
                    url: _this.options.relatedUrl,
                    data: "tags="+articleTags+"&page="+window.location,
                    success: function(response) {
                        var items;
                        container.empty();
                        items = [];

                        if (response.links.length > 0) {
                            $.each(response.links, function() {
                                return items.push('
'+this.label+'
');
                            });
                            container.html(items.join(''));
                        } else {
                            container.append('
No results found, please make sure you have some articles with the same tags set.
');
                        }

                    },
                    failure: function(response) {
                        container.empty();
                        container.append('
An Error has occured
');
                    },
                });
            });

            dialogSubmitCb = function (e) {
                var link, name;
                link = urlInput.val();
                name = nameInput.val();
                e. preventDefault();

                widget.options.editable.restoreSelection(widget.lastSelection);
                if (((new RegExp(/^\s*$/)).test(link)) || link === widget.options.defaultUrl) {
                    if (widget.lastSelection.collapsed) {
                        widget.lastSelection.setStartBefore(widget.lastSelection.startContainer);
                        widget.lastSelection.setEndAfter(widget.lastSelection.startContainer);
                        window.getSelection().addRange(widget.lastSelection);
                    }
                    document.execCommand("unlink", null, "");
                } else {
                    if (widget.lastSelection.startContainer.parentNode.href === void 0) {

                        if (widget.lastSelection.toString() !== name) {
                            var newSelection = window.getSelection();
                            var range = newSelection.getRangeAt(0);

                            newTextNode = document.createTextNode(name);
                            range.extractContents();
                            range.insertNode(newTextNode);
                            range.setStartBefore(newTextNode);
                            range.setEndAfter(newTextNode);
                            newSelection.removeAllRanges();

                            newSelection.addRange(range);
                        }

                        document.execCommand("createLink", null, link);
                    } else {
                        widget.lastSelection.startContainer.parentNode.href = link;
                    }
                }
                widget.options.editable.element.trigger('change');
                widget.options.editable.removeAllSelections();
                dialog.dialog('close');
                return false;
            };

            buttonize = function (type) {
                var button, id;
                id = "" + _this.options.uuid + "-" + type;
                buttonset.append(jQuery("<input id=\"" + id + "\" type=\"checkbox\" />" + type + "").button());
                button = jQuery("#" + id, buttonset);

                button.bind("change", function (event) {
                    widget.lastSelection = widget.options.editable.getSelection();
                    urlInput = jQuery('input[name=url]', dialog);
                    nameInput = jQuery('input[name=name]', dialog);
                    if (widget.lastSelection.startContainer.parentNode.href === void 0) {
                        urlInput.val(widget.options.defaultUrl);
                        if (widget.lastSelection.toString() !== "") {
                            nameInput.val(widget.lastSelection.toString());
                        }
                    } else {
                        urlInput.val(jQuery(widget.lastSelection.startContainer.parentNode).attr('href'));
                        jQuery(urlInput[0].form).find('input[type=submit]').val('update');
                        if (widget.lastSelection.toString() !== "") {
                            nameInput.val(widget.lastSelection.toString());
                        }
                    }
                    return dialog.dialog('open');
                });

                return _this.element.bind("keyup paste change mouseup", function (event) {
                    var nodeName, start;
                    start = jQuery(widget.options.editable.getSelection().startContainer);
                    nodeName = start.prop('nodeName') ? start.prop('nodeName') : start.parent().prop('nodeName');
                    if (nodeName && nodeName.toUpperCase() === "A") {
                        button.attr("checked", true);
                        button.next().addClass("ui-state-clicked");
                        return button.button("refresh");
                    } else {
                        button.attr("checked", false);
                        button.next().removeClass("ui-state-clicked");
                        return button.button("refresh");
                    }
                });
            };

            dialog.find("form").submit(dialogSubmitCb);
            buttonset = jQuery("");

            if (this.options.link) buttonize("A");
            if (this.options.link) {
                buttonset.buttonset();
                this.options.toolbar.append(buttonset);
                return dialog.dialog(this.options.dialogOpts);
            }
        },
        _init: function () {
            var firstTab = jQuery('#link-dialog .nav li').first().attr("id");
            jQuery('#' + firstTab + '-content').show();
        },

        getReferenceByTags: function () {
            var tmpArticleTags;

            tmpArticleTags = jQuery('.inEditMode').parent().find('.articleTags input').val();
            /*tmpArticleTags = tmpArticleTags.replace(/</g, '');
            tmpArticleTags = tmpArticleTags.replace(/>/g, '');*/
            // uri = uri.replace(/^</, '').replace(/>$/, '');
            tmpArticleTags = tmpArticleTags.split(',');

            return tmpArticleTags;
        },

        prepareTags: function (tmpArticleTags) {
            var articleTags = [];
            var tagType;

            for(var i in tmpArticleTags) {
                tagType = typeof tmpArticleTags[i];
                if('string' === tagType) {
                    if(tmpArticleTags[i].indexOf('http') !== -1) articleTags.push(tmpArticleTags[i]);
                }
            }

            return articleTags;
        },

        tagLabel: function (value) {

            if (value.substring(0, 9) == '<urn:tag:') {
                value = value.substring(9, value.length - 1);
            }

            if (value.substring(0, 8) == '<http://') {
                value = value.substring(value.lastIndexOf('/') + 1, value.length - 1);
                value = value.replace(/_/g, ' ');
            }

            return value;
        }

    });
})(jQuery);<commit_msg>Removed fail alert<commit_after>(function (jQuery) {
    return jQuery.widget("Liip.hallolink", {
        options: {
            editable: null,
            toolbar: null,
            uuid: "link",
            link: true,
            image: true,
            relatedUrl: false,
            defaultUrl: 'http://',
            dialog: 'link',
            dialogOpts: {
                autoOpen: false,
                width: 500,
                height: 195,
                title: "Enter Link",
                modal: true,
                resizable: false,
                draggable: false,
                dialogClass: 'hallolink-dialog'
            }
        },

        _create: function () {
            var buttonize, buttonset, dialog, dialogId, dialogSubmitCb, urlInput, widget;
            var _this = this;
            widget = this;
            dialogId = "" + this.options.dialog + "-dialog";
            dialog = jQuery("

Insert URL

Suggested URLs

Related URLs

<form action=\"#\" method=\"post\" class=\"linkForm\"><input class=\"name\" type=\"text\" name=\"name\" value=\"Homepage Name\" /><input class=\"url\" type=\"text\" name=\"url\" value=\"" + this.options.defaultUrl + "\" /><input type=\"submit\" id=\"addlinkButton\" value=\"Insert\" /></form>

");
            urlInput = jQuery('input[name=url]', dialog).focus(function (e) {
                return this.select();
            });

            nameInput = jQuery('input[name=name]', dialog).focus(function(e) {
                return this.select();
            });

            // show or hide tab panels
            jQuery('#link-dialog .nav li').live('click', function () {
                jQuery('.' + dialogId + '-tab').each(function () {
                    return jQuery(this).hide();
                });
                id = jQuery(this).attr('id');
                jQuery('#' + id + '-content').show();
                return jQuery("#" + dialogId + "-tab-activeIndicator").css("margin-left", jQuery(this).position().left + (jQuery(this).width() / 2));
            });

            // Action when user clicks on a suggested link
            jQuery('#'+ this.options.uuid + '-tab-suggested-content li a, #'+ this.options.uuid + '-tab-related-content li a').live('click', function (event) {
                event.preventDefault();
                if (widget.lastSelection.toString() === '') {
                    jQuery('input[name=name]', dialog).val(jQuery(this).text());
                }
                jQuery('input[name=url]', dialog).val(this.href);
                dialog.find('form').trigger('submit');
                jQuery('#link-dialog .nav li').first().trigger('click');
            });

            // if user clicks on the suggestet links tab
            jQuery('#' + this.options.uuid + '-tab-suggested').live('click', function () {
                var container = jQuery('#' + _this.options.uuid + "-tab-suggested-content ul");
                container.empty().append('

');

                var articleTags = _this.prepareTags(_this.getReferenceByTags());

                if(articleTags.length > 0) {
                    var vie = new VIE();
                    vie.use(new vie.DBPediaService({
                        url : "http://dev.iks-project.eu/stanbolfull",
                        proxyDisabled: true
                        }));

                        jQuery(articleTags).each(function () {
                            var that = this;
                            vie.load({
                                entity: this + ""
                                }).
                                using('dbpedia').
                                execute().
                                fail(function(e){
                                    console.log(e);
                                }).
                                done(function(entity) {
                                    jQuery(entity).each(function () {
                                        var data = this;
                                        if (this.attributes) {
                                            data = this.attributes; // different Stanbol version
                                        }
                                        var url = data['<http://xmlns.com/foaf/0.1/primaryTopic>'] || data['<http://xmlns.com/foaf/0.1/homepage>'] || data['<http://xmlns.com/foaf/0.1/page>'] || null;
                                        if (url) {
                                            url = url.substring(1, url.length - 1);
                                            if (container.children('li.loader').size() == 1) {
                                                container.empty();
                                            }
                                            container.append('
' + _this.tagLabel(that + "") + '
');
                                        }
                                    });
                                });
                        });
                }
                else {
                    container.empty();
                    container.append('
No results found, please make sure you have some article tags set.
');
                }
            });

            // if user clicks on the related links tab
            jQuery('#' + this.options.uuid + '-tab-related').live('click', function () {
                var container = jQuery('#' + _this.options.uuid + "-tab-related-content ul");
                container.empty().append('

');
                var articleTags = _this.getReferenceByTags();

                return jQuery.ajax({
                    type: "GET",
                    url: _this.options.relatedUrl,
                    data: "tags="+articleTags+"&page="+window.location,
                    success: function(response) {
                        var items;
                        container.empty();
                        items = [];

                        if (response.links.length > 0) {
                            $.each(response.links, function() {
                                return items.push('
'+this.label+'
');
                            });
                            container.html(items.join(''));
                        } else {
                            container.append('
No results found, please make sure you have some articles with the same tags set.
');
                        }

                    },
                    failure: function(response) {
                        container.empty();
                        container.append('
An Error has occured
');
                    },
                });
            });

            dialogSubmitCb = function (e) {
                var link, name;
                link = urlInput.val();
                name = nameInput.val();
                e. preventDefault();

                widget.options.editable.restoreSelection(widget.lastSelection);
                if (((new RegExp(/^\s*$/)).test(link)) || link === widget.options.defaultUrl) {
                    if (widget.lastSelection.collapsed) {
                        widget.lastSelection.setStartBefore(widget.lastSelection.startContainer);
                        widget.lastSelection.setEndAfter(widget.lastSelection.startContainer);
                        window.getSelection().addRange(widget.lastSelection);
                    }
                    document.execCommand("unlink", null, "");
                } else {
                    if (widget.lastSelection.startContainer.parentNode.href === void 0) {

                        if (widget.lastSelection.toString() !== name) {
                            var newSelection = window.getSelection();
                            var range = newSelection.getRangeAt(0);

                            newTextNode = document.createTextNode(name);
                            range.extractContents();
                            range.insertNode(newTextNode);
                            range.setStartBefore(newTextNode);
                            range.setEndAfter(newTextNode);
                            newSelection.removeAllRanges();

                            newSelection.addRange(range);
                        }

                        document.execCommand("createLink", null, link);
                    } else {
                        widget.lastSelection.startContainer.parentNode.href = link;
                    }
                }
                widget.options.editable.element.trigger('change');
                widget.options.editable.removeAllSelections();
                dialog.dialog('close');
                return false;
            };

            buttonize = function (type) {
                var button, id;
                id = "" + _this.options.uuid + "-" + type;
                buttonset.append(jQuery("<input id=\"" + id + "\" type=\"checkbox\" />" + type + "").button());
                button = jQuery("#" + id, buttonset);

                button.bind("change", function (event) {
                    widget.lastSelection = widget.options.editable.getSelection();
                    urlInput = jQuery('input[name=url]', dialog);
                    nameInput = jQuery('input[name=name]', dialog);
                    if (widget.lastSelection.startContainer.parentNode.href === void 0) {
                        urlInput.val(widget.options.defaultUrl);
                        if (widget.lastSelection.toString() !== "") {
                            nameInput.val(widget.lastSelection.toString());
                        }
                    } else {
                        urlInput.val(jQuery(widget.lastSelection.startContainer.parentNode).attr('href'));
                        jQuery(urlInput[0].form).find('input[type=submit]').val('update');
                        if (widget.lastSelection.toString() !== "") {
                            nameInput.val(widget.lastSelection.toString());
                        }
                    }
                    return dialog.dialog('open');
                });

                return _this.element.bind("keyup paste change mouseup", function (event) {
                    var nodeName, start;
                    start = jQuery(widget.options.editable.getSelection().startContainer);
                    nodeName = start.prop('nodeName') ? start.prop('nodeName') : start.parent().prop('nodeName');
                    if (nodeName && nodeName.toUpperCase() === "A") {
                        button.attr("checked", true);
                        button.next().addClass("ui-state-clicked");
                        return button.button("refresh");
                    } else {
                        button.attr("checked", false);
                        button.next().removeClass("ui-state-clicked");
                        return button.button("refresh");
                    }
                });
            };

            dialog.find("form").submit(dialogSubmitCb);
            buttonset = jQuery("");

            if (this.options.link) buttonize("A");
            if (this.options.link) {
                buttonset.buttonset();
                this.options.toolbar.append(buttonset);
                return dialog.dialog(this.options.dialogOpts);
            }
        },
        _init: function () {
            var firstTab = jQuery('#link-dialog .nav li').first().attr("id");
            jQuery('#' + firstTab + '-content').show();
        },

        getReferenceByTags: function () {
            var tmpArticleTags;

            tmpArticleTags = jQuery('.inEditMode').parent().find('.articleTags input').val();
            /*tmpArticleTags = tmpArticleTags.replace(/</g, '');
            tmpArticleTags = tmpArticleTags.replace(/>/g, '');*/
            // uri = uri.replace(/^</, '').replace(/>$/, '');
            tmpArticleTags = tmpArticleTags.split(',');

            return tmpArticleTags;
        },

        prepareTags: function (tmpArticleTags) {
            var articleTags = [];
            var tagType;

            for(var i in tmpArticleTags) {
                tagType = typeof tmpArticleTags[i];
                if('string' === tagType) {
                    if(tmpArticleTags[i].indexOf('http') !== -1) articleTags.push(tmpArticleTags[i]);
                }
            }

            return articleTags;
        },

        tagLabel: function (value) {

            if (value.substring(0, 9) == '<urn:tag:') {
                value = value.substring(9, value.length - 1);
            }

            if (value.substring(0, 8) == '<http://') {
                value = value.substring(value.lastIndexOf('/') + 1, value.length - 1);
                value = value.replace(/_/g, ' ');
            }

            return value;
        }

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


<commit_before>/*
 * grunt-deploy
 * https://github.com/kevinschaul/strib-deploy
 *
 * Copyright (c) 2013 Kevin Schaul
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerTask('deploy', 'Deploy to apps.startribune.com', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      appsSvnPath: '../apps',
      branch: 'master'
    });

    // Require `dateSlug` option
    if (!options.dateSlug) {
      grunt.log.error('dateSlug option is required.');
      return false;
    }

    // TODO
    // Ensure we are on correct git branch

    // TODO
    // Ensure all changes have been committed to git

    // TODO
    // Ensure appsSvnPath exists

    // TODO
    // Ensure local svn repository is up to date

    // TODO
    // Copy latest project files to local svn repository

    // TODO
    // Commit to svn repository using slug + most recent git message
  });

};

<commit_msg>Add ensureCorrectGitBranch<commit_after>/*
 * grunt-deploy
 * https://github.com/kevinschaul/strib-deploy
 *
 * Copyright (c) 2013 Kevin Schaul
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  var exec = require('child_process').exec;

  grunt.registerTask('deploy', 'Deploy to apps.startribune.com', function() {
    var done = this.async();

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      appsSvnPath: '../apps',
      branch: 'master'
    });

    var branch = options.branch;
    var cwd = process.cwd();

    // Require `dateSlug` option
    if (!options.dateSlug) {
      grunt.log.error('dateSlug option is required.');
      return false;
    }

    // Ensure we are on correct git branch
    ensureCorrectGitBranch(cwd, options.branch, function(not_error) {
      done(not_error);
    });

    // TODO
    // Ensure all changes have been committed to git

    // TODO
    // Ensure appsSvnPath exists

    // TODO
    // Ensure local svn repository is up to date

    // TODO
    // Copy latest project files to local svn repository

    // TODO
    // Commit to svn repository using slug + most recent git message
  });

  var ensureCorrectGitBranch = function(cwd, branch, callback) {
    var not_error = true;

    var child = exec('git branch', function(error, stdout, stderr) {
      if (error) {
        grunt.log.error(error);
        not_error = false;
      }

      if (stdout) {
        var this_branch = getCurrentBranch(stdout);
        grunt.verbose.write('Current branch is `' + this_branch + '`');

        if (this_branch !== branch) {
          grunt.log.error('Must deploy from `' + branch + '` branch.');
          grunt.log.error('(Current branch is `' + this_branch + '`)');
          not_error = false;
        }
      }

      if (callback) {
        callback(not_error);
      }
    });
  }

  var getCurrentBranch = function(stdout) {
    var re = /\* ([\S]+)/;
    var matches = re.exec(stdout);
    if (matches.length >= 2) {
      var this_branch = matches[1];
      return this_branch;
    }
  }

};

<|endoftext|>


<commit_before>/*
 * @desc close to solution, slightly off
 */
var array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30],
    arrayn = (function() {
        var i = 0,
            sub = [];

            for (; i<100; i+=1) {
                sub.push(i);
            }
            return sub;
    }());

    picker = {
        "pick": function(inputArray, num) {
            "use strict";

            var len = inputArray.length,
                subArray = [],
                i = 1;

            // console.log("array length: ", len);

            for (; i <= num; i+=1) {
                var iter = i - 1,
                    subdiv = Math.floor(len / (num - 1)),
                    ptIndex = 0;

                if (subdiv < 0) {
                    subdiv = 0;
                }

                ptIndex = subdiv * iter;

                // console.log("iter", iter);
                // console.log("subdiv", subdiv);
                // console.log("inputArray[subdiv * iter]", inputArray[ptIndex]);

                if (ptIndex >= len) {
                    // console.log("ptIndex >= array length, ptIndex = ", ptIndex);
                    ptIndex = len - 1;
                }

                subArray.push(inputArray[ptIndex]);
            }
            return subArray;
        }
    };

// picker.pick(arrayn, 3); // [0, 50, 99]; // correct
// picker.pick(arrayn, 4); // [0, 33, 66, 99]; // correct
<commit_msg>added debug option, documentation<commit_after>/*
 * @auth twitter.com/mrnovo6123 (norman.vo@gmail.com)
 * @desc for any passed in array, picked an evenly distributed set of points
 */
var array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30],
    arrayn = (function() {
        var i = 0,
            sub = [];

            for (; i<100; i+=1) {
                sub.push(i);
            }
            return sub;
    }());

    picker = {
        "pick": function(inputArray, num, debug) {
            "use strict";

            var len = inputArray.length,
                subArray = [],
                i = 1;

            if (!!debug) {
                console.log("array length: ", len);
            }

            for (; i <= num; i+=1) {
                var iter = i - 1,
                    subdiv = Math.floor(len / (num - 1)),
                    ptIndex = 0;

                if (subdiv < 0) {
                    console.log("subdiv < 0");
                    subdiv = 0;
                }

                ptIndex = subdiv * iter;

                if (!!debug) {
                    console.log("iter", iter);
                    console.log("subdiv", subdiv);
                    console.log("inputArray[subdiv * iter]", inputArray[ptIndex]);
                }

                if (ptIndex >= len) {

                    if (!!debug) {
                        console.log("ptIndex >= array length, ptIndex = ", ptIndex);
                    }

                    ptIndex = len - 1;
                }

                subArray.push(inputArray[ptIndex]);
            }
            return subArray;
        }
    };

// picker.pick(arrayn, 3); // [0, 50, 99]; // correct
// picker.pick(arrayn, 4); // [0, 33, 66, 99]; // correct
<|endoftext|>


<commit_before>document.getElementById("ayuda").setAttribute("aria-current", "page");

var aside = document.getElementById("complementario");
var button = document.createElement("BUTTON");
button.setAttribute("id", "addonsButton");
var buttonText = document.createTextNode("Información sobre complementos de nvdaes");
button.appendChild(buttonText);
aside.appendChild(button);

addons = [
	"clipContentsDesigner",
	"emoticons",
	"eMule",
	"placeMarkers",
	"readFeeds",
	"reportSymbols",
]

var addonsLength = addons.length;

$(document).ready(function () {
	$("#addonsButton").click(function () {
		for (var i = 0; i < addonsLength; i++) {
			var details = document.createElement("DETAILS");
			var summary = document.createElement("SUMMARY");
			var t = document.createTextNode(addons[i]);
			summary.appendChild(t);
			details.appendChild(summary);
			//$.getJSON("https://api.github.com/repos/nvdaes/" + addons[i] + "/releases/latest", function(json) {
			var ul = document.createElement("UL");
			var li = document.createElement("LI");
			var t = document.createTextNode("name");
			li.appendChild(t);
			ul.appendChild(li);")
			details.appendChild(ul);
			aside.appendChild(details);
		}
	});
});
<commit_msg>Update script<commit_after>document.getElementById("ayuda").setAttribute("aria-current", "page");

var aside = document.getElementById("complementario");
var button = document.createElement("BUTTON");
button.setAttribute("id", "addonsButton");
var buttonText = document.createTextNode("Información sobre complementos de nvdaes");
button.appendChild(buttonText);
aside.appendChild(button);

addons = [
	"clipContentsDesigner",
	"emoticons",
	"eMule",
	"placeMarkers",
	"readFeeds",
	"reportSymbols",
]

var addonsLength = addons.length;

$(document).ready(function () {
	$("#addonsButton").click(function () {
		for (var i = 0; i < addonsLength; i++) {
			var details = document.createElement("DETAILS");
			var summary = document.createElement("SUMMARY");
			var t = document.createTextNode(addons[i]);
			summary.appendChild(t);
			details.appendChild(summary);
			//$.getJSON("https://api.github.com/repos/nvdaes/" + addons[i] + "/releases/latest", function(json) {
			aside.appendChild(details);
		}
	});
});
<|endoftext|>


<commit_before>// @flow
import * as React from 'react'
import {globalStyles, globalMargins, globalColors, isMobile, platformStyles} from '../../styles'
import {Box, Button, Text, Checkbox} from '../../common-adapters'

type Props = {
  openAtLogin: boolean,
  onSetOpenAtLogin: (open: boolean) => void,
  onDBNuke: () => void,
  onTrace: (durationSeconds: number) => void,
  onBack: () => void,
  traceInProgress: boolean,
}

const Advanced = (props: Props) => (
  <Box
    style={{
      ...globalStyles.flexBoxColumn,
      flex: 1,
      padding: globalMargins.medium,
    }}
  >
    {!isMobile && (
      <Box
        style={{
          ...globalStyles.flexBoxColumn,
          alignItems: 'left',
          flex: 1,
        }}
      >
        <Checkbox
          label="Open Keybase on startup"
          checked={props.openAtLogin}
          onCheck={props.onSetOpenAtLogin}
        />
      </Box>
    )}
    <Developer {...props} />
  </Box>
)

type TraceButtonProps = {
  durationSeconds: number,
  traceInProgress: boolean,
  onTrace: (durationSeconds: number) => void,
}

class TraceButton extends React.Component<TraceButtonProps> {
  _onClick = () => {
    this.props.onTrace(this.props.durationSeconds)
  }

  render() {
    const label = `Trace (${this.props.durationSeconds}s)`
    return (
      <Button
        waiting={this.props.traceInProgress}
        style={{marginTop: globalMargins.small}}
        type="Danger"
        label={label}
        onClick={this._onClick}
      />
    )
  }
}

type DeveloperState = {
  clickCount: number,
}

const clickThreshold = 7

class Developer extends React.Component<Props, DeveloperState> {
  constructor(props: Props) {
    super(props)

    this.state = {
      clickCount: 0,
    }
  }

  _onLabelClick = () => {
    this.setState(state => {
      const clickCount = state.clickCount + 1
      if (clickCount < clickThreshold) {
        console.log(
          `clickCount = ${clickCount} (${clickThreshold - clickCount} away from showing developer controls)`
        )
      }
      return {clickCount}
    })
  }

  _showTrace = () => {
    return this.state.clickCount >= clickThreshold
  }

  render() {
    const props = this.props
    return (
      <Box
        style={{
          ...globalStyles.flexBoxColumn,
          alignItems: 'center',
          paddingTop: globalMargins.xlarge,
          paddingBottom: globalMargins.medium,
          flex: 1,
        }}
      >
        <Text
          type="BodySmallSemibold"
          onClick={this._onLabelClick}
          style={platformStyles({
            common: {
              textAlign: 'center',
            },
            isElectron: {
              cursor: 'default',
            },
          })}
        >
          {isMobile
            ? `Please don't do anything here unless instructed to by a developer.`
            : `Please don't do anything below here unless instructed to by a developer.`}
        </Text>
        <Box style={{width: '100%', height: 2, backgroundColor: globalColors.grey}} />
        <Button
          style={{marginTop: globalMargins.small}}
          type="Danger"
          label="DB Nuke"
          onClick={props.onDBNuke}
        />
        {this._showTrace() && (
          <TraceButton durationSeconds={30} onTrace={props.onTrace} traceInProgress={props.traceInProgress} />
        )}
        {this._showTrace() && (
          <Text type="BodySmallSemibold" style={{textAlign: 'center'}}>
            Trace files are included in logs sent with feedback.
          </Text>
        )}
        <Box style={{flex: 1}} />
      </Box>
    )
  }
}

export default Advanced
<commit_msg>Just turn off the linux startup setting (#11070)<commit_after>// @flow
import * as React from 'react'
import {globalStyles, globalMargins, globalColors, isMobile, platformStyles} from '../../styles'
import {Box, Button, Text, Checkbox} from '../../common-adapters'
import {isLinux} from '../../constants/platform'

type Props = {
  openAtLogin: boolean,
  onSetOpenAtLogin: (open: boolean) => void,
  onDBNuke: () => void,
  onTrace: (durationSeconds: number) => void,
  onBack: () => void,
  traceInProgress: boolean,
}

const Advanced = (props: Props) => (
  <Box
    style={{
      ...globalStyles.flexBoxColumn,
      flex: 1,
      padding: globalMargins.medium,
    }}
  >
    {!isMobile &&
      !isLinux && (
        <Box
          style={{
            ...globalStyles.flexBoxColumn,
            alignItems: 'left',
            flex: 1,
          }}
        >
          <Checkbox
            label="Open Keybase on startup"
            checked={props.openAtLogin}
            onCheck={props.onSetOpenAtLogin}
          />
        </Box>
      )}
    <Developer {...props} />
  </Box>
)

type TraceButtonProps = {
  durationSeconds: number,
  traceInProgress: boolean,
  onTrace: (durationSeconds: number) => void,
}

class TraceButton extends React.Component<TraceButtonProps> {
  _onClick = () => {
    this.props.onTrace(this.props.durationSeconds)
  }

  render() {
    const label = `Trace (${this.props.durationSeconds}s)`
    return (
      <Button
        waiting={this.props.traceInProgress}
        style={{marginTop: globalMargins.small}}
        type="Danger"
        label={label}
        onClick={this._onClick}
      />
    )
  }
}

type DeveloperState = {
  clickCount: number,
}

const clickThreshold = 7

class Developer extends React.Component<Props, DeveloperState> {
  constructor(props: Props) {
    super(props)

    this.state = {
      clickCount: 0,
    }
  }

  _onLabelClick = () => {
    this.setState(state => {
      const clickCount = state.clickCount + 1
      if (clickCount < clickThreshold) {
        console.log(
          `clickCount = ${clickCount} (${clickThreshold - clickCount} away from showing developer controls)`
        )
      }
      return {clickCount}
    })
  }

  _showTrace = () => {
    return this.state.clickCount >= clickThreshold
  }

  render() {
    const props = this.props
    return (
      <Box
        style={{
          ...globalStyles.flexBoxColumn,
          alignItems: 'center',
          paddingTop: globalMargins.xlarge,
          paddingBottom: globalMargins.medium,
          flex: 1,
        }}
      >
        <Text
          type="BodySmallSemibold"
          onClick={this._onLabelClick}
          style={platformStyles({
            common: {
              textAlign: 'center',
            },
            isElectron: {
              cursor: 'default',
            },
          })}
        >
          {isMobile
            ? `Please don't do anything here unless instructed to by a developer.`
            : `Please don't do anything below here unless instructed to by a developer.`}
        </Text>
        <Box style={{width: '100%', height: 2, backgroundColor: globalColors.grey}} />
        <Button
          style={{marginTop: globalMargins.small}}
          type="Danger"
          label="DB Nuke"
          onClick={props.onDBNuke}
        />
        {this._showTrace() && (
          <TraceButton durationSeconds={30} onTrace={props.onTrace} traceInProgress={props.traceInProgress} />
        )}
        {this._showTrace() && (
          <Text type="BodySmallSemibold" style={{textAlign: 'center'}}>
            Trace files are included in logs sent with feedback.
          </Text>
        )}
        <Box style={{flex: 1}} />
      </Box>
    )
  }
}

export default Advanced
<|endoftext|>