Generate exactly one reference to each of the parts in the package by
        performing a depth-first traversal of the rels graph.
492807
def iter_parts(self):
        
        def walk_parts(source, visited=list()):
            for rel in source.rels.values():
                if rel.is_external:
                    continue
                part = rel.target_part
                if part in visited:
                    continue
                visited.append(part)
                yield part
                new_source = part
                for part in walk_parts(new_source, visited):
                    yield part

        for part in walk_parts(self):
            yield part
1036156
def referenced_vertices(self):
        
        # no entities no reference
        if len(self.entities) == 0:
            return np.array([], dtype=np.int64)
        referenced = np.concatenate([e.points for e in self.entities])
        referenced = np.unique(referenced.astype(np.int64))

        return referenced
450759
def generate_gml(username, nodes, edges, cache=False):
    

    # file segment that represents all the nodes in graph
    node_content = ""
    for i in range(len(nodes)):
        node_id = "\t\tid %d\n" % (i + 1)
        node_label = "\t\tlabel \"%s\"\n" % (nodes[i])

        node_content += format_node(node_id, node_label)

    # file segment that represents all the edges in graph
    edge_content = ""
    for i in range(len(edges)):
        edge = edges[i]

        edge_source = "\t\tsource %d\n" % (nodes.index(edge[0]) + 1)
        edge_target = "\t\ttarget %d\n" % (nodes.index(edge[1]) + 1)

        edge_content += format_edge(edge_source, edge_target)

    # formatted file content
    content = format_content(node_content, edge_content)

    with open(username_to_file(username), 'w') as f:
        f.write(content)

    # save the file for further use
    if cache:
    	cache_file(username_to_file(username))
866317
def relate_to(self, part, reltype):
        
        rel = self.rels.get_or_add(reltype, part)
        return rel.rId
1334531
def dereference(self):
        
        all = []
        indexes = {}
        for child in self.children:
            child.content(all)
        deplist = DepList()
        for x in all:
            x.qualify()
            midx, deps = x.dependencies()
            item = (x, tuple(deps))
            deplist.add(item)
            indexes[x] = midx
        for x, deps in deplist.sort():
            midx = indexes.get(x)
            if midx is None:
                continue
            d = deps[midx]
            log.debug('(%s) merging %s <== %s', self.tns[1], Repr(x), Repr(d))
            x.merge(d)
1018727
def getStartNodes(fdefs,calls):
    ''''''
    s=[]
    for source in fdefs:
        for fn in fdefs[source]:
            inboundEdges=False
            for call in calls:
                if call.target==fn:
                    inboundEdges=True
            if not inboundEdges:
                s.append(fn)
    return s
831756
def _build_catalog(self, url, xml_content):
        '''
        
        '''
        try:
            tree = etree.XML(xml_content)
        except BaseException:
            return

        # Get a list of URLs
        references = self._compile_references(url, tree)
        # Using multiple processes, make HTTP requests for each child catalog
        jobs = [self.pool.apply_async(request_xml, args=(ref,)) for ref in references]
        responses = [j.get() for j in jobs]

        # This is essentially the graph traversal step
        for i, response in enumerate(responses):
            for ds in self._build_catalog(references[i], response):
                yield ds

        # Yield the leaves
        for ds in self._yield_leaves(url, tree):
            yield ds
