Yield strings, printable view of given graph
772945
def pretty_view(graph, oriented=False, construction=False,
                graphviz_prog=DEFAULT_GRAPHVIZ_PROG):
    """"""
    layout = create_layout(graph, graphviz_prog=graphviz_prog)
    matrix_view = defaultdict(lambda: ' ')

    # Add the edge to the view

    # print('GRAPH EDGES:', tuple(graph.edges()))
    # print('LAYOUT:', layout)

    edges = ((layout[source], layout[target])
             for source, target in graph.edges())
    # print('EDGES:', tuple(edges))

    for source, target in edges:
        previous_edge_char = None
        previous_position = source
        while source != target:
            for is_dir, transform, edge_char in DIRECTIONS:
                first_loop = previous_edge_char is None
                if is_dir(source, target):
                    previous_source = source
                    source = transform(source)
                    if not first_loop:  # first loop: no previous char
                        char = CHARACTER[previous_edge_char, edge_char]
                        if not isinstance(char, str):
                            char = char.value
                        matrix_view[previous_source] = char
                        if construction:
                            old = defaultdict(lambda: ' ', matrix_view)
                            yield view.build(matrix_view)
                        assert isinstance(matrix_view[previous_source], str)
                    if source != target:
                        previous_edge_char = edge_char
                    previous_position = previous_source
                    break  # for loop ; don't test the remain directions

        if oriented:
            matrix_view[previous_position] = ORIENTATION[previous_edge_char, edge_char]
        if construction:
            yield view.build(matrix_view)

    # mark the place where nodes labels will be added
    # for node, coords in layout.items():
        # matrix_view[coords] = node[0]
    # Add the node labels to the view
    # matrix_view = view.clean(matrix_view)
    for node, (x, y) in layout.items():
        if len(node) == 1:
            matrix_view[x, y] = node
            continue
        row_min, row_max = (view.previous_unwrittable_on_row(matrix_view, (x, y)),
                            view.next_unwrittable_on_row(matrix_view, (x, y)))
        col_min, col_max = (view.previous_unwrittable_on_col(matrix_view, (x, y)),
                              view.next_unwrittable_on_col(matrix_view, (x, y)))
        # print('NODE ' + node + ':',
              # '→row: [{};{}]'.format(row_min, row_max).ljust(20),
              # '↓col: [{};{}]'.format(col_min, col_max))
        print_coords = [itertools.count(x), itertools.cycle((y,))]
        if row_min is None:  # write left to right, end at (x, y)
            if row_max is None or row_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords[0] = tuple(
                x - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            )
            # print('DEBUG 1:', y, len(node), print_coords[0])
        elif row_max is None:  # write left to right, beginning at (x, y)
            if row_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords[0] = tuple(
                x + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            )
            # print('DEBUG 2:', print_coords[0])
        elif (row_max - row_min) > len(node) + 1:  # write left to right, if enough place
            print_coords[0] = tuple(
                x + offset
                for offset in range(len(node))
            )
            # print('DEBUG 3:', print_coords[0])

        elif col_min is None:  # write up to down, end at (x, y)
            if col_max is None or col_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords = (itertools.cycle((x,)), tuple(
                y - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            ))
            # print('DEBUG 4:', y, len(node), print_coords[1])
        elif col_max is None:  # write up to down, beginning at (x, y)
            if col_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            ))
            # print('DEBUG 5:', print_coords[1])
        elif (col_max - col_min) > len(node) + 1:  # write up to down, if enough place
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset
                for offset in range(len(node))
            ))
            # print('DEBUG 6:', print_coords[1])
        else:  # not enough space
            if (row_max - row_min) > (col_max - col_min):
                # more space on Y axis
                node = node[:row_max - row_min]  # cut the node
                print_coords = (itertools.cycle((x,)), tuple(
                    x + offset
                    for offset in range(len(node))
                ))
                # print('DEBUG 7:', print_coords[1])
            else:
                # more space on X axis
                node = node[:col_max - col_min]  # cut the node
                print_coords[0] = tuple(
                    x + offset
                    for offset in range(len(node))
                )
                # print('DEBUG 8:', print_coords[0])

        for letter, i, j in zip(node, *print_coords):
            matrix_view[i, j] = letter




    if construction:
        yield view.build(matrix_view)
    else:
        yield from view.build(matrix_view)
