text:
Q: Paging for D3 tree child nodes I am trying to implement paging in d3 tree. Can anyone please help me with the same.
Please find below my code with screenshots of current and expected output.
The data_tree is the input data variable. This gets read by script below and produces hierarchy tree as showed in screenshot

data_tree = {
  "Type": "Root",
  "id": 0,
  "name": "ERM",
  "ParentDocType": "EnterpriseWide",
  "children": [{
    "Type": "Stem",
    "id": 4,
    "name": "RG",
    "ParentDocType": "EnterpriseWide",
    "children": [{
        "Type": "Stem",
        "id": 5,
        "name": "WCR F",
        "ParentDocType": "WholesaleCreditRisk",
        "children": [{
          "Type": "Stem",
          "id": 50,
          "name": "WCR P",
          "ParentDocType": "WholesaleCreditRisk",
          "children": [{
              "Type": "Leaf",
              "id": 8,
              "name": "IBQA SD",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 9,
              "name": "WCR EMS",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 28,
              "name": "WCR DD & RGEC",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 29,
              "name": "PMM",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 30,
              "name": "PRRM",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 31,
              "name": "WCR Rep",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 32,
              "name": "RR",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 33,
              "name": "CO",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 34,
              "name": "LD",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 35,
              "name": "ESRM",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 36,
              "name": "TPCR",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 37,
              "name": "InterA",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 38,
              "name": "DR",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 39,
              "name": "MAR",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 40,
              "name": "BSLM",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 51,
              "name": "CCR Meas",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 52,
              "name": "WLP",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 53,
              "name": "TTS Pro",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 54,
              "name": "CI",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 55,
              "name": "LL",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 56,
              "name": "SP",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 57,
              "name": "CC",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 58,
              "name": "CRE",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 59,
              "name": "Sec",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            },
            {
              "Type": "Leaf",
              "id": 60,
              "name": "SS",
              "ParentDocType": "WholesaleCreditRisk",
              "children": [

              ]
            }
          ]
        }]
      },
      {
        "Type": "Stem",
        "id": 10,
        "name": "GCMP",
        "ParentDocType": "EnterpriseWide",
        "children": [{
          "Type": "Leaf",
          "id": 11,
          "name": "WCR CMS",
          "ParentDocType": "WholesaleCreditRisk",
          "children": [

          ]
        }]
      },
      {
        "Type": "Stem",
        "id": 12,
        "name": "REAVP",
        "ParentDocType": "EnterpriseWide",
        "children": [{
          "Type": "Stem",
          "id": 13,
          "name": "CREAVS",
          "ParentDocType": "WholesaleCreditRisk",
          "children": [{
            "Type": "Leaf",
            "id": 14,
            "name": "CREAVP",
            "ParentDocType": "WholesaleCreditRisk",
            "children": [

            ]
          }]
        }]
      }
    ]
  }]
};

var margin = {
    top: 20,
    right: 120,
    bottom: 20,
    left: 120
  },
  width = 960 - margin.right - margin.left,
  height = 800 - margin.top - margin.bottom;

var root =JSON.parse(data_tree);

var i = 0,
  duration = 750,
  rectW = 150,
  rectH = 50;

//var tree = d3.layout.tree().nodeSize([70, 40]);

var nodeWidth = 150;
var nodeHeight = 50;
var horizontalSeparationBetweenNodes = 16;
var verticalSeparationBetweenNodes = 128;

var tree = d3.layout.tree()
  .nodeSize([nodeWidth + horizontalSeparationBetweenNodes, nodeHeight + verticalSeparationBetweenNodes])
  .separation(function(a, b) {
    return a.parent == b.parent ? 1 : 1.25;
  });

/*var diagonal = d3.svg.diagonal()
    .projection(function (d) {
    return [d.x + rectW / 2, d.y + rectH / 6];
});*/

var diagonal = d3.svg.diagonal()
  .target(function(d) {
    var o = d.target;
    o.y = o.y - 50
    return o;
  })
  .projection(function(d) {
    return [d.x + rectW / 2, d.y + rectH];
  });

var svg = d3.select("#body").append("svg").attr("width", document.getElementById("body").style.width).attr("height", document.getElementById("body").style.height)
  .call(zm = d3.behavior.zoom().scaleExtent([0.5, 3]).on("zoom", redraw)).append("g")
  .attr("transform", "translate(" + 650 + "," + 20 + ")scale(0.7)");

//necessary so that zoom knows where to zoom and unzoom from
zm.translate([650, 20]);

root.x0 = 0;
root.y0 = height / 2;

d3.select("#myCheckbox").on("change", enableLink);

enableLink(root);

d3.select("#body").style("height", "800px");

function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
      words = text.text().split(/\s+/).reverse(),
      word,
      line = [],
      lineNumber = 0,
      lineHeight = 1.1, // ems
      x = text.attr("x"),
      y = text.attr("y"),
      dy = 0, //parseFloat(text.attr("dy")),
      tspan = text.text(null)
      .append("tspan")
      .attr("x", x)
      .attr("y", y)
      .attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan")
          .attr("x", x)
          .attr("y", y)
          .attr("dy", ++lineNumber * lineHeight + dy + "em")
          .text(word);
      }
    }
  });
}

function enableLink(source) {

  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse(),
    links = tree.links(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d) {
    d.y = d.depth * 125;

  });

  // Update the nodes…

  var node = svg.selectAll("g.node")
    .data(nodes, function(d) {
      return d.id || (d.id = ++i);
    });

  // Enter any new nodes at the parent's previous position.

  var nodeEnter = node.enter().append("g")
    .attr("class", "node")
    .attr("transform", function(d) {
      return "translate(" + source.x0 + "," + source.y0 + ")";
    }).on("click", click);

  nodeEnter.append("rect")
    .attr("width", rectW)
    .attr("height", rectH)
    .attr("stroke", "blue")
    .attr("rx", 4)
    .attr("ry", 4)
    .attr("stroke-width", 2)
    .style("fill", function(d) {
      if (d.ParentDocType == "EnterpriseWide") return "darkblue";
      if (d.ParentDocType == "WholesaleCreditRisk") return "blue";

      return d._children ? "lightsteelblue" : "#fff";
    });

  nodeEnter.append("text")
    .attr("x", rectW / 2)
    .attr("y", rectH / 2)
    .attr("dy", ".35em")
    .attr("text-anchor", "middle")
    .text(function(d) {
      return d.name;
    }).call(wrap, rectW - 10);

  nodeEnter
    .append("a")
    .attr("xlink:href", function(d) {
      return d.url;
    });

  // Transition nodes to their new position.
  var nodeUpdate = node.transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + d.x + "," + d.y + ")";
    });

  nodeUpdate.select("rect")
    .attr("width", rectW)
    .attr("height", rectH)
    .attr("stroke", "blue")
    .attr("stroke-width", 2)
    .style("fill", function(d) {
      if (d.ParentDocType == "EnterpriseWide") return "darkblue";
      if (d.ParentDocType == "WholesaleCreditRisk") return "blue";
      return d._children ? "lightsteelblue" : "#fff";
    });

  nodeUpdate.select("text")
    .style("fill-opacity", 1);

  // Transition exiting nodes to the parent's new position.
  var nodeExit = node.exit().transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + source.x + "," + source.y + ")";
    })
    .remove();

  nodeExit.select("rect")
    .attr("width", rectW)
    .attr("height", rectH)
    //.attr("width", bbox.getBBox().width)""
    //.attr("height", bbox.getBBox().height)
    .attr("stroke", "blue")
    .attr("stroke-width", 2);

  nodeExit.select("text");

  // Update the links…
  var link = svg.selectAll("path.link")
    .data(links, function(d) {
      d.y = d.y + 100;
      return d.target.id;
    });

  // Enter any new links at the parent's previous position.
  link.enter().insert("path", "g")
    .attr("class", "link")
    .attr("d", function(d) {
      var o = {
        x: source.x0,
        y: source.y0 + 100
      };
      return diagonal({
        source: o,
        target: o
      });
    });

  // Transition links to their new position.
  link.transition()
    .duration(duration)
    .attr("d", diagonal);

  // Transition exiting nodes to the parent's new position.
  link.exit().transition()
    .duration(duration)
    .attr("d", function(d) {
      var o = {
        x: source.x,
        y: source.y
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .remove();

  // Stash the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y + 100;
  });

}
// Toggle children on click.
function click(d) {

    if (d.children) {
      d._children = d.children;
      d.children = null;
    } else {
      d.children = d._children;
      d._children = null;
    }
    enableLink(d);

}

//Redraw for zoom
function redraw() {
  //console.log("here", d3.event.translate, d3.event.scale);
  svg.attr("transform",
    "translate(" + d3.event.translate + ")" +
    " scale(" + d3.event.scale + ")");
}
.node {
  cursor: pointer;
}

.node circle {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 1.5px;
}

.node text {
  font: 10px sans-serif;
  fill: white;
}

.link {
  fill: none;
  stroke: #ccc;
  stroke-width: 1.5px;
}

body {
  overflow: hidden;
}

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-color: #2196F3;
}

input:focus+.slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

.box {
  float: left;
  height: 20px;
  width: 20px;
  margin-bottom: 15px;
  border: 1px solid black;
}

.darkblue {
  background-color: darkblue;
}

.blue {
  background-color: blue;
}

Current output
Expected output

A:

