<commit_before>/*
jQuery.ganttView v.0.7.2
Copyright (c) 2010 JC Grubbs - jc.grubbs@devmynd.com
MIT License Applies
*/

/*
Options
-----------------
showWeekends: boolean
data: object
start: date
end: date
cellWidth: number
cellHeight: number
slideWidth: number
*/

var ChartLang = {
    days: "days"
};

(function (jQuery) {
    jQuery.fn.ganttView = function (options) {

        var els = this;
        var defaults = {
            showWeekends: true,
            cellWidth: 21,
            cellHeight: 21,
            slideWidth: 400,
            vHeaderWidth: 100,
            blockClick: null
        };
        var opts = jQuery.extend(defaults, options);
        var months = Chart.getMonths(opts.start, opts.end);

        els.each(function () {

            var container = jQuery(this);
            var div = jQuery("<div>", { "class": "ganttview" });

            Chart.addVtHeader(div, opts.data, opts.cellHeight);

            var slideDiv = jQuery("<div>", {
                "class": "ganttview-slide-container",
                "css": { "width": opts.slideWidth + "px" }
            });

            Chart.addHzHeader(slideDiv, months, opts.cellWidth);
            Chart.addGrid(slideDiv, opts.data, months, opts.cellWidth, opts.showWeekends);
            Chart.addBlockContainers(slideDiv, opts.data);
            Chart.addBlocks(slideDiv, opts.data, opts.cellWidth, opts.start, opts.cellWidth);

            div.append(slideDiv);
            container.append(div);

            var w = jQuery("div.ganttview-vtheader", container).outerWidth() +
              jQuery("div.ganttview-slide-container", container).outerWidth();

            Chart.applyLastClass(container);

            Events.bindBlockClick(container, opts.blockClick);
        });
    };

    var Chart = {

        monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],

        getMonths: function (start, end) {
            start = Date.parse(start); end = Date.parse(end);
            var months = []; months[start.getMonth()] = [start];
            var last = start;
            while (last.compareTo(end) == -1) {
                var next = last.clone().addDays(1);
                if (!months[next.getMonth()]) { months[next.getMonth()] = []; }
                months[next.getMonth()].push(next);
                last = next;
            }
            return months;
        },

        addVtHeader: function (div, data, cellHeight) {
            var headerDiv = jQuery("<div>", { "class": "ganttview-vtheader" });
            for (var i = 0; i < data.length; i++) {
                var itemDiv = jQuery("<div>", { "class": "ganttview-vtheader-item" });
                itemDiv.append(jQuery("<div>", {
                    "class": "ganttview-vtheader-item-name",
                    "css": { "height": (data[i].series.length * cellHeight) + "px" }
                }).append(data[i].name));
                var seriesDiv = jQuery("<div>", { "class": "ganttview-vtheader-series" });
                for (var j = 0; j < data[i].series.length; j++) {
                    seriesDiv.append(jQuery("<div>", { "class": "ganttview-vtheader-series-name" })
            .append(data[i].series[j].name));
                }
                itemDiv.append(seriesDiv);
                headerDiv.append(itemDiv);
            }
            div.append(headerDiv);
        },

        addHzHeader: function (div, months, cellWidth) {
            var headerDiv = jQuery("<div>", { "class": "ganttview-hzheader" });
            var monthsDiv = jQuery("<div>", { "class": "ganttview-hzheader-months" });
            var daysDiv = jQuery("<div>", { "class": "ganttview-hzheader-days" });
            var totalW = 0;
            for (var i = 0; i < 12; i++) {
                if (months[i]) {
                    var w = months[i].length * cellWidth;
                    totalW = totalW + w;
                    monthsDiv.append(jQuery("<div>", {
                        "class": "ganttview-hzheader-month",
                        "css": { "width": (w - 1) + "px" }
                    }).append(Chart.monthNames[i]));
                    for (var j = 0; j < months[i].length; j++) {
                        daysDiv.append(jQuery("<div>", { "class": "ganttview-hzheader-day" })
              .append(months[i][j].getDate()));
                    }
                }
            }
            monthsDiv.css("width", totalW + "px");
            daysDiv.css("width", totalW + "px");
            headerDiv.append(monthsDiv).append(daysDiv);
            div.append(headerDiv);
        },

        addGrid: function (div, data, months, cellWidth, showWeekends) {
            var gridDiv = jQuery("<div>", { "class": "ganttview-grid" });
            var rowDiv = jQuery("<div>", { "class": "ganttview-grid-row" });
            for (var i = 0; i < 12; i++) {
                if (months[i]) {
                    for (var j = 0; j < months[i].length; j++) {
                        var cellDiv = jQuery("<div>", { "class": "ganttview-grid-row-cell " });
                        if (DateUtils.isWeekend(months[i][j]) && showWeekends) { cellDiv.addClass("ganttview-weekend"); }
                        rowDiv.append(cellDiv);
                    }
                }
            }
            var w = jQuery("div.ganttview-grid-row-cell", rowDiv).length * cellWidth;
            rowDiv.css("width", w + "px");
            gridDiv.css("width", w + "px");
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < data[i].series.length; j++) {
                    gridDiv.append(rowDiv.clone());
                }
            }
            div.append(gridDiv);
        },

        addBlockContainers: function (div, data) {
            var blocksDiv = jQuery("<div>", { "class": "ganttview-blocks" });
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < data[i].series.length; j++) {
                    blocksDiv.append(jQuery("<div>", { "class": "ganttview-block-container" }));
                }
            }
            div.append(blocksDiv);
        },

        addBlocks: function (div, data, cellWidth, start, cellWidth) {
            var rows = jQuery("div.ganttview-blocks div.ganttview-block-container", div);
            var rowIdx = 0;
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < data[i].series.length; j++) {
                    var series = data[i].series[j];
                    var size = DateUtils.daysBetween(series.start, series.end);
                    if (size && size > 0) {
                        if (size > 365) { size = 365; } // Keep blocks from overflowing a year
                        var offset = DateUtils.daysBetween(start, series.start);
                        var blockDiv = jQuery("<div>", {
                            "class": "ganttview-block",
                            "title": series.name + ", " + size + ChartLang.days,
                            "css": {
                                "width": ((size * cellWidth) - 9) + "px",
                                "margin-left": ((offset * cellWidth) + 3) + "px"
                            }
                        }).data("block-data", {
                            id: data[i].id,
                            itemName: data[i].name,
                            seriesName: series.name,
                            start: Date.parse(series.start),
                            end: Date.parse(series.end),
                            color: series.color
                        });
                        if (data[i].series[j].color) {
                            blockDiv.css("background-color", data[i].series[j].color);
                        }
                        if(data[i].series[j].text) {
                            blockDiv.append($("<div>", { "class": "ganttview-block-text" }).text(data[i].series[j].text));
                        }else{
                            blockDiv.append($("<div>", { "class": "ganttview-block-text" }).text(size));
                        }
                        blockDiv.draggable({
                          axis: 'x',
                          containment: 'parent',
                          grid: [cellWidth, 0],
                          stop: function(event, ui) {
                            var distance = ui.position.left / 21
                            var s = blockDiv.data('block-data').start.clone().addDays(distance)
                            var e = blockDiv.data('block-data').end.clone().addDays(distance)
                            console.debug('distance: %o, start: %o, end: %o', distance, s, e)
                          }
                        }).resizable({
                          containment: 'parent',
                          grid: [cellWidth, 0],
                          handles: 'e',
                          stop: function(event, ui) {
                            var rdistance = Math.ceil(ui.size.width / 21)
                            var rs = blockDiv.data('block-data').start.clone().addDays(rdistance)
                            var re = blockDiv.data('block-data').end.clone().addDays(rdistance)
                            console.debug('width: %o, originalSize: %o, day: %o', ui.size.width, ui.originalSize.width, rdistance)
                          }
                        })
                        jQuery(rows[rowIdx]).append(blockDiv);
                    }
                    rowIdx = rowIdx + 1;
                }
            }
        },

        applyLastClass: function (div) {
            jQuery("div.ganttview-grid-row div.ganttview-grid-row-cell:last-child", div).addClass("last");
            jQuery("div.ganttview-hzheader-days div.ganttview-hzheader-day:last-child", div).addClass("last");
            jQuery("div.ganttview-hzheader-months div.ganttview-hzheader-month:last-child", div).addClass("last");
        }

    };

    var Events = {

        bindBlockClick: function (div, callback) {
            $("div.ganttview-block").live("click", function () {
                if (callback) { callback($(this).data("block-data")); }
            });
        }
    };

    var ArrayUtils = {
        contains: function (arr, obj) {
            var has = false;
            for (var i = 0; i < arr.length; i++) { if (arr[i] == obj) { has = true; } }
            return has;
        }
    };

    var DateUtils = {
        daysBetween: function (start, end) {
            if (!start || !end) { return 0; }
            start = Date.parse(start); end = Date.parse(end);
            if (start.getYear() == 1901 || end.getYear() == 8099) { return 0; }
            var count = 0, date = start.clone();
            while (date.compareTo(end) == -1) { count = count + 1; date.addDays(1); }
            return count;
        },
        isWeekend: function (date) {
            return date.getDay() % 6 == 0;
        }
    };

})(jQuery);
<commit_msg>Repetition is deleted.<commit_after>/*
jQuery.ganttView v.0.7.2
Copyright (c) 2010 JC Grubbs - jc.grubbs@devmynd.com
MIT License Applies
*/