116740
def _debugGraph(self):
        """"""
        print("Len of graph: ", len(self.rdflib_graph))
        for x, y, z in self.rdflib_graph:
            print(x, y, z)
698909
def _draw_ascii_graph(self, field):
        ''''''
        row_strings = []
        for y in range(len(field[0])):
            row = ''
            for x in range(len(field)):
                row += field[x][y]
            row_strings.insert(0, row)
        graph_string = '\n'.join(row_strings)
        return graph_string
852606
def _get_graph_properties(self, plot, element, data, mapping, ranges, style):
        ""
        sources = []
        properties, mappings = {}, {}

        for key in ('scatter_1', self.edge_glyph):
            gdata = data.pop(key, {})
            group_style = dict(style)
            style_group = self._style_groups.get('_'.join(key.split('_')[:-1]))

            with abbreviated_exception():
                group_style = self._apply_transforms(element, gdata, ranges, group_style, style_group)

            # Get source
            source = self._init_datasource(gdata)
            self.handles[key+'_source'] = source
            sources.append(source)

            # Get style
            others = [sg for sg in self._style_groups.values() if sg != style_group]
            glyph_props = self._glyph_properties(
                plot, element, source, ranges, group_style, style_group)
            for k, p in glyph_props.items():
                if any(k.startswith(o) for o in others):
                    continue
                properties[k] = p
            mappings.update(mapping.pop(key, {}))
        properties = {p: v for p, v in properties.items() if p not in ('legend', 'source')}
        properties.update(mappings)

        # Initialize graph layout
        layout = data.pop('layout', {})
        layout = StaticLayoutProvider(graph_layout=layout)
        self.handles['layout_source'] = layout

        return tuple(sources+[layout]), properties
302513
def iter(self, string):
		
		state = self.root
		for index, c in enumerate(string):
			while c not in state.children:
				state = state.fail

			state = state.children.get(c, self.root)

			tmp = state
			output = []
			while tmp is not nil:
				if tmp.output is not nil:
					output.append(tmp.output)

				tmp = tmp.fail

			if output:
				yield (index, output)
1343841
def graph_val_dump(self):
        """"""
        self._flush_graph_val()
        for (graph, key, branch, turn, tick, value) in self.sql('graph_val_dump'):
            yield (
                self.unpack(graph),
                self.unpack(key),
                branch,
                turn,
                tick,
                self.unpack(value)
            )
840342
def output_component(graph, edge_stack, u, v):
    """"""
    edge_list = []
    while len(edge_stack) > 0:
        edge_id = edge_stack.popleft()
        edge_list.append(edge_id)

        edge = graph.get_edge(edge_id)
        tpl_a = (u, v)
        tpl_b = (v, u)
        if tpl_a == edge['vertices'] or tpl_b == edge['vertices']:
            break

    return edge_list
778222
def get_vertex_string(self, i):
        """"""
        number = self.numbers[i]
        if number == 0:
            return Graph.get_vertex_string(self, i)
        else:
            # pad with zeros to make sure that string sort is identical to number sort
            return "%03i" % number
