Returns the root node of the abstract syntax tree created by parsing the rule.
192598
function parse(r, s) {
        var p = new ParseState(s, 0, []);
        if (!(r instanceof AstRule))
            r = r.ast;
        if (!r.parser(p))
            return null;
        return p && p.nodes ? p.nodes[0] : null;
    }
78590
def find_root(node):
    """"""
    # Scamper up to the top level namespace
    while node.type != syms.file_input:
        node = node.parent
        if not node:
            raise ValueError("root found before file_input node was found.")
    return node
1143809
public Node getRoot(Node node)
  {

    Node root = null;

    while (node != null)
    {
      root = node;
      node = getParentOfNode(node);
    }

    return root;
  }
1183891
protected Tree determineNonTrivialHead(Tree t, Tree parent) {
    Tree theHead = null;
    String motherCat = tlp.basicCategory(t.label().value());
    if (DEBUG) {
      System.err.println("Looking for head of " + t.label() +
                         "; value is |" + t.label().value() + "|, " +
                         " baseCat is |" + motherCat + '|');
    }
    // We know we have nonterminals underneath
    // (a bit of a Penn Treebank assumption, but).

    // Look at label.
    // a total special case....
    // first look for POS tag at end
    // this appears to be redundant in the Collins case since the rule already would do that
    //    Tree lastDtr = t.lastChild();
    //    if (tlp.basicCategory(lastDtr.label().value()).equals("POS")) {
    //      theHead = lastDtr;
    //    } else {
    String[][] how = nonTerminalInfo.get(motherCat);
    if (how == null) {
      if (DEBUG) {
        System.err.println("Warning: No rule found for " + motherCat +
                           " (first char: " + motherCat.charAt(0) + ')');
        System.err.println("Known nonterms are: " + nonTerminalInfo.keySet());
      }
      if (defaultRule != null) {
        if (DEBUG) {
          System.err.println("  Using defaultRule");
        }
        return traverseLocate(t.children(), defaultRule, true);
      } else {
        return null;
      }
    }
    for (int i = 0; i < how.length; i++) {
      boolean lastResort = (i == how.length - 1);
      theHead = traverseLocate(t.children(), how[i], lastResort);
      if (theHead != null) {
        break;
      }
    }
    if (DEBUG) {
      System.err.println("  Chose " + theHead.label());
    }
    return theHead;
  }
226661
protected function analyseRootNodes()
	{
		// Get every non-XSL element with no non-XSL ancestor. This should return us the first
		// HTML element of every branch
		$query = '//*[namespace-uri() != "' . self::XMLNS_XSL . '"]'
		       . '[not(ancestor::*[namespace-uri() != "' . self::XMLNS_XSL . '"])]';
		foreach ($this->xpath->query($query) as $node)
		{
			// Store the root node of this branch
			$this->rootNodes[] = $node;

			// If any root node is a block-level element, we'll mark the template as such
			if ($this->elementIsBlock($node))
			{
				$this->isBlock = true;
			}

			$this->rootBitfields[] = ElementInspector::getCategoryBitfield($node);
		}

		// Test for non-whitespace text nodes at the root. For that we need a predicate that filters
		// out: nodes with a non-XSL ancestor,
		$predicate = '[not(ancestor::*[namespace-uri() != "' . self::XMLNS_XSL . '"])]';

		// ..and nodes with an <xsl:attribute/>, <xsl:comment/> or <xsl:variable/> ancestor
		$predicate .= '[not(ancestor::xsl:attribute | ancestor::xsl:comment | ancestor::xsl:variable)]';

		$query = '//text()[normalize-space() != ""]' . $predicate
		       . '|'
		       . '//xsl:text[normalize-space() != ""]' . $predicate
		       . '|'
		       . '//xsl:value-of' . $predicate;

		$this->hasRootText = (bool) $this->evaluate('count(' . $query . ')');
	}
686989
def tree(self):
        
        bs = self.model.branchScale
        for node in self._tree.find_clades():
            if node != self._tree.root:
                node.branch_length = self.t[self.name_to_nodeindex[node]] * bs
        return self._tree
1197993
def root(self):
        

        if not self.parent:
            return self

        con = self.parent

        while con.parent:
            con = con.parent

        return con
424828
public SmiOidNode getRootNode() {
        SmiOidNode parent = this;
        while (parent.getParent() != null) {
            parent = parent.getParent();
        }
        return parent;
    }
265565
def getroot(self):
        """"""
        builder = ET.TreeBuilder()
        self.build(builder)
        return builder.close()
