Compute the layout positions

@param node Node to start with
@param depth Depth of the node
@param aoff Angular offset
@param awid Angular width
@param radius Current radius
@param radiusinc Radius per depth step
485694
public static void computePositions(Node node, int depth, double aoff, double awid, double radius, double radiusinc) {
    node.x = FastMath.sin(aoff) * radius;
    node.y = FastMath.cos(aoff) * radius;

    // Angular width per weight
    double cwid = awid / node.weight;
    // Avoid overly wide angles - shrink radius if necessary.
    double div = 1;
    if(node.weight > 1) {
      double s = FastMath.sin(awid * .5), c = FastMath.cos(awid * .5);
      double dx = s * (depth + 1), dy = c * (depth + 1) - depth;
      double d = FastMath.sqrt(dx * dx + dy * dy) / MathUtil.SQRT2;
      div = Math.max(div, d);
    }
    // Angular position of current child:
    double cang = aoff - awid * .5 / div;
    final double adjwid = cwid / div;
    for(Node c : node.children) {
      computePositions(c, depth + 1, cang + adjwid * c.weight * .5, adjwid * c.weight, radius + radiusinc, radiusinc);
      cang += adjwid * c.weight;
    }
  }
786791
function ( radius, segments, thetaStart, thetaLength ) {

	BufferGeometry.call( this );

	this.type = '';

	this.parameters = {
		radius: radius,
		segments: segments,
		thetaStart: thetaStart,
		thetaLength: thetaLength
	};

	radius = radius || 1;
	segments = segments !== undefined ? Math.max( 3, segments ) : 8;

	thetaStart = thetaStart !== undefined ? thetaStart : 0;
	thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;

	// buffers

	var indices = [];
	var vertices = [];
	var normals = [];
	var uvs = [];

	// helper variables

	var i, s;
	var vertex = new Vector3();
	var uv = new Vector2();

	// center point

	vertices.push( 0, 0, 0 );
	normals.push( 0, 0, 1 );
	uvs.push( 0.5, 0.5 );

	for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {

		var segment = thetaStart + s / segments * thetaLength;

		// vertex

		vertex.x = radius * Math.cos( segment );
		vertex.y = radius * Math.sin( segment );

		vertices.push( vertex.x, vertex.y, vertex.z );

		// normal

		normals.push( 0, 0, 1 );

		// uvs

		uv.x = ( vertices[ i ] / radius + 1 ) / 2;
		uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;

		uvs.push( uv.x, uv.y );

	}

	// indices

	for ( i = 1; i <= segments; i ++ ) {

		indices.push( i, i + 1, 0 );

	}

	// build geometry

	this.setIndex( indices );
	this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
	this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

}
882323
void sortEdgesCCW(FastQueue<Node> corners) {
		for (int nodeIdx = 0; nodeIdx < corners.size; nodeIdx++) {
			Node na = corners.get(nodeIdx);

			// reference node to do angles relative to.
			double ref = Double.NaN;
			int count = 0;
			for (int i = 0; i < 4; i++) {
				order[i] = i;
				tmpEdges[i] = na.edges[i];
				if( na.edges[i] == null ) {
					directions[i] = Double.MAX_VALUE;
				} else {
					Node nb = na.edges[i];
					double angleB = Math.atan2(nb.y-na.y,nb.x-na.x);
					if( Double.isNaN(ref) ) {
						ref = angleB;
						directions[i] = 0;
					} else {
						directions[i] = UtilAngle.distanceCCW(ref,angleB);
					}
					count++;
				}
			}

			sorter.sort(directions,0,4,order);
			for (int i = 0; i < 4; i++) {
				na.edges[i] = tmpEdges[ order[i] ];
			}
			if( count == 2 ) {
				// If there are only two then we define the order to be defined by the one which minimizes
				// CCW direction
				if( directions[order[1]] > Math.PI ) {
					na.edges[0] = tmpEdges[ order[1] ];
					na.edges[1] = tmpEdges[ order[0] ];
				} else {
					na.edges[0] = tmpEdges[ order[0] ];
					na.edges[1] = tmpEdges[ order[1] ];
				}
			} else if( count == 3 ) {
				// Edges need to point along the 4 possible directions, in the case of 3 edges, there might
				// need to be a gap at a different location than at the end
				int selected = -1;
				double largestAngle = 0;
				for (int i = 0,j=2; i < 3; j=i,i++) {
					double ccw = UtilAngle.distanceCCW(directions[order[j]],directions[order[i]]);
					if( ccw > largestAngle ) {
						largestAngle = ccw;
						selected = j;
					}
				}

				for (int i = 2; i > selected; i--) {
					na.edges[i+1] = na.edges[i];
				}
				na.edges[selected+1]=null;

			}
		}
	}
