void cv::split(const Mat& m, vector<Mat>& mv)
{
    mv.resize(!m.empty() ? m.channels() : 0);
    if(!m.empty())
        split(m, &mv[0]);
}
Example #2
0
  void GBitset::matExpDispers(vector<vector<int> > &INFase,
							  vector<vector<int> > &INGilb,
							  vector<int> &LFase,
							  vector<int> &LGilb
							  ){

   int y,x,n;
   int d,p,Nf,Ng,BAD=9999;
   int Porog,Delta;             // Delta число отбрасываемых отсчетов на хвостах
   //int sizeNcol=ncolumns;     // ГОРИЗОНТАЬНЫЙ РАЗМЕР ПЕЧА  w=ncolumns;
   int size=nrows;              // ВЕРТИКАЛЬНЫЙ РАЗМЕР ПЕЧА   h=nrows;


			LFase.resize(N0Fase);
			for ( y=0; y < N0Fase;  y++ ){ LFase[y]=BAD; }

			// преобразование массива срезов в один массив
			// фильтрация по порогу
	   Porog=nrows/8;     // расстояние между срезами в пикселях для угла <45гр
	   if ( Porog>ncolumns/(nfas+1)) Porog=ncolumns/(nfas+1);  // 67
	   d=0;  //  Porog=100;
	   for ( n=1; n < nfas; n++ ) {
			 for (  y=1; y < INGilb[n][0]+1 && y<size-1; y++ ){
				  if ( abs(INGilb[n][y])< Porog )
				  { LFase[d]=INGilb[n][y]; d++; }
				 }//for y
			}//for n

			//  SumNAmp суммарное число хороших отсчетов по всем слайсам
			SumNAmp=d;

 // Вызов подпрограммы расчета распределения вероятностей, фильтрация по порогу,
			// отбрасывание хвостов распределения по адаптивному порогу т.е.отбрасываем
			// Delta штук самых больших и самых маленьких отсчетов по всему массиву.
			Delta=SumNAmp/20+1;  // Delta=2;
			ScheduleProbability(LFase,LGilb, Porog, Delta);
/* */
#ifdef DEBUGLVL
/*
				   // ВИЗУАЛИЗАЦИЯ цифровая 1
			  DM(END);
		 //     Nf = INFase[0].size();
			  for ( y=0; y < N0Fase;  y++ ){      // y < d+1;
				DM(LFase[y]<<"\t"); if (y%10==0)DM(END);  /// ТАБЛИЦА
				  }//for y
			  DM(END);

					// ВИЗУАЛИЗАЦИЯ цифровая 2
			  DM(END);
			  Ng = INGilb[0].size();
			  for ( y=1; y < Ng;  y++ ){      // y < d+1;
				DM(INGilb[10][y]<<"\t"); if (y%10==0)DM(END);  /// ТАБЛИЦА
				  }//for y
			  DM(END);

					// ВИЗУАЛИЗАЦИЯ  параметров
			DM(SumNAmp<<" SumNAmp ");  DM(Delta<<" Delta ");
	 DM(Porog<<" Porog "); DM(N0Fase<<" N0Fase "); DM(N0Gilb<<" N0Gilb "); DM(END);

*/
#endif

}//_____________________________________________________________________________
Example #3
0
void train_online(char *model_file_name, char *input_file_name)
{
    int t1,t2=0,i,s,l,j;
    double timer=0;
    stopwatch *sw; // start measuring time after loading is finished (not true for fulltime)
    sw=new stopwatch;    // save timing information
    char t[1000];
    strcpy(t,model_file_name);
    strcat(t,".time");
    	
    lasvm_kcache_t *kcache = lasvm_kcache_create(kernel, NULL);
    lasvm_kcache_set_maximum_size (kcache, cache_size*1024*1024);
    lasvm_t *sv = lasvm_create (kcache, use_b0, C*C_pos, C*C_neg);
	if (verbosity > 0)
		Rcout << "set cache size to " << cache_size << "\n";

    // everything is new when we start
    for(i=0;i<m;i++) inew.push_back(i);
    
    // first add 5 examples of each class, just to balance the initial set
    int c1=0,c2=0;
    for(i=0;i<m;i++)
    {
        if(Y[i]==1 && c1<5) {lasvm_process(sv,i,(double) Y[i]); c1++; make_old(i);}
        if(Y[i]==-1 && c2<5){lasvm_process(sv,i,(double) Y[i]); c2++; make_old(i);}
        if(c1==5 && c2==5) break;
    }
    
    for(j=0;j<epochs;j++)
    {
		Rcpp::checkUserInterrupt();
		int steps = 10;
		if (m < 2*steps)
			steps = m;
		for(i=0;i<m;i++)
        {
			if(inew.size()==0) break; // nothing more to select
            s=select(sv);            // selection strategy, select new point
            
            t1=lasvm_process(sv,s,(double) Y[s]);
            
			if (deltamax<=1000) // potentially multiple calls to reprocess..
            {
                //printf("%g %g\n",lasvm_get_delta(sv),deltamax);
                t2=lasvm_reprocess(sv,epsgr);// at least one call to reprocess
				// actally this does not work with multiple times, and we do not intent to anyway.
				//std::cout << "i=" << i << "  m=" << m << "  m/10=" << m/10 << "\n";
				if (i % steps == 1) 
				{
					if (termination_type==TIME && sw->get_time()>=select_size[0])
					{
						// goto is completely underrated. please do more gotos.
						goto goto80;
					}
				}	
				while (lasvm_get_delta(sv)>deltamax && deltamax<1000)
                {
                    t2=lasvm_reprocess(sv,epsgr);
				}
            }
            
            if (verbosity==2) 
            {
                l=(int) lasvm_get_l(sv);
                Rcout << "l=" << l << " process=" << t1 << " reprocess=" << t2 << "\n";
            }
            else
                if(verbosity==1) {
                    if( (i%100)==0) { 
						Rcout << ".." << i << flush; 
						Rcpp::checkUserInterrupt();
					}
				}
            
            l=(int) lasvm_get_l(sv);
			if   ( (termination_type==ITERATIONS && i==select_size[0]) 
					|| (termination_type==SVS && l>=select_size[0])
					|| (termination_type==TIME && sw->get_time()>=select_size[0])
				)
			{  
				select_size.pop_back();
			}
            if(select_size.size()==0) break; // early stopping, all intermediate models saved
        }

        inew.resize(0);iold.resize(0); // start again for next epoch..
        for(i=0;i<m;i++) inew.push_back(i);
    }

goto80: 
    if(saves<2) 
    {
        finish(sv); // if haven't done any intermediate saves, do final save
        timer+=sw->get_time();
        //f << m << " " << count_svs() << " " << kcalcs << " " << timer << endl;
    }

    if(verbosity>0) {
		Rcout << "\n";
		l=count_svs(); 
		Rcout << "nSVs=" << l << "\n";
		Rcout << "||w||^2=" << lasvm_get_w2(sv) << "\n";
		Rcout << "kcalcs=" << kcalcs << endl;
	}
	
    //f.close();
    lasvm_destroy(sv);
    lasvm_kcache_destroy(kcache);
	delete sw;
}
int ReadLTraceLog(char* filename)
{
	char buf[2048];
	FILE *fp;

	pcre	*re;
	const char      *error;
	int             erroffset;
	int OVECCOUNT = 30;
	int rc;
	int             ovector[OVECCOUNT];
	const char pattern[] = "\\[0x([0-9a-fA-F]+)\\][\\s]+([a-zA-Z_0-9]+)[\\s]*(\\([^\\n\\r]+)";
	char entry_func[512];
	unsigned long long entry_addr, effective_addr;

	int nTokenStartCallUsageCheck = 0;
	int nTokenEndCallUsageCheck = 0;

	violations.resize(0);
	
	re = pcre_compile(pattern,0, &error, &erroffset, NULL);

	if (re == NULL) {
		log("PCRE compilation failed at offset %d: %s\n", erroffset, error);
		return -1;
    }

	
	fp = fopen(filename, "rt");
	
	if ( !fp) {
		log("failed to open %s", filename);
		return -2;
	}

	entry_func[0] = 0;
	
	while(fgets(buf, sizeof(buf), fp) ) {
		
		if ( strstr(buf, "__libc_start_main"))
			continue;
		
		rc = pcre_exec(re, NULL, buf, strlen(buf), 0, 0, ovector, OVECCOUNT);

		if ( rc==1+3){
			char sz_addr[512];
			char syscall_name[512];
			char call_argument[1024];
			unsigned long long addr;


			//printf("rc=%d\n", rc);
				
				
			sprintf(sz_addr, "%.*s", ovector[3]-ovector[2], buf+ovector[2]);
			sprintf(syscall_name, "%.*s", ovector[5]-ovector[4], buf+ovector[4]);
			sprintf(call_argument, "%.*s", ovector[7]-ovector[6], buf+ovector[6]);

			effective_addr = addr = strtoull(sz_addr, 0, 16);			
			
			if ( entry_func[0] )
				effective_addr = entry_addr;
			
			
			if ( nDEBUG_LEVEL > 2) {
				if ( entry_func[0] == 0)
					log("[%llx] @ [%llx] [%s] [%s] bCALL_USAGE_CHECK_ENABLED=%d", effective_addr, addr, syscall_name, call_argument, bCALL_USAGE_CHECK_ENABLED);
				else
					log("[%llx] @ [%llx][%s] -> [%llx] [%s] [%s] bCALL_USAGE_CHECK_ENABLED=%d", effective_addr, entry_addr, entry_func, addr, syscall_name, call_argument,bCALL_USAGE_CHECK_ENABLED);
			}
			
			if ( entry_addr==0 && strstr(buf,"<unfinished")) {
				entry_addr = addr;
				strcpy(entry_func, syscall_name);
			}
			
			//////// check

			if ( !strcmp(syscall_name, "SYS_fstat"))	{	/// to detect StartCallUsageCheck / EndCallUsageCheck
				long long nToken;

				if ( !ExtractNumber(nToken, call_argument, "\\(",  ",") )
					goto quit_start_end_tokens;

				if ( nToken ==  TOKEN_START_CALL_USAGE_CHECK[nTokenStartCallUsageCheck]) {
					nTokenStartCallUsageCheck++;

					if ( TOKEN_START_CALL_USAGE_CHECK[nTokenStartCallUsageCheck]==0) { // all checks passed
						bCALL_USAGE_CHECK_ENABLED = true;
						nTokenStartCallUsageCheck = 0;
						nTokenEndCallUsageCheck = 0;
					}

					goto nextone;
				}
				else if (nTokenStartCallUsageCheck)
					goto quit_start_end_tokens;

				if (nToken == TOKEN_END_CALL_USAGE_CHECK[nTokenEndCallUsageCheck]) {
					nTokenEndCallUsageCheck++;

					if ( TOKEN_END_CALL_USAGE_CHECK[nTokenEndCallUsageCheck]==0) { // all checks passed
						bCALL_USAGE_CHECK_ENABLED = false;
						nTokenStartCallUsageCheck = 0;
						nTokenEndCallUsageCheck = 0;
					}

					goto nextone;
				}
				else if ( nTokenEndCallUsageCheck)
					goto quit_start_end_tokens;



			}
			else {
quit_start_end_tokens:;
				nTokenStartCallUsageCheck = 0;
				nTokenEndCallUsageCheck = 0;
			}



			if ( !bCALL_USAGE_CHECK_ENABLED)
				goto nextone;
			if ( IsAddrInSkipRange(effective_addr))
				goto nextone;
/*				
			 if ( !IsAddrInAlertRanges(effective_addr) )
				 goto nextone;
*/
			/////////////// check blacklist ///////////////
			{
				int k;

				for ( k = 0; k < disallowed_func.size(); k++) {
					char buf[512];

					if ( !strcmp(syscall_name, disallowed_func[k].c_str())) 
						goto match_found;
/* Hank 2011.6.8
					sprintf(buf, "SYS_%s", disallowed_func[k].c_str());
					if (!strcmp(syscall_name, buf))
						goto match_found;
*/
					continue;
match_found:;
					log("[%s] vs [%s]", syscall_name, disallowed_func[k].c_str());
					add_violation( effective_addr, syscall_name);
					goto nextone;

				}

			}

			//////////check direct system call////////////

			//// check direct system call
			if ( bAllowDirectSyscall == false ) {
				if ( effective_addr == addr && IsAddrInAlertRanges(effective_addr) && !strncmp(syscall_name, "SYS_",4) ) {
					add_violation(effective_addr, syscall_name);
					goto nextone;
					//goto add_violation;
				}
			}
#if 0
			int m;
			
			for ( m = 0; m < alert_ranges.size(); m++) {
				// check range;				
				if ( effective_addr >= alert_ranges[m].start_addr && effective_addr <= alert_ranges[m].end_addr) {

					int k = 0;
			
					//// check direct system call
					if ( bAllowDirectSyscall == false) {
						if ( effective_addr == addr && !strncmp(syscall_name, "SYS_",4) ) {
							add_violation(effective_addr, syscall_name);
							goto nextone;
							//goto add_violation;
						}
					}

		
				}
			}
#endif
			
nextone:;
			
		}
		else if ( strstr(buf, "resumed>") && strstr(buf,entry_func)) {
			entry_func[0] = 0;
			entry_addr = 0;
		}
			
		
	}
	
	pcre_free(re);
	
	
	return 0;
} 
Example #5
0
 Graph(int _V = 0) : V(_V) {
     adj.resize(V);
 }
