A more specific version of the subdict utility aimed at handling
    node and edge attribute dictionaries for NetworkX file formats such as
    gexf (which does not allow attributes to have a list type) by making
    them writable in those formats
189401
def attribs_to_string(attrib_dict, keys):
    
    for key, value in attrib_dict.iteritems():
        if (isinstance(value, list) or isinstance(value, dict) or
            isinstance(value, tuple)):
            attrib_dict[key] = value

    return attrib_dict
1356096
def _to_dict(self, node):
        
        if node == BLANK_NODE:
            return {}

        node_type = self._get_node_type(node)

        if is_key_value_type(node_type):
            nibbles = without_terminator(unpack_to_nibbles(node[0]))
            key = b'+'.join([to_string(x) for x in nibbles])
            if node_type == NODE_TYPE_EXTENSION:
                sub_dict = self._to_dict(self._decode_to_node(node[1]))
            else:
                sub_dict = {to_string(NIBBLE_TERMINATOR): node[1]}

            # prepend key of this node to the keys of children
            res = {}
            for sub_key, sub_value in sub_dict.items():
                full_key = (key + b'+' + sub_key).strip(b'+')
                res[full_key] = sub_value
            return res

        elif node_type == NODE_TYPE_BRANCH:
            res = {}
            for i in range(16):
                sub_dict = self._to_dict(self._decode_to_node(node[i]))

                for sub_key, sub_value in sub_dict.items():
                    full_key = (
                        str_to_bytes(
                            str(i)) +
                        b'+' +
                        sub_key).strip(b'+')
                    res[full_key] = sub_value

            if node[16]:
                res[to_string(NIBBLE_TERMINATOR)] = node[-1]
            return res
775730
def get_subgraphs_by_citation(graph):
    
    rv = defaultdict(graph.fresh_copy)

    for u, v, key, data in graph.edges(keys=True, data=True):
        if CITATION not in data:
            continue
        dk = data[CITATION][CITATION_TYPE], data[CITATION][CITATION_REFERENCE]

        rv[dk].add_edge(u, v, key=key, **data)

    cleanup(graph, rv)

    return dict(rv)
1266354
def convert_to_networkx_graph(data, create_using=None, multigraph_input=False):
    """"""
    if isinstance(data, AllegedGraph):
        result = networkx.convert.from_dict_of_dicts(
            data.adj,
            create_using=create_using,
            multigraph_input=data.is_multigraph()
        )
        result.graph = dict(data.graph)
        result.node = {k: dict(v) for k, v in data.node.items()}
        return result
    return networkx.convert.to_networkx_graph(
        data, create_using, multigraph_input
    )
1152888
def merge_nested_environment_dicts(env_dicts, env_name=None, env_root=None):
    """"""
    # If the provided dictionary is just a single "level" (no nested
    # environments), it applies to all environments
    if all(isinstance(val, (six.string_types, list))
           for (_key, val) in env_dicts.items()):
        return flatten_path_lists(env_dicts, env_root)

    if env_name is None:
        if env_dicts.get('*'):
            return flatten_path_lists(env_dicts.get('*'), env_root)
        raise AttributeError("Provided config key:val pairs %s aren't usable with no environment provided" % env_dicts)  # noqa pylint: disable=line-too-long

    if not env_dicts.get('*') and not env_dicts.get(env_name):
        raise AttributeError("Provided config key:val pairs %s aren't usable with environment %s" % (env_dicts, env_name))  # noqa pylint: disable=line-too-long

    combined_dicts = merge_dicts(env_dicts.get('*', {}),
                                 env_dicts.get(env_name, {}))
    return flatten_path_lists(combined_dicts, env_root)
