Build the transfromation graph once.
11022
def start_bundle(self, element=None):
    """"""
    import tensorflow as tf
    from trainer import feature_transforms

    g = tf.Graph()
    session = tf.Session(graph=g)

    # Build the transformation graph
    with g.as_default():
      transformed_features, _, placeholders = (
          feature_transforms.build_csv_serving_tensors_for_transform_step(
              analysis_path=self._analysis_output_dir, 
              features=self._features, 
              schema=self._schema,
              stats=self._stats,
              keep_target=True))
      session.run(tf.tables_initializer())
    
    self._session = session
    self._transformed_features = transformed_features
    self._input_placeholder_tensor = placeholders['csv_example']
1368761
def _build_graph(self) -> nx.DiGraph:
        
        digraph = nx.DiGraph()
        for state in self.model.all_states():
            self._number_of_states += 1
            for next_state in self.model.available_state(state):
                self._number_of_transitions += 1
                digraph.add_edge(
                    self._transform_state_to_string(state),
                    self._transform_state_to_string(next_state)
                )
        return digraph
73108
def _initialize_operations(self):
    
    if isinstance(self._graph, tf.Graph):
      return self._graph.get_operations()
    elif isinstance(self._graph, mtf.Graph):
      return self._graph.operations
    else:
      raise TypeError('Graph is not tf.Graph or mtf.Graph: {}'
                      .format(type(self._graph)))
336380
static void constructAvgTransactionGraph(Map.Entry<String, LrProjectScenarioResults> scenarioResults,
                                             JSONObject scenarioGraphData) {
        Map<Integer, TreeMap<String, AvgTransactionResponseTime>> avgTransactionResponseTimeResults =
                scenarioResults.getValue().getAvgTransactionResponseTimeResults();
        JSONObject avgTransactionResponseTimeGraphSet =
                extractAvgTrtData(avgTransactionResponseTimeResults, scenarioResults.getValue().getTransactions());
        if (!avgTransactionResponseTimeGraphSet.getJSONArray(LABELS).isEmpty()) {
            avgTransactionResponseTimeGraphSet.put(TITLE, "Average Transaction Response TIme");
            avgTransactionResponseTimeGraphSet.put(X_AXIS_TITLE, "Build number");
            avgTransactionResponseTimeGraphSet
                    .put(Y_AXIS_TITLE, "Time (Sec.)");
            avgTransactionResponseTimeGraphSet.put(DESCRIPTION,
                    "Displays the average time taken to perform transactions during each second of the load test." +
                            " This graph helps you determine whether the performance of the server is within " +
                            "acceptable minimum and maximum transaction performance time ranges defined for your " +
                            "system.");
            scenarioGraphData.put("averageTransactionResponseTime", avgTransactionResponseTimeGraphSet);
        }
    }
567697
def process_input_graph(func):
    """"""
    @wraps(func)
    def wrapped_func(*args, **kwargs):
        input_graph = args[0]
        if isinstance(input_graph, nx.DiGraph):
            return func(*args, **kwargs)
        else:
            nx_graph = dict_to_nx(args[0], oriented=True)
            args = [nx_graph] + list(args[1:])
            return func(*args, **kwargs)
    return wrapped_func
342024
void build(int nodeOffset, GraphMeshData graphData, List<int[]> connections) {
		for (int n = 0; n < connections.size(); n++) {
			int[] nodeConnections = connections.get(n);
			MeshData tile = graphData.getTile(n);
			Poly node = graphData.getNode(n);
			for (int connection : nodeConnections) {
				MeshData neighbourTile = graphData.getTile(connection - nodeOffset);
				if (neighbourTile != tile) {
					buildExternalLink(tile, node, neighbourTile);
				} else {
					Poly neighbour = graphData.getNode(connection - nodeOffset);
					buildInternalLink(tile, node, neighbourTile, neighbour);
				}
			}
		}
	}
1264767
def tp_graph(dataframe, image_name, dir='./'):
    
    fig = pygal.TimeLine(x_title='Elapsed Time In Test (secs)',
                         x_label_rotation=25,
                         y_title='Transactions Per Second (count)',
                         human_readable=True,
                         js=('scripts/pygal-tooltip.min.js',))
    fig.add('Transactions per second', [(get_local_time(index), row['count'])
                                        for index, row in dataframe.iterrows()])
    fig.render_to_file(filename=os.path.join(dir, image_name))
