used to build the tree
350335
function(data) {
			// parse basic info from the dom item
			var item = {
				link: data.id,
				text: data.textContent || data.innerText,
				parent: ''
			};

			// build type identifier
			var level = data.tagName;
			for (var i = 0; i < data.classList.length; i++) {
				level += ',' + data.classList[i];
			}

			// here be dragons
			var stacksize = stack.length;
			if (stacksize === 0) {
				// we are at the top level and will stay there
				stack.push(level);
			} else if (level !== stack[stacksize - 1]) {
				// traverse the ancestry, looking for a match
				for (var j = stacksize - 1; j >= 0; j--) {
					if (level == stack[j]) {
						break; // found an ancestor
					}
				}
				if (j < 0) {
					// this is a new submenu item, lets push the stack
					stack.push(level);
					item.push = true;
					parentstack.push(lastitem);
				} else {
					// we are either a sibling or higher up the tree,
					// lets pop the stack if needed
					item.pop = stacksize - 1 - j;
					while (stack.length > j + 1) {
						stack.pop();
						parentstack.pop();
					}
				}
			}

			// if we have a parent, lets record it
			if(parentstack.length > 0) {
				item.parent= parentstack[parentstack.length-1];
			}

			// for next iteration
			lastitem= item.link;
			return item;
		}
658058
function _buildTree(&$tree, &$element) {
        $tree[$element->name()] = $element;
        if ($element->superclass()) {
            $rootDoc = & $this->_doclet->rootDoc();
            $superclass = & $rootDoc->classNamed($element->superclass());
            if ($superclass) {
                $this->_buildTree($tree, $superclass);
            }
        }
    }
145987
def __Build(leaves):
        
        if len(leaves) < 1:
            raise Exception('Leaves must have length')
        if len(leaves) == 1:
            return leaves[0]

        num_parents = int((len(leaves) + 1) / 2)
        parents = [MerkleTreeNode() for i in range(0, num_parents)]

        for i in range(0, num_parents):
            node = parents[i]
            node.LeftChild = leaves[i * 2]
            leaves[i * 2].Parent = node
            if (i * 2 + 1 == len(leaves)):
                node.RightChild = node.LeftChild
            else:
                node.RightChild = leaves[i * 2 + 1]
                leaves[i * 2 + 1].Parent = node

            hasharray = bytearray(node.LeftChild.Hash.ToArray() + node.RightChild.Hash.ToArray())
            node.Hash = UInt256(data=Crypto.Hash256(hasharray))

        return MerkleTree.__Build(parents)