11067
public void createLayout(final Sbgn sbgn, boolean doLayout)
    {
        viewToLayout = new HashMap();
        glyphToVNode = new HashMap();
        idToGLyph = new HashMap();
        idToCompartmentGlyphs = new HashMap();
        portIDToOwnerGlyph = new HashMap();
        layoutToView = new HashMap();
        idToArcs = new HashMap<String, Arc>();

        this.layout = new SbgnPDLayout();
        final LGraphManager graphMgr = layout.getGraphManager();
        graphMgr.addRoot();

        root = new VCompound(new Glyph());

        // Detect compartment glyphs and put them in a hashmap;
        // also set compartment glyphs of members of complexes.
        for (Glyph g: sbgn.getMap().getGlyph())
        {
            if(glyphClazzOneOf(g, GlyphClazz.COMPARTMENT)) {
                idToCompartmentGlyphs.put(g.getId(), g);
            }
            //Set compartmentRef to all children of a Complex node.
            Glyph compartment = (Glyph)g.getCompartmentRef();
            if(compartment != null && glyphClazzOneOf(g, GlyphClazz.COMPLEX)) {
                setCompartmentRefForComplexMembers(g, compartment, new HashSet<Glyph>());
            }
        }

        // Nest glyphs inside compartment glyphs according to their compartmentRef.
        // This list holds the glyphs that will be deleted after corresponding glyph
        // is added to child glyph of another glyph.
        if(!idToCompartmentGlyphs.isEmpty()) {
            List<Glyph> deletedList = new ArrayList<Glyph>();
            for (Glyph g : sbgn.getMap().getGlyph()) {
                Glyph containerCompartment = (Glyph) g.getCompartmentRef();
                if (containerCompartment != null) {
                    idToCompartmentGlyphs.get(containerCompartment.getId()).getGlyph().add(g);
                    deletedList.add(g);
                }
            }
            // Delete the duplicate glyphs, after they are moved to corresponding compartment glyph.
            for (Glyph g : deletedList) {
                sbgn.getMap().getGlyph().remove(g);
            }
        }

        // initialize the map for keeping ports and their owner glyphs
        // with entries like: <portID, ownerGlyph>
        initPortIdToGlyphMap(sbgn.getMap().getGlyph());

        //Remove ports from source and target field of ports
        //replace them with owner glyphs of these ports
        removePortsFromArcs(sbgn.getMap().getArc());

        // Assign logical operator and Process nodes to compartment
        assignProcessAndLogicOpNodesToCompartment(sbgn);

        // Create Vnodes for ChiLay layout component
        createVNodes(root, sbgn.getMap().getGlyph());

        for (VNode vNode: root.children) {
            createLNode(vNode, null);
        }

        // Create LEdges for ChiLay layout component
        createLEdges(sbgn.getMap().getArc());

        // Apply layout
        if(doLayout) {
            layout.runLayout();
        }

        graphMgr.updateBounds();

        // Here if any SbgnProcessNode node is returned from SBGNPD Layout
        // this means that we will have two additional port info. We should
        // add this information to libSbgn objects
        for (Object lNode : layout.getAllNodes()) {
            if (lNode instanceof SbgnProcessNode) {
                //Set geometry of corresponding node
                VNode vNode = layoutToView.get(((SbgnProcessNode) lNode).label);
                Bbox tempBbox = vNode.glyph.getBbox();
                tempBbox.setX((float) (((SbgnProcessNode) lNode).getLeft()));
                tempBbox.setY((float) (((SbgnProcessNode) lNode).getTop()));
                vNode.glyph.setBbox(tempBbox);

                //Created port objects in layout level
                SbgnPDNode inputLPort = ((SbgnProcessNode) lNode).getInputPort();
                SbgnPDNode outputLPort = ((SbgnProcessNode) lNode).getOutputPort();

                // New port objects
                Port inputPort = new Port();
                Port outputPort = new Port();

                // Set port attributes
                inputPort.setX((float) (inputLPort.getCenterX()));
                inputPort.setY((float) (inputLPort.getCenterY()));
                inputPort.setId(inputLPort.label);

                outputPort.setX((float) (outputLPort.getCenterX()));
                outputPort.setY((float) (outputLPort.getCenterY()));
                outputPort.setId((outputLPort.label));

                //Clear existing ports !
                vNode.glyph.getPort().clear();
                //Connect existing arcs to newly created ports
                //These ports are created by ChiLay and SBGNPD Layout
                connectArcToPort(inputLPort, inputPort);
                connectArcToPort(outputLPort, outputPort);

                //Add ports to the corresponding glyph
                vNode.glyph.getPort().add(inputPort);
                vNode.glyph.getPort().add(outputPort);
            }
        }

        // Update the bounds
        for (VNode vNode: root.children) {
            updateCompoundBounds(vNode.glyph, vNode.glyph.getGlyph());
        }

        // Clear inside of the compartmentGlyphs
        for (Glyph compGlyph: idToCompartmentGlyphs.values()) {
            //Again add the members of compartments
            for(Glyph memberGlyph: compGlyph.getGlyph() ) {
                sbgn.getMap().getGlyph().add(memberGlyph);
            }
            compGlyph.getGlyph().clear();
        }
    }
