void llvm::TripCountProfiler::saveTripCount(std::set<BasicBlock*> BBs, AllocaInst* tripCountPtr, Value* estimatedTripCount,  BasicBlock* loopHeader, int LoopClass) {


    for(std::set<BasicBlock*>::iterator it = BBs.begin(), end = BBs.end(); it != end; it++) {

        BasicBlock* BB = *it;

        IRBuilder<> Builder(BB->getFirstInsertionPt());

        ConstantInt* loopIdentifier = ConstantInt::get(Type::getInt64Ty(*context), (int64_t)loopHeader);
        ConstantInt* loopClass = ConstantInt::get(Type::getInt32Ty(*context), (int64_t)LoopClass);


        //Value* stderr = Builder.CreateAlignedLoad(GVstderr, 4);
        Value* tripCount = Builder.CreateAlignedLoad(tripCountPtr, 4);

        std::vector<Value*> args;
        args.push_back(loopIdentifier);
        args.push_back(tripCount);
        args.push_back(estimatedTripCount);
        args.push_back(loopClass);
        llvm::ArrayRef<llvm::Value *> arrayArgs(args);
        Builder.CreateCall(collectLoopData, arrayArgs, "");


        int count = 0;
        for(pred_iterator pred = pred_begin(BB); pred != pred_end(BB); pred++) {
            count ++;
        }

    }

}
 void 
 Intrepid2FieldPattern::
 buildSubcellClosure(const shards::CellTopology & cellTopo,unsigned dim,unsigned subCell,
                     std::set<std::pair<unsigned,unsigned> > & closure)
 {
   switch(dim) {
   case 0:
     closure.insert(std::make_pair(0,subCell));
     break;
   case 1:
     closure.insert(std::make_pair(0,cellTopo.getNodeMap(dim,subCell,0)));
     closure.insert(std::make_pair(0,cellTopo.getNodeMap(dim,subCell,1)));
     closure.insert(std::make_pair(1,subCell));
     break;
   case 2:
     {
       unsigned cnt = (shards::CellTopology(cellTopo.getCellTopologyData(dim,subCell))).getSubcellCount(dim-1);
       for(unsigned i=0;i<cnt;i++) {
         int edge = mapCellFaceEdge(cellTopo.getCellTopologyData(),subCell,i);
         buildSubcellClosure(cellTopo,dim-1,edge,closure);
       }
       closure.insert(std::make_pair(2,subCell));
     }
     break;
   default:
     // beyond a two dimension surface this thing crashes!
     TEUCHOS_ASSERT(false);
   };
 }
Example #3
0
//funciones temporales para simular la llegada de datos
//cuando se definan sockets y extracción desde fichero entonces se separarán a su modulo
void recibirEstaciones(std::set<Station>& estaciones){
        //datos que se sacarán del fichero que llegue, esto es a fuego temporalmente
        estaciones.insert(Station("0x0000", "0x0010", 35.222, -13.332, -1));
        estaciones.insert(Station("0x0001", "0x0011", 35.675, -10.322, -1));
        estaciones.insert(Station("0x0002", "0x0012", 36.232, -7.543, -1));
        estaciones.insert(Station("0x0003", "0x0013", 37.323, -5.887,-1));
}
Example #4
0
	void StoreHashMap(std::string filename) {
		if (filename.empty())
			filename = hashmapFileName;

		UpdateHashMap();
		if (hashMap.empty()) {
			return;
		}

		FILE *file = File::OpenCFile(filename, "wt");
		if (!file) {
			WARN_LOG(LOADER, "Could not store hash map: %s", filename.c_str());
			return;
		}

		for (auto it = hashMap.begin(), end = hashMap.end(); it != end; ++it) {
			const HashMapFunc &mf = *it;
			if (!mf.hardcoded) {
				if (fprintf(file, "%016llx:%d = %s\n", mf.hash, mf.size, mf.name) <= 0) {
					WARN_LOG(LOADER, "Could not store hash map: %s", filename.c_str());
					break;
				}
			}
		}
		fclose(file);
	}