const vector<string>& CCobUnitScriptNames::GetScriptNames()
{
	static vector<string> scriptNames;

	if (!scriptNames.empty()) {
		return scriptNames;
	}

	scriptNames.resize(COBFN_Last + (MAX_WEAPONS_PER_UNIT * COBFN_Weapon_Funcs));

	scriptNames[COBFN_Create]        = "Create";
	scriptNames[COBFN_Destroy]       = "Destroy";
	scriptNames[COBFN_StartMoving]   = "StartMoving";
	scriptNames[COBFN_StopMoving]    = "StopMoving";
	scriptNames[COBFN_Activate]      = "Activate";
	scriptNames[COBFN_Killed]        = "Killed";
	scriptNames[COBFN_Deactivate]    = "Deactivate";
	scriptNames[COBFN_SetDirection]  = "SetDirection";
	scriptNames[COBFN_SetSpeed]      = "SetSpeed";
	scriptNames[COBFN_RockUnit]      = "RockUnit";
	scriptNames[COBFN_HitByWeapon]   = "HitByWeapon";
	scriptNames[COBFN_MoveRate0]     = "MoveRate0";
	scriptNames[COBFN_MoveRate1]     = "MoveRate1";
	scriptNames[COBFN_MoveRate2]     = "MoveRate2";
	scriptNames[COBFN_MoveRate3]     = "MoveRate3";
	scriptNames[COBFN_SetSFXOccupy]  = "setSFXoccupy";
	scriptNames[COBFN_HitByWeaponId] = "HitByWeaponId";

	scriptNames[COBFN_QueryLandingPadCount] = "QueryLandingPadCount";
	scriptNames[COBFN_QueryLandingPad]      = "QueryLandingPad";
	scriptNames[COBFN_Falling]              = "Falling";
	scriptNames[COBFN_Landed]               = "Landed";
	scriptNames[COBFN_BeginTransport]       = "BeginTransport";
	scriptNames[COBFN_QueryTransport]       = "QueryTransport";
	scriptNames[COBFN_TransportPickup]      = "TransportPickup";
	scriptNames[COBFN_StartUnload]          = "StartUnload";
	scriptNames[COBFN_EndTransport]         = "EndTransport";
	scriptNames[COBFN_TransportDrop]        = "TransportDrop";
	scriptNames[COBFN_SetMaxReloadTime]     = "SetMaxReloadTime";
	scriptNames[COBFN_StartBuilding]        = "StartBuilding";
	scriptNames[COBFN_StopBuilding]         = "StopBuilding";
	scriptNames[COBFN_QueryNanoPiece]       = "QueryNanoPiece";
	scriptNames[COBFN_QueryBuildInfo]       = "QueryBuildInfo";
	scriptNames[COBFN_Go]                   = "Go";

	// Also add the weapon aiming stuff
	for (int i = 0; i < MAX_WEAPONS_PER_UNIT; ++i) {
		char buf[15];
		sprintf(buf, "Weapon%d", i + 1);
		string weapon(buf);
		sprintf(buf, "%d", i + 1);
		string weapnum(buf);
		const int n = COBFN_Weapon_Funcs * i;
		scriptNames[COBFN_QueryPrimary   + n] = "Query"   + weapon;
		scriptNames[COBFN_AimPrimary     + n] = "Aim"     + weapon;
		scriptNames[COBFN_AimFromPrimary + n] = "AimFrom" + weapon;
		scriptNames[COBFN_FirePrimary    + n] = "Fire"    + weapon;
		scriptNames[COBFN_EndBurst       + n] = "EndBurst"     + weapnum;
		scriptNames[COBFN_Shot           + n] = "Shot"         + weapnum;
		scriptNames[COBFN_BlockShot      + n] = "BlockShot"    + weapnum;
		scriptNames[COBFN_TargetWeight   + n] = "TargetWeight" + weapnum;
	}

	//for (size_t i = 0; i < scriptNames.size(); ++i) {
	//	logOutput.Print("COBFN: %3d %s", i, scriptNames[i].c_str());
	//}

	return scriptNames;
}
Example #7
0
void readMap()
{
    string doorIdToLoSymbol;
    string doorIdToHiSymbol;
    string doorIdToType;
    unordered_map<char,pair<ull,bool> > doorSymbolToId;
    int numAgents, numDoors;
    
    cin >> doorIdToLoSymbol >> doorIdToHiSymbol >> doorIdToType;
    numDoors = doorIdToType.length();
    assert(numDoors <= 64);
    assert(numDoors == doorIdToLoSymbol.length());
    assert(numDoors == doorIdToHiSymbol.length());
    //doorSymbolToId.clear();
    for (int i = 0; i < numDoors; ++i)
    {
        ull doorMask = 1ull << i;
        assert(doorSymbolToId.find(doorIdToLoSymbol[i]) == doorSymbolToId.end());
        assert(doorSymbolToId.find(doorIdToHiSymbol[i]) == doorSymbolToId.end());
        assert(doorIdToType[i] == 'O' || doorIdToType[i] == 'C');
        doorSymbolToId[doorIdToLoSymbol[i]] = make_pair(doorMask, false);
        doorSymbolToId[doorIdToHiSymbol[i]] = make_pair(doorMask, true);
        if (doorIdToType[i] == 'O')
            takeMin[0] |= doorMask;
        takeMin[1] |= doorMask;
    }
    cin >> numAgents;
    agents.resize(numAgents);
    for (Agent& agent : agents)
    {
        cin >> agent.numRows >> agent.numCols;
        agent.startPos = agent.goal.pos = nullptr;
        agent.raw_grid.resize(agent.numRows);
        agent.grid.resize(agent.numRows);
        agent.hDist.clear();
        for (int i = 0; i < agent.numRows; ++i)
        {
            agent.grid[i].resize(agent.numCols);
            cin >> agent.raw_grid[i];
            assert(agent.raw_grid[i].length() == agent.numCols);
            for (int j = 0; j < agent.numCols; ++j)
            {
                PositionNode* pos = &agent.grid[i][j];
                agent.hDist[pos] = INFINITE;
                pos->x = i;
                pos->y = j;
                pos->obst = false;
                pos->mask = 0;
                switch (agent.raw_grid[i][j])
                {
                    case '.':
                        break;
                    case '!':
                        assert(agent.startPos == nullptr);
                        agent.startPos = pos;
                        break;
                    case '#':
                        assert(agent.goal.pos == nullptr);
                        agent.goal.pos = pos;
                        break;
                    case '@':
                        pos->obst = true;
                        break;
                    default:
                        assert(doorSymbolToId.find(agent.raw_grid[i][j]) != doorSymbolToId.end());
                        tie(pos->mask, pos->late) = doorSymbolToId[agent.raw_grid[i][j]];
                }
            }
        }
        assert(agent.startPos != nullptr && agent.goal.pos != nullptr);
        assert(agent.startPos->mask == 0 && agent.goal.pos->mask == 0);
        // compute relaxed distance estimates for the heuristic
        unordered_set<PositionNode*> visited;
        queue<PositionNode*> Q;
        agent.hDist[agent.startPos] = 0;
        Q.push(agent.startPos);
        visited.insert(agent.startPos);
        while (!Q.empty())
        {
            PositionNode* curPos = Q.front(); Q.pop();
            visited.insert(curPos);
            for (int d = 0; d < DIRS; ++d)
            {
                int xx = curPos->x + dx[d];
                int yy = curPos->y + dy[d];
                if (0 <= xx && xx < agent.numRows && 0 <= yy && yy < agent.numCols)
                {
                    PositionNode* nextPos = &agent.grid[xx][yy];
                    if (!nextPos->obst && visited.find(nextPos) == visited.end())
                    {
                        agent.hDist[nextPos] = min(agent.hDist[nextPos], agent.hDist[curPos] + dcost[d]);
                        Q.push(nextPos);
                        visited.insert(nextPos);
                    }
                }
            }
        }
    }
}
void TriMeshObjLoader::read_material_library(const string& filename, vector<ObjMaterial>& materials)
{
	string fn = pathname + filename;
	FILE* file = fopen(fn.data(), "r");
	if (!file) 
		{
			cerr << "Could not open " << filename << endl;
			return;
		}
		
	char  buf[128];
	unsigned int nummaterials=1;
		
	// count the number of materials in the file 
	while(fscanf(file, "%s", buf) != EOF) 
		{
			switch(buf[0]) 
				{
				case '#':				/* comment */
					/* eat up rest of line */
					fgets(buf, sizeof(buf), file);
					break;
				case 'n':				/* newmtl */
					fgets(buf, sizeof(buf), file);
					nummaterials++;
					sscanf(buf, "%s %s", buf, buf);
					break;
				default:
					/* eat up rest of line */
					fgets(buf, sizeof(buf), file);
					break;
				}
		}
	rewind(file);
	
	/* allocate memory for the materials */
	materials.resize(nummaterials);

	/* now, read in the data */
	nummaterials = 0;
	while(fscanf(file, "%s", buf) != EOF) {
		switch(buf[0]) {
		case '#':				/* comment */
			/* eat up rest of line */
			fgets(buf, sizeof(buf), file);
			break;
		case 'n':				/* newmtl */
			fgets(buf, sizeof(buf), file);
			sscanf(buf, "%s %s", buf, buf);
			nummaterials++;
			materials[nummaterials].name = buf;
			break;
		case 'N':
      switch(buf[1])
        {
        case 's':
			    fscanf(file, "%f", &materials[nummaterials].shininess);
          break;
        case 'i':
			    fscanf(file, "%f", &materials[nummaterials].ior);
          break;
				default:
					/* eat up rest of line */
					fgets(buf, sizeof(buf), file);
					break;
        }
			break;
		case 'K': 
			switch(buf[1]) 
				{
				case 'd':
					fscanf(file, "%f %f %f",
								 &materials[nummaterials].diffuse[0],
								 &materials[nummaterials].diffuse[1],
								 &materials[nummaterials].diffuse[2]);
					break;
				case 's':
					fscanf(file, "%f %f %f",
								 &materials[nummaterials].specular[0],
								 &materials[nummaterials].specular[1],
								 &materials[nummaterials].specular[2]);
					break;
				case 'a':
					fscanf(file, "%f %f %f",
								 &materials[nummaterials].ambient[0],
								 &materials[nummaterials].ambient[1],
								 &materials[nummaterials].ambient[2]);
					break;
				default:
					/* eat up rest of line */
					fgets(buf, sizeof(buf), file);
					break;
				}
			break;
    case 'T':
			fscanf(file, "%f %f %f",
             &materials[nummaterials].transmission[0],
             &materials[nummaterials].transmission[1],
             &materials[nummaterials].transmission[2]);
      break;
    case 'i':
			fscanf(file, "%d", &materials[nummaterials].illum);
      break;
		case 'm': // Map ... all maps are treated equally.
			{
				fscanf(file,"%s",buf);
				materials[nummaterials].tex_path = pathname;
				materials[nummaterials].tex_name = string(buf);
        materials[nummaterials].has_texture = true;
			}
			break;
		default:
			/* eat up rest of line */
			fgets(buf, sizeof(buf), file);
			break;
		}
	}
  fclose(file);
}
Example #9
0
void Shoot(Tank & self, World & world, model::Move& move)
{
	 vector<Tank> t = world.tanks();

	/* always keep tower to some enemy */

	Tank * pEnemy = get_need_id(g_lock_id, t);

	if ( EnemyDead(pEnemy) )
	{
		pEnemy = 0;
	}

	/* not locked to anyone, select some, or change target every 300 tick */

	if (!pEnemy || world.tick() % 300 == 0)
	{
		Tank * pOldEnemy = pEnemy;
		pEnemy = get_best_enemy(self, t);

		if (pEnemy != pOldEnemy)
		{
			waves.clear();
			stats.clear();
			stats.resize(30);
		}
	}

	/* still bad luck ? */

	if (!pEnemy)
	{
		/* MoveAlgo */
		return;
	}

	double absBearing = self.GetAngleTo(*pEnemy);

	for (int i=0; i < waves.size(); i++)
	{
		if (waves[i].checkHit(self, pEnemy, world.tick()))
		{
			waves.erase(waves.begin() + i );
			i--;
		}
	}

	double power = 16.7;

	double e_velocity = sqrt( pEnemy->speed_x()*pEnemy->speed_x() + pEnemy->speed_y()*pEnemy->speed_y() );

	WaveBullet newWave( self.x(), self.y(), self.angle(), absBearing, power,
                        direction, world.tick(), &stats );

	int bestindex = 15;	
	for (int i=0; i<30; ++i)
	{
		if (stats[bestindex] < stats[i])
		{
			bestindex = i;
		}
	}
 
	double guessfactor = ( bestindex - ( (double)stats.size() - 1 )/2 ) / ( ( (double)stats.size() - 1) / 2) ;

	if (e_velocity > 0.01)
	{
		if ( sin( pEnemy->angle() - self.angle()  ) < 0 )
		{
			direction = -1;
		}
		else
		{
			direction = 1;
		}
	}

	double angleOffset = direction * guessfactor * newWave.maxEscapeAngle();

	/* got lock? move turret! */

	MoveTurretOrShoot( pEnemy, self, world, move, 0.0 );
	waves.push_back(newWave);
}
Example #10
0
  virtual void Handle_Keypress(unsigned char key,int x,int y)
  {
    switch(key) {
    case 'h':
      printf("Help:\n");
      printf("[space]: next link\n");
      printf("z: previous link\n");
      printf("+: increase joint value by 0.1\n");
      printf("-: decrease joint value by 0.1\n");
      printf("d: in pose-by-IK mode, delete constraint\n");
      printf("c: in pose-by-IK mode, constrain current rotations\n");
      printf("p: print the current configuration\n");
      break;
    case ' ':
      cur_link++;
      if(cur_link >= (int)robot->links.size()) cur_link=0;
      UpdateCurLinkGUI();
      UpdateLinkValueGUI();
      break;
    case 'z':
      cur_link--;
      if(cur_link < 0) cur_link = robot->links.size()-1;
      UpdateCurLinkGUI();
      UpdateLinkValueGUI();
      break;
    case '+':
    case '=':
      {
	Real val = robot->q(cur_link)+0.1;
	robot->q(cur_link) = Clamp(val,robot->qMin(cur_link),robot->qMin(cur_link));
	UpdateConfig();
	UpdateLinkValueGUI();
      }
      break;
    case '-':
    case '_':
      {
	Real val = robot->q(cur_link)-0.1;
	robot->q(cur_link) = Clamp(val,robot->qMin(cur_link),robot->qMin(cur_link));
	UpdateConfig();
	UpdateLinkValueGUI();
      }
      break;
    case 'c':
      if(true || pose_ik) {
	if(hoverLink < 0) {
	  printf("Before constraining a link you need to hover over it\n");
	}
	else {
	  for(size_t i=0;i<poseGoals.size();i++)
	    if(poseGoals[i].link == hoverLink) {
	      poseGoals.erase(poseGoals.begin()+i);
	      poseWidgets.erase(poseWidgets.begin()+i);
	      break;
	    }
	  printf("Fixing link %s\n",robot->LinkName(hoverLink).c_str());
	  poseGoals.resize(poseGoals.size()+1);
	  poseGoals.back().link = hoverLink;
	  poseGoals.back().localPosition = robot->links[hoverLink].com;
	  poseGoals.back().SetFixedPosition(robot->links[hoverLink].T_World*robot->links[hoverLink].com);
	  poseGoals.back().SetFixedRotation(robot->links[hoverLink].T_World.R);
	  poseWidgets.resize(poseWidgets.size()+1);
	  poseWidgets.back().T.R = robot->links[hoverLink].T_World.R;
	  poseWidgets.back().T.t = poseGoals.back().endPosition;
	}
      }
      break;
    case 'd':
      if(hoverWidget != -1) {
	printf("Deleting IK goal on link %s\n",robot->LinkName(poseGoals[hoverWidget].link).c_str());
	poseGoals.erase(poseGoals.begin()+hoverWidget);
	poseWidgets.erase(poseWidgets.begin()+hoverWidget);
	hoverWidget = -1;
      }
      else {
	for(size_t i=0;i<poseGoals.size();i++)
	  if(poseGoals[i].link == hoverLink) {
	    printf("Deleting IK goal on link %s\n",robot->LinkName(hoverLink).c_str());
	    poseGoals.erase(poseGoals.begin()+i);
	    poseWidgets.erase(poseWidgets.begin()+i);
	    break;
	  }
      }
      break;
    case 'p':
      cout<<robot->q<<endl;
      break;
    }
    Refresh();
  }