359042
public void add(T node) {
		for (int i = 0; i < numberOfReplicas; i++) {
			circle.put(hashFunc.hash(node.toString() + i), node);
		}
	}
1152247
private void setNodeRecrusively(ZooNode zooNode, int depth) {
        try {
            int currDepth = depth + 1;
            List<String> children = zkClient.getChildren(zooNode.getPath());
            if (CollectionUtils.isEmpty(children)) {
                zooNode.setLeaf(true);
                return;
            }
            for (String name : children) {
                ZooNode node = new ZooNode(ZkPathUtil.buildPath(zooNode.getPath(), name), name);
                if (currDepth < 2) {
                    node.setOpen(true);
                }
                zooNode.getChildren().add(node);
                setNodeRecrusively(node, currDepth);
            }
        } catch (NoNodeException e) {
            LOG.warn("Zookeeper path not found" + e.getMessage(), e);
        } catch (Exception e) {
            LOG.error("Zookeeper get children error" + e.getMessage(), e);
        }
    }
452607
function(node, canvas, callback) {
     var level = this.getRightLevelToShow(node, canvas), 
         fx = this.viz.labels,
         opt = $.merge({
           execShow:true,
           execHide:true,
           onHide: $.empty,
           onShow: $.empty
         }, callback || {});
     node.eachLevel(0, this.config.levelsToShow, function(n) {
         var d = n._depth - node._depth;
         if(d > level) {
             opt.onHide(n);
             if(opt.execHide) {
               n.drawn = false; 
               n.exist = false;
               fx.hideLabel(n, false);
             }
         } else {
             opt.onShow(n);
             if(opt.execShow) {
               n.exist = true;
             }
         }
     });
     node.drawn= true;
  }