/*
Options
-----------------
showWeekends: boolean
data: object
start: date
end: date
cellWidth: number
cellHeight: number
slideWidth: number
*/

var ChartLang = {
    days: "days"
};

(function (jQuery) {
    jQuery.fn.ganttView = function (options) {

        var els = this;
        var defaults = {
            showWeekends: true,
            cellWidth: 21,
            cellHeight: 21,
            slideWidth: 400,
            vHeaderWidth: 100,
            blockClick: null
        };
        var opts = jQuery.extend(defaults, options);
        var months = Chart.getMonths(opts.start, opts.end);

        els.each(function () {

            var container = jQuery(this);
            var div = jQuery("<div>", { "class": "ganttview" });

            Chart.addVtHeader(div, opts.data, opts.cellHeight);

            var slideDiv = jQuery("<div>", {
                "class": "ganttview-slide-container",
                "css": { "width": opts.slideWidth + "px" }
            });

            Chart.addHzHeader(slideDiv, months, opts.cellWidth);
            Chart.addGrid(slideDiv, opts.data, months, opts.cellWidth, opts.showWeekends);
            Chart.addBlockContainers(slideDiv, opts.data);
            Chart.addBlocks(slideDiv, opts.data, opts.cellWidth, opts.start);

            div.append(slideDiv);
            container.append(div);

            var w = jQuery("div.ganttview-vtheader", container).outerWidth() +
              jQuery("div.ganttview-slide-container", container).outerWidth();

            Chart.applyLastClass(container);

            Events.bindBlockClick(container, opts.blockClick);
        });
    };

    var Chart = {

        monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],

        getMonths: function (start, end) {
            start = Date.parse(start); end = Date.parse(end);
            var months = []; months[start.getMonth()] = [start];
            var last = start;
            while (last.compareTo(end) == -1) {
                var next = last.clone().addDays(1);
                if (!months[next.getMonth()]) { months[next.getMonth()] = []; }
                months[next.getMonth()].push(next);
                last = next;
            }
            return months;
        },

        addVtHeader: function (div, data, cellHeight) {
            var headerDiv = jQuery("<div>", { "class": "ganttview-vtheader" });
            for (var i = 0; i < data.length; i++) {
                var itemDiv = jQuery("<div>", { "class": "ganttview-vtheader-item" });
                itemDiv.append(jQuery("<div>", {
                    "class": "ganttview-vtheader-item-name",
                    "css": { "height": (data[i].series.length * cellHeight) + "px" }
                }).append(data[i].name));
                var seriesDiv = jQuery("<div>", { "class": "ganttview-vtheader-series" });
                for (var j = 0; j < data[i].series.length; j++) {
                    seriesDiv.append(jQuery("<div>", { "class": "ganttview-vtheader-series-name" })
            .append(data[i].series[j].name));
                }
                itemDiv.append(seriesDiv);
                headerDiv.append(itemDiv);
            }
            div.append(headerDiv);
        },

        addHzHeader: function (div, months, cellWidth) {
            var headerDiv = jQuery("<div>", { "class": "ganttview-hzheader" });
            var monthsDiv = jQuery("<div>", { "class": "ganttview-hzheader-months" });
            var daysDiv = jQuery("<div>", { "class": "ganttview-hzheader-days" });
            var totalW = 0;
            for (var i = 0; i < 12; i++) {
                if (months[i]) {
                    var w = months[i].length * cellWidth;
                    totalW = totalW + w;
                    monthsDiv.append(jQuery("<div>", {
                        "class": "ganttview-hzheader-month",
                        "css": { "width": (w - 1) + "px" }
                    }).append(Chart.monthNames[i]));
                    for (var j = 0; j < months[i].length; j++) {
                        daysDiv.append(jQuery("<div>", { "class": "ganttview-hzheader-day" })
              .append(months[i][j].getDate()));
                    }
                }
            }
            monthsDiv.css("width", totalW + "px");
            daysDiv.css("width", totalW + "px");
            headerDiv.append(monthsDiv).append(daysDiv);
            div.append(headerDiv);
        },

        addGrid: function (div, data, months, cellWidth, showWeekends) {
            var gridDiv = jQuery("<div>", { "class": "ganttview-grid" });
            var rowDiv = jQuery("<div>", { "class": "ganttview-grid-row" });
            for (var i = 0; i < 12; i++) {
                if (months[i]) {
                    for (var j = 0; j < months[i].length; j++) {
                        var cellDiv = jQuery("<div>", { "class": "ganttview-grid-row-cell " });
                        if (DateUtils.isWeekend(months[i][j]) && showWeekends) { cellDiv.addClass("ganttview-weekend"); }
                        rowDiv.append(cellDiv);
                    }
                }
            }
            var w = jQuery("div.ganttview-grid-row-cell", rowDiv).length * cellWidth;
            rowDiv.css("width", w + "px");
            gridDiv.css("width", w + "px");
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < data[i].series.length; j++) {
                    gridDiv.append(rowDiv.clone());
                }
            }
            div.append(gridDiv);
        },

        addBlockContainers: function (div, data) {
            var blocksDiv = jQuery("<div>", { "class": "ganttview-blocks" });
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < data[i].series.length; j++) {
                    blocksDiv.append(jQuery("<div>", { "class": "ganttview-block-container" }));
                }
            }
            div.append(blocksDiv);
        },

        addBlocks: function (div, data, cellWidth, start) {
            var rows = jQuery("div.ganttview-blocks div.ganttview-block-container", div);
            var rowIdx = 0;
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < data[i].series.length; j++) {
                    var series = data[i].series[j];
                    var size = DateUtils.daysBetween(series.start, series.end);
                    if (size && size > 0) {
                        if (size > 365) { size = 365; } // Keep blocks from overflowing a year
                        var offset = DateUtils.daysBetween(start, series.start);
                        var blockDiv = jQuery("<div>", {
                            "class": "ganttview-block",
                            "title": series.name + ", " + size + ChartLang.days,
                            "css": {
                                "width": ((size * cellWidth) - 9) + "px",
                                "margin-left": ((offset * cellWidth) + 3) + "px"
                            }
                        }).data("block-data", {
                            id: data[i].id,
                            itemName: data[i].name,
                            seriesName: series.name,
                            start: Date.parse(series.start),
                            end: Date.parse(series.end),
                            color: series.color
                        });
                        if (data[i].series[j].color) {
                            blockDiv.css("background-color", data[i].series[j].color);
                        }
                        if(data[i].series[j].text) {
                            blockDiv.append($("<div>", { "class": "ganttview-block-text" }).text(data[i].series[j].text));
                        }else{
                            blockDiv.append($("<div>", { "class": "ganttview-block-text" }).text(size));
                        }
                        blockDiv.draggable({
                          axis: 'x',
                          containment: 'parent',
                          grid: [cellWidth, 0],
                          stop: function(event, ui) {
                            var distance = ui.position.left / 21
                            var s = blockDiv.data('block-data').start.clone().addDays(distance)
                            var e = blockDiv.data('block-data').end.clone().addDays(distance)
                            console.debug('distance: %o, start: %o, end: %o', distance, s, e)
                          }
                        }).resizable({
                          containment: 'parent',
                          grid: [cellWidth, 0],
                          handles: 'e',
                          stop: function(event, ui) {
                            var rdistance = Math.ceil(ui.size.width / 21)
                            var rs = blockDiv.data('block-data').start.clone().addDays(rdistance)
                            var re = blockDiv.data('block-data').end.clone().addDays(rdistance)
                            console.debug('width: %o, originalSize: %o, day: %o', ui.size.width, ui.originalSize.width, rdistance)
                          }
                        })
                        jQuery(rows[rowIdx]).append(blockDiv);
                    }
                    rowIdx = rowIdx + 1;
                }
            }
        },

        applyLastClass: function (div) {
            jQuery("div.ganttview-grid-row div.ganttview-grid-row-cell:last-child", div).addClass("last");
            jQuery("div.ganttview-hzheader-days div.ganttview-hzheader-day:last-child", div).addClass("last");
            jQuery("div.ganttview-hzheader-months div.ganttview-hzheader-month:last-child", div).addClass("last");
        }

    };

    var Events = {

        bindBlockClick: function (div, callback) {
            $("div.ganttview-block").live("click", function () {
                if (callback) { callback($(this).data("block-data")); }
            });
        }
    };

    var ArrayUtils = {
        contains: function (arr, obj) {
            var has = false;
            for (var i = 0; i < arr.length; i++) { if (arr[i] == obj) { has = true; } }
            return has;
        }
    };

    var DateUtils = {
        daysBetween: function (start, end) {
            if (!start || !end) { return 0; }
            start = Date.parse(start); end = Date.parse(end);
            if (start.getYear() == 1901 || end.getYear() == 8099) { return 0; }
            var count = 0, date = start.clone();
            while (date.compareTo(end) == -1) { count = count + 1; date.addDays(1); }
            return count;
        },
        isWeekend: function (date) {
            return date.getDay() % 6 == 0;
        }
    };

})(jQuery);
<|endoftext|>