Example #11
0
  virtual bool Initialize()
  {
    cur_link=0;
    cur_driver=0;
    link_value = 0;
    driver_value = 0;
    draw_geom = 1;
    draw_bbs = 0;
    draw_com = 0;
    draw_frame = 0;
    draw_expanded = 0;
    draw_self_collision_tests = 0;
    hoverLink=hoverWidget=-1;
    hoverPt.setZero();
    pose_ik = 0;
    if(!RobotViewProgram::Initialize()) return false;
    self_colliding.resize(robot->links.size(),false);   
    UpdateConfig();

    /*
    //TEST: robot-to-robot IK test.  only works for AL5Dx2
    IKGoal test;
    test.link = 8;
    test.destLink = 16;
    test.localPosition.set(0,0,0.05);
    test.endPosition.set(0,0,0.05);
    //test.SetFixedPosition(test.endPosition);
    Matrix3 R;
    R.setRotateZ(120);
    test.SetFixedRotation(R);

    vector<IKGoal> problem(1,test);
    int iters=100;
    bool res=SolveIK(*robot,problem,1e-3,iters);
    printf("Solved IK: %d, %d iters, error %g\n",(int)res,iters,RobotIKError(*robot,test));
    UpdateConfig();
    */

    //setup GUI 
    glui = GLUI_Master.create_glui_subwindow(main_window,GLUI_SUBWINDOW_RIGHT);
    glui->set_main_gfx_window(main_window);
    GLUI_Panel* panel = glui->add_panel("Link controls");
    link_spinner = glui->add_spinner_to_panel(panel,"Index",GLUI_SPINNER_INT,&cur_link,LINK_SPINNER_ID,ControlFunc);
    link_spinner->set_int_limits(0,robot->links.size()-1,GLUI_LIMIT_WRAP);

    link_listbox = glui->add_listbox_to_panel(panel,"Name",&cur_link,LINK_LISTBOX_ID,ControlFunc);
    for(size_t i=0;i<robot->links.size();i++) {
      char buf[256];
      strcpy(buf,robot->linkNames[i].c_str());
      link_listbox->add_item(i,buf);
    }

    link_value_spinner = glui->add_spinner_to_panel(panel,"Angle",GLUI_SPINNER_FLOAT,&link_value,LINK_VALUE_SPINNER_ID,ControlFunc);
    link_info = glui->add_statictext_to_panel(panel,"Info");
    UpdateLinkValueGUI();
    UpdateLinkInfoGUI();

    panel = glui->add_panel("Driver controls");
    glui->add_checkbox_to_panel(panel,"Pose by IK",&pose_ik);
    driver_spinner = glui->add_spinner_to_panel(panel,"Index",GLUI_SPINNER_INT,&cur_driver,DRIVER_SPINNER_ID,ControlFunc);
    driver_spinner->set_int_limits(0,(int)robot->drivers.size()-1,GLUI_LIMIT_WRAP);

    driver_listbox = glui->add_listbox_to_panel(panel,"Name",&cur_driver,DRIVER_LISTBOX_ID,ControlFunc);
    for(size_t i=0;i<robot->drivers.size();i++) {
      char buf[256];
      strcpy(buf,robot->driverNames[i].c_str());
      driver_listbox->add_item(i,buf);
    }

    driver_value_spinner = glui->add_spinner_to_panel(panel,"Angle",GLUI_SPINNER_FLOAT,&driver_value,DRIVER_VALUE_SPINNER_ID,ControlFunc);
    driver_info = glui->add_statictext_to_panel(panel,"Info");

    glui->add_checkbox("Draw geometry",&draw_geom);
    glui->add_checkbox("Draw COM",&draw_com);
    glui->add_checkbox("Draw frame",&draw_frame);
    glui->add_checkbox("Draw bboxes",&draw_bbs);
    glui->add_checkbox("Draw expanded",&draw_expanded,DRAW_EXPANDED_CHECKBOX_ID,ControlFunc);
    glui->add_checkbox("Draw collision tests",&draw_self_collision_tests);
    UpdateDriverValueGUI();
    UpdateDriverInfoGUI();
    return true;
  }
