Parse territory containment tree.
178824
private void parseTerritoryContainment(JsonObject root) {
    JsonObject node = resolve(root, "supplemental", "territoryContainment");
    for (Map.Entry<String, JsonElement> entry : node.entrySet()) {
      String parentCode = entry.getKey();
      if (parentCode.contains("-")) {
        if (!parentCode.endsWith("-status-grouping")) {
          continue;
        }
        parentCode = parentCode.split("-")[0];
      }
      
      JsonObject value = entry.getValue().getAsJsonObject();
      JsonArray elements = (JsonArray) value.get("_contains");
      if (elements == null) {
        throw new RuntimeException("Unexpected object structure: " + value);
      }

      List<String> children = new ArrayList<>();
      for (JsonElement element : elements) {
        String code = element.getAsString();
        children.add(code);
      }
      
      Set<String> regions = territoryContainment.get(parentCode);
      if (regions == null) {
        regions = new TreeSet<>();
        territoryContainment.put(parentCode, regions);
      }
      regions.addAll(children);
    }
  }
462267
protected void parse(Node node) {
		parsed = true;
		NodeList childNodes = node.getChildNodes();
		for (int i = 0; i < childNodes.getLength(); i++) {
			Node child = childNodes.item(i);
			String nodeName = child.getNodeName();
			if ("Name".equalsIgnoreCase(nodeName)) {
				name = getValueRecursive(child);
			} else if ("Title".equalsIgnoreCase(nodeName)) {
				title = getValueRecursive(child);
			} else if ("Abstract".equalsIgnoreCase(nodeName)) {
				abstractt = getValueRecursive(child);
			} else if ("Keywords".equalsIgnoreCase(nodeName)) {
				addKeyWords(child);
			} else if ("SRS".equalsIgnoreCase(nodeName)) {
				defaultCrs = getValueRecursive(child);
			} else if ("LatLongBoundingBox".equalsIgnoreCase(nodeName)) {
				addLatLonBoundingBox(child);
			}
		}
	}
1140344
private static Span[] getConstituencySpans(final Parse parse) {

    final Stack<Parse> stack = new Stack<Parse>();

    if (parse.getChildCount() > 0) {
      for (final Parse child : parse.getChildren()) {
        stack.push(child);
      }
    }
    final List<Span> consts = new ArrayList<Span>();

    while (!stack.isEmpty()) {

      final Parse constSpan = stack.pop();

      if (!constSpan.isPosTag()) {
        final Span span = constSpan.getSpan();
        consts
            .add(new Span(span.getStart(), span.getEnd(), constSpan.getType()));

        for (final Parse child : constSpan.getChildren()) {
          stack.push(child);
        }
      }
    }

    return consts.toArray(new Span[consts.size()]);
  }
631752
def _parse_node(graph, text, condition_node_params, leaf_node_params):
    """"""
    match = _NODEPAT.match(text)
    if match is not None:
        node = match.group(1)
        graph.node(node, label=match.group(2), **condition_node_params)
        return node
    match = _LEAFPAT.match(text)
    if match is not None:
        node = match.group(1)
        graph.node(node, label=match.group(2), **leaf_node_params)
        return node
    raise ValueError('Unable to parse node: {0}'.format(text))
905906
def _parse_tree(self, node):
        
        if 'type' in node.attrib:
            self.kind = node.attrib['type']
        for c3 in node:
            if c3.tag == 'caption':
                self.caption = _parse_desc(c3)
            elif c3.tag == 'image':
                im = Image()
                im._parse_tree(c3)
                self.add_image(im)
677443
def tree(s, token=[WORD, POS, CHUNK, PNP, REL, LEMMA]):
    
    return Text(s, token)
1193230
def parse_at_root(
            self,
            root,  # type: ET.Element
            state  # type: _ProcessorState
    ):
        # type: (...) -> Any
        """"""
        xml_value = self._processor.parse_at_root(root, state)
        return _hooks_apply_after_parse(self._hooks, state, xml_value)
117561
def extract_tree(self, labels, without, suppress_unifurcations=True):
        ''''''
        if not isinstance(suppress_unifurcations, bool):
            raise TypeError("suppress_unifurcations must be a bool")
        if labels is not None and not isinstance(labels, set):
            try:
                labels = set(labels)
            except:
                raise TypeError("labels must be iterable")
        label_to_leaf = dict(); keep = set()
        for node in self.traverse_leaves():
            label_to_leaf[str(node)] = node
            if labels is None or (without and str(node) not in labels) or (not without and str(node) in labels):
                keep.add(node)
        for node in list(keep):
            for a in node.traverse_ancestors(include_self=False):
                keep.add(a)
        out = Tree(); out.root.label = self.root.label; out.root.edge_length = self.root.edge_length
        q_old = deque(); q_old.append(self.root)
        q_new = deque(); q_new.append(out.root)
        while len(q_old) != 0:
            n_old = q_old.popleft(); n_new = q_new.popleft()
            for c_old in n_old.children:
                if c_old in keep:
                    c_new = Node(label=str(c_old), edge_length=c_old.edge_length); n_new.add_child(c_new)
                    q_old.append(c_old); q_new.append(c_new)
        if suppress_unifurcations:
            out.suppress_unifurcations()
        return out