835190
function recursivePartitioner(graph, node, call_stack){
	
	var curr_level = call_stack.length -1;
	var next_level = curr_level +1;

	ll("recur on " + node.id() + " at level " + curr_level);

	// Get children and see where there are.
	//var child_nodes = graph.get_child_nodes(node.id(), relation);
	var child_nodes = graph.get_child_nodes(node.id());
	ll(node.id() + " has " + (child_nodes.length || 'no' ) + ' child(ren)');
	for( var i = 0; i < child_nodes.length; i++ ){
	    var cnode = child_nodes[i];

	    ll("looking at " + cnode.id());

	    if( _cycle_p(cnode, call_stack) ){
		ll('no update to ' + cnode.id() + ': cycle');
	    }else{

		// Add edges--safe since they're definition-based and will
		// clobber if they're already in.
		var new_edge =
		    new bbop.layout.sugiyama.simple_edge(cnode.id(), node.id());
		edge_set[ new_edge.id() ] = new_edge;

		// Nodes we have to be a little more careful with since
		// they're what we're using for traversal.
		if( ! vertex_set[ cnode.id() ] ){
		
		    // Create new vertex and add to set.
		    _new_node_at(cnode, next_level);
		    
		    // Since it is a new node, we traverse it.
		    ll('cs (a): ' + call_stack);
		    var new_cs = bbop.core.clone(call_stack);
		    ll('cs (b): ' + new_cs);
		    new_cs.push(cnode.id());
		    ll('cs (c): ' + new_cs);
		    recursivePartitioner(graph, cnode, new_cs);
		    
		}else{
		    
		    ll('to update ' + cnode.id() + ' level to ' + next_level +
		       '; fsr: '+ first_seen_reference[ cnode.id() ] +
		       '; lsr: '+ last_seen_reference[ cnode.id() ]);
		    
		    // Otherwise, just update the levels that we've seen
		    // the child at--do not descend.
		    if( first_seen_reference[ cnode.id() ] > next_level ){
			first_seen_reference[ cnode.id() ] = next_level;
		    }
		    if( last_seen_reference[ cnode.id() ] < next_level ){
			last_seen_reference[ cnode.id() ] = next_level;
			// LSR is also the level that things will
			// appear at, so update.
			// I believe node and simple node IDs are the same?
			vertex_set[ cnode.id() ].level = next_level;

			// Recur if the LSR has change--we need to
			// update all of the nodes below.
			ll('cs (a): ' + call_stack);
			var new_cs = bbop.core.clone(call_stack);
			ll('cs (b): ' + new_cs);
			new_cs.push(cnode.id());
			ll('cs (c): ' + new_cs);
			recursivePartitioner(graph, cnode, new_cs);
		    }

		    // ll('updated ' + cnode.id() + ' level to ' + next_level +
		    //    '; fsr: '+ first_seen_reference[ cnode.id() ] +
		    //    '; lsr: '+ last_seen_reference[ cnode.id() ]);
		}
	    }
	}
    }
822396
def generate_code_cover(self):
        

        lst = []
        for cfg_node in self.graph.nodes():
            size = cfg_node.size
            lst.append((cfg_node.addr, size))

        lst = sorted(lst, key=lambda x: x[0])
        return lst
1270507
def depth_first_recurse(node = nil, depth = 0, &block)
      node = self if node == nil
      yield node, depth
      node.children.each do |child|
        depth_first_recurse(child, depth+1, &block)
      end
    end
630473
def nx_all_nodes_between(graph, source, target, data=False):
    
    import utool as ut
    if source is None:
        # assume there is a single source
        sources = list(ut.nx_source_nodes(graph))
        assert len(sources) == 1, (
            'specify source if there is not only one')
        source = sources[0]
    if target is None:
        # assume there is a single source
        sinks = list(ut.nx_sink_nodes(graph))
        assert len(sinks) == 1, (
            'specify sink if there is not only one')
        target = sinks[0]
    all_simple_paths = list(nx.all_simple_paths(graph, source, target))
    nodes = sorted(set.union(*map(set, all_simple_paths)))
    return nodes
1233903
def _single_tree_paths(self, tree):
    """"""
    skel = tree.consolidate()

    tree = defaultdict(list)

    for edge in skel.edges:
      svert = edge[0]
      evert = edge[1]
      tree[svert].append(evert)
      tree[evert].append(svert)

    def dfs(path, visited):
      paths = []
      stack = [ (path, visited) ]
      
      while stack:
        path, visited = stack.pop(0)

        vertex = path[-1]
        children = tree[vertex]
        
        visited[vertex] = True

        children = [ child for child in children if not visited[child] ]

        if len(children) == 0:
          paths.append(path)

        for child in children:
          stack.append( 
            (path + [child], copy.deepcopy(visited))
          )

      return paths
      
    root = skel.edges[0,0]
    paths = dfs([root], defaultdict(bool))

    root = np.argmax([ len(_) for _ in paths ])
    root = paths[root][-1]
  
    paths = dfs([ root ], defaultdict(bool))
    
    return [ np.flip(skel.vertices[path], axis=0) for path in paths ]