Example #12
0
bool GpsSim::initialize(int argc, char *argv[]) throw()
{
   CommandOptionWithAnyArg
      codeOpt('c', "code",
              "Generate the signal defined by the argument. ARG takes "
              "the form of code:carrier:prn:offset:doppler:nav. Code is either "
              "c, p, or cp. Carrier is either 1 or 2. Prn is an integer between 1 "
              "and 32. Offset is a number in microseconds. Doppler is a number "
              "in Hz. Nav is 0, c, p, or cp. For example, to generate C/A on L1 for "
              "PRN 15 with zero time-offset, zero doppler, a dummy nav signal "
              "on both C/A and P, then specify -c c:1:15:0:p.  This option "
              "may be repeated to simulate multiple signals.");

   CommandOptionNoArg
      codeOnlyOpt('\0', "code-only",
                  "Only generate the codes. No carrier, no hetrodyning.");

   CommandOptionWithAnyArg
      sampleRateOpt('r',"sample-rate",
                    "Specifies the nominal sample rate, in MHz.  The "
                    "default is 20 MHz.");

   CommandOptionWithAnyArg
      interFreqOpt('x',"inter-freq",
                   "Specifies the intermediate frequency of the receiver,"
                   " in MHz.  Default is 0.42 MHz.");

   CommandOptionWithAnyArg
      quantizationOpt('q', "quantization",
                      "What type of IQ stream; 1, 2 or f. The default is f.");

   CommandOptionWithAnyArg
      gainOpt('g', "gain",
              "Gain to apply to the if prior to digitization, in dB. Default is 0.");

   CommandOptionWithAnyArg
      noiseGainOpt('n', "noise",
                   "Specify the gain (in dB) for the receiver's noise. The "
                   "default is 0 dB");

   CommandOptionWithAnyArg
      freqErrOpt('f', "freq-err",
                 "Specify the frequency error on the local receiver's "
                 "oscilator, in ppm. The default is 0 ppm");

   CommandOptionWithAnyArg
      runTimeOpt('t', "run-time",
                 "How long (in ms) to run the simulation for. The default is 20 ms");

   CommandOptionWithAnyArg
      outputOpt('o', "output",
                 "Where to write the output. The default is stdout");

   if (!BasicFramework::initialize(argc,argv))
      return false;

   using namespace gpstk::StringUtils;

   char quantization='f';
   if (quantizationOpt.getCount())
      quantization = quantizationOpt.getValue()[0][0];
   switch (quantization)
   {
      case '1': output = new IQ1Stream(); break;
      case '2': output = new IQ2Stream(); break;
      case 'f':
      default:  output = new IQFloatStream(); break;
   }

   if (sampleRateOpt.getCount()){
      rx_sample_rate = asDouble(sampleRateOpt.getValue().front()) * 1e6;
      time_step = 1.0/rx_sample_rate;
      samples_per_period = rx_sample_rate / 1e6;}

   if (interFreqOpt.getCount()){
      interFreq = asDouble(interFreqOpt.getValue().front()) * 1e6;
      rx_L1_LO = gpstk::L1_FREQ_GPS - interFreq;
      rx_L2_LO = gpstk::L2_FREQ_GPS - interFreq;}

   if (outputOpt.getCount())
   {
      output->open(outputOpt.getValue()[0].c_str(), ios::out);
   }
   else
   {
      using std::basic_ios;
      output->copyfmt(std::cout);
      output->clear(std::cout.rdstate());
      output->basic_ios<char>::rdbuf(std::cout.rdbuf());
      output->filename = "<stdout>";
   }
   if (debugLevel)
      cout << "Writing data to " << output->filename << endl;

   if (gainOpt.getCount())
   {
      double gainDb = StringUtils::asDouble(gainOpt.getValue()[0]);
      gain = exp10(gainDb/10);
      if (debugLevel)
         cout << "# Rx gain level: " << gainDb << " db ("
              << gain << ")" << endl;
   }

   if (noiseGainOpt.getCount())
   {
      double gain_local = StringUtils::asDouble(noiseGainOpt.getValue()[0]);
      noise_amplitude *= exp10(gain_local/10);
      if (debugLevel)
         cout << "# Noise level: " << gain_local << " db" << endl;
   }

   if (codeOnlyOpt.getCount())
      codeOnly = true;

   if (freqErrOpt.getCount())
      freqErr = StringUtils::asDouble(freqErrOpt.getValue()[0]) * 1e-6;
   else
      freqErr = 0;

   if (debugLevel)
      cout << "# Receiver frequency error: " << freqErr * 1e6 << " ppm" << endl;

   if (runTimeOpt.getCount())
   {
      double rt = asDouble(runTimeOpt.getValue()[0]);
      periods_to_generate = static_cast<long unsigned>(rt*1.0e6);
   }

   if (debugLevel)
      cout << "# Running for : " << periods_to_generate
           << " periods (" << 1e3 * periods_to_generate/1.0e6
           << " msec)" << endl;

   // Compute the local oscilator frequencies, units seem to be radians/sample
   omega_lo.resize(LO_COUNT);
   omega_lo[0] = 2.0*gpstk::PI*rx_L1_LO/rx_sample_rate;
   omega_lo[1] = 2.0*gpstk::PI*rx_L2_LO/rx_sample_rate;

   vector<double> lo(LO_COUNT);
   lo[0] = omega_lo[0]/time_step / 2 /PI;
   lo[1] = omega_lo[1]/time_step / 2 /PI;

   if (debugLevel)
      cout << "# LO 1: " << setw(7) << lo[0] * 1e-6<< " MHz"
           <<    "  2: " << setw(7) << lo[1] * 1e-6<< " MHz"
           <<  endl
           << "# IF 1: " << setw(7) << (L1_FREQ_GPS - lo[0]) * 1e-3<< " kHz"
           <<    "  2: " << setw(7) << (L2_FREQ_GPS - lo[1]) * 1e-3<< " kHz"
           <<  endl;

   for (int i=0; i < codeOpt.getCount(); i++)
   {
      string val=codeOpt.getValue()[i];
      const char delim(':');
      if (numWords(val, delim) != 6)
      {
         cout << "Error in code parameter:" << val << endl;
         exit(-1);
      }

      string code =   lowerCase(word(val, 0, delim));
      int    band =       asInt(word(val, 1, delim));
      int    prn =        asInt(word(val, 2, delim));
      double offset =  asDouble(word(val, 3, delim));
      double doppler = asDouble(word(val, 4, delim));
      string nav =    lowerCase(word(val, 5, delim));

      if (code.size() > 2 || nav.size() > 2 || band <1 || band > LO_COUNT ||
          prn < 1 || prn >32)
      {
         cout << "code:" << code << " band:" << band << " prn:" << prn
              << " offset:" << offset << " nav:" << nav << endl
              << "Error in specifying code. Ignoring this code." << endl;
         exit(-1);
      }

      // This is the number of P code chips in one sample. If this
      // is not around or less than 1/2, we have a problem
      double sampleRate = 1.0/(rx_sample_rate); //sec
      double chips_per_sample_base = gpstk::PY_CHIP_FREQ_GPS * sampleRate;

      switch(band)
      {
         case 1: doppler *= sampleRate / L1_MULT_GPS; break;
         case 2: doppler *= sampleRate / L2_MULT_GPS; break;
      }

      doppler *= 1-freqErr;
      chips_per_sample_base *= 1-freqErr;

      // Create and configure the SV source
      SVSource* src = new SVSource(prn, band);
      src->zchips_per_sample = chips_per_sample_base;
      src->doppler = doppler;
      src->ca_modulation = isLike(code, "c");
      src->p_modulation = isLike(code, "p");
      src->ca_nav = isLike(nav, "c") && src->ca_modulation;
      src->p_nav = isLike(nav, "p") && src->p_modulation;
      src->p_amplitude = p_amplitude;
      src->ca_amplitude = ca_amplitude;
      // offset needs to be provided to the SVSource in units of P chips
      src->slewZChipFraction(offset * gpstk::PY_CHIP_FREQ_GPS * 1.0e-6);

      if (codeOnlyOpt.getCount())
         src->code_only = true;

      if (debugLevel)
         src->dump(cout);

      sv_sources.push_back(src);
   }
   return true;

}
Example #13
0
void cv::gpu::split(const GpuMat& src, vector<GpuMat>& dst, Stream& stream)
{
    dst.resize(src.channels());
    if(src.channels() > 0)
        ::split(src, &dst[0], StreamAccessor::getStream(stream));
}
Example #14
0
inline void Encode(const vector<Unicode>& input, vector<string>& output) {
  output.resize(input.size());
  for (size_t i = 0; i < output.size(); i++) {
    Encode(input[i], output[i]);
  }
}
Example #15
0
void parseLine(const vector<string>& vs)
{
    //DONE: add parsing of NEAR, LEFT, RIGHT, BOTTOM, TOP, SPHERE, LIGHT, BACK, AMBIENT, OUTPUT.

	const int num_labels = 11;
	const string labels[] = { "NEAR",		//0
							"LEFT",			//1
							"RIGHT",		//2
							"BOTTOM",		//3
							"TOP",			//4
							"RES",			//5
							"SPHERE",		//6
							"LIGHT",		//7
							"BACK",			//8
							"AMBIENT",		//9
							"OUTPUT"		//10
	};
	unsigned label_id = find(labels, labels + num_labels, vs[0]) - labels;
	switch (label_id) {
		case 0:		g_near = toFloat(vs[1]);	break;		//NEAR
		case 1:		g_left = toFloat(vs[1]);	break;		//LEFT
		case 2:		g_right = toFloat(vs[1]);	break;		//RIGHT
		case 3:		g_bottom = toFloat(vs[1]);	break;		//BOTTOM
		case 4:		g_top = toFloat(vs[1]);		break;		//TOP
		case 5:												//RES
			g_width = (int)toFloat(vs[1]);
			g_height = (int)toFloat(vs[2]);
			g_colors.resize(g_width * g_height);
			break;
		case 6:												//SPHERE
		{
			Sphere new_sphere;
			new_sphere.center = toVec4(vs[2], vs[3], vs[4]);
			new_sphere.scale = vec3(toFloat(vs[5]), toFloat(vs[6]), toFloat(vs[7]));
			new_sphere.color = toVec4(vs[8], vs[9], vs[10]);
			new_sphere.k_a = toFloat(vs[11]);
			new_sphere.k_d = toFloat(vs[12]);
			new_sphere.k_s = toFloat(vs[13]);
			new_sphere.k_r = toFloat(vs[14]);
			new_sphere.n = toFloat(vs[15]);

			//store the inverse scale transform for later
			mat4 scale_matrix = Scale(new_sphere.scale);
			mat4 inverseScale;
			InvertMatrix(scale_matrix, inverseScale);
			new_sphere.inverse_scale = inverseScale;

			spheres.push_back(new_sphere);
		}
			break;
		case 7:												//LIGHT
		{
			Light new_light;
			new_light.position = toVec4(vs[2], vs[3], vs[4]);
			new_light.intensity = toVec4(vs[5], vs[6], vs[7]);
			lights.push_back(new_light);
		}
			break;
		case 8:												//BACK		
			bg_colors = toVec4(vs[1], vs[2], vs[3]);
			break;		
		case 9:												//AMBIENT
			ambience = toVec4(vs[1], vs[2], vs[3]);
			break;
		case 10:											//OUTPUT
		{
			output = vs[1];
			break;
		}
	}

}
Example #16
0
 void set_delay(const vector<int>& d)
 {
     delay = d;
     assert(delay.size() == 0 || delay.size() == this->from->num_seq_dims());
     delayedCoords.resize(delay.size());
 }
