External Peer object
357135
function Peer(internalPeer){
  Emitter.Target.call(this,emitter);
  
  this[rooms] = {};
  this[pids] = {};
  this[ip] = internalPeer;
  
  plugins.give('peer',this);
}
1019244
function getOnLinePeers()
{
	var arrOnlinePeers = [];
	function compare(){
		return function(a,b){
			return b['count'] - a['count'];
		}
	}

	Object.keys(assocOnlinePeers).forEach(function(curUrl){    
		arrOnlinePeers.push({peer:curUrl, count:assocOnlinePeers[curUrl]});
	})
	if(arrOnlinePeers.length === 0)
		return [];
	else
		return arrOnlinePeers.sort(compare());
}
503886
function PeerList() {
  this.map = new Map();
  this.ids = new Map();
  this.list = new List();
  this.load = null;
  this.inbound = 0;
  this.outbound = 0;
}
634624
def main(http_port, peer_name, node_name, app_id):
    
    # Create the framework
    framework = pelix.framework.create_framework(
        ('pelix.ipopo.core',
         'pelix.ipopo.waiting',
         'pelix.shell.core',
         'pelix.shell.ipopo',
         'pelix.shell.console',
         'pelix.http.basic',

         # Herald core
         'herald.core',
         'herald.directory',
         'herald.shell',

         # Herald HTTP
         'herald.transports.http.directory',
         'herald.transports.http.discovery_multicast',
         'herald.transports.http.servlet',
         'herald.transports.http.transport',

         # RPC
         'pelix.remote.dispatcher',
         'pelix.remote.registry',
         'herald.remote.discovery',
         'herald.remote.herald_xmlrpc',),
        {herald.FWPROP_NODE_UID: node_name,
         herald.FWPROP_NODE_NAME: node_name,
         herald.FWPROP_PEER_NAME: peer_name,
         herald.FWPROP_APPLICATION_ID: app_id})

    # Start everything
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate components
    with use_waiting_list(context) as ipopo:
        # ... HTTP server
        ipopo.add(pelix.http.FACTORY_HTTP_BASIC, "http-server",
                  {pelix.http.HTTP_SERVICE_PORT: http_port})

        # ... HTTP reception servlet
        ipopo.add(herald.transports.http.FACTORY_SERVLET,
                  "herald-http-servlet")

        # ... HTTP multicast discovery
        ipopo.add(herald.transports.http.FACTORY_DISCOVERY_MULTICAST,
                  "herald-http-discovery-multicast")

    # Start the framework and wait for it to stop
    framework.wait_for_stop()
633667
def require_peer(self, uuid, endpoint, public_key):
        
        return lib.zyre_require_peer(self._as_parameter_, uuid, endpoint, public_key)
889447
function getProdModules(externalModules, packagePath, dependencyGraph, forceExcludes) {
  const packageJsonPath = path.join(process.cwd(), packagePath);
  const packageJson = require(packageJsonPath);
  const prodModules = [];

  // only process the module stated in dependencies section
  if (!packageJson.dependencies) {
    return [];
  }

  // Get versions of all transient modules
  _.forEach(externalModules, module => {
    let moduleVersion = packageJson.dependencies[module.external];

    if (moduleVersion) {
      prodModules.push(`${module.external}@${moduleVersion}`);

      // Check if the module has any peer dependencies and include them too
      try {
        const modulePackagePath = path.join(
          path.dirname(path.join(process.cwd(), packagePath)),
          'node_modules',
          module.external,
          'package.json'
        );
        const peerDependencies = require(modulePackagePath).peerDependencies;
        if (!_.isEmpty(peerDependencies)) {
          this.options.verbose && this.serverless.cli.log(`Adding explicit peers for dependency ${module.external}`);
          const peerModules = getProdModules.call(this, _.map(peerDependencies, (value, key) => ({ external: key })), packagePath, dependencyGraph, forceExcludes);
          Array.prototype.push.apply(prodModules, peerModules);
        }
      } catch (e) {
        this.serverless.cli.log(`WARNING: Could not check for peer dependencies of ${module.external}`);
      }
    } else {
      if (!packageJson.devDependencies || !packageJson.devDependencies[module.external]) {
        // Add transient dependencies if they appear not in the service's dev dependencies
        const originInfo = _.get(dependencyGraph, 'dependencies', {})[module.origin] || {};
        moduleVersion = _.get(_.get(originInfo, 'dependencies', {})[module.external], 'version');
        if (!moduleVersion) {
          this.serverless.cli.log(`WARNING: Could not determine version of module ${module.external}`);
        }
        prodModules.push(moduleVersion ? `${module.external}@${moduleVersion}` : module.external);
      } else if (packageJson.devDependencies && packageJson.devDependencies[module.external] && !_.includes(forceExcludes, module.external)) {
        // To minimize the chance of breaking setups we whitelist packages available on AWS here. These are due to the previously missing check
        // most likely set in devDependencies and should not lead to an error now.
        const ignoredDevDependencies = ['aws-sdk'];

        if (!_.includes(ignoredDevDependencies, module.external)) {
          // Runtime dependency found in devDependencies but not forcefully excluded
          this.serverless.cli.log(`ERROR: Runtime dependency '${module.external}' found in devDependencies. Move it to dependencies or use forceExclude to explicitly exclude it.`);
          throw new this.serverless.classes.Error(`Serverless-webpack dependency error: ${module.external}.`);
        }

        this.options.verbose && this.serverless.cli.log(`INFO: Runtime dependency '${module.external}' found in devDependencies. It has been excluded automatically.`);
      }
    }
  });

  return prodModules;
}
1169491
@ObjectiveCName("onConversationPreLoadWithPeer:")
    public void onConversationPreLoad(@NotNull Peer peer) {
        modules.getEvents().post(new PeerChatPreload(peer));
    }
