Create all missing peers
546341
private static LeftTuple insertPeerLeftTuple(LeftTuple lt, LeftTupleSinkNode node, InternalWorkingMemory wm) {
        LeftInputAdapterNode.LiaNodeMemory liaMem = null;
        if ( node.getLeftTupleSource().getType() == NodeTypeEnums.LeftInputAdapterNode ) {
            liaMem = wm.getNodeMemory(((LeftInputAdapterNode) node.getLeftTupleSource()));
        }

        LeftTuple peer = node.createPeer(lt);
        Memory memory = wm.getNodeMemories().peekNodeMemory(node);
        if (memory == null || memory.getSegmentMemory() == null) {
            throw new IllegalStateException("Defensive Programming: this should not be possilbe, as the addRule code should init child segments if they are needed ");
        }

        if ( liaMem == null) {
            memory.getSegmentMemory().getStagedLeftTuples().addInsert(peer);
        } else {
            // If parent is Lian, then this must be called, so that any linking or unlinking can be done.
            LeftInputAdapterNode.doInsertSegmentMemory(wm, true, liaMem, memory.getSegmentMemory(), peer, node.getLeftTupleSource().isStreamMode());
        }

        return peer;
    }
267666
def atlasdb_get_random_peer( con=None, path=None ):
    
    ret = {}

    with AtlasDBOpen(con=con, path=path) as dbcon:

        num_peers = atlasdb_num_peers( con=con, path=path )
        if num_peers is None or num_peers == 0:
            # no peers
            ret['peer_hostport'] = None

        else:
            r = random.randint(1, num_peers)

            sql = "SELECT * FROM peers WHERE peer_index = ?;"
            args = (r,)

            cur = dbcon.cursor()
            res = atlasdb_query_execute( cur, sql, args )

            ret = {'peer_hostport': None}
            for row in res:
                ret.update( row )
                break


    return ret['peer_hostport']
242479
public Collection<String> getPeerNames() {
        if (peers == null) {
            return Collections.EMPTY_SET;
        } else {
            return new HashSet<>(peers.keySet());
        }
    }
1305660
def create_all_recommendations(self, cores, ip_views=False):
        """"""
        global _store
        _store = self.store
        _create_all_recommendations(cores, ip_views, self.config)
39589
def getPeers(self):
        '''
            
        '''
        parentNode = self.parentNode
        # If no parent, no peers
        if not parentNode:
            return None

        peers = parentNode.children

        # Otherwise, get all children of parent excluding this node
        return TagCollection([peer for peer in peers if peer is not self])
282144
def peers(self):
        ""
        return [addr for (addr, peer) in self._dispatcher.peers.items()
                if peer.up]
942622
function uploadMissing(missing, request, host, log, fn) {
  var batch = new Batch();

  missing.forEach(function(file) {
    batch.push(uploadFile(file, request, host));
  });

  batch.on('progress', function() {
    log('.');
  });

  batch.end(function(err, res) {
    log(' done\n');
    fn(err, res);
  });
}
768106
def create_missing(self):
        
        super(ProvisioningTemplate, self).create_missing()
        if (getattr(self, 'snippet', None) is False and
                not hasattr(self, 'template_kind')):
            self.template_kind = TemplateKind(self._server_config, id=1)
887982
def create_missing_perms(self):
        """"""
        from superset import db
        from superset.models import core as models

        logging.info(
            'Fetching a set of all perms to lookup which ones are missing')
        all_pvs = set()
        for pv in self.get_session.query(self.permissionview_model).all():
            if pv.permission and pv.view_menu:
                all_pvs.add((pv.permission.name, pv.view_menu.name))

        def merge_pv(view_menu, perm):
            """Create permission view menu only if it doesn't exist"""
            if view_menu and perm and (view_menu, perm) not in all_pvs:
                self.merge_perm(view_menu, perm)

        logging.info('Creating missing datasource permissions.')
        datasources = ConnectorRegistry.get_all_datasources(db.session)
        for datasource in datasources:
            merge_pv('datasource_access', datasource.get_perm())
            merge_pv('schema_access', datasource.schema_perm)

        logging.info('Creating missing database permissions.')
        databases = db.session.query(models.Database).all()
        for database in databases:
            merge_pv('database_access', database.perm)

        logging.info('Creating missing metrics permissions')
        metrics = []
        for datasource_class in ConnectorRegistry.sources.values():
            metrics += list(db.session.query(datasource_class.metric_class).all())

        for metric in metrics:
            if metric.is_restricted:
                merge_pv('metric_access', metric.perm)