1004517
function CytoDraw(graph, focus_node_list,
		  layout_name, context, elt_id,
		  start_wait, stop_wait, data_call){
    
    var logger = new bbop.logger('CD');
    logger.DEBUG = true;
    function ll(str){ logger.kvetch(str); }

    ll('in');

    // Convert the focus node list into a usable hash.
    var focus_nodes = {};
    each(focus_node_list, function(fn){
	focus_nodes[fn] = true;
    });
    
    // Get the layout information into the position object
    // required by cytoscape.js for sugiyama in grid, if required.
    var position_object = {};
    if( layout_name === 'sugiyama' ){
	var renderer = new bbop.layout.sugiyama.render();
	var layout = renderer.layout(graph);
	var layout_nodes = layout.nodes;
	each(layout_nodes, function(ln){
	    position_object[ln['id']] = {x: ln['x'], y: ln['y']};
	});
    }
    function get_pos(cn){
	var po = position_object[cn.id()];
	return {row: po['y'], col: po['x']};
    }
	
    // Nodes.
    var cyroots = [];
    var cynodes = [];
    var info_lookup = {};
    each(graph.all_nodes(), function(node){
	ll('node: ' + node.id());
	info_lookup[node.id()] = {
	    'id': node.id(), 
	    'label': node.label() || node.id()
	};
	if( graph.is_root_node(node.id()) ){
	    cyroots.push(node.id());
	}
	var node_opts = {
	    //'group': 'nodes',
	    'data': {
		'id': node.id(), 
		'label': node.label() || node.id()
	    },
	    'grabbable': true
	};
	// Highlight the focus if there.
	if( focus_nodes[node.id()] ){
	    node_opts['css'] = { 'background-color': '#111111' };
	}
	cynodes.push(node_opts);
    });
    
    // Edges.
    var cyedges = [];
    each(graph.all_edges(), function(edge){
	var sub = edge.subject_id();
	var obj = edge.object_id();
	var prd = edge.predicate_id();
	var clr = context.color(prd);
        var eid = '' + prd + '_' + sub + '_' + obj;
	ll('edge: ' + eid);
	cyedges.push(
            {
		//'group': 'edges',
		'data': {
                    'id': eid,
                    'pred': prd,
                    // 'source': sub,
                    // 'target': obj
                    'source': obj,
                    'target': sub
		},
		css: {
		    'line-color': clr
		}
            });
    });
    
    // Render.
    var elements = {nodes: cynodes, edges: cyedges};
	
    var layout_opts = {
	'sugiyama': {
            'name': 'grid',
	    'padding': 30,
	    'position': get_pos
	},
	'random': {
	    name: 'random'//,
	    // fit: true
	},
	'grid': {
	    name: 'grid',
	    // fit: true,
	    padding: 30,
	    rows: undefined,
	    columns: undefined
	},
	'circle': {
	    name: 'circle'//,
	    //fit: true
	},
	'concentric': {
	    name: 'concentric'//,
	    //fit: true
	},
	'breadthfirst': {
            'name': 'breadthfirst',
            'directed': true,
            //'fit': true,
	    //'maximalAdjustments': 0,
	    'circle': false,
	    'roots': cyroots
	},
	// 'arbor': {
	// },
	'cose': {
            'name': 'cose'//,
            // 'directed': true,
            // //'fit': true,
	    // //'maximalAdjustments': 0,
	    // 'circle': false,
	    // 'roots': cyroots
	}
    };
    
    jQuery('#' + elt_id).cytoscape(
        {
	    userPanningEnabled: true, // pan over box select
	    'elements': elements,
	    'layout': layout_opts[layout_name],
	    hideLabelsOnViewport: true, // opt
	    hideEdgesOnViewport: true, // opt
	    textureOnViewport: true, // opt
	    'style': [
                {
		    selector: 'node',
		    css: {
                        'content': 'data(label)',
			'font-size': 8,
			'min-zoomed-font-size': 6, //10,
                        'text-valign': 'center',
                        'color': 'white',
			'shape': 'roundrectangle',
                        'text-outline-width': 2,
                        'text-outline-color': '#222222'
		    }
                },
                {
		    selector: 'edge',
		    css: {
                        //'content': 'data(pred)', // opt
                        'width': 2,
			//'curve-style': 'haystack', // opt
                        'line-color': '#6fb1fc'
                        //'source-arrow-shape': 'triangle' // opt
		    }
                }
	    ]
        });
    
    var cy = jQuery('#' + elt_id).cytoscape('get');

    // Bind event.
    cy.nodes().bind('click',
		    function(e){
			e.stopPropagation();
			var nid = e.cyTarget.id();
			start_wait();
			data_call(nid);
		    });
    cy.nodes().bind('mouseover',
		    function(e){
			e.stopPropagation();
			var nid = e.cyTarget.id();
			var nlbl = info_lookup[nid]['label'];
 			var popt = {
			    title: nid,
			    content: nlbl,
			    animation: false,
			    placement: 'top',
			    trigger: 'manual'
			};
			//jQuery(this).popover(popt);
			//jQuery(this).popover('show');
			// TODO/BUG: this popover positioning got out of
			// hand; just rewrite doing it manually with a
			// div from bootstrap like normal people.
			// (couldn't do it the obvious way because the
			// canvas elements are just layers with nothing
			// to adere to).
			var epos = e.cyRenderedPosition;
			jQuery(e.originalEvent.target).popover(popt);
			jQuery(e.originalEvent.target).popover('show');
			jQuery('.arrow').hide();
			jQuery('.popover').css('top', epos.y -100);
			jQuery('.popover').css('left', epos.x -100);
			// TODO/BUG: Also, unfortunately, I cannot
			// figure out why I am stuck with the
			// single frozen pop-up on the versions of
			// jQuery/UI that monarch is using. I cannot
			// change from the intial, probably a quirk of
			// bs3). Manually change it.
			var new_html = '<div style="display: none;" class="arrow"></div><h3 class="popover-title">' + nid + '</h3><div class="popover-content">' + nlbl + '</div>';
			jQuery('.popover').html(new_html);

			//ll('node: ' + nid);
		    });
    cy.nodes().bind('mouseout',
		    function(e){
			e.stopPropagation();
			jQuery(e.originalEvent.target).popover('destroy');
		    });

    // 
    cy.edges().unselectify(); // opt
    cy.boxSelectionEnabled(false);
    cy.resize();
    
    // Make sure re respect resizing.
    jQuery(window).off('resize');
    jQuery(window).on('resize',
		      function(){
			  cy.resize(); 
		      });
    
    stop_wait();
    ll('done');
    return cy;
}
1184902
public double coveringRadiusFromEntries(DBID routingObjectID, AbstractMTree<O, N, E, ?> mTree) {
    double coveringRadius = 0.;
    for(int i = 0; i < getNumEntries(); i++) {
      E entry = getEntry(i);
      final double cover = entry.getParentDistance() + entry.getCoveringRadius();
      coveringRadius = coveringRadius < cover ? cover : coveringRadius;
    }
    return coveringRadius;
  }
