Compare the given parsed trees.

        :param dict parsed_pytree: A dictionary representing the parsed Python tree where each
            key is a parsed Python file and its key is its expected rst file name.
332348
def compare_trees(self, parsed_pytree, parsed_doctree):
        
        if parsed_pytree == parsed_doctree:
            return 0

        missing_pys, missing_docs = self.calculate_tree_differences(pytree=parsed_pytree,
                                                                    doctree=parsed_doctree)
        self.pprint_tree_differences(missing_pys=missing_pys, missing_docs=missing_docs)
        return 0 if self.args.no_fail else 1
1158252
def find_py_files(srctree, ignore=None):
        

        if not os.path.isdir(srctree):
            yield os.path.split(srctree)
        for srcpath, _, fnames in os.walk(srctree):
            # Avoid infinite recursion for silly users
            if ignore is not None and ignore in srcpath:
                continue
            for fname in (x for x in fnames if x.endswith('.py')):
                yield srcpath, fname
9310
def _token_list_matches_tree(self, token_list):
        
        try:
            parsed_selector = cssselect.parse(
                ''.join(token.as_css() for token in token_list))[0]

            return bool(
                self.tree.xpath(
                    self.xpath_translator.selector_to_xpath(parsed_selector)))
        except:
            # On error, assume the selector matches the tree
            return True
418428
def get_raw(tree):
    
    if isinstance(tree, Tree):
        words = []
        for child in tree:
            words.append(get_raw(child))
        return ' '.join(words)
    else:
        return tree
31420
def etree_to_dict(tree):
    
    d = {tree.tag.split('}')[1]: map(
        etree_to_dict, tree.iterchildren()
    ) or tree.text}

    return d
1268292
def phylotree(self):
        
        if not self._phylotree or self._dirty:
            try:
                if ISPY3:
                    self._phylotree = PhyloTree(self.newick.encode(), self.rooted)
                else:
                    self._phylotree = PhyloTree(self.newick, self.rooted)
            except ValueError:
                logger.error('Couldn\'t convert to C++ PhyloTree -- are there bootstrap values?')
            self._dirty = False
        return self._phylotree
781938
def get_tree(self, process_name):
        
        for tree_name, tree in self.trees.items():
            if process_name in tree:
                return tree
1240307
def hs2015tree2dgparentedtree(self):
        
        def transform(hs2015_tree):
            """Transform a HS2015 parse tree into a more conventional parse tree.

            The input tree::

                                 ROOT
                        __________|________
                satellite:contra      nucleus:span
                       st                  |
                       |                   |
                      text                text
                       |                   |
                    Although              they
                    they did            accepted
                    n't like           the offer
                      it ,                 .

                                  Contrast
                         ____________|___________
                        S                        N
                        |                        |
                  Although they            they accepted
                did n't like it ,           the offer .
            """
            if is_leaf_node(hs2015_tree):
                return hs2015_tree

            tree_type = get_tree_type(hs2015_tree)
            if tree_type in (SubtreeType.root, SubtreeType.nucleus, SubtreeType.satellite):
                child_types = get_child_types(hs2015_tree)
                rel_nuc_type = get_nuclearity_type(child_types)
                if rel_nuc_type == NucType.nucsat:
                    nuc_id = child_types['nucleus'][0]
                    sat_id = child_types['satellite'][0]
                    return get_nucsat_subtree(hs2015_tree, nuc_id, sat_id)

                elif rel_nuc_type == NucType.multinuc:
                    transformed_subtrees = [Tree('N', [transform(st)]) for st in hs2015_tree]
                    # in a multinuc, all nucs will carry the relation name
                    relname = get_capitalized_relname(hs2015_tree, 0)
                    return Tree(relname, transformed_subtrees)

                elif rel_nuc_type == NucType.multisat:
                    # In RST, multiple satellites (at least adjacent ones)
                    # can be in a relation with the same nucleus.
                    # To express this in a tree, we convert this schema to
                    # a left-branching structure, e.g. (((N S) S) S).
                    nuc_id = child_types['nucleus'][0]
                    first_sat_id in child_types['satellite'][0]

                    multisat_subtree = get_nucsat_subtree(hs2015_tree, nuc_id, first_sat_id)
                    for sat_id in child_types['satellite'][1:]:
                        sat_subtree = hs2015_tree[sat_id]
                        relname = get_capitalized_relname(hs2015_tree, sat_id)
                        multisat_subtree = Tree(relname, [
                            Tree('N', [multisat_subtree]),
                            Tree('S', [transform(sat_subtree)])
                        ])
                    return multisat_subtree

                elif rel_nuc_type == NucType.edu:
                    # return the EDU text string
                    return hs2015_tree[0][0]

                else:
                    raise ValueError("Unknown nuclearity type: {}".format(rel_nuc_type))

            else:
                assert tree_type == SubtreeType.text

        def get_nucsat_subtree(tree, nuc_id, sat_id):
            nuc_subtree = tree[nuc_id]
            sat_subtree = tree[sat_id]
            relname = get_capitalized_relname(tree, sat_id)

            # determine order of subtrees
            if nuc_id < sat_id:
                return Tree(relname, [
                    Tree('N', [transform(nuc_subtree)]),
                    Tree('S', [transform(sat_subtree)])
                ])
            else:
                return Tree(relname, [
                    Tree('S', [transform(sat_subtree)]),
                    Tree('N', [transform(nuc_subtree)])
                ])

        tree = transform(self.hs2015file_tree)
        return DGParentedTree.convert(tree)