1125776
def gdfs_to_graph(gdf_nodes, gdf_edges):
    

    G = nx.MultiDiGraph()
    G.graph['crs'] = gdf_nodes.crs
    G.graph['name'] = gdf_nodes.gdf_name.rstrip('_nodes')

    # add the nodes and their attributes to the graph
    G.add_nodes_from(gdf_nodes.index)
    attributes = gdf_nodes.to_dict()
    for attribute_name in gdf_nodes.columns:
        # only add this attribute to nodes which have a non-null value for it
        attribute_values = {k:v for k, v in attributes[attribute_name].items() if pd.notnull(v)}
        nx.set_node_attributes(G, name=attribute_name, values=attribute_values)

    # add the edges and attributes that are not u, v, key (as they're added
    # separately) or null
    for _, row in gdf_edges.iterrows():
        attrs = {}
        for label, value in row.iteritems():
            if (label not in ['u', 'v', 'key']) and (isinstance(value, list) or pd.notnull(value)):
                attrs[label] = value
        G.add_edge(row['u'], row['v'], key=row['key'], **attrs)

    return G
682068
def get_subs_dict(self, qnodes=None):
        
        #d = self.qparams.copy()
        d = self.qparams
        d.update(self.optimize_params(qnodes=qnodes))
        # clean null values
        subs_dict = {k: v for k, v in d.items() if v is not None}
        #print("subs_dict:", subs_dict)
        return subs_dict
424401
def write_compacted(g):
    
    d_nodes = {}
    d_edges = {}

    def conv(value):
        if isinstance(value, basestring):
            return value.strip('"')
        else:
            return value

    for node in g.nodes():
        label = None
        attrs = []

        for k, v in sorted(g.node_attributes(node)):
            v_ = conv(v)
            if k == "label":
                label = v_
            else:
                attrs.append((k, v_))

        value = (node, label) if label else node
        d_nodes.setdefault(tuple(attrs), []).append(value)

    for edge in g.edges():
        attrs = [(k, conv(v)) for k, v in sorted(g.edge_attributes(edge))]
        label = str(g.edge_label(edge))
        value = tuple(list(edge) + [label]) if label else edge
        d_edges.setdefault(tuple(attrs), []).append(tuple(value))

    doc = dict(nodes=d_nodes.items(), edges=d_edges.items())
    contents = str(doc)
    return contents
307721
def to_networkx(self, labels=None, edge_labels=False):
        
        import networkx as nx
        graph = nx.DiGraph()
        for node in self._traverse_nodes():
            u = node.key
            graph.add_node(u)  # Minor redundancy
            # Set node properties
            graph.nodes[u]['value'] = node.value
            if labels is not None:
                label = ','.join([str(getattr(node, k)) for k in labels])
                graph.nodes[u]['label'] = label
            if node.left is not None:
                v = node.left.key
                graph.add_node(v)
                graph.add_edge(u, v)
                if edge_labels:
                    graph.edge[u][v]['label'] = 'L'
            if node.right is not None:
                v = node.right.key
                graph.add_node(v)
                graph.add_edge(u, v)
                if edge_labels:
                    graph.edge[u][v]['label'] = 'R'
        return graph
522347
def buildIndex(ipFile, ndxFile, append='Y', silent='N', useShortFileName='Y'):
    
    if silent == 'N':
        pass
    if append == 'N':
        try:
            os.remove(ndxFile)
        except Exception as ex:
            print('file already deleted - ignore' + str(ex))
            
    delims = [',', chr(31), '', '$', '&', '"', '%', '/', '\\', '.', ';', ':', '!', '?', '-', '_', ' ', '\n', '*', '\'', '(', ')', '[', ']', '{', '}']
    # 1st pass - index the ontologies, including 2 depths up (later - TODO)
    #buildIndex(ipFile, ndxFile, ' ', 1, 'Y')

    # 2nd pass - use ALL delims to catch each word as part of hyphenated - eg AI Build py
    totWords, totLines, uniqueWords = getWordList(ipFile, delims)
    
    AppendIndexDictionaryToFile(uniqueWords, ndxFile, ipFile, useShortFileName)
    if silent == 'N':
        print(format_op_row(ipFile, totLines, totWords, uniqueWords))
   
        show('uniqueWords', uniqueWords, 5)
    DisplayIndexAsDictionary(uniqueWords)
181391
def _pylxd_model_to_dict(obj):
    ''''''
    marshalled = {}
    for key in obj.__attributes__.keys():
        if hasattr(obj, key):
            marshalled[key] = getattr(obj, key)
    return marshalled