Example #5
0
    void way(const osmium::Way& way) {
        // detect a new way
        if (current_way_id != 0 && current_way_id != way.positive_id()) {
            write_way_extra_nodes();
            current_way_nodes.clear();
        }
        current_way_id = way.positive_id();

        if (debug) {
            std::cerr << "softcut way " << way.positive_id() << " v" << way.version() << "\n";
        }

        for (const auto& node_ref : way.nodes()) {
            current_way_nodes.insert(node_ref.positive_ref());
        }

        for (const auto& extract : info->extracts) {
            for (const auto& node_ref : way.nodes()) {
                if (extract->node_tracker.get(node_ref.positive_ref())) {
                    if (debug) {
                        std::cerr << "way has a node (" << node_ref.positive_ref() << ") inside extract, recording in way_tracker\n";
                    }
                    extract->way_tracker.set(way.positive_id());
                    break;
                }
            }
        }
    }
Example #6
0
void printProcsRecursive(Function *function, int indent, OStream &f, std::set<Function *> &seen)
{
    const bool firsttime = (seen.find(function) == seen.end());

    if (firsttime) {
        seen.insert(function);
    }

    for (int i = 0; i < indent; i++) {
        f << "    ";
    }

    if (!function->isLib() && firsttime) { // seen lib proc
        f << function->getEntryAddress();
        f << " __nodecode __incomplete void " << function->getName() << "();\n";

        UserProc *proc = static_cast<UserProc *>(function);

        for (Function *callee : proc->getCallees()) {
            printProcsRecursive(callee, indent + 1, f, seen);
        }

        for (int i = 0; i < indent; i++) {
            f << "     ";
        }

        f << "// End of " << function->getName() << "\n";
    }
    else {
        f << "// " << function->getName() << "();\n";
    }
}
bool is_string_type(const std::string& type)
{
    //The string types are CHAR, VARCHAR, BINARY, VARBINARY, BLOB, TEXT, ENUM, and SET
    static const std::set<std::string> chartypes = boost::assign::list_of(std::string("char"))("varchar")("binary")("varbinary")("blob")("text")("enum")("set");
    std::string searchtype = type.substr(0,type.find("("));
    return chartypes.find(searchtype) != chartypes.end();
};
Example #8
0
//-----------------------------------------------------------------------------
// data <- xsheet
void TKeyframeData::setKeyframes(std::set<Position> positions, TXsheet *xsh)
{
	if (positions.empty())
		return;

	TStageObjectId cameraId = xsh->getStageObjectTree()->getCurrentCameraId();

	std::set<Position>::iterator it = positions.begin();
	int r0 = it->first;
	int c0 = it->second;
	for (++it; it != positions.end(); ++it) {
		r0 = std::min(r0, it->first);
		c0 = std::min(c0, it->second);
	}

	for (it = positions.begin(); it != positions.end(); ++it) {
		int row = it->first;
		int col = it->second;
		TStageObject *pegbar = xsh->getStageObject(col >= 0 ? TStageObjectId::ColumnId(col) : cameraId);
		assert(pegbar);
		m_isPegbarsCycleEnabled[col] = pegbar->isCycleEnabled();
		if (pegbar->isKeyframe(row)) {
			Position p(row - r0, col - c0);
			TStageObject::Keyframe k = pegbar->getKeyframe(row);
			m_keyData[p] = k;
		}
	}
}
Example #9
0
void Territory::calculateDistances(Territory* newTerritory, std::list<Territory*> &frontier, std::set<Territory*> &visited,
                                   int depthOfFrontier){
    Territory* expandingTerritory;
    std::list<Territory*> newFrontier;

    while(!frontier.empty()){
        expandingTerritory = frontier.front();
        frontier.pop_front();

        if(visited.count(expandingTerritory) == 0){
            visited.insert(expandingTerritory);
            distanceArr[territoryToDistanceIndex[newTerritory]][territoryToDistanceIndex[expandingTerritory]]
                    = depthOfFrontier;

            for(std::list<Territory*>::iterator iter = expandingTerritory->adjacentTerritories->begin();
                iter != expandingTerritory->adjacentTerritories->end(); iter++){
                newFrontier.push_back(*iter);
            }
        }

        if(newFrontier.empty()){
            return;
        }
        calculateDistances(newTerritory, newFrontier, visited, depthOfFrontier + 1);
    }
}
Example #10
0
bool formLegalRelaxedPhylipName(const std::string & origName, const NxsString & numericExtension, const std::set<std::string> & used, std::string & toReturn)
{
	toReturn = origName;
	toReturn.append(numericExtension.c_str());
	const std::string cap = NxsString::get_upper(toReturn);
	return (used.find(cap) == used.end());
}
void UDTClient::TrySendMsg(const std::set<UDTSOCKET>& writefds)
{
    if (writefds.find(sock_) == writefds.end())
    {
        //std::cout << "canot write" << std::endl;
        return;
    }

    //std::cout << "can write" << std::endl;

    while (!send_msg_buff_.empty())
    {
        msg_ptr_t msg = send_msg_buff_.front();

        const int send_ret = DoSendOneMsg(*msg);
        switch (send_ret)
        {
            case 0:
                return; // try send_at_next_epoll_return
            case -1:
                return; // udt_running_ = 0;
            case 1:
                send_msg_buff_.pop();
                continue;
            default:
                udt_running_ = 0;
                return;
        }
    }
}
void AbstractBoundaryConditionsContainer<ELEMENT_DIM,SPACE_DIM,PROBLEM_DIM>::DeleteDirichletBoundaryConditions(std::set<const AbstractBoundaryCondition<SPACE_DIM>*> alreadyDeletedConditions)
{
    for (unsigned i=0; i<PROBLEM_DIM; i++)
    {
        if (mpDirichletMap[i])
        {
            mDirichIterator = mpDirichletMap[i]->begin();
            while (mDirichIterator != mpDirichletMap[i]->end() )
            {
                if (alreadyDeletedConditions.count(mDirichIterator->second) == 0)
                {
                    alreadyDeletedConditions.insert(mDirichIterator->second);
                    if (mDeleteConditions)
                    {
                        delete mDirichIterator->second;
                    }
                }
                mDirichIterator++;
            }

            delete(mpDirichletMap[i]);
            mpDirichletMap[i] = NULL;
        }
    }

    // Recommunicate that Dirichlet BCs have changed (next time we ask)
    ResetDirichletCommunication();
}
Example #13
0
u32 sceUtilityLoadModule(u32 module)
{
	// TODO: Not all modules between 0x100 and 0x601 are valid.
	if (module < 0x100 || module > 0x601)
	{
		ERROR_LOG_REPORT(SCEUTILITY, "sceUtilityLoadModule(%i): invalid module id", module);
		return SCE_ERROR_MODULE_BAD_ID;
	}

	if (currentlyLoadedModules.find(module) != currentlyLoadedModules.end())
	{
		DEBUG_LOG(SCEUTILITY, "sceUtilityLoadModule(%i): already loaded", module);
		return SCE_ERROR_MODULE_ALREADY_LOADED;
	}
	INFO_LOG(SCEUTILITY, "sceUtilityLoadModule(%i)", module);
	// Fix Kamen Rider Climax Heroes OOO - ULJS00331 loading
	// Fix Naruto Shippuden Kizuna Drive (error module load failed)
	if (module == PSP_MODULE_NET_HTTPSTORAGE && !(currentlyLoadedModules.find(PSP_MODULE_NET_HTTP) != currentlyLoadedModules.end()))
	{
		ERROR_LOG(SCEUTILITY, "sceUtilityLoadModule: Library not found");
		return SCE_KERNEL_ERROR_LIBRARY_NOTFOUND;
	}
	// TODO: Each module has its own timing, technically, but this is a low-end.
	// Note: Some modules have dependencies, but they still resched.

	currentlyLoadedModules.insert(module);

	if (module == 0x3FF)
		return hleDelayResult(0, "utility module loaded", 130);
	else
		return hleDelayResult(0, "utility module loaded", 25000);
}
Example #14
0
Wt::Auth::OAuthClient OidcUserDatabase::idpClientAdd(const std::string &clientId,
                                                    bool confidential,
                                                    const std::set<std::string> &redirectUris,
                                                    Wt::Auth::ClientSecretMethod authMethod,
                                                    const std::string &secret)
{
  Wt::Dbo::Transaction t(session_);
  OAuthClient *client = new OAuthClient;
  client->clientId = clientId;
  client->confidential = confidential;
  std::set<std::string>::iterator uri = redirectUris.begin();
  std::string uris = *(uri++);
  for (; uri != redirectUris.end();++uri) {
    uris = uris + " " + *uri;
  }
  client->redirectUris = uris;
  client->authMethod = authMethod;
  client->secret = Wt::Auth::BCryptHashFunction(7)
    .compute(secret,
             Wt::WRandom::generateId());
  Wt::Dbo::ptr<OAuthClient> client_ = session_.add(client);
  t.commit();
  return Wt::Auth::OAuthClient(boost::lexical_cast<std::string>(client_.id()),
                               *this);
}
        void SetData(uint32 type, uint32 data)
        {
            switch (type)
            {
            case TYPE_MOGRAINE_AND_WHITE_EVENT:
                if (data == IN_PROGRESS)
                    DoUseDoorOrButton(DoorHighInquisitorGUID);
                if (data == FAIL)
                    DoUseDoorOrButton(DoorHighInquisitorGUID);

                encounter[0] = data;
                break;
            case GAMEOBJECT_PUMPKIN_SHRINE:
                HandleGameObject(PumpkinShrineGUID, false);
                break;
            case DATA_HORSEMAN_EVENT:
                encounter[1] = data;
                if (data == DONE)
                {
                    for (std::set<uint64>::const_iterator itr = HorsemanAdds.begin(); itr != HorsemanAdds.end(); ++itr)
                    {
                        Creature* add = instance->GetCreature(*itr);
                        if (add && add->IsAlive())
                            add->Kill(add);
                    }
                    HorsemanAdds.clear();
                    HandleGameObject(PumpkinShrineGUID, false);
                }
                break;
            }
        }
