Since num connections is not available, determine throughput by reading statistics
and assume the load of the peer

@param peer
@return throughput indicator
169359
protected long getNumConnections(IPeer peer) {
    if (peer == null) {
      return 0;
    }
    IStatistic stats = peer.getStatistic();

    // If no statistics are available, return zero
    if (!stats.isEnabled()) {
      if (logger.isDebugEnabled()) {
        logger.debug("Statistics for peer are disabled. Please enable statistics in client config");
      }
      return 0;
    }

    // Requests per second initiated by Local Peer + Request initiated by Remote peer
    String uri = peer.getUri() == null ? "local" : peer.getUri().toString();
    long requests = getRecord(IStatisticRecord.Counters.AppGenRequestPerSecond.name()+'.'+uri, stats)
        + getRecord(IStatisticRecord.Counters.NetGenRequestPerSecond.name()+'.'+uri, stats);

    // There are likely more requests than responses active
    long connections = Math.max(0, requests);

    if (logger.isTraceEnabled()) {
      logger.trace("Active connections for {}: {}", peer, connections);
    }

    return connections;
  }
811246
public int getNumberOfConnections() {
		int ret = 0;
		for (int i = 0; i < square.size(); i++) {
			if( edges[i] != null )
				ret++;
		}
		return ret;
	}
1272271
public int getPeerPort (String nodeName)
    {
        if (Objects.equal(_nodeName, nodeName)) {
            return _self.port;
        }
        PeerNode peer = _peers.get(nodeName);
        return (peer == null) ? -1 : peer.getPort();
    }
965609
public int getConnectionPoolSize(String host, int port) {
        RequestBuilder req = new RequestBuilder();
        req.host = host;
        req.port = port;
        return _getPoolSize(req);
    }
217211
private void notifyConnected(Peer peer) {
		for(Listener listener : new HashSet<>(listeners)) {
			listener.onConnected(peer);
		}
	}
152276
public int getAssignedNumWorkers(TopologyDetails topology) {
        SchedulerAssignment assignment = this.getAssignmentById(topology.getId());
        if (assignment == null) {
            return 0;
        }

        Set<WorkerSlot> slots = new HashSet<>();
        slots.addAll(assignment.getExecutorToSlot().values());

        return slots.size();
    }
416610
@Nullable
    @ObjectiveCName("loadDraftWithPeer:")
    public String loadDraft(Peer peer) {
        return modules.getMessagesModule().loadDraft(peer);
    }
109545
private synchronized boolean addPeer(final PeerInfo peer) {

		final String uuid = peer.getUuid();

		if (!peers.containsKey(uuid)) {

			peers.put(uuid, peer);

			peer.setLastSeen(System.currentTimeMillis());
			onAddPeer(peer);

			return true;
		}

		// not added
		return false;
	}
900627
public synchronized ConMgrStats getStats ()
    {
        // fill in our snapshot values
        _stats.connectionCount = _connections.size();
        _stats.handlerCount = _handlers.size();
        _stats.deathQueueSize = _deathq.size();
        _stats.outQueueSize = _outq.size();
        if (_oflowqs.size() > 0) {
            _stats.overQueueSize = 0;
            for (OverflowQueue oq : _oflowqs.values()) {
                _stats.overQueueSize += oq.size();
            }
        }
        return _stats.clone();
    }
660356
def _monitor_for_zero_connected_peers(self):
        
        if len(self.Peers) == 0 and len(self.connection_queue) == 0:
            if self.peer_zero_count > 2:
                logger.debug("Peer count 0 exceeded max retries threshold, restarting...")
                self.Restart()
            else:
                logger.debug(
                    f"Peer count is 0, allow for retries or queued connections to be established {self.peer_zero_count}")
                self.peer_zero_count += 1
908773
public SlaveConnectionInfo slaveConnectionInfo() {
        if (isMaster())
            throw new IllegalStateException("Unable to determine slave connection info. This is a master node");
        return SlaveConnectionInfo.builder().connectionUrl(subscriber.connectionUrl()).masterUrl(publishMasterUrl)
                        .build();

    }
