Take a random walk from a source.

    Start at a node randomly selected from those that receive input from a
    source. At each step, transmit to a randomly-selected downstream node.
190224
def random_walk(network):
    
    latest = network.latest_transmission_recipient()

    if (not network.transmissions() or latest is None):
        sender = random.choice(network.nodes(type=Source))
    else:
        sender = latest

    receiver = random.choice(sender.neighbors(direction="to", type=Agent))

    sender.transmit(to_whom=receiver)
56177
def add_node_to_network(self, node, network):
        """"""
        network.add_node(node)
        parents = node.neighbors(direction="from")
        if len(parents):
            parent = parents[0]
            parent.transmit()
        node.receive()
1345084
def visit(node)
      emitter = emitter(node)
      conditional_parentheses(!emitter.terminated?) do
        emitter.write_to_buffer
      end
    end
437615
public void step() throws IOException {
        if (closed) {
            throw new ClosedChannelException();
        }
        if (input.position() == header.length) {
            if (command == null) {
                command = CommandFactory.create(input);
            }

            if (command.complete()) {
                command.process();
                protocolHandler.execute(command, this);
                command = null;
                input.rewind();
            }
        }
    }
832426
function move(node, stayWithin, directionIsNext) {
  if (directionIsNext) {
    return NodeTraversal.next(node, stayWithin);
  } else {
    if (node === stayWithin) {
      return null;
    }
    return NodeTraversal.previous(node, null);
  }
}
230737
def _random_cycle(adj, random_state):
    """"""

    # step through idx values in adj to pick a random one, random.choice does not work on dicts
    n = random_state.randint(len(adj))
    for idx, v in enumerate(adj):
        if idx == n:
            break
    start = v

    walk = [start]
    visited = {start: 0}

    while True:
        if len(walk) > 1:
            # as long as we don't step back one we won't have any repeated edges
            previous = walk[-2]
            neighbors = [u for u in adj[walk[-1]] if u != previous]
        else:
            neighbors = list(adj[walk[-1]])

        if not neighbors:
            # we've walked into a dead end
            return None

        # get a random neighbor
        u = random_state.choice(neighbors)
        if u in visited:
            # if we've seen this neighbour, then we have a cycle starting from it
            return walk[visited[u]:]
        else:
            # add to walk and keep moving
            walk.append(u)
            visited[u] = len(visited)
865301
def send(x, inter=0, loop=0, count=None, verbose=None, realtime=None, *args, **kargs):
    """"""
    __gen_send(conf.L3socket(*args, **kargs), x, inter=inter, loop=loop, count=count,verbose=verbose, realtime=realtime)
296905
async def create_link(project, nodes):
    
    node1 = random.choice(list(nodes.values()))

    for port in range(0, 8):
        node2 = random.choice(list(nodes.values()))

        if node1 == node2:
            continue

        data = {"nodes":
                [
                    {
                        "adapter_number": 0,
                        "node_id": node1["node_id"],
                        "port_number": port
                    },
                    {
                        "adapter_number": 0,
                        "node_id": node2["node_id"],
                        "port_number": port
                    }
                ]
                }
        try:
            await post("/projects/{}/links".format(project["project_id"]), body=data)
        except (HTTPConflict, HTTPNotFound):
            pass
110016
function moveStart(rng) {
        var container = rng.startContainer,
          offset = rng.startOffset, isAtEndOfText,
          walker, node, nodes, tmpNode;

        if (rng.startContainer == rng.endContainer) {
          if (isInlineBlock(rng.startContainer.childNodes[rng.startOffset])) {
            return;
          }
        }

        // Convert text node into index if possible
        if (container.nodeType == 3 && offset >= container.nodeValue.length) {
          // Get the parent container location and walk from there
          offset = nodeIndex(container);
          container = container.parentNode;
          isAtEndOfText = true;
        }

        // Move startContainer/startOffset in to a suitable node
        if (container.nodeType == 1) {
          nodes = container.childNodes;
          container = nodes[Math.min(offset, nodes.length - 1)];
          walker = new TreeWalker(container, dom.getParent(container, dom.isBlock));

          // If offset is at end of the parent node walk to the next one
          if (offset > nodes.length - 1 || isAtEndOfText) {
            walker.next();
          }

          for (node = walker.current(); node; node = walker.next()) {
            if (node.nodeType == 3 && !isWhiteSpaceNode(node)) {
              // IE has a "neat" feature where it moves the start node into the closest element
              // we can avoid this by inserting an element before it and then remove it after we set the selection
              tmpNode = dom.create('a', { 'data-mce-bogus': 'all' }, INVISIBLE_CHAR);
              node.parentNode.insertBefore(tmpNode, node);

              // Set selection and remove tmpNode
              rng.setStart(node, 0);
              selection.setRng(rng);
              dom.remove(tmpNode);

              return;
            }
          }
        }
      }