574674
function build(importsObj, tree) {
  const modules = {};

  const instantiate = filepath => {
    if (modules[filepath] != null) {
      return modules[filepath];
    }

    const mod = tree.modules[filepath];
    const promise = Promise.all(
      Object.entries(mod.deps).map(([key, dep]) => {
        return instantiate(dep.filepath).then(result => [key, result]);
      })
    )
      .then(importsMap => {
        const imports = importsMap.reduce((acc, [key, module]) => {
          acc[key] = module.instance.exports;
          return acc;
        }, {});

        return WebAssembly.instantiate(
          tree.opcodes[filepath],
          Object.assign({}, imports, importsObj)
        );
      })
      .catch(e => {
        // TODO: do some logging here
        throw e;
      });

    modules[filepath] = promise;

    return promise;
  };

  modules[tree.root.filepath] = instantiate(tree.root.filepath);

  return modules[tree.root.filepath];
}
499418
function buildTree(index, api) {
  const modules = {};

  const dependency = (module, parent) => {
    const filepath = api.resolve(module, parent);
    if (modules[filepath] != null) {
      return modules[filepath];
    }

    const src = api.getFileContents(module, parent, "utf8");
    const basic = api.parser(src);
    const [nestedImports, hasMemory] = parseImports(basic, api);

    const deps = {};

    Object.keys(nestedImports).forEach(mod => {
      if (mod.indexOf(".") === 0) {
        const dep = dependency(mod, filepath);
        deps[mod] = dep;
      }
    });

    const patched = inferImportTypes(basic, deps, api);
    const ast = api.semantics(patched);

    api.validate(ast, {
      lines: src.split("\n"),
      filename: module.split("/").pop(),
    });

    const result = {
      ast,
      deps,
      filepath,
      hasMemory,
    };
    modules[filepath] = result;

    return result;
  };

  const root = dependency(index, null);

  return {
    root,
    modules,
  };
}
451134
void  build() {
           // If there were no rules, just return.  This situation can easily arise
           //   for the reverse rules.
           if (fRB.fTreeRoots[fRootIx]==null) {
               return;
           }

           //
           // Walk through the tree, replacing any references to $variables with a copy of the
           //   parse tree for the substition expression.
           //
           fRB.fTreeRoots[fRootIx] = fRB.fTreeRoots[fRootIx].flattenVariables();
           if (fRB.fDebugEnv!=null && fRB.fDebugEnv.indexOf("ftree")>=0) {
               System.out.println("Parse tree after flattening variable references.");
               fRB.fTreeRoots[fRootIx].printTree(true);
           }

           //
           // If the rules contained any references to {bof}
           //   add a {bof} <cat> <former root of tree> to the
           //   tree.  Means that all matches must start out with the
           //   {bof} fake character.
           //
           if (fRB.fSetBuilder.sawBOF()) {
               RBBINode bofTop    = new RBBINode(RBBINode.opCat);
               RBBINode bofLeaf   = new RBBINode(RBBINode.leafChar);
               bofTop.fLeftChild  = bofLeaf;
               bofTop.fRightChild = fRB.fTreeRoots[fRootIx];
               bofLeaf.fParent    = bofTop;
               bofLeaf.fVal       = 2;      // Reserved value for {bof}.
               fRB.fTreeRoots[fRootIx] = bofTop;
           }

           //
           // Add a unique right-end marker to the expression.
           //   Appears as a cat-node, left child being the original tree,
           //   right child being the end marker.
           //
           RBBINode cn = new RBBINode(RBBINode.opCat);
           cn.fLeftChild = fRB.fTreeRoots[fRootIx];
           fRB.fTreeRoots[fRootIx].fParent = cn;
           cn.fRightChild = new RBBINode(RBBINode.endMark);
           cn.fRightChild.fParent = cn;
           fRB.fTreeRoots[fRootIx] = cn;

           //
           //  Replace all references to UnicodeSets with the tree for the equivalent
           //      expression.
           //
           fRB.fTreeRoots[fRootIx].flattenSets();
           if (fRB.fDebugEnv!=null && fRB.fDebugEnv.indexOf("stree")>=0) {
               System.out.println("Parse tree after flattening Unicode Set references.");
               fRB.fTreeRoots[fRootIx].printTree(true);
           }


           //
           // calculate the functions nullable, firstpos, lastpos and followpos on
           // nodes in the parse tree.
           //    See the alogrithm description in Aho.
           //    Understanding how this works by looking at the code alone will be
           //       nearly impossible.
           //
           calcNullable(fRB.fTreeRoots[fRootIx]);
           calcFirstPos(fRB.fTreeRoots[fRootIx]);
           calcLastPos(fRB.fTreeRoots[fRootIx]);
           calcFollowPos(fRB.fTreeRoots[fRootIx]);
           if (fRB.fDebugEnv!=null && fRB.fDebugEnv.indexOf("pos")>=0) {
               System.out.print("\n");
               printPosSets(fRB.fTreeRoots[fRootIx]);
           }

           //
           //  For "chained" rules, modify the followPos sets
           //
           if (fRB.fChainRules) {
               calcChainedFollowPos(fRB.fTreeRoots[fRootIx]);
           }

           //
           //  BOF (start of input) test fixup.
           //
           if (fRB.fSetBuilder.sawBOF()) {
               bofFixup();
           }

           //
           // Build the DFA state transition tables.
           //
           buildStateTable();
           flagAcceptingStates();
           flagLookAheadStates();
           flagTaggedStates();

           //
           // Update the global table of rule status {tag} values
           // The rule builder has a global vector of status values that are common
           //    for all tables.  Merge the ones from this table into the global set.
           //
           mergeRuleStatusVals();

           if (fRB.fDebugEnv!=null && fRB.fDebugEnv.indexOf("states")>=0) {printStates();}
       }