<commit_before>/**
 * Router controller: Project page.
 */
TileMill.controller.project = function() {
  var id = $.bbq.getState('id');
  TileMill.backend.get('project/' + id + '/' + id + '.mml', function(mml) {
    // Bail if MML was not valid.
    if (typeof mml != 'string') {
      TileMill.errorPage(mml.data);
      return false;
    }

    // Store current project data.
    TileMill.data.mml = mml;
    TileMill.data.id = id;
    TileMill.data.type = 'project';
    TileMill.data.filename = 'project/' + id + '/' + id + '.mml';

    // Set the unique query string.
    TileMill.data.uniq = (new Date().getTime());

    // Parse MML.
    var parsed = TileMill.mml.parseMML(mml);

    TileMill.show(TileMill.template('project', {id: id}));

    var layers = TileMill.mml.init();
    var inspector = TileMill.inspector.init();
    var stylesheets = TileMill.stylesheet.init();
    var map = TileMill.map.init();
    var color = TileMill.colors.init();

    $('#sidebar').append(layers);
    $('#sidebar').append(inspector);
    $('#sidebar').append(map).addClass('with-map');
    $('#main').append(stylesheets);
    $('#main').append(color);

    // Init elements which require DOM presence.
    TileMill.colors.initFarb(color);
    // TODO: actually configure map, don't pretend to
    TileMill.map.initOL(map, TileMill.backend.servers(TileMill.mml.url()), {
        navigation: 1,
        fullscreen: 1,
        zoom: 1,
        panzoombar: 0
    }, parsed.metadata.mapCenter);

    $('div#header a.save').click(function() {
      if ($(this).is('.changed')) {
        TileMill.project.save();
      }
      return false;
    });

    $(document).bind('keypress', 'Ctrl+S', function(event) {
      TileMill.project.save();
      return false;
    });

    $('div#header a.info').click(function() {
      var tilelive_url = TileMill.backend.servers(TileMill.mml.url())[0] +
        'tile/' + TileMill.mml.url({ timestamp: false, encode: true });
      var mml_url = TileMill.mml.url({
          timestamp: false,
          encode: false
      });
      var popup = $(TileMill.template('popup-info-project', {
          tilelive_url: tilelive_url,
          mml_url: mml_url
      }));
      TileMill.popup.show({content: popup, title: 'Info'});
      return false;
    });

    $('div#header a.minimal').toggle(
        function() {
          $('#main').hide();
          $('#sidebar').css('width', '100%');
          TileMill.project_watcher = setInterval(TileMill.project.watch, 1000);
        },
        function() {
          $('#main').show();
          $('#sidebar').css('width', '30%');
          TileMill.project_watcher = null;
        }
    );

    $('div#header a.home').click(function() {
      if (!$('div#header a.save').is('.changed') ||
          confirm('You have unsaved changes. Are you sure you ' +
              'want to close this project?')) {
        return true;
      }
      return false;
    });

    // Hide inspector to start.
    inspector.hide();
    $('a.inspector-close').click(function() {
      $('#layers').show();
      $('#inspector').hide();
      return false;
    });

    setInterval(TileMill.project.status, 10000);
  });
};

TileMill.project = {};

/**
 * Mark this project as changed (and needing to be saved).
 */
TileMill.project.changed = function() {
  $('div#header a.save').addClass('changed');
};

TileMill.project.checkStale = function(data) {
  $('#tabs a.tab').each(function() {
    if (($.url.setUrl($(this).data('tilemill').src)
            .param('filename') == data.filename) &&
      ($(this).data('tilemill').mtime != data.mtime)) {
      TileMill.inspector.load();
      TileMill.data.uniq = (new Date().getTime());
      TileMill.map.reload(
          $('#map-preview'),
          TileMill.backend.servers(TileMill.mml.url()));
      $('div#header a.save').removeClass('changed');
      $(this).data('tilemill').mtime = data.mtime;
    }
  });
};

TileMill.project.status = function() {
  TileMill.backend.status(function(status) {
    if (status) {
        $('.status').removeClass('offline');
    } else {
        $('.status').text('tile server offline');
        $('.status').addClass('offline');
    }
  });
};

TileMill.project.watch = function() {
  var id = TileMill.data.id,
      queue = new TileMill.queue();
  $('#tabs a.tab').each(function() {
    TileMill.stylesheet.setCode($('#tabs a.active'), true);
    TileMill.stylesheet.mtime(
      $.url.setUrl($(this).data('tilemill').src).param('filename'),
      TileMill.project.checkStale);
  });
};

/**
 * Save a project from its current DOM state.
 */
TileMill.project.save = function() {
  // Refresh storage of active stylesheet before saving.
  TileMill.stylesheet.setCode($('#tabs a.active'), true);

  var id = TileMill.data.id,
      queue = new TileMill.queue();
  queue.add(function(id, next) {
    var mml = {
      metadata: {},
      stylesheets: [],
      layers: []
    };

    // Retrieve map preview.
    mml.metadata.mapCenter = TileMill.map.getCenter($('#map-preview'));

    $('#tabs a.tab').each(function() {
      mml.stylesheets.push(
          TileMill.backend.url($.url.setUrl($(this).data('tilemill').src)
              .param('filename')) + '&c=' + TileMill.data.uniq);
      TileMill.stylesheet.save(
          $.url.setUrl($(this).data('tilemill').src).param('filename'),
          $('input', this).val());
    });
    $('#layers ul.sidebar-content li').reverse().each(function() {
      var layer = $(this).data('tilemill');
      if (layer) {
        layer.status = !!$(this).find('input[type=checkbox]').is(':checked');
        mml.layers.push(layer);
      }
    });
    mml = TileMill.mml.generate(mml);
    TileMill.backend.post('project/' + id + '/' + id + '.mml', mml, next);
  }, [id]);
  queue.add(function() {
    TileMill.inspector.load();
    TileMill.data.uniq = (new Date().getTime());
    TileMill.map.reload(
        $('#map-preview'),
        TileMill.backend.servers(TileMill.mml.url()));
    $('div#header a.save').removeClass('changed');
  });
  queue.execute();
};

/**
 * Add a new project.
 */
TileMill.project.add = function(name) {
  $('body').append(TileMill.template('loading', {}));

  var queue = new TileMill.queue();
  queue.add(function(name, next) {
    var self = this;
    TileMill.backend.list('project', function(projects) {
      if ($.inArray(name, projects) !== -1) {
        $('body div.loading').remove();
        TileMill.message('Error', 'A project with the name ' +
            name + ' already exists. Please choose another name.',
            'error');
        self.reset();
      }
      else {
        next();
      }
    });
  }, [name]);
  queue.add(function(name, next) {
    var mss = 'project/' + name + '/' + name + '.mss';
    var data = TileMill.mss.generate({
      'Map': {
        'map-bgcolor': '#fff'
      },
      '#world': {
        'polygon-fill': '#eee',
        'line-color': '#ccc',
        'line-width': '0.5'
      }
    });
    TileMill.backend.post(mss, data, next);
  }, [name]);
  queue.add(function(name, next) {
    var mss = 'project/' + name + '/' + name + '.mss';
    var mml = 'project/' + name + '/' + name + '.mml';
    var data = TileMill.mml.generate({
      stylesheets: [TileMill.backend.url(mss)],
      layers: [{
        id: 'world',
        srs: '&srsWGS84;',
        // TODO: make configurable
        file: 'http://cascadenik-sampledata.s3.amazonaws.com/world_borders.zip',
        type: 'shape'
      }]
    });
    TileMill.backend.post(mml, data, next);
  }, [name]);
  queue.add(function(name) {
    $.bbq.pushState({ 'action': 'project', 'id': name });
  }, [name]);
  queue.execute();
};
<commit_msg>Properly killing minimal mode when you flip back<commit_after>/**
 * Router controller: Project page.
 */