1183421
def add_node(self, node):
        """"""
        other_nodes = [n for n in self.nodes() if n.id != node.id]

        for n in other_nodes:
            if isinstance(n, Source):
                node.connect(direction="from", whom=n)
            else:
                node.connect(direction="both", whom=n)
344698
protected Map.Entry<TrustGraphNodeId,TrustGraphNodeId> randomRoute() {
        final int routeNumber = rng.nextInt(routingTable.size()); 
        final Iterator<Map.Entry<TrustGraphNodeId,TrustGraphNodeId>> routes =
                routingTable.entrySet().iterator();
        for (int i = 0; i < routeNumber; i++) { routes.next(); }
        return routes.next();
    }
1300643
function receive(node, config, socket, message) {

    message.socket = socket.id

    let data = botmgr.buildMessageFlow({ "message" : message }, {
        userId:     'message.socket', 
        convId:     'message.socket',
        payload:    'message.content',
        inputType:  'message.type',
        source:     CARRIER
    })
    

    if (data.message.type === "event") {
        if (data.message.content === "cmd-next") {
            node.warn({'next': data.message})
            return helper.emitEvent('endSound', node);
        }
    }
    else {
        node.warn({'received': data.message})

        // Handle Prompt
        let convId  = botmgr.getConvId(data)
        if (botmgr.hasDelayedCallback(convId, data.message)) return;
    }

    // Trigger received message
    helper.emitEvent('received', node, data, config);
    node.send(data);
}
1051235
def start(self):
        
        assert self.stop_event.ready(), f'Node already started. node:{self!r}'
        self.stop_event.clear()
        self.greenlets = list()

        self.ready_to_process_events = False  # set to False because of restarts

        if self.database_dir is not None:
            self.db_lock.acquire(timeout=0)
            assert self.db_lock.is_locked, f'Database not locked. node:{self!r}'

        # start the registration early to speed up the start
        if self.config['transport_type'] == 'udp':
            endpoint_registration_greenlet = gevent.spawn(
                self.discovery.register,
                self.address,
                self.config['transport']['udp']['external_ip'],
                self.config['transport']['udp']['external_port'],
            )

        self.maybe_upgrade_db()

        storage = sqlite.SerializedSQLiteStorage(
            database_path=self.database_path,
            serializer=serialize.JSONSerializer(),
        )
        storage.update_version()
        storage.log_run()
        self.wal = wal.restore_to_state_change(
            transition_function=node.state_transition,
            storage=storage,
            state_change_identifier='latest',
        )

        if self.wal.state_manager.current_state is None:
            log.debug(
                'No recoverable state available, creating inital state.',
                node=pex(self.address),
            )
            # On first run Raiden needs to fetch all events for the payment
            # network, to reconstruct all token network graphs and find opened
            # channels
            last_log_block_number = self.query_start_block
            last_log_block_hash = self.chain.client.blockhash_from_blocknumber(
                last_log_block_number,
            )

            state_change = ActionInitChain(
                pseudo_random_generator=random.Random(),
                block_number=last_log_block_number,
                block_hash=last_log_block_hash,
                our_address=self.chain.node_address,
                chain_id=self.chain.network_id,
            )
            self.handle_and_track_state_change(state_change)

            payment_network = PaymentNetworkState(
                self.default_registry.address,
                [],  # empty list of token network states as it's the node's startup
            )
            state_change = ContractReceiveNewPaymentNetwork(
                transaction_hash=constants.EMPTY_HASH,
                payment_network=payment_network,
                block_number=last_log_block_number,
                block_hash=last_log_block_hash,
            )
            self.handle_and_track_state_change(state_change)
        else:
            # The `Block` state change is dispatched only after all the events
            # for that given block have been processed, filters can be safely
            # installed starting from this position without losing events.
            last_log_block_number = views.block_number(self.wal.state_manager.current_state)
            log.debug(
                'Restored state from WAL',
                last_restored_block=last_log_block_number,
                node=pex(self.address),
            )

            known_networks = views.get_payment_network_identifiers(views.state_from_raiden(self))
            if known_networks and self.default_registry.address not in known_networks:
                configured_registry = pex(self.default_registry.address)
                known_registries = lpex(known_networks)
                raise RuntimeError(
                    f'Token network address mismatch.\n'
                    f'Raiden is configured to use the smart contract '
                    f'{configured_registry}, which conflicts with the current known '
                    f'smart contracts {known_registries}',
                )

        # Restore the current snapshot group
        state_change_qty = self.wal.storage.count_state_changes()
        self.snapshot_group = state_change_qty // SNAPSHOT_STATE_CHANGES_COUNT

        # Install the filters using the latest confirmed from_block value,
        # otherwise blockchain logs can be lost.
        self.install_all_blockchain_filters(
            self.default_registry,
            self.default_secret_registry,
            last_log_block_number,
        )

        # Complete the first_run of the alarm task and synchronize with the
        # blockchain since the last run.
        #
        # Notes about setup order:
        # - The filters must be polled after the node state has been primed,
        # otherwise the state changes won't have effect.
        # - The alarm must complete its first run before the transport is started,
        #   to reject messages for closed/settled channels.
        self.alarm.register_callback(self._callback_new_block)
        self.alarm.first_run(last_log_block_number)

        chain_state = views.state_from_raiden(self)

        self._initialize_payment_statuses(chain_state)
        self._initialize_transactions_queues(chain_state)
        self._initialize_messages_queues(chain_state)
        self._initialize_whitelists(chain_state)
        self._initialize_monitoring_services_queue(chain_state)
        self._initialize_ready_to_processed_events()

        if self.config['transport_type'] == 'udp':
            endpoint_registration_greenlet.get()  # re-raise if exception occurred

        # Start the side-effects:
        # - React to blockchain events
        # - React to incoming messages
        # - Send pending transactions
        # - Send pending message
        self.alarm.link_exception(self.on_error)
        self.transport.link_exception(self.on_error)
        self._start_transport(chain_state)
        self._start_alarm_task()

        log.debug('Raiden Service started', node=pex(self.address))
        super().start()
