Create or retrieve the parse tree for defining a sensor graph.
760533
def get_language():
    """"""

    global sensor_graph, statement

    if sensor_graph is not None:
        return sensor_graph

    _create_primitives()
    _create_simple_statements()
    _create_block_bnf()

    sensor_graph = ZeroOrMore(statement) + StringEnd()
    sensor_graph.ignore(comment)

    return sensor_graph
1322169
def build_graph(self):
        
        for child, parents in self.dependencies.items():
            if child not in self.nodes:
                raise NodeNotFoundError(
                    "App %s SQL item dependencies reference nonexistent child node %r" % (
                        child[0], child),
                    child
                )
            for parent in parents:
                if parent not in self.nodes:
                    raise NodeNotFoundError(
                        "App %s SQL item dependencies reference nonexistent parent node %r" % (
                            child[0], parent),
                        parent
                    )
                self.node_map[child].add_parent(self.node_map[parent])
                self.node_map[parent].add_child(self.node_map[child])

        for node in self.nodes:
            self.ensure_not_cyclic(node,
                                   lambda x: (parent.key for parent in self.node_map[x].parents))
1032150
def get_root_graph(self,root):
      """"""
      children = self.get_children(root)
      g = Graph()
      nodes = [root]+children
      for node in nodes: g.add_node(node)
      node_ids = [x.id for x in nodes]
      edges = [x for x in self._edges.values() if x.node1.id in node_ids and x.node2.id in node_ids]
      for e in edges: g.add_edge(e)
      return g
469884
def build_event_graph(graph, tree, node):
    """"""
    # If we have already added this node then let's return
    if node_key(node) in graph:
        return
    type = get_type(node)
    text = get_text(node)
    label = '%s (%s)' % (type, text)
    graph.add_node(node_key(node), type=type, label=label, text=text)
    args = get_args(node)
    for arg_role, (arg_id, arg_tag) in args.items():
        arg = get_node_by_id(tree, arg_id)
        if arg is None:
            arg = arg_tag
        build_event_graph(graph, tree, arg)
        graph.add_edge(node_key(node), node_key(arg), type=arg_role,
                       label=arg_role)
178250
def import_graph(self, t_input=None, scope='import', forget_xy_shape=True):
    """"""
    graph = tf.get_default_graph()
    assert graph.unique_name(scope, False) == scope, (
        'Scope "%s" already exists. Provide explicit scope names when '
        'importing multiple instances of the model.') % scope
    t_input, t_prep_input = self.create_input(t_input, forget_xy_shape)
    tf.import_graph_def(
        self.graph_def, {self.input_name: t_prep_input}, name=scope)
    self.post_import(scope)
250117
private ExtractingResult parse(Result terms, boolean useForest) {
		if(terms==null || terms.size()==0){
			return new ExtractingResult() ;
		}

		if (useForest) {
			Graph graph = new Graph(terms);
			new UserDefineRecognition(TermUtil.InsertTermType.REPLACE,ruleIndex.getForest()).recognition(graph);
			graph.rmLittlePath();
			List<Term> result = new ArrayList<Term>();
			int length = graph.terms.length - 1;
			for (int i = 0; i < length; i++) {
				if (graph.terms[i] != null) {
					result.add(graph.terms[i]);
				}
			}
			terms = new Result(result) ;
		}


		List<ExtractingTask> tasks = new ArrayList<>();

		ExtractingResult result = new ExtractingResult();

		for (int i = 0; i < terms.size(); i++) {
			Term term = terms.get(i);

			Set<Rule> sets = new HashSet<>();

			Set<Rule> rules = ruleIndex.getRules(term.getName());
			if (rules != null) {
				sets.addAll(rules);
			}

			rules = ruleIndex.getRules(":" + term.getNatureStr());
			if (rules != null) {
				sets.addAll(rules);
			}

			rules = ruleIndex.getRules(":*");
			if (rules != null) {
				sets.addAll(rules);
			}

			for (Rule rule : sets) {
				tasks.add(new ExtractingTask(result, rule, i, terms));
			}
		}

		for (ExtractingTask task : tasks) {
			task.run();
		}

		return result;
	}
467467
def parseNode(self):
		
		n = SGFParser.parseNode(self)			# process one Node as usual
		self.index = self.datalen				# set end of data
		return n
1355113
def to_indra_statements(graph):
    
    from indra.sources.bel import process_pybel_graph

    pbp = process_pybel_graph(graph)
    return pbp.statements