251915
function(newRoot, p) {

            var self = this;

            if (document.documentElement.__transition__) return;

            // Rescale outside angles to match the new layout.
            var enterArc,
                exitArc,
                outsideAngle = d3.scale.linear().domain([0, 2 * Math.PI]);

            function insideArc(d) {
                return p.key > d.key
                    ? {depth: d.depth - 1, x: 0, dx: 0} : p.key < d.key
                    ? {depth: d.depth - 1, x: 2 * Math.PI, dx: 0}
                    : {depth: 0, x: 0, dx: 2 * Math.PI};
            }

            function outsideArc(d) {
                return {
                    depth: d.depth + 1, 
                    x: outsideAngle(d.x), 
                    dx: outsideAngle(d.x + d.dx) - outsideAngle(d.x)
                    };
            }

            function arcTween(b) {
                var i = d3.interpolate(this._current, b);
                this._current = i(0);
                return function(t) {
                    return self.arc(i(t));
                };
            }

            self.center.datum(newRoot);
            //console.log("newRoot");
            //console.log(newRoot);

            // When zooming in, 
            // arcs enter from the outside and exit to the inside.
            // Entering outside arcs start from the old layout.
            if (newRoot === p) {
                enterArc = outsideArc;
                exitArc = insideArc;
                outsideAngle.range([p.x, p.x + p.dx]);
            }

            self.path = self.path.data(self.partition.nodes(newRoot)
                                       .slice(1), function(d) { 
                                           return d.key; 
                                       });

            // When zooming out, 
            // arcs enter from the inside and exit to the outside.
            // Exiting outside arcs transition to the new layout.
            if (newRoot !== p) {
                enterArc = insideArc;
                exitArc = outsideArc;
                outsideAngle.range([p.x, p.x + p.dx]);
            }

            d3.transition()
              .duration(d3.event.altKey ? 7500 : 750)
              .each(function() {
                  self.path.exit().transition()
                      .style("fill-opacity", function(d) { 
                          return d.depth === 1 + (newRoot === p) ? 
                                 1 : 0;
                      })
                      .attrTween("d", function(d) { 
                          return arcTween.call(this, exitArc(d));
                      })
                      .remove();

                  self.path.enter().append("path")
                      .style("fill-opacity", function(d) { 
                          return d.depth === 2 - (newRoot === p) ? 
                                 1 : 0;
                      })
                      .style("fill", function(d) { 
                          return d.fill; 
                      })
                      .on("click", function(d, i) {
                          self.zoomIn(d);
                      })
                      .each(function(d) { 
                          this._current = enterArc(d);
                      });
                  // add the tooltip
                  self.path.append("title")
                      .text(function(d) {
                          return d.name + "\n" + 
                                 self.formatNumber(d.value) + 
                                 " Pageviews\n" +
                                 self.formatPercentage(d.value / self.totalValue) + 
                                 " of total pageviews";
                      });

                  self.path.transition()
                      .style("fill-opacity", 1)
                      .attrTween("d", function(d) { 
                          return arcTween.call(this, 
                                                self.updateArc(d)); 
                      });
              });
        }