1335994
@VisibleForTesting
  public static List<FlowEdge> dijkstraBasedPathFindingHelper(ServiceNode sourceNode, ServiceNode targetNode,
      DirectedWeightedMultigraph<ServiceNode, FlowEdge> weightedGraph) {
    Map<DistancedNode, ArrayList<FlowEdge>> shortestPath = new HashMap<>();
    Map<DistancedNode, Double> shortestDist = new HashMap<>();
    PriorityQueue<DistancedNode> pq = new PriorityQueue<>(new Comparator<DistancedNode>() {
      @Override
      public int compare(DistancedNode o1, DistancedNode o2) {
        if (o1.getDistToSrc() < o2.getDistToSrc()) {
          return -1;
        } else {
          return 1;
        }
      }
    });
    pq.add(new DistancedNode(sourceNode, 0.0));

    Set<FlowEdge> visitedEdge = new HashSet<>();

    while(!pq.isEmpty()) {
      DistancedNode node = pq.poll();
      if (node.getNode().getNodeName().equals(targetNode.getNodeName())) {
        // Searching finished
        return shortestPath.get(node);
      }

      Set<FlowEdge> outgoingEdges = weightedGraph.outgoingEdgesOf(node.getNode());
      for (FlowEdge outGoingEdge:outgoingEdges) {
        // Since it is a multi-graph problem, should use edge for deduplicaiton instead of vertex.
        if (visitedEdge.contains(outGoingEdge)) {
          continue;
        }

        DistancedNode adjacentNode = new DistancedNode(weightedGraph.getEdgeTarget(outGoingEdge));
        if (shortestDist.containsKey(adjacentNode)) {
          adjacentNode.setDistToSrc(shortestDist.get(adjacentNode));
        }

        double newDist = node.getDistToSrc() + ((LoadBasedFlowEdgeImpl) outGoingEdge).getEdgeLoad();

        if (newDist < adjacentNode.getDistToSrc()) {
          if (pq.contains(adjacentNode)) {
            pq.remove(adjacentNode);
          }

          // Update the shortest path.
          ArrayList<FlowEdge> path = shortestPath.containsKey(node)
              ? new ArrayList<>(shortestPath.get(node)) : new ArrayList<>();
          path.add(outGoingEdge);
          shortestPath.put(adjacentNode, path);
          shortestDist.put(adjacentNode, newDist);

          adjacentNode.setDistToSrc(newDist);
          pq.add(adjacentNode);
        }
        visitedEdge.add(outGoingEdge);
      }
    }
    log.error("No path found");
    return new ArrayList<>();
  }