578737
function extractRefs(node, refs) {
  	var i, list;

  	if (node.t === REFERENCE) {
  		if (refs.indexOf(node.n) === -1) {
  			refs.unshift(node.n);
  		}
  	}

  	list = node.o || node.m;
  	if (list) {
  		if (isObject(list)) {
  			extractRefs(list, refs);
  		} else {
  			i = list.length;
  			while (i--) {
  				extractRefs(list[i], refs);
  			}
  		}
  	}

  	if (node.x) {
  		extractRefs(node.x, refs);
  	}

  	if (node.r) {
  		extractRefs(node.r, refs);
  	}

  	if (node.v) {
  		extractRefs(node.v, refs);
  	}
  }
674623
def to_gremlin(self):
        """"""
        self.validate()
        template = 'copySplit({recurse}).exhaustMerge'
        recurse_base = '_()'
        recurse_traversal = '.{direction}(\'{edge_name}\')'.format(
            direction=self.direction, edge_name=self.edge_name)

        recurse_steps = [
            recurse_base + (recurse_traversal * i)
            for i in six.moves.xrange(self.depth + 1)
        ]
        recursion_string = template.format(recurse=','.join(recurse_steps))
        if self.within_optional_scope:
            # During a traversal, the pipeline element may be null.
            # The following code returns null when the current pipeline entity is null
            # (an optional edge did not exist at some earlier traverse).
            # Otherwise it performs a normal recursion (previous optional edge did exist).
            recurse_template = u'ifThenElse{{it == null}}{{null}}{{it.{recursion_string}}}'
            return recurse_template.format(recursion_string=recursion_string)
        else:
            return recursion_string
899502
def ancestors(self, start, generations=None):
        
        visited = self.vertex_set()
        visited.add(start)
        to_visit = deque([(start, 0)])
        while to_visit:
            vertex, depth = to_visit.popleft()
            if depth == generations:
                continue
            for parent in self.parents(vertex):
                if parent not in visited:
                    visited.add(parent)
                    to_visit.append((parent, depth+1))
        return self.full_subgraph(visited)
449284
def dbg_repr(self):
        

        output = [ ]

        for obj in self.project.loader.all_objects:
            for section in obj.sections:
                if section.memsize == 0:
                    continue
                min_addr, max_addr = section.min_addr, section.max_addr
                output.append("### Object %s" % repr(section))
                output.append("### Range %#x-%#x" % (min_addr, max_addr))

                pos = min_addr
                while pos < max_addr:
                    try:
                        addr, thing = self.floor_item(pos)
                        output.append("%#x: %s" % (addr, repr(thing)))

                        if thing.size == 0: pos += 1
                        else: pos += thing.size
                    except KeyError:
                        pos += 1

                output.append("")

        return "\n".join(output)
755027
def computeNodeLinks(cls, element, graph):
        
        index = element.nodes.kdims[-1]
        node_map = {}
        if element.nodes.vdims:
            values = zip(*(element.nodes.dimension_values(d)
                           for d in element.nodes.vdims))
        else:
            values = cycle([tuple()])
        for index, vals in zip(element.nodes.dimension_values(index), values):
            node = {'index': index, 'sourceLinks': [], 'targetLinks': [], 'values': vals}
            graph['nodes'].append(node)
            node_map[index] = node

        links = [element.dimension_values(d) for d in element.dimensions()[:3]]
        for i, (src, tgt, value) in enumerate(zip(*links)):
            source, target = node_map[src], node_map[tgt]
            link = dict(index=i, source=source, target=target, value=value)
            graph['links'].append(link)
            source['sourceLinks'].append(link)
            target['targetLinks'].append(link)