1328791
def atlas_peer_get_neighbors( my_hostport, peer_hostport, timeout=None, peer_table=None, con=None, path=None ):
    
   
    if timeout is None:
        timeout = atlas_neighbors_timeout()

    peer_list = None

    host, port = url_to_host_port( peer_hostport )
    RPC = get_rpc_client_class()
    rpc = RPC( host, port, timeout=timeout, src=my_hostport )

    # sane limits
    max_neighbors = atlas_max_neighbors()

    assert not atlas_peer_table_is_locked_by_me()
    
    try:
        peer_list = blockstack_atlas_peer_exchange( peer_hostport, my_hostport, timeout=timeout, proxy=rpc )
        if json_is_exception(peer_list):
            # fall back to legacy method 
            peer_list = blockstack_get_atlas_peers(peer_hostport, timeout=timeout, proxy=rpc)

    except (socket.timeout, socket.gaierror, socket.herror, socket.error), se:
        atlas_log_socket_error( "atlas_peer_exchange(%s)" % peer_hostport, peer_hostport, se)
        log.error("Socket error in response from '%s'" % peer_hostport)

    except Exception, e:
        if os.environ.get("BLOCKSTACK_DEBUG") == "1":
            log.exception(e)
        log.error("Failed to talk to '%s'" % peer_hostport)
   
    if peer_list is None:
        log.error("Failed to query remote peer %s" % peer_hostport)
        atlas_peer_update_health( peer_hostport, False, peer_table=peer_table )
        return None 

    if 'error' in peer_list:
        log.debug("Remote peer error: %s" % peer_list['error'])
        log.error("Remote peer error on %s" % peer_hostport)
        atlas_peer_update_health( peer_hostport, False, peer_table=peer_table )
        return None

    ret = peer_list['peers']
    atlas_peer_update_health( peer_hostport, True, peer_table=peer_table )
    return ret
622410
@ObjectiveCName("sendDocumentWithPeer:withName:withMime:withDescriptor:")
    public void sendDocument(Peer peer, String fileName, String mimeType, String descriptor) {
        sendDocument(peer, fileName, mimeType, null, descriptor);
    }
713269
function getExternals(packageInfo) {
  let externals = {
    // Hard coded externals
    'h3-js': 'h3',
    's2-geometry': 'S2'
  };
  const {peerDependencies = {}} = packageInfo;

  for (const depName in peerDependencies) {
    if (depName.startsWith('@deck.gl')) {
      // Instead of bundling the dependency, import from the global `deck` object
      externals[depName] = 'deck';
    }
  }

  if (externals['@deck.gl/core']) {
    // Do not bundle luma.gl if `core` is peer dependency
    externals = [
      externals,
      (context, request, callback) => {
        if (/^@?luma\.gl/.test(request)) {
          return callback(null, 'luma');
        }
        return callback();
      }
    ];
  }

  return externals;
}
346807
function getPeerGlobals(externals = [], bundleType) {
  const peerGlobals = {}
  externals.forEach(name => {
    if (!knownGlobals[name] && bundleType === UNIVERSAL) {
      throw new Error("Cannot build UMD without a global name for: " + name)
    }
    peerGlobals[name] = knownGlobals[name]
  })
  return peerGlobals
}
475756
def add_peer(self, peerAddr, networks=None):
        """"""
        if _debug: BTR._debug("add_peer %r networks=%r", peerAddr, networks)

        # see if this is already a peer
        if peerAddr in self.peers:
            # add the (new?) reachable networks
            if not networks:
                networks = []
            else:
                self.peers[peerAddr].extend(networks)
        else:
            if not networks:
                networks = []

            # save the networks
            self.peers[peerAddr] = networks