TileMill.controller.project = function() {
  var id = $.bbq.getState('id');
  TileMill.backend.get('project/' + id + '/' + id + '.mml', function(mml) {
    // Bail if MML was not valid.
    if (typeof mml != 'string') {
      TileMill.errorPage(mml.data);
      return false;
    }

    // Store current project data.
    TileMill.data.mml = mml;
    TileMill.data.id = id;
    TileMill.data.type = 'project';
    TileMill.data.filename = 'project/' + id + '/' + id + '.mml';

    // Set the unique query string.
    TileMill.data.uniq = (new Date().getTime());

    // Parse MML.
    var parsed = TileMill.mml.parseMML(mml);

    TileMill.show(TileMill.template('project', {id: id}));

    var layers = TileMill.mml.init();
    var inspector = TileMill.inspector.init();
    var stylesheets = TileMill.stylesheet.init();
    var map = TileMill.map.init();
    var color = TileMill.colors.init();

    $('#sidebar').append(layers);
    $('#sidebar').append(inspector);
    $('#sidebar').append(map).addClass('with-map');
    $('#main').append(stylesheets);
    $('#main').append(color);

    // Init elements which require DOM presence.
    TileMill.colors.initFarb(color);
    // TODO: actually configure map, don't pretend to
    TileMill.map.initOL(map, TileMill.backend.servers(TileMill.mml.url()), {
        navigation: 1,
        fullscreen: 1,
        zoom: 1,
        panzoombar: 0
    }, parsed.metadata.mapCenter);

    $('div#header a.save').click(function() {
      if ($(this).is('.changed')) {
        TileMill.project.save();
      }
      return false;
    });

    $(document).bind('keypress', 'Ctrl+S', function(event) {
      TileMill.project.save();
      return false;
    });

    $('div#header a.info').click(function() {
      var tilelive_url = TileMill.backend.servers(TileMill.mml.url())[0] +
        'tile/' + TileMill.mml.url({ timestamp: false, encode: true });
      var mml_url = TileMill.mml.url({
          timestamp: false,
          encode: false
      });
      var popup = $(TileMill.template('popup-info-project', {
          tilelive_url: tilelive_url,
          mml_url: mml_url
      }));
      TileMill.popup.show({content: popup, title: 'Info'});
      return false;
    });

    $('div#header a.minimal').toggle(
        function() {
          $('#main').hide();
          $('#sidebar').css('width', '100%');
          TileMill.project_watcher = setInterval(TileMill.project.watch, 1000);
        },
        function() {
          $('#main').show();
          $('#sidebar').css('width', '30%');
          window.clearInterval(TileMill.project_watcher);
        }
    );

    $('div#header a.home').click(function() {
      if (!$('div#header a.save').is('.changed') ||
          confirm('You have unsaved changes. Are you sure you ' +
              'want to close this project?')) {
        return true;
      }
      return false;
    });

    // Hide inspector to start.
    inspector.hide();
    $('a.inspector-close').click(function() {
      $('#layers').show();
      $('#inspector').hide();
      return false;
    });

    setInterval(TileMill.project.status, 10000);
  });
};

TileMill.project = {};

/**
 * Mark this project as changed (and needing to be saved).
 */
TileMill.project.changed = function() {
  $('div#header a.save').addClass('changed');
};

TileMill.project.checkStale = function(data) {
  $('#tabs a.tab').each(function() {
    if (($.url.setUrl($(this).data('tilemill').src)
            .param('filename') == data.filename) &&
      ($(this).data('tilemill').mtime != data.mtime)) {
      TileMill.inspector.load();
      TileMill.data.uniq = (new Date().getTime());
      TileMill.map.reload(
          $('#map-preview'),
          TileMill.backend.servers(TileMill.mml.url()));
      $('div#header a.save').removeClass('changed');
      $(this).data('tilemill').mtime = data.mtime;
    }
  });
};

TileMill.project.status = function() {
  TileMill.backend.status(function(status) {
    if (status) {
        $('.status').removeClass('offline');
    } else {
        $('.status').text('tile server offline');
        $('.status').addClass('offline');
    }
  });
};

TileMill.project.watch = function() {
  var id = TileMill.data.id,
      queue = new TileMill.queue();
  $('#tabs a.tab').each(function() {
    TileMill.stylesheet.setCode($('#tabs a.active'), true);
    TileMill.stylesheet.mtime(
      $.url.setUrl($(this).data('tilemill').src).param('filename'),
      TileMill.project.checkStale);
  });
};

/**
 * Save a project from its current DOM state.
 */
TileMill.project.save = function() {
  // Refresh storage of active stylesheet before saving.
  TileMill.stylesheet.setCode($('#tabs a.active'), true);

  var id = TileMill.data.id,
      queue = new TileMill.queue();
  queue.add(function(id, next) {
    var mml = {
      metadata: {},
      stylesheets: [],
      layers: []
    };

    // Retrieve map preview.
    mml.metadata.mapCenter = TileMill.map.getCenter($('#map-preview'));

    $('#tabs a.tab').each(function() {
      mml.stylesheets.push(
          TileMill.backend.url($.url.setUrl($(this).data('tilemill').src)
              .param('filename')) + '&c=' + TileMill.data.uniq);
      TileMill.stylesheet.save(
          $.url.setUrl($(this).data('tilemill').src).param('filename'),
          $('input', this).val());
    });
    $('#layers ul.sidebar-content li').reverse().each(function() {
      var layer = $(this).data('tilemill');
      if (layer) {
        layer.status = !!$(this).find('input[type=checkbox]').is(':checked');
        mml.layers.push(layer);
      }
    });
    mml = TileMill.mml.generate(mml);
    TileMill.backend.post('project/' + id + '/' + id + '.mml', mml, next);
  }, [id]);
  queue.add(function() {
    TileMill.inspector.load();
    TileMill.data.uniq = (new Date().getTime());
    TileMill.map.reload(
        $('#map-preview'),
        TileMill.backend.servers(TileMill.mml.url()));
    $('div#header a.save').removeClass('changed');
  });
  queue.execute();
};

/**
 * Add a new project.
 */
TileMill.project.add = function(name) {
  $('body').append(TileMill.template('loading', {}));

  var queue = new TileMill.queue();
  queue.add(function(name, next) {
    var self = this;
    TileMill.backend.list('project', function(projects) {
      if ($.inArray(name, projects) !== -1) {
        $('body div.loading').remove();
        TileMill.message('Error', 'A project with the name ' +
            name + ' already exists. Please choose another name.',
            'error');
        self.reset();
      }
      else {
        next();
      }
    });
  }, [name]);
  queue.add(function(name, next) {
    var mss = 'project/' + name + '/' + name + '.mss';
    var data = TileMill.mss.generate({
      'Map': {
        'map-bgcolor': '#fff'
      },
      '#world': {
        'polygon-fill': '#eee',
        'line-color': '#ccc',
        'line-width': '0.5'
      }
    });
    TileMill.backend.post(mss, data, next);
  }, [name]);
  queue.add(function(name, next) {
    var mss = 'project/' + name + '/' + name + '.mss';
    var mml = 'project/' + name + '/' + name + '.mml';
    var data = TileMill.mml.generate({
      stylesheets: [TileMill.backend.url(mss)],
      layers: [{
        id: 'world',
        srs: '&srsWGS84;',
        // TODO: make configurable
        file: 'http://cascadenik-sampledata.s3.amazonaws.com/world_borders.zip',
        type: 'shape'
      }]
    });
    TileMill.backend.post(mml, data, next);
  }, [name]);
  queue.add(function(name) {
    $.bbq.pushState({ 'action': 'project', 'id': name });
  }, [name]);
  queue.execute();
};
<|endoftext|>


<commit_before>/**
 * Created by ar on 7/31/15.
 */

var dbInit=require("../config/dbInit");
var job=require("../model/JobType");
var idDM = require("./../blogic/SCTIdBulkDataManager");
var sIdDM = require("./../blogic/SchemeIdBulkDataManager");
var stateMachine=require("../model/StateMachine");
var db;
var model;

function getModel(){
    if (!model){
        dbInit.getDB(function (err, pdb, podel1) {
            if (err) {
                throw err;
            }else {

                db = pdb;
                model = podel1;
            }
        })
    }
}

getModel();

var runner = function (){
    model.bulkJob.find({status:"1"},function(err,records){
        if (records&& records.length>0){
            console.log("running job.");
            return;
        }
        model.bulkJob.find({status:0}, [ "created_at", "A" ],function(err,bulkJobRecords) {
            if (bulkJobRecords&& bulkJobRecords.length>0) {
                bulkJobRecords[0].status="1";
                bulkJobRecords[0].save(function(err){
                    if (err){
                        console.log("Error-1 in back end service:" + err);
                        return;
                    }
                    processJob(bulkJobRecords[0]);

                })

            }else{
                return;
            }
        })
    });
};