781650
private void buildCoverTree() {
        ArrayList<DistanceSet> pointSet = new ArrayList<>();
        ArrayList<DistanceSet> consumedSet = new ArrayList<>();

        E point = data[0];
        int idx = 0;
        double maxDist = -1;

        for (int i = 1; i < data.length; i++) {
            DistanceSet set = new DistanceSet(i);
            double dist = distance.d(point, data[i]);
            set.dist.add(dist);
            pointSet.add(set);
            if (dist > maxDist) {
                maxDist = dist;
            }
        }

        root = batchInsert(idx, getScale(maxDist), getScale(maxDist), pointSet, consumedSet);
    }
839673
def build_tree(self):
        """"""
        for spec in self.specs:
            if spec.ismodule:
                self.modules.append(Module(spec.name, spec.path, dsm=self))
            else:
                self.packages.append(Package(
                    spec.name, spec.path,
                    dsm=self, limit_to=spec.limit_to,
                    build_tree=True,
                    build_dependencies=False,
                    enforce_init=self.enforce_init))
778970
public void buildTree(INDArray x) {
        this.X = x;
        for(int i = 0; i < x.rows(); i++) {
            root.getIndices().add(i);
        }



        RPUtils.buildTree(this,root,rpHyperPlanes,
                x,maxSize,0,similarityFunction);
    }
969141
def build_tree(self, *args, **kwargs):
        """"""
        # Check length #
        assert len(self) > 3
        # Default option #
        algorithm = kwargs.pop(kwargs, None)
        if algorithm is None: algorithm = 'raxml'
        # Dispatch #
        if algorithm is 'raxml':    return self.build_tree_raxml(*args, **kwargs)
        if algorithm is 'fasttree': return self.build_tree_fast(*args, **kwargs)
909152
def _build_tree(self):
        
        #find unassigned i*
        istar = np.argmin(self._x)

        #compute distances
        self._d = self.c[istar] - self._v
        _pred = np.zeros(self.n, dtype=np.int) + istar

        #initialize sets
        #READY: set of nodes visited and in the path (whose price gets
        #updated in augment)
        #SCAN: set of nodes at the bottom of the tree, which we need to
        #look at
        #T0DO: unvisited nodes
        _ready = np.zeros(self.n, dtype=np.bool)
        _scan = np.zeros(self.n, dtype=np.bool)
        _todo = np.zeros(self.n, dtype=np.bool) + True

        while True:
            #populate scan with minimum reduced distances
            if True not in _scan:
                mu = np.min(self._d[_todo])
                _scan[self._d == mu] = True
                _todo[_scan] = False
                j = np.argmin(self._y * _scan)
                if self._y[j] == -1 and _scan[j]:
                    return _pred, _ready, istar, j, mu

            #pick jstar from scan (scan always has at least 1)
            _jstar = np.argmax(_scan)

            #pick i associated with jstar
            i = self._y[_jstar]

            _scan[_jstar] = False
            _ready[_jstar] = True

            #find shorter distances
            newdists = mu + self.cred[i, :]
            shorter = np.logical_and(newdists < self._d, _todo)

            #update distances
            self._d[shorter] = newdists[shorter]

            #update predecessors
            _pred[shorter] = i

            for j in np.nonzero(np.logical_and(self._d == mu, _todo))[0]:
                if self._y[j] == -1:
                    return _pred, _ready, istar, j, mu
                _scan[j] = True
                _todo[j] = False