234951
def save_graph_to_file(graph_file_name, module_spec, class_count):
  """"""
  sess, _, _, _, _, _ = build_eval_session(module_spec, class_count)
  graph = sess.graph

  output_graph_def = tf.graph_util.convert_variables_to_constants(
      sess, graph.as_graph_def(), [FLAGS.final_tensor_name])

  with tf.gfile.GFile(graph_file_name, 'wb') as f:
    f.write(output_graph_def.SerializeToString())
320241
def show_graph(cn_topo, showintfs=False, showaddrs=False):
    '''
     
    '''
    __do_draw(cn_topo, showintfs=showintfs, showaddrs=showaddrs)
    pyp.show()
970241
def merge(self, graph, witness_sigil, witness_tokens, alignments={}):
        
        # NOTE: token_to_vertex only contains newly generated vertices
        token_to_vertex = {}
        last = graph.start
        for token in witness_tokens:
            vertex = alignments.get(token, None)
            if not vertex:
                vertex = graph.add_vertex(token, witness_sigil)
                token_to_vertex[token] = vertex
            else:
                vertex.add_token(witness_sigil, token)
                # graph.add_token_to_vertex(vertex, token, witness_sigil)
            graph.connect(last, vertex, witness_sigil)
            last = vertex
        graph.connect(last, graph.end, witness_sigil)
        return token_to_vertex
104474
def build_chvatal_graph():
    """"""
    # The easiest way to build the Chvatal graph is to start
    # with C12 and add the additional 12 edges
    graph = build_cycle_graph(12)

    edge_tpls = [
        (1,7), (1,9), (2,5), (2,11),
        (3,7), (3,9), (4,10), (4,12),
        (5,8), (6,10), (6,12), (8,11),
    ]

    for i, j in edge_tpls:
        graph.new_edge(i, j)

    return graph
1112786
def bfs(graph, start):
    
    # maintain a queue of paths
    queue = []
    visited = []
    # maintain a queue of nodes
    # push the first path into the queue
    queue.append([['', start]])
    while queue:
        # get the first path from the queue
        path = queue.pop(0)
        # get the last node from the path
        node = path[-1][1]
        if node.stateid not in visited:
            visited.append(node.stateid)
            # path found
            if node.final != TropicalWeight(float('inf')):
                return "".join([mnode[0] for mnode in path])
            # enumerate all adjacent nodes, construct a new path and push
            # it into the queue
            for arc in node.arcs:
                char = graph.isyms.find(arc.ilabel)
                next_state = graph[arc.nextstate]
                # print next_state.stateid
                if next_state.stateid not in visited:
                    new_path = list(path)
                    new_path.append([char, next_state])
                    queue.append(new_path)
887163
def build_wheel_graph(num_nodes):
    """"""
    # The easiest way to build a wheel graph is to build
    # C_n-1 and then add a hub node and spoke edges
    graph = build_cycle_graph(num_nodes - 1)

    cycle_graph_vertices = graph.get_all_node_ids()

    node_id = graph.new_node()
    for cycle_node in cycle_graph_vertices:
        graph.new_edge(node_id, cycle_node)

    return graph
1353880
def graph(bare=False, json=False, json_tree=False, reverse=False):
    """"""
    from ..core import do_graph

    do_graph(bare=bare, json=json, json_tree=json_tree, reverse=reverse)
1138161
def project_onto(objs, axis, min_gap_size=4.0):
    
    if axis == "x":
        axis = 0
    if axis == "y":
        axis = 1
    axis_end = axis + 2
    if axis == 0:  # if projecting onto X axis
        objs.sort(key=lambda o: o.x0)
    else:
        objs.sort(key=lambda o: o.y0)

    intervals = []
    groups = []

    start_i = 0
    start = objs[0].bbox[axis]
    end = objs[0].bbox[axis_end]

    # Use _inf_bbox to trigger the last interval divide
    for o_i, o in enumerate(chain(objs, [_inf_bbox])):

        # Get current interval
        o_start = o.bbox[axis]
        o_end = o.bbox[axis_end]

        # start new interval when gap with previous end is big
        if o_start > end + min_gap_size:

            # Append new interval coordinates for children
            intervals.append((start, end))

            # Append child object group on page
            groups.append(objs[start_i:o_i])

            # Mark next obj list range
            start_i = o_i
            start = o_start

        # Always check to extend current interval to new end
        if o_end > end:
            end = o_end
        # else do nothing
    return intervals, groups