function processJob(record){
    var request=record.request;
    request.jobId=record.id;

    if (request.type==job.JOBTYPE.generateSctids) {
        if (!request.systemIds || request.systemIds.length==0){
            var arrayUuids=[];
            for (var i=0;i<request.quantity;i++){
                arrayUuids.push(guid());
            }
            request.systemIds=arrayUuids;
        }
        request.action=stateMachine.actions.generate;
        idDM.generateSctids(request, function(err){
            if (err){
                record.status="3";
                if (typeof err=="object"){
                    record.log=JSON.stringify(err);
                }else {
                    record.log = err;
                }
            }else{
                record.status="2";
            }
            record.save(function(err){
                if (err){
                    console.log("Error-2 in back end service:" + err);
                    return;
                }else{
                    console.log("End job " + record.name + " - id:" + record.id);
                }
            });
        });
    }else if (request.type==job.JOBTYPE.registerSctids){

        idDM.registerSctids(request, function(err){
            if (err){
                record.status="3";
                if (typeof err=="object"){
                    record.log=JSON.stringify(err);
                }else {
                    record.log = err;
                }
            }else{
                record.status="2";
            }
            record.save(function(err){
                if (err){
                    console.log("Error-3 in back end service:" + JSON.stringify(err));
                    return;
                }else{
                    console.log("End job " + record.name + " - id:" + record.id);
                }
            });
        });
    }else if (request.type==job.JOBTYPE.reserveSctids){
        if (!request.systemIds || request.systemIds.length==0){
            var arrayUuids=[];
            for (var i=0;i<request.quantity;i++){
                arrayUuids.push(guid());
            }
            request.systemIds=arrayUuids;
        }
        request.action=stateMachine.actions.reserve;
        idDM.generateSctids(request, function(err){
            if (err){
                record.status="3";
                if (typeof err=="object"){
                    record.log=JSON.stringify(err);
                }else {
                    record.log = err;
                }
            }else{
                record.status="2";
            }
            record.save(function(err){
                if (err){
                    console.log("Error-4 in back end service:" + err);
                    return;
                }else{
                    console.log("End job " + record.name + " - id:" + record.id);
                }
            });
        });
    }else if (request.type==job.JOBTYPE.deprecateSctids){
        request.action=stateMachine.actions.deprecate;
        idDM.updateSctids(request, function(err){
            if (err){
                record.status="3";
                if (typeof err=="object"){
                    record.log=JSON.stringify(err);
                }else {
                    record.log = err;
                }
            }else{
                record.status="2";
            }
            record.save(function(err){
                if (err){
                    console.log("Error-5 in back end service:" + err);
                    return;
                }else{
                    console.log("End job " + record.name + " - id:" + record.id);
                }
            });
        });
    }else if (request.type==job.JOBTYPE.releaseSctids){
        request.action=stateMachine.actions.release;
        idDM.updateSctids(request, function(err){
            if (err){
                record.status="3";
                if (typeof err=="object"){
                    record.log=JSON.stringify(err);
                }else {
                    record.log = err;
                }
            }else{
                record.status="2";
            }
            record.save(function(err){
                if (err){
                    console.log("Error-6 in back end service:" + err);
                    return;
                }else{
                    console.log("End job " + record.name + " - id:" + record.id);
                }
            });
        });
    }else if (request.type==job.JOBTYPE.publishSctids) {
        request.action=stateMachine.actions.publish;
        idDM.updateSctids(request, function(err){
            if (err){
                record.status="3";
                if (typeof err=="object"){
                    record.log=JSON.stringify(err);
                }else {
                    record.log = err;
                }
            }else{
                record.status="2";
            }
            record.save(function(err){
                if (err){
                    console.log("Error-7 in back end service:" + err);
                    return;
                }else{
                    console.log("End job " + record.name + " - id:" + record.id);
                }
            });
        });
    }else if (request.type==job.JOBTYPE.generateSchemeIds ) {
        if (!request.systemIds || request.systemIds.length==0){
            var arrayUuids=[];
            for (var i=0;i<request.quantity;i++){
                arrayUuids.push(guid());
            }
            request.systemIds=arrayUuids;
        }
        request.action=stateMachine.actions.generate;
        sIdDM.generateSchemeIds( request, function(err){
            if (err){
                record.status="3";
                if (typeof err=="object"){
                    record.log=JSON.stringify(err);
                }else {
                    record.log = err;
                }
            }else{
                record.status="2";
            }
            record.save(function(err){
                if (err){
                    console.log("Error-8 in back end service:" + err);
                    return;
                }else{
                    console.log("End job " + record.name + " - id:" + record.id);
                }
            });
        });
    }else if (request.type==job.JOBTYPE.registerSchemeIds){

        sIdDM.registerSchemeIds(request, function(err){
            if (err){
                record.status="3";
                if (typeof err=="object"){
                    record.log=JSON.stringify(err);
                }else {
                    record.log = err;
                }
            }else{
                record.status="2";
            }
            record.save(function(err){
                if (err){
                    console.log("Error-9 in back end service:" + JSON.stringify(err));
                    return;
                }else{
                    console.log("End job " + record.name + " - id:" + record.id);
                }
            });
        });
    }else if (request.type==job.JOBTYPE.reserveSchemeIds){
        if (!request.systemIds || request.systemIds.length==0){
            var arrayUuids=[];
            for (var i=0;i<request.quantity;i++){
                arrayUuids.push(guid());
            }
            request.systemIds=arrayUuids;
        }
        request.action=stateMachine.actions.reserve;
        sIdDM.generateSchemeIds(request, function(err){
            if (err){
                record.status="3";
                if (typeof err=="object"){
                    record.log=JSON.stringify(err);
                }else {
                    record.log = err;
                }
            }else{
                record.status="2";
            }
            record.save(function(err){
                if (err){
                    console.log("Error-10 in back end service:" + err);
                    return;
                }else{
                    console.log("End job " + record.name + " - id:" + record.id);
                }
            });
        });
    }else if (request.type==job.JOBTYPE.deprecateSchemeIds){
        request.action=stateMachine.actions.deprecate;
        sIdDM.updateSchemeIds(request, function(err){
            if (err){
                record.status="3";
                if (typeof err=="object"){
                    record.log=JSON.stringify(err);
                }else {
                    record.log = err;
                }
            }else{
                record.status="2";
            }
            record.save(function(err){
                if (err){
                    console.log("Error-11 in back end service:" + err);
                    return;
                }else{
                    console.log("End job " + record.name + " - id:" + record.id);
                }
            });
        });
    }else if (request.type==job.JOBTYPE.releaseSchemeIds){
        request.action=stateMachine.actions.release;
        sIdDM.updateSchemeIds(request, function(err){
            if (err){
                record.status="3";
                if (typeof err=="object"){
                    record.log=JSON.stringify(err);
                }else {
                    record.log = err;
                }
            }else{
                record.status="2";
            }
            record.save(function(err){
                if (err){
                    console.log("Error-12 in back end service:" + err);
                    return;
                }else{
                    console.log("End job " + record.name + " - id:" + record.id);
                }
            });
        });
    }else if (request.type==job.JOBTYPE.publishSchemeIds) {
        request.action=stateMachine.actions.publish;
        sIdDM.updateSchemeIds(request, function(err){
            if (err){
                record.status="3";
                if (typeof err=="object"){
                    record.log=JSON.stringify(err);
                }else {
                    record.log = err;
                }
            }else{
                record.status="2";
            }
            record.save(function(err){
                if (err){
                    console.log("Error-13 in back end service:" + err);
                    return;
                }else{
                    console.log("End job " + record.name + " - id:" + record.id);
                }
            });
        });
    }
}

var guid = (function() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    return function() {
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
            s4() + '-' + s4() + s4() + s4();
    };
})();

setInterval(runner,3000);

<commit_msg>test null generationData in bulk method<commit_after>/**
 * Created by ar on 7/31/15.
 */

var dbInit=require("../config/dbInit");
var job=require("../model/JobType");
var idDM = require("./../blogic/SCTIdBulkDataManager");
var sIdDM = require("./../blogic/SchemeIdBulkDataManager");
var stateMachine=require("../model/StateMachine");
var db;
var model;

function getModel(){
    if (!model){
        dbInit.getDB(function (err, pdb, podel1) {
            if (err) {
                throw err;
            }else {

                db = pdb;
                model = podel1;
            }
        })
    }
}

getModel();

var runner = function (){
    model.bulkJob.find({status:"1"},function(err,records){
        if (records&& records.length>0){
            console.log("running job.");
            return;
        }
        model.bulkJob.find({status:0}, [ "created_at", "A" ],function(err,bulkJobRecords) {
            if (bulkJobRecords&& bulkJobRecords.length>0) {
                bulkJobRecords[0].status="1";
                bulkJobRecords[0].save(function(err){
                    if (err){
                        console.log("Error-1 in back end service:" + err);
                        return;
                    }
                    processJob(bulkJobRecords[0]);

                })

            }else{
                return;
            }
        })
    });
};