37869
protected void spawnFragment(FragmentBuilder parentBuilder, Node node, int position,
                            FragmentBuilder spawnedBuilder) {
        Trace trace = parentBuilder.getTrace();
        String id = UUID.randomUUID().toString();
        String location = null;
        String uri = null;
        String operation = null;
        String type = null; // Set to null to indicate internal

        if (!trace.getNodes().isEmpty()) {
            Node rootNode = trace.getNodes().get(0);
            uri = rootNode.getUri();
            operation = rootNode.getOperation();
        }

        // Create Producer node to represent the internal connection to the spawned fragment
        Producer producer = new Producer();
        producer.setEndpointType(type);
        producer.setUri(uri);
        producer.setOperation(operation);
        producer.getCorrelationIds().add(new CorrelationIdentifier(Scope.ControlFlow, id));

        if (node != null && node.containerNode()) {
            parentBuilder.initNode(producer);
            if (position == -1) {
                ((ContainerNode)node).getNodes().add(producer);
            } else {
                ((ContainerNode)node).getNodes().add(position, producer);
            }
        } else {
            push(location, parentBuilder, producer);
            pop(location, parentBuilder, Producer.class, uri);
        }

        // Transfer relevant details to the spawned trace and builder
        Trace spawnedTrace = spawnedBuilder.getTrace();
        spawnedTrace.setTraceId(trace.getTraceId());
        spawnedTrace.setTransaction(trace.getTransaction());

        spawnedBuilder.setLevel(parentBuilder.getLevel());

        // Create Consumer node to represent other end of internal spawn link
        Consumer consumer = new Consumer();
        consumer.setEndpointType(type);
        consumer.setUri(uri);
        consumer.setOperation(operation);
        consumer.getCorrelationIds().add(new CorrelationIdentifier(Scope.ControlFlow, id));

        push(location, spawnedBuilder, consumer);

        // Pop immediately as easier than attempting to determine end of spawned scope and
        // removing it from the stack then.
        // TODO:  Could look at moving subsequent top level nodes under this Consumer
        // at the point when the fragment is recorded
        pop(location, spawnedBuilder, Consumer.class, uri);
    }
627911
def recv_loop(stream):
    """"""
    message = recv(stream)
    while message:
        yield message
        message = recv(stream)
997315
def parallel_generate_walks(d_graph, global_walk_length, num_walks, cpu_num, sampling_strategy=None,
                            num_walks_key=None, walk_length_key=None, neighbors_key=None, probabilities_key=None,
                            first_travel_key=None, quiet=False):
    

    walks = list()



    if not quiet:
        pbar = tqdm(total=num_walks, desc='Generating walks (CPU: {})'.format(cpu_num))

    for n_walk in range(num_walks):

        # Update progress bar
        if not quiet:
            pbar.update(1)

        # Shuffle the nodes
        shuffled_nodes = list(d_graph.keys())
        random.shuffle(shuffled_nodes)

        # Start a random walk from every node
        for source in shuffled_nodes:

            # Skip nodes with specific num_walks
            if source in sampling_strategy and \
                    num_walks_key in sampling_strategy[source] and \
                    sampling_strategy[source][num_walks_key] <= n_walk:
                continue

            # Start walk
            walk = [source]

            # Calculate walk length
            if source in sampling_strategy:
                walk_length = sampling_strategy[source].get(walk_length_key, global_walk_length)
            else:
                walk_length = global_walk_length

            # Perform walk
            while len(walk) < walk_length:

                walk_options = d_graph[walk[-1]].get(neighbors_key, None)

                # Skip dead end nodes
                if not walk_options:
                    break

                if len(walk) == 1:  # For the first step
                    probabilities = d_graph[walk[-1]][first_travel_key]
                    walk_to = np.random.choice(walk_options, size=1, p=probabilities)[0]
                else:
                    probabilities = d_graph[walk[-1]][probabilities_key][walk[-2]]
                    walk_to = np.random.choice(walk_options, size=1, p=probabilities)[0]

                walk.append(walk_to)

            walk = list(map(str, walk))  # Convert all to strings

            walks.append(walk)

    if not quiet:
        pbar.close()

    return walks