<commit_before><commit_msg>show which module is cloned next, with module url<commit_after><|endoftext|>


<commit_before><commit_msg>fix(cloudcmd) prefix<commit_after><|endoftext|>


<commit_before><commit_msg>Added comment on CubeHash<commit_after><|endoftext|>


<commit_before><commit_msg>Due to Node bug (#1877) timeout configured for Infinity blocked propagation of other event loops, it's same for all timeout values larger than about 1e19 milliseconds. 1e13 milliseconds seems as safe fix - it spans over 325 years ;-)<commit_after><|endoftext|>


<commit_before><commit_msg>Logic cleanup<commit_after><|endoftext|>


<commit_before><commit_msg>:new: Respect `itemsToShowInHistory` config<commit_after><|endoftext|>


<commit_before><commit_msg>[api] Stop application properly<commit_after><|endoftext|>


<commit_before><commit_msg>Fix error on Linux if no kernel specs can be found<commit_after><|endoftext|>


<commit_before><commit_msg>CF-40: Updating to tabs to 4 spaces<commit_after><|endoftext|>


<commit_before><commit_msg>Added new Midi over Websockets client class.<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed typo<commit_after><|endoftext|>


<commit_before><commit_msg>fixed linting warnings, added comments, added impl<commit_after><|endoftext|>


<commit_before>$( document ).ready(function() {

    var statsEnabled = isDataPublishingEnabled();
    var table = null;

    var selectedOptionKey = $("#alertSelected option:selected" ).val();
    var tableName = null;

    changeActiveTableName();

    if(statsEnabled){
        drawTable();
    } else {
        $('.content-data').empty();
        $('.content-data').append('
' + i18n.t("Stats are disabled.") + '
');
    }

    $("#alertSelected").change( function() {
        selectedOptionKey = $("#alertSelected option:selected" ).val();
        changeActiveTableName();
        if(statsEnabled){
            table.ajax.reload(null, true);
        } else{
            $('.content-data').empty();
            $('.content-data').append('
' + i18n.t("Stats are disabled.") + '
');
        }
    });

    $('#alertHistoryTable_filter input').unbind();
    $('#alertHistoryTable_filter input').bind('keyup', function(e) {
        if(e.keyCode == 13) {
            table.search( this.value ).draw();
        }
    });

    function changeActiveTableName() {
        if(selectedOptionKey == 1){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALLAPIMALERTSSTREAM"
        } else if(selectedOptionKey== 2){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALERT_UNUSUALIPACCESS";
        } else if(selectedOptionKey== 3){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ABNORMALREQUESTSPERMINALERTSTREAM";
        } else if(selectedOptionKey== 4){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ABNORMALRESPONSETIMEALERTSTREAM";
        } else if(selectedOptionKey== 5){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALERT_ABNORMALTIERUSAGEALERT";
        } else if(selectedOptionKey== 6){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALERT_ABNORMALTOKENREFRESH";
        } else if(selectedOptionKey== 7){
            tableName = "ORG_WSO2_ANALYTICS_APIM_TIERLIMITHITTINGALERT";
        } else if(selectedOptionKey== 8){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ABNORMALBACKENDTIMEALERTSTREAM";
        } else if(selectedOptionKey== 9){
            tableName = "ORG_WSO2_ANALYTICS_APIM_APIHEALTHMONITORALERTSTREAM";
        } else if(selectedOptionKey== 10){
            tableName = "ORG_WSO2_ANALYTICS_APIM_REQUESTPATTERNCHANGEDSTREAM";
        }

    }

    function isDataPublishingEnabled() {
        var isStatsEnabled;

        jagg.syncPost("/site/blocks/alert-table/ajax/alert-table.jag", { action: "isDataPublishingEnabled"},
            function (json) {
                if (!json.error) {
                    isStatsEnabled = json.usage;
                } else {
                    if (json.message == "AuthenticateError") {
                        jagg.showLogin();
                    } else {
                        jagg.message({content: json.message, type: "error"});
                    }
                }
            }, "json");

        return isStatsEnabled;
    }

    function changeSelectedAlertType(alertType) {
        if(alertType != null){
            if(alertType == "Unseen Source IP Access"){
                $('#alertSelected').val(2).change();
            } else if(alertType == "Abnormal Request Count"){
                $('#alertSelected').val(3).change();
            } else if(alertType == "Abnormal Response Time"){
                $('#alertSelected').val(4).change();
            } else if(alertType == "Abnormal API Usage"){
                $('#alertSelected').val(5).change();
            } else if(alertType == "Abnormal Renewal of Access Tokens"){
                $('#alertSelected').val(6).change();
            } else if(alertType == "Tier Crossing"){
                $('#alertSelected').val(7).change();
            } else if(alertType == "Abnormal Backend Time"){
                $('#alertSelected').val(8).change();
            } else if(alertType == "Health Availability"){
                $('#alertSelected').val(9).change();
            } else if(alertType == "Abnormal Resource Access"){
                $('#alertSelected').val(10).change();
            }
        }
    }

    function drawTable() {

        table =$('#alertHistoryTable').datatables_extended({
            "order": [[ 0, "desc" ]],
            //"processing": true,
            "serverSide": true,
            "columns" : [
                { title: i18n.t("Alert Timestamp") },
                { title: i18n.t("Type"), "orderable": false },
                { title: i18n.t("Message") , "orderable": false ,"render":function(data){
                    var userId = data['userId'];
                    var applicationName = data['applicationName'];
                    var applicationOwner = data['applicationOwner'];
                    var applicationId = data['applicationId'];
                    var api_version = data['api_version'];
                    var ip = data['ip'];
                    var api = data['api'];
                    var apiPublisher = data['apiPublisher'];
                    var resourceTemplate = data['resourceTemplate'];
                    var method = data['method'];
                    var backendTime = data['backendTime'];
                    var requestPerMin = data['requestPerMin'];
                    var reason = data['reason'];
                    var scope = data['scope'];
                    var consumerKey = data['consumerKey'];
                    var subscriber = data['subscriber'];

                    var fullMessage = "";;

                    if (userId != null) {
                        fullMessage = '' + i18n.t("User ID") + ''+userId+'
';
                    }
                    if (applicationName != null) {
                        fullMessage = fullMessage + '' + i18n.t("Application Name") + ''+applicationName+'
';
                    }
                    if (applicationOwner != null) {
                        fullMessage = fullMessage + '' + i18n.t("Application Owner") + ''+applicationOwner+'
';
                    }
                    if (applicationId != null) {
                        fullMessage = fullMessage + '' + i18n.t("Application ID") + ''+applicationId+'
';
                    }
                    if (api_version != null) {
                        fullMessage = fullMessage + '' + i18n.t("API Version") + ''+api_version+'
';
                    }
                    if (ip != null) {
                        fullMessage = fullMessage + '' + i18n.t("IP") + ''+ip+'
';
                    }
                    if (api != null) {
                        fullMessage = fullMessage + '' + i18n.t("API") + ''+api+'
';
                    }
                    if (apiPublisher != null) {
                        fullMessage = fullMessage + '' + i18n.t("API Publisher") + ''+apiPublisher+'
';
                    }
                    if (resourceTemplate != null) {
                        fullMessage = fullMessage + '' + i18n.t("Resource Template") + ''+resourceTemplate+'
';
                    }
                    if (method != null) {
                        fullMessage = fullMessage + '' + i18n.t("Method") + ''+method+'
';
                    }
                    if (backendTime != null) {
                        fullMessage = fullMessage + '' + i18n.t("Backend Time") + ''+backendTime+'
';
                    }
                    if (requestPerMin != null) {
                        fullMessage = fullMessage + '' + i18n.t("Requests Per-Min") + ''+requestPerMin+'
';
                    }
                    if (reason != null) {
                        fullMessage = fullMessage + '' + i18n.t("Reason") + ''+reason+'
';
                    }
                    if (scope != null) {
                        fullMessage = fullMessage + '' + i18n.t("Scope") + ''+scope+'
';
                    }
                    if (consumerKey != null) {
                        fullMessage = fullMessage + '' + i18n.t("Consumer Key") + ''+consumerKey+'
';
                    }
                    if (subscriber != null) {
                        fullMessage = fullMessage + '' + i18n.t("API Subscriber") + ''+subscriber+'
';
                    }

                    fullMessage = fullMessage + data['msg'];
                    return fullMessage;
                }
                },
                {title: i18n.t("Severity"), "render": function(data){
                    var severityLabel;
                    if(data == 1) {
                        severityLabel = '' + i18n.t("severe") + '';
                    } else if (data == 2) {
                        severityLabel = '' + i18n.t("moderate") + '';
                    } else if (data == 3){
                        severityLabel = '' + i18n.t("mild") + '';
                    } else {
                        severityLabel = '' + i18n.t("mild") + '';
                    }
                    return severityLabel;
                }
                }
            ],
            ajax: {
                "url" : "site/blocks/alert-table/ajax/alert-table.jag",
                "type": "POST",
                "data" : function (d) {
                    d.action = "getDataFromTable";
                    d.tableName = tableName;
                    d.searchQuery = null;
                    d.entriesPerPage = $("#alertHistoryTable_length option:selected" ).val();
                },
                error:function(xhr,status,error){
                    console.log('Error while trying to connect to the DAS endpoint');
                }
            },
            "drawCallback": function(){
                $('.alertTypeLink').click(function(){
                    changeSelectedAlertType(this.text);
                });

            }
        });

    }

});
<commit_msg>Fix https://wso2.org/jira/browse/APIMANAGER-5053<commit_after>$( document ).ready(function() {

    var statsEnabled = isDataPublishingEnabled();
    var table = null;

    var selectedOptionKey = $("#alertSelected option:selected" ).val();
    var tableName = null;

    changeActiveTableName();

    if(statsEnabled){
        drawTable();
    } else {
        $('.content-data').empty();
        $('.content-data').append('
' + i18n.t("Stats are disabled.") + '
');
    }

    $("#alertSelected").change( function() {
        selectedOptionKey = $("#alertSelected option:selected" ).val();
        changeActiveTableName();
        if(statsEnabled){
            table.ajax.reload(null, true);
        } else{
            $('.content-data').empty();
            $('.content-data').append('
' + i18n.t("Stats are disabled.") + '
');
        }
    });

    $('#alertHistoryTable_filter input').unbind();
    $('#alertHistoryTable_filter input').bind('keyup', function(e) {
        if(e.keyCode == 13) {
            table.search( this.value ).draw();
        }
    });

    function changeActiveTableName() {
        if(selectedOptionKey == 1){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALLAPIMALERTSSTREAM"
        } else if(selectedOptionKey== 2){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALERT_UNUSUALIPACCESS";
        } else if(selectedOptionKey== 3){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ABNORMALREQUESTSPERMINALERTSTREAM";
        } else if(selectedOptionKey== 4){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ABNORMALRESPONSETIMEALERTSTREAM";
        } else if(selectedOptionKey== 5){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALERT_ABNORMALTIERUSAGEALERT";
        } else if(selectedOptionKey== 6){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ALERT_ABNORMALTOKENREFRESH";
        } else if(selectedOptionKey== 7){
            tableName = "ORG_WSO2_ANALYTICS_APIM_TIERLIMITHITTINGALERT";
        } else if(selectedOptionKey== 8){
            tableName = "ORG_WSO2_ANALYTICS_APIM_ABNORMALBACKENDTIMEALERTSTREAM";
        } else if(selectedOptionKey== 9){
            tableName = "ORG_WSO2_ANALYTICS_APIM_APIHEALTHMONITORALERTSTREAM";
        } else if(selectedOptionKey== 10){
            tableName = "ORG_WSO2_ANALYTICS_APIM_REQUESTPATTERNCHANGEDSTREAM";
        }

    }

    function isDataPublishingEnabled() {
        var isStatsEnabled;

        jagg.syncPost("/site/blocks/alert-table/ajax/alert-table.jag", { action: "isDataPublishingEnabled"},
            function (json) {
                if (!json.error) {
                    isStatsEnabled = json.usage;
                } else {
                    if (json.message == "AuthenticateError") {
                        jagg.showLogin();
                    } else {
                        jagg.message({content: json.message, type: "error"});
                    }
                }
            }, "json");

        return isStatsEnabled;
    }

    function changeSelectedAlertType(alertType) {
        if(alertType != null){
            if(alertType == "Unseen Source IP Access"){
                $('#alertSelected').val(2).change();
            } else if(alertType == "Abnormal Request Count"){
                $('#alertSelected').val(3).change();
            } else if(alertType == "Abnormal Response Time"){
                $('#alertSelected').val(4).change();
            } else if(alertType == "Abnormal API Usage"){
                $('#alertSelected').val(5).change();
            } else if(alertType == "Abnormal Renewal of Access Tokens"){
                $('#alertSelected').val(6).change();
            } else if(alertType == "Tier Crossing"){
                $('#alertSelected').val(7).change();
            } else if(alertType == "Abnormal Backend Time"){
                $('#alertSelected').val(8).change();
            } else if(alertType == "Health Availability"){
                $('#alertSelected').val(9).change();
            } else if(alertType == "Abnormal Resource Access"){
                $('#alertSelected').val(10).change();
            }
        }
    }

    function drawTable() {

        table =$('#alertHistoryTable').datatables_extended({
            "order": [[ 0, "desc" ]],
            //"processing": true,
            "serverSide": true,
            "columns" : [
                { title: i18n.t("Alert Timestamp") },
                { title: i18n.t("Type"), "orderable": false },
                { title: i18n.t("Message") , "orderable": false ,"render":function(data){
                    var userId = data['userId'];
                    var applicationName = data['applicationName'];
                    var applicationOwner = data['applicationOwner'];
                    var applicationId = data['applicationId'];
                    var api_version = data['api_version'];
                    var ip = data['ip'];
                    var api = data['api'];
                    var apiPublisher = data['apiPublisher'];
                    var resourceTemplate = data['resourceTemplate'];
                    var method = data['method'];
                    var backendTime = data['backendTime'];
                    var requestPerMin = data['requestPerMin'];
                    var reason = data['reason'];
                    var scope = data['scope'];
                    var consumerKey = data['consumerKey'];
                    var subscriber = data['subscriber'];

                    var fullMessage = "";;

                    if (userId != null) {
                        fullMessage = '' + i18n.t("User ID") + ''+userId+'
';
                    }
                    if (applicationName != null) {
                        fullMessage = fullMessage + '' + i18n.t("Application Name") + ''+applicationName+'
';
                    }
                    if (applicationOwner != null) {
                        fullMessage = fullMessage + '' + i18n.t("Application Owner") + ''+applicationOwner+'
';
                    }
                    if (applicationId != null) {
                        fullMessage = fullMessage + '' + i18n.t("Application ID") + ''+applicationId+'
';
                    }
                    if (api_version != null) {
                        fullMessage = fullMessage + '' + i18n.t("API Version") + ''+api_version+'
';
                    }
                    if (ip != null) {
                        fullMessage = fullMessage + '' + i18n.t("IP") + ''+ip+'
';
                    }
                    if (api != null) {
                        fullMessage = fullMessage + '' + i18n.t("API") + ''+api+'
';
                    }
                    if (apiPublisher != null) {
                        fullMessage = fullMessage + '' + i18n.t("API Publisher") + ''+apiPublisher+'
';
                    }
                    if (resourceTemplate != null) {
                        fullMessage = fullMessage + '' + i18n.t("Resource Template") + ''+resourceTemplate+'
';
                    }
                    if (method != null) {
                        fullMessage = fullMessage + '' + i18n.t("Method") + ''+method+'
';
                    }
                    if (backendTime != null) {
                        fullMessage = fullMessage + '' + i18n.t("Backend Time") + ''+backendTime+'msgi
';
                    }
                    if (requestPerMin != null) {
                        fullMessage = fullMessage + '' + i18n.t("Requests Per-Min") + ''+requestPerMin+'
';
                    }
                    if (reason != null) {
                        fullMessage = fullMessage + '' + i18n.t("Reason") + ''+reason+'
';
                    }
                    if (scope != null) {
                        fullMessage = fullMessage + '' + i18n.t("Scope") + ''+scope+'
';
                    }
                    if (consumerKey != null) {
                        fullMessage = fullMessage + '' + i18n.t("Consumer Key") + ''+consumerKey+'
';
                    }
                    if (subscriber != null) {
                        fullMessage = fullMessage + '' + i18n.t("API Subscriber") + ''+subscriber+'
';
                    }

                    fullMessage = fullMessage + data['msg'];
                    return fullMessage;
                }
                },
                {title: i18n.t("Severity"), "render": function(data){
                    var severityLabel;
                    if(data == 1) {
                        severityLabel = '' + i18n.t("severe") + '';
                    } else if (data == 2) {
                        severityLabel = '' + i18n.t("moderate") + '';
                    } else if (data == 3){
                        severityLabel = '' + i18n.t("mild") + '';
                    } else {
                        severityLabel = '' + i18n.t("mild") + '';
                    }
                    return severityLabel;
                }
                }
            ],
            ajax: {
                "url" : "site/blocks/alert-table/ajax/alert-table.jag",
                "type": "POST",
                "data" : function (d) {
                    d.action = "getDataFromTable";
                    d.tableName = tableName;
                    d.searchQuery = null;
                    d.entriesPerPage = $("#alertHistoryTable_length option:selected" ).val();
                },
                error:function(xhr,status,error){
                    console.log('Error while trying to connect to the DAS endpoint');
                }
            },
            "drawCallback": function(){
                $('.alertTypeLink').click(function(){
                    changeSelectedAlertType(this.text);
                });

            }
        });

    }

});
<|endoftext|>


<commit_before>// A rudimentary force layout using Gauss-Seidel.
d3.layout.force = function() {
  var force = {},
      event = d3.dispatch("start", "tick", "end"),
      size = [1, 1],
      drag,
      alpha,
      friction = .9,
      linkDistance = d3_layout_forceLinkDistance,
      linkStrength = d3_layout_forceLinkStrength,
      charge = -30,
      gravity = .1,
      theta = .8,
      interval,
      nodes = [],
      links = [],
      distances,
      strengths,
      charges;

  function repulse(node) {
    return function(quad, x1, y1, x2, y2) {
      if (quad.point !== node) {
        var dx = quad.cx - node.x,
            dy = quad.cy - node.y,
            dn = 1 / Math.sqrt(dx * dx + dy * dy);

        /* Barnes-Hut criterion. */
        if ((x2 - x1) * dn < theta) {
          var k = quad.charge * dn * dn;
          node.px -= dx * k;
          node.py -= dy * k;
          return true;
        }

        if (quad.point && isFinite(dn)) {
          var k = quad.pointCharge * dn * dn;
          node.px -= dx * k;
          node.py -= dy * k;
        }
      }
      return !quad.charge;
    };
  }

  force.tick = function() {
    // simulated annealing, basically
    if ((alpha *= .99) < .005) {
      event.end({type: "end", alpha: alpha = 0});
      return true;
    }

    var n = nodes.length,
        m = links.length,
        q,
        i, // current index
        o, // current object
        s, // current source
        t, // current target
        l, // current distance
        k, // current force
        x, // x-distance
        y; // y-distance

    // gauss-seidel relaxation for links
    for (i = 0; i < m; ++i) {
      o = links[i];
      s = o.source;
      t = o.target;
      x = t.x - s.x;
      y = t.y - s.y;
      if (l = (x * x + y * y)) {
        l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l;
        x *= l;
        y *= l;
        t.x -= x * (k = s.weight / (t.weight + s.weight));
        t.y -= y * k;
        s.x += x * (k = 1 - k);
        s.y += y * k;
      }
    }

    // apply gravity forces
    if (k = alpha * gravity) {
      x = size[0] / 2;
      y = size[1] / 2;
      i = -1; if (k) while (++i < n) {
        o = nodes[i];
        o.x += (x - o.x) * k;
        o.y += (y - o.y) * k;
      }
    }

    // compute quadtree center of mass and apply charge forces
    if (charge) {
      d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);
      i = -1; while (++i < n) {
        if (!(o = nodes[i]).fixed) {
          q.visit(repulse(o));
        }
      }
    }

    // position verlet integration
    i = -1; while (++i < n) {
      o = nodes[i];
      if (o.fixed) {
        o.x = o.px;
        o.y = o.py;
      } else {
        o.x -= (o.px - (o.px = o.x)) * friction;
        o.y -= (o.py - (o.py = o.y)) * friction;
      }
    }

    event.tick({type: "tick", alpha: alpha});
  };

  force.nodes = function(x) {
    if (!arguments.length) return nodes;
    nodes = x;
    return force;
  };

  force.links = function(x) {
    if (!arguments.length) return links;
    links = x;
    return force;
  };

  force.size = function(x) {
    if (!arguments.length) return size;
    size = x;
    return force;
  };

  force.linkDistance = function(x) {
    if (!arguments.length) return linkDistance;
    linkDistance = d3_functor(x);
    return force;
  };

  // For backwards-compatibility.
  force.distance = force.linkDistance;

  force.linkStrength = function(x) {
    if (!arguments.length) return linkStrength;
    linkStrength = d3_functor(x);
    return force;
  };

  force.friction = function(x) {
    if (!arguments.length) return friction;
    friction = x;
    return force;
  };

  force.charge = function(x) {
    if (!arguments.length) return charge;
    charge = typeof x === "function" ? x : +x;
    return force;
  };

  force.gravity = function(x) {
    if (!arguments.length) return gravity;
    gravity = x;
    return force;
  };

  force.theta = function(x) {
    if (!arguments.length) return theta;
    theta = x;
    return force;
  };

  force.alpha = function(x) {
    if (!arguments.length) return alpha;

    if (alpha) { // if we're already running
      if (x > 0) alpha = x; // we might keep it hot
      else alpha = 0; // or, next tick will dispatch "end"
    } else if (x > 0) { // otherwise, fire it up!
      event.start({type: "start", alpha: alpha = x});
      d3.timer(force.tick);
    }

    return force;
  };

  force.start = function() {
    var i,
        j,
        n = nodes.length,
        m = links.length,
        w = size[0],
        h = size[1],
        neighbors,
        o;

    for (i = 0; i < n; ++i) {
      (o = nodes[i]).index = i;
      o.weight = 0;
    }

    distances = [];
    strengths = [];
    for (i = 0; i < m; ++i) {
      o = links[i];
      if (typeof o.source == "number") o.source = nodes[o.source];
      if (typeof o.target == "number") o.target = nodes[o.target];
      distances[i] = linkDistance.call(this, o, i);
      strengths[i] = linkStrength.call(this, o, i);
      ++o.source.weight;
      ++o.target.weight;
    }

    for (i = 0; i < n; ++i) {
      o = nodes[i];
      if (isNaN(o.x)) o.x = position("x", w);
      if (isNaN(o.y)) o.y = position("y", h);
      if (isNaN(o.px)) o.px = o.x;
      if (isNaN(o.py)) o.py = o.y;
    }

    charges = [];
    if (typeof charge === "function") {
      for (i = 0; i < n; ++i) {
        charges[i] = +charge.call(this, nodes[i], i);
      }
    } else {
      for (i = 0; i < n; ++i) {
        charges[i] = charge;
      }
    }

    // initialize node position based on first neighbor
    function position(dimension, size) {
      var neighbors = neighbor(i),
          j = -1,
          m = neighbors.length,
          x;
      while (++j < m) if (!isNaN(x = neighbors[j][dimension])) return x;
      return Math.random() * size;
    }

    // initialize neighbors lazily
    function neighbor() {
      if (!neighbors) {
        neighbors = [];
        for (j = 0; j < n; ++j) {
          neighbors[j] = [];
        }
        for (j = 0; j < m; ++j) {
          var o = links[j];
          neighbors[o.source.index].push(o.target);
          neighbors[o.target.index].push(o.source);
        }
      }
      return neighbors[i];
    }

    return force.resume();
  };

  force.resume = function() {
    return force.alpha(.1);
  };

  force.stop = function() {
    return force.alpha(0);
  };

  // use `node.call(force.drag)` to make nodes draggable
  force.drag = function() {
    if (!drag) drag = d3.behavior.drag()
        .origin(d3_identity)
        .on("dragstart", d3_layout_forceDragstart)
        .on("drag", dragmove)
        .on("dragend", d3_layout_forceDragend);

    this.on("mouseover.force", d3_layout_forceMouseover)
        .on("mouseout.force", d3_layout_forceMouseout)
        .call(drag);
  };

  function dragmove(d) {
    d.px = d3.event.x;
    d.py = d3.event.y;
    force.resume(); // restart annealing
  }

  return d3.rebind(force, event, "on");
};

// The fixed property has three bits:
// Bit 1 can be set externally (e.g., d.fixed = true) and show persist.
// Bit 2 stores the dragging state, from mousedown to mouseup.
// Bit 3 stores the hover state, from mouseover to mouseout.
// Dragend is a special case: it also clears the hover state.

function d3_layout_forceDragstart(d) {
  d.fixed |= 2; // set bit 2
}

function d3_layout_forceDragend(d) {
  d.fixed &= 1; // unset bits 2 and 3
}

function d3_layout_forceMouseover(d) {
  d.fixed |= 4; // set bit 3
}

function d3_layout_forceMouseout(d) {
  d.fixed &= 3; // unset bit 3
}

function d3_layout_forceAccumulate(quad, alpha, charges) {
  var cx = 0,
      cy = 0;
  quad.charge = 0;
  if (!quad.leaf) {
    var nodes = quad.nodes,
        n = nodes.length,
        i = -1,
        c;
    while (++i < n) {
      c = nodes[i];
      if (c == null) continue;
      d3_layout_forceAccumulate(c, alpha, charges);
      quad.charge += c.charge;
      cx += c.charge * c.cx;
      cy += c.charge * c.cy;
    }
  }
  if (quad.point) {
    // jitter internal nodes that are coincident
    if (!quad.leaf) {
      quad.point.x += Math.random() - .5;
      quad.point.y += Math.random() - .5;
    }
    var k = alpha * charges[quad.point.index];
    quad.charge += quad.pointCharge = k;
    cx += k * quad.point.x;
    cy += k * quad.point.y;
  }
  quad.cx = cx / quad.charge;
  quad.cy = cy / quad.charge;
}

function d3_layout_forceLinkDistance(link) {
  return 20;
}

function d3_layout_forceLinkStrength(link) {
  return 1;
}
<commit_msg>export force.drag instance so user can access it by calling force.drag() with no arguments; the drag events have been namespaced as <event>.force, similar to the other force events: mouseover.force and mouseout.force.<commit_after>// A rudimentary force layout using Gauss-Seidel.
d3.layout.force = function() {
  var force = {},
      event = d3.dispatch("start", "tick", "end"),
      size = [1, 1],
      drag,
      alpha,
      friction = .9,
      linkDistance = d3_layout_forceLinkDistance,
      linkStrength = d3_layout_forceLinkStrength,
      charge = -30,
      gravity = .1,
      theta = .8,
      interval,
      nodes = [],
      links = [],
      distances,
      strengths,
      charges;

  function repulse(node) {
    return function(quad, x1, y1, x2, y2) {
      if (quad.point !== node) {
        var dx = quad.cx - node.x,
            dy = quad.cy - node.y,
            dn = 1 / Math.sqrt(dx * dx + dy * dy);

        /* Barnes-Hut criterion. */
        if ((x2 - x1) * dn < theta) {
          var k = quad.charge * dn * dn;
          node.px -= dx * k;
          node.py -= dy * k;
          return true;
        }

        if (quad.point && isFinite(dn)) {
          var k = quad.pointCharge * dn * dn;
          node.px -= dx * k;
          node.py -= dy * k;
        }
      }
      return !quad.charge;
    };
  }

  force.tick = function() {
    // simulated annealing, basically
    if ((alpha *= .99) < .005) {
      event.end({type: "end", alpha: alpha = 0});
      return true;
    }

    var n = nodes.length,
        m = links.length,
        q,
        i, // current index
        o, // current object
        s, // current source
        t, // current target
        l, // current distance
        k, // current force
        x, // x-distance
        y; // y-distance

    // gauss-seidel relaxation for links
    for (i = 0; i < m; ++i) {
      o = links[i];
      s = o.source;
      t = o.target;
      x = t.x - s.x;
      y = t.y - s.y;
      if (l = (x * x + y * y)) {
        l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l;
        x *= l;
        y *= l;
        t.x -= x * (k = s.weight / (t.weight + s.weight));
        t.y -= y * k;
        s.x += x * (k = 1 - k);
        s.y += y * k;
      }
    }

    // apply gravity forces
    if (k = alpha * gravity) {
      x = size[0] / 2;
      y = size[1] / 2;
      i = -1; if (k) while (++i < n) {
        o = nodes[i];
        o.x += (x - o.x) * k;
        o.y += (y - o.y) * k;
      }
    }

    // compute quadtree center of mass and apply charge forces
    if (charge) {
      d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);
      i = -1; while (++i < n) {
        if (!(o = nodes[i]).fixed) {
          q.visit(repulse(o));
        }
      }
    }

    // position verlet integration
    i = -1; while (++i < n) {
      o = nodes[i];
      if (o.fixed) {
        o.x = o.px;
        o.y = o.py;
      } else {
        o.x -= (o.px - (o.px = o.x)) * friction;
        o.y -= (o.py - (o.py = o.y)) * friction;
      }
    }

    event.tick({type: "tick", alpha: alpha});
  };

  force.nodes = function(x) {
    if (!arguments.length) return nodes;
    nodes = x;
    return force;
  };

  force.links = function(x) {
    if (!arguments.length) return links;
    links = x;
    return force;
  };

  force.size = function(x) {
    if (!arguments.length) return size;
    size = x;
    return force;
  };

  force.linkDistance = function(x) {
    if (!arguments.length) return linkDistance;
    linkDistance = d3_functor(x);
    return force;
  };

  // For backwards-compatibility.
  force.distance = force.linkDistance;

  force.linkStrength = function(x) {
    if (!arguments.length) return linkStrength;
    linkStrength = d3_functor(x);
    return force;
  };

  force.friction = function(x) {
    if (!arguments.length) return friction;
    friction = x;
    return force;
  };

  force.charge = function(x) {
    if (!arguments.length) return charge;
    charge = typeof x === "function" ? x : +x;
    return force;
  };

  force.gravity = function(x) {
    if (!arguments.length) return gravity;
    gravity = x;
    return force;
  };

  force.theta = function(x) {
    if (!arguments.length) return theta;
    theta = x;
    return force;
  };

  force.alpha = function(x) {
    if (!arguments.length) return alpha;

    if (alpha) { // if we're already running
      if (x > 0) alpha = x; // we might keep it hot
      else alpha = 0; // or, next tick will dispatch "end"
    } else if (x > 0) { // otherwise, fire it up!
      event.start({type: "start", alpha: alpha = x});
      d3.timer(force.tick);
    }

    return force;
  };

  force.start = function() {
    var i,
        j,
        n = nodes.length,
        m = links.length,
        w = size[0],
        h = size[1],
        neighbors,
        o;

    for (i = 0; i < n; ++i) {
      (o = nodes[i]).index = i;
      o.weight = 0;
    }

    distances = [];
    strengths = [];
    for (i = 0; i < m; ++i) {
      o = links[i];
      if (typeof o.source == "number") o.source = nodes[o.source];
      if (typeof o.target == "number") o.target = nodes[o.target];
      distances[i] = linkDistance.call(this, o, i);
      strengths[i] = linkStrength.call(this, o, i);
      ++o.source.weight;
      ++o.target.weight;
    }

    for (i = 0; i < n; ++i) {
      o = nodes[i];
      if (isNaN(o.x)) o.x = position("x", w);
      if (isNaN(o.y)) o.y = position("y", h);
      if (isNaN(o.px)) o.px = o.x;
      if (isNaN(o.py)) o.py = o.y;
    }

    charges = [];
    if (typeof charge === "function") {
      for (i = 0; i < n; ++i) {
        charges[i] = +charge.call(this, nodes[i], i);
      }
    } else {
      for (i = 0; i < n; ++i) {
        charges[i] = charge;
      }
    }

    // initialize node position based on first neighbor
    function position(dimension, size) {
      var neighbors = neighbor(i),
          j = -1,
          m = neighbors.length,
          x;
      while (++j < m) if (!isNaN(x = neighbors[j][dimension])) return x;
      return Math.random() * size;
    }

    // initialize neighbors lazily
    function neighbor() {
      if (!neighbors) {
        neighbors = [];
        for (j = 0; j < n; ++j) {
          neighbors[j] = [];
        }
        for (j = 0; j < m; ++j) {
          var o = links[j];
          neighbors[o.source.index].push(o.target);
          neighbors[o.target.index].push(o.source);
        }
      }
      return neighbors[i];
    }

    return force.resume();
  };

  force.resume = function() {
    return force.alpha(.1);
  };

  force.stop = function() {
    return force.alpha(0);
  };

  // use `node.call(force.drag)` to make nodes draggable
  force.drag = function() {
    if (!arguments.length) return drag;

    if (!drag) drag = d3.behavior.drag()
        .origin(d3_identity)
        .on("dragstart.force", d3_layout_forceDragstart)
        .on("drag.force", dragmove)
        .on("dragend.force", d3_layout_forceDragend);

    this.on("mouseover.force", d3_layout_forceMouseover)
        .on("mouseout.force", d3_layout_forceMouseout)
        .call(drag);
  };

  function dragmove(d) {
    d.px = d3.event.x;
    d.py = d3.event.y;
    force.resume(); // restart annealing
  }

  return d3.rebind(force, event, "on");
};

// The fixed property has three bits:
// Bit 1 can be set externally (e.g., d.fixed = true) and show persist.
// Bit 2 stores the dragging state, from mousedown to mouseup.
// Bit 3 stores the hover state, from mouseover to mouseout.
// Dragend is a special case: it also clears the hover state.

function d3_layout_forceDragstart(d) {
  d.fixed |= 2; // set bit 2
}

function d3_layout_forceDragend(d) {
  d.fixed &= 1; // unset bits 2 and 3
}

function d3_layout_forceMouseover(d) {
  d.fixed |= 4; // set bit 3
}

function d3_layout_forceMouseout(d) {
  d.fixed &= 3; // unset bit 3
}

function d3_layout_forceAccumulate(quad, alpha, charges) {
  var cx = 0,
      cy = 0;
  quad.charge = 0;
  if (!quad.leaf) {
    var nodes = quad.nodes,
        n = nodes.length,
        i = -1,
        c;
    while (++i < n) {
      c = nodes[i];
      if (c == null) continue;
      d3_layout_forceAccumulate(c, alpha, charges);
      quad.charge += c.charge;
      cx += c.charge * c.cx;
      cy += c.charge * c.cy;
    }
  }
  if (quad.point) {
    // jitter internal nodes that are coincident
    if (!quad.leaf) {
      quad.point.x += Math.random() - .5;
      quad.point.y += Math.random() - .5;
    }
    var k = alpha * charges[quad.point.index];
    quad.charge += quad.pointCharge = k;
    cx += k * quad.point.x;
    cy += k * quad.point.y;
  }
  quad.cx = cx / quad.charge;
  quad.cy = cy / quad.charge;
}

function d3_layout_forceLinkDistance(link) {
  return 20;
}

function d3_layout_forceLinkStrength(link) {
  return 1;
}
<|endoftext|>


<commit_before>foam.CLASS({
  package: 'foam.demos.graphics',
  name: 'LifeStar',
  extends: 'foam.graphics.Box',

  requires: [ 'foam.graphics.Arc' ],

  classes: [
    {
      name: 'Point',
      extends: 'foam.graphics.Circle',
      properties: [
        'z',
        { class: 'Float', name: 'glowRadius' }
      ],
      methods: [
        function rotateY(a) {
          var x = this.x, z = this.z;
          this.z = z * Math.cos(a) - x * Math.sin(a);
          this.x = z * Math.sin(a) + x * Math.cos(a);
        },
        function rotateX(a) {
          var y = this.y, z = this.z;
          this.z = z * Math.cos(a) - y * Math.sin(a);
          this.y = z * Math.sin(a) + y * Math.cos(a);
        },
        function doTransform(x) {
          var t = this.transform;
          var s = 1 - this.z/300;
          t.scale(s, s);
          x.transform(t.a, t.d, t.b, t.e, t.c, t.f);
        },
        function paintSelf(x) {
          this.SUPER(x);
          if ( this.glowRadius ) {
            x.globalAlpha = 0.2;
            var oldR = this.radius;
            this.radius = this.glowRadius;
            this.SUPER(x);
            this.radius = oldR;
          }
        }
      ]
    }
  ],

  properties: [
    [ 'n',      217 ],
    [ 'x',      500 ],
    [ 'y',      350 ],
    [ 'width',  1000 ],
    [ 'height', 500 ],
    [ 'time',   0 ],
    [ 'color', 'black' ]
  ],

  methods: [
    function initCView() {
      this.SUPER();
      for ( var i = 0 ; i < this.n ; i++ ) this.addPoint(i);
      this.tick();
    },
    function addPoint(i) {
      var p = this.Point.create({
        radius: 3,
        border: null,
        arcWidth: 0
      });

      this.time$.sub(function() {
        var time = this.time;
        var r    = Math.sin(Math.PI * i/this.n)*200;
        var a    = (i-time/10)*Math.PI*19/this.n;

        p.x = Math.sin(a) * r;
        p.y = Math.cos(a) * r;
        p.z = Math.sqrt(200*200 - p.x*p.x - p.y*p.y) * (( i > this.n/2 ) ? 1 : -1);

        p.rotateY(0.01*time);
        p.rotateX(0.005*time);

        var on = Math.abs((time % this.n - i + this.n)%this.n) < 20
        p.glowRadius = on ? 8 : 0;
        var s = on ? 100 : 70;
        var l = on ?  70 : 40;
        p.color = this.hsl(i*365/this.n, s, l);
      }.bind(this));
      this.addChildren(p);
    }
  ],
  listeners: [
    {
      name: 'tick',
      isFramed: true,
      code: function() { this.time++; this.tick(); this.invalidated.pub(); }
    }
  ]
});
<commit_msg>Simplified LifeStar demo.<commit_after>foam.CLASS({
  package: 'foam.demos.graphics',
  name: 'LifeStar',
  extends: 'foam.graphics.Box',

  requires: [ 'foam.graphics.Arc' ],

  imports: [ 'framed' ],

  classes: [
    {
      name: 'Point',
      extends: 'foam.graphics.Circle',
      properties: [
        'z',
        [ 'radius',   3 ],
        [ 'border',   null ],
        [ 'arcWidth', 0 ],
        { class: 'Float', name: 'glowRadius' }
      ],
      methods: [
        function rotateY(a) {
          var x = this.x, z = this.z;
          this.z = z * Math.cos(a) - x * Math.sin(a);
          this.x = z * Math.sin(a) + x * Math.cos(a);
        },
        function rotateX(a) {
          var y = this.y, z = this.z;
          this.z = z * Math.cos(a) - y * Math.sin(a);
          this.y = z * Math.sin(a) + y * Math.cos(a);
        },
        function doTransform(x) {
          var t = this.transform;
          var s = 1 - this.z/300;
          t.scale(s, s);
          x.transform(t.a, t.d, t.b, t.e, t.c, t.f);
        },
        function paintSelf(x) {
          this.SUPER(x);
          if ( this.glowRadius ) {
            x.globalAlpha = 0.2;
            var oldR = this.radius;
            this.radius = this.glowRadius;
            this.SUPER(x);
            this.radius = oldR;
          }
        }
      ]
    }
  ],

  properties: [
    [ 'n',      197 ],
    [ 'x',      500 ],
    [ 'y',      350 ],
    [ 'width',  1000 ],
    [ 'height', 500 ],
    [ 'time',   0 ],
    [ 'color', 'black' ]
  ],

  methods: [
    function initCView() {
      this.SUPER();
      for ( var i = 0 ; i < this.n ; i++ ) this.addChildren(this.Point.create());
    },
    function paint(x) {
      this.SUPER(x);

      var time = this.time++;

      for ( var i = 0 ; i < this.n ; i++ ) {
        var p = this.children[i];
        var r = Math.sin(Math.PI * i/this.n)*200;
        var a = (i-time/20)*Math.PI*15/this.n;

        p.x = Math.sin(a) * r;
        p.y = Math.cos(a) * r;
        p.z = Math.sqrt(40000 - p.x*p.x - p.y*p.y) * (( i > this.n/2 ) ? 1 : -1);

        p.rotateY(0.005*time);
        p.rotateX(0.003*time);

        var on = Math.abs((time % this.n - i + this.n)%this.n) < 20
        p.glowRadius = on ? 8 : 0;
        var s = on ? 100 : 70;
        var l = on ?  70 : 40;
        p.color = this.hsl(i*365/this.n, s, l);
      }

      this.invalidated.pub();
    }
  ]
});
<|endoftext|>


<commit_before>'use strict';

/**
* ESLint rules for JSHint/JSLint compatibility.
*
* @namespace rules
*/
var rules = {};

/**
* Maximum depth that blocks can be nested.
*
* @name max-depth
* @memberof rules
* @type {Array}
* @default [ 2, 5 ]
* @see [max-depth]{@link http://eslint.org/docs/rules/max-depth}
*/
rules[ 'max-depth' ] = [ 2, 5 ];

/**
* Maximum line length.
*
* @name max-len
* @memberof rules
* @type {Array}
* @see [max-len]{@link http://eslint.org/docs/rules/max-len}
*/
rules[ 'max-len' ] = [ 1, 80, 4, {
	'ignoreComments': true,
	'ignoreUrls': true
}];

/**
* Maximum number of parameters.
*
* @name max-params
* @memberof rules
* @type {Array}
* @default [ 2, 10 ]
* @see [max-params]{@link http://eslint.org/docs/rules/max-params}
*/
rules[ 'max-params' ] = [ 2, 10 ];

/**
* Maximum number of statements in a function.
*
* @name max-statements
* @memberof rules
* @type {Array}
* @default [ 2, 100 ]
* @see [max-statements]{@link http://eslint.org/docs/rules/max-statements}
*/
rules[ 'max-statements' ] = [ 2, 100 ];

/**
* Allow the use of bitwise operators.
*
* @name no-bitwise
* @memberof rules
* @type {number}
* @default 0
* @see [no-bitwise]{@link http://eslint.org/docs/rules/no-bitwise}
*/
rules[ 'no-bitwise' ] = 0;

/**
* Allow the use of `++` and `--`.
*
* @name no-plusplus
* @memberof rules
* @type {number}
* @default 0
* @see [no-plusplus]{@link http://eslint.org/docs/rules/no-plusplus}
*/
rules[ 'no-plusplus' ] = 0;

// EXPORTS //

module.exports = rules;
<commit_msg>Remove file<commit_after><|endoftext|>


<commit_before>import 'select2'
import { Slick } from 'slickgrid-es6';

export { Select2Formatter, Select2Editor }

function PopulateSelect(select, dataSource, addBlank) {
  var newOption;

  if (addBlank) { select.appendChild(new Option('', '')); }

  if (dataSource.grouped) {
    $.each(dataSource.grouped, function (groupKey, groupItems) {
      let groupName = I18n.t(`gobierto_admin.custom_fields_plugins.common.${groupKey}`)
      var $group = $(`<optgroup label="${groupName}"></optgroup`)
      $group.appendTo($(select));

      var groupItemsPairs = _.toPairs(groupItems)
      $.each(groupItemsPairs, function(idx) {
        newOption = new Option(groupItemsPairs[idx][1], groupItemsPairs[idx][0]);
        $group[0].appendChild(newOption);
      })
    });
  } else if (Array.isArray(dataSource)) {
    $.each(dataSource, function (_idx, value) {
      newOption = new Option(value, value)
      select.appendChild(newOption)
    })
  } else {
    $.each(dataSource, function (value, text) {
      newOption = new Option(text, value);
      select.appendChild(newOption);
    });
  }
};

function Select2Formatter(_row, _cell, value, columnDef, _dataContext) {
  var groupedData = columnDef.dataSource.grouped

  if (groupedData) {
    var result
    $.each(groupedData, function (_groupKey, groupItems) {
      $.each(groupItems, function (itemValue, _text) {
        if (groupedData[itemValue.split("/")[0]][value]) {
          result = groupedData[itemValue.split("/")[0]][value]
          return false
        }
      })
      if (result) return false
    })
  }

  if (Array.isArray(columnDef.dataSource) && columnDef.dataSource.indexOf(value) > -1) {
    return value
  }

  return result || columnDef.dataSource[value] || '-'
}

function Select2Editor(args) {
  var _grid = args.grid
  var $input;
  var defaultValue;

  this.keyCaptureList = [Slick.keyCode.UP, Slick.keyCode.DOWN, Slick.keyCode.ENTER];

  this.init = function () {
    $input = $('<select></select>');
    $input.width(args.container.clientWidth + 3);
    PopulateSelect($input[0], args.column.dataSource, false);
    $input.appendTo(args.container);
    $input.focus().select();

    $input.select2({
      placeholder: '-',
      allowClear: true
    });

    /* Ensure focus is lost after choosing an option */
    $input.on('select2:close', function() {
      var lock = Slick.GlobalEditorLock
      if (lock.isActive()) lock.commitCurrentEdit()

      if (_grid) _grid.resetActiveCell()
    })
  };

  this.destroy = function () {
    $input.select2('close');
    $input.select2('destroy');
    $input.remove();
  };

  this.show = function () {
    $input.select2('open');
  };

  this.hide = function () {
  };

  this.position = function (position) {
  };

  this.focus = function () {
    $input.select2('input_focus');
  };

  this.loadValue = function (item) {
    defaultValue = item[args.column.field];
    $input.val(defaultValue);
    $input[0].defaultValue = defaultValue;
    $input.trigger("change.select2");
  };

  this.serializeValue = function () {
    var inputValue = $input.val()
    var inputValueInt = parseInt(inputValue)

    if (isNaN(inputValueInt)) return inputValue
    return inputValueInt
  };

  this.applyValue = function (item, state) {
    item[args.column.field] = state;
  };

  this.isValueChanged = function () {
    return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
  };

  this.validate = function () {
    return {
      valid: true,
      msg: null
    };
  };

  this.init();
}
<commit_msg>Automatically focus on next cell after clicking on select2 option<commit_after>import 'select2'
import { Slick } from 'slickgrid-es6';

export { Select2Formatter, Select2Editor }

function PopulateSelect(select, dataSource, addBlank) {
  var newOption;

  if (addBlank) { select.appendChild(new Option('', '')); }

  if (dataSource.grouped) {
    $.each(dataSource.grouped, function (groupKey, groupItems) {
      let groupName = I18n.t(`gobierto_admin.custom_fields_plugins.common.${groupKey}`)
      var $group = $(`<optgroup label="${groupName}"></optgroup`)
      $group.appendTo($(select));

      var groupItemsPairs = _.toPairs(groupItems)
      $.each(groupItemsPairs, function(idx) {
        newOption = new Option(groupItemsPairs[idx][1], groupItemsPairs[idx][0]);
        $group[0].appendChild(newOption);
      })
    });
  } else if (Array.isArray(dataSource)) {
    $.each(dataSource, function (_idx, value) {
      newOption = new Option(value, value)
      select.appendChild(newOption)
    })
  } else {
    $.each(dataSource, function (value, text) {
      newOption = new Option(text, value);
      select.appendChild(newOption);
    });
  }
};

function Select2Formatter(_row, _cell, value, columnDef, _dataContext) {
  var groupedData = columnDef.dataSource.grouped

  if (groupedData) {
    var result
    $.each(groupedData, function (_groupKey, groupItems) {
      $.each(groupItems, function (itemValue, _text) {
        if (groupedData[itemValue.split("/")[0]][value]) {
          result = groupedData[itemValue.split("/")[0]][value]
          return false
        }
      })
      if (result) return false
    })
  }

  if (Array.isArray(columnDef.dataSource) && columnDef.dataSource.indexOf(value) > -1) {
    return value
  }

  return result || columnDef.dataSource[value] || '-'
}

function Select2Editor(args) {
  var _grid = args.grid
  var $input;
  var defaultValue;

  this.keyCaptureList = [Slick.keyCode.UP, Slick.keyCode.DOWN, Slick.keyCode.ENTER];

  this.init = function () {
    $input = $('<select></select>');
    $input.width(args.container.clientWidth + 3);
    PopulateSelect($input[0], args.column.dataSource, false);
    $input.appendTo(args.container);
    $input.focus().select();

    $input.select2({
      placeholder: '-',
      allowClear: true
    });

    /* Automatically focus on next cell after chosing an option */
    $input.on('select2:close', function() {
      var lock = Slick.GlobalEditorLock
      if (lock.isActive()) lock.commitCurrentEdit()

      let activeCell = _grid.getActiveCell()

      _grid.setActiveCell(activeCell.row, activeCell.cell + 1)
      _grid.editActiveCell()
    })
  };

  this.destroy = function () {
    $input.select2('close');
    $input.select2('destroy');
    $input.remove();
  };

  this.show = function () {
    $input.select2('open');
  };

  this.hide = function () {
  };

  this.position = function (position) {
  };

  this.focus = function () {
    $input.select2('input_focus');
  };

  this.loadValue = function (item) {
    defaultValue = item[args.column.field];
    $input.val(defaultValue);
    $input[0].defaultValue = defaultValue;
    $input.trigger("change.select2");
  };

  this.serializeValue = function () {
    var inputValue = $input.val()
    var inputValueInt = parseInt(inputValue)

    if (isNaN(inputValueInt)) return inputValue
    return inputValueInt
  };

  this.applyValue = function (item, state) {
    item[args.column.field] = state;
  };

  this.isValueChanged = function () {
    return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
  };

  this.validate = function () {
    return {
      valid: true,
      msg: null
    };
  };

  this.init();
}
<|endoftext|>


<commit_before>// document identifiers
var TOP_SITES_CONTENT_ID = 'top-sites-content';
var PIE_CHART_CONTENT_ID = 'pie-chart-content';
var TOP_SITES_BUTTON_ID = 'top-sites-button';
var PIE_CHART_BUTTON_ID = 'pie-chart-button';
var TIMESLICE_SELECT_ID = 'timesliceSelectBox';
var TOP_SITES_LIST_ID = 'top-sites-list';
var TIME_LABEL_ID = 'time-label-span';
var LOADING_ICON_ID = 'loading-icon';

// default coloring
var ACTIVE_BACKGROUND_COLOR = '#FCFCFC';
var DORMANT_BACKGROUND_COLOR = 'white';
var BORDER_COLOR = 'black';

// time slice identifiers
var WEEK = '1';
var MONTH = '2';
var YEAR = '3';
var TOP_X = 10; // top X items to show to the user

function buildHistoryItemList(timeslice) {
  /**
   * buildHistoryItemList()
   * This function builds a list of history items from the Chrome history api.
   * @param {string} timeslice A string indicating which of 3 timeslice
   *     durations to use. Note that the if the timeslice is undefined, a
   *     default of '1' is used, indicating the duration of a week.
   */
  showLoadingIcon();

  if (typeof timeslice === 'undefined') { timeslice = WEEK; }
  var searchDepth = 0

  if (timeslice == WEEK) {
    var microsecondsPerWeek = 1000 * 60 * 60 * 24 * 7;
    searchDepth = (new Date).getTime() - microsecondsPerWeek;
  } else if (timeslice == MONTH) {
    var microsecondsPerMonth = 1000 * 60 * 60 * 24 * 30;
    searchDepth = (new Date).getTime() - microsecondsPerMonth;
  } else {
    var microsecondsPerYear = 1000 * 60 * 60 * 24 * 360;
    searchDepth = (new Date).getTime() - microsecondsPerYear;
  }

   /* Track the number of callbacks from chrome.history.getVisits()
    *     that we expect to get.  When it reaches zero, we have all results.
    */
  var numRequestsOutstanding = 0;

  chrome.history.search({
    'text': '',                // Return every history item...
    'startTime': searchDepth,  // accessed less than x time ago.
    'maxResults': 0            // 0 == all results
    },
   function(historyItems) {
    // For each history item, get details on all visits.
    for (var i = 0; i < historyItems.length; ++i) {
      var url = historyItems[i].url;
      var processVisitsWithUrl = function(url) {
        /**
          * processVisitsWithUrl()
          * We need the url of the visited item to process the visit. Use a
          *     closure to bind the url into the callback's args.
          * @return {function} A closure to bind url+callback
          */
        return function(visitItems) { processVisits(url, visitItems); };
      };
      chrome.history.getVisits({url: url}, processVisitsWithUrl(url));
      numRequestsOutstanding++;
    }
    if (!numRequestsOutstanding) {
      onAllVisitsProcessed();
    }
  });

  // Maps URLs to a count of the number of times the user visited that URL
  var urlCountObject = {};
  // to be sorted by url count
  var sortedUrlArray = [];

  var processVisits = function(url, visitItems) {
    /**
      * processVisits()
      * Callback for chrome.history.getVisits().  Counts the number of times a
      *     user visited a URL.
      * @param {string} url The url to count.
      * @param {object} visitItems The object from the API representing a visit.
      */
    for (var i = 0, ie = visitItems.length; i < ie; ++i) {
      // get simple domains from a given url
      var rootDomain = new URL(url).hostname;

      if (!urlCountObject[rootDomain]) {
        urlCountObject[rootDomain] = 0;
        sortedUrlArray.push(rootDomain);
      }

      urlCountObject[rootDomain]++;
    }

     /* If this is the final outstanding call to processVisits(),
      *     then we have the final results.  Use them to build the list
      *     of URLs to show in the popup.
      */
    if (!--numRequestsOutstanding) { // if you can no longer decrement...
      onAllVisitsProcessed();
    }
  };

  var onAllVisitsProcessed = function() {
    /**
      * onAllVisitsProcessed()
      * Sort the URLs by the number of times the user typed them, then call
      *     the function to print them. This is called when we have the final
      *     list of URls to display.
      */
   sortedUrlArray.sort(function(a, b) {
     return urlCountObject[b] - urlCountObject[a];
   });

   printTopResults(sortedUrlArray, urlCountObject);
  };
}

var printTopResults = function(sortedUrlArray, urlCountObject) {
  /**
   * printTopResults()
   * Displays urls and counts. Also calls pie chart code.
   * @param {array} sortedUrlArray An array of count-sorted Urls.
   * @param {object} urlCountObject An object containing url to count mappings.
   */
  pieChartData = new Array(); // object to store pie chart data

  // for (var i in sortedUrlArray) {
  for (var i =0; i < TOP_X; i++) {
    url = sortedUrlArray[i];
    count = urlCountObject[sortedUrlArray[i]];

    // grab the hostname from the url with this hack
    var linkElement = document.createElement('a');
    linkElement.href = 'http://' + url;
    linkElement.text = url;
    linkElement.target = 'blank';

    // create an li for each site, and append the link created above
    var lineItemElement = document.createElement('li');
    lineItemElement.appendChild(linkElement);
    // add the count to the li
    var countText = document.createTextNode(', ' + count + ' times.');
    lineItemElement.appendChild(countText);

    // append each line item to the appropriate ol element
    var orderedListElement = document.getElementById('top-sites-list');
    orderedListElement.appendChild(lineItemElement);

    // this is massaged data for the pie chart
    var tmp = new Object();
    tmp.label = url;
    tmp.value = count;
    pieChartData.push(tmp);
  }
  createPieChart(pieChartData);
  hideLoadingIcon();
}

var createDropShadowFilter = function() {
 /**
   * createDropShadowFilter()
   * Creates an SVG drop shadow filter for the pie chart.
   */
  var svg = d3.select('svg');
  var defs = svg.append("defs");

  var filter = defs.append("filter")
      .attr("id", "dropshadow")

  filter.append("feGaussianBlur")
      .attr("in", "SourceAlpha")
      .attr("stdDeviation", 4)
      .attr("result", "blur");
  filter.append("feOffset")
      .attr("in", "blur")
      .attr("dx", 2)
      .attr("dy", 2)
      .attr("result", "offsetBlur");

  var feMerge = filter.append("feMerge");

  feMerge.append("feMergeNode")
      .attr("in", "offsetBlur")
  feMerge.append("feMergeNode")
      .attr("in", "SourceGraphic");
}

var createPieChart = function(pieChartData) {
  /**
   * createPieChart()
   * Creates a pie chart with url data, using nvd3 libraries.
   * @param {object} pieChartData An object containing url-to-count mappings
   *     formatted for the nvd3 pie chart library.
   */
  var data = pieChartData;

  nv.addGraph(function() {
  var chart = nv.models.pieChart()
    .x(function(d) { return d.label })
    .y(function(d) { return d.value })
    .showLegend(false)
    .labelType("percent")
    .tooltipContent(function(key, y, e, graph) { return key + ', ' +
      e.value + ' visits.' })
    .labelThreshold(.05)
    .showLabels(true);

  createDropShadowFilter();

  d3.selectAll("svg")
  .attr("class", "shadow")
  .attr("filter", "url(#dropshadow)");

  d3.select("#chart svg")
    .datum(data)
    .transition().duration(1200)
    .call(chart);

  return chart;
  });
}

var addListeners = function() {
  /**
   * addListeners()
   * Add listeners for page events.
   */
  addTabChangeListeners();
  addTimesliceListeners();
}

var addTabChangeListeners = function(){
  /**
   * addTabChangeListeners()
   * Add listeners to the tab buttons, enabling a user to switch between them.
   */
  var topSitesButton = document.getElementById(TOP_SITES_BUTTON_ID);
  var pieChartButton = document.getElementById(PIE_CHART_BUTTON_ID);

  topSitesButton.addEventListener('click', function(){
    showHiddenContent(PIE_CHART_CONTENT_ID, TOP_SITES_CONTENT_ID,
                      topSitesButton, pieChartButton);
  });

  pieChartButton.addEventListener('click', function() {
    showHiddenContent(TOP_SITES_CONTENT_ID, PIE_CHART_CONTENT_ID,
                      pieChartButton, topSitesButton);
  })
}

var clearCurrentContents = function(targetNode) {
  /**
   * clearCurrentContents()
   * Clears the current contents of a provided node.
   * @param {element} targetNode A DOM node from which its children will be
   *     cleared.
   */
  var node = document.getElementById(targetNode);
  if (node) {
    while (node.firstChild) {
      node.removeChild(node.firstChild);
    }
  }
}

var addTimesliceListeners = function() {
  /**
   * addTimesliceListeners()
   * Listens to onchange events from the selectbox containing timeslices, and
   *     rebuilds the display according to what was selected.
   */
  var timesliceSelectBox = document.getElementById(TIMESLICE_SELECT_ID);
  timesliceSelectBox.onchange = function (e) {
    var selectedOption = this[this.selectedIndex];
    var selectedValue = selectedOption.value;
    var timesliceLabelDisplay = document.getElementById(TIME_LABEL_ID);
    timesliceLabelDisplay.innerHTML = selectedOption.innerText;
    targetNode = TOP_SITES_LIST_ID;
    clearCurrentContents(targetNode);
    buildHistoryItemList(selectedValue);
  }
}

var showHiddenContent = function(currentContent,
                                 targetContent,
                                 callingButton,
                                 currentButton) {
  /**
   * showHiddenContent()
   * Hides currently displayed content and shows another set of content.
   * @param {string} currentContent A string containing the ID of the content
   *     currently displayed.
   * @param {string} targetContent A string containing the ID of the content
   *     that should be displayed.
   * @param {element} callingButton A DOM element containing the object that was
   *     clicked and caused the event to fire.
   * @param {element} currentButton A DOM element containing the object that
   *     represents the currently active button.
   */
  var displayStyle = 'block';

  hideContent(currentContent, currentButton);

  var toShow = document.getElementById(targetContent);
  toShow.style.display = displayStyle;
  callingButton.style.borderBottomColor = ACTIVE_BACKGROUND_COLOR;
  callingButton.style.backgroundColor = ACTIVE_BACKGROUND_COLOR;
}

var hideContent = function(currentContent, currentButton) {
  /**
   * hideContent()
   * Hides a given content node, and updates its active button style.
   * @param {string} currentContent A string representign the ID of the current
   *     content displayed.
   * @param {element} currentButton A DOM element representing the currently
   *     active button.
   */
  var toHide = document.getElementById(currentContent);
  toHide.style.display = 'none';
  currentButton.style.borderBottomColor = BORDER_COLOR;
  currentButton.style.backgroundColor = DORMANT_BACKGROUND_COLOR;
}

var showLoadingIcon = function() {
  /**
   * showLoadingIcon()
   * Shows a loading icon while the API is being queried and content is being
   *     loaded.
   */
  var loadingIcon = document.getElementById(LOADING_ICON_ID);
  loadingIcon.style.display = 'block';
}

var hideLoadingIcon = function() {
  /**
   * hideLoadingIcon()
   * Hides the currently displayed loading icon after the API has returned and
   *     the results are ready to display.
   */
  var loadingIcon = document.getElementById(LOADING_ICON_ID);
  loadingIcon.style.display = 'none';
}

document.addEventListener('DOMContentLoaded', function () {
  /**
   * document.addEventListener()
   * Entry point into the code. Fires when the DOMContentLoaded event completes.
   */
  // add event listeners to elements
  addListeners();
  // begin querying the history API and setting up the page
  buildHistoryItemList();
});
<commit_msg>Added newline<commit_after>// document identifiers
var TOP_SITES_CONTENT_ID = 'top-sites-content';
var PIE_CHART_CONTENT_ID = 'pie-chart-content';
var TOP_SITES_BUTTON_ID = 'top-sites-button';
var PIE_CHART_BUTTON_ID = 'pie-chart-button';
var TIMESLICE_SELECT_ID = 'timesliceSelectBox';
var TOP_SITES_LIST_ID = 'top-sites-list';
var TIME_LABEL_ID = 'time-label-span';
var LOADING_ICON_ID = 'loading-icon';

// default coloring
var ACTIVE_BACKGROUND_COLOR = '#FCFCFC';
var DORMANT_BACKGROUND_COLOR = 'white';
var BORDER_COLOR = 'black';

// time slice identifiers
var WEEK = '1';
var MONTH = '2';
var YEAR = '3';
var TOP_X = 10; // top X items to show to the user

function buildHistoryItemList(timeslice) {
  /**
   * buildHistoryItemList()
   * This function builds a list of history items from the Chrome history api.
   * @param {string} timeslice A string indicating which of 3 timeslice
   *     durations to use. Note that the if the timeslice is undefined, a
   *     default of '1' is used, indicating the duration of a week.
   */
  showLoadingIcon();

  if (typeof timeslice === 'undefined') { timeslice = WEEK; }
  var searchDepth = 0

  if (timeslice == WEEK) {
    var microsecondsPerWeek = 1000 * 60 * 60 * 24 * 7;
    searchDepth = (new Date).getTime() - microsecondsPerWeek;
  } else if (timeslice == MONTH) {
    var microsecondsPerMonth = 1000 * 60 * 60 * 24 * 30;
    searchDepth = (new Date).getTime() - microsecondsPerMonth;
  } else {
    var microsecondsPerYear = 1000 * 60 * 60 * 24 * 360;
    searchDepth = (new Date).getTime() - microsecondsPerYear;
  }

   /* Track the number of callbacks from chrome.history.getVisits()
    *     that we expect to get.  When it reaches zero, we have all results.
    */
  var numRequestsOutstanding = 0;

  chrome.history.search({
    'text': '',                // Return every history item...
    'startTime': searchDepth,  // accessed less than x time ago.
    'maxResults': 0            // 0 == all results
    },
   function(historyItems) {
    // For each history item, get details on all visits.
    for (var i = 0; i < historyItems.length; ++i) {
      var url = historyItems[i].url;
      var processVisitsWithUrl = function(url) {
        /**
          * processVisitsWithUrl()
          * We need the url of the visited item to process the visit. Use a
          *     closure to bind the url into the callback's args.
          * @return {function} A closure to bind url+callback
          */
        return function(visitItems) { processVisits(url, visitItems); };
      };
      chrome.history.getVisits({url: url}, processVisitsWithUrl(url));
      numRequestsOutstanding++;
    }
    if (!numRequestsOutstanding) {
      onAllVisitsProcessed();
    }
  });

  // Maps URLs to a count of the number of times the user visited that URL
  var urlCountObject = {};
  // to be sorted by url count
  var sortedUrlArray = [];

  var processVisits = function(url, visitItems) {
    /**
      * processVisits()
      * Callback for chrome.history.getVisits().  Counts the number of times a
      *     user visited a URL.
      * @param {string} url The url to count.
      * @param {object} visitItems The object from the API representing a visit.
      */
    for (var i = 0, ie = visitItems.length; i < ie; ++i) {
      // get simple domains from a given url
      var rootDomain = new URL(url).hostname;

      if (!urlCountObject[rootDomain]) {
        urlCountObject[rootDomain] = 0;
        sortedUrlArray.push(rootDomain);
      }

      urlCountObject[rootDomain]++;
    }

     /* If this is the final outstanding call to processVisits(),
      *     then we have the final results.  Use them to build the list
      *     of URLs to show in the popup.
      */
    if (!--numRequestsOutstanding) { // if you can no longer decrement...
      onAllVisitsProcessed();
    }
  };

  var onAllVisitsProcessed = function() {
    /**
      * onAllVisitsProcessed()
      * Sort the URLs by the number of times the user typed them, then call
      *     the function to print them. This is called when we have the final
      *     list of URls to display.
      */
   sortedUrlArray.sort(function(a, b) {
     return urlCountObject[b] - urlCountObject[a];
   });

   printTopResults(sortedUrlArray, urlCountObject);
  };
}

var printTopResults = function(sortedUrlArray, urlCountObject) {
  /**
   * printTopResults()
   * Displays urls and counts. Also calls pie chart code.
   * @param {array} sortedUrlArray An array of count-sorted Urls.
   * @param {object} urlCountObject An object containing url to count mappings.
   */
  pieChartData = new Array(); // object to store pie chart data

  // for (var i in sortedUrlArray) {
  for (var i =0; i < TOP_X; i++) {
    url = sortedUrlArray[i];
    count = urlCountObject[sortedUrlArray[i]];

    // grab the hostname from the url with this hack
    var linkElement = document.createElement('a');
    linkElement.href = 'http://' + url;
    linkElement.text = url;
    linkElement.target = 'blank';

    // create an li for each site, and append the link created above
    var lineItemElement = document.createElement('li');
    lineItemElement.appendChild(linkElement);
    // add the count to the li
    var countText = document.createTextNode(', ' + count + ' times.');
    lineItemElement.appendChild(countText);

    // append each line item to the appropriate ol element
    var orderedListElement = document.getElementById('top-sites-list');
    orderedListElement.appendChild(lineItemElement);

    // this is massaged data for the pie chart
    var tmp = new Object();
    tmp.label = url;
    tmp.value = count;
    pieChartData.push(tmp);
  }
  createPieChart(pieChartData);
  hideLoadingIcon();
}

var createDropShadowFilter = function() {
 /**
   * createDropShadowFilter()
   * Creates an SVG drop shadow filter for the pie chart.
   */
  var svg = d3.select('svg');
  var defs = svg.append("defs");

  var filter = defs.append("filter")
      .attr("id", "dropshadow")

  filter.append("feGaussianBlur")
      .attr("in", "SourceAlpha")
      .attr("stdDeviation", 4)
      .attr("result", "blur");
  filter.append("feOffset")
      .attr("in", "blur")
      .attr("dx", 2)
      .attr("dy", 2)
      .attr("result", "offsetBlur");

  var feMerge = filter.append("feMerge");

  feMerge.append("feMergeNode")
      .attr("in", "offsetBlur")
  feMerge.append("feMergeNode")
      .attr("in", "SourceGraphic");
}

var createPieChart = function(pieChartData) {
  /**
   * createPieChart()
   * Creates a pie chart with url data, using nvd3 libraries.
   * @param {object} pieChartData An object containing url-to-count mappings
   *     formatted for the nvd3 pie chart library.
   */
  var data = pieChartData;

  nv.addGraph(function() {
  var chart = nv.models.pieChart()
    .x(function(d) { return d.label })
    .y(function(d) { return d.value })
    .showLegend(false)
    .labelType("percent")
    .tooltipContent(function(key, y, e, graph) { return key + ', ' +
      e.value + ' visits.' })
    .labelThreshold(.05)
    .showLabels(true);

  createDropShadowFilter();

  d3.selectAll("svg")
  .attr("class", "shadow")
  .attr("filter", "url(#dropshadow)");

  d3.select("#chart svg")
    .datum(data)
    .transition().duration(1200)
    .call(chart);

  return chart;
  });
}

var addListeners = function() {
  /**
   * addListeners()
   * Add listeners for page events.
   */
  addTabChangeListeners();
  addTimesliceListeners();
}

var addTabChangeListeners = function(){
  /**
   * addTabChangeListeners()
   * Add listeners to the tab buttons, enabling a user to switch between them.
   */
  var topSitesButton = document.getElementById(TOP_SITES_BUTTON_ID);
  var pieChartButton = document.getElementById(PIE_CHART_BUTTON_ID);

  topSitesButton.addEventListener('click', function(){
    showHiddenContent(PIE_CHART_CONTENT_ID, TOP_SITES_CONTENT_ID,
                      topSitesButton, pieChartButton);
  });

  pieChartButton.addEventListener('click', function() {
    showHiddenContent(TOP_SITES_CONTENT_ID, PIE_CHART_CONTENT_ID,
                      pieChartButton, topSitesButton);
  })
}

var clearCurrentContents = function(targetNode) {
  /**
   * clearCurrentContents()
   * Clears the current contents of a provided node.
   * @param {element} targetNode A DOM node from which its children will be
   *     cleared.
   */
  var node = document.getElementById(targetNode);
  if (node) {
    while (node.firstChild) {
      node.removeChild(node.firstChild);
    }
  }
}

var addTimesliceListeners = function() {
  /**
   * addTimesliceListeners()
   * Listens to onchange events from the selectbox containing timeslices, and
   *     rebuilds the display according to what was selected.
   */
  var timesliceSelectBox = document.getElementById(TIMESLICE_SELECT_ID);
  timesliceSelectBox.onchange = function (e) {
    var selectedOption = this[this.selectedIndex];
    var selectedValue = selectedOption.value;
    var timesliceLabelDisplay = document.getElementById(TIME_LABEL_ID);
    timesliceLabelDisplay.innerHTML = selectedOption.innerText;
    targetNode = TOP_SITES_LIST_ID;
    clearCurrentContents(targetNode);
    buildHistoryItemList(selectedValue);
  }
}

var showHiddenContent = function(currentContent,
                                 targetContent,
                                 callingButton,
                                 currentButton) {
  /**
   * showHiddenContent()
   * Hides currently displayed content and shows another set of content.
   * @param {string} currentContent A string containing the ID of the content
   *     currently displayed.
   * @param {string} targetContent A string containing the ID of the content
   *     that should be displayed.
   * @param {element} callingButton A DOM element containing the object that was
   *     clicked and caused the event to fire.
   * @param {element} currentButton A DOM element containing the object that
   *     represents the currently active button.
   */
  var displayStyle = 'block';

  hideContent(currentContent, currentButton);

  var toShow = document.getElementById(targetContent);
  toShow.style.display = displayStyle;
  callingButton.style.borderBottomColor = ACTIVE_BACKGROUND_COLOR;
  callingButton.style.backgroundColor = ACTIVE_BACKGROUND_COLOR;
}

var hideContent = function(currentContent, currentButton) {
  /**
   * hideContent()
   * Hides a given content node, and updates its active button style.
   * @param {string} currentContent A string representign the ID of the current
   *     content displayed.
   * @param {element} currentButton A DOM element representing the currently
   *     active button.
   */
  var toHide = document.getElementById(currentContent);
  toHide.style.display = 'none';
  currentButton.style.borderBottomColor = BORDER_COLOR;
  currentButton.style.backgroundColor = DORMANT_BACKGROUND_COLOR;
}

var showLoadingIcon = function() {
  /**
   * showLoadingIcon()
   * Shows a loading icon while the API is being queried and content is being
   *     loaded.
   */
  var loadingIcon = document.getElementById(LOADING_ICON_ID);
  loadingIcon.style.display = 'block';
}

var hideLoadingIcon = function() {
  /**
   * hideLoadingIcon()
   * Hides the currently displayed loading icon after the API has returned and
   *     the results are ready to display.
   */
  var loadingIcon = document.getElementById(LOADING_ICON_ID);
  loadingIcon.style.display = 'none';
}

document.addEventListener('DOMContentLoaded', function () {
  /**
   * document.addEventListener()
   * Entry point into the code. Fires when the DOMContentLoaded event completes.
   */
  // add event listeners to elements
  addListeners();
  // begin querying the history API and setting up the page
  buildHistoryItemList();
});

<|endoftext|>


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

fs = require("fs");
_ = require("underscore");
glob = require("glob");
Q = require("q");

function get_files(glob_pattern) {
  deferred = Q.defer();
  glob(glob_pattern, {}, function(er, files) {
    deferred.resolve(files);
  });
  return deferred.promise;
}

function read_files(files) {
  var file_data = {};
  _.each(files, function(file) {
    var data = fs.readFileSync(file, "utf8");
    console.log(data);
    file_data[file] = data;
  });
  return file_data;
}

function main(argc, argv) {
  console.log(argv[2]);
  get_files(argv[2]).done(function(files) {
    console.log('files', files);
    file_data = read_files(files);
    console.log(JSON.stringify(file_data));
  });
}

if (require.main === module) {
  main(process.argv.length, process.argv);
}
<commit_msg>Removed destructive logs.<commit_after>#! /usr/bin/env node

fs = require("fs");
_ = require("underscore");
glob = require("glob");
Q = require("q");

function get_files(glob_pattern) {
  deferred = Q.defer();
  glob(glob_pattern, {}, function(er, files) {
    deferred.resolve(files);
  });
  return deferred.promise;
}

function read_files(files) {
  var file_data = {};
  _.each(files, function(file) {
    var data = fs.readFileSync(file, "utf8");
    file_data[file] = data;
  });
  return file_data;
}

function main(argc, argv) {
  get_files(argv[2]).done(function(files) {
    file_data = read_files(files);
    console.log(JSON.stringify(file_data));
  });
}

if (require.main === module) {
  main(process.argv.length, process.argv);
}
<|endoftext|>