1275427
def to_string(self):
        


        graph = list()

        if self.obj_dict.get('strict', None) is not None:

            if (self == self.get_parent_graph() and
                    self.obj_dict['strict']):

                graph.append('strict ')

        graph_type = self.obj_dict['type']
        if (graph_type == 'subgraph' and
                not self.obj_dict.get('show_keyword', True)):
            graph_type = ''
        s = '{type} {name} {{\n'.format(
            type=graph_type,
            name=self.obj_dict['name'])
        graph.append(s)

        for attr in sorted(self.obj_dict['attributes']):

            if self.obj_dict['attributes'].get(attr, None) is not None:

                val = self.obj_dict['attributes'].get(attr)
                if val == '':
                    val = '""'
                if val is not None:
                    graph.append('%s=%s' %
                                 (attr, quote_if_necessary(val)))
                else:
                    graph.append( attr )

                graph.append( ';\n' )


        edges_done = set()

        edge_obj_dicts = list()
        for k in self.obj_dict['edges']:
            edge_obj_dicts.extend(self.obj_dict['edges'][k])

        if edge_obj_dicts:
            edge_src_set, edge_dst_set = list(zip(
                *[obj['points'] for obj in edge_obj_dicts]))
            edge_src_set, edge_dst_set = set(edge_src_set), set(edge_dst_set)
        else:
            edge_src_set, edge_dst_set = set(), set()

        node_obj_dicts = list()
        for k in self.obj_dict['nodes']:
            node_obj_dicts.extend(self.obj_dict['nodes'][k])

        sgraph_obj_dicts = list()
        for k in self.obj_dict['subgraphs']:
            sgraph_obj_dicts.extend(self.obj_dict['subgraphs'][k])


        obj_list = [(obj['sequence'], obj)
                    for obj in (edge_obj_dicts +
                                node_obj_dicts + sgraph_obj_dicts) ]
        obj_list.sort(key=lambda x: x[0])

        for idx, obj in obj_list:

            if obj['type'] == 'node':

                node = Node(obj_dict=obj)

                if self.obj_dict.get('suppress_disconnected', False):

                    if (node.get_name() not in edge_src_set and
                        node.get_name() not in edge_dst_set):

                        continue

                graph.append( node.to_string()+'\n' )

            elif obj['type'] == 'edge':

                edge = Edge(obj_dict=obj)

                if (self.obj_dict.get('simplify', False) and
                        edge in edges_done):
                    continue

                graph.append( edge.to_string() + '\n' )
                edges_done.add(edge)

            else:

                sgraph = Subgraph(obj_dict=obj)

                graph.append( sgraph.to_string()+'\n' )

        graph.append( '}\n' )

        return ''.join(graph)
175075
def visit_print(self, node):
        """"""
        nodes = ", ".join(n.accept(self) for n in node.values)
        if not node.nl:
            nodes = "%s," % nodes
        if node.dest:
            return "print >> %s, %s" % (node.dest.accept(self), nodes)
        return "print %s" % nodes
453904
def get_subgraphs(graph=None):
    
    graph = graph or DEPENDENCIES
    keys = set(graph)
    frontier = set()
    seen = set()
    while keys:
        frontier.add(keys.pop())
        while frontier:
            component = frontier.pop()
            seen.add(component)
            frontier |= set([d for d in get_dependencies(component) if d in graph])
            frontier |= set([d for d in get_dependents(component) if d in graph])
            frontier -= seen
        yield dict((s, get_dependencies(s)) for s in seen)
        keys -= seen
        seen.clear()
353708
def visit_yieldfrom(self, node):
        
        yi_val = (" " + node.value.accept(self)) if node.value else ""
        expr = "yield from" + yi_val
        if node.parent.is_statement:
            return expr

        return "(%s)" % (expr,)
604487
def fetch(self):
        
        self.retrieveVals()
        for parent_name in self._graphNames:
            graph = self._graphDict[parent_name]
            if self.isMultigraph:
                print "multigraph %s" % self._getMultigraphID(parent_name)
            print self._formatVals(graph.getVals())
            print
        if (self.isMultigraph and self._nestedGraphs 
            and self._subgraphDict and self._subgraphNames):
            for (parent_name, subgraph_names) in self._subgraphNames.iteritems():
                for graph_name in subgraph_names:
                    graph = self._subgraphDict[parent_name][graph_name]
                    print "multigraph %s" % self.getMultigraphID(parent_name, 
                                                                 graph_name)
                    print self._formatVals(graph.getVals())
                    print
        return True
226281
def dump_pytorch_graph(graph):
    """"""
    f = "{:25} {:40}   {} -> {}"
    print(f.format("kind", "scopeName", "inputs", "outputs"))
    for node in graph.nodes():
        print(f.format(node.kind(), node.scopeName(),
                       [i.unique() for i in node.inputs()],
                       [i.unique() for i in node.outputs()]
                       ))
1048079
def make_batch(size, graph):
        
        i = iter(graph)
        chunk = list(islice(i, size))
        while chunk:
            yield chunk
            chunk = list(islice(i, size))
34240
def _to_graph(self, contexts):
        """"""
        prev = None

        for context in contexts:
            if prev is None:
                prev = context
                continue

            yield prev[0], context[1], context[0]
            prev = context
86628
def _pathology_iterator(graph):
    
    for node in itt.chain.from_iterable(graph.edges()):
        if isinstance(node, Pathology):
            yield node