342261
def ppiece(self, content):
        '''
        
        '''
        piece_index, byte_begin = struct.unpack('!ii', content[0:8])

        # TODO -- figure out a better way to catch this error.
        # How is piece_index getting swapped out from under me?
        if piece_index != self.piece.index:
            return

        assert byte_begin % REQUEST_SIZE == 0
        block_begin = byte_begin / REQUEST_SIZE
        block = content[8:]
        self.piece.save(index=block_begin, bytes=block)
        if self.piece.complete:
            piece_bytes = self.piece.get_bytes()
            if self.piece.index == self.torrent.last_piece:
                piece_bytes = piece_bytes[:self.torrent.last_piece_length]
            if hashlib.sha1(piece_bytes).digest() == (self.torrent.torrent_dict
                                                      ['info']['pieces']
                                                      [20 * piece_index:20 *
                                                       piece_index + 20]):

                print 'hash matches'

                # Take care of visualizer stuff
                piece_dict = {'kind': 'piece', 'peer': self.sock.getpeername(),
                              'piece_index': piece_index}
                self.torrent.switchboard.broadcast(piece_dict)

                print ('writing piece {}. Length is '
                       '{}').format(repr(piece_bytes)[:10] + '...',
                                    len(piece_bytes))

                # Write out
                byte_index = piece_index * self.torrent.piece_length
                self.piece = self.init_piece()
                self.request_all()
                self.torrent.switchboard.write(byte_index, piece_bytes)
                self.torrent.switchboard.mark_off(piece_index)
                print self.torrent.switchboard.bitfield
                if self.torrent.switchboard.complete:
                    print '\nDownload complete\n'
                    self.reactor.is_running = False
            else:
                print "Bad data -- hash doesn't match. Discarding piece."
                self.piece = self.init_piece()
                self.request_all()
664669
function PeerOptions(options) {
  if (!(this instanceof PeerOptions))
    return new PeerOptions(options);

  this.network = Network.primary;
  this.logger = Logger.global;

  this.createSocket = tcp.createSocket;
  this.version = common.PROTOCOL_VERSION;
  this.services = common.LOCAL_SERVICES;
  this.agent = common.USER_AGENT;
  this.noRelay = false;
  this.spv = false;
  this.compact = false;
  this.headers = false;
  this.banScore = common.BAN_SCORE;

  this.getHeight = PeerOptions.getHeight;
  this.isFull = PeerOptions.isFull;
  this.hasWitness = PeerOptions.hasWitness;
  this.createNonce = PeerOptions.createNonce;
  this.hasNonce = PeerOptions.hasNonce;
  this.getRate = PeerOptions.getRate;

  if (options)
    this.fromOptions(options);
}
1191088
function getPeerInfo (peer, peerBook) {
  let peerInfo

  // Already a PeerInfo instance,
  // add to the peer book and return the latest value
  if (PeerInfo.isPeerInfo(peer)) {
    return peerBook.put(peer)
  }

  // Attempt to convert from Multiaddr instance (not string)
  if (multiaddr.isMultiaddr(peer)) {
    const peerIdB58Str = peer.getPeerId()
    try {
      peerInfo = peerBook.get(peerIdB58Str)
    } catch (err) {
      peerInfo = new PeerInfo(PeerId.createFromB58String(peerIdB58Str))
    }
    peerInfo.multiaddrs.add(peer)
    return peerInfo
  }

  // Attempt to convert from PeerId
  if (PeerId.isPeerId(peer)) {
    const peerIdB58Str = peer.toB58String()
    try {
      return peerBook.get(peerIdB58Str)
    } catch (err) {
      throw new Error(`Couldnt get PeerInfo for ${peerIdB58Str}`)
    }
  }

  throw new Error('peer type not recognized')
}
536645
def peer_store(key, value, relation_name='cluster'):
    """"""
    cluster_rels = relation_ids(relation_name)
    if len(cluster_rels) > 0:
        cluster_rid = cluster_rels[0]
        relation_set(relation_id=cluster_rid,
                     relation_settings={key: value})
    else:
        raise ValueError('Unable to detect '
                         'peer relation {}'.format(relation_name))
1203910
def get_peercred(sock):
    """"""
    buf = sock.getsockopt(_PEERCRED_LEVEL, _PEERCRED_OPTION, struct.calcsize('3i'))
    return struct.unpack('3i', buf)