2974
def build_graph(self, image, label):
        """"""

        # In tensorflow, inputs to convolution function are assumed to be
        # NHWC. Add a single channel here.
        image = tf.expand_dims(image, 3)

        image = image * 2 - 1   # center the pixels values at zero
        # The context manager `argscope` sets the default option for all the layers under
        # this context. Here we use 32 channel convolution with shape 3x3
        with argscope(Conv2D, kernel_size=3, activation=tf.nn.relu, filters=32):
            logits = (LinearWrap(image)
                      .Conv2D('conv0')
                      .MaxPooling('pool0', 2)
                      .Conv2D('conv1')
                      .Conv2D('conv2')
                      .MaxPooling('pool1', 2)
                      .Conv2D('conv3')
                      .FullyConnected('fc0', 512, activation=tf.nn.relu)
                      .Dropout('dropout', rate=0.5)
                      .FullyConnected('fc1', 10, activation=tf.identity)())

        # a vector of length B with loss of each sample
        cost = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=label)
        cost = tf.reduce_mean(cost, name='cross_entropy_loss')  # the average cross-entropy loss

        correct = tf.cast(tf.nn.in_top_k(predictions=logits, targets=label, k=1), tf.float32, name='correct')
        accuracy = tf.reduce_mean(correct, name='accuracy')

        # This will monitor training error & accuracy (in a moving average fashion). The value will be automatically
        # 1. written to tensosrboard
        # 2. written to stat.json
        # 3. printed after each epoch
        train_error = tf.reduce_mean(1 - correct, name='train_error')
        summary.add_moving_summary(train_error, accuracy)

        # Use a regex to find parameters to apply weight decay.
        # Here we apply a weight decay on all W (weight matrix) of all fc layers
        # If you don't like regex, you can certainly define the cost in any other methods.
        wd_cost = tf.multiply(1e-5,
                              regularize_cost('fc.*/W', tf.nn.l2_loss),
                              name='regularize_loss')
        total_cost = tf.add_n([wd_cost, cost], name='total_cost')
        summary.add_moving_summary(cost, wd_cost, total_cost)

        # monitor histogram of all weight (of conv and fc layers) in tensorboard
        summary.add_param_summary(('.*/W', ['histogram', 'rms']))
        # the function should return the total cost to be optimized
        return total_cost
904277
def construct(start_block, vmap, exceptions):
    
    bfs_blocks = bfs(start_block)

    graph = Graph()
    gen_ret = GenInvokeRetName()

    # Construction of a mapping of basic blocks into Nodes
    block_to_node = {}

    exceptions_start_block = []
    for exception in exceptions:
        for _, _, block in exception.exceptions:
            exceptions_start_block.append(block)

    for block in bfs_blocks:
        node = make_node(graph, block, block_to_node, vmap, gen_ret)
        graph.add_node(node)

    graph.entry = block_to_node[start_block]
    del block_to_node, bfs_blocks

    graph.compute_rpo()
    graph.number_ins()

    for node in graph.rpo:
        preds = [pred for pred in graph.all_preds(node) if pred.num < node.num]
        if preds and all(pred.in_catch for pred in preds):
            node.in_catch = True

    # Create a list of Node which are 'return' node
    # There should be one and only one node of this type
    # If this is not the case, try to continue anyway by setting the exit node
    # to the one which has the greatest RPO number (not necessarily the case)
    lexit_nodes = [node for node in graph if node.type.is_return]

    if len(lexit_nodes) > 1:
        # Not sure that this case is possible...
        logger.error('Multiple exit nodes found !')
        graph.exit = graph.rpo[-1]
    elif len(lexit_nodes) < 1:
        # A method can have no return if it has throw statement(s) or if its
        # body is a while(1) whitout break/return.
        logger.debug('No exit node found !')
    else:
        graph.exit = lexit_nodes[0]

    return graph