Add a node to the sensor_graph using a binary node descriptor.

        Args:
            binary_descriptor (bytes): An encoded binary node descriptor.

        Returns:
            int: A packed error code.
431057
def add_node(self, binary_descriptor):
        

        try:
            node_string = parse_binary_descriptor(binary_descriptor)
        except:
            self._logger.exception("Error parsing binary node descriptor: %s", binary_descriptor)
            return _pack_sgerror(SensorGraphError.INVALID_NODE_STREAM)  # FIXME: Actually provide the correct error codes here

        try:
            self.graph.add_node(node_string)
        except NodeConnectionError:
            return _pack_sgerror(SensorGraphError.STREAM_NOT_IN_USE)
        except ProcessingFunctionError:
            return _pack_sgerror(SensorGraphError.INVALID_PROCESSING_FUNCTION)
        except ResourceUsageError:
            return _pack_sgerror(SensorGraphError.NO_NODE_SPACE_AVAILABLE)

        return Error.NO_ERROR
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
952517
def _add(self, xer, primary, type):
        
        if xer not in primary:
            primary[xer] = TwistedSocketNotifier(None, self, xer, type)
1282723
def add_node(namespace_inc_global, body, opts = {})
      data, _status_code, _headers = add_node_with_http_info(namespace_inc_global, body, opts)
      return data
    end
562949
def _add_json_binary_field(b, serialized, field):
    '''' 
    '''
    try:
        val = b.decode('utf-8')
        serialized[field] = val
    except UnicodeDecodeError:
        val = base64.b64encode(b).decode('utf-8')
        serialized[field + '64'] = val
48411
def graph_add_node(self, node_object):
        
        if ((node_object not in self._graph.nodes()) and
            (isinstance(node_object, (StationDing0,
                                      CableDistributorDing0,
                                      LVLoadAreaCentreDing0,
                                      CircuitBreakerDing0,
                                      GeneratorDing0)))):
            self._graph.add_node(node_object)
1005170
def add_node(self, payload):
        
        self.nodes.append(Node(len(self.nodes), payload))
        return len(self.nodes) - 1
1374006
def binary(self):
        
        creation_size = len(self.creation)
        if creation_size == 1:
            return (
                b_chr(_TAG_PID_EXT) +
                self.node.binary() + self.id + self.serial + self.creation
            )
        elif creation_size == 4:
            return (
                b_chr(_TAG_NEW_PID_EXT) +
                self.node.binary() + self.id + self.serial + self.creation
            )
        else:
            raise OutputException('unknown pid type')
637070
def add_nodes(self, nodes, nesting=1):
        
        hopNodes = set()  # nodes in this hop
        hopEdges = []     # edges in this hop
        # get nodes and edges for this hop
        for i, n in zip(range(len(nodes)), nodes):
            r, g, b = rainbowcolour(i, len(nodes))
            colour = '#%02X%02X%02X' % (r, g, b)
            for p in n.calls:
                if p not in hopNodes:
                    hopNodes.add(p)
                hopEdges.append((n, p, 'solid', colour))
            for p in getattr(n, 'interfaces', []):
                if p not in hopNodes:
                    hopNodes.add(p)
                hopEdges.append((n, p, 'dashed', colour))
        # add nodes, edges and attributes to the graph if maximum number of
        # nodes is not exceeded
        if self.add_to_graph(hopNodes, hopEdges, nesting):
            self.dot.attr('graph', size='11.875,1000.0')
            self.dot.attr('graph', concentrate='false')
487246
def add_chain(self, *nodes, _input=BEGIN, _output=None, _name=None):
        
        if len(nodes):
            _input = self._resolve_index(_input)
            _output = self._resolve_index(_output)
            _first = None
            _last = None

            for i, node in enumerate(nodes):
                _last = self.add_node(node)
                if not i and _name:
                    if _name in self.named:
                        raise KeyError("Duplicate name {!r} in graph.".format(_name))
                    self.named[_name] = _last
                if _first is None:
                    _first = _last
                self.outputs_of(_input, create=True).add(_last)
                _input = _last

            if _output is not None:
                self.outputs_of(_input, create=True).add(_output)

            if hasattr(self, "_topologcally_sorted_indexes_cache"):
                del self._topologcally_sorted_indexes_cache

            return GraphRange(self, _first, _last)
        return GraphRange(self, None, None)
665912
def from_dict(self, graph_dict):
        

        self.reset_graph()
        for new_node in six.iterkeys(graph_dict):
            self.add_node(new_node)
        for ind_node, dep_nodes in six.iteritems(graph_dict):
            if not isinstance(dep_nodes, list):
                raise TypeError('dict values must be lists')
            for dep_node in dep_nodes:
                self.add_edge(ind_node, dep_node)
846678
def which_with_node_modules(self):
        

        if self.binary is None:
            return None

        # first, log down the pedantic things...
        if isdir(self.join_cwd(NODE_MODULES)):
            logger.debug(
                "'%s' instance will attempt to locate '%s' binary from "
                "%s%s%s%s%s, located through the working directory",
                self.__class__.__name__, self.binary,
                self.join_cwd(), sep, NODE_MODULES, sep, NODE_MODULES_BIN,
            )
        if self.node_path:
            logger.debug(
                "'%s' instance will attempt to locate '%s' binary from "
                "its %s of %s",
                self.__class__.__name__, self.binary,
                NODE_PATH, self.node_path,
            )

        paths = self.find_node_modules_basedir()
        whichpaths = pathsep.join(join(p, NODE_MODULES_BIN) for p in paths)

        if paths:
            logger.debug(
                "'%s' instance located %d possible paths to the '%s' binary, "
                "which are %s",
                self.__class__.__name__, len(paths), self.binary, whichpaths,
            )

        return which(self.binary, path=whichpaths)