1179752
def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize, position0, momentum0):
        
        if depth == 0:

            position_bar, momentum_bar, candidate_set_size, accept_set_bool =\
                self._initalize_tree(position, momentum, slice_var, direction * stepsize)

            alpha = min(1, self._acceptance_prob(position, position_bar, momentum, momentum_bar))

            return (position_bar, momentum_bar, position_bar, momentum_bar, position_bar,
                    candidate_set_size, accept_set_bool, alpha, 1)

        else:
            (position_backward, momentum_backward, position_forward, momentum_forward, position_bar,
             candidate_set_size, accept_set_bool, alpha, n_alpha) =\
                self._build_tree(position, momentum, slice_var,
                                 direction, depth - 1, stepsize, position0, momentum0)

            if accept_set_bool == 1:
                if direction == -1:
                    # Build tree in backward direction
                    (position_backward, momentum_backward, _, _, position_bar2, candidate_set_size2, accept_set_bool2,
                     alpha2, n_alpha2) = self._build_tree(position_backward, momentum_backward, slice_var, direction,
                                                          depth - 1, stepsize, position0, momentum0)
                else:
                    # Build tree in forward direction
                    (_, _, position_forward, momentum_forward, position_bar2, candidate_set_size2, accept_set_bool2,
                     alpha2, n_alpha2) = self._build_tree(position_forward, momentum_forward, slice_var, direction,
                                                          depth - 1, stepsize, position0, momentum0)

                if np.random.rand() < candidate_set_size2 / (candidate_set_size2 + candidate_set_size):
                    position_bar = position_bar2

                alpha += alpha2
                n_alpha += n_alpha2
                accept_set_bool, candidate_set_size =\
                    self._update_acceptance_criteria(position_forward, position_backward, momentum_forward,
                                                     momentum_backward, accept_set_bool2, candidate_set_size,
                                                     candidate_set_size2)

            return (position_backward, momentum_backward, position_forward, momentum_forward, position_bar,
                    candidate_set_size, accept_set_bool, alpha, n_alpha)
