Accepts a list of y values and returns an ascii graph
        Optionally values can also be a dictionary with a key of timestamp, and a value of value. InGraphs returns data in this format for example.
433176
def asciigraph(self, values=None, max_height=None, max_width=None, label=False):
        '''
        
        '''
        result = ''
        border_fill_char = '*'
        start_ctime = None
        end_ctime = None

        if not max_width:
            max_width = 180

        # If this is a dict of timestamp -> value, sort the data, store the start/end time, and convert values to a list of values
        if isinstance(values, dict):
            time_series_sorted = sorted(list(values.items()), key=lambda x: x[0])  # Sort timestamp/value dict by the timestamps

            start_timestamp = time_series_sorted[0][0]
            end_timestamp = time_series_sorted[-1][0]

            start_ctime = datetime.fromtimestamp(float(start_timestamp)).ctime()
            end_ctime = datetime.fromtimestamp(float(end_timestamp)).ctime()
            values = self._scale_x_values_timestamps(values=time_series_sorted, max_width=max_width)
        values = [value for value in values if value is not None]

        if not max_height:
            max_height = min(20, max(values))

        stdev = statistics.stdev(values)
        mean = statistics.mean(values)

        # Do value adjustments
        adjusted_values = list(values)
        adjusted_values = self._scale_x_values(values=values, max_width=max_width)
        upper_value = max(adjusted_values)  # Getting upper/lower after scaling x values so we don't label a spike we can't see
        lower_value = min(adjusted_values)
        adjusted_values = self._scale_y_values(values=adjusted_values, new_min=0, new_max=max_height, scale_old_from_zero=False)
        adjusted_values = self._round_floats_to_ints(values=adjusted_values)

        # Obtain Ascii Graph String
        field = self._get_ascii_field(adjusted_values)
        graph_string = self._draw_ascii_graph(field=field)

        # Label the graph
        if label:
            top_label = 'Upper value: {upper_value:.2f} '.format(upper_value=upper_value).ljust(max_width, border_fill_char)
            result += top_label + '\n'
        result += '{graph_string}\n'.format(graph_string=graph_string)
        if label:
            lower = f'Lower value: {lower_value:.2f} '
            stats = f' Mean: {mean:.2f} *** Std Dev: {stdev:.2f} ******'
            fill_length = max_width - len(lower) - len(stats)
            stat_label = f'{lower}{"*" * fill_length}{stats}\n'
            result += stat_label

            if start_ctime and end_ctime:
                fill_length = max_width - len(start_ctime) - len(end_ctime)
                result += f'{start_ctime}{" " * fill_length}{end_ctime}\n'

        return result
492437
def _get_accepted(self, graph):
        
        accepted = []
        for state in graph.states:
            if state.final != TropicalWeight(float('inf')):
                accepted.append(state)
        return accepted
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)
            )
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
1149890
public <K, EV> Graph<K, NullValue, EV> edgeTypes(Class<K> vertexKey, Class<EV> edgeValue) {

		if (edgeReader == null) {
			throw new RuntimeException("The edge input file cannot be null!");
		}

		DataSet<Tuple3<K, K, EV>> edges = edgeReader
			.types(vertexKey, vertexKey, edgeValue)
				.name(GraphCsvReader.class.getName());

		return Graph.fromTupleDataSet(edges, executionContext);
	}
908926
def _get_values(values, skipna, fill_value=None, fill_value_typ=None,
                isfinite=False, copy=True, mask=None):
    

    if is_datetime64tz_dtype(values):
        # com.values_from_object returns M8[ns] dtype instead of tz-aware,
        #  so this case must be handled separately from the rest
        dtype = values.dtype
        values = getattr(values, "_values", values)
    else:
        values = com.values_from_object(values)
        dtype = values.dtype

    if mask is None:
        if isfinite:
            mask = _isfinite(values)
        else:
            mask = isna(values)

    if is_datetime_or_timedelta_dtype(values) or is_datetime64tz_dtype(values):
        # changing timedelta64/datetime64 to int64 needs to happen after
        #  finding `mask` above
        values = getattr(values, "asi8", values)
        values = values.view(np.int64)

    dtype_ok = _na_ok_dtype(dtype)

    # get our fill value (in case we need to provide an alternative
    # dtype for it)
    fill_value = _get_fill_value(dtype, fill_value=fill_value,
                                 fill_value_typ=fill_value_typ)

    if skipna:
        if copy:
            values = values.copy()
        if dtype_ok:
            np.putmask(values, mask, fill_value)

        # promote if needed
        else:
            values, changed = maybe_upcast_putmask(values, mask, fill_value)

    elif copy:
        values = values.copy()

    # return a platform independent precision dtype
    dtype_max = dtype
    if is_integer_dtype(dtype) or is_bool_dtype(dtype):
        dtype_max = np.int64
    elif is_float_dtype(dtype):
        dtype_max = np.float64

    return values, mask, dtype, dtype_max, fill_value