function processJob(record){
    var request=record.request;

    if (!request || !request.type || request.type==null){
        record.status="3";
        record.log="Request property is null";

        record.save(function(err){
            if (err){
                console.log("Error-14 in back end service:" + err);
            }else{
                console.log("Error: Can not process the job " + record.name + " - id:" + record.id + " -" + record.log);
            }
        });
    }else {
        request.jobId = record.id;

        if (request.type == job.JOBTYPE.generateSctids) {
            if (!request.systemIds || request.systemIds.length == 0) {
                var arrayUuids = [];
                for (var i = 0; i < request.quantity; i++) {
                    arrayUuids.push(guid());
                }
                request.systemIds = arrayUuids;
            }
            request.action = stateMachine.actions.generate;
            idDM.generateSctids(request, function (err) {
                if (err) {
                    record.status = "3";
                    if (typeof err == "object") {
                        record.log = JSON.stringify(err);
                    } else {
                        record.log = err;
                    }
                } else {
                    record.status = "2";
                }
                record.save(function (err) {
                    if (err) {
                        console.log("Error-2 in back end service:" + err);
                        return;
                    } else {
                        console.log("End job " + record.name + " - id:" + record.id);
                    }
                });
            });
        } else if (request.type == job.JOBTYPE.registerSctids) {

            idDM.registerSctids(request, function (err) {
                if (err) {
                    record.status = "3";
                    if (typeof err == "object") {
                        record.log = JSON.stringify(err);
                    } else {
                        record.log = err;
                    }
                } else {
                    record.status = "2";
                }
                record.save(function (err) {
                    if (err) {
                        console.log("Error-3 in back end service:" + JSON.stringify(err));
                        return;
                    } else {
                        console.log("End job " + record.name + " - id:" + record.id);
                    }
                });
            });
        } else if (request.type == job.JOBTYPE.reserveSctids) {
            if (!request.systemIds || request.systemIds.length == 0) {
                var arrayUuids = [];
                for (var i = 0; i < request.quantity; i++) {
                    arrayUuids.push(guid());
                }
                request.systemIds = arrayUuids;
            }
            request.action = stateMachine.actions.reserve;
            idDM.generateSctids(request, function (err) {
                if (err) {
                    record.status = "3";
                    if (typeof err == "object") {
                        record.log = JSON.stringify(err);
                    } else {
                        record.log = err;
                    }
                } else {
                    record.status = "2";
                }
                record.save(function (err) {
                    if (err) {
                        console.log("Error-4 in back end service:" + err);
                        return;
                    } else {
                        console.log("End job " + record.name + " - id:" + record.id);
                    }
                });
            });
        } else if (request.type == job.JOBTYPE.deprecateSctids) {
            request.action = stateMachine.actions.deprecate;
            idDM.updateSctids(request, function (err) {
                if (err) {
                    record.status = "3";
                    if (typeof err == "object") {
                        record.log = JSON.stringify(err);
                    } else {
                        record.log = err;
                    }
                } else {
                    record.status = "2";
                }
                record.save(function (err) {
                    if (err) {
                        console.log("Error-5 in back end service:" + err);
                        return;
                    } else {
                        console.log("End job " + record.name + " - id:" + record.id);
                    }
                });
            });
        } else if (request.type == job.JOBTYPE.releaseSctids) {
            request.action = stateMachine.actions.release;
            idDM.updateSctids(request, function (err) {
                if (err) {
                    record.status = "3";
                    if (typeof err == "object") {
                        record.log = JSON.stringify(err);
                    } else {
                        record.log = err;
                    }
                } else {
                    record.status = "2";
                }
                record.save(function (err) {
                    if (err) {
                        console.log("Error-6 in back end service:" + err);
                        return;
                    } else {
                        console.log("End job " + record.name + " - id:" + record.id);
                    }
                });
            });
        } else if (request.type == job.JOBTYPE.publishSctids) {
            request.action = stateMachine.actions.publish;
            idDM.updateSctids(request, function (err) {
                if (err) {
                    record.status = "3";
                    if (typeof err == "object") {
                        record.log = JSON.stringify(err);
                    } else {
                        record.log = err;
                    }
                } else {
                    record.status = "2";
                }
                record.save(function (err) {
                    if (err) {
                        console.log("Error-7 in back end service:" + err);
                        return;
                    } else {
                        console.log("End job " + record.name + " - id:" + record.id);
                    }
                });
            });
        } else if (request.type == job.JOBTYPE.generateSchemeIds) {
            if (!request.systemIds || request.systemIds.length == 0) {
                var arrayUuids = [];
                for (var i = 0; i < request.quantity; i++) {
                    arrayUuids.push(guid());
                }
                request.systemIds = arrayUuids;
            }
            request.action = stateMachine.actions.generate;
            sIdDM.generateSchemeIds(request, function (err) {
                if (err) {
                    record.status = "3";
                    if (typeof err == "object") {
                        record.log = JSON.stringify(err);
                    } else {
                        record.log = err;
                    }
                } else {
                    record.status = "2";
                }
                record.save(function (err) {
                    if (err) {
                        console.log("Error-8 in back end service:" + err);
                        return;
                    } else {
                        console.log("End job " + record.name + " - id:" + record.id);
                    }
                });
            });
        } else if (request.type == job.JOBTYPE.registerSchemeIds) {

            sIdDM.registerSchemeIds(request, function (err) {
                if (err) {
                    record.status = "3";
                    if (typeof err == "object") {
                        record.log = JSON.stringify(err);
                    } else {
                        record.log = err;
                    }
                } else {
                    record.status = "2";
                }
                record.save(function (err) {
                    if (err) {
                        console.log("Error-9 in back end service:" + JSON.stringify(err));
                        return;
                    } else {
                        console.log("End job " + record.name + " - id:" + record.id);
                    }
                });
            });
        } else if (request.type == job.JOBTYPE.reserveSchemeIds) {
            if (!request.systemIds || request.systemIds.length == 0) {
                var arrayUuids = [];
                for (var i = 0; i < request.quantity; i++) {
                    arrayUuids.push(guid());
                }
                request.systemIds = arrayUuids;
            }
            request.action = stateMachine.actions.reserve;
            sIdDM.generateSchemeIds(request, function (err) {
                if (err) {
                    record.status = "3";
                    if (typeof err == "object") {
                        record.log = JSON.stringify(err);
                    } else {
                        record.log = err;
                    }
                } else {
                    record.status = "2";
                }
                record.save(function (err) {
                    if (err) {
                        console.log("Error-10 in back end service:" + err);
                        return;
                    } else {
                        console.log("End job " + record.name + " - id:" + record.id);
                    }
                });
            });
        } else if (request.type == job.JOBTYPE.deprecateSchemeIds) {
            request.action = stateMachine.actions.deprecate;
            sIdDM.updateSchemeIds(request, function (err) {
                if (err) {
                    record.status = "3";
                    if (typeof err == "object") {
                        record.log = JSON.stringify(err);
                    } else {
                        record.log = err;
                    }
                } else {
                    record.status = "2";
                }
                record.save(function (err) {
                    if (err) {
                        console.log("Error-11 in back end service:" + err);
                        return;
                    } else {
                        console.log("End job " + record.name + " - id:" + record.id);
                    }
                });
            });
        } else if (request.type == job.JOBTYPE.releaseSchemeIds) {
            request.action = stateMachine.actions.release;
            sIdDM.updateSchemeIds(request, function (err) {
                if (err) {
                    record.status = "3";
                    if (typeof err == "object") {
                        record.log = JSON.stringify(err);
                    } else {
                        record.log = err;
                    }
                } else {
                    record.status = "2";
                }
                record.save(function (err) {
                    if (err) {
                        console.log("Error-12 in back end service:" + err);
                        return;
                    } else {
                        console.log("End job " + record.name + " - id:" + record.id);
                    }
                });
            });
        } else if (request.type == job.JOBTYPE.publishSchemeIds) {
            request.action = stateMachine.actions.publish;
            sIdDM.updateSchemeIds(request, function (err) {
                if (err) {
                    record.status = "3";
                    if (typeof err == "object") {
                        record.log = JSON.stringify(err);
                    } else {
                        record.log = err;
                    }
                } else {
                    record.status = "2";
                }
                record.save(function (err) {
                    if (err) {
                        console.log("Error-13 in back end service:" + err);
                        return;
                    } else {
                        console.log("End job " + record.name + " - id:" + record.id);
                    }
                });
            });
        }
    }
}

var guid = (function() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    return function() {
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
            s4() + '-' + s4() + s4() + s4();
    };
})();

setInterval(runner,3000);

<|endoftext|>


<commit_before>import React, {Component} from 'react'
import { Link } from 'react-router'
import {Grid, Row, Col, Jumbotron} from 'react-bootstrap'
import logo from './logo.svg'
import './App.css'

class App extends Component {

  state = {
      politicians: [],
      parties: [],
      topics: []
  };

  load(what, url) {
      let self = this;
      fetch(url)
          .then(res => res.json())
          .then(data => {
              self.state[what] = data;
              self.setState(self.state);
          })
          .catch(e => console.log(e))
  }

  componentWillMount() {
    this.load('parties', 'https://trustfact.dilab.co/api/v1/parties');
    this.load('politicians', 'https://trustfact.dilab.co/api/v1/politicians');
    this.load('topics', 'https://raw.githubusercontent.com/codeforfrankfurt/PolBotCheck/master/web/json/topics.json');
  }

  render() {
    return (
      <Grid className="App">
        <Row>

Welcome to PolBotCheck

        </Row>
        <Row>
          <Jumbotron>

                Our goal is to show information about politicians regarding who is retweeting their Twitter tweets,
                if it is humans or bots.

                We use information from Truthy BotOrNot, a project
                from Indiana University, which calculates a probability of a Twitter account being a bot or a human.
                We check that on retweeters of a politician and calculate a score for each topic (aka hashtag) he or
                she is talking about. This helps to identify, if a tweet is really interesting to the public or if it
                is only interesting for certain bots.

                The list of politicians was loaded from Bundestwitter.

          </Jumbotron>
        </Row>
          <Row>
              <Col md={4}>

Politiker

                    {this.state.politicians.map(function(value) {
                        return
<Link to={'/politicians/' + value.screenname}>{value.name}</Link>

                    })}

              </Col>
              <Col md={4}>

Parteien

                      {this.state.parties.map(function(value) {
                          return
<Link to={'/parties/' + value.name}>{value.name} - {value.longName}</Link>
;
                      })}

              </Col>
              <Col md={4}>

Themen

                      {this.state.topics.map(function(value) {
                          return
<Link to={'/topics/' + value}>{value}</Link>
;
                      })}

              </Col>
          </Row>
      </Grid>
    );
  }
}

export default App;
<commit_msg>New API version for party list<commit_after>import React, {Component} from 'react'
import { Link } from 'react-router'
import {Grid, Row, Col, Jumbotron} from 'react-bootstrap'
import logo from './logo.svg'
import './App.css'