485776
def _link_vertex_and_edge_types(self):
        """"""
        for edge_class_name in self._edge_class_names:
            edge_element = self._elements[edge_class_name]

            if (EDGE_SOURCE_PROPERTY_NAME not in edge_element.properties or
                    EDGE_DESTINATION_PROPERTY_NAME not in edge_element.properties):
                if edge_element.abstract:
                    continue
                else:
                    raise AssertionError(u'Found a non-abstract edge class with undefined '
                                         u'endpoint types: {}'.format(edge_element))

            from_class_name = edge_element.properties[EDGE_SOURCE_PROPERTY_NAME].qualifier
            to_class_name = edge_element.properties[EDGE_DESTINATION_PROPERTY_NAME].qualifier

            edge_schema_element = self._elements[edge_class_name]

            # Link from_class_name with edge_class_name
            for from_class in self._subclass_sets[from_class_name]:
                from_schema_element = self._elements[from_class]
                from_schema_element.out_connections.add(edge_class_name)
                edge_schema_element.in_connections.add(from_class)

            # Link edge_class_name with to_class_name
            for to_class in self._subclass_sets[to_class_name]:
                to_schema_element = self._elements[to_class]
                edge_schema_element.out_connections.add(to_class)
                to_schema_element.in_connections.add(edge_class_name)
369159
protected void addAttributes(SXTag dataNode, String keyPrefix,
			Collection<XAttribute> attributes) throws IOException {
		for (XAttribute attribute : attributes) {
			// skip attributes defined by standard extensions
			// to ensure parity with MXML input files.
			if (// BVD: KEEP ALL Attributes
				// attribute.getKey().equals(XConceptExtension.KEY_NAME)
				// || attribute.getKey()
				// .equals(XConceptExtension.KEY_INSTANCE)
				// || attribute.getKey().equals(XLifecycleExtension.KEY_MODEL)
				// || attribute.getKey().equals(
				// XLifecycleExtension.KEY_TRANSITION)
				// || attribute.getKey().equals(
				// XOrganizationalExtension.KEY_GROUP)
				// || attribute.getKey().equals(
				// XOrganizationalExtension.KEY_RESOURCE)
				// || attribute.getKey().equals(
				// XOrganizationalExtension.KEY_ROLE)||
			attribute.getKey().equals(XSemanticExtension.KEY_MODELREFERENCE)
			// || attribute.getKey().equals(XTimeExtension.KEY_TIMESTAMP)
			) {
				continue;
			}
			SXTag attributeTag = dataNode.addChildNode("attribute");
			attributeTag.addAttribute("name", keyPrefix + attribute.getKey());
			addModelReference(attribute, attributeTag);
			attributeTag.addTextNode(attribute.toString());
			Collection<XAttribute> subAttributes = attribute.getAttributes()
					.values();
			if (subAttributes.size() > 0) {
				String subKeyPrefix = attribute.getKey();
				if (keyPrefix.length() > 0) {
					subKeyPrefix = keyPrefix + ":" + subKeyPrefix;
				}
				addAttributes(dataNode, subKeyPrefix, subAttributes);
			}
		}
	}
100079
def make_node_dict(outer_list, sort="zone"):
    """"""
    raw_dict = {}
    x = 1
    for inner_list in outer_list:
        for node in inner_list:
            raw_dict[x] = node
            x += 1
    if sort == "name":  # sort by provider - name
        srt_dict = OrderedDict(sorted(raw_dict.items(), key=lambda k:
                               (k[1].cloud, k[1].name.lower())))
    else:  # sort by provider - zone - name
        srt_dict = OrderedDict(sorted(raw_dict.items(), key=lambda k:
                               (k[1].cloud, k[1].zone, k[1].name.lower())))
    x = 1
    node_dict = {}
    for i, v in srt_dict.items():
        node_dict[x] = v
        x += 1
    return node_dict