217129
protected void showCustomSlideStep(final Node node) {

        addSubSlide(node);
        final Node nextSlide = this.subSlides.get(model().getStepPosition());

        if (this.currentSubSlide == null || nextSlide == null) {
            // No Animation
            this.currentSubSlide = nextSlide;
        } else {
            performStepAnimation(nextSlide);
        }
    }
784752
function depth(root) {
	let i = 0;
	let walker = document.createTreeWalker(root, 0xFFFFFFFF, {
		acceptNode: function(node){
			let nt = node.nodeType;
			return nt === 1 || nt === 3;
		}
	});

	while(walker.nextNode()) {
		i++;
	}
	return i;
}
782935
public static void slimNode(RPNode node) {
        if(node.getRight() != null && node.getLeft() != null) {
            node.getIndices().clear();
        }

    }
523982
public void selectAndReveal(INode node) {
		int[] offsetLength = this.locationSearcher.getNodeOffset(node);
		selectAndReveal(offsetLength[0], offsetLength[1]);
	}
755579
public static void centerNode(final Node node, final Double marginSize) {
        AnchorPane.setTopAnchor(node, marginSize);
        AnchorPane.setBottomAnchor(node, marginSize);
        AnchorPane.setLeftAnchor(node, marginSize);
        AnchorPane.setRightAnchor(node, marginSize);
    }
1016772
function squarify(node) {
    var children = node.children;
    if (children && children.length) {
      var rect = pad(node),
          row = [],
          remaining = children.slice(), // copy-on-write
          child,
          best = Infinity, // the best row score so far
          score, // the current row score
          u = Math.min(rect.dx, rect.dy), // initial orientation
          n;
      scale(remaining, rect.dx * rect.dy / node.value);
      row.area = 0;
      while ((n = remaining.length) > 0) {
        row.push(child = remaining[n - 1]);
        row.area += child.area;
        if ((score = worst(row, u)) <= best) { // continue with this orientation
          remaining.pop();
          best = score;
        } else { // abort, and try a different orientation
          row.area -= row.pop().area;
          position(row, u, rect, false);
          u = Math.min(rect.dx, rect.dy);
          row.length = row.area = 0;
          best = Infinity;
        }
      }
      if (row.length) {
        position(row, u, rect, true);
        row.length = row.area = 0;
      }
      children.forEach(squarify);
    }
  }
984925
function revalue(node, depth) {
    var children = node.children,
        v = 0;
    if (children && (n = children.length)) {
      var i = -1,
          n,
          j = depth + 1;
      while (++i < n) v += revalue(children[i], j);
    } else if (value) {
      v = +value.call(hierarchy, d3_layout_hierarchyInline ? node : node.data, depth) || 0;
    }
    if (value) node.value = v;
    return v;
  }