class App extends Component {

  state = {
      politicians: [],
      parties: [],
      topics: []
  };

  load(what, url) {
      let self = this;
      fetch(url)
          .then(res => res.json())
          .then(data => {
              self.state[what] = data;
              self.setState(self.state);
          })
          .catch(e => console.log(e))
  }

  componentWillMount() {
    this.load('parties', 'https://trustfact.dilab.co/api/v2/parties');
    this.load('politicians', 'https://trustfact.dilab.co/api/v1/politicians');
    this.load('topics', 'https://raw.githubusercontent.com/codeforfrankfurt/PolBotCheck/master/web/json/topics.json');
  }

  render() {
    return (
      <Grid className="App">
        <Row>

Welcome to PolBotCheck

        </Row>
        <Row>
          <Jumbotron>

                Our goal is to show information about politicians regarding who is retweeting their Twitter tweets,
                if it is humans or bots.

                We use information from Truthy BotOrNot, a project
                from Indiana University, which calculates a probability of a Twitter account being a bot or a human.
                We check that on retweeters of a politician and calculate a score for each topic (aka hashtag) he or
                she is talking about. This helps to identify, if a tweet is really interesting to the public or if it
                is only interesting for certain bots.

                The list of politicians was loaded from Bundestwitter.

          </Jumbotron>
        </Row>
          <Row>
              <Col md={4}>

Politiker

                    {this.state.politicians.map(function(value) {
                        return
<Link to={'/politicians/' + value.screenname}>{value.name}</Link>

                    })}

              </Col>
              <Col md={4}>

Parteien

                      {this.state.parties.map(function(value) {
                          return
<Link to={'/parties/' + value.name}>{value.name} - {value.longName}</Link>
;
                      })}

              </Col>
              <Col md={4}>

Themen

                      {this.state.topics.map(function(value) {
                          return
<Link to={'/topics/' + value}>{value}</Link>
;
                      })}

              </Col>
          </Row>
      </Grid>
    );
  }
}

export default App;
<|endoftext|>


<commit_before>"use strict";
var VScroller = {
Core: {
  animate: null,
  calibrationBoundary: 150,
  maxCalibration: 1.6,
  minCalibration: 0.5,
  // high:  60f / 1000ms :  400ms / 24f # 600 / 28
  // low:   15f /  250ms :   33ms /  2f # 200 / 6
  maxInterval: 28,
  minDelay: 600,
  performScroll: function(el, di, amount) {
    var before;
    if (di) {
      if (el) {
        before = el.scrollTop;
        el.scrollTop += amount;
        return el.scrollTop !== before;
      } else {
        before = window.scrollY;
        window.scrollBy(0, amount);
        return window.scrollY !== before;
      }
    } else if (el) {
      before = el.scrollLeft;
      el.scrollLeft += amount;
      return el.scrollLeft !== before;
    } else {
      before = window.scrollX;
      window.scrollBy(amount, 0);
      return window.scrollX !== before;
    }
  },
  scroll: function(element, di, amount) {
    if (!amount) { return; }
    if (!VSettings.cache.smoothScroll) {
      this.performScroll(element, di, amount);
      VDom.isVisibile(VScroller.current) || (VScroller.current = element);
      return;
    }
    this.animate(amount, di, element);
  }
},

  current: null,
  keyIsDown: 0,
  Properties: [{
    axisName: "scrollLeft",
    max: "scrollWidth",
    viewSize: "clientWidth"
  }, {
    axisName: "scrollTop",
    max: "scrollHeight",
    viewSize: "clientHeight"
  }],
  scrollBy: function(di, amount, factor) {
    if (VHints.tryNestedFrame("VScroller.scrollBy", arguments)) { return; }
    var element = this.findScrollable(this.getActivatedElement(), di, amount);
    amount = !factor ? this.adjustAmount(di, amount, element)
      : factor === 1 ? (amount > 0 ? Math.ceil : Math.floor)(amount)
      : amount * this.getDimension(element, di, factor);
    this.Core.scroll(element, di, amount);
  },
  scrollTo: function(di, amount, fromMax) {
    if (VHints.tryNestedFrame("VScroller.scrollTo", arguments)) { return; }
    var element = this.findScrollable(this.getActivatedElement(), di, fromMax ? 1 : -1);
    amount = this.adjustAmount(di, amount, element);
    amount = fromMax ? this.getDimension(element, di, "max") - amount : amount;
    amount -= element ? element[this.Properties[di].axisName] : di ? window.scrollY : window.scrollX;
    this.Core.scroll(element, di, amount);
  },
  adjustAmount: function(di, amount, element) {
    amount *= VSettings.cache.scrollStepSize;
    return amount && !di && element && element.scrollWidth <= element.scrollHeight * 2
      ? Math.ceil(amount * 0.6) : amount;
  },
  findScrollable: function(element, di, amount) {
    amount = amount > 0 ? 1 : -1;
    while (element !== document.body && !(this.scrollDo(element, di, amount) && this.shouldScroll(element, di))) {
      element = element.parentElement || (element.parentNode && element.parentNode.host) || document.body;
    }
    return element === document.body ? this.selectFirst(element) : element;
  },
  getActivatedElement: function() {
    var element = this.current;
    if (element) { return element; }
    element = document.body;
    return this.current = element && (this.selectFirst(element) || element);
  },
  getDimension: function(el, di, name) {
    return !el || name !== "viewSize" || el !== document.body
        ? (el || document.documentElement)[this.Properties[di][name]]
      : di ? window.innerHeight : window.innerWidth;
  },
  scrollDo: function(element, di, amount) {
    return this.Core.performScroll(element, di, amount) && this.Core.performScroll(element, di, -amount);
  },
  selectFirst: function(element) {
    if (this.scrollDo(element, 1, 1) || this.scrollDo(element, 1, -1)) {
      return element;
    }
    VDom.prepareCrop();
    var children = [], rect, _ref = element.children, _len = _ref.length;
    while (0 < _len--) {
      element = _ref[_len];
      if (rect = VDom.getVisibleClientRect(element)) {
        children.push([(rect[2] - rect[0]) * (rect[3] - rect[1]), element]);
      }
    }
    if (_len = children.length) {
      children.sort(this.sortBy0);
      while (0 < _len--) {
        if (element = this.selectFirst(children[_len][1])) {
          return element;
        }
      }
    }
    return null;
  },
  scrollIntoView: function(el) {
    this.getActivatedElement();
    var rect = el.getClientRects()[0], amount, height, width, hasY, oldSmooth;
    if (!rect) { return; }
    height = window.innerHeight, width = window.innerWidth;
    amount = rect.bottom < 0 ? rect.bottom - Math.min(rect.height, height)
      : height < rect.top ? rect.top + Math.min(rect.height, height, 0) : 0;
    if (amount) {
      this.Core.scroll(this.findScrollable(el, 1, amount), 1, amount);
      VScroller.keyIsDown = 0;
    }
    hasY = amount;
    amount = rect.right < 0 ? rect.right - Math.min(rect.width, width)
      : width < rect.left ? rect.left + Math.min(rect.width - width, 0) : 0;
    if (!amount) { return; }
    oldSmooth = VSettings.cache.smoothScroll;
    VSettings.cache.smoothScroll = !hasY;
    el = this.findScrollable(el, 0, amount);
    this.Core.scroll(el, 0, amount);
    VSettings.cache.smoothScroll = oldSmooth;
    VScroller.keyIsDown = 0;
  },
  shouldScroll: function(element, di) {
    var st = window.getComputedStyle(element);
    return VDom.isStyleVisible(st) && (di ? st.overflowY : st.overflowX) !== "hidden";
  },
  isScrollable: function(el, di) {
    return this.scrollDo(el, di, (di ? el.scrollTop : el.scrollLeft) > 0 ? -1 : 1) && this.shouldScroll(el, di);
  },
  sortBy0: function(a, b) {
    return a[0] - b[0];
  }
};