1230896
def fromtree(cls, tree):
        
        mets = cls()
        mets.tree = tree
        mets._parse_tree(tree)

        return mets
680743
def parse_simplereq(self, tup_tree):
        

        self.check_node(tup_tree, 'SIMPLEREQ')

        child = self.one_child(tup_tree, ('IMETHODCALL', 'METHODCALL'))

        return name(tup_tree), attrs(tup_tree), child
716026
def get_trees(self, data, showerrors = False): # -> list:
        
        if showerrors:
            raise NotImplementedError("This parser doesn't implement errors")
        self.data = data
        self.index = 0
        try:
            return [self.__aux_parser(self._productionset.initialsymbol)]
        except (IndexError, ParseError):
            return []
1059057
def tree(self, path):
        '''
        
        '''
        ret = {}
        try:
            items = self.read(path)
        except (etcd.EtcdKeyNotFound, ValueError):
            return None
        except etcd.EtcdConnectionFailed:
            log.error("etcd: failed to perform 'tree' operation on path %s due to connection error", path)
            return None

        for item in items.children:
            comps = six.text_type(item.key).split('/')
            if item.dir is True:
                if item.key == path:
                    continue
                ret[comps[-1]] = self.tree(item.key)
            else:
                ret[comps[-1]] = item.value
        return ret
793919
def dplptree2dgparentedtree(self):
        
        def transform(dplp_tree):
            """Transform a DPLP parse tree into a more conventional parse tree."""
            if isinstance(dplp_tree, basestring) or not hasattr(dplp_tree, 'label'):
                return dplp_tree
            assert len(dplp_tree) == 2, "We can only handle binary trees."

            match = DPLP_REL_RE.match(dplp_tree.label())
            assert match, "Relation '{}' does not match regex '{}'".format(dplp_tree.label(), DPLP_REL_RE)
            left_child_nuc, right_child_nuc, relname = match.groups()
            dplp_tree._label = relname

            for i, child_nuclearity in enumerate([left_child_nuc, right_child_nuc]):
                child = dplp_tree[i]
                dplp_tree[i] = Tree(child_nuclearity, [transform(child)])
            return dplp_tree

        tree = transform(self.parsetree)
        return DGParentedTree.convert(tree)
1106329
def _parse_tree_dump(text_dump):
    # type: (str) -> Optional[Dict[str, Any]]
    
    result = None
    stack = []  # type: List[Dict]
    for line in text_dump.split('\n'):
        if line:
            depth, node = _parse_dump_line(line)
            if depth == 0:
                assert not stack
                result = node
                stack.append(node)
            elif depth > len(stack):
                raise ValueError('Unexpected dump structure')
            else:
                if depth < len(stack):
                    stack = stack[:depth]
                stack[-1].setdefault('children', []).append(node)
                stack.append(node)
    return result
1138886
def etree(self, data, root=None):
        ''''''
        result = self.list() if root is None else root
        if isinstance(data, (self.dict, dict)):
            for key, value in data.items():
                if isinstance(value, (self.dict, dict)):
                    elem = self.element(key)
                    if elem is None:
                        continue
                    result.append(elem)

                    if 'attributes' in value:
                        for k, v in value['attributes'].items():
                            elem.set(k, self._tostring(v))
                    # else:
                    #     raise ValueError('Cobra requires "attributes" key for each element')

                    if 'children' in value:
                        for v in value['children']:
                            self.etree(v, root=elem)
                else:
                    elem = self.element(key)
                    if elem is None:
                        continue
                    elem.text = self._tostring(value)
                    result.append(elem)
        else:
            if root is not None:
                root.text = self._tostring(data)
            else:
                elem = self.element(self._tostring(data))
                if elem is not None:
                    result.append(elem)

        return result
543586
def parse_parameter(self, tup_tree):
        

        self.check_node(tup_tree, 'PARAMETER', ('NAME', 'TYPE'), (),
                        ('QUALIFIER',))

        attrl = attrs(tup_tree)

        qualifiers = self.list_of_matching(tup_tree, ('QUALIFIER',))

        return CIMParameter(attrl['NAME'],
                            type=attrl['TYPE'],
                            is_array=False,
                            qualifiers=qualifiers,
                            embedded_object=False)
669319
def convert_parens_in_rst_tree_str(rst_tree_str):
    '''
    
    '''
    def replace_brackets(matchobj):
        edu = matchobj.group(0)
        for (br, br_repl) in DIS_ESCAPES:
            edu = re.sub("\{}".format(br), br_repl, edu)
        return edu

    return re.sub('_!(.*?)_!', replace_brackets, rst_tree_str)