703134
def _build_tree(node, sourcetree):
    
    for child_source_node in sourcetree:
        try:
            main_file = child_source_node['files'][0] if 'files' in child_source_node else {}
            kind = guess_content_kind(path=main_file.get('path'), web_video_data=main_file.get('youtube_id') or main_file.get('web_url'), questions=child_source_node.get("questions"))
        except UnknownContentKindError:
            continue

        if kind == content_kinds.TOPIC:
            child_node = nodes.TopicNode(
                source_id=child_source_node["id"],
                title=child_source_node["title"],
                author=child_source_node.get("author"),
                description=child_source_node.get("description"),
                thumbnail=child_source_node.get("thumbnail"),
            )
            node.add_child(child_node)

            source_tree_children = child_source_node.get("children", [])

            _build_tree(child_node, source_tree_children)

        elif kind == content_kinds.VIDEO:
            child_node = nodes.VideoNode(
                source_id=child_source_node["id"],
                title=child_source_node["title"],
                license=get_license(child_source_node.get("license"), description="Description of license", copyright_holder=child_source_node.get('copyright_holder')),
                author=child_source_node.get("author"),
                description=child_source_node.get("description"),
                derive_thumbnail=True, # video-specific data
                thumbnail=child_source_node.get('thumbnail'),
            )
            add_files(child_node, child_source_node.get("files") or [])
            node.add_child(child_node)

        elif kind == content_kinds.AUDIO:
            child_node = nodes.AudioNode(
                source_id=child_source_node["id"],
                title=child_source_node["title"],
                license=child_source_node.get("license"),
                author=child_source_node.get("author"),
                description=child_source_node.get("description"),
                thumbnail=child_source_node.get("thumbnail"),
                copyright_holder=child_source_node.get("copyright_holder"),
            )
            add_files(child_node, child_source_node.get("files") or [])
            node.add_child(child_node)

        elif kind == content_kinds.DOCUMENT:
            child_node = nodes.DocumentNode(
                source_id=child_source_node["id"],
                title=child_source_node["title"],
                license=child_source_node.get("license"),
                author=child_source_node.get("author"),
                description=child_source_node.get("description"),
                thumbnail=child_source_node.get("thumbnail"),
                copyright_holder=child_source_node.get("copyright_holder"),
            )
            add_files(child_node, child_source_node.get("files") or [])
            node.add_child(child_node)

        elif kind == content_kinds.EXERCISE:
            mastery_model = (child_source_node.get('mastery_model') and {"mastery_model": child_source_node['mastery_model']}) or {}
            child_node = nodes.ExerciseNode(
                source_id=child_source_node["id"],
                title=child_source_node["title"],
                license=child_source_node.get("license"),
                author=child_source_node.get("author"),
                description=child_source_node.get("description"),
                exercise_data=mastery_model,
                thumbnail=child_source_node.get("thumbnail"),
                copyright_holder=child_source_node.get("copyright_holder"),
            )
            add_files(child_node, child_source_node.get("files") or [])
            for q in child_source_node.get("questions"):
                question = create_question(q)
                child_node.add_question(question)
            node.add_child(child_node)

        elif kind == content_kinds.HTML5:
            child_node = nodes.HTML5AppNode(
                source_id=child_source_node["id"],
                title=child_source_node["title"],
                license=child_source_node.get("license"),
                author=child_source_node.get("author"),
                description=child_source_node.get("description"),
                thumbnail=child_source_node.get("thumbnail"),
                copyright_holder=child_source_node.get("copyright_holder"),
            )
            add_files(child_node, child_source_node.get("files") or [])
            node.add_child(child_node)

        else:                   # unknown content file format
            continue

    return node
1347835
function plotTree(tree,x,y) {
  var results=[],items=[],
      width=0,height=0,
      fromX=x,top=y,bottom=y;
  if (!tree.length) return plotNode.empty(null,x,y);
  tree.forEach(function (node) {
    var ret;
    if (node.repeat) {
      ret=plotNode.repeat(node,fromX,y);
    } else {
      ret=plotNode[node.type](node,fromX,y);
    }
    results.push(ret);
    fromX+=ret.width+PATH_LEN;
    width+=ret.width;
    top=Math.min(top,ret.y);
    bottom=Math.max(bottom,ret.y+ret.height);
    items=items.concat(ret.items);
  });
  height=bottom-top;
  results.reduce(function (a,b) {
    width+=PATH_LEN;
    var p=hline(a.lineOutX,y,b.lineInX);
    items.push(p);
    return b;
  });
  var lineInX=results[0].lineInX,lineOutX=results[results.length-1].lineOutX;
  return {
    items:items,
    width:width,height:height,x:x,y:top,
    lineInX:lineInX,lineOutX:lineOutX
  };
}
1205821
public void gotoEnd() {
	currentNode = tree;
	while (currentNode.hasChildren()) {
	    currentNode = currentNode.getChildren().get(
		    currentNode.getChildren().size() - 1);
	}
    }
219857
private StringTreeNode buildOrgHierarchyTree(final Object[] data) {
		StringTreeNode childNode = new StringTreeNode((String) data[0]);

		if (data.length > 1) {
			for (int i = 1; i < data.length; i++) {
				childNode.add(buildOrgHierarchyTree((Object[]) data[i]));
			}
		}

		return childNode;
	}
1083025
def setup_tree(self):
        """"""
        self.tree.insert("", tk.END, text="Example 1", iid="1")
        self.tree.insert("", tk.END, text="Example 2", iid="2")
        self.tree.insert("2", tk.END, text="Example Child")
        self.tree.heading("#0", text="Example heading")