761234
function getViewRoot(source) {
	const tokens = parse(source);

	let position = tokens.length;
	let tagDepth = 0;
	let tagName;
	let token;

	/**
	 * Loop backwards through the view's source and find the last closing tag
	 * and its matching opening tag to determine the view's root node position.
	 */
	while (token = tokens[--position]) {
		if (token.type !== TokenTypes.TagStart) {
			continue;
		}

		let tag = parseTag(position, tokens);

		// the last node in the source is a self-closing tag; use that
		if (!tagName && tag.self) {
			break;
		}

		// this is the last tag in the source; save the name and find its pair
		if (!tagName) {
			tagName = tag.name;
			tagDepth++;
			continue;
		}

		// ignore any tags with a different name
		if (tag.name !== tagName) {
			continue;
		}

		// increase tags' depth in the tree for closing tags
		if (!tag.open) {
			tagDepth++;
		}

		// decrease tags' depth in the tree for opening (not self-closing) tags
		if (tag.open && !tag.self) {
			tagDepth--;
		}

		// if the tag's depth reached 0, it means this is the opening tag
		if (tagDepth === 0) {
			break;
		}
	}

	token = tokens[position];

	return token ? token.start : 0;
}
159864
def node_ancestor(node, levels)
      while levels > 0
        node = node.node_parent
        return unless node
        levels -= 1
      end

      node
    end
576571
def splitted_rules(root):
    # type: (Nonterminal) -> Nonterminal
    
    items = Traversing.post_order(root)
    items = filter(lambda x: isinstance(x, SplitRule), items)
    for i in items:
        # create the original rule
        newRule = i.from_rule()
        # replace it with the node in the tree
        Manipulations.replace(i, newRule)
    return root
932663
def get_xpath_root(xpath):
    

    if xpath:
        if xpath.startswith('@'):
            xpath = ''
        else:
            index = xpath.find('/@' if '@' in xpath else '/{')
            xpath = xpath[:index] if index >= 0 else xpath

    return xpath
928732
function parseHierarchy(nodes) {
  let prev = nodes[0], // the previous node
      heads = [[]],    // the set of inserton heads, at each level
      set = heads[0];  // the current insertion set

  nodes.forEach(node => {
    node.children = node.children || [];

    // indented -->
    if (node.level > prev.level) {
      node.level = prev.level + 1; // ensures consistent nesting.
      set = heads[node.level] = prev.children;
    }
    
    // outdented <--
    if (node.level < prev.level) {
      set = heads[node.level] = heads[node.level] || [];
    }

    set.push(node);
    prev = node;
  });

  return heads[0]; // root node set
}
1005850
protected ParserRuleContext getParentSourceElement(ParserRuleContext node) {
        if (node == null) return null;
        ParserRuleContext parent = node.getParent();
        if (parent instanceof QueryParser.SourceElementContext) {
            return parent;
        }
        return getParentSourceElement(parent);
    }
1058069
def _parse_sentencetree(self, tree, parent_node_id=None, ignore_traces=True):
        """"""
        def get_nodelabel(node):
            if isinstance(node, nltk.tree.Tree):
                return node.label()
            elif isinstance(node, unicode):
                return node.encode('utf-8')
            else:
                raise ValueError("Unexpected node type: {0}, {1}".format(type(node), node))

        root_node_id = self._node_id
        self.node[root_node_id]['label'] = get_nodelabel(tree)

        for subtree in tree:
            self._node_id += 1
            node_label = get_nodelabel(subtree)
            # unescape the node label, if necessary
            node_label = PTB_BRACKET_UNESCAPE.get(node_label, node_label)
            # TODO: refactor this, so we don't need to query this all the time
            if ignore_traces and node_label == '-NONE-': # ignore tokens annotated for traces
                continue
            if isinstance(subtree, nltk.tree.Tree):
                if len(subtree) > 1: # subtree is a syntactic category
                    node_attrs = {'label': node_label,
                                  self.ns+':cat': node_label}
                    layers = {self.ns, self.ns+':syntax'}
                else:  # subtree represents a token and its POS tag
                    node_attrs = {'label': node_label}
                    layers = {self.ns}

                edge_type = dg.EdgeTypes.dominance_relation
                self.add_node(self._node_id, layers=layers,
                              attr_dict=node_attrs)
                self.add_edge(root_node_id, self._node_id, edge_type=edge_type)

            else: # isinstance(subtree, unicode); subtree is a token
                # we'll have to modify the parent node of a token, since
                # in NLTK Trees, even a leaf node (with its POS tag) is
                # represented as a Tree (an iterator over a single unicode
                # string), e.g. ``Tree('NNS', ['prices'])``
                pos_tag = self.node[parent_node_id]['label']
                token_attrs = {
                    'label': node_label, self.ns+':token': node_label,
                    self.ns+':pos': pos_tag}
                self.node[parent_node_id].update(token_attrs)
                self.tokens.append(parent_node_id)

            if isinstance(subtree, nltk.tree.Tree):
                self._parse_sentencetree(subtree, parent_node_id=self._node_id)
925676
def schema_root(self) -> "SchemaTreeNode":
        """"""
        sn = self
        while sn.parent:
            sn = sn.parent
        return sn