16895
def export_dict(mesh, encoding=None):
    

    def encode(item, dtype=None):
        if encoding is None:
            return item.tolist()
        else:
            if dtype is None:
                dtype = item.dtype
            return util.array_to_encoded(item, dtype=dtype, encoding=encoding)

    # metadata keys we explicitly want to preserve
    # sometimes there are giant datastructures we don't
    # care about in metadata which causes exports to be
    # extremely slow, so skip all but known good keys
    meta_keys = ['units', 'file_name', 'file_path']
    metadata = {k: v for k, v in mesh.metadata.items() if k in meta_keys}

    export = {
        'metadata': metadata,
        'faces': encode(mesh.faces),
        'face_normals': encode(mesh.face_normals),
        'vertices': encode(mesh.vertices)
    }
    if mesh.visual.kind == 'face':
        export['face_colors'] = encode(mesh.visual.face_colors)
    elif mesh.visual.kind == 'vertex':
        export['vertex_colors'] = encode(mesh.visual.vertex_colors)

    return export
1340908
private <T,E extends TypedEdge<T>> void write(
                         Multigraph<T,E> g, File f, Map<T,Color> edgeColors, 
                         boolean useColors, Indexer<String> vertexLabels,
                         boolean useLabels) throws IOException {

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = null;
        try {
            docBuilder = dbfac.newDocumentBuilder();
        } catch (ParserConfigurationException pce) {
            throw new IOError(new IOException(pce));
        }
        Document doc = docBuilder.newDocument();

        Element root = doc.createElement("gexf");
        root.setAttribute("xmlns","http://www.gexf.net/1.2draft");
        root.setAttribute("xmlns:viz", "http://www.gexf.net/1.2draft/viz");
        root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        root.setAttribute("version","1.2");
        root.setAttribute("xsi:schemaLocation","http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd");
        doc.appendChild(root);

        Element graph = doc.createElement("graph");
        graph.setAttribute("defaultedgetype","undirected");
        root.appendChild(graph);

        Element nodes = doc.createElement("nodes");
        graph.appendChild(nodes);
        Element edges = doc.createElement("edges");
        graph.appendChild(edges);

        IntIterator vIter = g.vertices().iterator();
        while (vIter.hasNext()) {
            int vertex = vIter.next();
            Element node = doc.createElement("node");
            node.setAttribute("id", String.valueOf(vertex));
            if (useLabels) 
                node.setAttribute("label", vertexLabels.lookup(vertex));
            else
                node.setAttribute("label", String.valueOf(vertex));
            nodes.appendChild(node);
        }

        ColorGenerator cg = null;
        if (useColors)
            cg = new ColorGenerator();

        int edgeId = 0;
        for (E e : g.edges()) {
            Element edge = doc.createElement("edge");
            edges.appendChild(edge);
            edge.setAttribute("id", "" + (edgeId++));
            edge.setAttribute("source", String.valueOf(e.from()));
            edge.setAttribute("target", String.valueOf(e.to()));
            edge.setAttribute("label", String.valueOf(e.edgeType()));
            if (useColors) {
                Element cEdge = doc.createElement("viz:color");
                edge.appendChild(cEdge);
                Color c = edgeColors.get(e.edgeType());
                if (c == null) {
                    c = cg.next();
                    edgeColors.put(e.edgeType(), c);
                }
                cEdge.setAttribute("r", String.valueOf(c.getRed()));
                cEdge.setAttribute("g", String.valueOf(c.getGreen()));
                cEdge.setAttribute("b", String.valueOf(c.getBlue()));
            }
        }

        // Set up a transformer
        try {
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            trans.setOutputProperty(
                "{http://xml.apache.org/xslt}indent-amount", "2");
        
            // Create string from xml tree
            BufferedOutputStream bos = 
                new BufferedOutputStream(new FileOutputStream(f));
            StreamResult result = new StreamResult(bos);
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);
            bos.close();         
        } catch (TransformerException te) {
            throw new IOError(new IOException(te));
        }
    }
49347
def subgraph(graph, nodes: Iterable[BaseEntity]):
    
    sg = graph.subgraph(nodes)

    # see implementation for .copy()
    result = graph.fresh_copy()
    result.graph.update(sg.graph)

    for node, data in sg.nodes(data=True):
        result.add_node(node, **data)

    result.add_edges_from(
        (u, v, key, datadict.copy())
        for u, v, key, datadict in sg.edges(keys=True, data=True)
    )

    return result