var root = {
  "Type": "Root",
  "id": 0,
  "name": "ERM",
  "ParentDocType": "EnterpriseWide",
  "children": [{
    "Type": "Stem",
    "id": 4,
    "name": "RG",
    "ParentDocType": "EnterpriseWide",
    "children": [{
        "Type": "Stem",
        "id": 5,
        "name": "WCR F",
        "ParentDocType": "WholesaleCreditRisk",
        "children": [{
          "Type": "Stem",
          "id": 50,
          "name": "WCR P",
          "ParentDocType": "WholesaleCreditRisk",
          "children": [{
              "Type": "Leaf",
              "id": 8,
              "name": "IBQA SD",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 9,
              "name": "WCR EMS",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 28,
              "name": "WCR DD & RGEC",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 29,
              "name": "PMM",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 30,
              "name": "PRRM",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 31,
              "name": "WCR Rep",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 32,
              "name": "RR",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 33,
              "name": "CO",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 34,
              "name": "LD",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 35,
              "name": "ESRM",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 36,
              "name": "TPCR",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 37,
              "name": "InterA",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 38,
              "name": "DR",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 39,
              "name": "MAR",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 40,
              "name": "BSLM",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 51,
              "name": "CCR Meas",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 52,
              "name": "WLP",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 53,
              "name": "TTS Pro",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 54,
              "name": "CI",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 55,
              "name": "LL",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 56,
              "name": "SP",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 57,
              "name": "CC",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 58,
              "name": "CRE",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 59,
              "name": "Sec",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            },
            {
              "Type": "Leaf",
              "id": 60,
              "name": "SS",
              "ParentDocType": "WholesaleCreditRisk",
              "children": []
            }
          ]
        }]
      },
      {
        "Type": "Stem",
        "id": 10,
        "name": "GCMP",
        "ParentDocType": "EnterpriseWide",
        "children": [{
          "Type": "Leaf",
          "id": 11,
          "name": "WCR CMS",
          "ParentDocType": "WholesaleCreditRisk",
          "children": []
        }]
      },
      {
        "Type": "Stem",
        "id": 12,
        "name": "REAVP",
        "ParentDocType": "EnterpriseWide",
        "children": [{
          "Type": "Stem",
          "id": 13,
          "name": "CREAVS",
          "ParentDocType": "WholesaleCreditRisk",
          "children": [{
            "Type": "Leaf",
            "id": 14,
            "name": "CREAVP",
            "ParentDocType": "WholesaleCreditRisk",
            "children": []
          }]
        }]
      }
    ]
  }]
};

function pageNodes(d) {
  if (d.children) {
    d.children.forEach(c => pageNodes(c));
    if (d.children.length > pageNodes.maxNode) {
      d.pages = {}
      const count = pageNodes.maxNode - 1;
      const l = Math.ceil(d.children.length / count);
      for (let i = 0; i < l; i++) {
        let startRange = i * count;
        let endRange = i * count + count;
        d.pages[i] = d.children.slice(startRange, endRange);
        pageNodes.addNode(d.pages[i], "More...", {
          __next: i != (l - 1) ? i + 1 : 0,
        });
      }
      d.children = d.pages[0];
    }
  }
}

pageNodes.maxNode = 5;

pageNodes.addNode = function(children, name, more) {
  let node = Object.assign({
    Type: "Leaf",
    id: children[children.length - 1].id + 10000,
    ParentDocType: children[children.length - 1].ParentDocType,
    name: name,
  }, more);
  children.push(node);
};

root.children.forEach(c => pageNodes(c));

var margin = {
    top: 20,
    right: 120,
    bottom: 20,
    left: 120
  },
  width = window.innerWidth - margin.right - margin.left,
  height = window.innerHeight - margin.top - margin.bottom;

var i = 0,
  duration = 750,
  rectW = 150,
  rectH = 50;

// var tree = d3.layout.tree().nodeSize([70, 40]);

var nodeWidth = 150;
var nodeHeight = 50;
var horizontalSeparationBetweenNodes = 16;
var verticalSeparationBetweenNodes = 128;

var tree = d3.layout.tree()
  .nodeSize([nodeWidth + horizontalSeparationBetweenNodes, nodeHeight + verticalSeparationBetweenNodes])
  .separation(function(a, b) {
    return a.parent == b.parent ? 1 : 1.25;
  });

/*var diagonal = d3.svg.diagonal()
    .projection(function (d) {
    return [d.x + rectW / 2, d.y + rectH / 6];
});*/

var diagonal = d3.svg.diagonal()
  .target(function(d) {
    var o = d.target;
    o.y = o.y - 50
    return o;
  })
  .projection(function(d) {
    return [d.x + rectW / 2, d.y + rectH];
  });

var svg = d3.select("#body").append("svg").attr("width", document.getElementById("body").style.width).attr("height", document.getElementById("body").style.height)
  .call(zm = d3.behavior.zoom().scaleExtent([0.5, 3]).on("zoom", redraw)).append("g")
  .attr("transform", "translate(" + 650 + "," + 20 + ")scale(0.7)");

//necessary so that zoom knows where to zoom and unzoom from
zm.translate([650, 20]);

root.x0 = 0;
root.y0 = height / 2;

d3.select("#myCheckbox").on("change", enableLink);

enableLink(root);

d3.select("#body").style("height", "800px");

function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
      words = text.text().split(/\s+/).reverse(),
      word,
      line = [],
      lineNumber = 0,
      lineHeight = 1.1, // ems
      x = text.attr("x"),
      y = text.attr("y"),
      dy = 0, //parseFloat(text.attr("dy")),
      tspan = text.text(null)
      .append("tspan")
      .attr("x", x)
      .attr("y", y)
      .attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (tspan.node().getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan")
          .attr("x", x)
          .attr("y", y)
          .attr("dy", ++lineNumber * lineHeight + dy + "em")
          .text(word);
      }
    }
  });
}

function enableLink(source) {

  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse(),
    links = tree.links(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d) {
    d.y = d.depth * 125;

  });

  // Update the nodes…

  var node = svg.selectAll("g.node")
    .data(nodes, function(d) {
      return d.id || (d.id = ++i);
    });

  // Enter any new nodes at the parent's previous position.

  var nodeEnter = node.enter().append("g")
    .attr("class", "node")
    .attr("transform", function(d) {
      return "translate(" + source.x0 + "," + source.y0 + ")";
    }).on("click", click);

  nodeEnter.append("rect")
    .attr("width", rectW)
    .attr("height", rectH)
    .attr("stroke", "blue")
    .attr("rx", 4)
    .attr("ry", 4)
    .attr("stroke-width", 2)
    .style("fill", function(d) {
      if (d.ParentDocType == "EnterpriseWide") return "darkblue";
      if (d.ParentDocType == "WholesaleCreditRisk") return "blue";

      return d._children ? "lightsteelblue" : "#fff";
    });

  nodeEnter.append("text")
    .attr("x", rectW / 2)
    .attr("y", rectH / 2)
    .attr("dy", ".35em")
    .attr("text-anchor", "middle")
    .text(function(d) {
      return d.name;
    }).call(wrap, rectW - 10);

  nodeEnter
    .append("a")
    .attr("xlink:href", function(d) {
      return d.url;
    });

  // Transition nodes to their new position.
  var nodeUpdate = node.transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + d.x + "," + d.y + ")";
    });

  nodeUpdate.select("rect")
    .attr("width", rectW)
    .attr("height", rectH)
    .attr("stroke", "blue")
    .attr("stroke-width", 2)
    .style("fill", function(d) {
      if (d.ParentDocType == "EnterpriseWide") return "darkblue";
      if (d.ParentDocType == "WholesaleCreditRisk") return "blue";
      return d._children ? "lightsteelblue" : "#fff";
    });

  nodeUpdate.select("text")
    .style("fill-opacity", 1);

  // Transition exiting nodes to the parent's new position.
  var nodeExit = node.exit().transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + source.x + "," + source.y + ")";
    })
    .remove();

  nodeExit.select("rect")
    .attr("width", rectW)
    .attr("height", rectH)
    //.attr("width", bbox.getBBox().width)""
    //.attr("height", bbox.getBBox().height)
    .attr("stroke", "blue")
    .attr("stroke-width", 2);

  nodeExit.select("text");

  // Update the links…
  var link = svg.selectAll("path.link")
    .data(links, function(d) {
      d.y = d.y + 100;
      return d.target.id;
    });

  // Enter any new links at the parent's previous position.
  link.enter().insert("path", "g")
    .attr("class", "link")
    .attr("d", function(d) {
      var o = {
        x: source.x0,
        y: source.y0 + 100
      };
      return diagonal({
        source: o,
        target: o
      });
    });

  // Transition links to their new position.
  link.transition()
    .duration(duration)
    .attr("d", diagonal);

  // Transition exiting nodes to the parent's new position.
  link.exit().transition()
    .duration(duration)
    .attr("d", function(d) {
      var o = {
        x: source.x,
        y: source.y
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .remove();

  // Stash the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y + 100;
  });
}
// Toggle children on click.
function click(d) {
  if (d.hasOwnProperty('__next')) {
    d.parent.children = d.parent.pages[d.__next];
  } else if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  enableLink(d);
}

//Redraw for zoom
function redraw() {
  //console.log("here", d3.event.translate, d3.event.scale);
  svg.attr("transform",
    "translate(" + d3.event.translate + ")" +
    " scale(" + d3.event.scale + ")");
}
.node {
  cursor: pointer;
}

.node circle {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 1.5px;
}

.node text {
  font: 10px sans-serif;
  fill: white;
}

.link {
  fill: none;
  stroke: #ccc;
  stroke-width: 1.5px;
}

body {
  overflow: hidden;
}

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked+.slider {
  background-color: #2196F3;
}

input:focus+.slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

.box {
  float: left;
  height: 20px;
  width: 20px;
  margin-bottom: 15px;
  border: 1px solid black;
}

.darkblue {
  background-color: darkblue;
}

.blue {
  background-color: blue;
}