875415
def add_obograph_digraph(self, og, node_type=None, predicates=None, xref_graph=None, logical_definitions=None,
                             property_chain_axioms=None,
                             parse_meta=True,
                             **args):
        
        digraph = self.digraph
        logging.info("NODES: {}".format(len(og['nodes'])))

        # if client passes an xref_graph we must parse metadata
        if xref_graph is not None:
            parse_meta = True

        for n in og['nodes']:
            is_obsolete =  'is_obsolete' in n and n['is_obsolete'] == 'true'
            if is_obsolete:
                continue
            if node_type is not None and ('type' not in n or n['type'] != node_type):
                continue
            id = self.contract_uri(n['id'])
            digraph.add_node(id, **n)
            if 'lbl' in n:
                digraph.node[id]['label'] = n['lbl']
            if parse_meta and 'meta' in n:
                if n['meta'] is None:
                    n['meta'] = {}
                meta = self.transform_meta(n['meta'])
                if xref_graph is not None and 'xrefs' in meta:
                    for x in meta['xrefs']:
                        xref_graph.add_edge(self.contract_uri(x['val']), id, source=id)
        logging.info("EDGES: {}".format(len(og['edges'])))
        for e in og['edges']:
            sub = self.contract_uri(e['sub'])
            obj = self.contract_uri(e['obj'])
            pred = self.contract_uri(e['pred'])
            pred = map_legacy_pred(pred)
            if pred == 'is_a':
                pred = 'subClassOf'
            if predicates is None or pred in predicates:
                digraph.add_edge(obj, sub, pred=pred)
        if 'equivalentNodesSets' in og:
            nslist = og['equivalentNodesSets']
            logging.info("CLIQUES: {}".format(len(nslist)))
            for ns in nslist:
                equivNodeIds = ns['nodeIds']
                for i in ns['nodeIds']:
                    ix = self.contract_uri(i)
                    for j in ns['nodeIds']:
                        if i != j:
                            jx = self.contract_uri(j)
                            digraph.add_edge(ix, jx, pred='equivalentTo')
        if logical_definitions is not None and 'logicalDefinitionAxioms' in og:
            for a in og['logicalDefinitionAxioms']:
                ld = LogicalDefinition(self.contract_uri(a['definedClassId']),
                                       [self.contract_uri(x) for x in a['genusIds']],
                                       [(self.contract_uri(x['propertyId']),
                                         self.contract_uri(x['fillerId'])) for x in a['restrictions'] if x is not None])
                logical_definitions.append(ld)
        if property_chain_axioms is not None and 'propertyChainAxioms' in og:
            for a in og['propertyChainAxioms']:
                pca = PropertyChainAxiom(predicate_id=self.contract_uri(a['predicateId']),
                                         chain_predicate_ids=[self.contract_uri(x) for x in a['chainPredicateIds']])
                property_chain_axioms.append(pca)
1122550
def update_binary_stats(self, label, pred):
        
        pred = pred.asnumpy()
        label = label.asnumpy().astype('int32')
        pred_label = numpy.argmax(pred, axis=1)

        check_label_shapes(label, pred)
        if len(numpy.unique(label)) > 2:
            raise ValueError("%s currently only supports binary classification."
                             % self.__class__.__name__)
        pred_true = (pred_label == 1)
        pred_false = 1 - pred_true
        label_true = (label == 1)
        label_false = 1 - label_true

        true_pos = (pred_true * label_true).sum()
        false_pos = (pred_true * label_false).sum()
        false_neg = (pred_false * label_true).sum()
        true_neg = (pred_false * label_false).sum()
        self.true_positives += true_pos
        self.global_true_positives += true_pos
        self.false_positives += false_pos
        self.global_false_positives += false_pos
        self.false_negatives += false_neg
        self.global_false_negatives += false_neg
        self.true_negatives += true_neg
        self.global_true_negatives += true_neg
112569
def get_node(self, name, memory=False, binary=False):
        
        return self._api_get(
            url='/api/nodes/{0}'.format(name),
            params=dict(
                binary=binary,
                memory=memory,
            ),
        )
336503
def __addNode(self, name, cls):
        '''
        
        '''
        if name in self.nodes:
            raise Exception("A node by the name {} already exists.  Can't add a duplicate.".format(name))
        self.__nxgraph.add_node(name)
        self.__nxgraph.node[name]['label'] = name
        self.__nxgraph.node[name]['nodeobj'] = cls()
        self.__nxgraph.node[name]['type'] = cls.__name__
1024477
def create_binary_descriptor(streamer):
    

    trigger = 0
    if streamer.automatic:
        trigger = 1
    elif streamer.with_other is not None:
        trigger = (1 << 7) | streamer.with_other

    return struct.pack("<8sHBBBx", streamer.dest.encode(), streamer.selector.encode(), trigger, streamer.KnownFormats[streamer.format], streamer.KnownTypes[streamer.report_type])