1245648
public Graph nodes(Node... values) {
        if (values == null || values.length == 0) {
            return this;
        }
        this.nodes().addAll(Arrays.asList(values));
        return this;
    }
368847
def get_parameters(self, graph=None):
        
        g = graph if graph is not None else self.tf_graph

        with g.as_default():
            with tf.Session() as self.tf_session:
                self.tf_saver.restore(self.tf_session, self.model_path)

                return {
                    'W': self.W.eval(),
                    'bh_': self.bh_.eval(),
                    'bv_': self.bv_.eval()
                }
1364226
def rdf2dot( g, stream, opts={} ):
    

    accept_lang = set( opts.get('lang',[]) )
    do_literal = opts.get('literal')
    nodes = {}
    links = []

    def node_id(x):
        if x not in nodes:
            nodes[x] = "node%d" % len(nodes)
        return nodes[x]

    def qname(x, g):
        try:
            q = g.compute_qname(x)
            return q[0] + ":" + q[2]
        except:
            return x

    def accept( node ):
        if isinstance( node, (rdflib.URIRef,rdflib.BNode) ):
            return True
        if not do_literal:
            return False
        return (not accept_lang) or (node.language in accept_lang)


    stream.write( u'digraph { \n node [ fontname="DejaVu Sans,Tahoma,Geneva,sans-serif" ] ; \n' )

    # Write all edges. In the process make a list of all nodes
    for s, p, o in g:
        # skip triples for labels
        if p == rdflib.RDFS.label:
            continue

        # Create a link if both objects are graph nodes
        # (or, if literals are also included, if their languages match)
        if not (accept(s) and accept(o)):
            continue

        # add the nodes to the list
        sn = node_id(s)
        on = node_id(o)

        # add the link
        q = qname(p,g)
        if isinstance(p, rdflib.URIRef):
            opstr = u'\t%s -> %s [ arrowhead="open", color="#9FC9E560", fontsize=9, fontcolor="#204080", label="%s", href="%s", target="_other" ] ;\n' % (sn,on,q,p)
        else:
            opstr = u'\t%s -> %s [ arrowhead="open", color="#9FC9E560", fontsize=9, fontcolor="#204080", label="%s" ] ;\n'%(sn,on,q)
        stream.write( opstr )

    # Write all nodes
    for u, n in nodes.items():
        lbl = escape( label(u,g,accept_lang), True )
        if isinstance(u, rdflib.URIRef):
            opstr = u'%s [ shape=none, fontsize=10, fontcolor=%s, label="%s", href="%s", target=_other ] \n' % (n, 'blue', lbl, u )
        else:
            opstr = u'%s [ shape=none, fontsize=10, fontcolor=%s, label="%s" ] \n' % (n, 'black', lbl )
        stream.write( u"# %s %s\n" % (u, n) )
        stream.write( opstr )

    stream.write(u'}\n')
81512
def as_graph(self) -> Graph:  # pragma: no cover
        """"""
        if Graph is None:
            raise ImportError('The graphviz package is required to draw the graph.')
        graph = Graph()
        nodes_left = {}  # type: Dict[TLeft, str]
        nodes_right = {}  # type: Dict[TRight, str]
        node_id = 0
        for (left, right), value in self._edges.items():
            if left not in nodes_left:
                name = 'node{:d}'.format(node_id)
                nodes_left[left] = name
                graph.node(name, label=str(left))
                node_id += 1
            if right not in nodes_right:
                name = 'node{:d}'.format(node_id)
                nodes_right[right] = name
                graph.node(name, label=str(right))
                node_id += 1
            edge_label = value is not True and str(value) or ''
            graph.edge(nodes_left[left], nodes_right[right], edge_label)
        return graph
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
470254
def edges(self):
        
        edge_str = ctypes.create_string_buffer(MAX_CHARS)

        cgaddag.gdg_edges(self.gdg, self.node, edge_str)

        return [char for char in edge_str.value.decode("ascii")]