text:
Q: C++ double returning a 0 instead of 0.1 So I'm trying my hand at C++ again and I'm writing a function that keeps giving the wrong value.
I've boiled it down to a line basically this: double testD = (10/100); that gives me 0 instead of 0.1.
I might have missed something major but I thought double held decimal values? For the life of me I can't get this to be correct.
Please help me (even if I'm terribly stupid).

A: 10 and 100 are integers. This will result in integer division, which will evaluate to 0. That 0 will then be stored in testD.
To force floating-point division cast one of the numbers to float or double.
((double)whatever)/something

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java Heap Space error in glassfish I am using a fresh Glassfish install with very little customizations.
I have a Message Driven Bean (ObjectUpdateMDB) that listens to a topic, then updates the object it receives in a database.  There are a lot of objects being updated.  After a while of running I get this exception:

SEVERE: JTS5031: Exception [org.omg.CORBA.INTERNAL:   vmcid: 0x0  minor code: 0 completed: Maybe] on Resource [rollback] operation.
SEVERE: MDB00049: Message-driven bean [Persistence:ObjectUpdateMDB]: Exception in postinvoke : [javax.transaction.SystemException: org.omg.CORBA.INTERNAL: JTS5031: Exception [org.omg.CORBA.INTERNAL:   vmcid: 0x0  minor code: 0 completed: Maybe] on Resource [rollback] operation.  vmcid: 0x0  minor code: 0  completed: No]
SEVERE: javax.transaction.SystemException
javax.transaction.SystemException: org.omg.CORBA.INTERNAL: JTS5031: Exception [org.omg.CORBA.INTERNAL:   vmcid: 0x0  minor code: 0 completed: Maybe] on Resource [rollback] operation.  vmcid: 0x0  minor code: 0  completed: No
    at com.sun.jts.jta.TransactionManagerImpl.rollback(TransactionManagerImpl.java:350)
    at com.sun.enterprise.distributedtx.J2EETransactionManagerImpl.rollback(J2EETransactionManagerImpl.java:1144)
    at com.sun.enterprise.distributedtx.J2EETransactionManagerOpt.rollback(J2EETransactionManagerOpt.java:426)
    at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:3767)
    at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:3571)
    at com.sun.ejb.containers.MessageBeanContainer.afterMessageDeliveryInternal(MessageBeanContainer.java:1226)
    at com.sun.ejb.containers.MessageBeanContainer.afterMessageDelivery(MessageBeanContainer.java:1197)
    at com.sun.ejb.containers.MessageBeanListenerImpl.afterMessageDelivery(MessageBeanListenerImpl.java:79)
    at com.sun.enterprise.connectors.inflow.MessageEndpointInvocationHandler.invoke(MessageEndpointInvocationHandler.java:139)
    at $Proxy98.afterDelivery(Unknown Source)
    at com.sun.messaging.jms.ra.OnMessageRunner.run(OnMessageRunner.java:324)
    at com.sun.enterprise.connectors.work.OneWork.doWork(OneWork.java:76)
    at com.sun.corba.ee.impl.orbutil.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:555)

INFO: MDB00037: [Persistence:ObjectUpdateMDB]: Message-driven bean invocation exception: [java.lang.OutOfMemoryError: Java heap space]
INFO: java.lang.OutOfMemoryError
java.lang.OutOfMemoryError: Java heap space

Looks like it is an issue with Heap Space.  What do I need to adjust the heap space for?  The App Server itself or the Broker?  How do I do this?

A: You need to assign more RAM to your Glassfish  installation.
See http://spaquet.blogspot.com/2006/07/liferay-glassfish-part-ii-configuring.html
and http://docs.sun.com/app/docs/doc/820-4495/gepzd?a=view.

A: I have used the following asadmin commands to sort the problem on Glassfish 3.1:
asadmin create-jvm-options --target server-config -- '-XX\:+UnlockExperimentalVMOptions'
asadmin create-jvm-options --target server-config -- '-XX\:+UseG1GC'
asadmin delete-jvm-options --target server-config -- '-Xmx512m'
asadmin create-jvm-options --target server-config -- '-Xmx1024m'
asadmin delete-jvm-options --target server-config -- '-XX\:MaxPermSize=192m'
asadmin create-jvm-options --target server-config -- '-XX\:MaxPermSize=256m'

asadmin create-jvm-options --target default-config -- '-XX\:+UnlockExperimentalVMOptions'
asadmin create-jvm-options --target default-config -- '-XX\:+UseG1GC'
asadmin delete-jvm-options --target default-config -- '-Xmx512m'
asadmin create-jvm-options --target default-config -- '-Xmx1024m'
asadmin delete-jvm-options --target default-config -- '-XX\:MaxPermSize=192m'
asadmin create-jvm-options --target default-config -- '-XX\:MaxPermSize=256m'

It is a variation on Michael Myers hint. Using asadmin commands makes the change easily repeatable.
Also I switched to the new G1 collector which is a lot better then the normal collector. Helps with Eclipse as well ;-)
Note that syntax is for TakeCommand on Windows. If you use a different combination of shell and OS you might need different escape characters (i.E. strait ticks instead of backticks for most unix shells).
If you mess your setup up with the *-jvm-options commands then you can fix it with domain.xml file.

A: I have a post on my blog about VM tuning and I'm pointing readers to the Java Tuning White Paper.
Anyways, to get you a quick answer you should probably look into a couple of basic settings:
-Xms: initial heap size
-Xmx: maximum heap size
To get a quick descriptions for these just run: java -X.
./alex

A: I don't know if this is related, but we got some strange exceptions when using XA Transactions which resulted in CORBA exceptions. The reason was the MySQL driver and we upgraded to the latest MySQL JDBC driver (5.1.7) and then these XA problems disappeared.


text:
Q: Timer Event in Bash I have a bash script that runs indefinitely. I've searched high and low for a solution to add a timed event into the script that fires every 5 minutes, while the rest of the script keeps running. I can not have the script sleep, as it is constantly sending/receiving information to the server. Does anyone have any function or idea that will accomplish this. Basically I want it to send a specific command to the server every 300 seconds(5 minutes). I do not have access to make rewrite the server code to request the command every 5 minutes.
Basically the main script is similar to this:
#!/bin/bash

Var1="localhost"
Var2="2356"
Var3="DSDSASAQ"
Var4= "Admin"
#other variables as needed.

function fun1(){
#do some stuff
}
function fun2(){
#do some stuff
}
function fun3(){
#do some stuff
}

#Main code section.
exec 3<>/dev/tcp/${Var1}/${Var2}
echo "login Var4 Var3" >&3

While read LINE <&3;
do
#do some stuff
done
exit $?

Any help is appreciated. Also I have tried stuff like start=$SECONDS and duration=$SECONDS-$start and checked with if...then statements in the while loop, but it tends to fire the command off multiple times before it resets the start variable....the server likes to break link when it detects spam as well, so sending the same command that 10+ times in a short burst is not ideal.

A: Run a loop in a separate background process.
#!/bin/bash

...

#Main code section.
exec 3<>/dev/tcp/${Var1}/${Var2}

# watchdog
while sleep 300 & wait; do
  echo "login Var4 Var3"
done >&3 &
trap "kill $!" EXIT

while read LINE <&3;
do
#do some stuff
done
exit $?

A: I think you tried out wrong if...then condition.
Here is my shot at it ... and it should send the "special command" only once at the required time.
#!/bin/bash

# Set the "next time" when special command should be sent
((start=SECONDS+300))

while read LINE <&3; do
    echo "do some stuff"

    # Did we reach the "next time" ... if yes
    if ((SECONDS>=start)); then
        echo "special command"
        # And now set the new "next time"
        ((start=SECONDS+300))
    fi
done

A: There are many ways you could do this, cron, watch, or even while sleep, all come to mind.
watch
watch -n300 command

while sleep
while sleep 300; do command; done

cron
* * * * * sleep 300; command

There are other ways, but one of these methods likely would work in regards to your question.


text:
Q: Regarding integer memory allocation If the memory allocated to an integer has a limit (say 2 bytes in C or 4 bytes or 8 bytes) in any language. How does it matter to compile the code on 32-bit or 64-bit machine using 32-bit or 64-bit compiler. Please forgive me if it is really trivial question. But please leave an answer.

A: If you are using fixed-size integer types (like int8_t or int16_t) then whether you target a 32- or 64-bit platform doesn't matter much.
One of the things that does matter is the size of pointers.  All pointers are 32 bits when targeting a 32-bit architecture, and 64 bits when targeting a 64-bit architecture.
It used to be rather common to store pointer values in an int, though this practice has become very discouraged for portability reasons, and the 32/64-bit case is a great example.  If you store a pointer in an int, then your code will invoke undefined behavior on 64-bit architectures, as you truncated a pointer.  When you would go to extract the pointer, you'd dereference it likely crash, or (worse) proceed with invalid data.

A: There are several reasons why you have to compile different executables between 32-bit and 64-bit machines - the size of an int might not be a factor, or it might, since the C standard only defines minimums and relative sizes - there is no maximum size of an int so far as I know (provided it is not longer than a long).
The size of a pointer is a major difference.  The compiler and linker produce a different layout of executable file between 32 and 64 bit process address spaces.  The runtime libraries are different, and dynamically linked libaries (shared objects on UNIX) have to share the same size pointers, otherwise they cannot interact with the rest of the process.
Why use 64-bit?  What is the advantage of 64-bit over 32-bit?  The main advantage is the maximum size of a pointer, and hence process-address space.  On 32-bit this is 4GB, on 64-bit it is 16EB (about 16,000 terabytes).

A: If you have a look at this page, you can see that the basic types in C have certain guaranteed minimum sizes. So, you will not find a compliant C implementation where int is 2 bits, it has to be at least 16.
Differences between platforms makes porting software into the interesting challenge it often is.
If you have code that assumes things about basic data types that are not guaranteed to be true (for instance, code that does something like this: int x = 0xfeedf00d;), then that code will not be portable. It will break, in various often hard to predict ways, when compiled on a platform that doesn't match the assumptions. For instance, on a platform where int is 16 bits, the above code would leave x set to some different value from what the programmer intended.

A: For the most part the word size affects performance and stack usage.  It's fastest to work with whatever the word size is for a given architecture.  If you define two 32 bit integers, one right after the other, on a 64 bit machine, one will be on a word boundary and the other won't.  It takes less processing to get the one on the word boundary into a register than the one that's not on a word boundary.  On the other hand, if you have a 64 bit integer defined on a 32 bit machine, it will take two fetches to get the two words and some funky register manipulation to perform integer operations on it.  The last part has to do with the stack.  The stack is always made up of words.  If the machine's word size is 32 bit, the stack will be a stack of 32 bit values, and on a 64 bit machine they are 64 bit values.  Not that you really care that much, but a 32 bit integer will be placed in a 64 bit word on the stack, and a 64 bit value, unless you're pushing a pointer to the value, will take up two words on the stack.
If you select word-alignment in your compiler, it will automatically put all variable on a word boundary.  This is much faster, but takes up a bit more space.  Unless you're really pressed for space, you should go for the performance.  Not that it's that big a difference on a CISC architecture.  On RISC it made a huge difference.
Does that help?


text:
Q: Как уменьшить таблицу HTML, CSS У меня таблица растянулась как можно ее уменьшить, чтобы прямо по центру. И ширина была не большая как указал стрелками на картинке.