421097
def parse_xml(self, node):
        

        def read_points(text):
            """parse a text string of float tuples and return [(x,...),...]
            """
            return tuple(tuple(map(float, i.split(','))) for i in text.split())

        self._set_properties(node)

        # correctly handle "tile objects" (object with gid set)
        if self.gid:
            self.gid = self.parent.register_gid(self.gid)

        points = None
        polygon = node.find('polygon')
        if polygon is not None:
            points = read_points(polygon.get('points'))
            self.closed = True

        polyline = node.find('polyline')
        if polyline is not None:
            points = read_points(polyline.get('points'))
            self.closed = False

        if points:
            x1 = x2 = y1 = y2 = 0
            for x, y in points:
                if x < x1: x1 = x
                if x > x2: x2 = x
                if y < y1: y1 = y
                if y > y2: y2 = y
            self.width = abs(x1) + abs(x2)
            self.height = abs(y1) + abs(y2)
            self.points = tuple(
                [(i[0] + self.x, i[1] + self.y) for i in points])

        return self
568324
def parse_ontology(self):
        """"""
        start = time.clock()
        log.info("Parsing ontology file for %s" % self.__class__.__name__)
        for subj, pred, obj in self._schema_nodes():
            if subj not in self.attributes_by_class:
                if obj == rt.URIRef(self.lexicon['class']) and \
                        pred == rt.URIRef(self.lexicon['type']):
                    self.attributes_by_class[subj] = []

            leaves = [(subj, pred, obj)]
            if type(obj) == rt.BNode:
                leaves = deepest_node((subj, pred, obj), self.graph)

            for s, p, o in leaves:
                if o not in self.attributes_by_class:
                    self.attributes_by_class[o] = []
                if pred == rt.URIRef(self.lexicon['domain']):
                    self.attributes_by_class[o].append(subj)
        if not self.attributes_by_class:
            log.info("No nodes found in ontology")
        log.info("Ontology parsing complete in {}".format(
            (time.clock() - start) * 1000))
261964
def parse_regime(self, node):
        

        if 'name' in node.lattrib:
            name = node.lattrib['name']
        else:
            name = ''

        if 'initial' in node.lattrib:
            initial = (node.lattrib['initial'].strip().lower() == 'true')
        else:
            initial = False

        regime = Regime(name, self.current_dynamics, initial)
        old_regime = self.current_regime
        self.current_dynamics.add_regime(regime)
        self.current_regime = regime

        self.process_nested_tags(node)

        self.current_regime = old_regime
853069
def parse(self, parser):
        """"""
        lineno = next(parser.stream).lineno

        if parser.stream.skip_if('name:short'):
            parser.stream.skip(1)
            short = parser.parse_expression()
        else:
            short = nodes.Const(False)

        result = self.call_method('_commit_hash', [short], [], lineno=lineno)
        return nodes.Output([result], lineno=lineno)
372043
def _parse_organism_tag(self):
        ''''''
        organism_name_types = UniProtACEntry.organism_name_types
        self.organisms = []
        organism_tags = [child for child in self.entry_tag.childNodes if child.nodeType == child.ELEMENT_NODE and child.tagName == 'organism']
        assert(len(organism_tags) == 1)
        for organism_tag in organism_tags:
            names = dict.fromkeys(organism_name_types, None)
            for name_tag in [child for child in organism_tag.childNodes if child.nodeType == child.ELEMENT_NODE and child.tagName == 'name']:
                name_type = name_tag.getAttribute("type")
                assert(name_type in organism_name_types)
                names[name_type] = name_tag.firstChild.nodeValue.strip()
            assert(names.get('scientific'))
            self.organisms.append(names)
859684
def parse(self, root):
        """"""
        #Use the first element in the versions list since there should only be one.
        v = _get_xml_version(root)[0]
        result = {}

        for child in root:         
            if child.tag in self.versions[v].entries:
                entry = self.versions[v].entries[child.tag]
                #Entry can be either a line or a group. Both objects have a parse
                #method that returns a list of values. In the line's case, the
                #list is the values from that line. For the group, it is a list
                #of dictionaries, a dictionary for each tag name.
                result[child.tag] = entry.parse(child)

        return result
137734
def _parse_description(self, node):
        # type: (ElementTree.Element) -> EndpointDescription
        
        endpoint = {}
        for prop_node in node.findall(TAG_PROPERTY):
            name, value = self._parse_property(prop_node)
            endpoint[name] = value

        return EndpointDescription(None, endpoint)
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)
489338
def _parse_block(self, block, node):
        '''
        
        '''
        assert block[self.get_key()] == 'Block'

        if self.is_compact_ast:
            statements = block['statements']
        else:
            statements = block[self.get_children('children')]

        for statement in statements:
            node = self._parse_statement(statement, node)
        return node