Recursively builds a tree for proposing new position and momentum
439838
def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize):
        

        # Parameter names in algorithm (here -> representation in algorithm)
        # position -> theta, momentum -> r, slice_var -> u, direction -> v, depth ->j, stepsize -> epsilon
        # candidate_set_size -> n, accept_set_bool -> s
        if depth == 0:
            # Take single leapfrog step in the given direction (direction * stepsize)
            position_bar, momentum_bar, candidate_set_size, accept_set_bool =\
                self._initalize_tree(position, momentum, slice_var, direction * stepsize)

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

        else:
            # Build left and right subtrees
            (position_backward, momentum_backward, position_forward, momentum_forward, position_bar,
             candidate_set_size, accept_set_bool) = self._build_tree(position, momentum,
                                                                     slice_var, direction, depth - 1, stepsize)
            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) = self._build_tree(position_backward, momentum_backward,
                                                          slice_var, direction, depth - 1, stepsize)
                else:
                    # Build tree in forward direction
                    (_, _, position_forward, momentum_forward, position_bar2, candidate_set_size2,
                     accept_set_bool2) = self._build_tree(position_forward, momentum_forward,
                                                          slice_var, direction, depth - 1, stepsize)

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

                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)
1350707
private long grow(PrintStream out, List<ItemSet> list, TotalSupportTree ttree, FPTree.Node node, int[] itemset, int support) {
        int height = 0;
        for (FPTree.Node currentNode = node; currentNode != null; currentNode = currentNode.parent) {
            height ++;
        }

        int n = 0;
        if (height > 0) {
            int[] items = new int[height];
            int i = 0;
            for (FPTree.Node currentNode = node; currentNode != null; currentNode = currentNode.parent) {
                items[i ++] = currentNode.id;
            }

            int[] itemIndexStack = new int[height];
            int itemIndexStackPos = 0;
            itemset = insert(itemset, items[itemIndexStack[itemIndexStackPos]]);
            collect(out, list, ttree, itemset, support);
            n ++;
            while (itemIndexStack[0] < height - 1) {
                if (itemIndexStack[itemIndexStackPos] < height - 1) {
                    itemIndexStackPos ++;
                    itemIndexStack[itemIndexStackPos] = itemIndexStack[itemIndexStackPos - 1] + 1;
                    itemset = insert(itemset, items[itemIndexStack[itemIndexStackPos]]);
                    collect(out, list, ttree, itemset, support);
                    n ++;
                } else {
                    itemset = drop(itemset);
                    if (itemset != null) {
                        itemIndexStackPos --;
                        itemIndexStack[itemIndexStackPos] = itemIndexStack[itemIndexStackPos] + 1;
                        itemset[0] = items[itemIndexStack[itemIndexStackPos]];
                        collect(out, list, ttree, itemset, support);
                        n ++;
                    }
                }
            }
        }

        return n;
    }
1299072
function(root, depth, context, delta) {
        var i;
        var currentValue = context[depth];
        var isMulti = currentValue.constructor === Array;
        if(depth === context.length-1) {
            if(isMulti) {
                for(i=0; i<currentValue.length; i++) {
                    var curDelta = delta;
                    if(root[currentValue[i]] !== undefined) {
                        curDelta = mergeDeep(delta, root[currentValue[i]], true);
                    }
                    root[currentValue[i]] = curDelta;
                }
            } else {
                curDelta = delta;
                if(root[currentValue] !== undefined) {
                    curDelta = mergeDeep(delta, root[currentValue], true);
                }
                root[currentValue] = curDelta;
            }
            return;
        }
        if(isMulti){
            for(i=0; i<currentValue.length; i++) {
                if(root[currentValue[i]] === undefined) {
                    root[currentValue[i]] = {};
                }
                this._buildTreeHelper(root[currentValue[i]], depth+1, context, delta);
            }
        } else {
            if(root[currentValue] === undefined) {
                root[currentValue] = {};
            }
            this._buildTreeHelper(root[currentValue], depth+1, context, delta);
        }
    }