Вот мои коды
AllStudentsAdmin.JSP
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta name="keywords" content="" />
    <meta name="description" content="" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

    <link href="../css/style.css" rel="stylesheet" type="text/css">

    <title>Все студенты</title>

Список всех студентов

    ${message}

            #
            Name

            Surname
            Avatar

        <c:forEach var="student" items="${studentList}">

                1
                ${student.name}
                ${student.surname}

                    <c:if test="${empty student.avatar}">

                    </c:if>
                    <c:if test="${not empty student.avatar}">

                    </c:if>

        </c:forEach>


text:
Q: SMTP ERROR: (552, '5.6.0 Submission denied Sender does not match originator ) I've writted a Python script to send emails via a relay server. I've tested that the appropriate email address's etc are permissioned etc by sending an email using Telnet. My Python script also work when set up to send via my old relay server.
Therefore i am confused as to why i am getting the following error message:
 (552, '5.6.0 Submission denied Sender does not match originator <myEmailAddress>)

I've looked at the SMTP error 552 and it is caused by the message size being exceeded, but i am only sending an email containing a few lines of html which is only a few kb in size so i'm assuming i can safely rule this issue out.
Any other ideas as to what could be the issue?
EDIT:
Here is the Python code which generates the error.
1 #!/usr/bin/env python
  2 import sys
  3 from sys import argv
  4 import smtplib
  5 import logging
  6 import logging.handlers
  7
  8 LOG_FILENAME = 'sendMail.log'
  9 inputMessage = argv[1]
 10 sender = 'hi@sender.com'
 11 receivers = 'hi@sender.com'
 12 #Reads in the file as a single string
 13 message = open(inputMessage, 'r').read()
 14 log = logging.getLogger()
 15
 16 def initializelogging():
 17     log.setLevel(logging.DEBUG)
 18     fileformatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
 19     filehandler = logging.handlers.RotatingFileHandler(
 20                   LOG_FILENAME,
 21                   maxBytes=10000000,
 22                   backupCount=100)
 23     filehandler.setFormatter(fileformatter)
 24     consoleformatter = logging.Formatter('%(levelname)s: %(message)s')
 25     consolehandler = logging.StreamHandler()
 26     consolehandler.setLevel(logging.INFO)
 27     consolehandler.setFormatter(consoleformatter)
 28     log.addHandler(filehandler)
 29     log.addHandler(consolehandler)
 30 initializelogging()
 31
 32 def sendMail():
 33     try:
 34
 35         smtpObj = smtplib.SMTP('mailserver@server.com')
 36         smtpObj.sendmail(sender,sender, message)
 37         print "Successfully sent email"
 38         log.info('Successfully sent email')
 39     except Exception, err:
 40         log.error('Unable to send email. See below stack trace........')
 41         log.error('%s\n' % str(err))
 42 sendMail()

A: I can't guarantee that either of these is the actual cause of the error, but:

*

*I think the message you're getting might be saying that the From: header in your message doesn't match the e-mail address you are using for the sender in the sendmail() call. Make sure that the message you are reading from the file a) has valid SMTP headers (at least From, To, and Subject, and MIME-Version and Content-Type wouldn't hurt) and more specifically b) has a From: hi@sender.com header.

*The instantiation for a SMTP object takes a server address, not an e-mail address. You should be using smtpObj = smtplib.SMTP('mail.server.com') or something else without so much @ in it. Otherwise, it may not be connecting to the server you think it is.


text:
Q: Javascript iterations - keep same number until next run I have the following HTML
<form action="sendform.php" method="post" id="monogramming-builder">
  <fieldset>

        Qty
        Colour
        Size
        Name
        Remaining
        Remove

        <input type="text" name="qty1" />

          <select name="colour1">
            <option value="">[Please Select]</option>
            <option value="Red">Red</option>
            <option value="Black">Black</option>
            <option value="White">White</option>
          </select>

          <select name="size1">
            <option value="">[Please Select]</option>
            <option value="Small">Small</option>
            <option value="Medium">Medium</option>
            <option value="Large">Large</option>
            <option value="XL">XL</option>
            <option value="2XL">2XL</option>
          </select>

        <input type="text" name="name1" />
        18
        Remove Row

Add a row

  </fieldset>
</form>

When the .addrow link is clicked, I want a new row to be added, but for each of the names, I want to add 1 to them. I have the following javascript:
var x = 2;
var tablerow = '
<input type="text" name="qty'+ x++ +'" />	<select name="colour'+ x++ +'"><option value="">[Please Select]</option><option value="Red">Red</option><option value="Black">Black</option><option value="White">White</option></select>	<select name="colour'+ x++ +'"><option value="">[Please Select]</option><option value="Small">Small</option><option value="Medium">Medium</option><option value="Large">Large</option><option value="XL">XL</option><option value="2XL">2XL</option></select>	<input type="text" name="name'+ x++ +'" />	18	Remove Row
';

$('.addrow').click(function(){
  $('tr:last-child').after(tablerow);
});

Obviously this is incrementing up to 5 by the end.
My question is, can the increment only be run after the whole row's been added?

A: You are incrementing x each time you write x++. Remove ++ from first occurances of x, and leave it x++ only after the last one.
For example, if you use the string : "b" + x++ + "b" + x++ + "b" + x++ , you will increment x three times, but if you are using it like "b" + x + "b" + x + "b" + x++ , you increment x only once.

A: so you want to increase x after each time the click fires and a row is added so:
var x = 2;

$('.addrow').click(function(){
  var tablerow = '
<input type="text" name="qty'+ x +'" />	<select name="colour'+ x +'"><option value="">[Please Select]</option><option value="Red">Red</option><option value="Black">Black</option><option value="White">White</option></select>	<select name="colour'+ x +'"><option value="">[Please Select]</option><option value="Small">Small</option><option value="Medium">Medium</option><option value="Large">Large</option><option value="XL">XL</option><option value="2XL">2XL</option></select>	<input type="text" name="name'+ x +'" />	18	Remove Row
';
  $('tr:last-child').after(tablerow);
  x++;
});

A: tablerow is a string, created prior to the row being added, so to answer your question literally, the answer is "no".
However, answering what I believe to be the spirit of your question, the answer is "yes", you have a number of options.
var x = 1
var mystring = "a" + x + "b" + x;  //mystring = a1b1
x = x + 1
mystring = "c" + x + d + x;  //mystring = c2d2
mystring = "e" + (++x) + "f" + x; // mystring = e3f3


text:
Q: How do I delete the first and only commit if it's the only commit in the branch? I goofed the author info. up on the first commit.
However, it seems like most of the rebase or tree modification operations rely on some other commit already existing.
Even when I run Git's interactive rebase command, all I see in my little list of commits is a single line, "noop". :/ (Solved this by running my rebase against the Git tree's root with git rebase -i --root, but removing the line for the first commit I made did not actually remove it from the tree.)
Rebasing on top of root, or the first commit, does not work.
[vagrant@localhost vagrant]$ git rebase -i HEAD~1
fatal: Needed a single revision
invalid upstream HEAD~1
[vagrant@localhost vagrant]$ git rebase -i HEAD
Unknown command: rnoop
Please fix this using 'git rebase --edit-todo'.
[vagrant@localhost vagrant]$ git rebase --edit-todo
[vagrant@localhost vagrant]$ git rebase --abort

The following looked like a relevant possible alternative answer, but I think something more, or at least more specific, is worth an answer for this special case:
Delete commits from a branch in Git
This other answer (How do you undo the last commit?) resulted in the following:
[vagrant@localhost vagrant]$ git reset --soft HEAD~
fatal: ambiguous argument 'HEAD~': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
[vagrant@localhost vagrant]$ git reset --soft HEAD

Here, for those still reading this, is the vim buffer with noop I mentioned earlier:
noop

# Rebase 3d1c632..3d1c632 onto 3d1c632 (1 command(s))
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

For those wondering why I don't just edit the files and re-add them to the commit, or something, I had incorrect author information, which I corrected only after I had run "git commit", and I changed the author information while I had the commit message open for editing.
Maybe I could try deleting the entire .git folder, or something, but I'd prefer a more elegant way.
Plus, if I don't delete the entire .git folder, I keep my hooks and stuff, and I have a feeling that answers to this sort of question will speak to fundamental design principles in Git that I may not yet understand.

A: You can rebase on top of --root:
git rebase -i --root

To simply change the author on the last commit, use this:
git commit --amend --no-edit --author="The Name <email@domain>"

A: I see you have worked through the mechanics of fixing the one particular issue.
I will try to address your more general question, though:

... I have a feeling that answers to this sort of question will speak to fundamental design principles in Git that I may not yet understand.

Here are all the tricky bits involved in this particular process.

*

*Branch names (like master) are moveable pointers that point to one particular commit.

*Each commit points to its parent commit(s).  A root commit, by definition, has no parent.  (Not relevant here but useful to know: a merge commit is simply defined as any commit with at least two parents.)

*To create any commit, we need to be on a branch,1 but to create a root commit, which has no parent, we need to have the branch have no commits—but see point #1: a branch name points to a commit.

*Rebase works by doing repeated git cherry-pick operations, on an anonymous branch grown from the --onto target.  (Once the repeated cherry-picking is done, the new anonymous branch tip commit replaces the original branch tip commit, i.e., we re-point the branch to the new tip.)

*A single git cherry-pick works by diffing the commit against its parent.  For instance, if the parent has three files and the commit being picked has four, the commit added a new file.  If just one of the three carried-over files is different as well, then whatever changed in that one file makes up the rest of that commit (well, the commit's author and other metadata count too: those are also brought over in the cherry-pick).  Having turned the original commit into a set of changes, Git then applies the same changes to some other (already-existing) commit and makes a new commit out of that.  The new commit's parent is the other commit.

These principles create a Gordian knot that --root slices through.  It's also worth noting that --root was new in Git version 1.6.2, and heavily modified in 1.7.12 (I vaguely recall using rebase before then and encountering some problems).
Git always had to solve the tension between #1 and #3 (the solution itself was improved and properly formalized at some point when git checkout grew the --orphan option).  The trick here is that, when on what is called an "unborn branch", Git records the current branch name in HEAD as usual, but leaves the branch name itself un-created.
(Here it helps to know—although this is an implementation detail that you are not supposed to worry about—that the branch pointers are currently stored in one or both of two places.  Git stores these name-to-ID mappings in small individual files in .git/refs/ and/or a single flat text file, .git/packed-refs.  If a branch name is in neither place, but is in HEAD, Git considers this an "unborn branch".)
When making a new commit, if the current state is "on unborn branch", Git makes a root commit.  The new commit ID becomes the ID for the now-created branch and we are now out of the self-contradictory state of being on a branch, and yet not having a commit.
We still have the problem that git cherry-pick works by comparing a commit to its parent.  This is why, if you wish to cherry-pick a merge commit, you must specify which parent: a merge is a commit with two or more parents, so it is not clear which one to diff against.  But what about a root commit, with all of its zero-count-'em-zero parents?
Git solves this particular problem by comparing a cherry-picked root commit against the empty tree.  Since the empty tree is empty, every file is newly added, and this is the right result for the cherry-pick.
Hence, to rebase with --root, we would like to create an orphan branch, then cherry-pick the root commit, and then all the rest of the commits, as usual.  But git rebase uses an anonymous branch.  The only normal way to create an orphan branch is by name, but rebase uses "detached HEAD" mode.  Moreover, each cherry-pick, including the first, needs to apply changes to an existing commit, but to create a new root commit, we must avoid using some existing parent.
The tricky internals for this are found (indirectly) in this answer from VonC, which links to this commit to the Git code.  The rebase script makes a truly empty root commit (using the empty tree, and the git commit-tree internal "plumbing" command that creates a commit object with user-specified parent IDs), then generates an internal "squash" operation to cherry-pick the existing root commit (with cherry-pick diffing against that same empty tree) and combine it with the dummy empty root commit.
(Here it also helps to note that a "squash" operation during rebase means "amend the previous commit", a la git commit --amend.  The --amend operation tells git commit to make a new commit—the existing one cannot be changed—but to make the new commit's parents match the existing commit's parents.  This has the effect of shoving the old commit aside: the branch now points to the new commit, which points to the "amended" commit's parent(s).  The amended commit is still in the repository, but unless there is some other way to find it, it is no longer visible.)
(This two-step trick means that the authorship information is handled specially.)

1For the purpose of this claim, at least, being in detached HEAD mode (after git checkout hash or git checkout --detach branchname, for instance) counts as being on the special anonymous branch, whose tip is the current commit's hash.


text:
Q: How to remove duplicates (nodes with the same fields) from drupal 7 view? For example: we have some products with diff colors. I want to get its colors.
If I add to view fields the color field I will get duplicates (colors) in output.
Needs realize something like GROUP BY field_color_value in sql-query.

A: I don't understand at all what do you want to do. For example, what are the colors? (terms, item from a text listbox field...).
Without having this information I can tell you that in some view's style settings (click on the gear icon next to style), you can group by the fields you have in the view's field section.


text:
Q: Instagram logout is not working in iphone? I am integrated Instagram in iPhone,At first time login page display on my iPhone and after logout when again login than credentials are not Asking and directly login. i also 'nil' old credentials on logout and i also clear cookie at logout but it not working.when i delete cookie from safari then it work fine. how to solve it programetically.
Logout Button code as below
-(void)doLogout
 {
    IGAppDelegate* appDelegate = (IGAppDelegate*)[UIApplication sharedApplication].delegate;
    [cookies deleteCookie:cookie];

// clear cookie

 NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
 NSArray* instagramCookies = [cookies cookiesForURL:[NSURL URLWithString:@"https://instagram.com/"]];

    NSLog(@"Array is == %@",instagramCookies);

    for (NSHTTPCookie* cookie in instagramCookies)
    {
        [cookies deleteCookie:cookie];
    }

// accessToken set nil

    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"accessToken"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self.navigationController popViewControllerAnimated:YES];
}

A: We have to use WebView instead of safari so this problem will be solved.
I have made some changes in crino's sdk in which this problem has been resolved.
You can get code from https://github.com/gouravgupta72/instagramIOSsdk/  here.


text:
Q: dbo.aspnet_Users table is empty where it shouldn't be Why can't I see the users in this table whereas I knwon that there's users?
I can actually see them by using the Microsoft SQL Server Management Studio.
when I do a "SELECT" statement on the dbo.aspnet_users table, it comes up empty.
I'm querying as administrator then i should have all high level permissions.


text:
Q: Conceptual vs real world signal transmission When data or information is sent through any medium, (be it through phone lines, cable, fiber optics or through empty space or some other means), is it volts, current of charges, 0s and 1s, codes, binaries, photons Or is it something else?
Thank you.

A:
However, the two states are represented, charge, no charge, volts, no volts, etc but rarely if ever + and -. That is how it is taught conceptually in a classroom to my knowledge from the very start and it is emphasized if you will.

No it isn't (or shouldn't be). Logic ONE and logic ZERO (or logic HI and logic LO) are not physical. They do not "represent" something as much as they map to each other. The reason ONE and ZERO are common is because we do math with it. You can't do that as conveniently if you use something else like HI and LO or + and -.

If + and - values were taught, off state of 0 volts would be having a different significance.

Because they aren't physical, you can't do what you just did here where you say you have +, -, and 0 Volts because they aren't even the same thing. The first two are logical abstractions, the third is a real phenomena. One maps to the other but you speak of them here as though they exist in the same space which they do not.
However, trinary logic is a thing. This is where you have three logical states (as opposed to just two in binary) which map to three real-world values.
The logical states might be named:

*

*ZERO

*ONE

*TWO
Or you might prefer them to be labelled

*

*-ONE

*ZERO

*+ONE
Each of the three states might be mapped to real world measurement ranges:

*

*0V<\$v\$<1V

*1V<\$v\$<2V

*2V<\$v\$<3V

Or, maybe you want to map it bipolar voltages:

*

*-3V<\$v\$<-1V

*-1V<\$v\$<+1V

*+1V<\$v\$<+3V

But you still can't mix up abstract logical with real world values so you would never talk about ZERO, ONE, TWO, and voltages 2V<v<3V as group.

Would I be correct to say if that was an actual case in the real world, in an ideal oscilloscope one should see two dots only. one dot for + volt up (whatever the value may be) above the time axis in the direction of + volt axis and for 0 volts there will be a dot on time axis horizontal axis and of course nothing below or the left of each axis.

Both the verticle line and the horizontal line would be meaningless in discrete on and off of our conceptual values.

Because of what I just said above, this part is rather meaningless and needs to be reformulated. It was rather incoherent to begin with.

While in the classroom it is 1 and 0, in the real world we round it off and make it look like it is. And if someone comes along and says you can't send 0 volts as it would be the same as the microprocessor, the system as being turned off at least on the sending side, and the receiving side then receives lots of 0 volts guaranteed for sure, the disagreement would loudly become obvious. Mostly the side that says you can turn the sending system on and then send signals and no voltage is needed wins and proves it too. What am I missing, assuming I didn't lose anyone.

This paragraph is even more incoherent. I have no idea what you are trying to say here.

A:
Figure 1. RS232 waveform and voltage levels. Image credits: Rs232_oscilloscope_trace.jpg: Ktnbnderivative work: Samuel Tardieu (talk) - Rs232_oscilloscope_trace.jpg, CC SA 1.0, https://commons.wikimedia.org/w/index.php?curid=6101703.
The old RS232 protocol may help your understanding. In this case data was transmitted at low speeds over long distances. Because of the possibility of differences in ground potential between both ends the system use a dual-polarity signal.

*

*-3 to -15 V is logic '1'.

*+3 to +15 V is logic '0'.

*Anything in between is undefined.

To avoid problems with strings of 0s or 1s and to tell where one byte started and ended, a byte1 was preceeded by a start bit, 0, and ended with a stop bit, 1. This guaranteed that a transition would occur even if an all 0s or all 1s was transmitted.

Would ... an ideal oscilloscope one should see two dots only.

It would show a continuous line on an analog oscilloscope for the duration the signal stays at each level. A digital 'scope takes samples which could be presented as dots or joined by lines.

Both the verticle line and the horizontal line would be meaningless in discrete on and off of our conceptual values.

I don't understand this statement.

... you can't send 0 volts as it would be the same as the microprocessor, ... and the receiving side then receives lots of 0 volts ...

If that's going to be an issue then you use a signalling handshake similar to RS232's start bit. Alternatively you use a separate clock line to synchronise both ends.


text:
Q: NAS is very slow on OS X10.11 I am currently using a Retina MacBook Pro 13" (512GB SSD, 8GB RAM, Early 2015). It's connected via Wi-Fi (5GHz) to Asus RT-AC67U (AC2400) Router in which a Seagate Expansion 2TB (4 Partitions; Main partition is HFS+ formatted for samba share) is connected physically via USB 3.0 to the router.
When I am connected to my Seagate locally via USB 3.0, transfer speeds are good and normal, however when I connect via network wirelessly, I often see the beachball icon on my Mac, even to open a MPEG-4 video file, it takes a lot of time, basically transfer speeds are about 400Kbps as opposed to 20-30Mbps.
When I am connected to my router physically via ThunderBolt Ethernet, the speeds are absolutely fine. Could this be a Wi-Fi problem then?

A: Looks like this could be caused by an SMB3 signing default change introduced in OS X 10.11.5. It can be overridden by adding or modifying a file in your /etc directory. See the thread El Capitan 10.11.5 update SMB slow (bug) in the Apple support community for the whole story.


text:
Q: Non-completing observables Somewhere in my application, I have a function that must return an Observable. Most of the time, this works fine, but there is an instance where it's not really possible to provide a meaningful result. If this is the case, the caller won't do anything with the result either.
Because it doesn't really matter what the result is, I return new Observable() here. If I return nothing (like return;), I get an error so I must return an Observable.
The thing I'm worried about is making Observables like these that never complete. At the end of an Observable's lifespan, subscriber.complete() is used to indicate the Observable isn't going to do anything anymore. If I don't do that, will this result in any serious problems, like memory leaks?

A: There's an RxJS constant observable that completes immediately. It's called EMPTY
So just return EMPTY. It'll be semantically clearer too.

A: There are many types of Observable :

*

*finite (like Http requests)

*infinite

The type of infinite is allowing memory leak or some "bizarre" issues because depend on observable used like replay.
To return observable who complete() now without emit next() value :
return EMPTY;

If you need to pass through next() :
return of({});

Return an empty Observable
My advice is to use a takeUntil in pipe to unsubscribe to avoid memory leak.
https://blog.bitsrc.io/6-ways-to-unsubscribe-from-observables-in-angular-ab912819a78f


text:
Q: Injecting sudo su with aliases I'm wondering if there is a way to inject alias when you switch to root profile with sudo.
What I have in mind is this:
sshLogin@linuxVM /home/sshLoginUser/> sudo su -x "alias goHome='cd /home/sshLoginUser/'"
root@linuxVM /home/OtherDir/> goHome
root@linuxVM /home/sshLoginUser/>

I am using a VM box on cloud to setup and run some operations, and I want to eventually add more alias for repetitive tasks.
Ideally, I would like to sudo su and source on a file which contains my collection of aliases and functions.

A: It is important to understand, that sudo does not do shell expansion; it runs a command. There are probably two solutions for what you would want to do, each with there own advantages/disadvantages:
1 alias hop='sudo id': let the sudo be part of the alias or
2 sudo -s (without command), which starts an interactive shell and reads /root/.bashrc.

A: [tom@alarm ~]$ sudo -i
[root@alarm ~]# tail -n 1 .bashrc
alias goHome="cd /home/$SUDO_USER"
[root@alarm ~]# goHome
[root@alarm tom]# pwd
/home/tom
[root@alarm tom]#

If the "built-in" env vars are not sufficient for your cases, you can also make sudo preserve some custom ones. For example:
CERTAINFILE="/home/$USER/different_name" sudo -i --preserve-env=CERTAINFILE


text:
Q: Formatting the decimal place without converting the class numeric to character I have a number, say 0.4 which is of class numeric. I wish to make it 2 decimal places without changing the class numeric. Is it possible to do this?

A: I'm not totally sure what you mean, but you can control the number of digits that print with sprintf.
sprintf("%.2f",0.4)
# [1] "0.40"

Programmatically, 0.4 and 0.40 are identical.
all.equal(0.4,0.40)
# [1] TRUE


text:
Q: Connect two MONGO dbs on different port using mongoose in a node js app I am having two mongodb dbs running on different port, how can I connect and do operations to these both dbs using mongoose.
I know we have createconnection feature to connect to different dbs but there they are supposed to be on same url like
http://localhost:{port1}
and then we use mongoose.connect(http://localhost:{port1}) and then mongoose.createconnection(http://localhost:{port1}/db1) and mongoose.createconnection(http://localhost:{port1}/db1) to create two connections.
but my dbs are on http://localhost:{port1} and http://localhost:{port2}
how can I use mongoose to Connect two MONGO dbs on different port using mongoose in a node js app?


text:
Q: Deciding between np hard and np complete in my own set of rules I have the Iris dataset which looks something like:
1,3,1,1,0
1,1,1,1,0
1,3,1,1,0
1,2,1,1,0
1,3,1,1,0
1,2,1,1,0
2,2,2,2,1
2,2,2,2,1
2,2,2,2,1
2,1,2,2,1
1,1,2,2,1
2,1,2,2,1
2,2,3,4,2
2,1,3,4,2
3,1,3,4,2
2,1,3,4,2
2,1,3,4,2
3,1,3,4,2

I am just giving 18 rows but there are total 150 rows. The 1st 4 column gives the 4 attribute values and the fifth column gives the class.
So 3,1,3,4,2 means if the att_1=3, att_2=1, att_3=3, att_4=4 the class=2
Now I have written 2 classifier algorithms, where I tried to extract rules from this dataset.
The 1st algorithm(Implemented using C and python) gives the output as:
*,*,1,*,0
*,*,2,2,1
*,*,*,3,1
*,*,*,4,2
*,*,3,*,2

By these above 5 rows I tried to keep all the characteristics of the main dataset which contains 150 rows. Here * stands for don't care and *,*,2,2,1 this simply means if the value of attribute 3 and 4 =2 then we don't care about the value of attribute 1 and 2, the class will be = 1.
The 2nd algorithm(Implemented using C and python) gives the output as:
*,*,1,*,0
*,*,2,2,1
2,*,*,3,1
*,2,2,*,1
*,*,3,4,2
*,1,*,4,2
*,*,3,2,2
3,*,*,*,2
1,*,*,3,2

Now I took the union of these 2 rule sets. And got the outcome as:
*,*,2,2,1
*,*,1,*,0
*,2,2,*,1
*,*,3,2,2
*,*,3,4,2
3,*,*,*,2
*,*,*,3,1
1,*,*,3,2
*,*,*,4,2
*,*,3,*,2
*,1,*,4,2
2,*,*,3,1

Now the question that is arriving in my mind is, there are 12 rules in that union file. But may be there can be 3 or 4 most effective rules, using which we can get the clear view of the initial iris dataset with 150 rows. So my point is : To find the top 5 most effective rules from this above union rules. Basically I got those rules from the initial iris dataset and now I want to get the initial iris dataset back from the best possible generated rules. Is this problem a np-hard or a np-complete problem? And why so?


text:
Q: How to read strings using loop with function and methods in Java I am a newbie in java and need some little bit of help.
So i should be able to display the string message to the user via the filestream stream.
here is my main method:
public static void main (String[] args)
{
    writeline("Hello World!", System.out);
}

and here is my writeline method
public static int writeline (String message, PrintStream stream)
{
    //need some loops to read in each character of "Hello World!" and display.
}

I know you can use String method charAt and length method.
any idea how to tackle this situation??
any tips will be much appreciated.
thanks
also, value of message  are expected to be NULL terminated character arrays
and values of stream are expected to be System.out and System.err.

A: This is unnecessary.
But since you asked, in the method writeline() you can try following:
for(int i = 0; i < message.length(); i++)
{
   stream.print(message.charAt(i));
}

But again, there is no need of doing this.

A: You can try this:
String s = "Hello World!";
for(int i = 0; i < s.length(); i++)
{
   char c = s.charAt(i);
}


text:
Q: Core plot with month on x Axis (iphone) I would like to draw an XY graph using coreplot on iphone with date on x axis and some values on y axis. Referring to the DatePlot example shipping with the coreplot SDK, I was able to draw graph with date on x axis on a monthly scale (ie x ranges from 1 date of the month to last date). Now I want an yearly scale , ie I want to show All month names (Jan,Feb,Mar etc) on x axis and my tick inteval as one month time.
I used following code for showing values in a monthly scale
oneXUnit        =   60 * 60 * 24;
x.majorIntervalLength    =  CPDecimalFromFloat((float) oneXUnit);
NSDateFormatter *dateFormatter   =   [[[NSDateFormatter alloc] init]autorelease];
NSString *dateString        =   @"0";
[dateFormatter setDateFormat:@"MM"];
CPTimeFormatter *timeFormatter  =   [[CPTimeFormatter alloc]initWithDateFormatter:dateFormatter];
timeFormatter.referenceDate =   [dateFormatter dateFromString:dateString];
x.labelFormatter    =   timeFormatter;

Now For yearly mode x tick inteval needs to be one month. I tried the below code , but didnt work
oneXUnit        =   60 * 60 * 24 * 30;
x.majorIntervalLength    =  CPDecimalFromFloat((float) oneXUnit);
NSDateFormatter *dateFormatter   =   [[[NSDateFormatter alloc] init]autorelease];
NSString *dateString        =   @"Jan";
[dateFormatter setDateFormat:@"MMM"];
CPTimeFormatter *timeFormatter  =   [[CPTimeFormatter alloc]initWithDateFormatter:dateFormatter];
timeFormatter.referenceDate =   [dateFormatter dateFromString:dateString];
x.labelFormatter    =   timeFormatter;

I think this logic fails because number of days for each months are different. Now months are showing on x axis, but it is showing as
Jan,Mar,April,May,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec.
You can see that there is no Feb and there are 2 entries for May. How can my tick interval relates with the number of days with each month. Any solutions?
Thanks and Regards,

A: I had the same problem. My quick&dirty solutions is to do custom labeling, looping through all month and add the timestamps to an array.
x.labelingPolicy = CPAxisLabelingPolicyNone;

NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:12];
NSMutableArray *customMajorTickLocations = [NSMutableArray arrayWithCapacity:12];
NSMutableArray *customMinorTickLocations = [NSMutableArray arrayWithCapacity:12];
NSDate* dateCurrentMonth = [[NSDate date] dateAtStartOfYear];

for (NSUInteger iMonth = 0; iMonth < 12; iMonth++)
{
    NSNumber* numMajorTickLocation = [NSNumber numberWithDouble:[dateCurrentMonth timestampAtMidnight]];
    NSNumber* numMinorTickLocation = [NSNumber numberWithDouble:[dateCurrentMonth timestampAtMidnight]+14*oneDay];

CPAxisLabel *newLabel = [[CPAxisLabel alloc] initWithText:[dateFormatter stringFromDate:dateCurrentMonth] textStyle:x.labelTextStyle];
newLabel.tickLocation = [numMinorTickLocation decimalValue];
newLabel.offset = x.labelOffset + x.majorTickLength;

dateCurrentMonth = [[dateCurrentMonth dateByAddingDays:32] dateAtStartOfMonth];

[customLabels addObject:newLabel];
[customMajorTickLocations addObject:numMajorTickLocation];
[customMinorTickLocations addObject:numMinorTickLocation];
[newLabel release];

}

// add a last major tick to close the range
[customMajorTickLocations addObject:[NSNumber numberWithDouble:[dateCurrentMonth timestampAtMidnight]]];

x.axisLabels = [NSSet setWithArray:customLabels];
x.majorTickLocations = [NSSet setWithArray:customMajorTickLocations];
x.minorTickLocations = [NSSet setWithArray:customMinorTickLocations];

A: Just answered in a related question. Use CPTCalendarFormatter instead of CPTTimeFormatter, that is good when you have to set time interval offset in seconds (ex. hour= 60*60, day=24*60*60), but months have a variable number of days/seconds (30*24*60*60 or 31*24*60*60, 28, leap years ecc.). CPTCalendarFormatter let you decide the calendar unit for date calculations on labels. In this way, fixed a reference date and a reference calendar unit, in the datasource method you will have to return the number of those units starting from the reference date.
Here's full code, enjoy.
In your viewDidLoad or elsewhere you initialize the graph:
[...]

// Graph host view
CPTGraphHostingView* hostView = [[CPTGraphHostingView alloc] initWithFrame:self.view.frame];
[self.view addSubview: hostView];

// Your graph
CPTGraph* graph = [[CPTXYGraph alloc] initWithFrame:hostView.bounds];
hostView.hostedGraph = graph;
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)[graph axisSet];

