Returns number of discovered peers.
197100
protected int discoverPeers() {
        // Don't hold the lock whilst doing peer discovery: it can take a long time and cause high API latency.
        checkState(!lock.isHeldByCurrentThread());
        int maxPeersToDiscoverCount = this.vMaxPeersToDiscoverCount;
        long peerDiscoveryTimeoutMillis = this.vPeerDiscoveryTimeoutMillis;
        final Stopwatch watch = Stopwatch.createStarted();
        final List<PeerAddress> addressList = Lists.newLinkedList();
        for (PeerDiscovery peerDiscovery : peerDiscoverers /* COW */) {
            InetSocketAddress[] addresses;
            try {
                addresses = peerDiscovery.getPeers(requiredServices, peerDiscoveryTimeoutMillis, TimeUnit.MILLISECONDS);
            } catch (PeerDiscoveryException e) {
                log.warn(e.getMessage());
                continue;
            }
            for (InetSocketAddress address : addresses) addressList.add(new PeerAddress(params, address));
            if (addressList.size() >= maxPeersToDiscoverCount) break;
        }
        if (!addressList.isEmpty()) {
            for (PeerAddress address : addressList) {
                addInactive(address);
            }
            final ImmutableSet<PeerAddress> peersDiscoveredSet = ImmutableSet.copyOf(addressList);
            for (final ListenerRegistration<PeerDiscoveredEventListener> registration : peerDiscoveredEventListeners /* COW */) {
                registration.executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        registration.listener.onPeersDiscovered(peersDiscoveredSet);
                    }
                });
            }
        }
        watch.stop();
        log.info("Peer discovery took {} and returned {} items", watch, addressList.size());
        return addressList.size();
    }
1337386
def peer_retrieve(key, relation_name='cluster'):
    """"""
    cluster_rels = relation_ids(relation_name)
    if len(cluster_rels) > 0:
        cluster_rid = cluster_rels[0]
        return relation_get(attribute=key, rid=cluster_rid,
                            unit=local_unit())
    else:
        raise ValueError('Unable to detect'
                         'peer relation {}'.format(relation_name))
96656
def discover(*nodes)
      nodes.flatten.compact.each do |peer|
        node = Node.new(peer, options)
        node.credentials.merge!(@credentials)
        peers.push(node) unless peers.include?(node)
      end
    end
1110785
def discover_details(self):
        '''
        
        '''
        if (self.root_node == None):
            return

        if (self.verbose > 0):
            print('\nCollecting node details...')

        ni = 0
        for n in self.nodes:
            ni = ni + 1

            indicator = '+'
            if (n.snmpobj.success == 0):
                indicator = '!'

            if (self.verbose > 0):
                sys.stdout.write('[%i/%i]%s %s (%s)' % (ni, len(self.nodes), indicator, n.name, n.snmpobj._ip))
                sys.stdout.flush()

            # set what details to discover for this node
            n.opts.get_router        = True
            n.opts.get_ospf_id       = True
            n.opts.get_bgp_las       = True
            n.opts.get_hsrp_pri      = True
            n.opts.get_hsrp_vip      = True
            n.opts.get_serial        = True 
            n.opts.get_stack         = True
            n.opts.get_stack_details = self.config.diagram.get_stack_members
            n.opts.get_vss           = True
            n.opts.get_vss_details   = self.config.diagram.get_vss_members
            n.opts.get_svi           = True
            n.opts.get_lo            = True
            n.opts.get_vpc           = True
            n.opts.get_ios           = True
            n.opts.get_plat          = True

            start = timer()
            n.query_node()
            end = timer()
            if (self.verbose > 0):
                print(' %.2f sec' % (end - start))

        # There is some back fill information we can populate now that
        # we know all there is to know.
        if (self.verbose > 0):
            print('\nBack filling node details...')

        for n in self.nodes:
            # Find and link VPC nodes together for easy reference later
            if ((n.vpc_domain != None) & (n.vpc_peerlink_node == None)):
                for link in n.links:
                    if ((link.local_port == n.vpc_peerlink_if) | (link.local_lag == n.vpc_peerlink_if)):
                        n.vpc_peerlink_node         = link.node
                        link.node.vpc_peerlink_node = n
                        break
966840
@ObjectiveCName("findPeersWithQuery:")
    public Command<List<PeerSearchEntity>> findPeers(String query) {
        return callback -> modules.getSearchModule().findPeers(query)
                .then(v -> callback.onResult(v))
                .failure(e -> callback.onError(e));
    }
749036
def __get_known_node(self, ip, host):
        '''
        
        '''
        # already known by IP ?
        for ex in self.nodes:
            for exip in ex.ip:
                if (exip == '0.0.0.0'):
                    continue
                if (exip == ip):
                    return (ex, 0)

        # already known by HOST ?
        node = self.__get_known_node_by_host(host)
        if (node != None):
            # node already known
            if (ip not in node.ip):
                node.ip.append(ip)
                return (node, 1)
            return (node, 0)

        return (None, 0)
1014499
async def _nodes_found(self, responses):
        
        toremove = []
        for peerid, response in responses.items():
            response = RPCFindResponse(response)
            if not response.happened():
                toremove.append(peerid)
            else:
                self.nearest.push(response.get_node_list())
        self.nearest.remove(toremove)

        if self.nearest.have_contacted_all():
            return list(self.nearest)
        return await self.find()