12617
def _traverse_tree(tree, path):
        """"""
        path_steps = (step for step in path.split('.') if step != '')
        # Special handling for first step, because the first step isn't under 'objects'
        first_step = path_steps.next()
        subtree = tree[first_step]

        for step in path_steps:
            subtree = subtree['children'][step]
        return subtree
428952
private GeometryIndex recursiveCreate(GeometryIndex index, int lastValue, GeometryIndexType lastType) {
		if (index.hasChild()) {
			return new GeometryIndex(index.getType(), index.getValue(), recursiveCreate(index.getChild(), lastValue,
					lastType));
		} else {
			GeometryIndexType type = lastType == null ? index.getType() : lastType;
			return new GeometryIndex(type, lastValue, null);
		}
	}
836673
def _build_kth_tree(self):
        """"""
        neg_tau = -1.0 * abs(self.tau_matrix)
        edges = self.previous_tree.edges
        visited = set([0])
        unvisited = set(range(self.n_nodes))

        while len(visited) != self.n_nodes:
            adj_set = set()
            for x in visited:
                for k in range(self.n_nodes):
                    # check if (x,k) is a valid edge in the vine
                    if k not in visited and k != x and self._check_contraint(edges[x], edges[k]):
                        adj_set.add((x, k))

            # find edge with maximum tau
            if len(adj_set) == 0:
                visited.add(list(unvisited)[0])
                continue

            pairs = sorted(adj_set, key=lambda e: neg_tau[e[0]][e[1]])[0]
            left_parent, right_parent = Edge.sort_edge([edges[pairs[0]], edges[pairs[1]]])

            new_edge = Edge.get_child_edge(len(visited) - 1, left_parent, right_parent)
            new_edge.tau = self.tau_matrix[pairs[0], pairs[1]]
            self.edges.append(new_edge)

            visited.add(pairs[1])
            unvisited.remove(pairs[1])
519042
def traversal(root):
    ''''''
    stack = [root]
    while len(stack) > 0:
        node = stack.pop()
        if hasattr(node,'children'):
            if node.children == set():
                try:
                    stack[-1].children.remove(node)
                except:
                    pass
                yield (node,stack)
            else:
                childnode = node.children.pop()
                stack += [node,childnode]
        else: 
            children = [x for x in ast.iter_child_nodes(node)]
            node.children = set(children)
            stack.append(node)
69900
def _build_kth_tree(self):
        """"""
        anchor = self.get_anchor()
        aux_sorted = self._sort_tau_by_y(anchor)
        edges = self.previous_tree.edges

        for itr in range(self.n_nodes - 1):
            right = int(aux_sorted[itr, 0])
            left_parent, right_parent = Edge.sort_edge([edges[anchor], edges[right]])
            new_edge = Edge.get_child_edge(itr, left_parent, right_parent)
            new_edge.tau = aux_sorted[itr, 1]
            self.edges.append(new_edge)
1255539
def build_subtree_strut(self, result, *args, **kwargs):
        
        items = list(result)
        root_elem = {"node": None, "children": OrderedDict()}
        if len(items) == 0:
            return root_elem
        for _, node in enumerate(items):
            new_elem = {"node": node.Resource, "children": OrderedDict()}
            path = list(map(int, node.path.split("/")))
            parent_node = root_elem
            normalized_path = path[:-1]
            if normalized_path:
                for path_part in normalized_path:
                    parent_node = parent_node["children"][path_part]
            parent_node["children"][new_elem["node"].resource_id] = new_elem
        return root_elem