// xAxis configuration
CPTXYAxis *xAxis = [axisSet xAxis];
[xAxis setLabelingPolicy:CPTAxisLabelingPolicyFixedInterval];
// Prepare dateFormat for current Locale, we want "JAN 2014" "FEB 2014" and so on
NSString *dateComponents = @"MMMYY";
NSString *localDateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:[NSLocale currentLocale]];
NSDateFormatter *labelDateFormatter=[[NSDateFormatter alloc] init];
labelDateFormatter.dateFormat=localDateFormat;
// Set xAxis date Formatter
CPTCalendarFormatter *xDateYearFormatter = [[CPTCalendarFormatter alloc] initWithDateFormatter:labelDateFormatter];
//Keep in mind this reference date, it will be used to calculate NSNumber in dataSource method
xDateYearFormatter.referenceDate = [NSDate dateWithTimeIntervalSince1970:0];
xDateYearFormatter.referenceCalendarUnit=NSMonthCalendarUnit;
[xAxis setLabelFormatter:xDateYearFormatter];

// yAxis configuration
CPTXYAxis *yAxis = [axisSet yAxis];
[yAxis setMajorIntervalLength:CPTDecimalFromFloat(_YOURYINTERVAL_)];
[yAxis setLabelingPolicy:CPTAxisLabelingPolicyFixedInterval];
[yAxis setLabelFormatter:_YOURYFORMATTER_];
[yAxis setAxisConstraints:[CPTConstraints constraintWithLowerOffset:0.0]]

