randomEngine getDefaultRandomEngine(void) { af_random_engine internal_handle, handle; AF_THROW(af_get_default_random_engine(&internal_handle)); AF_THROW(af_retain_random_engine(&handle, internal_handle)); return randomEngine(handle); }
void threadFunc(int threadNum) { std::random_device rd; std::mt19937 randomEngine(rd()); int writes = 0; volatile int accumulator = 0; // Prevent compiler from eliminating this variable for (int i = 0; i < m_iterationCount; i++) { // Choose randomly whether to read or write. if (std::uniform_int_distribution<>(0, 30)(randomEngine) == 0) { WriteLockGuard<NonRecursiveRWLock> guard(m_rwLock); m_sharedInt++; writes++; } else { ReadLockGuard<NonRecursiveRWLock> guard(m_rwLock); accumulator += m_sharedInt; } } m_totalWrites.fetch_add(writes, std::memory_order_relaxed); }
TEST_P(BlobCacheTest, ExceedingTotalLimitRemovesLRUEntries) { if (GetParam().first != BlobCache::Select::LRU) return; // test doesn't apply for this policy // Fill up the entire cache with 1 char key/value pairs. static const int maxEntries = MAX_TOTAL_SIZE / 2; for (int i = 0; i < maxEntries; i++) { uint8_t k = i; mBC->set(&k, 1, "x", 1); } // Access entries in some known pseudorandom order. int accessSequence[maxEntries]; std::iota(&accessSequence[0], &accessSequence[maxEntries], 0); std::mt19937 randomEngine(MAX_TOTAL_SIZE /* seed */); std::shuffle(&accessSequence[0], &accessSequence[maxEntries], randomEngine); for (int i = 0; i < maxEntries; i++) { uint8_t k = accessSequence[i]; uint8_t buf[1]; // If we were to pass NULL to get() as the value pointer, this // won't count as an access for LRU purposes. mBC->get(&k, 1, buf, 1); } // Insert one more entry, causing a cache overflow. { uint8_t k = maxEntries; mBC->set(&k, 1, "x", 1); } // Check which entries are in the cache. We expect to see the // "one more entry" we just added, and also the most-recently // accessed (according to accessSequence). That is, we should // find exactly the entries with the following keys: // . maxEntries // . accessSequence[j..maxEntries-1] for some 0 <= j < maxEntries uint8_t k = maxEntries; ASSERT_EQ(size_t(1), mBC->get(&k, 1, NULL, 0)); bool foundAny = false; for (int i = 0; i < maxEntries; i++) { uint8_t k = accessSequence[i]; bool found = (mBC->get(&k, 1, NULL, 0) == 1); if (foundAny == found) continue; if (!foundAny) { // found == true, so we just discovered j == i foundAny = true; } else { // foundAny == true, found == false -- oops FAIL() << "found [" << i-1 << "]th entry but not [" << i << "]th entry"; } } }
static Grid uniformGrid(u_int width, u_int height, double obstacleProbability, int seed = 0) { Grid grid(width, height); std::default_random_engine randomEngine(seed); std::uniform_int_distribution<int> widthDistribution(0, width - 1); std::uniform_int_distribution<int> heightDistribution(0, height - 1); std::bernoulli_distribution obstacleDistribution(obstacleProbability); for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { } } return grid; };
void MainGame::initBalls() { // Initializes the grid _grid = std::make_unique<Grid>(m_screenWidth, m_screenHeight, CELL_SIZE); #define ADD_BALL(p, ...) \ totalProbability += p; \ possibleBalls.emplace_back(__VA_ARGS__); // Number of balls to spawn const int NUM_BALLS = 5000; // Random engine stuff std::mt19937 randomEngine((unsigned int)time(nullptr)); std::uniform_real_distribution<float> randX(0.0f, (float)m_screenWidth); std::uniform_real_distribution<float> randY(0.0f, (float)m_screenHeight); std::uniform_real_distribution<float> randDir(-1.0f, 1.0f); // Add all possible balls std::vector <BallSpawn> possibleBalls; float totalProbability = 0.0f; std::uniform_real_distribution<float> r1(2.0f, 6.0f); std::uniform_int_distribution<int> r2(0, 255); // Adds the balls using a macro ADD_BALL(20.0f, Engine::Color(255, 255, 255, 255), 2.0f, 1.0f, 0.1f, 7.0f, totalProbability); ADD_BALL(10.0f, Engine::Color(0, 0, 255, 255), 3.0f, 2.0f, 0.1f, 3.0f, totalProbability); ADD_BALL(1.0f, Engine::Color(255, 0, 0, 255), 5.0f, 4.0f, 0.0f, 0.0f, totalProbability); for (int i = 0; i < 10000; i++){ ADD_BALL(1.0f, Engine::Color(r2(randomEngine), r2(randomEngine), r2(randomEngine), 255), r1(randomEngine), r1(randomEngine), 0.0f, 0.0f, totalProbability); } // Random probability for ball spawn std::uniform_real_distribution<float> spawn(0.0f, totalProbability); // Small optimization that sets the size of the internal array to prevent // extra allocations. m_balls.reserve(NUM_BALLS); // Set up ball to spawn with default value BallSpawn* ballToSpawn = &possibleBalls[0]; for (int i = 0; i < NUM_BALLS; i++) { // Get the ball spawn roll float spawnVal = spawn(randomEngine); // Figure out which ball we picked for (size_t j = 0; j < possibleBalls.size(); j++) { if (spawnVal <= possibleBalls[j].probability) { ballToSpawn = &possibleBalls[j]; break; } } // Get random starting position glm::vec2 pos(randX(randomEngine), randY(randomEngine)); // Hacky way to get a random direction glm::vec2 direction(randDir(randomEngine), randDir(randomEngine)); if (direction.x != 0.0f || direction.y != 0.0f) { // The chances of direction == 0 are astronomically low direction = glm::normalize(direction); } else { direction = glm::vec2(1.0f, 0.0f); // default direction } // Add ball m_balls.emplace_back(ballToSpawn->radius, ballToSpawn->mass, pos, direction * ballToSpawn->randSpeed(randomEngine), Engine::ResourceManager::getTexture("Textures/circle.png").id, ballToSpawn->color); // Add the ball to the grid. _grid->addBall(&m_balls.back()); } }
WebAPIResult_t WebAPI::SendSteamMessage(Message message) { this->debugEnabled = message.config.debugEnabled; this->requestTimeout = message.config.requestTimeout; std::vector<uint64_t> recipientsCopy(message.config.recipients); if (message.config.shuffleRecipients) { std::random_device randomDevice; std::mt19937 randomEngine(randomDevice()); std::shuffle(recipientsCopy.begin(), recipientsCopy.end(), randomEngine); Debug("[DEBUG] Shuffled recipient list"); } Debug("[DEBUG] Trying to send a message to user '%s' with password '%s' and message '%s'", message.config.username.c_str(), message.config.password.c_str(), message.text.c_str()); WebAPIResult_t result; // No recipient? if (recipientsCopy.size() == 0) { Debug("[DEBUG] Couldn't send message, as no recipients are defined"); result.type = WebAPIResult_NO_RECEIVER; result.error = "No receiver was configurated"; return result; } Json::Value loginSteamCommunityResult = this->LoginSteamCommunity(message.config.username, message.config.password); if (!loginSteamCommunityResult["success"].asBool()) { LogError(loginSteamCommunityResult["error"].asString().c_str()); result.type = WebAPIResult_LOGIN_ERROR; result.error = loginSteamCommunityResult["error"].asString(); return result; } std::string accessToken = loginSteamCommunityResult["oauth_token"].asString(); std::string steamid = loginSteamCommunityResult["steamid"].asString(); std::string sessionid = this->GetCookie(this->steamCommunityClient, "sessionid"); Json::Value loginWebAPIResult = this->LoginWebAPI(accessToken); if (!loginWebAPIResult["success"].asBool()) { LogError(loginWebAPIResult["error"].asString().c_str()); result.type = WebAPIResult_LOGIN_ERROR; result.error = loginSteamCommunityResult["error"].asString(); return result; } std::string umqid = loginWebAPIResult["umqid"].asString(); // Get friend list Json::Value friendListResult = this->GetFriendList(accessToken); if (!friendListResult["success"].asBool()) { LogError(friendListResult["error"].asString().c_str()); result.type = WebAPIResult_API_ERROR; result.error = loginSteamCommunityResult["error"].asString(); return result; } // Accept all friends Json::Value friendValue = friendListResult.get("friends", ""); for (int i = 0; friendValue.isValidIndex(i); i++) { std::string steam = friendValue[i].get("steamid", "").asString(); std::string relation = friendValue[i].get("relationship", "").asString(); if (relation == "requestrecipient") { // Accept the friend if there is a request this->AcceptFriend(sessionid, steamid, steam); // Add a second timeout, as otherwise two consecutive requests can fail! sleep_ms(1000); } } // Get user stats Json::Value userStatsResult = this->GetUserStats(accessToken, recipientsCopy); if (!userStatsResult["success"].asBool()) { LogError(userStatsResult["error"].asString().c_str()); result.type = WebAPIResult_API_ERROR; result.error = loginSteamCommunityResult["error"].asString(); return result; } // Check if there is valid recipient which is online Json::Value userValues = userStatsResult.get("players", ""); for (auto recipient = recipientsCopy.begin(); recipient != recipientsCopy.end(); recipient++) { for (int i = 0; userValues.isValidIndex(i); i++) { std::string steam = userValues[i].get("steamid", "").asString(); int online = userValues[i].get("personastate", 0).asInt(); if (steam == std::to_string(*recipient) && online) { // Send the message to the recipient Json::Value sendMessageResult = this->SendSteamMessage(accessToken, umqid, *recipient, message.text); if (!sendMessageResult["success"].asBool()) { LogError(sendMessageResult["error"].asString().c_str()); this->LogoutWebAPI(); // Wait after logout, as steam needs a few seconds until logout is complete sleep_ms(message.config.waitAfterLogout); result.type = WebAPIResult_API_ERROR; result.error = loginSteamCommunityResult["error"].asString(); return result; } // Wait between messages, as the user may occur some limitations on how much messages he can send sleep_ms(message.config.waitBetweenMessages); break; } } } // Logout on finish this->LogoutWebAPI(); // Wait after logout, as steam needs a few seconds until logout is complete sleep_ms(message.config.waitAfterLogout); Debug("[DEBUG] Sent message"); result.type = WebAPIResult_SUCCESS; result.error = std::string(); return result; }
void LevelOneScreen::initLevel(){ std::mt19937 randomEngine((unsigned int)time(NULL)); std::uniform_int_distribution<int> randMonster(0, MONSTER_KIND-1); std::uniform_int_distribution<int> randomMovement(0,1000); std::uniform_int_distribution<int> randomItemNum(1, 10); std::uniform_int_distribution<int> randomItemKind(0, ITEM_KIND - 1); glm::vec4 playerArea; _level = std::make_unique<LevelManager>("Levels/Version1/level1.txt"); // Objects Creation code goes here. std::uniform_int_distribution<int> yPos(3, _level->getHeight() - 3); std::uniform_int_distribution<int> xPos(3, _level->getWidth() - 3); //Monsters int i = 0; int count = 2; int numMonster = _level->getNumMonsters(); _monsters.reserve(numMonster); while(i < numMonster){ int temp = randMonster(randomEngine); int x = xPos(randomEngine); int y = yPos(randomEngine); int movement = ((randomMovement(randomEngine) * count) % MAX_MOVEMENT + count/2); if (_level->getSymbol(x, y) == '.'){ glm::vec2 pos = glm::vec2(x * TILE_WIDTH, y * TILE_WIDTH); if (temp == 0){ _monsters.push_back(new Werewolf); _monsters.back()->init(4, 2, pos, 10); } else if (temp == 1){ _monsters.push_back(new Orga); _monsters.back()->init(3, 3, pos, 30); } else{ _monsters.push_back(new Wolf); _monsters.back()->init(2, 2, pos, movement); //std::cout << "Movement : " << movement << std::endl; } i++; } count++; } //Testing /*_monsters.push_back(new Wolf); _monsters.back()->init(3, 3, glm::vec2(500, 1000));*/ int numItem = randomItemNum(randomEngine); int j = 0; while (j < numItem) { int temp = randomItemKind(randomEngine); int x = xPos(randomEngine); int y = yPos(randomEngine); if (_level->getSymbol(x, y) == '.') { glm::vec2 pos = glm::vec2(x * TILE_WIDTH, y * TILE_WIDTH); switch (temp) { case 0: _items.push_back(new BigPotion); break; case 1: _items.push_back(new SmallPotion); break; case 2: _items.push_back(new GoodMeat); break; case 3: _items.push_back(new BadMeat); break; case 4: _items.push_back(new GoodFish); break; case 5: _items.push_back(new BadFish); } _items.back()->init(pos); j++; } } //Initialize player. _player = Player::getInstance(); _player->init(_level->getStartPlayerPosition(), PLAYER_SPEED); //Testing for weapon. _items.push_back(new Sword); _items.back()->init(glm::vec2(200, 1000)); }
string WdtBase::generateTransferId() { std::default_random_engine randomEngine(time(0)); string transferId = to_string(randomEngine()); LOG(INFO) << "Generated a transfer id " << transferId; return transferId; }