1014135
private void condenseTree(IndexTreePath<E> subtree, Stack<N> stack) {
    N node = getNode(subtree.getEntry());
    // node is not root
    if(!isRoot(node)) {
      N parent = getNode(subtree.getParentPath().getEntry());
      int index = subtree.getIndex();
      if(hasUnderflow(node)) {
        if(parent.deleteEntry(index)) {
          stack.push(node);
        }
        else {
          node.adjustEntry(parent.getEntry(index));
        }
      }
      else {
        node.adjustEntry(parent.getEntry(index));
      }
      writeNode(parent);
      // get subtree to parent
      condenseTree(subtree.getParentPath(), stack);
    }

    // node is root
    else {
      if(hasUnderflow(node) && node.getNumEntries() == 1 && !node.isLeaf()) {
        N child = getNode(node.getEntry(0));
        final N newRoot;
        if(child.isLeaf()) {
          newRoot = createNewLeafNode();
          newRoot.setPageID(getRootID());
          for(int i = 0; i < child.getNumEntries(); i++) {
            newRoot.addLeafEntry(child.getEntry(i));
          }
        }
        else {
          newRoot = createNewDirectoryNode();
          newRoot.setPageID(getRootID());
          for(int i = 0; i < child.getNumEntries(); i++) {
            newRoot.addDirectoryEntry(child.getEntry(i));
          }
        }
        writeNode(newRoot);
        height--;
      }
    }
  }
211602
def move(self, newX1) :
		""""""
		if self.x1 != None and self.x2 != None :
			offset = newX1-self.x1
			aux_moveTree(offset, self)
		elif len(self.children) > 0 :
			offset = newX1-self.children[0].x1
			aux_moveTree(offset, self)
482387
function flattenTree(root) {
  let newChildren = [];
  root.children.forEach(child => {
    const commonParent = getDeepMoreThenOneChild(child);
    if (commonParent.children.length === 0) {
      newChildren.push(commonParent);
    } else {
      newChildren = newChildren.concat(commonParent.children);
    }
  });
  root.children = newChildren;
}
339781
def assoc(self, index, value):
        ''''''
        newnode = LookupTreeNode(index, value)
        newtree = LookupTree()
        newtree.root = _assoc_down(self.root, newnode, 0)
        return newtree
484766
protected N buildTree(int[] msg, int cur, int parent, ArrayList<N> nodes) {
    // Count the number of children:
    int c = 0;
    for(int i = 1; i < msg.length; i += 2) {
      if((msg[i - 1] == cur && msg[i] != parent) || (msg[i] == cur && msg[i - 1] != parent)) {
        c++;
      }
    }
    // Build children:
    List<N> children = Collections.emptyList();
    if(c > 0) {
      children = new ArrayList<>(c);
      for(int i = 1; i < msg.length; i += 2) {
        if(msg[i - 1] == cur && msg[i] != parent) {
          children.add(buildTree(msg, msg[i], cur, nodes));
        }
        else if(msg[i] == cur && msg[i - 1] != parent) {
          children.add(buildTree(msg, msg[i - 1], cur, nodes));
        }
      }
    }
    N node = makeNode(cur, children);
    nodes.set(cur, node);
    return node;
  }
266993
def _build(self, leaves):
        
        new, odd = [], None
        # check if even number of leaves, promote odd leaf to next level, if not
        if len(leaves) % 2 == 1:
            odd = leaves.pop(-1)
        for i in range(0, len(leaves), 2):
            newnode = Node(leaves[i].val + leaves[i + 1].val)
            newnode.l, newnode.r = leaves[i], leaves[i + 1]
            leaves[i].side, leaves[i + 1].side, leaves[i].p, leaves[i + 1].p = 'L', 'R', newnode, newnode
            leaves[i].sib, leaves[i + 1].sib = leaves[i + 1], leaves[i]
            new.append(newnode)
        if odd:
            new.append(odd)
        return new
933100
private static Tree traverse(Tree parent, List<Tree> kids, Tree node) {
        for (Tree kid : kids) {
            if (kid == node) {
                return parent;
            }

            Tree ret = node.parent(kid);
            if (ret != null) {
                return ret;
            }
        }
        return null;
    }
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);
    }