// Get the (default) plotspace from the graph so we can set its x/y ranges
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
NSDate *startDate=_YOURSTARTINGDATE_
//Number of months since the reference date
NSInteger xStart=[[[NSCalendar currentCalendar] components: NSCalendarUnitMonth
                                 fromDate: xDateYearFormatter.referenceDate
                                   toDate: _YOURSTARTINGDATE_
                                  options: 0] month];
[plotSpace setXRange: [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInteger(xStart)     length:CPTDecimalFromInteger(_YOURDATESARRAY_.count-1)]];
[plotSpace setYRange: [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(_YOURMAXYVALUE_)]];

[...]

Datasource method to return values on axis:
 -(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
    switch (fieldEnum) {

        case CPTScatterPlotFieldX: {

            NSInteger monthsOffset=[[[NSCalendar currentCalendar] components: NSCalendarUnitMonth  fromDate: [NSDate dateWithTimeIntervalSince1970:0] toDate: [_YOURDATESARRAY_ objectAtIndex:index] options: 0] month];
            NSNumber *val = [NSNumber numberWithInteger:monthsOffset];
            return val;
            break;
        }
        case CPTScatterPlotFieldY: {
            NSNumber *val=_YOURVALUEFORYAXIS_;
            return val;
            break;
        }
        default:
            break;
    }

    return nil;
}


