LRESULT CLogListBox::OnDrawitem(UINT uMsg, WPARAM wParam, LPARAM lParam,BOOL& bHandled) { LPDRAWITEMSTRUCT dis = (LPDRAWITEMSTRUCT) lParam; if(!dis) return FALSE; LogListBoxItem * item = (LogListBoxItem *)dis->itemData; if(!item) return FALSE; CDCHandle dc = dis->hDC; if(dis->itemAction & (ODA_DRAWENTIRE|ODA_SELECT)) { dc.SetBkColor(GetSysColor(COLOR_WINDOW)); dc.SetTextColor(GetSysColor(COLOR_WINDOWTEXT)); CRect r(dis->rcItem); if(!(dis->itemState & ODS_SELECTED )) { CBrush br; br.CreateSolidBrush(GetSysColor(COLOR_WINDOW)); dc.FillRect(r,br); } CRect rct; GetClientRect(&rct); if(dis->itemState & ODS_SELECTED ) { CRect rd(dis->rcItem); GuiTools::FillRectGradient(dis->hDC,rd,0xEAE2D9, 0xD3C1AF, false); } else if(dis->itemID != GetCount()-1) // If it isn't last item { CPen pen; pen.CreatePen(PS_SOLID, 1, RGB(190,190,190)); SelectObject(dc.m_hDC, pen); dc.MoveTo(rct.left, r.bottom-1); dc.LineTo(rct.right, r.bottom-1); } SetBkMode(dc.m_hDC,TRANSPARENT); SIZE TimeLabelDimensions; SelectObject(dc.m_hDC, NormalFont); GetTextExtentPoint32(dc, item->Time, item->Time.GetLength(), &TimeLabelDimensions); // Writing error time ExtTextOutW(dc.m_hDC, rct.right-5-TimeLabelDimensions.cx, r.top + LLB_VertMargin, ETO_CLIPPED, r, item->Time, item->Time.GetLength(), 0); // Writing error title SelectObject(dc.m_hDC, UnderlineFont); ExtTextOutW(dc.m_hDC, r.left+56, r.top + LLB_VertMargin, ETO_CLIPPED, r, item->strTitle, wcslen(item->strTitle), 0); // Writing some info SelectObject(dc.m_hDC, NormalFont); RECT ItemRect={r.left+56, r.top + LLB_VertMargin + LLB_VertDivider + item->TitleHeight, r.right - 10, r.bottom-LLB_VertMargin}; dc.DrawText(item->Info, item->Info.GetLength() , &ItemRect, DT_NOPREFIX); // Writing error text with bold (explication of error) SelectObject(dc.m_hDC, BoldFont); RECT TextRect = {r.left+56, LLB_VertMargin +r.top+ item->TitleHeight+LLB_VertDivider+((item->Info.GetLength())?(item->InfoHeight+LLB_VertDivider):0), r.right - 10, r.bottom-LLB_VertMargin}; dc.DrawText(item->strText, wcslen(item->strText), &TextRect, DT_NOPREFIX); if(item->Type == logError) dc.DrawIcon(12,r.top+8,ErrorIcon); else if(item->Type == logWarning) dc.DrawIcon(12,r.top+8,WarningIcon); } bHandled = true; return 0; }
Entity* Grpg::dropEasterEgg() { //Drop chances directly from https://www.reddit.com/r/hearthstone/comments/2emnxl/drops_chances_rarity_by_11359_hearthstone_expert/ //(Gold added to normal chances) //Decimal places removed, multiply everything by 1000 for full number. int commonChance = 70000 + 1470; //rand() generates a random number from 0 to RAND_MAX... //RAND_MAX is guaranteed to be at least 32767 on any standard library implementation... which is WAY TOO LOW! //So we use a different method instead: https://stackoverflow.com/questions/19758694/c-generate-a-random-number-between-0-and-100-000 std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(0, 100000); int randomNumber = dis(gen); stringstream ss; ss << "Random number generated: " << randomNumber; //ui->addChatText(ss.str()); ss.str(""); ss << "Common chance: " << commonChance; //ui->addChatText(ss.str()); ss.str(""); InventoryItem* newItem; if (randomNumber > commonChance || easterEggCounter >= 4) { //You got a rare (or better!) //Reset free rare+ counter. easterEggCounter = 0; int rareChance = 21400 + 1370; ss << "Rare chance: " << (rareChance + commonChance); //ui->addChatText(ss.str()); ss.str(""); if (randomNumber > (commonChance + rareChance)) { //You got an epic (or better!) int epicChance = 4280 + 1370; ss << "Epic chance: " << (rareChance + commonChance + epicChance); //ui->addChatText(ss.str()); ss.str(""); if (randomNumber > (commonChance + rareChance + epicChance)) { //WOAH, LEGENDARY!!!!!!!!!!! newItem = new InventoryFood(itemLoader->getItem(35), 1, DELICIOUS); } else { //Epic confirmed newItem = new InventoryItem(itemLoader->getItem(34), 1); } } else { //Rare confirmed newItem = new InventoryBoost(itemLoader->getItem(33), 1); } } else { //You got a common! easterEggCounter++; newItem = new InventoryFood(itemLoader->getItem(32), 1, DELICIOUS); } //Generate new item Entity* e = new Entity(); e->initialize(this, newItem, false); return e; }
int mpx_test (int argc, const char **argv) { rd (buf1, 2, 10.0d, 10.0d, buf, 100, buf1); return 0; }
// Returns a random float between min and max, // default parameters are FLT_MIN and FLT_MAX float RNG::randFloat(float min, float max){ rnd = std::default_random_engine(rd()); std::uniform_real_distribution<float> flt(min,max); return flt(rnd); };
gene_t_p Gene::get_random_tree(){ //ランダムな木を再帰的に生成する gene_t_p tr = new gene_t; mt19937 mt(rd()); uniform_real_distribution<double> rd_double(0.0,1.0); if(rd_double(mt)<RAND_FRONT){ tr->mov = front; }else if(rd_double(mt) < RAND_FRONT + RAND_LR){ tr->mov = l; }else if(rd_double(mt) < RAND_FRONT + RAND_LR*2.0){ tr->mov = r; }else if(rd_double(mt) < RAND_FRONT + RAND_LR*2.0+RAND_IF){ tr->mov = if_f; do{ tr->lt = get_random_tree(); tr->rt = get_random_tree(); }while(tr->lt->mov == tr->rt->mov && tr->lt->mov != if_f && tr->lt->mov != proc); uniform_int_distribution<int> rd_int(0,NUM_IF-1); tr->n_func = rd_int(mt); switch(tr->n_func){ case 0: tr->p = &Snake::get_l_snake; break; case 1: tr->p = &Snake::get_f_snake; break; case 2: tr->p = &Snake::get_r_snake; break; case 3: tr->p = &Snake::get_l_food; break; case 4: tr->p = &Snake::get_f_food; break; case 5: tr->p = &Snake::get_r_food; break; case 6: tr->p = &Snake::get_food_front; break; case 7: tr->p = &Snake::get_food_left_side; break; case 8: tr->p = &Snake::get_food_right_side; break; default: printf("Error if function\n"); exit(1); } }else{ tr->mov = proc; do{ tr->lt = get_random_tree(); tr->rt = get_random_tree(); }while(tr->lt->mov == tr->rt->mov && tr->lt->mov != if_f && tr->lt->mov != proc); } return tr; }
void test_atomic() { std::random_device rd; std::mt19937 gen(rd()); for(int ii=0; ii<100; ++ii) { std::atomic<bool> o_ab(std::uniform_int_distribution<int>(0,1)(gen)); std::atomic<signed char> o_asc(std::uniform_int_distribution<signed char>( std::numeric_limits<signed char>::min(), std::numeric_limits<signed char>::max() )(gen)); std::atomic<unsigned short> o_aus(std::uniform_int_distribution<unsigned short>( std::numeric_limits<unsigned short>::min(), std::numeric_limits<unsigned short>::max() )(gen)); std::atomic<int> o_asi(std::uniform_int_distribution<int>( std::numeric_limits<int>::min(), std::numeric_limits<int>::max() )(gen)); std::atomic<long> o_asl(std::uniform_int_distribution<long>( std::numeric_limits<long>::min(), std::numeric_limits<long>::max() )(gen)); std::atomic<unsigned long long> o_aull(std::uniform_int_distribution<unsigned long long>( std::numeric_limits<unsigned long long>::min(), std::numeric_limits<unsigned long long>::max() )(gen)); std::ostringstream os; { OArchive oar(os); oar(o_ab); oar(o_asc); oar(o_aus); oar(o_asi); oar(o_asl); oar(o_aull); } std::atomic<bool> i_ab; std::atomic<signed char> i_asc; std::atomic<unsigned short> i_aus; std::atomic<int> i_asi; std::atomic<long> i_asl; std::atomic<unsigned long long> i_aull; std::istringstream is(os.str()); { IArchive iar(is); iar(i_ab); iar(i_asc); iar(i_aus); iar(i_asi); iar(i_asl); iar(i_aull); } BOOST_CHECK_EQUAL(o_ab.load(),i_ab.load()); BOOST_CHECK_EQUAL(o_asc.load(),i_asc.load()); BOOST_CHECK_EQUAL(o_aus.load(),i_aus.load()); BOOST_CHECK_EQUAL(o_asi.load(),i_asi.load()); BOOST_CHECK_EQUAL(o_asl.load(),i_asl.load()); BOOST_CHECK_EQUAL(o_aull.load(),i_aull.load()); } }
bool load_nonface_patch(std::vector< std::unique_ptr<NeuralNet::Image> >& images, size_t num_image, size_t train_set) { const size_t set_size = 2000; const size_t patch_size = 32; const size_t sample_per_img = 10; const size_t max_sample_per_img = 1000; const float var_thresh = 0.0007; size_t lbound = set_size * train_set + 1; size_t ubound = lbound + set_size; std::vector<size_t> idxes; for (size_t i = lbound; i < ubound; i++) idxes.push_back(i); std::random_device rd; std::mt19937 rgen(rd()); std::shuffle(idxes.begin(), idxes.end(), rgen); size_t num_failed_imgs = 0; size_t num_accept_imgs = 0; size_t img_count = 0; size_t loaded_patch = 0; while (loaded_patch < num_image && img_count < idxes.size()) { std::ostringstream oss; oss << "image-nonface/img_" << idxes[img_count] << ".bmp"; auto img_ptr = NeuralNet::loadBitmapImage(oss.str().c_str()); if (!img_ptr) { std::cout << "missing file " << oss.str() << std::endl; return false; } std::uniform_int_distribution<size_t> dis_w(0, img_ptr->getWidth() - patch_size); std::uniform_int_distribution<size_t> dis_h(0, img_ptr->getHeight() - patch_size); size_t added_patch = 0; for (size_t i=0; i<max_sample_per_img && added_patch < sample_per_img && added_patch + loaded_patch < num_image; i++) { auto cropImage = NeuralNet::cropImage( img_ptr, dis_w(rgen), dis_h(rgen), patch_size, patch_size); auto grayImage = NeuralNet::grayscaleImage(cropImage); if (NeuralNet::getVariance(grayImage) <= var_thresh) { num_failed_imgs++; } else { num_accept_imgs++; } if (NeuralNet::getVariance(grayImage) <= var_thresh) continue; images.push_back(preprocessImage(cropImage)); added_patch++; } loaded_patch += added_patch; img_count++; } std::cout << "accept=" << num_accept_imgs << " reject=" << num_failed_imgs << std::endl; if (loaded_patch == num_image) return true; return false; }
void distanceTransform::fourSEDFiltering(channel &chnl, matrix<point> &dist) const { //create all masks point mask0[] = { point(-1, 0) }; sedMask l(mask0, 1); point mask1[] = { point(0, -1) }; sedMask u(mask1, 1); point mask2[] = { point(0, -1), point(-1, 0) }; sedMask ul(mask2, 2); point mask3[] = { point(1, 0) }; sedMask r(mask3, 1); point mask4[] = { point(0, 1) }; sedMask d(mask4, 1); point mask5[] = { point(1, 0), point(0, 1) }; sedMask rd(mask5, 2); point pos; pos.y = 0; //first line for(pos.x = 1; pos.x < chnl.columns(); ++pos.x) l.filter(dist, pos); for(pos.x = chnl.columns() - 2; pos.x >= 0; --pos.x) r.filter(dist, pos); for(pos.y = 1; pos.y < chnl.rows(); ++pos.y){ pos.x = 0; //step down u.filter(dist, pos); for(pos.x = 1; pos.x < chnl.columns(); ++pos.x) ul.filter(dist, pos); for(pos.x = chnl.columns() - 2; pos.x >= 0; --pos.x) r.filter(dist, pos); } //and now filter the picture in the opposite direction pos.y = chnl.rows() - 1; //last line for(pos.x = chnl.columns() - 2; pos.x >= 0; --pos.x) r.filter(dist, pos); for(pos.x = 1; pos.x < chnl.columns(); ++pos.x) l.filter(dist, pos); for(pos.y = chnl.rows() - 2; pos.y >= 0; --pos.y){ pos.x = chnl.columns() - 1; //step up d.filter(dist, pos); for(pos.x = chnl.columns() - 2; pos.x >= 0; --pos.x) rd.filter(dist, pos); for(pos.x = 1; pos.x < chnl.columns(); ++pos.x) l.filter(dist, pos); } }
// Helper function to generate a random integer in the specified range. unsigned int random_value( unsigned int left, unsigned int right ) { std::random_device rd; std::mt19937 gen{ rd() }; return std::uniform_int_distribution< unsigned int >{left, right}(gen); }
inline void seed_rand() { rand_engine().seed(rd()); }
/*! \brief Compute the pose using the Lowe non linear approach it consider the minimization of a residual using the levenberg marquartd approach. The approach has been proposed by D.G Lowe in 1992 paper \cite Lowe92a. */ void vpPose::poseLowe(vpHomogeneousMatrix & cMo) { #if (DEBUG_LEVEL1) std::cout << "begin CCalcuvpPose::PoseLowe(...) " << std::endl; #endif int n, m; /* nombre d'elements dans la matrice jac */ int lwa; /* taille du vecteur wa */ int ldfjac; /* taille maximum d'une ligne de jac */ int info, ipvt[NBR_PAR]; int tst_lmder; double f[2 * NBPTMAX], sol[NBR_PAR]; double tol, jac[NBR_PAR][2 * NBPTMAX], wa[2 * NBPTMAX + 50]; // double u[3]; /* vecteur de rotation */ // double rd[3][3]; /* matrice de rotation */ n = NBR_PAR; /* nombres d'inconnues */ m = (int)(2 * npt); /* nombres d'equations */ lwa = 2 * NBPTMAX + 50; /* taille du vecteur de travail */ ldfjac = 2 * NBPTMAX; /* nombre d'elements max sur une ligne */ tol = std::numeric_limits<double>::epsilon(); /* critere d'arret */ // c = cam ; // for (i=0;i<3;i++) // for (j=0;j<3;j++) rd[i][j] = cMo[i][j]; // mat_rot(rd,u); vpRotationMatrix cRo ; cMo.extract(cRo) ; vpThetaUVector u(cRo) ; for (unsigned int i=0;i<3;i++) { sol[i] = cMo[i][3]; sol[i+3] = u[i]; } vpPoint P ; unsigned int i_=0; for (std::list<vpPoint>::const_iterator it = listP.begin(); it != listP.end(); ++it) { P = *it; XI[i_] = P.get_x();//*cam.px + cam.xc ; YI[i_] = P.get_y() ;//;*cam.py + cam.yc ; XO[i_] = P.get_oX(); YO[i_] = P.get_oY(); ZO[i_] = P.get_oZ(); ++i_; } tst_lmder = lmder1 (&fcn, m, n, sol, f, &jac[0][0], ldfjac, tol, &info, ipvt, lwa, wa); if (tst_lmder == -1) { std::cout << " in CCalculPose::PoseLowe(...) : " ; std::cout << "pb de minimisation, returns FATAL_ERROR"; // return FATAL_ERROR ; } for (unsigned int i = 0; i < 3; i++) u[i] = sol[i + 3]; for (unsigned int i=0;i<3;i++) { cMo[i][3] = sol[i]; u[i] = sol[i+3]; } vpRotationMatrix rd(u) ; cMo.insert(rd) ; // rot_mat(u,rd); // for (i=0;i<3;i++) for (j=0;j<3;j++) cMo[i][j] = rd[i][j]; #if (DEBUG_LEVEL1) std::cout << "end CCalculPose::PoseLowe(...) " << std::endl; #endif // return OK ; }
inline random_engine& rand_engine() { static thread_local random_engine engine{ rd() }; return engine; }
int mpx_test (int argc, const char **argv) { rd (buf1, 3, buf1, buf1, buf1, buf, 0, buf1); rd (buf1, 3, buf1, buf1, buf1, buf, 99, buf1); return 0; }
tmp<volScalarField> SpalartAllmarasDDES::fd(const volScalarField& S) const { return 1 - tanh(pow3(8*rd(nuEff(), S))); }
void handleMapLoadTrap(InterruptedContext* c) { int32* pc = (int32*)c->pc(); assert(isMapLoad(pc), "not a map load"); assert(c->next_pc() == c->pc() + 4, "flow should be sequential"); Location dest = Location(rd(pc)); mapOop resultMap; // get the result map to load # if TARGET_OS_VERSION == SOLARIS_VERSION_broken // disabled for now -- there's some bug in get_reg --Urs 8/94 Location src = Location(rs1(pc)); fint rcvrTag = int(c->get_reg(src)) & Tag_Mask; if (rcvrTag == Int_Tag) { resultMap = Memory->smi_map->enclosing_mapOop(); } else if (rcvrTag == Float_Tag) { resultMap = Memory->float_map->enclosing_mapOop(); } else { fatal("bad receiver tag in map load trap"); } # else // Can't read registers, and signal handler doesn't get faulting address, // so don't know what the correct map is. But it's not really needed // (only important thing is that it's different from any mem map) since // the map testing code always checks the tag if an immediate is expected. resultMap = NULL; # endif NCodeBase* thing = findThing(pc); if (!thing->isNMethod()) { // a PIC -- no problem, will fix itself to eliminate trap } else { nmethod* nm = findNMethod(pc); if ((char*)pc >= nm->verifiedEntryPoint()) { // the trap happened in the body, not in the prologue if (nm->flags.trapCount > MapLoadTrapLimit) { // recompile the nmethod on next invocation to eliminate the traps nm->makeToBeRecompiled(); if (nm->isYoung()) // manipulate counters to provoke recompilation nm->makeVeryYoung(); else nm->makeYoung(); } else { nm->flags.trapCount++; if (nm->flags.trapCount <= 0) { // counter overflowed nm->flags.trapCount--; } } } } # if TARGET_OS_VERSION == SOLARIS_VERSION // simply set the destination register and continue c->set_reg(dest, resultMap); c->set_pc(c->next_pc()); c->set_next_pc(c->pc() + 4); # elif TARGET_OS_VERSION == SUNOS_VERSION // can't set register in interrupt handler - argh!! if (mapLoadHandler[dest]) { char* cont = c->next_pc(); InterruptedContext::set_continuation_address(first_inst_addr(mapLoadHandler[dest]), true, true); continuePC = cont; mapToLoad = resultMap; } else { fatal1("map load trap: bad destination register %d", dest); } # endif }
/////////////////////////////////////////////////////////////////////// // Generate random float float gen_random_float(float min, float max) { std::random_device rd; std::mt19937 mt(rd()); std::uniform_real_distribution<double> dist(min, max - 0.0001); return dist(mt); }
Spectrum DirectLighting::Li(const Scene *scene, const RayDifferential &ray, const Sample *sample, float *alpha) const { Intersection isect; Spectrum L(0.); if (scene->Intersect(ray, &isect)) { if (alpha) *alpha = 1.; // Evaluate BSDF at hit point BSDF *bsdf = isect.GetBSDF(ray); Vector wo = -ray.d; const Point &p = bsdf->dgShading.p; const Normal &n = bsdf->dgShading.nn; // Compute emitted light if ray hit an area light source L += isect.Le(wo); // Compute direct lighting for _DirectLighting_ integrator if (scene->lights.size() > 0) { // Apply direct lighting strategy switch (strategy) { case SAMPLE_ALL_UNIFORM: L += UniformSampleAllLights(scene, p, n, wo, bsdf, sample, lightSampleOffset, bsdfSampleOffset, bsdfComponentOffset); break; case SAMPLE_ONE_UNIFORM: L += UniformSampleOneLight(scene, p, n, wo, bsdf, sample, lightSampleOffset[0], lightNumOffset, bsdfSampleOffset[0], bsdfComponentOffset[0]); break; case SAMPLE_ONE_WEIGHTED: L += WeightedSampleOneLight(scene, p, n, wo, bsdf, sample, lightSampleOffset[0], lightNumOffset, bsdfSampleOffset[0], bsdfComponentOffset[0], avgY, avgYsample, cdf, overallAvgY); break; } } return L; if (rayDepth++ < maxDepth) { Vector wi; // Trace rays for specular reflection and refraction Spectrum f = bsdf->Sample_f(wo, &wi, BxDFType(BSDF_REFLECTION | BSDF_SPECULAR)); if (!f.Black()) { // Compute ray differential _rd_ for specular reflection RayDifferential rd(p, wi); rd.hasDifferentials = true; rd.rx.o = p + isect.dg.dpdx; rd.ry.o = p + isect.dg.dpdy; // Compute differential reflected directions Normal dndx = bsdf->dgShading.dndu * bsdf->dgShading.dudx + bsdf->dgShading.dndv * bsdf->dgShading.dvdx; Normal dndy = bsdf->dgShading.dndu * bsdf->dgShading.dudy + bsdf->dgShading.dndv * bsdf->dgShading.dvdy; Vector dwodx = -ray.rx.d - wo, dwody = -ray.ry.d - wo; float dDNdx = Dot(dwodx, n) + Dot(wo, dndx); float dDNdy = Dot(dwody, n) + Dot(wo, dndy); rd.rx.d = wi - dwodx + 2 * Vector(Dot(wo, n) * dndx + dDNdx * n); rd.ry.d = wi - dwody + 2 * Vector(Dot(wo, n) * dndy + dDNdy * n); L += scene->Li(rd, sample) * f * AbsDot(wi, n); } f = bsdf->Sample_f(wo, &wi, BxDFType(BSDF_TRANSMISSION | BSDF_SPECULAR)); if (!f.Black()) { // Compute ray differential _rd_ for specular transmission RayDifferential rd(p, wi); rd.hasDifferentials = true; rd.rx.o = p + isect.dg.dpdx; rd.ry.o = p + isect.dg.dpdy; float eta = bsdf->eta; Vector w = -wo; if (Dot(wo, n) < 0) eta = 1.f / eta; Normal dndx = bsdf->dgShading.dndu * bsdf->dgShading.dudx + bsdf->dgShading.dndv * bsdf->dgShading.dvdx; Normal dndy = bsdf->dgShading.dndu * bsdf->dgShading.dudy + bsdf->dgShading.dndv * bsdf->dgShading.dvdy; Vector dwodx = -ray.rx.d - wo, dwody = -ray.ry.d - wo; float dDNdx = Dot(dwodx, n) + Dot(wo, dndx); float dDNdy = Dot(dwody, n) + Dot(wo, dndy); float mu = eta * Dot(w, n) - Dot(wi, n); float dmudx = (eta - (eta*eta*Dot(w,n))/Dot(wi, n)) * dDNdx; float dmudy = (eta - (eta*eta*Dot(w,n))/Dot(wi, n)) * dDNdy; rd.rx.d = wi + eta * dwodx - Vector(mu * dndx + dmudx * n); rd.ry.d = wi + eta * dwody - Vector(mu * dndy + dmudy * n); L += scene->Li(rd, sample) * f * AbsDot(wi, n); } } --rayDepth; } else { // Handle ray with no intersection if (alpha) *alpha = 0.; for (u_int i = 0; i < scene->lights.size(); ++i) L += scene->lights[i]->Le(ray); if (alpha && !L.Black()) *alpha = 1.; return L; } return L; }
int main(int, char**) { lptk::fiber::FiberInitStruct fiberInit; fiberInit.numWorkerThreads = 4; fiberInit.numSmallFibersPerThread = 64; lptk::fiber::Init(fiberInit); lptk::fiber::Counter counter; { //////////////////////////////////////// constexpr int N = 1000; lptk::fiber::Task tasks[N]; size_t i = 0; for (auto& task : tasks) { const auto testCounter = reinterpret_cast<void*>(i++); task.Set([](void* p) { const auto num = int(reinterpret_cast<size_t>(p)); printf("Fiber %d, part A\n", num); lptk::fiber::YieldFiber(); printf("Fiber %d, part B\n", num); lptk::fiber::YieldFiber(); printf("Fiber %d, part C\n", num); // TODO: the current implementation can't handle subtasks- they end up locking things up because // we can't allocate more fibers. //lptk::fiber::Counter subcounter; //lptk::fiber::Task subtask([](void* p) { // const auto subNum = int(reinterpret_cast<size_t>(p)); // printf("Fiber %d, %d, part A\n", subNum / 1000, subNum); // lptk::fiber::YieldFiber(); // printf("Fiber %d, %d, part B\n", subNum / 1000, subNum); // lptk::fiber::YieldFiber(); // printf("Fiber %d, %d, part C\n", subNum / 1000, subNum); //}, reinterpret_cast<void*>(reinterpret_cast<size_t>(p) * 1000)); //lptk::fiber::RunTasks(&subtask, 1, &subcounter); //lptk::fiber::WaitForCounter(&subcounter); }, testCounter); } lptk::fiber::RunTasks(tasks, N, &counter); lptk::fiber::WaitForCounter(&counter); printf("Finished all fibers.\n"); } //////////////////////////////////////// printf("Testing fiber services.\n"); { std::random_device rd; std::default_random_engine random(rd()); std::uniform_real_distribution<float> dist(0.f, 1.f); SleepService sleepService; sleepService.Start(); struct ServiceData { int id; SleepService* sleepService; std::default_random_engine* random; std::uniform_real_distribution<float>* dist; }; constexpr int N = 1000; ServiceData serviceDataAry[N]; lptk::fiber::Task serviceTasks[N]; for (size_t i = 0; i < N; ++i) { ServiceData* serviceData = &serviceDataAry[i]; serviceData->id = int(i); serviceData->sleepService = &sleepService; serviceData->random = &random; serviceData->dist = &dist; serviceTasks[i].Set([](void* p) { ServiceData* serviceData = reinterpret_cast<ServiceData*>(p); const auto id = serviceData->id; { const auto sleepService = serviceData->sleepService; printf("Fiber %d, before sleep.\n", id); const auto beforeTime = Clock::now(); sleepService->Sleep(0.1f + 0.3f * (*serviceData->dist)((*serviceData->random))); const auto timeSince = std::chrono::duration<float>{ Clock::now() - beforeTime }.count(); printf("Fiber %d, after sleep (slept %f).\n", id, timeSince); } }, serviceData); } lptk::fiber::RunTasks(serviceTasks, N, &counter); lptk::fiber::WaitForCounter(&counter); printf("Finished all fiber service fibers.\n"); sleepService.Stop(); } lptk::fiber::Purge(); return 0; }
TEST(GeoLib, SurfaceIsPointInSurface) { std::vector<std::function<double(double, double)>> surface_functions; surface_functions.emplace_back(constant); surface_functions.emplace_back(coscos); for (const auto& f : surface_functions) { std::random_device rd; std::string name("Surface"); // generate ll and ur in random way std::mt19937 random_engine_mt19937(rd()); std::normal_distribution<> normal_dist_ll(-10, 2); std::normal_distribution<> normal_dist_ur(10, 2); MathLib::Point3d ll(std::array<double,3>({{ normal_dist_ll(random_engine_mt19937), normal_dist_ll(random_engine_mt19937), 0.0}})); MathLib::Point3d ur(std::array<double,3>({{ normal_dist_ur(random_engine_mt19937), normal_dist_ur(random_engine_mt19937), 0.0}})); for (std::size_t k(0); k<3; ++k) if (ll[k] > ur[k]) std::swap(ll[k], ur[k]); // random discretization of the domain std::default_random_engine re(rd()); std::uniform_int_distribution<std::size_t> uniform_dist(2, 25); std::array<std::size_t,2> n_steps = {{uniform_dist(re),uniform_dist(re)}}; std::unique_ptr<MeshLib::Mesh> sfc_mesh( MeshLib::MeshGenerator::createSurfaceMesh( name, ll, ur, n_steps, f ) ); // random rotation angles std::normal_distribution<> normal_dist_angles( 0, boost::math::double_constants::two_pi); std::array<double,3> euler_angles = {{ normal_dist_angles(random_engine_mt19937), normal_dist_angles(random_engine_mt19937), normal_dist_angles(random_engine_mt19937) }}; MathLib::DenseMatrix<double, std::size_t> rot_mat(getRotMat( euler_angles[0], euler_angles[1], euler_angles[2])); std::vector<MeshLib::Node*> const& nodes(sfc_mesh->getNodes()); GeoLib::rotatePoints<MeshLib::Node>(rot_mat, nodes); MathLib::Vector3 const normal(0,0,1.0); MathLib::Vector3 const surface_normal(rot_mat * normal); double const scaling(1e-6); MathLib::Vector3 const displacement(scaling * surface_normal); GeoLib::GEOObjects geometries; MeshLib::convertMeshToGeo(*sfc_mesh, geometries); std::vector<GeoLib::Surface*> const& sfcs(*geometries.getSurfaceVec(name)); GeoLib::Surface const*const sfc(sfcs.front()); std::vector<GeoLib::Point*> const& pnts(*geometries.getPointVec(name)); double const eps(std::numeric_limits<double>::epsilon()); // test triangle edge point of the surface triangles for (auto const p : pnts) { EXPECT_TRUE(sfc->isPntInSfc(*p, eps)); MathLib::Point3d q(*p); for (std::size_t k(0); k<3; ++k) q[k] += displacement[k]; EXPECT_FALSE(sfc->isPntInSfc(q, eps)); } // test edge middle points of the triangles for (std::size_t k(0); k<sfc->getNumberOfTriangles(); ++k) { MathLib::Point3d p, q, r; std::tie(p,q,r) = getEdgeMiddlePoints(*(*sfc)[k]); EXPECT_TRUE(sfc->isPntInSfc(p, eps)); EXPECT_TRUE(sfc->isPntInSfc(q, eps)); EXPECT_TRUE(sfc->isPntInSfc(r, eps)); } } }
Spectrum PhotonIntegrator::Li(const Scene *scene, const RayDifferential &ray, const Sample *sample, float *alpha) const { // Compute reflected radiance with photon map Spectrum L(0.); Intersection isect; if (scene->Intersect(ray, &isect)) { if (alpha) *alpha = 1.; Vector wo = -ray.d; // Compute emitted light if ray hit an area light source L += isect.Le(wo); // Evaluate BSDF at hit point BSDF *bsdf = isect.GetBSDF(ray); const Point &p = bsdf->dgShading.p; const Normal &n = bsdf->dgShading.nn; // Compute direct lighting for photon map integrator if (directWithPhotons) L += LPhoton(directMap, nDirectPaths, nLookup, bsdf, isect, wo, maxDistSquared); else L += UniformSampleAllLights(scene, p, n, wo, bsdf, sample, lightSampleOffset, bsdfSampleOffset, bsdfComponentOffset); // Compute indirect lighting for photon map integrator L += LPhoton(causticMap, nCausticPaths, nLookup, bsdf, isect, wo, maxDistSquared); if (finalGather) { // Do one-bounce final gather for photon map Spectrum Li(0.); for (int i = 0; i < gatherSamples; ++i) { // Sample random direction for final gather ray Vector wi; float u1 = sample->twoD[gatherSampleOffset][2*i]; float u2 = sample->twoD[gatherSampleOffset][2*i+1]; float u3 = sample->oneD[gatherComponentOffset][i]; float pdf; Spectrum fr = bsdf->Sample_f(wo, &wi, u1, u2, u3, &pdf, BxDFType(BSDF_ALL & (~BSDF_SPECULAR))); if (fr.Black() || pdf == 0.f) continue; RayDifferential bounceRay(p, wi); static StatsCounter gatherRays("Photon Map", // NOBOOK "Final gather rays traced"); // NOBOOK ++gatherRays; // NOBOOK Intersection gatherIsect; if (scene->Intersect(bounceRay, &gatherIsect)) { // Compute exitant radiance at final gather intersection BSDF *gatherBSDF = gatherIsect.GetBSDF(bounceRay); Vector bounceWo = -bounceRay.d; Spectrum Lindir = LPhoton(directMap, nDirectPaths, nLookup, gatherBSDF, gatherIsect, bounceWo, maxDistSquared) + LPhoton(indirectMap, nIndirectPaths, nLookup, gatherBSDF, gatherIsect, bounceWo, maxDistSquared) + LPhoton(causticMap, nCausticPaths, nLookup, gatherBSDF, gatherIsect, bounceWo, maxDistSquared); Lindir *= scene->Transmittance(bounceRay); Li += fr * Lindir * AbsDot(wi, n) / pdf; } } L += Li / float(gatherSamples); } else L += LPhoton(indirectMap, nIndirectPaths, nLookup, bsdf, isect, wo, maxDistSquared); if (specularDepth++ < maxSpecularDepth) { Vector wi; // Trace rays for specular reflection and refraction Spectrum f = bsdf->Sample_f(wo, &wi, BxDFType(BSDF_REFLECTION | BSDF_SPECULAR)); if (!f.Black()) { // Compute ray differential _rd_ for specular reflection RayDifferential rd(p, wi); rd.hasDifferentials = true; rd.rx.o = p + isect.dg.dpdx; rd.ry.o = p + isect.dg.dpdy; // Compute differential reflected directions Normal dndx = bsdf->dgShading.dndu * bsdf->dgShading.dudx + bsdf->dgShading.dndv * bsdf->dgShading.dvdx; Normal dndy = bsdf->dgShading.dndu * bsdf->dgShading.dudy + bsdf->dgShading.dndv * bsdf->dgShading.dvdy; Vector dwodx = -ray.rx.d - wo, dwody = -ray.ry.d - wo; float dDNdx = Dot(dwodx, n) + Dot(wo, dndx); float dDNdy = Dot(dwody, n) + Dot(wo, dndy); rd.rx.d = wi - dwodx + 2 * Vector(Dot(wo, n) * dndx + dDNdx * n); rd.ry.d = wi - dwody + 2 * Vector(Dot(wo, n) * dndy + dDNdy * n); L += scene->Li(rd, sample) * f * AbsDot(wi, n); } f = bsdf->Sample_f(wo, &wi, BxDFType(BSDF_TRANSMISSION | BSDF_SPECULAR)); if (!f.Black()) { // Compute ray differential _rd_ for specular transmission RayDifferential rd(p, wi); rd.hasDifferentials = true; rd.rx.o = p + isect.dg.dpdx; rd.ry.o = p + isect.dg.dpdy; float eta = bsdf->eta; Vector w = -wo; if (Dot(wo, n) < 0) eta = 1.f / eta; Normal dndx = bsdf->dgShading.dndu * bsdf->dgShading.dudx + bsdf->dgShading.dndv * bsdf->dgShading.dvdx; Normal dndy = bsdf->dgShading.dndu * bsdf->dgShading.dudy + bsdf->dgShading.dndv * bsdf->dgShading.dvdy; Vector dwodx = -ray.rx.d - wo, dwody = -ray.ry.d - wo; float dDNdx = Dot(dwodx, n) + Dot(wo, dndx); float dDNdy = Dot(dwody, n) + Dot(wo, dndy); float mu = eta * Dot(w, n) - Dot(wi, n); float dmudx = (eta - (eta*eta*Dot(w,n))/Dot(wi, n)) * dDNdx; float dmudy = (eta - (eta*eta*Dot(w,n))/Dot(wi, n)) * dDNdy; rd.rx.d = wi + eta * dwodx - Vector(mu * dndx + dmudx * n); rd.ry.d = wi + eta * dwody - Vector(mu * dndy + dmudy * n); L += scene->Li(rd, sample) * f * AbsDot(wi, n); } } --specularDepth; } else { // Handle ray with no intersection if (alpha) *alpha = 0.; for (u_int i = 0; i < scene->lights.size(); ++i) L += scene->lights[i]->Le(ray); if (alpha && !L.Black()) *alpha = 1.; return L; } return L; }
// Initialize the RNG engine void RNG::Init(){ rnd = std::default_random_engine(rd()); };
int main(int argc, char** argv){ std::random_device rd; std::mt19937 mt(rd()); std::uniform_real_distribution<> dist(0,100); double pct; //pct= dist(mt); double thresh; char starType=argv[1][0]; int num [5] = {0,0,0,0,0}; Planet* planets[5]; switch (starType){ case 'A': break; case 'B': thresh = 2; for (int i=0; i<5; i++){ pct = dist(mt); if (pct<thresh){ //HIT //planets[i] = new Planet(); thresh = thresh*0.9; num[i]++; } else{ planets[i] = nullptr; thresh=thresh*2.5; } } break; case 'F': for (int j=0;j<1000000; j++){ thresh = 20; for (int i=0; i<5; i++){ pct = dist(mt); if (pct<thresh){ //HIT //planets[i] = new Planet(); thresh = thresh/2; num[i]++; } else{ planets[i] = nullptr; thresh=thresh+10; } } } break; case 'G': thresh = 20; for (int i=0; i<5; i++){ pct = dist(mt); if (pct<thresh){ //HIT //planets[i] = new Planet(); thresh = thresh/3; num[i]++; } else{ planets[i] = nullptr; thresh=thresh+15; } } break; case 'K': break; case 'M': break; case 'O': for (int i=0; i<5; i++) { planets[i] = nullptr; } break; default: return 0; } for (int i=0; i<5; i++){ cout << "Planet " << i << ": " ; cout << num[i] << " (" << num[i]/10000.0 << "%)" << endl; /*if (planets[i]==nullptr){ cout << "N/A" << endl; } else{ //planets[i]->printPlanet(); cout << planets[i]->getTypeString() << endl; delete planets[i]; }*/ } return 0; }
// Returns a random double between min and max, // default parameters are DBL_MIN and DBL_MAX double RNG::randDouble(double min, double max){ rnd = std::default_random_engine(rd()); std::uniform_real_distribution<double> dbl(min,max); return dbl(rnd); };
void Random::Init() { std::random_device rd; Random::Seed(rd()); }
float SAHer::Objective(const cv::Rect &roi) { float wg = .98, wt = 1 - wg; int blur_range = 11; cv::Point lu(std::max(0, roi.x - 2*blur_range), std::max(0, roi.y - 2*blur_range)), rd(std::min(w_, roi.x + roi.width + 2*blur_range), std::min(h_, roi.y + roi.height + 2*blur_range)); cv::Point offset1(blur_range, blur_range); if ( roi.x - blur_range < 0) { offset1.x = 0; } else if (roi.x - blur_range*2 < 0) { offset1.x = roi.x - blur_range; } if ( roi.y - blur_range < 0) { offset1.y = 0; } else if (roi.y - blur_range*2 < 0) { offset1.y = roi.y - blur_range; } cv::Rect new_roi(lu, rd); cv::Mat src_roi = src_image_(new_roi), halftone_roi = halftone_image_(new_roi); cv::Rect sub_roi = cv::Rect(offset1.x, offset1.y, std::min(roi.width + 2*blur_range, new_roi.width - offset1.x), std::min(roi.height + 2*blur_range, new_roi.height - offset1.y)); //info() << "begin" << roi.x << roi.y << roi.width << roi.height << offset1.x << offset1.y << new_roi.x << new_roi.y << new_roi.width << new_roi.height; cv::Mat ssim_map = ssim(src_roi, halftone_roi)(sub_roi); //info () << "end"; float mean_ssim = float(cv::mean(ssim_map)[0]); cv::Mat gI, gH, se; cv::GaussianBlur(src_roi, gI, cv::Size(blur_range, blur_range), 0); cv::GaussianBlur(halftone_roi, gH, cv::Size(blur_range, blur_range), 0); cv::subtract(gI(sub_roi), gH(sub_roi), se); cv::multiply(se, se, se); float gaussian_diff = float(cv::mean(se)[0]); return wg*gaussian_diff + wt*(1.f - mean_ssim); }
ParticleFilter::ParticleFilter() : particles(particleCount){ std::random_device rd; rnd = std::mt19937(rd()); // Seed randomizeParticles(); }
void RandomCreator::init() { std::random_device rd; mRandom.seed(rd()); }
int main() { std::random_device rd; std::mt19937 gen(rd()); auto rngC = [&](){ return random_value<uint8_t>(gen); }; auto rngD = [&](){ return random_value<double>(gen); }; const bool randomize = false; //######################################## auto vectorDoubleTest = [&](size_t s, bool randomize_) { std::ostringstream name; name << "Vector(double) size " << s; std::vector<double> data(s); if(randomize_) for( auto & d : data ) d = rngD(); test<binary>( name.str(), data ); }; vectorDoubleTest(1, randomize); // 8B vectorDoubleTest(16, randomize); // 128B vectorDoubleTest(1024, randomize); // 8KB vectorDoubleTest(1024*1024, randomize); // 8MB //######################################## auto vectorCharTest = [&](size_t s, bool randomize_) { std::ostringstream name; name << "Vector(uint8_t) size " << s; std::vector<uint8_t> data(s); if(randomize_) for( auto & d : data ) d = rngC(); test<binary>( name.str(), data ); }; vectorCharTest(1024*1024*64, randomize); //######################################## auto vectorPoDStructTest = [&](size_t s) { std::ostringstream name; name << "Vector(PoDStruct) size " << s; std::vector<PoDStructCereal> dataC(s); std::vector<PoDStructBoost> dataB(s); test<binary>( name.str(), dataC, dataB ); }; vectorPoDStructTest(1); vectorPoDStructTest(64); vectorPoDStructTest(1024); vectorPoDStructTest(1024*1024); vectorPoDStructTest(1024*1024*2); //######################################## auto vectorPoDChildTest = [&](size_t s) { std::ostringstream name; name << "Vector(PoDChild) size " << s; std::vector<PoDChildCereal> dataC(s); std::vector<PoDChildBoost> dataB(s); test<binary>( name.str(), dataC, dataB ); }; vectorPoDChildTest(1024); vectorPoDChildTest(1024*32); //######################################## auto stringTest = [&](size_t s) { std::ostringstream name; name << "String size " << s; std::string data = random_basic_string<char>(gen, s); std::cout << "data.size " << data.size() << std::endl; test<binary>( name.str(), data ); }; stringTest(200000); stringTest(2000000); stringTest(20000000); //######################################## auto vectorStringTest = [&](size_t s) { std::ostringstream name; name << "Vector(String) size " << s; std::vector<std::string> data(s); for(size_t i=0; i<data.size(); ++i) data[i] = random_basic_string<char>(gen); test<binary>( name.str(), data ); }; vectorStringTest(512); vectorStringTest(1024); vectorStringTest(1024*64); vectorStringTest(1024*128); //######################################## auto mapPoDStructTest = [&](size_t s) { std::ostringstream name; name << "Map(PoDStruct) size " <<s; std::map<std::string, PoDStructCereal> mC; std::map<std::string, PoDStructBoost> mB; for(size_t i=0; i<s; ++i) { mC[std::to_string( i )] = PoDStructCereal(); mB[std::to_string( i )] = PoDStructBoost(); } test<binary>(name.str(), mC, mB); }; mapPoDStructTest(1024); mapPoDStructTest(1024*64); return 0; }
//------------------------------------------------------------------- bool test_rebalance_epetra_linproblem2(int numProcs, int localProc, bool verbose) { bool test_passed = false; #ifndef HAVE_MPI return(test_passed); #endif Epetra_CrsMatrix* input_matrix = create_epetra_test_matrix_1(numProcs, localProc, verbose); Epetra_Vector* x = new Epetra_Vector(input_matrix->RowMap()); Epetra_Vector* b = new Epetra_Vector(input_matrix->RowMap()); Epetra_LinearProblem problem(input_matrix, x, b); Teuchos::ParameterList paramlist; //Wrap a RefCountPtr around the matrix graph, and specify 'false', meaning //that the RefCountPtr will not take ownership of the graph (will not //delete it). Teuchos::RefCountPtr<const Epetra_CrsGraph> graph = Teuchos::rcp( &(input_matrix->Graph()), false); Teuchos::RefCountPtr<Isorropia::Epetra::Partitioner> partitioner = Teuchos::rcp(new Isorropia::Epetra::Partitioner(graph, paramlist)); Isorropia::Epetra::Redistributor rd(partitioner); Teuchos::RefCountPtr<Epetra_CrsMatrix> bal_matrix = rd.redistribute(*(problem.GetMatrix())); Teuchos::RefCountPtr<Epetra_MultiVector> bal_x = rd.redistribute(*(problem.GetLHS())); Teuchos::RefCountPtr<Epetra_MultiVector> bal_b = rd.redistribute(*(problem.GetRHS())); Teuchos::RefCountPtr<Epetra_LinearProblem> balanced_problem = Teuchos::rcp(new Epetra_LinearProblem(bal_matrix.get(), bal_x.get(), bal_b.get())); //Now check the result matrix and make sure that the number of nonzeros //is indeed equal on each processor. (We constructed the input matrix //so that a correct rebalancing would result in the same number of //nonzeros being on each processor.) const Epetra_Map& bal_rowmap = balanced_problem->GetMatrix()->RowMatrixRowMap(); int bal_local_num_rows = bal_rowmap.NumMyElements(); //count the local nonzeros. if (verbose) { std::cout << "test_rebalance_epetra_linproblem: " << std::endl; std::cout << " counting local nnz for balanced matrix..." << std::endl; } int num_nonzeros = 0; for(int i=0; i<bal_local_num_rows; ++i) { int numrowentries = 0; balanced_problem->GetMatrix()->NumMyRowEntries(i,numrowentries); num_nonzeros += numrowentries; } const Epetra_Comm& comm = input_matrix->Comm(); int global_num_nonzeros; comm.SumAll(&num_nonzeros, &global_num_nonzeros, 1); int avg_nnz_per_proc = global_num_nonzeros/numProcs; if (verbose) { std::cout << " making sure local nnz ("<<num_nonzeros <<") is the same on every proc...\n" << std::endl; } if (num_nonzeros == avg_nnz_per_proc) test_passed = true; int local_int_result = test_passed ? 1 : 0; int global_int_result; comm.MinAll(&local_int_result, &global_int_result, 1); test_passed = global_int_result==1 ? true : false; if (!test_passed && verbose) { std::cout << "test FAILED!" << std::endl; } delete input_matrix; delete x; delete b; return(test_passed); }
/** * @brief Rss 2.0 parsing * @param xml input string * @param data output data */ void Rss20Parser::parseRss(const QString& xml, QList<TRssItem>& data){ QXmlStreamReader rd(xml); //support variables QString elemName; TRssChanel channel; TRssItem item; int state = 0; //default channel values channel.desc = QString(); channel.link = QString(); channel.title = QString(); channel.version = Rss20; channel.image.link = QString(); channel.image.title = QString(); channel.image.url = QString(); //parsing file while(!rd.atEnd()){ switch(rd.readNext()){ case QXmlStreamReader::StartElement: elemName = rd.name().toString(); //image parsing if(state == 0 && elemName == "image"){ state = 1; } //item parsing else if(state == 0 && elemName == "item"){ //empty item item.desc = QString(); item.dt = QDateTime(); item.guid = QString(); item.link = QString(); item.channel = channel; item.title = QString(); //state for item parsing state = 2; } break; case QXmlStreamReader::EndElement: elemName = ""; //image parsing if(rd.name() == "image"){ state = 0; } //item parsing else if(rd.name() == "item"){ data.append(item); state = 0; } break; case QXmlStreamReader::Characters: if(elemName.isEmpty()) break; //channel description if(state == 0){ if(elemName == "description") channel.desc = rd.text().toString().trimmed(); else if(elemName == "link") channel.link = rd.text().toString(); else if(elemName == "title") channel.title = rd.text().toString(); } //channel image if(state == 1){ if(elemName == "title") channel.image.title = rd.text().toString(); else if(elemName == "link") channel.image.link = rd.text().toString(); else if(elemName == "url") channel.image.url = rd.text().toString(); } //item parsing if(state == 2){ if(elemName == "title") item.title = rd.text().toString(); else if(elemName == "description") item.desc = rd.text().toString(); else if(elemName == "link") item.link = rd.text().toString(); else if(elemName == "guid") item.guid = rd.text().toString(); else if(elemName == "pubDate") item.dt = parseDateTime(rd.text().toString()); } default: break; } } }