859391
public int seeders() {
    int count = 0;
    for (TrackedPeer peer : this.peers.values()) {
      if (peer.isCompleted()) {
        count++;
      }
    }
    return count;
  }
170137
def total_msg_recv(self):
        
        return (self.get_count(PeerCounterNames.RECV_UPDATES) +
                self.get_count(PeerCounterNames.RECV_REFRESH) +
                self.get_count(PeerCounterNames.RECV_NOTIFICATION))
1155659
def get_ntp_stats(self):
        """"""
        # NTP Peers does not have XML RPC defined
        # thus we need to retrieve raw text and parse...
        # :(

        ntp_stats = []

        REGEX = (
            '^\s?(\+|\*|x|-)?([a-zA-Z0-9\.+-:]+)'
            '\s+([a-zA-Z0-9\.]+)\s+([0-9]{1,2})'
            '\s+(-|u)\s+([0-9h-]+)\s+([0-9]+)'
            '\s+([0-9]+)\s+([0-9\.]+)\s+([0-9\.-]+)'
            '\s+([0-9\.]+)\s?$'
        )

        ntp_assoc_output = self.device.cli('show ntp associations no-resolve')
        ntp_assoc_output_lines = ntp_assoc_output.splitlines()

        for ntp_assoc_output_line in ntp_assoc_output_lines[3:]:  # except last line
            line_search = re.search(REGEX, ntp_assoc_output_line, re.I)
            if not line_search:
                continue  # pattern not found
            line_groups = line_search.groups()
            try:
                ntp_stats.append({
                    'remote': napalm_base.helpers.ip(line_groups[1]),
                    'synchronized': (line_groups[0] == '*'),
                    'referenceid': py23_compat.text_type(line_groups[2]),
                    'stratum': int(line_groups[3]),
                    'type': py23_compat.text_type(line_groups[4]),
                    'when': py23_compat.text_type(line_groups[5]),
                    'hostpoll': int(line_groups[6]),
                    'reachability': int(line_groups[7]),
                    'delay': float(line_groups[8]),
                    'offset': float(line_groups[9]),
                    'jitter': float(line_groups[10])
                })
            except Exception:
                continue  # jump to next line

        return ntp_stats
741493
def publish_receiver_count(self, service, routing_id):
        '''
        '''
        peers = len(list(self._dispatcher.find_peer_routes(
            const.MSG_TYPE_PUBLISH, service, routing_id)))
        if self._dispatcher.locally_handles(const.MSG_TYPE_PUBLISH,
                service, routing_id):
            return peers + 1
        return peers
1222515
function sumOnLinePeers() {
	let nowTime = Date.now();
	assocOnlinePeers = {};
	Object.keys(assocAllOutBoundPeers).forEach(function(curUrl){    
		var curPeers = assocAllOutBoundPeers[curUrl];   
		if(nowTime - parseInt(curPeers.time) < 3 * 60 * 1000){
			for (var j=0; j<curPeers.peers.length; j++){
                if(assocOnlinePeers[curPeers.peers[j]]) 
					assocOnlinePeers[curPeers.peers[j]]++;
				else
					assocOnlinePeers[curPeers.peers[j]] = 1;
            }
		}       
    }); 
}
985224
def canonical_new_peer_list( self, peers_to_add ):
        
        new_peers = list(set(self.new_peers + peers_to_add))
        random.shuffle( new_peers )
        
        # canonicalize
        tmp = []
        for peer in new_peers:
            tmp.append( self.canonical_peer(peer) )

        new_peers = tmp

        # don't talk to myself
        if self.my_hostport in new_peers:
            new_peers.remove(self.my_hostport)

        return new_peers
484726
def getPeersFromTracker(torrentData, infoHash)
      addPeer = Proc.new do |trackerPeer|
        peer = Peer.new(trackerPeer)
        peer.infoHash = infoHash
        torrentData.peers.add peer
        true
      end

      classifiedPeers = nil
      replaceDisconnectedPeer = Proc.new do |trackerPeer|
        classifiedPeers = ClassifiedPeers.new(torrentData.peers.all) if ! classifiedPeers
  
        if classifiedPeers.disconnectedPeers.size > 0
          torrentData.peers.delete classifiedPeers.disconnectedPeers.pop
          addPeer.call trackerPeer
          true
        else
          false
        end
      end

      trackerclient = torrentData.trackerClient 
    
      addProc = addPeer
      flipped = false
      trackerclient.peers.each do |p|
        if ! flipped && torrentData.peers.size >= @maxPeerCount
          addProc = replaceDisconnectedPeer
          flipped = true
        end
      
        # Don't treat ourself as a peer.
        next if p.id && p.id == trackerclient.peerId
            
        if ! torrentData.peers.findByAddr(p.ip, p.port)
          @logger.debug "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Adding tracker peer #{p} to peers list"
          break if ! addProc.call(p)
        end
      end
    end
242479
public Collection<String> getPeerNames() {
        if (peers == null) {
            return Collections.EMPTY_SET;
        } else {
            return new HashSet<>(peers.keySet());
        }
    }
1203412
def peers(cls):
        """"""
        contentType = ContentType.objects.get_for_model(cls)
        return cls.objects.filter(content_type=contentType)
636771
def getPeer(self, url):
        
        peers = filter(lambda x: x.getUrl() == url, self.getPeers())
        if len(peers) == 0:
            raise exceptions.PeerNotFoundException(url)
        return peers[0]