Example #16
0
static bool hasLinearPathInternal(std::set<uint32> &visited, const Block &block1, const Block &block2) {
	/* Checks that a linear path exists between two blocks, by recursively
	 * descending into the children of the earlier block, until we either
	 * reached the later block (which means there is a path), or moved
	 * past the later block (which means there is no path). */

	// Remember which blocks we already visited, so we don't process them twice
	visited.insert(block1.address);

	// The two blocks are the same => we found a path
	if (block1.address == block2.address)
		return true;

	// We moved past the destination => no path
	if (block1.address > block2.address)
		return false;

	// Continue along the children
	assert(block1.children.size() == block1.childrenTypes.size());

	for (size_t i = 0; i < block1.children.size(); i++) {
		const Block        &child = *block1.children[i];
		const BlockEdgeType type  =  block1.childrenTypes[i];

		// Don't follow subroutine calls, don't jump backwards and don't visit blocks twice
		if (!isSubRoutineCall(type) && (child.address > block1.address))
			if (visited.find(child.address) == visited.end())
				if (hasLinearPathInternal(visited, child, block2))
					return true;
	}

	return false;
}
Example #17
0
static std::set <T> mergeSets(const std::set <T> & set1, const std::set <T> & set2)
{
	std::set <T> result = set1;
	for (typename std::set <T>::const_iterator i = set2.begin(); i != set2.end(); i++)
		result.insert(*i);
	return result;
}
Example #18
0
bool GoalNode::CrystalInitialize(const PropNet& pn,
                                 const std::map<const Node*, CrystalData>& crystal_data_map,
                                 PropNetPayLoad& payload,
                                 std::set<const Node*>& initialized)
{
    if(initialized.find(this) != initialized.end())
        return holding_value;

    for(auto it : in_degree)
    {
        bool temp = it->CrystalInitialize(pn, crystal_data_map, payload, initialized);
        SimPolicyInitializeUpdate(temp, payload.data[crystal_data_map.find(this)->second.id]);
    }

    holding_value = CrystalConfig::GetCrystalBoolValue(payload.data[crystal_data_map.find(this)->second.id]);

    if(holding_value)
    {
        payload.goals[r_id] = id;
    }

    initialized.insert(this);

    return holding_value;
}
Example #19
0
bool CNodeDefManager::getIds(const std::string &name,
		std::set<content_t> &result) const
{
	//TimeTaker t("getIds", NULL, PRECISION_MICRO);
	if (name.substr(0,6) != "group:") {
		content_t id = CONTENT_IGNORE;
		bool exists = getId(name, id);
		if (exists)
			result.insert(id);
		return exists;
	}
	std::string group = name.substr(6);

	std::map<std::string, GroupItems>::const_iterator
		i = m_group_to_items.find(group);
	if (i == m_group_to_items.end())
		return true;

	const GroupItems &items = i->second;
	for (GroupItems::const_iterator j = items.begin();
		j != items.end(); ++j) {
		if ((*j).second != 0)
			result.insert((*j).first);
	}
	//printf("getIds: %dus\n", t.stop());
	return true;
}
void gSpan::read(char* _fname)
{
    std::cout << "In gSpan::read function" << std::endl;
    int lineoffset = 0;
    Graph g(directed);
    totalLabels.clear();

    maxVertices = 0;
    maxEdges = 0;

    while(true) {
        lineoffset = g.read(_fname,lineoffset);
        if(g.empty()) break;
        TRANS.push_back(g);

    }



    NumOfLabels = (int)totalLabels.size();

    std::cout << "Total: " << NumOfLabels << std::endl;
    std::cout << "MaxVertices = " << maxVertices << "     MaxEdges = " << maxEdges << std::endl;

    totalLabels.clear();

    return;
}
Example #21
0
bool is_datetime_type(const std::string& type)
{
    //The date and time types for representing temporal values are DATE, TIME, DATETIME, TIMESTAMP, and YEAR. 
    static const std::set<std::string> chartypes = boost::assign::list_of(std::string("date"))("time")("datetime")("timestamp")("year");
    std::string searchtype = type.substr(0,type.find("("));
    return chartypes.find(searchtype) != chartypes.end();
};
	void FillVertices(VertexIt begin, VertexIt end, bool add_conjugate) {
		for (auto it = begin; it != end; ++it) {
			vertices_.insert(*it);
			if (add_conjugate)
				vertices_.insert(graph_.conjugate(*it));
		}
	}