917025
def refresh_peers(node, &block)
      node.peers.each do |node|
        if node.address.resolved
          block.call(node) unless seeds.include?(node)
          peers.push(node) unless peers.include?(node)
        end
      end
    end
1182385
def update_existing_peers( self, num_to_remove, peer_table=None, con=None, path=None ):
        
        
        if path is None:
            path = self.atlasdb_path

        # remove peers that are too old
        if self.last_clean_time + atlas_peer_clean_interval() < time_now():
            # remove stale peers
            log.debug("%s: revalidate old peers" % self.my_hostport)
            atlas_revalidate_peers( con=con, path=path, peer_table=peer_table )
            self.last_clean_time = time_now()

        removed = self.remove_unhealthy_peers( num_to_remove, con=con, path=path, peer_table=peer_table )

        # if they're also in the new set, remove them there too
        for peer in removed:
            if peer in self.new_peers:
                self.new_peers.remove(peer)

        return len(removed)
887421
function getOrCreatePeer(id)
    {
        if(scope.peers[id])
        {
            return scope.peers[id];
        }
        return createPeerInstance(id);
    }
31005
protected function createMissingSitesNode()
    {
        $this->dispatch(self::EVENT_NOTICE, sprintf('Checking for "%s" node ...', SiteService::SITES_ROOT_PATH));
        $rootNode = $this->contextFactory->create()->getRootNode();
        // We fetch the workspace to be sure it's known to the persistence manager and persist all
        // so the workspace and site node are persisted before we import any nodes to it.
        $rootNode->getContext()->getWorkspace();
        $this->persistenceManager->persistAll();
        $sitesNode = $rootNode->getNode(SiteService::SITES_ROOT_PATH);
        if ($sitesNode === null) {
            $taskDescription = sprintf('Create missing site node "<i>%s</i>"', SiteService::SITES_ROOT_PATH);
            $taskClosure = function () use ($rootNode) {
                $rootNode->createNode(NodePaths::getNodeNameFromPath(SiteService::SITES_ROOT_PATH));
                $this->persistenceManager->persistAll();
            };
            $this->dispatch(self::EVENT_TASK, $taskDescription, $taskClosure);
        }
    }
313213
public static HTTPAnnounceResponseMessage craft(int interval,
                                                  int complete, int incomplete,
                                                  List<Peer> peers, String hexInfoHash) throws IOException, UnsupportedEncodingException {
    Map<String, BEValue> response = new HashMap<String, BEValue>();
    response.put("interval", new BEValue(interval));
    response.put("complete", new BEValue(complete));
    response.put("incomplete", new BEValue(incomplete));
    if (hexInfoHash != null) {
      response.put("torrentIdentifier", new BEValue(hexInfoHash));
    }

    ByteBuffer data = ByteBuffer.allocate(peers.size() * 6);
    for (Peer peer : peers) {
      byte[] ip = peer.getRawIp();
      if (ip == null || ip.length != 4) {
        continue;
      }
      data.put(ip);
      data.putShort((short) peer.getPort());
    }
    response.put("peers", new BEValue(Arrays.copyOf(data.array(), data.position())));

    return new HTTPAnnounceResponseMessage(
            BEncoder.bencode(response),
            interval, complete, incomplete, peers, hexInfoHash);
  }
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;
            }
		}       
    }); 
}
307774
def on_peer_down(self, peer):
        
        LOG.debug('Cleaning obsolete paths whose source/version: %s/%s',
                  peer.ip_address, peer.version_num)
        # Launch clean-up for each global tables.
        self._table_manager.clean_stale_routes(peer)
223352
def addPeer(self):
        
        self._openRepo()
        try:
            peer = peers.Peer(
                self._args.url, json.loads(self._args.attributes))
        except exceptions.BadUrlException:
            raise exceptions.RepoManagerException("The URL for the peer was "
                                                  "malformed.")
        except ValueError as e:
            raise exceptions.RepoManagerException(
                "The attributes message "
                "was malformed. {}".format(e))
        self._updateRepo(self._repo.insertPeer, peer)