void App::InitScene( int width, int height ) { Renderer* renderer = dynamic_cast<Renderer*>(m_Worker.get()); BOOST_ASSERT(renderer); renderer->Init(); std::vector< BrushPtr > brushes; brushes.push_back( LoadBrush<BmpBrush>("FireBase.bmp") ); brushes.push_back( LoadBrush<TgaBrush>("lightmap.tga") ); brushes.push_back( LoadBrush<TgaBrush>("FieldstoneNoisy.tga") ); brushes.push_back( LoadBrush<DdsBrush>("MetalDecoB.dds") ); //////////////////////////////////////////////////////////////////////////// // Compose our scene // Add a viewport EntityPtr viewport(new Viewport(width, height)); // this entity renders renderer->AddEntity(viewport); // listen to resize events m_EntityEventHandlerList.push_back( viewport ); // Add the camera EntityPtr camera(new Camera(m_Joystick)); // this entity handles events m_EntityEventHandlerList.push_back( camera ); // this entity renders viewport->AddEntity(camera, 0); EntityPtr flag( new Surface( brushes ) ); flag->GetRenderState()->Translate( Vector(0.0, 0, 0), Vector(1.0f, 1.0f, 1.0f) ); flag->GetRenderState()->Rotate( Vector(-90.0f, 0.0f, 0.0f ) ); // this entity renders camera->AddEntity(flag, 20 ); // some custom event handler m_EventHandlerList.push_back( boost::bind( &OnHandleEvent, _1, flag ) ); }
bool exist(vector<vector<char>>& board, string word) { int m = board.size(); int word_len = word.size(); if(!m || !word_len) return false; int n = board[0].size(); vector<vector<bool>> flag(m); for(int i=0; i<m; i++) flag[i].assign(n, false); list<char> temp(word.begin(), word.end()); for(int i=0; i<m; i++) for(int j=0; j<n; j++) { if(flag[i][j]) continue; if(dfs(board, flag, temp, i, j)) return true; } return false; }
static PyObject* PyView_flatten(PyView *o, PyObject *_args, PyObject *_kwargs) { try { PWOSequence args(_args); PWOMapping kwargs; if (_kwargs) kwargs = PWOBase(_kwargs); if (!PyProperty_Check((PyObject*)args[0])) Fail(PyExc_TypeError, "First arg must be a property object identifying the subview"); const c4_Property& subview = *(PyProperty *)(PyObject* )args[0]; bool outer = false; if (args.len() > 1) { PWONumber flag(args[1]); if ((int)flag > 0) outer = true; } if (kwargs.hasKey("outer")) { if (int(PWONumber(kwargs["outer"]))) outer = true; } return new PyView (o->JoinProp((const c4_ViewProp&) subview, outer), 0, o->computeState(ROVIEWER)); } catch (...) { return 0; } }
void InventoryItem::SaveItem() { //_log( ITEM__TRACE, "Saving item %u.", itemID() ); //mAttributeMap.Save(); SaveAttributes(); m_factory.db().SaveItem( itemID(), ItemData( itemName().c_str(), typeID(), ownerID(), locationID(), flag(), contraband(), singleton(), quantity(), position(), customInfo().c_str() ) ); }
TEST(SegmentArray, PackSegments) { CudppPlanFactory planPool; SegmentArray<int> a(&planPool, 30); for (int i = 0; i != a.getSize(); i++) { a[i] = i; } a.getSegments()[15] = 1; a.segmentsChanged(); MirroredArray<uint> flag(30); memset(flag.getPtr(), 0, sizeof(uint) * flag.getSize()); flag[0] = 1; flag[10] = 1; flag[15] = 1; flag[20] = 1; flag[21] = 1; flag[27] = 1; flag[25] = 1; SegmentArray<int> packedArray(&planPool, 0); a.packByFlag(flag, packedArray); EXPECT_EQ(packedArray[2], 15); EXPECT_EQ(packedArray[3], 20); EXPECT_EQ(packedArray.getSegmentIndex(0), 0); EXPECT_EQ(packedArray.getSegmentIndex(1), 0); EXPECT_EQ(packedArray.getSegmentIndex(2), 1); EXPECT_EQ(packedArray.getSegmentLength(0), 2); EXPECT_EQ(packedArray.getSegmentLength(1), 5); }
int main(void) { /* declare local vars */ int x,y; /* Sets position */ x = 3; y = 0; /* seeds random */ srand((int)time(NULL)); /* clear screen and home cursor */ printf(CLRSCR); printf(POSXY, 0, 0); elephant(25,3); flag(2,2); /* display credits */ animate_credits_type(8, 6, "Circus Fun!!!"); // animate_credits_from_left(x+37, y+7, 5, credits[0]); // animate_credits_from_left(x+38, y+8, 10, credits[1]); // animate_credits_from_top(x+42, 1, y+19, credits[2]); // usleep(DELAY*10); // animate_credits_from_left(x+42, y+19, strlen(credits[2]), " "); // animate_credits_type(x+45, y+9, "Happy"); // animate_credits_type(x+50, y+11, "Halloween"); // /* Home cursor */ printf(COLOR_RESET); printf(HOME); fflush(stdout); /* ends function */ return(0); }
void action(struct map *map) { int tmp; printf("What do you want to do ?\n" "\t1) Abandon\n" "\t2) Set a flag\n" "\t3) Erase a flag\n" "\t4) Explore a cell\n" "\t5) Quit\n\t"); scanf("%d", &tmp); if(tmp == 1) abandon(); else if(tmp == 2) flag(map); else if(tmp == 3) unflag(map); else if(tmp == 4) explore(map); else if(tmp == 5) quit(map); #if defined CHEAT_ALLOWED else if(tmp == 16012006) display_map_debug(map); #endif }
void WeightMatrix_iter::find_large_degree(std::vector<unsigned int>& ridx){ std::multimap<double, unsigned int> sorted_degree; for(size_t ii=0; ii < _nrows ; ii++){ sorted_degree.insert(std::make_pair(_degree[ii], ii)); } std::vector<unsigned int> flag(_nrows, 0); std::multimap<double, unsigned int>::reverse_iterator sit = sorted_degree.rbegin(); for(; sit!= sorted_degree.rend(); sit++){ unsigned int sidx = sit->second; if (!flag[sidx]){ flag[sidx] = 1; ridx.push_back(sidx); std::vector<RowVal>& nbr_wts = _wtmat[sidx]; for(size_t ii=0; ii < nbr_wts.size(); ii++ ){ unsigned int sjdx = nbr_wts[ii].j; flag[sjdx] = 2; } } } }
TEST(CrvFunctionalTest, SatStack) { constexpr unsigned N = 5; crv::tracer().reset(); crv::Encoder encoder; crv::Mutex mutex; crv::External<unsigned int> top(0U); crv::External<int> flag(0); bool error = false; do { crv::Thread t0(sat_stack_t0, N, mutex, top, flag); crv::Thread t1(sat_stack_t1, N, mutex, top, flag); if (!crv::tracer().errors().empty() && smt::sat == encoder.check(crv::tracer())) error = true; } while (crv::tracer().flip()); EXPECT_TRUE(error); }
sqInt setMicroSecondsandOffset(sqLong * microSeconds, int * utcOffset) { flag("toRemove"); return -1; }
void Strand2dFCBlockMesh::initialize(const int& level0, const int& meshOrder0, const int& nSurfElem0, const int& nSurfNodeG, const int& nBndNode0, const int& nStrandNodeG, const int& nCompBd0, int** surfElemG, const Array1D<int>& bndNodeG, const Array2D<double>& surfXG, const Array1D<double>& strandXG, const Array1D<int>& surfElemTagG, const Array1D<int>& bndNodeTagG, const Array2D<double>& bndNodeNormalG) { // copy dimensions for this block level = level0; meshOrder = meshOrder0; nSurfElem = nSurfElem0; nBndNode = nBndNode0; nCompBd = nCompBd0; // allocate space for the mesh data, and copy the known data surfElem.allocate(nSurfElem,meshOrder+1); surfElemTag.allocate(nSurfElem); bndNode.allocate(nBndNode); bndNodeTag.allocate(nBndNode); bndNodeNormal.allocate(nBndNode,2); for (int n=0; n<nSurfElem; n++) surfElemTag(n) = surfElemTagG(n); for (int n=0; n<nBndNode; n++){ bndNodeTag(n) = bndNodeTagG(n); bndNodeNormal(n,0) = bndNodeNormalG(n,0); bndNodeNormal(n,1) = bndNodeNormalG(n,1); } // form surface elements of the desired order, count surface nodes int n1,n2; Array1D<int> flag(nSurfNodeG); flag.set(-1); nSurfNode = 0; for (int n=0; n<nSurfElem; n++){ //add element end points first n1 = surfElemG[n][1]; n2 = surfElemG[n][2]; if (flag(n1) == -1) flag(n1) = nSurfNode++; if (flag(n2) == -1) flag(n2) = nSurfNode++; surfElem(n,0) = flag(n1); surfElem(n,1) = flag(n2); } for (int n=0; n<nSurfElem; n++) //add interior dofs next for (int j=2; j<meshOrder+1; j++) surfElem(n,j) = nSurfNode++; // point the bndNode array to the new node numbers for (int n=0; n<nBndNode; n++) bndNode(n) = flag(bndNodeG(n)); // find surface mesh coordinates based on mappings from the mesh file Array1D<double> ss(meshOrder+1); int spacing=0; // assume equal spacing for now solutionPoints1D(meshOrder, //find s-locations based on desired spacing spacing, &ss(0)); surfX.allocate(nSurfNode,2); surfX.set(0.); bool test=false; int orderM; double lm; Array1D<double> sM; Array2D<double> lcM; flag.deallocate(); flag.allocate(nSurfNode); flag.set(-1); for (int n=0; n<nSurfElem; n++){ orderM = surfElemG[n][0]; // s-locations using numbering consistent with the mesh sM.allocate(orderM+1); solutionPoints1D(orderM, spacing, &sM(0)); // lagrange polynomials at the sM locations lcM.allocate(orderM+1,orderM+1); lagrangePoly1D(test, orderM, &sM(0), &lcM(0,0)); // evaluate the x-coordinates at the local solution points for (int i=0; i<meshOrder+1; i++) //ith local point if (flag(surfElem(n,i)) == -1){//haven't computed this location yet for (int m=0; m<orderM+1; m++){ //mth Lagrange poly. used in mapping lm = 0.; for (int k=0; k<orderM+1; k++) lm += pow(ss(i),k)*lcM(m,k); surfX(surfElem(n,i),0) += lm*surfXG(surfElemG[n][m+1],0); surfX(surfElem(n,i),1) += lm*surfXG(surfElemG[n][m+1],1); } flag(surfElem(n,i)) = 0; } sM.deallocate(); lcM.deallocate(); } // generate pointing vectors // first find surface mapping based on global mesh Array2D<double> xS(nSurfElem,meshOrder+1),yS(nSurfElem,meshOrder+1); xS.set(0.); yS.set(0.); int ni,nm; Array2D<double> lsM; for (int n=0; n<nSurfElem; n++){ orderM = surfElemG[n][0]; // s-locations using numbering consistent with the mesh sM.allocate(orderM+1); solutionPoints1D(orderM, spacing, &sM(0)); // lagrange polynomials at the sM locations lcM.allocate(orderM+1,orderM+1); lagrangePoly1D(test, orderM, &sM(0), &lcM(0,0)); // ls(i,j) = (dl_j/ds)_i (a row is all Lagrange polynomials (derivatives) // evaluated at a single mesh point i) lsM.allocate(meshOrder+1,orderM+1); lsM.set(0.); int km; for (int i=0; i<meshOrder+1; i++) // ith mesh point for (int j=0; j<orderM+1; j++) // jth Lagrange polynomial for (int k=0; k<orderM+1; k++){ km = max(0,k-1); lsM(i,j) +=((double)k)*pow(ss(i),km)*lcM(j,k); } for (int n=0; n<nSurfElem; n++) for (int i=0; i<meshOrder+1; i++) //ith point in the element for (int m=0; m<orderM+1; m++){ //mth Lagrange poly. in mapping xS(n,i) += lsM(i,m)*surfXG(surfElemG[n][m+1],0); yS(n,i) += lsM(i,m)*surfXG(surfElemG[n][m+1],1); } sM.deallocate(); lcM.deallocate(); } // initialize all pointing vectors // using the surface mapping (averaged among neighboring elements) pointingVec.allocate(nSurfNode,2); pointingVec.set(0.); int m; double nx,ny,ds,rms; for (int n=0; n<nSurfElem; n++) for (int i=0; i<meshOrder+1; i++){ m = surfElem(n,i); nx =-yS(n,i); ny = xS(n,i); ds = 1./sqrt(nx*nx+ny*ny); nx *= ds; ny *= ds; //////////////////////////////////////////////////////////////////////// //~ change the 2 comment lines below with code lines to have normal //~ pointing vectors instead of verticle pointing vectors //~ pointingVec(m,0) += nx; //~ pointingVec(m,1) += ny; pointingVec(m,0) = 0.; //shaun change pointingVec(m,1) = 1.; } for (int n=0; n<nSurfNode; n++){ ds = 1./sqrt(pointingVec(n,0)*pointingVec(n,0)+ pointingVec(n,1)*pointingVec(n,1)); pointingVec(n,0) *= ds; pointingVec(n,1) *= ds; } // smooth the strands interior to elements iteratively int* psp1; int** psp2; psp1 = new int[meshOrder+1]; psp2 = new int*[meshOrder+1]; if (meshOrder == 1){ psp1[0] = 1; psp1[1] = 1; psp2[0] = new int[psp1[0]]; psp2[0][0] = 1; psp2[1] = new int[psp1[1]]; psp2[1][0] = 0; } else if (meshOrder == 2){ psp1[0] = 1; psp1[1] = 1; psp1[2] = 2; psp2[0] = new int[psp1[0]]; psp2[0][0] = 2; psp2[1] = new int[psp1[1]]; psp2[1][0] = 2; psp2[2] = new int[psp1[2]]; psp2[2][0] = 0; psp2[2][1] = 1; } else if (meshOrder == 3){ psp1[0] = 1; psp1[1] = 1; psp1[2] = 2; psp1[3] = 2; psp2[0] = new int[psp1[0]]; psp2[0][0] = 2; psp2[1] = new int[psp1[1]]; psp2[1][0] = 3; psp2[2] = new int[psp1[2]]; psp2[2][0] = 0; psp2[2][1] = 3; psp2[3] = new int[psp1[3]]; psp2[3][0] = 2; psp2[3][1] = 1; } else if (meshOrder == 4){ psp1[0] = 1; psp1[1] = 1; psp1[2] = 2; psp1[3] = 2; psp1[4] = 2; psp2[0] = new int[psp1[0]]; psp2[0][0] = 2; psp2[1] = new int[psp1[1]]; psp2[1][0] = 4; psp2[2] = new int[psp1[2]]; psp2[2][0] = 0; psp2[2][1] = 3; psp2[3] = new int[psp1[3]]; psp2[3][0] = 2; psp2[3][1] = 4; psp2[4] = new int[psp1[4]]; psp2[4][0] = 3; psp2[4][1] = 1; } else{ cout << "\nPlease choose meshOrder=3 or less." << endl; exit(0); } if (meshOrder > 1) for (int n=0; n<nSurfElem; n++) for (int iter=0; iter<1000; iter++){ rms = 0.; for (int i=2; i<meshOrder+1; i++){ ni = surfElem(n,i); nx = 0.; ny = 0.; for (int m=0; m<psp1[i]; m++){ nm = surfElem(n,psp2[i][m]); nx += pointingVec(nm,0); ny += pointingVec(nm,1); } ds = 1./sqrt(nx*nx+ny*ny); nx *= ds; ny *= ds; rms += (nx-pointingVec(ni,0))*(nx-pointingVec(ni,0))+ (ny-pointingVec(ni,1))*(ny-pointingVec(ni,1)); pointingVec(ni,0) = nx; pointingVec(ni,1) = ny; } rms = sqrt(rms/(double)(meshOrder-1)); if (rms < 1.e-13) break; } /* for (int n=0; n<nSurfNode; n++){ pointingVec(n,0) = 0.; pointingVec(n,1) = 1.; } */ // determine strand node distribution int ks=nStrandNodeG-1,js=pow(2,level); if (ks%js != 0){ cout << "\n***Number of strand nodes not a good multigrid number.***" << endl; exit(0); } nStrandNode =(nStrandNodeG-1)/pow(2,level); nStrandNode++; strandX.allocate(nStrandNode); int i=0; for (int j=0; j<nStrandNode; j++){ strandX(j) = strandXG(i); i += pow(2,level); } // generate clipping index clip.allocate(nSurfNode); clip.set(nStrandNode-1); // report mesh statistics if (level == 0){ cout.setf(ios::scientific); cout << "\nMesh statistics: " << endl << "Number of surface elements: " << nSurfElem << endl << "Number of surface nodes: " << nSurfNode << endl << "Number of boundary nodes: " << nBndNode << endl << "Number of boundary comp.: " << nCompBd << endl << "Number of strand nodes: " << nStrandNode << endl; cout << "\nstrand distribution:"; for (int n=0; n<nStrandNode; n++) cout << "\n" << n << "\t" << strandX(n); cout << "\nwall spacing: " << strandX(1) << "\ntip spacing: " << strandX(nStrandNode-1)-strandX(nStrandNode-2) << "\n" << endl; } // clean up if (psp1){ delete [] psp1; psp1 = NULL; } if (psp2){ for (int i=0; i<meshOrder+1; i++) if (psp2[i]){ delete [] psp2[i]; psp2[i] = NULL; } delete [] psp2; psp2 = NULL; } xS.deallocate(); yS.deallocate(); lcM.deallocate(); lsM.deallocate(); sM.deallocate(); ss.deallocate(); flag.deallocate(); }
// Adds sub-pixel resolution EdgeOffsets for the outline if the supplied // pix is 8-bit. Does nothing otherwise. // Operation: Consider the following near-horizontal line: // _________ // |________ // |________ // At *every* position along this line, the gradient direction will be close // to vertical. Extrapoaltion/interpolation of the position of the threshold // that was used to binarize the image gives a more precise vertical position // for each horizontal step, and the conflict in step direction and gradient // direction can be used to ignore the vertical steps. void C_OUTLINE::ComputeEdgeOffsets(int threshold, Pix* pix) { if (pixGetDepth(pix) != 8) return; const l_uint32* data = pixGetData(pix); int wpl = pixGetWpl(pix); int width = pixGetWidth(pix); int height = pixGetHeight(pix); bool negative = flag(COUT_INVERSE); delete [] offsets; offsets = new EdgeOffset[stepcount]; ICOORD pos = start; ICOORD prev_gradient; ComputeGradient(data, wpl, pos.x(), height - pos.y(), width, height, &prev_gradient); for (int s = 0; s < stepcount; ++s) { ICOORD step_vec = step(s); TPOINT pt1(pos); pos += step_vec; TPOINT pt2(pos); ICOORD next_gradient; ComputeGradient(data, wpl, pos.x(), height - pos.y(), width, height, &next_gradient); // Use the sum of the prev and next as the working gradient. ICOORD gradient = prev_gradient + next_gradient; // best_diff will be manipulated to be always positive. int best_diff = 0; // offset will be the extrapolation of the location of the greyscale // threshold from the edge with the largest difference, relative to the // location of the binary edge. int offset = 0; if (pt1.y == pt2.y && abs(gradient.y()) * 2 >= abs(gradient.x())) { // Horizontal step. diff_sign == 1 indicates black above. int diff_sign = (pt1.x > pt2.x) == negative ? 1 : -1; int x = MIN(pt1.x, pt2.x); int y = height - pt1.y; int best_sum = 0; int best_y = y; EvaluateVerticalDiff(data, wpl, diff_sign, x, y, height, &best_diff, &best_sum, &best_y); // Find the strongest edge. int test_y = y; do { ++test_y; } while (EvaluateVerticalDiff(data, wpl, diff_sign, x, test_y, height, &best_diff, &best_sum, &best_y)); test_y = y; do { --test_y; } while (EvaluateVerticalDiff(data, wpl, diff_sign, x, test_y, height, &best_diff, &best_sum, &best_y)); offset = diff_sign * (best_sum / 2 - threshold) + (y - best_y) * best_diff; } else if (pt1.x == pt2.x && abs(gradient.x()) * 2 >= abs(gradient.y())) { // Vertical step. diff_sign == 1 indicates black on the left. int diff_sign = (pt1.y > pt2.y) == negative ? 1 : -1; int x = pt1.x; int y = height - MAX(pt1.y, pt2.y); const l_uint32* line = pixGetData(pix) + y * wpl; int best_sum = 0; int best_x = x; EvaluateHorizontalDiff(line, diff_sign, x, width, &best_diff, &best_sum, &best_x); // Find the strongest edge. int test_x = x; do { ++test_x; } while (EvaluateHorizontalDiff(line, diff_sign, test_x, width, &best_diff, &best_sum, &best_x)); test_x = x; do { --test_x; } while (EvaluateHorizontalDiff(line, diff_sign, test_x, width, &best_diff, &best_sum, &best_x)); offset = diff_sign * (threshold - best_sum / 2) + (best_x - x) * best_diff; } offsets[s].offset_numerator = static_cast<inT8>(ClipToRange(offset, -MAX_INT8, MAX_INT8)); offsets[s].pixel_diff = static_cast<uinT8>(ClipToRange(best_diff, 0 , MAX_UINT8)); if (negative) gradient = -gradient; // Compute gradient angle quantized to 256 directions, rotated by 64 (pi/2) // to convert from gradient direction to edge direction. offsets[s].direction = Modulo(FCOORD::binary_angle_plus_pi(gradient.angle()) + 64, 256); prev_gradient = next_gradient; } }
void CFG::eliminateEpsilonProductions() { findNullableSymbols(); for(size_t i = 0; i < p.size(); ++i) { vector<string> ns; for(size_t j = 0; j < p[i].right.size(); ++j) { if(in(p[i].right[j], nullableSymbols)) { ns.push_back(p[i].right[j]); } } vector<bool> flag(ns.size()); size_t j = 0; if(ns.size() == p[i].right.size()) { j = 1; } for(; j < ns.size(); ++j) // j represents number of nullable symbols to be present { flag.clear(); fill(flag.begin(), flag.end() - ns.size() + j, true); do { vector<string> presentNullableSymbols; for(size_t k = 0; k < ns.size(); ++k) { if(flag[k]) { presentNullableSymbols.push_back(ns[i]); } } bool exist = false; for(size_t k = 0; k < p.size(); ++k) { if(p[k].left == p[i].left && p[k].right == presentNullableSymbols) { exist = true; break; } } if(!exist) { p.push_back(Production(p[i].left, presentNullableSymbols)); } }while(prev_permutation(flag.begin(), flag.end())); } } if(in(s, nullableSymbols)) { bool exist = false; for(size_t i = 0; i < p.size(); ++i) { if(p[i].left == s && p[i].right.size() == 1 && p[i].right[0] == "") { exist = true; break; } } if(!exist) { p.push_back(Production(s, {""})); } } }
void DL_my_algo_PacketScheduler2::RBsAllocation () { #ifdef SCHEDULER_DEBUG std::cout << " ---- DL_my_algo_PacketScheduler2::my_algo"; #endif FlowsToSchedule* flows = GetFlowsToSchedule (); int nbOfRBs = GetMacEntity ()->GetDevice ()->GetPhy ()->GetBandwidthManager ()->GetDlSubChannels ().size (); //create a matrix of flow metrics double metrics[nbOfRBs][flows->size ()]; /* for (int i = 0; i < nbOfRBs; i++) { for (int j = 0; j < flows->size (); j++) { metrics[i][j] = ComputeSchedulingMetric (flows->at (j)->GetBearer (), flows->at (j)->GetSpectralEfficiency ().at (i), i); } }*/ #ifdef SCHEDULER_DEBUG std::cout << ", available RBs " << nbOfRBs << ", flows " << flows->size () << std::endl; /*for (int ii = 0; ii < flows->size (); ii++) { std::cout << "\t metrics for flow " << flows->at (ii)->GetBearer ()->GetApplication ()->GetApplicationID () << ":"; for (int jj = 0; jj < nbOfRBs; jj++) { std::cout << " " << metrics[jj][ii]; } std::cout << std::endl; }*/ #endif AMCModule *amc = GetMacEntity ()->GetAmcModule (); double l_dAllocatedRBCounter = 0; int l_iNumberOfUsers = ((ENodeB*)this->GetMacEntity()->GetDevice())->GetNbOfUserEquipmentRecords(); bool * l_bFlowScheduled = new bool[flows->size ()]; int l_iScheduledFlows = 0; std::vector<double> * l_bFlowScheduledSINR = new std::vector<double>[flows->size ()]; int radius=NetworkManager::Init()->GetCellByID (0)->GetRadius()*1000; //get radius std::vector<UserEquipment*>* users = NetworkManager::Init()->GetUserEquipmentContainer(); int nbUE=users->size(); int nbCell = NetworkManager::Init()->GetNbCell(); int nbFlows = total_flow::Init()->get_total_flows(); const double guarantee_MB=total_flow::Init()->get_data_rate(); const double guarantee_bit = (guarantee_MB*1000*8.0)/100 ; //bit per TTI static std::vector<bool> IsCell_Center(nbUE*nbFlows , false); static std::vector<double> credit(nbUE,0.0); vector<bool> flag(nbUE*nbFlows, false); for (int i=0;i<nbUE;i++) { //---------------get ue radius---------- double x=users->at(i)->GetMobilityModel ()->GetAbsolutePosition()->GetCoordinateX(); //ue x,y position double y=users->at(i)->GetMobilityModel ()->GetAbsolutePosition()->GetCoordinateY(); double x1=users->at(i)->GetCell () ->GetCellCenterPosition ()->GetCoordinateX (); //enb x,y position double y1=users->at(i)->GetCell () ->GetCellCenterPosition ()->GetCoordinateY (); double ue_radius=sqrt( (x-x1)*(x-x1) + (y-y1)*(y-y1) ); //Enb ID = users->at(i)->GetCell ()->GetIdCell() //UEid = users->at(i)->GetIDNetworkNode() if(ue_radius < radius*2.0/3){ for(int k=i*nbFlows;k<(i+1)*nbFlows;k++){ IsCell_Center[k]=true; } }else{ for(int k=i*nbFlows;k<(i+1)*nbFlows;k++){ IsCell_Center[k]=false; } } } //RBs allocation std::vector<vector<double> > my_metrics(nbOfRBs, vector<double>(flows->size ())); int max_edge_RB=0; double edge_demand_bit=0; double center_demand_bit=0; double total_demand_bit=0; for(int k=0;k<flows->size ();k++) { if(IsCell_Center[flows->at (k)->GetBearer ()->GetApplication ()->GetApplicationID ()]==false){ edge_demand_bit+=flows->at (k)->GetDataToTransmit(); }else{ center_demand_bit+=flows->at (k)->GetDataToTransmit(); } } if( ( edge_demand_bit/(edge_demand_bit + center_demand_bit) ) * nbOfRBs < 1.0/5.0*nbOfRBs){ max_edge_RB=( edge_demand_bit/( edge_demand_bit + center_demand_bit) ) * nbOfRBs; } else{ max_edge_RB=1.0/5.0*nbOfRBs; } total_demand_bit = edge_demand_bit + center_demand_bit; vector<double> copy_credit(nbUE , 0.0 ); copy_credit.assign(credit.begin(), credit.end()); for(int i=0;i<nbUE;i++){ if(copy_credit[i]>0){ copy_credit[i]=0; } } double min= *min_element(copy_credit.begin(), copy_credit.end()); for(int i=0;i<nbUE;i++){ copy_credit[i]-=min; } double max= *max_element(copy_credit.begin(), copy_credit.end()); if(max==0){ max=1; } double sum_credit=0; for(int i=0;i<nbUE;i++){ //cout << "copy_credit[" << i << "] = " << copy_credit[i]/max << endl; sum_credit+=(2-copy_credit[i]/max); } vector<double> cqi(flows->size (),0.0); for (int j = 0; j < flows->size (); j++) { for (int s = 0; s < nbOfRBs; s++) { cqi.at(j)+=flows->at (j)->GetCqiFeedbacks ().at(s); } cqi.at(j)/=nbOfRBs; } for (int s = 0; s < nbOfRBs; s++) { for (int j = 0; j < flows->size (); j++) { my_metrics[s][j] = mlwdf_ComputeSchedulingMetric (flows->at (j)->GetBearer (), flows->at (j)->GetSpectralEfficiency ().at (s), s,copy_credit[flows->at (j)->GetBearer ()->GetApplication ()->GetApplicationID ()/nbFlows]/max , sum_credit/nbUE ,flows->at (j)->GetDataToTransmit(),flows->at (j)->GetCqiFeedbacks ().at(s)/cqi.at(j)); } for (int j = 0; j < flows->size (); j++) { metrics[s][j] = ComputeSchedulingMetric1 (flows->at (j)->GetBearer (), flows->at (j)->GetSpectralEfficiency ().at (s), s,flows->at (j)->GetDataToTransmit(), total_demand_bit,copy_credit[flows->at (j)->GetBearer ()->GetApplication ()->GetApplicationID ()/nbFlows]/max , sum_credit/nbUE); } if (l_iScheduledFlows == flows->size ()) break; double targetMetric = 0; bool RBIsAllocated = false; FlowToSchedule* scheduledFlow; int l_iScheduledFlowIndex = 0; //std::cout << "avg_cqi = " << avg_cqi << std::endl; RBIsAllocated = false; if(s<max_edge_RB) { targetMetric=-1; for(int k=0;k<flows->size ();k++) { if(metrics[s][k] > targetMetric && !l_bFlowScheduled[k] && flows->at (k)->GetDataToTransmit() >0 && IsCell_Center[flows->at (k)->GetBearer ()->GetApplication ()->GetApplicationID ()]==false) { targetMetric=metrics[s][k]; RBIsAllocated = true; scheduledFlow = flows->at (k); l_iScheduledFlowIndex = k; } } if(!RBIsAllocated) { targetMetric=-1; for(int k=0;k<flows->size ();k++) { if(my_metrics[s][k] > targetMetric && !l_bFlowScheduled[k] && flows->at (k)->GetDataToTransmit() >0 ) { targetMetric=my_metrics[s][k]; RBIsAllocated = true; scheduledFlow = flows->at (k); l_iScheduledFlowIndex = k; } } } }else { targetMetric=-1; l_iScheduledFlowIndex=0; for (int k = 0; k < flows->size (); k++) { if (my_metrics[s][k] > targetMetric && !l_bFlowScheduled[k] && flows->at (k)->GetDataToTransmit() >0 ) { targetMetric = my_metrics[s][k]; RBIsAllocated = true; scheduledFlow = flows->at (k); l_iScheduledFlowIndex = k; //std::cout << "\tschedule to flow : " << flows->at (k)->GetBearer ()->GetApplication ()->GetApplicationID () << std::endl; } } } if (RBIsAllocated) { l_dAllocatedRBCounter++; scheduledFlow->GetListOfAllocatedRBs()->push_back (s); // the s RB has been allocated to that flow! #ifdef SCHEDULER_DEBUG /* std::cout << "\t *** RB " << s << " assigned to the " " flow " << scheduledFlow->GetBearer ()->GetApplication ()->GetApplicationID () << std::endl;*/ std::cout << "\t *** RB " << s << " assigned to the " " flow " << scheduledFlow->GetBearer ()->GetApplication ()->GetApplicationID () << " cqi " << scheduledFlow->GetCqiFeedbacks ().at (s) << " cell_center " << IsCell_Center[scheduledFlow->GetBearer ()->GetApplication ()->GetApplicationID ()] << std::endl; #endif double sinr = amc->GetSinrFromCQI (scheduledFlow->GetCqiFeedbacks ().at (s)); l_bFlowScheduledSINR[l_iScheduledFlowIndex].push_back(sinr); double effectiveSinr = GetEesmEffectiveSinr (l_bFlowScheduledSINR[l_iScheduledFlowIndex]); int mcs = amc->GetMCSFromCQI (amc->GetCQIFromSinr (effectiveSinr)); int transportBlockSize = amc->GetTBSizeFromMCS (mcs, scheduledFlow->GetListOfAllocatedRBs ()->size ()); if (transportBlockSize >= scheduledFlow->GetDataToTransmit() * 8) { #ifdef SCHEDULER_DEBUG cout << "-- FLOW " << scheduledFlow->GetBearer ()->GetApplication ()->GetApplicationID () << ", demand = " << scheduledFlow->GetDataToTransmit()*8 << ", transportBlockSize = " << transportBlockSize << endl; #endif l_bFlowScheduled[l_iScheduledFlowIndex] = true; l_iScheduledFlows++; } } } delete [] l_bFlowScheduled; delete [] l_bFlowScheduledSINR; //Finalize the allocation PdcchMapIdealControlMessage *pdcchMsg = new PdcchMapIdealControlMessage (); for (FlowsToSchedule::iterator it = flows->begin (); it != flows->end (); it++) { FlowToSchedule *flow = (*it); if (flow->GetListOfAllocatedRBs ()->size () > 0) { //cout << "----------------------------------" << endl; //this flow has been scheduled std::vector<double> estimatedSinrValues; for (int rb = 0; rb < flow->GetListOfAllocatedRBs ()->size (); rb++ ) { double sinr = amc->GetSinrFromCQI ( flow->GetCqiFeedbacks ().at (flow->GetListOfAllocatedRBs ()->at (rb))); //cout << "CQI = " << flow->GetCqiFeedbacks ().at (flow->GetListOfAllocatedRBs ()->at (rb)) << endl; estimatedSinrValues.push_back (sinr); } //compute the effective sinr double effectiveSinr = GetEesmEffectiveSinr (estimatedSinrValues); //get the MCS for transmission //cout << "effectiveCQI = " << amc->GetCQIFromSinr (effectiveSinr) << endl; int mcs = amc->GetMCSFromCQI (amc->GetCQIFromSinr (effectiveSinr)); //define the amount of bytes to transmit //int transportBlockSize = amc->GetTBSizeFromMCS (mcs); int transportBlockSize = amc->GetTBSizeFromMCS (mcs, flow->GetListOfAllocatedRBs ()->size ()); double bitsToTransmit = transportBlockSize; flow->UpdateAllocatedBits (bitsToTransmit); #ifdef SCHEDULER_DEBUG std::cout << "\t\t --> flow " << flow->GetBearer ()->GetApplication ()->GetApplicationID () << " has been scheduled: " << "\n\t\t\t nb of RBs " << flow->GetListOfAllocatedRBs ()->size () << "\n\t\t\t effectiveSinr " << effectiveSinr << "\n\t\t\t tbs " << transportBlockSize << "\n\t\t\t bitsToTransmit " << bitsToTransmit << std::endl; #endif credit[flow->GetBearer ()->GetApplication ()->GetApplicationID()/nbFlows]+=bitsToTransmit; //new add //create PDCCH messages for (int rb = 0; rb < flow->GetListOfAllocatedRBs ()->size (); rb++ ) { pdcchMsg->AddNewRecord (PdcchMapIdealControlMessage::DOWNLINK, flow->GetListOfAllocatedRBs ()->at (rb), flow->GetBearer ()->GetDestination (), mcs); } } } if (pdcchMsg->GetMessage()->size () > 0) { GetMacEntity ()->GetDevice ()->GetPhy ()->SendIdealControlMessage (pdcchMsg); } delete pdcchMsg; for (int i = 0; i< nbUE ; i++ ) //new add { credit[i]-=guarantee_bit; //cout << "credit[" << i << "] = " << credit[i] << endl; } }
void selectCameraOrder(int camNum, const int* distMat, Mat_i& order) { int maxVal = 0; int iMax = -1, jMax = -1; const int* pDistMat = distMat; // find the max value in the distMat at (iMax, jMax) for (int i = 0; i < camNum; i++) { for (int j = i; j < camNum; j++) { if (pDistMat[j] > maxVal) { maxVal = pDistMat[j]; iMax = i; jMax = j; } } pDistMat += camNum; } Mat_uc flag(camNum, 1); flag.fill(0); flag[iMax] = 1; flag[jMax] = 1; std::list<int> cams; cams.push_back(iMax); cams.push_back(jMax); while (maxVal > 0) { int iHead = cams.front(); int iTail = cams.back(); int iMaxHead = -1; int maxValHead = 0; pDistMat = distMat + camNum * iHead; for (int j = 0; j < camNum; j++) { if (flag[j] > 0) continue; else if (maxValHead < pDistMat[j]) { maxValHead = pDistMat[j]; iMaxHead = j; } } int iMaxTail = -1; int maxValTail = 0; pDistMat = distMat + camNum * iTail; for (int j = 0; j < camNum; j++) { if (flag[j] > 0) continue; else if (maxValTail < pDistMat[j]) { maxValTail = pDistMat[j]; iMaxTail = j; } } if (iMaxHead < 0 && iMaxTail < 0) { break; } if (maxValHead > maxValTail) { cams.push_front(iMaxHead); flag[iMaxHead] = 1; } else if (maxValHead < maxValTail) { cams.push_back(iMaxTail); flag[iMaxTail] = 1; } } order.resize(cams.size(), 1); int k = 0; std::list<int>::iterator iter; for (iter = cams.begin(); iter != cams.end(); iter++) { order.data[k++] = *iter; } order.rows = k; if (order.rows != camNum) { repErr("selectCameraOrder - not all camera have the intersection of views"); } }
vector<vector<int> > generateMatrix(int n) { vector<vector<int> > r(n,vector<int> (n)); int cnt =1 ; int maxx = n; if (maxx == 0) return r; int maxy = n; int x = 0; int y = 0; vector<vector<bool> > flag(n,vector<bool> (n,false)); int dx = 0, dy = 1; for (;;) { r[x][y]=cnt++; // marked as visited flag[x][y] = true; // next pixel valid ? int nx = x + dx; int ny = y + dy; if ((nx >= 0) && (nx < maxx) && (ny >= 0) && (ny < maxy)) { // go with the same direction if possible if (!flag[nx][ny]) { x = nx; y = ny; continue; } } // try first right if ((y < maxy - 1) && (!flag[x][y + 1])) { y ++; dx = 0; dy = 1; continue; } // then down if ((x < maxx - 1) && (!flag[x + 1][y])) { x ++; dx = 1; dy = 0; continue; } // then left if ((y > 0) && (!flag[x][y - 1])) { y --; dx = 0; dy = -1; continue; } // then up if ((x >0) && (!flag[x - 1][y])) { x --; dx = -1; dy = 0; continue; } // ok finish , can't go one step any more break; } return r; }
inline void SieveOfAtkin::switchBit(const unsigned index) { sieve[index/DWORD_BITS] ^= flag(index%DWORD_BITS); }
void launch_flag() { flag(); update(); }
BOOL8 REJ::rej_before_mm_accept() { return rej_between_nn_and_mm () || (rej_before_nn_accept () && !flag (R_NN_ACCEPT) && !flag (R_HYPHEN_ACCEPT)); }
// increment the flag value (mod 4): void inc_flag(uint i) { set_flag(uchar((flag() + i) % (1 << FLAG_BITS))); }
void KLanguageCombo::insertLanguage(const QString& path, const QString& name, const QString& sub, const QString &submenu, int index) { QString output = name + QLatin1String(" (") + path + QString::fromLatin1(")"); QPixmap flag(locate("locale", sub + path + QLatin1String("/flag.png"))); insertItem(QIcon(flag), output, path, submenu, index); }
bool check_filedes(bool report) { bool allOk = true; // See how many file descriptors there are with values < 256. // In order to avoid disturbing things, we scan the file descriptors // first, marking the ones that were OPEN at startup (report == FALSE) // as STILLOPEN and the ones that were not as LEAKED. Then we run // through again and print the results. for(int d = 0; d < FILEDES_MAX; ++d) { if(::fcntl(d, F_GETFD) != -1) { // File descriptor obviously exists, but is it /dev/log? // Mark it as OPEN for now, and we'll find out later. if(report) { if(filedes_open[d] == OPEN) { filedes_open[d] = STILLOPEN; } else { filedes_open[d] = LEAKED; } } else { filedes_open[d] = OPEN; } } else { filedes_open[d] = CLOSED; } } if(!report) { filedes_initialised = true; return true; } // Now loop again, reporting differences. for(int d = 0; d < FILEDES_MAX; ++d) { if(filedes_open[d] != LEAKED) { continue; } bool stat_success = false; struct stat st; if(fstat(d, &st) == 0) { stat_success = true; if(st.st_mode & S_IFSOCK) { char buffer[256]; socklen_t addrlen = sizeof(buffer); #ifdef HAVE_GETPEERNAME if(getpeername(d, (sockaddr*)buffer, &addrlen) != 0) { BOX_LOG_SYS_WARNING("Failed to getpeername(" << d << "), cannot identify /dev/log"); } else { struct sockaddr_un *sa = (struct sockaddr_un *)buffer; if(sa->sun_family == PF_UNIX && !strcmp(sa->sun_path, "/dev/log")) { // it's a syslog socket, ignore it filedes_open[d] = SYSLOG; } } #endif // HAVE_GETPEERNAME } } if(filedes_open[d] == SYSLOG) { // Different libcs have different ideas // about when to open and close this // socket, and it's not a leak, so // ignore it. } else if(stat_success) { int m = st.st_mode; #define flag(x) ((m & x) ? #x " " : "") BOX_FATAL("File descriptor " << d << " left open (type == " << flag(S_IFIFO) << flag(S_IFCHR) << flag(S_IFDIR) << flag(S_IFBLK) << flag(S_IFREG) << flag(S_IFLNK) << flag(S_IFSOCK) << " or " << m << ")"); allOk = false; } else { BOX_FATAL("File descriptor " << d << " left open (and stat failed)"); allOk = false; } } if (!report && allOk) { filedes_initialised = true; } return allOk; }
void CMsgBoxResult::OnPaint() { CPaintDC dc(this); CGameImageHelper help(&m_bkImg); CDC srcDC; srcDC.CreateCompatibleDC(&dc); CBitmap *pOldBmp = srcDC.SelectObject(help); ::TransparentBlt(dc.GetSafeHdc(),0,0,m_bkImg.GetWidth(),m_bkImg.GetHeight(), srcDC.GetSafeHdc(),0,0,m_bkImg.GetWidth(),m_bkImg.GetHeight(),srcDC.GetPixel(0,0)); srcDC.SelectObject(pOldBmp); CRect ClientRect; GetClientRect(&ClientRect); //int x=24;//ClientRect.left+20; //int y=ClientRect.Height()/2 - 34; CRect rect; TCHAR sz[100]; CFont Font; Font.CreateFont(14,0,0,0,0,0,0,0,134,3,2,1,2,TEXT("宋体")); CFont *OldFont=dc.SelectObject(&Font); dc.SetTextColor(RGB(255,255,255)); dc.SetBkMode(TRANSPARENT); //int StartX = 222; //int StartY = 78; for(int i = 0; i < PLAY_COUNT; i ++) { if(strlen(m_iFinish.name[i]) <= 0) continue; if(m_iFinish.iWardPoint[i] > 0||m_iFinish.iMoney[i]>0) { dc.SetTextColor(RGB(255,0,0)); } else { dc.SetTextColor(RGB(0,0,0)); } wsprintf(sz,"%s",m_iFinish.name[i]); rect.left=m_iGameEndX; rect.right=rect.left+80; rect.top=m_iGameEndY+33*i; rect.bottom=rect.top+33; dc.DrawText(sz,lstrlen(sz),&rect,DT_LEFT|DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS); wsprintf(sz,TEXT("%d"), m_iFinish.iWardPoint[i]); rect.left=225; rect.right=rect.left+70; rect.top=m_iGameEndY+33*i; rect.bottom=rect.top+33; dc.DrawText(sz,lstrlen(sz),&rect,DT_CENTER|DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS); CString strMoney; GetNumString(m_iFinish.iMoney[i],strMoney,m_nPowerOfGold,false); wsprintf(sz,TEXT("%s"),strMoney); rect.left=306; rect.right=rect.left+70; rect.top=m_iGameEndY+33*i; rect.bottom=rect.top+33; dc.DrawText(sz,lstrlen(sz),&rect,DT_CENTER|DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS); if(m_iFinish.iWardPoint[i] > 0||m_iFinish.iMoney[i]>0) wsprintf(sz,".\\image\\win.bmp"); else if(m_iFinish.iWardPoint[i] == 0 && m_iFinish.iMoney[i] == 0) wsprintf(sz,".\\image\\equal.bmp"); else wsprintf(sz,".\\image\\lost.bmp"); m_Flag.SetLoadInfo(sz,false); CGameImageHelper flag(&m_Flag); CDC srcDC; srcDC.CreateCompatibleDC(&dc); srcDC.SelectObject(flag); //flag.BitBlt(dc.GetSafeHdc(),StartX,StartY+33*i,SRCCOPY); ::TransparentBlt(dc.GetSafeHdc(),m_iGameEndWinLostX+6,m_iGameEndWinLostY+ 33* i,flag.GetWidth(),flag.GetHeight(), srcDC.GetSafeHdc(),0,0,m_Flag.GetWidth(),m_Flag.GetHeight(),srcDC.GetPixel(0,0)); } dc.DeleteDC(); }
BOOL8 REJ::rej_before_quality_accept() { return rej_between_mm_and_quality_accept () || (!flag (R_MM_ACCEPT) && rej_before_mm_accept ()); }
int main(int argc, char ** argv) { int my_ID; /* Thread ID */ long vector_length; /* length of vectors to be aggregated */ long total_length; /* bytes needed to store reduction vectors */ double reduce_time, /* timing parameters */ avgtime; double epsilon=1.e-8; /* error tolerance */ int group_size, /* size of aggregating half of thread pool */ old_size, /* group size in previous binary tree iteration */ i, id, iter, stage; /* dummies */ double element_value; /* reference element value for final vector */ char *algorithm; /* reduction algorithm selector */ int intalgorithm; /* integer encoding of algorithm selector */ int iterations; /* number of times the reduction is carried out */ int flag[MAX_THREADS*LINEWORDS]; /* used for pairwise synchronizations */ int start[MAX_THREADS], end[MAX_THREADS];/* segments of vectors for bucket algorithm */ long segment_size; int my_donor, my_segment; int nthread_input, /* thread parameters */ nthread; double RESTRICT *vector;/* vector pair to be reduced */ int num_error=0; /* flag that signals that requested and obtained numbers of threads are the same */ /***************************************************************************** ** process and test input parameters ******************************************************************************/ printf("Parallel Research Kernels version %s\n", PRKVERSION); printf("OpenMP Vector Reduction\n"); if (argc != 4 && argc != 5){ printf("Usage: %s <# threads> <# iterations> <vector length> ", *argv); printf("[<alghorithm>]\n"); printf("Algorithm: linear, binary-barrier, binary-p2p, or long-optimal\n"); return(EXIT_FAILURE); } /* Take number of threads to request from command line */ nthread_input = atoi(*++argv); if ((nthread_input < 1) || (nthread_input > MAX_THREADS)) { printf("ERROR: Invalid number of threads: %d\n", nthread_input); exit(EXIT_FAILURE); } omp_set_num_threads(nthread_input); iterations = atoi(*++argv); if (iterations < 1){ printf("ERROR: Iterations must be positive : %d \n", iterations); exit(EXIT_FAILURE); } vector_length = atol(*++argv); if (vector_length < 1){ printf("ERROR: vector length must be >= 1 : %ld \n",vector_length); exit(EXIT_FAILURE); } total_length = vector_length*2*nthread_input*sizeof(double); vector = (double *) prk_malloc(total_length); if (!vector) { printf("ERROR: Could not allocate space for vectors: %ld\n", total_length); exit(EXIT_FAILURE); } algorithm = "binary-p2p"; if (argc == 5) algorithm = *++argv; intalgorithm = NONE; if (!strcmp(algorithm,"linear" )) intalgorithm = LINEAR; if (!strcmp(algorithm,"binary-barrier")) intalgorithm = BINARY_BARRIER; if (!strcmp(algorithm,"binary-p2p" )) intalgorithm = BINARY_P2P; if (!strcmp(algorithm,"long-optimal" )) intalgorithm = LONG_OPTIMAL; if (intalgorithm == NONE) { printf("Wrong algorithm: %s; choose linear, binary-barrier, ", algorithm); printf("binary-p2p, or long-optimal\n"); exit(EXIT_FAILURE); } else { if (nthread_input == 1) intalgorithm = LOCAL; } #pragma omp parallel private(i, old_size, group_size, my_ID, iter, start, end, \ segment_size, stage, id, my_donor, my_segment) { my_ID = omp_get_thread_num(); #pragma omp master { nthread = omp_get_num_threads(); if (nthread != nthread_input) { num_error = 1; printf("ERROR: number of requested threads %d does not equal ", nthread_input); printf("number of spawned threads %d\n", nthread); } else { printf("Number of threads = %d\n",nthread_input); printf("Vector length = %ld\n", vector_length); printf("Reduction algorithm = %s\n", algorithm); printf("Number of iterations = %d\n", iterations); } } bail_out(num_error); for (iter=0; iter<=iterations; iter++) { /* start timer after a warmup iteration */ if (iter == 1) { #pragma omp barrier #pragma omp master { reduce_time = wtime(); } } /* in case of the long-optimal algorithm we need a barrier before the reinitialization to make sure that we don't overwrite parts of the vector before other threads are done with those parts */ if (intalgorithm == LONG_OPTIMAL) { #pragma omp barrier } /* initialize the arrays, assuming first-touch memory placement */ for (i=0; i<vector_length; i++) { VEC0(my_ID,i) = (double)(my_ID+1); VEC1(my_ID,i) = (double)(my_ID+1+nthread); } if (intalgorithm == BINARY_P2P) { /* we need a barrier before setting all flags to zero, to avoid zeroing some that are still in use in a previous iteration */ #pragma omp barrier flag(my_ID) = 0; /* we also need a barrier after setting the flags, to make each is visible to all threads, and to synchronize before the timer starts */ #pragma omp barrier } /* do actual reduction */ /* first do the "local" part, which is the same for all algorithms */ for (i=0; i<vector_length; i++) { VEC0(my_ID,i) += VEC1(my_ID,i); } /* now do the "non-local" part */ switch (intalgorithm) { case LOCAL: break; case LINEAR: { #pragma omp barrier #pragma omp master { for (id=1; id<nthread; id++) { for (i=0; i<vector_length; i++) { VEC0(0,i) += VEC0(id,i); } } } } break; case BINARY_BARRIER: group_size = nthread; while (group_size >1) { /* barrier to make sure threads have completed their updates before the results are being read */ #pragma omp barrier old_size = group_size; group_size = (group_size+1)/2; /* Threads in "first half" of group aggregate data from threads in second half; must make sure the counterpart is within old group. If group size is odd, the last thread in the group does not have a counterpart. */ if (my_ID < group_size && my_ID+group_size<old_size) { for (i=0; i<vector_length; i++) { VEC0(my_ID,i) += VEC0(my_ID+group_size,i); } } } break; case BINARY_P2P: group_size = nthread; while (group_size >1) { old_size = group_size; group_size = (group_size+1)/2; /* synchronize between each pair of threads that collaborate to aggregate a new subresult, to make sure the donor of the pair has updated its vector in the previous round before it is being read */ if (my_ID < group_size && my_ID+group_size<old_size) { while (flag(my_ID+group_size) == 0) { #pragma omp flush } /* make sure I read the latest version of vector from memory */ #pragma omp flush for (i=0; i<vector_length; i++) { VEC0(my_ID,i) += VEC0(my_ID+group_size,i); } } else { if (my_ID < old_size) { /* I am a producer of data in this iteration; make sure my updated version can be seen by all threads */ flag(my_ID) = 1; #pragma omp flush } } } break; case LONG_OPTIMAL: /* compute starts and ends of subvectors to be passed among threads */ segment_size = (vector_length+nthread-1)/nthread; for (id=0; id<nthread; id++) { start[id] = segment_size*id; end[id] = MIN(vector_length,segment_size*(id+1)); } /* first do the Bucket Reduce Scatter in nthread-1 stages */ my_donor = (my_ID-1+nthread)%nthread; for (stage=1; stage<nthread; stage++) { #pragma omp barrier my_segment = (my_ID-stage+nthread)%nthread; for (i=start[my_segment]; i<end[my_segment]; i++) { VEC0(my_ID,i) += VEC0(my_donor,i); } } /* next, each thread pushes its contribution into the master thread vector; no need to synchronize, because of the push model */ my_segment = (my_ID+1)%nthread; if (my_ID != 0) for (i=start[my_segment]; i<end[my_segment]; i++) { VEC0(0,i) = VEC0(my_ID,i); } break; } /* end of algorithm switch statement */ } /* end of iter loop */ #pragma omp barrier #pragma omp master { reduce_time = wtime() - reduce_time; } } /* end of OpenMP parallel region */ /* verify correctness */ element_value = (double)nthread*(2.0*(double)nthread+1.0); for (i=0; i<vector_length; i++) { if (ABS(VEC0(0,i) - element_value) >= epsilon) { printf("First error at i=%d; value: %lf; reference value: %lf\n", i, VEC0(0,i), element_value); exit(EXIT_FAILURE); } } printf("Solution validates\n"); #ifdef VERBOSE printf("Element verification value: %lf\n", element_value); #endif avgtime = reduce_time/iterations; printf("Rate (MFlops/s): %lf Avg time (s): %lf\n", 1.0E-06 * (2.0*nthread-1.0)*vector_length/avgtime, avgtime); exit(EXIT_SUCCESS); }
bool AnimatableLengthBoxAndBool::equalTo(const AnimatableValue* value) const { const AnimatableLengthBoxAndBool* lengthBox = toAnimatableLengthBoxAndBool(value); return box()->equals(lengthBox->box()) && flag() == lengthBox->flag(); }
int main(int argc, char* argv[]) { initscr(); scrollok(stdscr, TRUE); wprintw(stdscr, "Welcome to Scripted ver. %d.%d for the Brave Quest engine.\nCopyright 2012 Mad Science Inc.\nPlease do not redistrubute.\n",scriptedvernum,scriptedvernum2); stufffilename(); if(loadscript(filename) == 1) { wprintw(stdscr, "File not Found. Would you like to make a new file?\n"); if(bie() == 'y') { cleanfilebuff(); if(savescript(filename) == 1) { wprintw(stdscr, "Your disk sucks.\n"); bi(); return 1; } } else { wprintw(stdscr, "Goodbye.\n"); endwin(); return 1; } } currlinenum = linenum; menu(); wprintw(stdscr, "Press escape to go to the save menu\n"); for(;;) { wprintw(stdscr, "q= give, w= take, e= say, r= flag, t= move, y= battle, u= check flag, i= check item, o= party add, p= party remove, [ = check character\n"); wprintw(stdscr, "a= warp, s= check experience, d= give experience, f= make experience, g= exec script, h= screen effect, j= user input, k= goline, l= make health\n"); wprintw(stdscr, "b= check stat, n= make stat, m= blank, ,= show line, .= change line.\n"); input[0] = bie(); if(input[0] == 27) menu(); if(input[0] == 'q') give(); if(input[0] == 'w') take(); if(input[0] == 'e') say(); if(input[0] == 'r') flag(); if(input[0] == 't') mmove(); if(input[0] == 'y') battle(); if(input[0] == 'u') checkflag(); if(input[0] == 'i') checkitem(); if(input[0] == 'o') partyadd(); if(input[0] == 'p') partyrm(); if(input[0] == '[') checkparty(); if(input[0] == 'a') warp(); if(input[0] == 's') checkexp(); if(input[0] == 'd') giveexp(); if(input[0] == 'f') makeexp(); if(input[0] == 'g') execscript(); if(input[0] == 'h') screeneffect(); if(input[0] == 'j') userinput(); if(input[0] == 'k') goline(); if(input[0] == 'l') makehealth(); if(input[0] == 'z') teachspell(); if(input[0] == 'x') unlearnspell(); if(input[0] == 'b') checkstat(); if(input[0] == 'n') makestat(); if(input[0] == 'm') blank(); if(input[0] == ',') showline(); if(input[0] == '.') changeline(); if(currlinenum > linenum) linenum = currlinenum; } return 0; };
GAIndividual<CodeVInt> GSTM::crossover(const GAIndividual<CodeVInt> &indivl1, const GAIndividual<CodeVInt> &indivl2) { if (indivl1 == indivl2) return indivl1; GAIndividual<CodeVInt> indivl; int i, j, n; vector<int> arr(m_numDim), flag(m_numDim+1); vector<vector<int>> matrix1(m_numDim), matrix2(m_numDim); for (i = 0; i < m_numDim; i++) { matrix1[i].resize(m_numDim); matrix2[i].resize(m_numDim); } map<int, vector<int> > frag; for (i = 0; i<m_numDim; i++) arr[i] = indivl1.data().m_x[i]; for (i = 0; i<m_numDim + 1; i++) flag[i] = 0; for (i = 0; i<m_numDim; i++) { for (j = 0; j<m_numDim; j++) { matrix1[i][j] = 0; matrix2[i][j] = 0; } } for (i = 0; i<m_numDim; i++) { matrix1[arr[i]][arr[(i + 1) % m_numDim]] = 1; matrix1[arr[(i + 1) % m_numDim]][arr[i]] = 1; matrix2[indivl2.data().m_x[i]][indivl2.data().m_x[(i + 1) % m_numDim]] = 1; matrix2[indivl2.data().m_x[(i + 1) % m_numDim]][indivl2.data().m_x[i]] = 1; } for (i = 0; i<m_numDim; i++) { if (matrix2[arr[i]][arr[(i + 1) % m_numDim]] == 0) flag[i + 1] = 1; } flag[0] = flag[m_numDim]; int m = 0; n = 0; j = 0; frag[n].push_back(arr[j++]); m++; while (flag[j] == 0 && m<m_numDim) { frag[n].push_back(arr[j++]); m++; } i = m_numDim; while (flag[i] == 0 && m<m_numDim) { frag[n].insert(frag[n].begin(), arr[i - 1]); i--; m++; } while (m<m_numDim) { if (flag[j] == 1) n++; frag[n].push_back(arr[j++]); m++; while (flag[j] == 0) { frag[n].push_back(arr[j++]); m++; } } vector<int> visited(m_numDim); map<int, int> mp; for (i = 0; i<m_numDim; i++) visited[i] = 0; m = 0; for (i = 0; i <= n; i++) { visited[m++] = frag[i].front(); mp[visited[m - 1]] = i; if (frag[i].size()>1) { visited[m++] = frag[i].back(); mp[visited[m - 1]] = i; } } int starts; i = Global::msp_global->getRandInt(0, m - 1); j = 0; arr[j++] = visited[i]; starts = visited[i]; if (frag[mp[visited[i]]].front() == starts) { for (size_t z = 1; z<frag[mp[visited[i]]].size(); z++) arr[j++] = frag[mp[visited[i]]][z]; starts = frag[mp[visited[i]]].back(); if (frag[mp[visited[i]]].size()>1) { int fg = 0; if (visited[m - 1] == visited[i]) fg = 1; for (int z = 0; z<m; z++) { if (visited[z] == frag[mp[visited[i]]].back()) { visited[z] = visited[m - 1]; m--; if (fg == 1) i = z; break; } } } visited[i] = visited[m - 1]; m--; } else if (frag[mp[visited[i]]].back() == starts) { for (int z = frag[mp[visited[i]]].size() - 2; z >= 0; z--) arr[j++] = frag[mp[visited[i]]][z]; starts = frag[mp[visited[i]]].front(); if (frag[mp[visited[i]]].size()>1) { int fg = 0; if (visited[m - 1] == visited[i]) fg = 1; for (int z = 0; z<m; z++) { if (visited[z] == frag[mp[visited[i]]].front()) { visited[z] = visited[m - 1]; m--; if (fg == 1) i = z; break; } } } visited[i] = visited[m - 1]; m--; } n--; for (i = 0; i <= n; i++) { double min = DBL_MAX; int temp; int pos = -1; TravellingSalesman * ptr = dynamic_cast<TravellingSalesman*>(Global::msp_global->mp_problem.get()); for (int z = 0; z<m; z++) { if (min>ptr->getCost()[starts][visited[z]] && matrix1[starts][visited[z]] == 0 && matrix2[starts][visited[z]] == 0) { min = ptr->getCost()[starts][visited[z]]; temp = visited[z]; pos = z; } } if (pos == -1) { temp = visited[0]; pos = 0; } arr[j++] = temp; if (frag[mp[temp]].front() == temp) { for (size_t z = 1; z<frag[mp[temp]].size(); z++) arr[j++] = frag[mp[temp]][z]; starts = frag[mp[temp]].back(); if (frag[mp[temp]].size()>1) { int fg = 0; if (visited[m - 1] == visited[pos]) fg = 1; for (int z = 0; z<m; z++) { if (visited[z] == frag[mp[temp]].back()) { visited[z] = visited[m - 1]; m--; if (fg == 1) pos = z; break; } } } visited[pos] = visited[m - 1]; m--; } else if (frag[mp[temp]].back() == temp) { for (int z = frag[mp[temp]].size() - 2; z >= 0; z--) arr[j++] = frag[mp[temp]][z]; starts = frag[mp[temp]].front(); if (frag[mp[temp]].size()>1) { int fg = 0; if (visited[m - 1] == visited[pos]) fg = 1; for (int z = 0; z<m; z++) { if (visited[z] == frag[mp[temp]].front()) { visited[z] = visited[m - 1]; m--; if (fg == 1) pos = z; break; } } } visited[pos] = visited[m - 1]; m--; } } for (i = 0; i<m_numDim; i++) indivl.data().m_x[i] = arr[i]; return indivl; }
/** * Export VirtualBox machine */ void exportVirtualBoxMachine(IVirtualBox *virtualBox, IMachine *machine, xmlTextWriterPtr writer) { nsCOMPtr<ISystemProperties> systemProperties; nsresult rc = virtualBox->GetSystemProperties(getter_AddRefs(systemProperties)); if (NS_SUCCEEDED(rc)) { xmlTextWriterStartElement(writer, TOXMLCHAR("machine")); // uuid ADDXMLSTRING(machine->GetId, "id"); // name ADDXMLSTRING(machine->GetName, "name"); // description ADDXMLSTRING(machine->GetDescription, "description"); // os type ADDXMLSTRING(machine->GetOSTypeId, "ostype"); // settings file ADDXMLSTRING(machine->GetSettingsFilePath, "path"); // hardware uuid ADDXMLSTRING(machine->GetHardwareUUID, "hardwareuuid"); // memory size ADDXMLINT32U(machine->GetMemorySize, "memory"); // memory balloon size ADDXMLINT32U(machine->GetMemoryBalloonSize, "memoryballoon"); // page fusion ADDXMLBOOL(machine->GetPageFusionEnabled, "pagefusion"); // vram size ADDXMLINT32U(machine->GetVRAMSize, "vram"); // hpet ADDXMLBOOL(machine->GetHPETEnabled, "hpet"); // cpu count ADDXMLINT32U(machine->GetCPUCount, "cpus"); // cpu execution cap ADDXMLINT32U(machine->GetCPUExecutionCap, "cpucap"); // cpu hotplug ADDXMLBOOL(machine->GetCPUHotPlugEnabled, "cpuhotplug"); // synthcpu // { // PRBool value; // rc = machine->GetCPUProperty(CPUPropertyType_Synthetic, &value); // if (NS_SUCCEEDED(rc)) { // WRITEXMLBOOL("synthcpu", value); // } // } // firmware type ADDXMLENUM(machine->GetFirmwareType, "firmware", firmwareTypeConverter); // bios settings { nsCOMPtr<IBIOSSettings> value; rc = machine->GetBIOSSettings(getter_AddRefs(value)); if (NS_SUCCEEDED(rc)) { exportVirtualBoxBIOSSettings(value, writer); } } // boot order { PRUint32 bootPositions; rc = systemProperties->GetMaxBootPosition(&bootPositions); if (NS_SUCCEEDED(rc)) { for (PRUint32 i = 1; i <= bootPositions; i++) { PRUint32 value; rc = machine->GetBootOrder(i, &value); if (NS_SUCCEEDED(rc)) { char name[256]; sprintf(name, "boot%d", i); WRITEXMLENUM(name, value, deviceTypeConverter); } } } } // pae { PRBool value; rc = machine->GetCPUProperty(CPUPropertyType_PAE, &value); if (NS_SUCCEEDED(rc)) { WRITEXMLBOOL("pae", value); } } // rtc use utc ADDXMLBOOL(machine->GetRTCUseUTC, "rtcuseutc"); // monitor count ADDXMLINT32U(machine->GetMonitorCount, "monitorcount"); // accelerate 3D ADDXMLBOOL(machine->GetAccelerate3DEnabled, "accelerate3d"); // accelerate 2D video ADDXMLBOOL(machine->GetAccelerate2DVideoEnabled, "accelerate2dvideo"); // hwvirtex { PRBool value; rc = machine->GetCPUProperty(HWVirtExPropertyType_Enabled, &value); if (NS_SUCCEEDED(rc)) { WRITEXMLBOOL("hwvirtex", value); } } // vtxvpid { PRBool value; rc = machine->GetHWVirtExProperty(HWVirtExPropertyType_VPID, &value); if (NS_SUCCEEDED(rc)) { WRITEXMLBOOL("vtxvpid", value); } } // nestedpaging { PRBool value; rc = machine->GetHWVirtExProperty(HWVirtExPropertyType_NestedPaging, &value); if (NS_SUCCEEDED(rc)) { WRITEXMLBOOL("nestedpaging", value); } } // unrestrictedexec { PRBool value; rc = machine->GetHWVirtExProperty(HWVirtExPropertyType_UnrestrictedExecution, &value); if (NS_SUCCEEDED(rc)) { WRITEXMLBOOL("unrestrictedexec", value); } } // largepages { PRBool value; rc = machine->GetHWVirtExProperty(HWVirtExPropertyType_LargePages, &value); if (NS_SUCCEEDED(rc)) { WRITEXMLBOOL("largepages", value); } } // force { PRBool value; rc = machine->GetHWVirtExProperty(HWVirtExPropertyType_Force, &value); if (NS_SUCCEEDED(rc)) { WRITEXMLBOOL("hwforce", value); } } // io cache ADDXMLBOOL(machine->GetIOCacheEnabled, "iocache"); // io cache size ADDXMLINT32U(machine->GetIOCacheSize, "iocachesize"); // chipset type ADDXMLENUM(machine->GetChipsetType, "chipset", chipsetTypeConverter); // pointing hid type ADDXMLENUM(machine->GetPointingHIDType, "mouse", pointingHidTypeConverter); // keyboard hid type ADDXMLENUM(machine->GetKeyboardHIDType, "keyboard", keyboardHidTypeConverter); // clipboard mode ADDXMLENUM(machine->GetClipboardMode, "clipboard", clipboardModeConverter); // vm state ADDXMLENUM(machine->GetState, "state", stateConverter); // vm state change ADDXMLTIMESTAMP(machine->GetLastStateChange, "statechanged"); // teleporterenabled, teleporterport, teleporteraddress, teleporterpassword // storage controller { IStorageController **storageControllers = nsnull; PRUint32 storageControllersCount = 0; rc = machine->GetStorageControllers(&storageControllersCount, &storageControllers); if (NS_SUCCEEDED(rc)) { for (PRUint32 i = 0; i < storageControllersCount; i++) { exportVirtualBoxStorageController(storageControllers[i], i, writer); } } NS_FREE_XPCOM_ISUPPORTS_POINTER_ARRAY(storageControllersCount, storageControllers); } // medium attachments { IMediumAttachment **mediumAttachments = nsnull; PRUint32 mediumAttachmentsCount = 0; rc = machine->GetMediumAttachments(&mediumAttachmentsCount, &mediumAttachments); if (NS_SUCCEEDED(rc)) { for (PRUint32 i = 0; i < mediumAttachmentsCount; i++) { exportVirtualBoxMediumAttachment(mediumAttachments[i], writer); } } NS_FREE_XPCOM_ISUPPORTS_POINTER_ARRAY(mediumAttachmentsCount, mediumAttachments); } // network adapters { PRUint32 networkAdaptersCount; PRUint32 chipsetType; rc = machine->GetChipsetType(&chipsetType); if (NS_SUCCEEDED(rc)) { rc = systemProperties->GetMaxNetworkAdapters(chipsetType, &networkAdaptersCount); if (NS_SUCCEEDED(rc)) { for (PRUint32 i = 0; i < networkAdaptersCount; i++) { nsCOMPtr<INetworkAdapter> networkAdapter; rc = machine->GetNetworkAdapter(i, getter_AddRefs(networkAdapter)); if (NS_SUCCEEDED(rc)) { exportVirtualBoxNetworkAdapter(networkAdapter, i + 1, writer); } } } } } // uartX // audio adapter { nsCOMPtr<IAudioAdapter> value; rc = machine->GetAudioAdapter(getter_AddRefs(value)); if (NS_SUCCEEDED(rc)) { exportVirtualBoxAudioAdapter(value, writer); } } // vrde server { nsCOMPtr<IVRDEServer> value; rc = machine->GetVRDEServer(getter_AddRefs(value)); if (NS_SUCCEEDED(rc)) { exportVirtualBoxVRDEServer(value, writer); } } // usb controllers // { // nsCOMPtr<IUSBController> value; // rc = machine->GetUSBController(getter_AddRefs(value)); // if (NS_SUCCEEDED(rc)) { // exportVirtualBoxUSBController(value, writer); // } // } // guest properties { PRUnichar **names = nsnull; PRUnichar **values = nsnull; PRInt64 *timestamps = nsnull; PRUnichar **flags = nsnull; PRUint32 namesCount = 0; PRUint32 valuesCount = 0; PRUint32 timestampsCount = 0; PRUint32 flagsCount = 0; rc = machine->EnumerateGuestProperties((const PRUnichar*)nsnull, &namesCount, &names, &valuesCount, &values, ×tampsCount, ×tamps, &flagsCount, &flags); if (NS_SUCCEEDED(rc)) { for (PRUint32 i = 0; i < namesCount; i++) { nsAutoString name(names[i]); nsAutoString value(values[i]); PRUint64 timestamp = timestamps[i]; nsAutoString flag(flags[i]); WRITEXMLSTRING(convertString(name).c_str(), convertString(value)); } } NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(namesCount, names); NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(valuesCount, values); nsMemory::Free(timestamps); NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(flagsCount, flags); } xmlTextWriterEndElement(writer); } }
inline bool SieveOfAtkin::getBit(const unsigned index) { return sieve[index/DWORD_BITS] & flag(index%DWORD_BITS); }