*
Tree building utility functions
503026
function insertComment(data) {
    var parent = stack.top;
    if (foster_parent_mode && isA(parent, tablesectionrowSet)) {
      fosterParent(function(doc) { return doc.createComment(data); });
    } else {
      // "If the adjusted insertion location is inside a template element,
      // let it instead be inside the template element's template contents"
      if (parent instanceof impl.HTMLTemplateElement) {
        parent = parent.content;
      }
      parent._appendChild(parent.ownerDocument.createComment(data));
    }
  }
916455
function Node(tree, options) {
		this.tree = tree;
		if (options && options.parent) {this.parent = options.parent;}
		if (options && options.hasOwnProperty('key')) { this.key = options.key; }
		this.data = options && options.hasOwnProperty('value') ? [options.value] : [];
	}
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
642029
function treeSetMutable (address, tree, value) {
  if (address.length === 0) {
    return value
  } else {
    const [ rest, last ] = tail(address)
    const parent = treeGet(rest, tree)
    if (checkType(NODE, parent)) {
      parent.children[last] = value
    } else {
      parent[last] = value
    }
    return tree
  }
}
800200
async function buildLocalDepTree() {
  for (const packageName of await _list()) {
    tree.set(packageName, await exports.list(packageName, {
      includeTransitive: false,
      localOnly: true
    }));
  }
}
1117047
function treeSorter(node) {
    if(node[options.childsProp]) {
      node[options.childsProp].forEach(function(node) {
        treeSorter(node);
      });
      node[options.childsProp].sort(function childSorter(a, b) {
        var result;
        if('undefined' === typeof a[options.sortProp]) {
          result = (options.sortDesc ? 1 : -1);
        } else if('undefined' === typeof b[options.sortProp]) {
          result = (options.sortDesc ? -1 : 1);
        } else {
          result = a[options.sortProp] > b[options.sortProp] ?
            (options.sortDesc ? -1 : 1) : (options.sortDesc ? 1 : -1);
        }
        return result;
      });
    }
  }
856909
function buildTree(tokens) {
  var items = _.map(tokens, function(token) {
    return tartan.utils.node.newStripe(token);
  });
  var isReflected = (tokens.length >= 2) && (tokens[0].isPivot);
  return tartan.utils.node.newRootBlock(items, isReflected);
}
675482
function buildHierarchy(csv) {
  var root = {"name": "root", "children": []};
  for (var i = 0; i < csv.length; i++) {
    var sequence = csv[i][0];
    var size = +csv[i][1];
    if (isNaN(size)) { // e.g. if this is a header row
      continue;
    }
    var parts = sequence.split("/");
    var currentNode = root;
    for (var j = 0; j < parts.length; j++) {
      var children = currentNode["children"];
      var nodeName = parts[j];
      var childNode;
      if (j + 1 < parts.length) {
   // Not yet at the end of the sequence; move down the tree.
 	var foundChild = false;
 	for (var k = 0; k < children.length; k++) {
 	  if (children[k]["name"] == nodeName) {
 	    childNode = children[k];
 	    foundChild = true;
 	    break;
 	  }
 	}
  // If we don't already have a child node for this branch, create it.
 	if (!foundChild) {
 	  childNode = {"name": nodeName, "children": []};
 	  children.push(childNode);
 	}
 	currentNode = childNode;
      } else {
 	// Reached the end of the sequence; create a leaf node.
 	childNode = {"name": nodeName, "size": size};
 	children.push(childNode);
      }
    }
  }
  return root;
}
97033
function lazyBuildObjectTree(priv, formatted) {
  definePropertyGetters(formatted, {
    children: lazy(function() { return priv.fqnMap.getChildrenOf(formatted.fqn); }),
    fields: lazy(function() { return formatted.children.filter(Filter.ofType('property')); }),
    methods: lazy(function() { return formatted.children.filter(Filter.ofType('function')); }),
    parent: lazy(function() { return priv.fqnMap.getParentOf(formatted.fqn); }),
    parentElement: lazy(function() { return priv.fqnMap.get(formatted.idTags['parent-element']); }),
  });
}
1203695
async function makeDirTree() {
    console.log('Creating Directory Tree ...');
    let dirTree = {},
        dirs = [],
        relative = '';
    AllFiles = {};
    idx = 0;
    id = 0;

    dirs.push({ name: 'root', type: 'dir', path: `.`, files: {} });
    dirTree['root'] = { name: 'root', type: 'dir', path: `.`, files: {} };
    return new Promise(async(res, rej) => {
        console.log('Reading files ...');
        while (dirs.length > 0) {
            let activeDir = dirs.shift(),
                files = await walkTree(activeDir.path);
            if (files.length > 0) {
                for (const i of files) {
                    let name = i.type === 'dir' ? i.name : idx++;
                    if (i.type === 'dir' && !i.path.match(/node_modules|.git|bower/)) {
                        dirs.push(i);
                    }
                    activeDir.files[name] = i;
                }
            }
            dirTree[activeDir.name] = activeDir;
        }
        dirTree = dirTree.root;
        res([dirTree, AllFiles]);
    })
}
590273
function toArray(tree, f) {
	var out = [];
	if (tree.root) {
		_util.rootToArray(tree.root, f, out);
	}
	var tail = tree.tail;
	for(var i = 0, l = tail.length; i<l; i++) {
		out.push(f(tail[i]));
	}
	return out;
}
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();}
       }