746841
public static int getMostCommonChainHeight(final List<Peer> peers) {
        if (peers.isEmpty())
            return 0;
        List<Integer> heights = new ArrayList<>(peers.size());
        for (Peer peer : peers) heights.add((int) peer.getBestHeight());
        return Utils.maxOfMostFreq(heights);
    }

    /**
     * Given a list of Peers, return a Peer to be used as the download peer. If you don't want PeerGroup to manage
     * download peer statuses for you, just override this and always return null.
     */
    @Nullable
    protected Peer selectDownloadPeer(List<Peer> peers) {
        // Characteristics to select for in order of importance:
        //  - Chain height is reasonable (majority of nodes)
        //  - High enough protocol version for the features we want (but we'll settle for less)
        //  - Randomly, to try and spread the load.
        if (peers.isEmpty())
            return null;
        // Make sure we don't select a peer that is behind/synchronizing itself.
        int mostCommonChainHeight = getMostCommonChainHeight(peers);
        List<Peer> candidates = new ArrayList<>();
        for (Peer peer : peers) {
            if (!peer.getPeerVersionMessage().hasBlockChain())
                continue;
            if (peer.getBestHeight() < mostCommonChainHeight)
                continue;
            candidates.add(peer);
        }
        // Of the candidates, find the peers that meet the minimum protocol version we want to target. We could select
        // the highest version we've seen on the assumption that newer versions are always better but we don't want to
        // zap peers if they upgrade early. If we can't find any peers that have our preferred protocol version or
        // better then we'll settle for the highest we found instead.
        int highestVersion = 0, preferredVersion = 0;
        // If/when PREFERRED_VERSION is not equal to vMinRequiredProtocolVersion, reenable the last test in PeerGroupTest.downloadPeerSelection
        final int PREFERRED_VERSION = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.BLOOM_FILTER);
        for (Peer peer : candidates) {
            highestVersion = Math.max(peer.getPeerVersionMessage().clientVersion, highestVersion);
            preferredVersion = Math.min(highestVersion, PREFERRED_VERSION);
        }
        ArrayList<Peer> candidates2 = new ArrayList<>(candidates.size());
        for (Peer peer : candidates) {
            if (peer.getPeerVersionMessage().clientVersion >= preferredVersion) {
                candidates2.add(peer);
            }
        }
        if (candidates2.isEmpty())
            return null;
        int index = (int) (Math.random() * candidates2.size());
        return candidates2.get(index);
    }

    /**
     * Returns the currently selected download peer. Bear in mind that it may have changed as soon as this method
     * returns. Can return null if no peer was selected.
     */
    public Peer getDownloadPeer() {
        lock.lock();
        try {
            return downloadPeer;
        } finally {
            lock.unlock();
        }
    }

    /**
     * Returns the maximum number of {@link Peer}s to discover. This maximum is checked after
     * each {@link PeerDiscovery} so this max number can be surpassed.
     * @return the maximum number of peers to discover
     */
    public int getMaxPeersToDiscoverCount() {
        return vMaxPeersToDiscoverCount;
    }

    /**
     * Sets the maximum number of {@link Peer}s to discover. This maximum is checked after
     * each {@link PeerDiscovery} so this max number can be surpassed.
     * @param maxPeersToDiscoverCount the maximum number of peers to discover
     */
    public void setMaxPeersToDiscoverCount(int maxPeersToDiscoverCount) {
        this.vMaxPeersToDiscoverCount = maxPeersToDiscoverCount;
    }

    /** See {@link #setUseLocalhostPeerWhenPossible(boolean)} */
    public boolean getUseLocalhostPeerWhenPossible() {
        lock.lock();
        try {
            return useLocalhostPeerWhenPossible;
        } finally {
            lock.unlock();
        }
    }

    /**
     * When true (the default), PeerGroup will attempt to connect to a Bitcoin node running on localhost before
     * attempting to use the P2P network. If successful, only localhost will be used. This makes for a simple
     * and easy way for a user to upgrade a bitcoinj based app running in SPV mode to fully validating security.
     */
    public void setUseLocalhostPeerWhenPossible(boolean useLocalhostPeerWhenPossible) {
        lock.lock();
        try {
            this.useLocalhostPeerWhenPossible = useLocalhostPeerWhenPossible;
        } finally {
            lock.unlock();
        }
    }

    public boolean isRunning() {
        return vRunning;
    }

    /**
     * Can be used to disable Bloom filtering entirely, even in SPV mode. You are very unlikely to need this, it is
     * an optimisation for rare cases when full validation is not required but it's still more efficient to download
     * full blocks than filtered blocks.
     */
    public void setBloomFilteringEnabled(boolean bloomFilteringEnabled) {
        this.vBloomFilteringEnabled = bloomFilteringEnabled;
    }

    /** Returns whether the Bloom filtering protocol optimisation is in use: defaults to true. */
    public boolean isBloomFilteringEnabled() {
        return vBloomFilteringEnabled;
    }
1047302
public List<Peer> getSomePeers(Peer peer) {
    List<Peer> peers = new LinkedList<Peer>();

    // Extract answerPeers random peers
    List<TrackedPeer> candidates = new LinkedList<TrackedPeer>(this.peers.values());
    Collections.shuffle(candidates);

    int count = 0;
    for (TrackedPeer candidate : candidates) {
      // Don't include the requesting peer in the answer.
      if (peer != null && peer.looksLike(candidate)) {
        continue;
      }

      // Only serve at most ANSWER_NUM_PEERS peers
      if (count++ > this.answerPeers) {
        break;
      }

      peers.add(candidate);
    }

    return peers;
  }
910657
public Client getPeerClient (String nodeName)
    {
        PeerNode peer = _peers.get(nodeName);
        return (peer == null) ? null : peer.getClient();
    }
377903
def client_for(connection)
    # skip if an indirect node type or local
    return nil, nil if self.indirect? || self.node_type == :local

    begin
      return Socket.unpack_sockaddr_in(connection.get_peername)
    rescue Exception=>e
    end

    return nil, nil
  end
243113
def _connected(cm, nodes, connection):
    """"""
    if nodes is not None:
        cm = cm[np.ix_(nodes, nodes)]

    num_components, _ = connected_components(cm, connection=connection)
    return num_components < 2
1086068
final public int getConnectionCount() {
		int total = 0;
		synchronized(poolLock) {
			for(PooledConnection<C> pooledConnection : allConnections) {
				if(pooledConnection.connection!=null) total++;
			}
		}
		return total;
	}