1098899
def make_graph(node, inputs):
        
        initializer = []
        tensor_input_info = []
        tensor_output_info = []

        # Adding input tensor info.
        for index in range(len(node.input)):
            tensor_input_info.append(
                helper.make_tensor_value_info(str(node.input[index]), TensorProto.FLOAT, [1]))

            # Creating an initializer for Weight params.
            # Assumes that weight params is named as 'W'.
            # TODO: Handle multiple weight params.
            # TODO: Add for "bias" if needed
            if node.input[index] == 'W':
                dim = inputs[index].shape
                param_tensor = helper.make_tensor(
                    name=node.input[index],
                    data_type=TensorProto.FLOAT,
                    dims=dim,
                    vals=inputs[index].flatten())

                initializer.append(param_tensor)

        # Adding output tensor info.
        for index in range(len(node.output)):
            tensor_output_info.append(
                helper.make_tensor_value_info(str(node.output[index]), TensorProto.FLOAT, [1]))

        # creating graph proto object.
        graph_proto = helper.make_graph(
            [node],
            "test",
            tensor_input_info,
            tensor_output_info,
            initializer=initializer)

        return graph_proto
956527
def graph(self, name, *args, **kwargs):
        
        return Graph(self, name, *args, **kwargs)
1313069
def _parse_tree(self, node):
        
        if 'filename' in node.attrib:
            self.filename = node.attrib['filename']
        if 'type' in node.attrib:
            self.kind = node.attrib['type']
        if 'target' in node.attrib:
            self.target = node.attrib['target']
        self.value = node.text
518760
def dict_to_object(self, obj):  # pylint: disable=no-self-use
        """"""
        if not isinstance(obj, dict):
            return obj
        if 'sensor_id' in obj:
            sensor = Sensor(obj['sensor_id'])
            for key, val in obj.items():
                setattr(sensor, key, val)
            return sensor
        if all(k in obj for k in ['id', 'type', 'values']):
            child = ChildSensor(
                obj['id'], obj['type'], obj.get('description', ''))
            child.values = obj['values']
            return child
        if all(k.isdigit() for k in obj.keys()):
            return {int(k): v for k, v in obj.items()}
        return obj
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)
616610
def sg_query_streamer(self, index):
        """"""

        resp = self.sensor_graph.query_streamer(index)
        if resp is None:
            return [struct.pack("<L", _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED))]

        return [struct.pack("<LLLLBBBx", *resp)]
384742
def treewalk(self, root, parsed, unparsed):
        
        suggestions = dict()
        if not unparsed:
            logger.debug("no tokens left unparsed. returning %s, %s", parsed, suggestions)
            return parsed, unparsed, suggestions

        token = unparsed.pop().strip()
        logger.debug("begin parsing at %s w/ tokens: %s", root.node, unparsed)
        if root.node == token:
            logger.debug("root node: %s matches next token:%s", root.node, token)
            parsed.append(token)
            if self.peekForOption(unparsed):  # check for localFlags and globalFlags
                logger.debug("option(s) upcoming %s", unparsed)
                parsed_opts, unparsed, suggestions = self.evalOptions(root, list(), unparsed[:])
                if parsed_opts:
                    logger.debug("parsed option(s): %s", parsed_opts)
                    parsed.extend(parsed_opts)
            if unparsed and not self.peekForOption(unparsed):  # unparsed bits without options
                logger.debug("begin subtree %s parsing", root.node)
                for child in root.children:
                    parsed_subtree, unparsed, suggestions = self.treewalk(child, list(), unparsed[:])
                    if parsed_subtree:  # subtree returned further parsed tokens
                        parsed.extend(parsed_subtree)
                        logger.debug("subtree at: %s has matches. %s, %s", child.node, parsed, unparsed)
                        break
                else:
                    # no matches found in command tree
                    # return children of root as suggestions
                    logger.debug("no matches in subtree: %s. returning children as suggestions", root.node)
                    for child in root.children:
                        suggestions[child.node] = child.help
        else:
            logger.debug("no token or option match")
            unparsed.append(token)
        return parsed, unparsed, suggestions
173490
def _parse(self, root, line, idx):
        
        # Base (or degenerate..) case.
        if len(line) == 0:
            return [], idx

        parse = []
        curr = 0
        node = root
        cidx = idx
        while curr < len(line):
            node = node.children.get(line[curr])
            curr += 1
            if not node:
                break
            if node.sentinel:
                subparse, cidx = self._parse(root, line[curr:], idx + curr)
                # Always keep the latest valid parse, which will be
                # the longest-matched (greedy match) graphemes.
                parse = [line[:curr]]
                parse.extend(subparse)
        if parse:
            idx = cidx
        return parse, idx
330206
def __extract_pattern_nodes(graph):
    
    tp_nodes = graph.subjects(RDF.type, AGORA.TriplePattern)
    for tpn in tp_nodes:
        subject = list(graph.objects(tpn, AGORA.subject)).pop()
        predicate = list(graph.objects(tpn, AGORA.predicate)).pop()
        obj = list(graph.objects(tpn, AGORA.object)).pop()
        subject_str = list(graph.objects(subject, RDFS.label)).pop().toPython()
        predicate_str = graph.qname(predicate)
        if (obj, RDF.type, AGORA.Variable) in graph:
            object_str = list(graph.objects(obj, RDFS.label)).pop().toPython()
        else:
            object_str = list(graph.objects(obj, AGORA.value)).pop().toPython()
        __plan_patterns[tpn] = '{} {} {}'.format(subject_str, predicate_str, object_str)