310227
def _build_tree(self):
        
        if not self.nn_ready:
            self.kdtree   = scipy.spatial.cKDTree(self.data)
            self.nn_ready = True
1348031
function _addToTree(tree, branchToken, leafToken) {
  /* eslint-disable max-len, no-param-reassign */
  const leafValue = Utils.merge(tree[branchToken].fields[leafToken] || {}, _parseLeafToken(leafToken));
  tree[branchToken].fields[leafToken] = leafValue;
  /* eslint-enable max-len, no-param-reassign */

  return tree;
}
16720
function(treeRoot) {
      var stat = fs.statSync(treeRoot);
      if (stat.isDirectory()) {
        return buildTree(treeRoot);
      } else {
        throw new Error("path: " + treeRoot + " is not a directory");
      }
    }
972957
function mergeTree(in_tree1, in_tree2) {
  var queue = [{tree1: in_tree1, tree2: in_tree2}];
  var conflicts = false;
  while (queue.length > 0) {
    var item = queue.pop();
    var tree1 = item.tree1;
    var tree2 = item.tree2;

    if (tree1[1].status || tree2[1].status) {
      tree1[1].status =
        (tree1[1].status ===  'available' ||
        tree2[1].status === 'available') ? 'available' : 'missing';
    }

    for (var i = 0; i < tree2[2].length; i++) {
      if (!tree1[2][0]) {
        conflicts = 'new_leaf';
        tree1[2][0] = tree2[2][i];
        continue;
      }

      var merged = false;
      for (var j = 0; j < tree1[2].length; j++) {
        if (tree1[2][j][0] === tree2[2][i][0]) {
          queue.push({tree1: tree1[2][j], tree2: tree2[2][i]});
          merged = true;
        }
      }
      if (!merged) {
        conflicts = 'new_branch';
        insertSorted(tree1[2], tree2[2][i], compareTree);
      }
    }
  }
  return {conflicts: conflicts, tree: in_tree1};
}
23023
function arrayTreeFilter (data, filterFn, options) {
    options = options || {}
    options.childrenKeyName = options.childrenKeyName || 'children'
    let children = data || []
    const result = []
    let level = 0
    do {
        const foundItem = children.filter(function (item) {
            return filterFn(item, level)
        })[0]
        if (!foundItem) {
            break
        }
        result.push(foundItem)
        children = foundItem[options.childrenKeyName] || []
        level += 1
    } while (children.length > 0)
    return result
}