text:
Q: How do I pass a binary literal to JavaScript eval? Before I start, please don't tell me not to use eval; I know the input is perfectly sanitary, so it's safe, fast, and easy.
I'm using a JavaScript engine to power a calculator I've written in Java. To do this, I simply concatonate input into a string and pass it to JavaScript. For instance, clicking the buttons 1, +, and 5 results in building the String "1+5". I got this working for hexadecimal, too, by putting 0x before the letters, so A, +, and 8 gives me "0xA+8. My problem comes from programming its binary mode. I tried passing it 0b1101+0b10 (which is how Java does binary literals), but it just throws an error. How do I handle binary literals in JavaScript?

A: Update: As of ES2015, JavaScript supports binary Number literals:

console.log(0b1101+0b10) // 15 (in decimal)

Alternatively, you can use a string, and use Number.parseInt with a base of 2:

var a = parseInt('1101', 2) // Note base 2!
var b = parseInt('0010', 2) // Note base 2!
console.log(a+b) // 15 (in decimal)

For displaying numbers in different bases, Number#toString also accepts a base:

(15).toString(2) // 1111

Note: If passing user input directly to eval(), use a regex to ensure the input only contains numbers and the operators you expect (+, -, etc).


text:
Q: Jar files in the Ubuntu Hud So I have a few jar files that I frequently use (Minecraft and other launchers, to name a few) and they show up under the "File and Folders" section.  If I open other files that have a similar file path, those ones may get farther down in the list whenever I search for the file through the Hud.
Is there any way to have them treated as applications, so that they show up in that section of the Hud, and then their priority gets increased every time I open them?

A: In fact jar is not an application.  It can be treated like pdf or docx or smth like that.  In detail, jar is just a set of compiled java classes and some meta information packed into zip archive with jar extension.
Can't say if there is any native way, but try to create a shell script launcher, I guess it should be treated as "normal" executable.


text:
Q: Sql Server Procedure Possuo a seguinte procedure
 PROCEDURE [dbo].[spAVL_Ignition]
        @DeviceIMEI VARCHAR(50),
        @TimeStamp SMALLDATETIME,
        @Value INT,
        @Tag VARCHAR(50)
    AS
    BEGIN
        IF NOT EXISTS (SELECT TOP (1) TimeStamp FROM AVL_Ignition)
            INSERT INTO  AVL_Ignition (DeviceIMEI, TimeStamp, Value)
            VALUES ('@DeviceIMEI', '@TimeStamp', '@Value')
        ELSE
            DECLARE @LastValue INT = (SELECT CONVERT (int,Value)
                                      FROM AVL_Ignition
                                      WHERE TimeStamp = (SELECT MAX(TimeStamp) FROM AVL_Ignition))
            IF(@LastValue != @Value)
                    INSERT INTO  AVL_Ignition (DeviceIMEI, TimeStamp, Value)
                    VALUES ('@DeviceIMEI', '@TimeStamp', '@Value')
    END

Quando tento executar a procedure passando os parametros.
execute spAVL_Ignition 123, 2019-07-29 14:35:00, 1, null

O SQL Server aponta o seguinte erro.

Sintaxe incorreta perto de '-'.

Também tentei fazer da seguinte forma.
execute spAVL_Ignition '123', '2019-07-29 14:35:00', '1', null

porém me apontou outro erro.

A conversão falhou ao converter uma cadeia de caracteres para o tipo
  de dados smalldatetime.

Qual seria a forma correta de passar a data por parâmetro ?

A: Boa noite Gabriel.
O erro não ocorre por conta dos valores passados incorretamente nos parâmetros pois o segundo exemplo esta certo, mas sim porque esta escrevendo as variáveis como string.
Incorreto
VALUES ('@DeviceIMEI', '@TimeStamp', '@Value')

Correto
VALUES (@DeviceIMEI, @TimeStamp, @Value)

Segue uma breve correção no código:
 PROCEDURE [dbo].[spAVL_Ignition]
        @DeviceIMEI VARCHAR(50),
        @TimeStamp SMALLDATETIME,
        @Value INT,
        @Tag VARCHAR(50)
    AS
    BEGIN
        IF NOT EXISTS (SELECT TOP (1) TimeStamp FROM AVL_Ignition)
            INSERT INTO  AVL_Ignition (DeviceIMEI, TimeStamp, Value)
            VALUES (@DeviceIMEI, @TimeStamp, @Value)
        ELSE
            DECLARE @LastValue INT = (SELECT CONVERT (int,Value)
                                      FROM AVL_Ignition
                                      WHERE TimeStamp = (SELECT MAX(TimeStamp) FROM AVL_Ignition))
            IF(@LastValue != @Value)
                    INSERT INTO  AVL_Ignition (DeviceIMEI, TimeStamp, Value)
                    VALUES (@DeviceIMEI, @TimeStamp, @Value)
    END


text: Q: Ext.js - text fields losing focus while typing & become hidden by keyboard I made a web app using Ext.js & Sencha Cmd. Everything works well in the desktop view & almost everything works in the mobile view.... except for the text fields in the form panel. When I view on iPhone & focus on a text field, the keyboard appears & the page slides up, bringing the field into view. However, once I type 1 letter, it slides back down & the text fields are covered up by the keyboard, preventing the user from seeing what they are typing. Sometimes it jumps up & down but usually just stays down until I focus on another field. Everything I can find on line says this shouldn't be a problem with iOS devices but it clearly is for me. Any suggestions?


text:
Q: SELECT DISTINCT Inside WHERE IN clause performance I have a performance question about the following code...
SELECT*FROM GCL_Loans WHERE Loan_ID IN
(
    SELECT Loan_ID FROM GCL_Loan_Items
)

GCL_Loans has a list of loans with basic infomation
CCL_Loan_Items has information about a specific item in a loan. There can be duplicate Loan_ID's in GCL_Loan_Items
Can anyone explain why this query would be faster or slower than the one above?
SELECT*FROM GCL_Loans WHERE Loan_ID IN
(
    SELECT DISTINCT Loan_ID FROM GCL_Loan_Items
)

A: The "DISTINCT" version is probably faster, because the IN clause will have a smaller data set to search to determine if any given GCL_Loans.Loan_ID is in the set.  Without the DISTINCT, the data set will be larger.
There's a reasonably good argument to be made that the query optimizer will automatically recognize the IN test is a set-wise, not a list-wise test and do the DISTINCT during auto-indexing ... but I've seen that fail before.
Note that subselects can be a fail here too, because some databases (mysql) will execute the subselect for each element in the primary select.

A: The plan and performance of both is equal

A: Because by selecting DISTINCT there is less criteria in the SUBQuery (IN).
My understanding is SQL will run the subquery first to generate the list of items that are to be included in the IN.


text:
Q: How can I align this text to be centered within my CSS grid? I'm trying to recreate FreeCodeCamp's Product Landing Page as a personal project.
For the content below the Get Started button and above the video, I  used a grid to try to align them properly. However, I'm having trouble aligning the text (the heads and paragraphs) vertically in their rows. How may I go about doing this? They seem to be sitting at the "bottom" of their rows.
HTML code:

body {
    font-family: Lato, sans-serif;
    background-color: #ececec;
}

#top {
    margin-top: 100px;
}