Example #17
0
	Node()
	{
		children.resize(27,NULL);
		num = 0;
		isWord = false;
	}
int main(int argc, char *argv[])
{
	ofstream output;
	vector<tdata> td;
	vector<pthread_t> threads;

	int rc, step, idx;
	struct timeval t1, t2;

	KICK(argc < 4, "./md5 <output_file> <data_file> <num_threads>");

	int num_threads = atoi(argv[3]);
	int size = N + 1;
	results.resize(size);
	td.resize(num_threads);
	threads.resize(num_threads);
	step = size / num_threads;
	if (size % num_threads) {
		step++;
	}

	gettimeofday(&t1, NULL);

	idx = 0;
	for (int i = 0; i < num_threads; i++) {
		td[i].begin = idx;
		td[i].end = min(idx + step, size);
		idx = td[i].end;
		rc = pthread_create(&threads[i], NULL, hash, &td[i]);
		DIE(rc != 0, "pthread_create");
	}

	for (int i = 0; i < num_threads; i++) {
		rc = pthread_join(threads[i], NULL);
		DIE(rc != 0, "pthread_join");
	}

	gettimeofday(&t2, NULL);
	uint64_t usec = diff(&t2, &t1);
	cout << "djb2: " << "0 - " << N << endl;
	cout << usec << " usec" << endl;

	for (int i = 0; i < size; i++) {
		results_hexa.push_back(to_hex((unsigned char *)&results[i]));
	}

	map<string, int> m;
	int num_collisions = 0;
	cerr << "collisions: " << endl;
	for (int i = 0; i < size; i++) {
		string key = results_hexa[i];

		if (m.count(key)) {
			cerr << "(" << m.find(key)->second << ", " << i << ")" << endl;
			num_collisions++;
		}

		m.insert(pair<string, int>(key, i));
	}
	cout << num_collisions << " collisions" << endl;

	output.open(argv[1]);
	DIE(output.fail(), "open");
	for (int i = 0; i < size; i++) {
		output << results_hexa[i] << " " << i << endl;
	}
	output.close();

	output.open(argv[2]);
	DIE(output.fail(), "open");
	for (int i = 0; i < size; i++) {
		uint16_t x, y;
		to_data((unsigned char *)&results[i], x, y);
		output << x << " " << y << endl;
	}
	output.close();

	return 0;
}
 segment_tree(int a_n, T a_unit, F a_append) {
     n = pow(2,ceil(log2(a_n)));
     a.resize(2*n-1, a_unit);
     unit = a_unit;
     append = a_append;
 }