Example #23
0
	void ApplyHashMap() {
		UpdateHashToFunctionMap();

		for (auto mf = hashMap.begin(), end = hashMap.end(); mf != end; ++mf) {
			auto iter = hashToFunction.find(mf->hash);
			if (iter == hashToFunction.end()) {
				continue;
			}

			// Yay, found a function.

			for (unsigned int i = 0; i < iter->second.size(); i++) {
				AnalyzedFunction &f = *(iter->second[i]);
				if (f.hash == mf->hash && f.size == mf->size) {
					strncpy(f.name, mf->name, sizeof(mf->name) - 1);

					std::string existingLabel = symbolMap.GetLabelString(f.start);
					char defaultLabel[256];
					// If it was renamed, keep it.  Only change the name if it's still the default.
					if (existingLabel.empty() || existingLabel == DefaultFunctionName(defaultLabel, f.start)) {
						symbolMap.SetLabelName(mf->name, f.start);
					}
				}
			}
		}
	}
Example #24
0
// ============= Atomicity Breaker ==================
static bool is_am_call(int syscall_id, int arg1, int arg2, int arg3) {
  static int FS_CALLS[] = {
    SYS_open,
    SYS_ftruncate,
    SYS_ftruncate64,
    SYS_creat,
    SYS_unlink,
  };
  static std::set<int> fs_calls = std::set<int>(FS_CALLS, FS_CALLS + sizeof(FS_CALLS) / sizeof(int));

  // write a chunk
  if (syscall_id == SYS_write) {
    int count = arg3;
    if (count > 512) {
      return true;
    }
  }
  // open with write
  if (syscall_id == SYS_open) {
    int flags = arg2;
    return (flags & O_WRONLY) || (flags & O_RDWR);
  }
  // or in the system call list
  return fs_calls.find(syscall_id) != fs_calls.end();
}
Example #25
0
template <typename PointT> bool
pcl::SampleConsensusModelStick<PointT>::doSamplesVerifyModel (
      const std::set<int> &indices, const Eigen::VectorXf &model_coefficients, const double threshold) const
{
  // Needs a valid set of model coefficients
  if (!isModelValid (model_coefficients))
    return (false);

  // Obtain the line point and direction
  Eigen::Vector4f line_pt  (model_coefficients[0], model_coefficients[1], model_coefficients[2], 0);
  Eigen::Vector4f line_dir (model_coefficients[3] - model_coefficients[0], model_coefficients[4] - model_coefficients[1], model_coefficients[5] - model_coefficients[2], 0);
  //Eigen::Vector4f line_dir (model_coefficients[3], model_coefficients[4], model_coefficients[5], 0);
  line_dir.normalize ();

  float sqr_threshold = static_cast<float> (threshold * threshold);
  // Iterate through the 3d points and calculate the distances from them to the line
  for (std::set<int>::const_iterator it = indices.begin (); it != indices.end (); ++it)
  {
    // Calculate the distance from the point to the line
    // D = ||(P2-P1) x (P1-P0)|| / ||P2-P1|| = norm (cross (p2-p1, p2-p0)) / norm(p2-p1)
    if ((line_pt - input_->points[*it].getVector4fMap ()).cross3 (line_dir).squaredNorm () > sqr_threshold)
      return (false);
  }

  return (true);
}
Example #26
0
void game_menus::inv::common( player &p )
{
    static const std::set<int> allowed_selections = { { ' ', '.', 'q', '=', '\n', KEY_LEFT, KEY_ESCAPE } };

    p.inv.restack( &p );
    p.inv.sort();

    inventory_pick_selector inv_s( p );

    inv_s.add_character_items( p );
    inv_s.set_title( _( "Inventory" ) );

    int res;
    do {
        inv_s.set_hint( string_format(
                            _( "Item hotkeys assigned: <color_ltgray>%d</color>/<color_ltgray>%d</color>" ),
                            p.allocated_invlets().size(), inv_chars.size() - p.allocated_invlets().size() ) );
        const item_location &location = inv_s.execute();
        if( location == item_location::nowhere ) {
            break;
        }
        g->refresh_all();
        res = g->inventory_item_menu( p.get_item_position( location.get_item() ) );
        g->refresh_all();
    } while( allowed_selections.count( res ) != 0 );
}
Example #27
0
std::string Model::cleanNamespaceTrailingChars(std::string ns) {
    static const std::set<char> IGNORED_LAST_CHARS = {'#', ':', '/'};
    if ( IGNORED_LAST_CHARS.count(ns.back()) ) {
        ns.pop_back();
    }
    return ns;
}
Example #28
0
  void postWalkComponents(es::ESCoreBase& core)
  {
    StaticFontMan* man = core.getStaticComponent<StaticFontMan>();
    if (man == nullptr)
    {
      std::cerr << "Unable to complete font fulfillment. There is no StaticFontMan." << std::endl;
      return;
    }
    FontMan& fontMan = *man->instance;
    fontMan.mNewUnfulfilledAssets = false;

    if (mAssetsAwaitingRequest.size() > 0)
    {
      std::set<std::string> assetsWithNoRequest;
      // Compute set difference and initiate requests for appropriate
      // components.
      std::set_difference(mAssetsAwaitingRequest.begin(), mAssetsAwaitingRequest.end(),
                          mAssetsAlreadyRequested.begin(), mAssetsAlreadyRequested.end(),
                          std::inserter(assetsWithNoRequest, assetsWithNoRequest.end()));

      for (const std::string& asset : assetsWithNoRequest)
      {
        fontMan.requestFont(core, asset, fontMan.mNumRetries);
      }
    }
  }