123956
def _tag_dict_values(self, map_node):
        
        new_values = []
        for key, value in map_node.value:
            if not value.tag.endswith(':str'):
                new_values.append((key, value,))
                continue

            augmented_string = yaml.nodes.MappingNode(
                tag=map_node.tag,
                value=[
                    self._create_key_value_pair_for_mapping_node_value(
                        '__value__',
                        value.value,
                        'tag:yaml.org,2002:str',
                    ),
                    self._create_key_value_pair_for_mapping_node_value(
                        '__line__',
                        str(value.__line__),
                        'tag:yaml.org,2002:int',
                    ),
                ],
            )

            new_values.append((key, augmented_string,))

        output = yaml.nodes.MappingNode(
            tag=map_node.tag,
            value=new_values,
            start_mark=map_node.start_mark,
            end_mark=map_node.end_mark,
            flow_style=map_node.flow_style,
        )
        return output
393841
def get_unused_list_annotation_values(graph) -> Mapping[str, Set[str]]:
    
    result = {}
    for annotation, values in graph.annotation_list.items():
        used_values = get_annotation_values(graph, annotation)
        if len(used_values) == len(values):  # all values have been used
            continue
        result[annotation] = set(values) - used_values
    return result
406452
def to_json(df, x, y, timeseries=False):
        """"""
        values = {k: [] for k in y}
        for i, row in df.iterrows():
            for yy in y:
                values[yy].append({
                    "x": row[x],
                    "y": row[yy]
                    })
        return {"result":  [values[k] for k in y], "date": timeseries}
1271822
def parse_dot_data(s):
    
    global top_graphs
    top_graphs = list()
    try:
        graphparser = graph_definition()
        graphparser.parseWithTabs()
        tokens = graphparser.parseString(s)
        return list(tokens)
    except ParseException as err:
        print(
            err.line +
            " "*(err.column-1) + "^" +
            err)
        return None
121048
def prepare_values(self, raw, offset=0):
        """"""
        from pygal.graph.map import BaseMap
        from pygal import Histogram

        if self.zero == 0 and isinstance(self, BaseMap):
            self.zero = 1

        if self.x_label_rotation:
            self.x_label_rotation %= 360

        if self.y_label_rotation:
            self.y_label_rotation %= 360

        for key in ('x_labels', 'y_labels'):
            if getattr(self, key):
                setattr(self, key, list(getattr(self, key)))
        if not raw:
            return

        adapters = list(self._adapters) or [lambda x: x]
        if self.logarithmic:
            for fun in not_zero, positive:
                if fun in adapters:
                    adapters.remove(fun)
            adapters = adapters + [positive, not_zero]
        adapters = adapters + [decimal_to_float]

        self._adapt = reduce(compose, adapters) if not self.strict else ident
        self._x_adapt = reduce(
            compose, self._x_adapters
        ) if not self.strict and getattr(self, '_x_adapters', None) else ident

        series = []

        raw = [(
            list(raw_values) if not isinstance(raw_values, dict) else
            raw_values, serie_config_kwargs
        ) for raw_values, serie_config_kwargs in raw]

        width = max([len(values)
                     for values, _ in raw] + [len(self.x_labels or [])])

        for raw_values, serie_config_kwargs in raw:
            metadata = {}
            values = []
            if isinstance(raw_values, dict):
                if isinstance(self, BaseMap):
                    raw_values = list(raw_values.items())
                else:
                    value_list = [None] * width
                    for k, v in raw_values.items():
                        if k in (self.x_labels or []):
                            value_list[self.x_labels.index(k)] = v
                    raw_values = value_list

            for index, raw_value in enumerate(raw_values + (
                (width - len(raw_values)) * [None]  # aligning values
                    if len(raw_values) < width else [])):
                if isinstance(raw_value, dict):
                    raw_value = dict(raw_value)
                    value = raw_value.pop('value', None)
                    metadata[index] = raw_value
                else:
                    value = raw_value

                # Fix this by doing this in charts class methods
                if isinstance(self, Histogram):
                    if value is None:
                        value = (None, None, None)
                    elif not is_list_like(value):
                        value = (value, self.zero, self.zero)
                    elif len(value) == 2:
                        value = (1, value[0], value[1])
                    value = list(map(self._adapt, value))
                elif self._dual:
                    if value is None:
                        value = (None, None)
                    elif not is_list_like(value):
                        value = (value, self.zero)
                    if self._x_adapt:
                        value = (
                            self._x_adapt(value[0]), self._adapt(value[1])
                        )
                    if isinstance(self, BaseMap):
                        value = (self._adapt(value[0]), value[1])
                    else:
                        value = list(map(self._adapt, value))
                else:
                    value = self._adapt(value)

                values.append(value)
            serie_config = SerieConfig()
            serie_config(
                **dict((k, v) for k, v in self.state.__dict__.items()
                       if k in dir(serie_config))
            )
            serie_config(**serie_config_kwargs)
            series.append(
                Serie(offset + len(series), values, serie_config, metadata)
            )
        return series