void initSet(int n){
	id.clear();	id.resize(n);
	cant_hijos.clear();	cant_hijos.resize(n,1);
	for(int i=0;i<n;i++)	id[i]=i;
}
Example #21
0
int ReadProcMaps(char* filename)
{
	char buf[2048];
	FILE *fp;

	pcre	*re;
	const char      *error;
	int             erroffset;
	int OVECCOUNT = 30;
	int rc;
	int             ovector[OVECCOUNT];
	const char pattern[] = "([0-9a-fA-F]+)-([0-9a-fA-F]+)[\\s]+([^\\s]+)[\\s]+([^\\s]+)[\\s]+([^\\s]+)[\\s]+([^\\s]+)[\\s]+([^\\s\\n\\r]+)";

	alert_ranges.resize(0);
	
	re = pcre_compile(pattern,0, &error, &erroffset, NULL);

	if (re == NULL) {
		log("PCRE compilation failed at offset %d: %s\n", erroffset, error);
		return -1;
    }

	
	fp = fopen(filename, "rt");
	
	if ( !fp) {
		log("can't open %s", filename);
		return -2;
	}

	while(fgets(buf, sizeof(buf), fp) ) {
		
		rc = pcre_exec(re, NULL, buf, strlen(buf), 0, 0, ovector, OVECCOUNT);

			if ( rc==1+7){
				char saddr[512];
				char eaddr[512];
				char priv[512];
				char offset[512];
				char dev[512];
				char length[512];
				char path[512];
				char *p_error;
				tAddrRange	R;

				//printf("rc=%d\n", rc);
				
				sprintf(saddr, "%.*s", ovector[3]-ovector[2], buf+ovector[2]);
				sprintf(eaddr, "%.*s", ovector[5]-ovector[4], buf+ovector[4]);
				sprintf(priv, "%.*s", ovector[7]-ovector[6], buf+ovector[6]);
				sprintf(offset, "%.*s", ovector[9]-ovector[8], buf+ovector[8]);
				sprintf(dev, "%.*s", ovector[11]-ovector[10], buf+ovector[10]);
				sprintf(length, "%.*s", ovector[13]-ovector[12], buf+ovector[12]);
				sprintf(path, "%.*s", ovector[15]-ovector[14], buf+ovector[14]);
				
				R.start_addr = strtoull(saddr, &p_error, 16);
				R.end_addr = strtoull(eaddr, &p_error, 16);

				if ( nDEBUG_LEVEL > 2)
					log("[%llx] [%llx] %s [%s]\n", R.start_addr, R.end_addr, priv, path);
				
				
				if ( strstr(path, "/tmp/") && strstr(priv, "x")) {
					alert_ranges.push_back(R);
					
					if ( nDEBUG_LEVEL > 0)
						log("alert range : [%llx]-[%llx]  \n", R.start_addr, R.end_addr);
					
				}
				
			
				
			}
		
		
	}
	
	pcre_free(re);
	
	return 0;
}
Example #22
0
 BITree(int N){
     this->N = N;
     array.resize(N+1,0);
 }