Example #29
0
void RouteTable::getFromStates(const State& toState,
	std::set<State*>& fromStates) {
	// if didn't found, then just return
	const std::string& toStateName = toState.name();
	StateMapConstIterator it = mapToStateToFromStates.find(toStateName);
	if (it == mapToStateToFromStates.end()) {
		std::cout << "RouteTable:: state \"" << toState
			<< "\" didn't have any other state directed to"
			<< std::endl;
		return;
	}
	
	StateManager* stateManager = StateManager::instance();
	fromStates.clear();
	const std::set<std::string>& fromStateNames =
		mapToStateToFromStates[toStateName];
	for (std::set<std::string>::const_iterator it = fromStateNames.begin();
		it != fromStateNames.end(); ++it) {
		const std::string& fromState = *it;
		State* state = stateManager->getState(fromState);
		if (state)
			fromStates.insert(state);	
	}
	return;
}
  //Use the DHT Kademlia algorithm to find the best node that we're aware of.
  //This works using the following method:
  //Find the peer with the lowest distance between the key, and the peer ID (distance is the result of (key ^ peer GUID))
  //Return the peer which was found.
  //In our case; we modify our method such that it can return multiple peers, 
  size_t FindBestPeersForHash(const GlobalGrid::Guid& lukeup, GlobalGrid::Guid* peerlist, size_t numPeers) {
    size_t numLeft = sessions.size();
    uint64_t distance[2]; //Current distance
    distance[0] = -1;
    distance[1] = -1;
    size_t currentPeer = 0;
    size_t found = 0;
    size_t foundPeers = 0;
    for(auto bot = sessions.begin();bot != sessions.end();bot++) {
      //Compute distance
      uint64_t cdist[2];
      cdist[0] = distance[0] ^ lukeup.value[0];
      cdist[1] = distance[1] ^ lukeup.value[1];
      
      //NOTE: We really only need to compare the first 64-bits
      //The chances of any two being the same are astronomically low.
      if(cdist[0]<distance[0]) {
      
      
	if((*bot).verified) {
	  distance[0] = cdist[0];
	  distance[1] = cdist[1];
	  peerlist[currentPeer] = GlobalGrid::Guid((*bot).claimedThumbprint);
	  currentPeer = (currentPeer + 1) % numPeers;
	  if(foundPeers<numPeers) {
	    foundPeers++;
	  }
	}
      
      }
    }
    return foundPeers;
  }