VScroller.Core.animate = function () {
  var amount = 0, calibration = 1.0, di = 0, duration = 0, element = null, //
  sign = 0, timestamp = -1, totalDelta = 0, totalElapsed = 0.0, //
  animate = function(newTimestamp) {
    var int1 = timestamp, elapsed, continuous, _this;
    timestamp = newTimestamp;
    if (int1 === -1) {
      requestAnimationFrame(animate);
      return;
    }
    elapsed = newTimestamp - int1;
    int1 = (totalElapsed += elapsed);
    _this = VScroller.Core;
    if (continuous = VScroller.keyIsDown > 0) {
      if (int1 >= 75) {
        if (int1 > _this.minDelay) { --VScroller.keyIsDown; }
        int1 = calibration;
        if (_this.minCalibration <= int1 && int1 <= _this.maxCalibration) {
          int1 = _this.calibrationBoundary / amount / int1;
          calibration *= (int1 > 1.05) ? 1.05 : (int1 < 0.95) ? 0.95 : 1.0;
        }
      }
    }
    int1 = Math.ceil(amount * (elapsed / duration) * calibration);
    int1 = continuous ? int1 : Math.max(0, Math.min(int1, amount - totalDelta));
    if (int1 && _this.performScroll(element, di, sign * int1)) {
      totalDelta += int1;
      requestAnimationFrame(animate);
      return;
    }
    if (VScroller.current !== element) {
      VDom.isVisibile(VScroller.current) || (VScroller.current = element);
    }
    element = null;
  };
  this.animate = function(newAmount, newDi, newEl) {
    amount = Math.abs(newAmount); calibration = 1.0; di = newDi;
    duration = Math.max(100, 20 * Math.log(amount)); element = newEl;
    sign = newAmount === 0 ? 0 : newAmount < 0 ? -1 : 1;
    timestamp = -1; totalDelta = 0; totalElapsed = 0.0;
    var keyboard = VSettings.cache.keyboard;
    this.maxInterval = Math.round(keyboard[1] / 16.67) + 4;
    this.minDelay = (((keyboard[0] - keyboard[1]) / 30) | 0) * 30;
    VScroller.keyIsDown = this.maxInterval;
    requestAnimationFrame(animate);
  };
  this.animate.apply(this, arguments);
};
<commit_msg>Revert "merge from philc: Relocate first scrollable element."<commit_after>"use strict";
var VScroller = {
Core: {
  animate: null,
  calibrationBoundary: 150,
  maxCalibration: 1.6,
  minCalibration: 0.5,
  // high:  60f / 1000ms :  400ms / 24f # 600 / 28
  // low:   15f /  250ms :   33ms /  2f # 200 / 6
  maxInterval: 28,
  minDelay: 600,
  performScroll: function(el, di, amount) {
    var before;
    if (di) {
      if (el) {
        before = el.scrollTop;
        el.scrollTop += amount;
        return el.scrollTop !== before;
      } else {
        before = window.scrollY;
        window.scrollBy(0, amount);
        return window.scrollY !== before;
      }
    } else if (el) {
      before = el.scrollLeft;
      el.scrollLeft += amount;
      return el.scrollLeft !== before;
    } else {
      before = window.scrollX;
      window.scrollBy(amount, 0);
      return window.scrollX !== before;
    }
  },
  scroll: function(element, di, amount) {
    if (!amount) { return; }
    if (!VSettings.cache.smoothScroll) {
      this.performScroll(element, di, amount);
      VDom.isVisibile(VScroller.current) || (VScroller.current = element);
      return;
    }
    this.animate(amount, di, element);
  }
},

  current: null,
  keyIsDown: 0,
  Properties: [{
    axisName: "scrollLeft",
    max: "scrollWidth",
    viewSize: "clientWidth"
  }, {
    axisName: "scrollTop",
    max: "scrollHeight",
    viewSize: "clientHeight"
  }],
  scrollBy: function(di, amount, factor) {
    if (VHints.tryNestedFrame("VScroller.scrollBy", arguments)) { return; }
    var element = this.findScrollable(this.getActivatedElement(), di, amount);
    amount = !factor ? this.adjustAmount(di, amount, element)
      : factor === 1 ? (amount > 0 ? Math.ceil : Math.floor)(amount)
      : amount * this.getDimension(element, di, factor);
    this.Core.scroll(element, di, amount);
  },
  scrollTo: function(di, amount, fromMax) {
    if (VHints.tryNestedFrame("VScroller.scrollTo", arguments)) { return; }
    var element = this.findScrollable(this.getActivatedElement(), di, fromMax ? 1 : -1);
    amount = this.adjustAmount(di, amount, element);
    amount = fromMax ? this.getDimension(element, di, "max") - amount : amount;
    amount -= element ? element[this.Properties[di].axisName] : di ? window.scrollY : window.scrollX;
    this.Core.scroll(element, di, amount);
  },
  adjustAmount: function(di, amount, element) {
    amount *= VSettings.cache.scrollStepSize;
    return amount && !di && element && element.scrollWidth <= element.scrollHeight * 2
      ? Math.ceil(amount * 0.6) : amount;
  },
  findScrollable: function(element, di, amount) {
    amount = amount > 0 ? 1 : -1;
    while (element !== document.body && !(this.scrollDo(element, di, amount) && this.shouldScroll(element, di))) {
      element = element.parentElement || (element.parentNode && element.parentNode.host) || document.body;
    }
    return element;
  },
  getActivatedElement: function() {
    var element = this.current;
    if (element) { return element; }
    element = document.body;
    return this.current = element && (this.selectFirst(element) || element);
  },
  getDimension: function(el, di, name) {
    return !el || name !== "viewSize" || el !== document.body
        ? (el || document.documentElement)[this.Properties[di][name]]
      : di ? window.innerHeight : window.innerWidth;
  },
  scrollDo: function(element, di, amount) {
    return this.Core.performScroll(element, di, amount) && this.Core.performScroll(element, di, -amount);
  },
  selectFirst: function(element) {
    if (this.scrollDo(element, 1, 1) || this.scrollDo(element, 1, -1)) {
      return element;
    }
    VDom.prepareCrop();
    var children = [], rect, _ref = element.children, _len = _ref.length;
    while (0 < _len--) {
      element = _ref[_len];
      if (rect = VDom.getVisibleClientRect(element)) {
        children.push([(rect[2] - rect[0]) * (rect[3] - rect[1]), element]);
      }
    }
    if (_len = children.length) {
      children.sort(this.sortBy0);
      while (0 < _len--) {
        if (element = this.selectFirst(children[_len][1])) {
          return element;
        }
      }
    }
    return null;
  },
  scrollIntoView: function(el) {
    this.getActivatedElement();
    var rect = el.getClientRects()[0], amount, height, width, hasY, oldSmooth;
    if (!rect) { return; }
    height = window.innerHeight, width = window.innerWidth;
    amount = rect.bottom < 0 ? rect.bottom - Math.min(rect.height, height)
      : height < rect.top ? rect.top + Math.min(rect.height, height, 0) : 0;
    if (amount) {
      this.Core.scroll(this.findScrollable(el, 1, amount), 1, amount);
      VScroller.keyIsDown = 0;
    }
    hasY = amount;
    amount = rect.right < 0 ? rect.right - Math.min(rect.width, width)
      : width < rect.left ? rect.left + Math.min(rect.width - width, 0) : 0;
    if (!amount) { return; }
    oldSmooth = VSettings.cache.smoothScroll;
    VSettings.cache.smoothScroll = !hasY;
    el = this.findScrollable(el, 0, amount);
    this.Core.scroll(el, 0, amount);
    VSettings.cache.smoothScroll = oldSmooth;
    VScroller.keyIsDown = 0;
  },
  shouldScroll: function(element, di) {
    var st = window.getComputedStyle(element);
    return VDom.isStyleVisible(st) && (di ? st.overflowY : st.overflowX) !== "hidden";
  },
  isScrollable: function(el, di) {
    return this.scrollDo(el, di, (di ? el.scrollTop : el.scrollLeft) > 0 ? -1 : 1) && this.shouldScroll(el, di);
  },
  sortBy0: function(a, b) {
    return a[0] - b[0];
  }
};

VScroller.Core.animate = function () {
  var amount = 0, calibration = 1.0, di = 0, duration = 0, element = null, //
  sign = 0, timestamp = -1, totalDelta = 0, totalElapsed = 0.0, //
  animate = function(newTimestamp) {
    var int1 = timestamp, elapsed, continuous, _this;
    timestamp = newTimestamp;
    if (int1 === -1) {
      requestAnimationFrame(animate);
      return;
    }
    elapsed = newTimestamp - int1;
    int1 = (totalElapsed += elapsed);
    _this = VScroller.Core;
    if (continuous = VScroller.keyIsDown > 0) {
      if (int1 >= 75) {
        if (int1 > _this.minDelay) { --VScroller.keyIsDown; }
        int1 = calibration;
        if (_this.minCalibration <= int1 && int1 <= _this.maxCalibration) {
          int1 = _this.calibrationBoundary / amount / int1;
          calibration *= (int1 > 1.05) ? 1.05 : (int1 < 0.95) ? 0.95 : 1.0;
        }
      }
    }
    int1 = Math.ceil(amount * (elapsed / duration) * calibration);
    int1 = continuous ? int1 : Math.max(0, Math.min(int1, amount - totalDelta));
    if (int1 && _this.performScroll(element, di, sign * int1)) {
      totalDelta += int1;
      requestAnimationFrame(animate);
      return;
    }
    if (VScroller.current !== element) {
      VDom.isVisibile(VScroller.current) || (VScroller.current = element);
    }
    element = null;
  };
  this.animate = function(newAmount, newDi, newEl) {
    amount = Math.abs(newAmount); calibration = 1.0; di = newDi;
    duration = Math.max(100, 20 * Math.log(amount)); element = newEl;
    sign = newAmount === 0 ? 0 : newAmount < 0 ? -1 : 1;
    timestamp = -1; totalDelta = 0; totalElapsed = 0.0;
    var keyboard = VSettings.cache.keyboard;
    this.maxInterval = Math.round(keyboard[1] / 16.67) + 4;
    this.minDelay = (((keyboard[0] - keyboard[1]) / 30) | 0) * 30;
    VScroller.keyIsDown = this.maxInterval;
    requestAnimationFrame(animate);
  };
  this.animate.apply(this, arguments);
};
<|endoftext|>