Example #23
0
void dijkstra(const vector<vector<pair<int, int>>> &graph, 
    int src, int dst, vector<int> &dists, vector<int> &costs, vector<int> &path)
{
    int num_vs = graph.size();
    dists.resize(num_vs);  // 记录当前顶点 src 到顶点 i 的最短路径长度
    costs.resize(num_vs);  // 记录当前顶点 src 到顶点 i 的最小花费
    vector<int> pre(num_vs);  // 记录当前顶点 src 到顶点 i 最短路径上 i 的前一个顶点

    vector<int> visited(num_vs, 0);
    visited[src] = 1;  // 访问起始顶点
    dists[src] = 0;
    costs[src] = 0;
    pre[src] = -1;

    // 初始化辅助数组
    for (int i = 0; i < num_vs; ++i)
    {
        if (i == src)
            continue;

        if (graph[src][i].first != k_INF)
        {
            dists[i] = graph[src][i].first;
            costs[i] = graph[src][i].second;
            pre[i] = src;
        }
        else
        {
            dists[i] = k_INF;
            costs[i] = k_INF;
        }
    }

    // 处理剩下 N - 1 个顶点
    for (int k = 0; k < num_vs - 1; ++k)
    {
        // 找到到当前已访问集合的距离最短的顶点
        int min_dist = k_INF;
        int u = -1;
        for (int i = 0; i < num_vs; ++i)
        {
            if (visited[i])
                continue;

            if (min_dist > dists[i])
            {
                min_dist = dists[i];
                u = i;
            }
        }

        if (u == -1)
            break;

        visited[u] = 1;  // 顶点 u 的最短路径已经找到

        // 以刚加入的顶点作为中介,更新剩余顶点信息
        for (int i = 0; i < num_vs; ++i)
        {
            if (visited[i] || graph[u][i].first == k_INF)
                continue;

            if (dists[i] > dists[u] + graph[u][i].first)
            {
                dists[i] = dists[u] + graph[u][i].first;
                costs[i] = costs[u] + graph[u][i].second;
                pre[i] = u;
            }
            else if (dists[i] == dists[u] + graph[u][i].first)  // 距离相同,考虑花费更小
            {
                if (costs[i] > costs[u] + graph[u][i].second)
                {
                    costs[i] = costs[u] + graph[u][i].second;
                    pre[i] = u;
                }
            }
        }
    }

    // src 到 dst 的最短路径上的顶点
    path.clear();
    while (dst != -1)
    {
        path.push_back(dst);
        dst = pre[dst];
    }
    std::reverse(path.begin(), path.end());
}
Example #24
0
static void initMaterials() {
  // Create some prototype materials
  Material diffuse("./shaders/basic-gl3.vshader", "./shaders/diffuse-gl3.fshader");
  Material solid("./shaders/basic-gl3.vshader", "./shaders/solid-gl3.fshader");
  Material specular("./shaders/basic-gl3.vshader", "./shaders/specular-gl3.fshader");

  // copy diffuse prototype and set red color
  g_redDiffuseMat.reset(new Material(diffuse));
  g_redDiffuseMat->getUniforms().put("uColor", Cvec3f(1, 0, 0));

  // copy diffuse prototype and set blue color
  g_blueDiffuseMat.reset(new Material(diffuse));
  g_blueDiffuseMat->getUniforms().put("uColor", Cvec3f(0, 0, 1));

  //Specular mat for mesh material
  g_meshSpecularMat.reset(new Material(specular));
  g_meshSpecularMat->getUniforms().put("uColor", Cvec3f(1, 1, 0));

  // normal mapping material
  g_bumpFloorMat.reset(new Material("./shaders/normal-gl3.vshader", "./shaders/normal-gl3.fshader"));
  g_bumpFloorMat->getUniforms().put("uTexColor", shared_ptr<ImageTexture>(new ImageTexture("Fieldstone.ppm", true)));
  g_bumpFloorMat->getUniforms().put("uTexNormal", shared_ptr<ImageTexture>(new ImageTexture("FieldstoneNormal.ppm", false)));

  // copy solid prototype, and set to wireframed rendering
  g_arcballMat.reset(new Material(solid));
  g_arcballMat->getUniforms().put("uColor", Cvec3f(0.27f, 0.82f, 0.35f));
  g_arcballMat->getRenderStates().polygonMode(GL_FRONT_AND_BACK, GL_LINE);

  // copy solid prototype, and set to color white
  g_lightMat.reset(new Material(solid));
  g_lightMat->getUniforms().put("uColor", Cvec3f(1, 1, 1));

  // pick shader
  g_pickingMat.reset(new Material("./shaders/basic-gl3.vshader", "./shaders/pick-gl3.fshader"));

  g_bunnyMat.reset(new Material("./shaders/basic-gl3.vshader", "./shaders/bunny-gl3.fshader"));
  g_bunnyMat->getUniforms()
  .put("uColorAmbient", Cvec3f(0.45f, 0.3f, 0.3f))
  .put("uColorDiffuse", Cvec3f(0.2f, 0.2f, 0.2f));

  // bunny shell materials;
  shared_ptr<ImageTexture> shellTexture(new ImageTexture("shell.ppm", false)); // common shell texture

  // needs to enable repeating of texture coordinates
  shellTexture->bind();
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

  // eachy layer of the shell uses a different material, though the materials will share the
  // same shader files and some common uniforms. hence we create a prototype here, and will
  // copy from the prototype later
  Material bunnyShellMatPrototype("./shaders/bunny-shell-gl3.vshader", "./shaders/bunny-shell-gl3.fshader");
  bunnyShellMatPrototype.getUniforms().put("uTexShell", shellTexture);
  bunnyShellMatPrototype.getRenderStates()
  .blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) // set blending mode
  .enable(GL_BLEND) // enable blending
  .disable(GL_CULL_FACE); // disable culling

  // allocate array of materials
  g_bunnyShellMats.resize(g_numShells);
  for (int i = 0; i < g_numShells; ++i) {
    g_bunnyShellMats[i].reset(new Material(bunnyShellMatPrototype)); // copy from the prototype
    // but set a different exponent for blending transparency
    g_bunnyShellMats[i]->getUniforms().put("uAlphaExponent", 2.f + 5.f * float(i + 1)/g_numShells);
  }
}
Example #25
0
bool SkinnedMesh::Animate(double deltaTime, vector<Matrix4x4>& boneTransformationMatrices) {
    if (currentAnimationState_ == nullptr) {
        return false;
    }

    time_ += deltaTime;
    map<const Bone_t*, Matrix4x4> transformationMatrices;
    if (!skeleton_->GetTransformationMatrices(time_, currentAnimationState_, isLooping_,
                                              transformationMatrices))
    {
        return false;
    }

    if (meshType_ == MESH_TYPE_DYNAMIC) {
        // Pass over each vertex and transform them
        bool useNormals = vertexAttributes_.find(VERTEX_ATTRIBUTES_NORMAL) != vertexAttributes_.end();
        map<const Bone_t*, Matrix4x4>::iterator it, end_it = transformationMatrices.end();
        size_t baseIndex = 0;

        vector<vector<Vector3>> originalVertices, originalNormals;

        for (size_t i = 0; i < surfaces_.size(); i++) {
            SurfaceTriangles_t* surface = surfaces_[i];
            bool hasNormals = (surface->numNormals > 0);

            Vector3* vertices = surface->vertices;
            Vector3* normals = surface->normals;
            originalVertices.push_back(vector<Vector3>());
            if (useNormals && hasNormals) {
                originalNormals.push_back(vector<Vector3>());
            }

            for (size_t j = 0; j < surface->numVertices; j++) {
                Matrix4x4 boneTransform;
                it = transformationMatrices.begin();
                size_t numberOfBones = 0;

                for (; it != end_it; ++it) {
                    const Bone_t* bone = it->first;

                    // The key is the vertex index, taking into account at which mesh we're at and the
                    // value if the weight of that vertex for that bone
                    unordered_map<size_t, float>::const_iterator w_it = bone->vertexWeight.find(baseIndex + j);
                    if (w_it != bone->vertexWeight.end()) {
                        if (numberOfBones == 0) {
                            boneTransform = it->second * w_it->second;
                        } else {
                            boneTransform += it->second * w_it->second;
                        }

                        numberOfBones += 1;
                    }

                    // A maximum of 4 bones can contribute to a vertex
                    if (numberOfBones == 4) {
                        break;
                    }
                }

                Vector3 vertex = vertices[j];
                Vector4 transformedVertex(vertex.x, vertex.y, vertex.z);
                transformedVertex = boneTransform * transformedVertex;
                vertices[j] = Vector3(transformedVertex.x, transformedVertex.y, transformedVertex.z);
                originalVertices[i].push_back(vertex);

                if (useNormals && hasNormals) {
                    Vector3 normal = normals[j];
                    Vector4 transformedNormal(normal.x, normal.y, normal.z, 0.0f);
                    transformedNormal = boneTransform * transformedNormal;
                    normals[j] = Vector3(normal.x, normal.y, normal.z);
                    originalNormals[i].push_back(normal);
                }
            }

            baseIndex += surface->numVertices;
        }

        Mesh::UpdateMeshData();

        for (size_t i = 0; i < surfaces_.size(); i++) {
            SurfaceTriangles_t* surface = surfaces_[i];
            bool hasNormals = (surface->numNormals > 0);

            Vector3* vertices = surface->vertices;
            Vector3* normals = surface->normals;

            for (size_t j = 0; j < surface->numVertices; j++) {
                vertices[j] = originalVertices[i][j];

                if (useNormals && hasNormals) {
                    normals[j] = originalNormals[i][j];
                }
            }
        }
    } else {
        // Populate the vector of transformation matrices so that it can be used by the GPU
        map<const Bone_t*, size_t>::iterator it = boneToIndex_.begin();
        boneTransformationMatrices.resize(skeleton_->GetNumberOfBones());
        for (; it != boneToIndex_.end(); ++it) {
            boneTransformationMatrices[it->second] = transformationMatrices[it->first];
        }
    }

    return true;
}
Example #26
0
bool ReadModelFile( const string &fileName, vector<Vector3> &vertices, vector<int> &indices,
	vector<Vector3> &normals)
{
	using namespace std;
	ifstream fin(fileName.c_str());
	if (!fin.is_open())
		return false;

	string vtx, eq;
	int numVertices;
	fin >> vtx >> eq >> numVertices;

	if (numVertices <= 0)
		return  false;

	vertices.resize(numVertices);

	float num1, num2, num3;
	for (int i = 0; i < numVertices; i++)
	{
		fin >> num1 >> num2 >> num3;
		vertices[i] = Vector3(num1, num2, num3);
	}

	string idx;
	int numIndices;
	fin >> idx >> eq >> numIndices;

	if (numIndices <= 0)
		return false;

	indices.resize(numIndices*3);

	int num4, num5, num6;
	for (int i = 0; i < numIndices*3; i+=3)
	{
		fin >> num4 >> num5 >> num6;
		indices[ i] = num4;
		indices[ i+1] = num5;
		indices[ i+2] = num6;	
	}


	string norm;
	int numNormal;
	fin >> norm >> eq >> numNormal;

	normals.resize(numVertices);

	if (numNormal > 0)
	{
		float num1, num2, num3;
		vector<int> vertCount(numVertices, 0);
		for (int i = 0; i < numNormal; i++)
		{
			fin >> num1 >> num2 >> num3;
			Vector3 n(num1, num2, num3);

			// 법선벡터의 평균을 구해서 할당한다.
			for (int k=0; k < 3; ++k)
			{
				const int vtxIdx = indices[ i*3 + k];
				normals[ vtxIdx] += n;
				++vertCount[ vtxIdx];
			}
		}

		for (int i=0; i < numVertices; ++i)
		{
			normals[ i] /= (float)vertCount[ i];
			normals[ i].Normalize();
		}
	}
Example #27
0
void GBitset::ScheduleProbability( vector<int> &LFase, vector<int> &LGilb,
								   int &Porog,
								   int &Delta ) {

   int x;
   int Nf,Ng,p;
   int Nff;
// int sizeNcol=ncolumns;       // ГОРИЗОНТАЬНЫЙ РАЗМЕР ПЕЧА  w=ncolumns;
// int size=nrows;              // ВЕРТИКАЛЬНЫЙ РАЗМЕР ПЕЧА   h=nrows;



							Nf=N0Fase;
						//  DM(Nf<<" Nf+ ");
							if( Nf==0) { return; }
	/*
			 // TMP
			  DM(END);  DM(END);
			  for ( x=0; x < N0Fase;  x++ ){      // x < d+1;
				DM(LFase[x]<<"\t"); if (x%10==0)DM(END);  /// ТАБЛИЦА
				  }//for x
			  DM(END);
   */
						   // Сортировка вектора.
// сортируем наш вектор от начала и до конца. http://progs.biz/cpp/stl/lessons/005.aspx
						   sort(LFase.begin(), LFase.end());
				 // работает также как "сортировка Шейкера".

						// "сортировка Шейкера".
				 // http://www.abc-it.lv/index.php/id/610
//                              Nff=Nf-1;
//                          Sort(LFase, Nff);

/*
   int trash=0;
   bool f=true;
   int i,j;
							   // сортировка
	 for ( i=1; (i<=Nff) && (f=true) ; i++)
	   {
		  f=false;
		  for ( j=i; j<=Nff-i; j++) // проходим с лева на право
			 {
				if (LFase[j]>LFase [j+1]) // если число слева больше числа
			   {
				  trash=LFase[j]; // справа, то меняем местами
				  LFase[j]=LFase [j+1]; // справа собираются большие числа
				  LFase[j+1]=trash;
				  f=true;
			   }
			 }
			   for ( j=Nff-i-1; j>i ; j--)  // проходим с права на лево
				 {
				   if (LFase[j]<LFase[j-1])  // если число справа меньше числа
				   {
				   trash=LFase[j]; // слева, то меняем местами
				   LFase[j]=LFase[j-1]; // слева собираются меньшие числа
				   LFase[j-1]=trash;
				   f=true;
				 }
				 }
			 }
   */

	/*        // TMP
			  DM(END);            // size-1   N0Fase
			  for ( x=0; x < N0Fase;  x++ ){      // x < d+1;
				DM(LFase[x]<<"\t"); if (x%10==0)DM(END);  /// ТАБЛИЦА
				  }//for x
			 DM(END);
   */

			//определение безопастного размера массива Ng NewSizeMassif
				Ng=0;
				for ( x=0; x <Nf-2; x++ ) {  // +1
					if ( abs(LFase[x])<Porog && abs(LFase[x+1])<Porog ){
					p=LFase[x+1]-LFase[x]; Ng=Ng+p;}
					}//for x
	 //             Ng=Ng+nrows/4+50; // Ng-ширина распределения вероятностей, nrows/8; (100)-max мат ожидание, 50-запас.
					Ng=Ng+2*ncolumns/(nfas+1)+50; // Ng-ширина распределения вероятностей, nrows/8; (100)-max мат ожидание, 50-запас.

						N0Gilb = Ng ;
						LGilb.resize(N0Gilb);
				for ( x=0; x < N0Gilb;  x++ ){ LGilb[x]=0; }
					//теперь LGilb массив размера (Ng) // LGilb.assign(N0Gilb,0);

					// вычисление распределения вероятностей
////                // фильтрация по порогу, отбрасывание хвостов распределения
				 // p=0; x <Nf-Delta-1
				 for ( x=Delta; x <Nf-Delta; x++ ) {
					if( abs(LFase[x])<Porog )
					   {
					   p=LFase[x]+ Ng/2;
					   if( p > 0 && p < Ng ){  // p выходящие за пределы массива Ng
						   LGilb[p]++; }       // отбрасываем (хотя таких не дб)
					   }
					 }//for x


#ifdef DEBUGLVL
 /*                        // ВИЗУАЛИЗАЦИЯ цифровая 0
			   DM(N0Gilb<<" N0Gilb ");
			   DM(END);
			   // INGilb[0][Ng/2]=9999;
				for ( x=0; x < N0Gilb;  x++ ){
				DM(LGilb[x]<<"\t"); if (x%10==0)DM(END);  /// ТАБЛИЦА
				 }//for x

DM(END); DM(Porog<<" Porog calc "); DM(N0Fase<<" N0Fase calc "); DM(N0Gilb<<" N0Gilb calc ");
DM(END);
*/
#endif
/*
	 //    if ( abs(LFase[x])<Porog && p>=0 && p<Ng ){ LGilb[p]++; }
	 ///   if ( LFase[x]<Porog){ LGilb[p]++; }
*/
}//_____________________________________________________________________________
void SparseBCSRMatrix::ConvertCOOToIdxValMatrix(vector<iv_arr_t> &iv_matrix) {
    iv_matrix.resize(m_);
    // assign the row id
    for (int i = 0; i < m_; i++)
        iv_matrix[i].id = i;
    for (int i = 0; i < nnz_; i++) 
        iv_matrix[rows_[i]].data.push_back(make_pair(cols_[i], vals_[i]));

    int max_row_nnz = 0;
    int min_row_nnz = (int)iv_matrix[0].data.size();
    double avg_row_nnz = 0.0;
    for (int i = 0; i < m_; i++) {
        max_row_nnz = max((int) iv_matrix[i].data.size(), max_row_nnz);
        min_row_nnz = min((int) iv_matrix[i].data.size(), min_row_nnz);
        avg_row_nnz += iv_matrix[i].data.size();
    }
    avg_row_nnz /= m_;
    printf("Transformed to IdxVal Matrix \n");
    printf("Number of Rows:\t %d\n",    iv_matrix.size());
    printf("Max NNZ Size:\t %d\n",      max_row_nnz);
    printf("Min NNZ Size:\t %d\n",      min_row_nnz);
    printf("Avg NNZ Size:\t %.2f\n",    avg_row_nnz);

    // sorting 
    printf("Sorting ...\n");
    sort(iv_matrix.begin(), iv_matrix.end(), CmpIdxValArrBySize);

    //printf("Transformed to intermediate queues\n");
    //vector<index_t> index;
    //vector<value_t> value;
    //vector<index_t> clrwr;
    //// padding
    //long long pad_num_row = ceil((double)m/r) * r;
    //long long pad_num_col = ceil((double)n/c) * c;
    //long long pad_nnz = 0;
//
    //value_t *vec = (value_t *) malloc(sizeof(value_t) * pad_num_col);
    //value_t *res = (value_t *) malloc(sizeof(value_t) * pad_num_row);
    //for (int i = 0; i < pad_num_col; i++) 
    //    vec[i] = 0.01;
    //for (int i = 0; i < pad_num_row; i++)
    //    res[i] = 0.0;
//
    //// generalized iteration
    //for (int i = 0; i < pad_num_row; i += r) {
    //    for (int j = 0; j < pad_num_col; j += c) {
    //        clrwr.push_back((j == 0));
    //        bool is_empty = true;
    //        for (int _i = 0; _i < r; _i++) {
    //            int _r = i + _i;
    //            int _c = j;
    //            if (_r < m && _c < index_queues[_r].size())
    //                is_empty = false; 
    //        }
    //        if (is_empty) 
    //            break;
    //        // for each block
    //        for (int _j = 0; _j < c; _j ++) {
    //            for (int _i = 0; _i < r; _i ++) {
    //                int _r = i + _i;
    //                int _c = j + _j;
    //                index_t _index = (_r >= m || _c >= index_queues[_r].size()) ? 0   : index_queues[_r][_c];
    //                value_t _value = (_r >= m || _c >= value_queues[_r].size()) ? 0.0 : value_queues[_r][_c];
    //                index.push_back(_index);
    //                value.push_back(_value);
    //                pad_nnz ++;
    //            }
    //        }
    //    }
    //}
}
Example #29
0
void place_vert(vert v, vector<vert>& l) {
    if(v.n >= l.size()) l.resize(v.n+1);
    l[v.n] = v;
}
Example #30
0
void reorder(vector<vector<int>>& vorder)
{
    vorder.clear();
    vorder.resize(literal_maximum_ring_level() + 1);
    //stage 1: build unknown literal
    set<int> unknown_literal;
    //loop over vP and vfunc
    for (const auto& P : vP)
    {
        int i = literal_get(P.name());
        assert(i != -1);
        unknown_literal.insert(i);
    }
    for (const auto& F : vfunc)
    {
        int i = literal_get(F._resname);
        assert(i != -1);
        unknown_literal.insert(i);
    }
    //stage 2: find known literal
    vector<int> un_vf(vfunc.size());//index of all unknown vfunc
    for (int i = 0; i < vfunc.size(); ++i) { un_vf[i] = i; }
    vector<int> un_vp(vP.size());//index of all unknown vP
    for (int i = 0; i < vP.size(); ++i) { un_vp[i] = i; }
    bool flag = true;
    while (flag)
    {
        flag = false;
        for (auto it = un_vf.begin(); it != un_vf.end();)
        {
            if (unknown_literal.count(vfunc[*it]._paraid) == 0)//known!
            {
                flag = true;
                vorder[vfunc[*it].ring_level()].push_back(-1 - (*it));
                //mark as known
                int li = literal_get(vfunc[*it]._resname);
                assert(li != -1);
                unknown_literal.erase(li);
                it = un_vf.erase(it);
            }
            else
            {
                ++it;
            }
        }
        for (auto it = un_vp.begin(); it != un_vp.end();)
        {
            if (!vP[*it].contain_literals(unknown_literal))//known!
            {
                flag = true;
                vorder[vP[*it].ring_level()].push_back(*it);
                //mark as known
                int li = literal_get(vP[*it].name());
                assert(li != -1);
                unknown_literal.erase(li);
                it = un_vp.erase(it);
            }
            else
            {
                ++it;
            }
        }
    }
    assert(un_vf.size() == 0);
    for (int i = 0; i < un_vp.size(); ++i)
    {
        std::cerr<<vP[un_vp[i]]<<std::endl;
    }
    assert(un_vp.size() == 0);
}