#top h1 {
    font-size: 1.5em;
    font-weight: 600;
    margin-bottom: 0;
}

#nav-bar {
    position: fixed;
    width: 100%;
    height: 80px;
    background-color: #ececec;
    display: flex;
    justify-content: space-between;
    align-items: center;
    top: 0;
}

#header-img {
    height: 35px;
    left: 0;
    margin-left: 20px;
}

#top {
    text-align: center;
}

#navbar li {
    display: inline;
    right: 0;
}

#navlinks {
    display: flex;
    list-style-type: none;
}

#navlinks li {
    padding: 5px;
    text-align: center;
    margin-right: 50px;
}

#submit {
    width: 150px;
    height: 30px;
    margin-top: 15px;
    font-weight: 900;
    font-size: 1em;
    background-color: #f3c807;
    border: none;
}

#submit:hover {
    background-color: orange;
    transition: background-color 1s;
    cursor: pointer;
}

#email {
    height: 23px;
    padding-left: 7px;
    width: 275px;
}

i.fa, i.fas {
    color: rgb(255, 136, 0);
    text-align: center;
}

#grid {
    display: grid;
    grid-template-columns: 100px auto;
    grid-template-rows: 50px 50px 50px;
    grid-column-gap: 50px;
    grid-row-gap: 80px;
    margin-left: 50px;
    align-content: center;
    margin-top: 100px;
}

.icon {
    text-align: center;
}

.middlecontent h1 {
    font-size: 1.5em;
    margin-bottom: 0;
}

.middlecontent p {
    margin-top: 0;
}
    <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,100;0,300;0,400;1,100;1,300&display=swap" rel="stylesheet">
    <link href="./css/landingpagestyles.css" rel="stylesheet">

    <title>Original Trombones</title>

                Features

                How It Works

                Pricing

Handcrafted, home-made masterpieces

            <form id="form" action="https://www.freecodecamp.com/email-submit">

            <input type="email" name="email" id="email" placeholder="Enter your email address">

            <input type="submit" id="submit" value="GET STARTED">
            </form>

                    Premium Materials

                    Our trombones use the shiniest brass which is sourced locally. This will increase the longevity of your purchase.

                        Fast Shipping

                        We make sure you recieve your trombone as soon as we have finished making it. We also provide free returns if you are not satisfied.

                        Quality Assurance

                        For every purchase you make, we will ensure there are no damages or faults and we will check and test the pitch of your instrument.

A: What I did was I made the div surrounding the h1 and p tags into a flexbox
.middlecontent {
    display: flex;
    justify-content: center;
    flex-direction: column;
}

And that seemed to work. It was really as simple as that.

body {
    font-family: Lato, sans-serif;
    background-color: #ececec;
}

h1 {
    margin-bottom: 0;
}

p {
    margin-top: 0;
}

#top {
    margin-top: 100px;
}

#top h1 {
    font-size: 1.5em;
    font-weight: 600;
    margin-bottom: 0;
}

#nav-bar {
    position: fixed;
    width: 100%;
    height: 80px;
    background-color: #ececec;
    display: flex;
    justify-content: space-between;
    align-items: center;
    top: 0;
}

#header-img {
    height: 35px;
    left: 0;
    margin-left: 20px;
}

#top {
    text-align: center;
}

#navbar li {
    display: inline;
    right: 0;
}

#navlinks {
    display: flex;
    list-style-type: none;
}

#navlinks li {
    padding: 5px;
    text-align: center;
    margin-right: 50px;
}

#submit {
    width: 150px;
    height: 30px;
    margin-top: 15px;
    font-weight: 900;
    font-size: 1em;
    background-color: #f3c807;
    border: none;
}

#submit:hover {
    background-color: orange;
    transition: background-color 1s;
    cursor: pointer;
}

#email {
    height: 23px;
    padding-left: 7px;
    width: 275px;
}

i.fa, i.fas {
    color: rgb(255, 136, 0);
    text-align: center;
}

#grid {
    display: grid;
    grid-template-columns: 100px auto;
    grid-template-rows: 50px 50px 50px;
    grid-column-gap: 50px;
    grid-row-gap: 80px;
    margin-left: 50px;
    align-content: center;
    margin-top: 100px;
}

.icon {
    text-align: center;
}

.middlecontent h1 {
    font-size: 1.5em;
    margin-bottom: 0;
}

.middlecontent p {
    margin-top: 0;
}

.middlecontent {
    display: flex;
    justify-content: center;
    flex-direction: column;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,100;0,300;0,400;1,100;1,300&display=swap" rel="stylesheet">
    <link href="./css/landingpagestyles.css" rel="stylesheet">

    <title>Original Trombones</title>

                Features

                How It Works

                Pricing

Handcrafted, home-made masterpieces

            <form id="form" action="https://www.freecodecamp.com/email-submit">

            <input type="email" name="email" id="email" placeholder="Enter your email address">

            <input type="submit" id="submit" value="GET STARTED">
            </form>

                    Premium Materials

                    Our trombones use the shiniest brass which is sourced locally. This will increase the longevity of your purchase.

                        Fast Shipping

                        We make sure you recieve your trombone as soon as we have finished making it. We also provide free returns if you are not satisfied.

                        Quality Assurance

                        For every purchase you make, we will ensure there are no damages or faults and we will check and test the pitch of your instrument.

A: According to my experience, If we want to align items(vertically or horizontally) in a grid we can use flex property inside that child element. The following example will help to get an idea.
To vertically align:
align-items:{position}

To horizontally align:
justify-content:{position}

 body{
        color: #ffff;
    }
    .content{
        display: grid;
        grid-gap: 10px;
        max-width: 960px;
        margin: auto;
        text-align: center;
        font-weight: bold;
        font-size: 50px;
        font-family: sans-serif;
        grid-template-columns: repeat(3,1fr);
        grid-auto-rows:200px;
    }

    .content div{
        background: gray;
        padding: 30px;
    }

    .content div:nth-child(even){
        background: green;
    }

    .one{
      display:flex;
      align-items: start;
      justify-content: start;
    }

    .two{
      display:flex;
      align-items: center;
      justify-content: center;
    }

    .three{
      display:flex;
      align-items: end;
      justify-content: end;
    }

    .four{
      display:flex;
      align-items: start;
      justify-content: center;
    }

    .five{
      display:flex;
      align-items: end;
      justify-content: center;
    }

    .six{
      display:flex;
      align-items: start;
      justify-content: end;
    }

1

2

3

4

5

6


text:
Q: Mongoose Virtual Referencing Other Model/Collection Trying to reference one collection in mongo via another model's virtual. Currently the only output I'm getting is 'undefined'. Was able to execute this in my main js file as a standalone query but can't figure out how to get this to function as a virtual. Help appreciated.
const mongoose = require('mongoose');
const { stylesList } = require('../styles.js')
const Schema = mongoose.Schema;
const Post = require('./post')

const options = { toJSON: { virtuals: true } };
// options object for the schema, passed in after the actual schema.

const BrandSchema = new Schema({
    name: {
        type: String,
        unique: true,
        required: true
    },
    linkedBrands: [String],
    styles: [{ type: String, enum: stylesList }],
    links: {
        homepage: {
            type: String,
            required: true
        },
        grailed: {
            type: String,
            required: true
        },
        wikipedia: String
    },
    bannerImage: String,
    likes: {
        type: Number,
        default: 0
    }
}, options);

BrandSchema.set('toObject', { getters: true });

BrandSchema.virtual('amountWorn').get(async function() {
    const wornPosts = await Post.find({includedBrands: this._id});
    return wornPosts.length
});

module.exports = mongoose.model('Brand', BrandSchema)


text:
Q: Regression Coefficients in terms of Individual treatment effect According to the famous book "Mostly Harmless Econometrics", the regression coefficient can be written in terms of the individual treatment effects.
Precisely, the authors state that:

Even so, allowing for random variation in potential outcomes across
people and for nonlinearity for a given person, regression can
be thought of as a strategy for the estimation of a weighted
average of the individual-specific difference, $Y_{1i}-Y_{0i}$.

($Y_{1i}$ is the potential treated outcome, and $Y_{0i}$ is the potential untreated outcome.)
Although I look over the entire book, I was not able to how the regression estimand (coefficient) can be thought a weighted average of the individual treatment effect.
So, if you know where I can find the reference related to this issue, or you can show me the derivation, please help me.


text:
Q: How to remove lines from the files based on key values in a different file I have a file1:
1   a   aa
2   b   bb
3   a   aa
4   b   bb
5   a   aa
6   b   bb
7   a   aa
8   b   bb

and file2:
1
2
5

I need to delete all lines in from file1 where values in column1 are found in file2

A: Assuming that both files are sorted lexicographically (with e.g. sort -b) on the first column:
$ join -v 1 file1 file2
3 a aa
4 b bb
6 b bb
7 a aa
8 b bb

This uses the join utility to extract all the lines from file1 whose first column does not match any of the values in file2.
The default behavior of join is to produce the INNER JOIN based on the first column of both files, but with -v 1 we instead get the unpairable lines from the first file.

A: Try this with GNU awk:
Solution 1:
$ awk 'NR==FNR {a[$0]} FNR!=NR {printf("%s",!($1 in a)? $0"\n": "")}' file2 file1
3 a aa
4 b bb
6 b bb
7 a aa
8 b bb

That 1st solution looks unnecessarily contrived, with a ternary operator !($1 in a)? $0"\n": ""inside the printf block.  I just propose it for generality's sake, meaning that if instead of merely deleting unwanted lines per your scheme, you ever wanted to replace them with my_string, you could just put my_string\n inside the empty string "".
Solution 2:
$ awk 'NR==FNR {a[$0]} FNR!=NR && !($1 in a) {print $0}' file2 file1

which can be further simplified to:
$ awk 'NR==FNR {a[$0]} FNR!=NR && !($1 in a)' file2 file1

because awk prints the whole record ($0) by default.
man awk will give you a very good intro to awk, whatever your particular installed flavor.  If you still have questions after some surfing, just ask for specifics.
I bet someone will find a way to make this look even simpler. ;-)

A: awk 'NR==FNR{a[$1];next}!($1 in a){print $0}' file2 file1

output
3   a   aa
4   b   bb
6   b   bb
7   a   aa
8   b   bb