Ejemplo n.º 1
0
void print(int32 P[], int i)
{
	for(int j=0;j<i;j++)
		cout<<hex<<setw(8)<<setfill('0')<<P[j]<<" ";
}
Ejemplo n.º 2
0
/*
 * 获得一条报警信息,先到内存中找,如果没有就到数据库中取1000条,放在内存中慢慢发
 *  LBSU,ALARM,htgl,0000000004,13911447899;20120627113703;A;113.252432;22.564152;30;270;130;100;7,END
 */
string getAlaData(int &minAla_id,int &act_Ala_id,int &serivalnum){
	if(act_Ala_id==0){           // 最多获取1000条
		alarmInit();
		db.getData(motorid2,lat2,lon2,dis2,a2,gprs2,speed2,dir2,gpsLocate2,weekday2,state_id2,sys_state_id2,uploadTime2,createTime2,minAla_id,ArraySize,"alarm");
	}
	if(motorid2.size()==0)//如果没有取到数据,就直接返回
		return "nodata";

	//从内存中读,直到ArraySize条都读完
	string result = "";
	stringstream ss; //流水号固定格式
	ss<<setfill('0')<<setw(10)<<serivalnum;
	string serival = ss.str();

	string locate="A";// 定位标志。。偶数的时候表示定位精确
	int locate_int = atoi(gpsLocate2[act_Ala_id].c_str());
	if(locate_int%2==0)
		locate = "A";
	else
		locate ="V";
	
	char al[14];
	memset(al,'0',sizeof(al));
	vector<string> alarminfors = getSubString(state_id2[act_Ala_id],",");
	vector<string>::iterator iter1 = alarminfors.begin(), iter2 = alarminfors.end();
	while (iter1 != iter2)
	{
		if(*iter1=="6")//超速
			al[11] ='1';
		else if(*iter1=="4")//入界
			al[9] = '1';
		else if(*iter1=="5")//出界
			al[8] = '1';
		else if(*iter1=="3")//碰撞,震动
			al[4] = '1';
		else if(*iter1=="13")//剪线,断电
			al[2] = '1';
		++iter1;
	}
	al[13]='\0';
	char al_state[8];
	memset(al_state,'0',sizeof(al_state));
	vector<string> al_state_infors = getSubString(sys_state_id2[act_Ala_id],",");
	vector<string>::iterator iter3 = al_state_infors.begin(), iter4 = al_state_infors.end();
	while (iter3 != iter4)
	{
		if(*iter3=="5")  //ACC开
			al_state[5] ='1';
		else if(locate == "A") //判断设备是否准确定位
			al_state[6] = '1';
		else if(state_id2[act_Ala_id].find("12")>0) //到报警字段中找是否设防
			al_state[4] = '1';
		++iter3;
	}
	//车子没有熄火的时候一直保持acc开的,就是状态中有5这个标志位,若没有,则表示车辆熄火,这个记录一下。
	if(al_state[5] !='1'){
		al_state[0] = '1';
	}
	al_state[7]='\0';
	string al_infor = binaryToHex(al);//传入2进制表示的   char 数组
	string al_state_result = binaryToHex(al_state);//传入2进制表示的  char数组

	if(al_infor=="0"||al_infor==""){
		al_infor = "0";
	}
	if(al_state_result=="0"||al_state_result==""){
		al_state_result = "0";
	}
	result="LBSU,ALARM,ctsm,"+serival+","+motorid2[act_Ala_id]+";"+uploadTime2[act_Ala_id]+";"+locate
			+";"+lon2[act_Ala_id]+";"+lat2[act_Ala_id]+";"+speed2[act_Ala_id]+";"+dir2[act_Ala_id]
			+";"+dis2[act_Ala_id]+";"+al_infor+";"+al_state_result+",END";

	act_Ala_id++;
	serivalnum++;
	if(act_Ala_id==motorid2.size()){//内存中的数据都读过了,就重置0,重新到数据库中加载。
		act_Ala_id=0;
	}

	return result;
}
Ejemplo n.º 3
0
int main() //命令行开启,输入参数
{
	//初始化,建立socket,登录
    init();

	//========================一旦进入while循环就不跳出了,除非手动关闭,  登录成功后发1000条跳一次心跳=======================
    while(1){
    	if(act_Nor_id==0&&act_Ala_id==0){  //一轮以后才进去一次(act_Nor_id循环1000次会重新置零)
    		stringstream ss; //流水号固定格式
			ss<<setfill('0')<<setw(10)<<serivalnum;
			string serival = ss.str();
    		char send_sh[MAXDATASIZE];
    		string heart_smg = HEARTBEAT_SMG1+serival+HEARTBEAT_SMG2;
    		strcpy(send_sh,heart_smg.c_str());

    		cout<<"send heartbeat...."<<endl;
			if(send(sock_fd, send_sh, MAXDATASIZE, 0) == -1) {//发送心跳
				perror("send heartbeat 出错!");
			}
			heart_beat = checkRecv(sock_fd,buf,HEARTBEAT_SMG_BACK1+serival+HEARTBEAT_SMG_BACK2);
			if(!heart_beat){
				cout<<"heartbeat back fail...."<<endl; //如果没有心跳返回,就不发了
				continue;
			}
			cout<<"heartbeat back success...."<<endl;
    		serivalnum++;
    		sleep(1);
    	}
    	memset(buf, '\0', sizeof(buf));


		// ****************检查点名和密码同步,结果无阻塞返回*****************************
		recvbytes=recv(sock_fd, buf, MAXDATASIZE, 0);
		if (recvbytes == -1 ) {
			if(errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN){//几种特殊情况,不断开socket

			}else{
				//socket 需要释放
				cout<<"关闭socket,重启初始化"<<endl;
				close(sock_fd);
				init();
				continue;
			}
		}else if(recvbytes == 0){
			//socket 需要释放
			cout<<"关闭socket,重启初始化"<<endl;
			close(sock_fd);
			init();
			continue;
		}else{                             //其他信息
			buf[recvbytes] = '\0';
			printf("Received: %s",buf);
			string str(buf);
			if(str!=""&&str.length()!=0)
				cout<<"收到服务端发送的数据   "<<str<<endl;
			//点名
			if(str.find(RECV_CALL_SMG)){//LBSD,CALL, htgl,0000000011,13911447899,END
				string calldata = getCallData(str);
				if(calldata!="nodata"){
					if(send(sock_fd, calldata.c_str(), MAXDATASIZE, 0) == -1) {//发送点名回应(服务器能不能成功接收暂时不管)
						perror("发送点名信息出错!");
					}
				}
			}
			//密码同步
			else if(str.find(PASS_SMG)){
				string passdata = getPassData(str);
				if("nodata"!=passdata){
					if(send(sock_fd, passdata.c_str(), MAXDATASIZE, 0) == -1) {//发送密码回应(服务器能不能成功接收暂时不管)
						perror("发送点名信息出错!");
					}
				}

			}
		}

		//--------------发送位置信息---------------------
		string data = getNormalData(minNor_id,act_Nor_id,serivalnum);
		if(data!="nodata"){
			cout<<"normal: "<<data<<endl;
			//向服务器发送常规数据
			if(send(sock_fd, data.c_str(), MAXDATASIZE, 0) == -1) {
				perror("发送正常位置信息 出错!");
			}
		}else{
			cout<<"目前数据库中没有新的非报警数据可以上传"<<endl;
		}

		//--------------发送报警信息-----------------------
		string alaData = getAlaData(minAla_id,act_Ala_id,serivalnum);
		cout<<alaData<<endl;
		if(alaData!="nodata"){
			cout<<"alarm: "<<alaData<<endl;
			//向服务器发送报警数据
			if(send(sock_fd, alaData.c_str(), MAXDATASIZE, 0) == -1) {
				perror("发送报警信息出错!");
			}
		}else{
			cout<<"目前数据库中没有新的报警数据可以上传"<<endl;
		}

		//查看有没有新的设备,如果有,全部获取到,并且循环在这里发完(成功的做个标记,下次不发了,失败的不做标记下一次继续发)-----------
//		sendNewDeviceInfor(serivalnum);


		//------------------写入数据库---------------------
		db.writeMin_num(minNor_id,minAla_id,serivalnum);

    }

}
Ejemplo n.º 4
0
void replace_ver_info(const wstring& pe_path, const SfxVersionInfo& ver_info) {
    // numeric version
    list<wstring> ver_parts = split(ver_info.version, L'.');
    DWORD ver_hi = 0, ver_lo = 0;
    list<wstring>::const_iterator ver_part = ver_parts.cbegin();
    if (ver_part != ver_parts.end()) {
        ver_hi |= (str_to_int(*ver_part) & 0xFFFF) << 16;
        ver_part++;
    }
    if (ver_part != ver_parts.end()) {
        ver_hi |= str_to_int(*ver_part) & 0xFFFF;
        ver_part++;
    }
    if (ver_part != ver_parts.end()) {
        ver_lo |= (str_to_int(*ver_part) & 0xFFFF) << 16;
        ver_part++;
    }
    if (ver_part != ver_parts.end()) {
        ver_lo |= str_to_int(*ver_part) & 0xFFFF;
        ver_part++;
    }

    // existing version info list
    list<IdLang> vi_list;
    RsrcModule module(pe_path);
    list<RsrcId> ids = enum_rsrc_names(module.handle(), RT_VERSION);
    for_each(ids.begin(), ids.end(), [&] (const RsrcId& id) {
        list<WORD> lang_ids = enum_rsrc_langs(module.handle(), RT_VERSION, id);
        for_each(lang_ids.begin(), lang_ids.end(), [&] (WORD lang_id) {
            IdLang id_lang;
            id_lang.id = id;
            id_lang.lang_id = lang_id;
            vi_list.push_back(id_lang);
        });
    });
    module.close();

    WORD lang_id;
    RsrcId ver_id;
    if (vi_list.empty()) {
        ver_id = MAKEINTRESOURCE(1);
        lang_id = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL);
    }
    else {
        ver_id = vi_list.front().id;
        lang_id = vi_list.front().lang_id;
    }

    // encode version info
    VersionEncoder e;
    e.reserve(4096);

    size_t vs_versioninfo_pos = e.size();
    e.encode_WORD(0); // VS_VERSIONINFO
    e.encode_WORD(sizeof(VS_FIXEDFILEINFO));
    e.encode_WORD(0);
    e.encode_string(L"VS_VERSION_INFO");
    e.pad();

    e.encode_DWORD(0xFEEF04BD); // VS_FIXEDFILEINFO
    e.encode_DWORD(0x00010000);
    e.encode_DWORD(ver_hi);
    e.encode_DWORD(ver_lo);
    e.encode_DWORD(ver_hi);
    e.encode_DWORD(ver_lo);
    e.encode_DWORD(0x3F);
    e.encode_DWORD(0);
    e.encode_DWORD(VOS_NT_WINDOWS32);
    e.encode_DWORD(VFT_APP);
    e.encode_DWORD(0);
    e.encode_DWORD(0);
    e.encode_DWORD(0);
    e.pad();

    size_t string_file_info_pos = e.size();
    e.encode_WORD(0); // StringFileInfo
    e.encode_WORD(0);
    e.encode_WORD(1);
    e.encode_string(L"StringFileInfo");
    e.pad();

    size_t string_table_pos = e.size();
    e.encode_WORD(0); // StringTable
    e.encode_WORD(0);
    e.encode_WORD(1);
    wostringstream st;
    st << hex << setw(4) << setfill(L'0') << lang_id << L"04b0";
    e.encode_string(st.str());
    e.pad();

    map<wstring, wstring> strings;
    strings[L"Comments"] = ver_info.comments;
    strings[L"CompanyName"] = ver_info.company_name;
    strings[L"FileDescription"] = ver_info.file_description;
    strings[L"FileVersion"] = ver_info.version;
    strings[L"LegalCopyright"] = ver_info.legal_copyright;
    strings[L"ProductName"] = ver_info.product_name;
    strings[L"ProductVersion"] = ver_info.version;

    for_each(strings.cbegin(), strings.cend(), [&] (const pair<wstring, wstring>& str) {
        size_t string_pos = e.size();
        e.encode_WORD(0); // String
        e.encode_WORD(str.second.size() + 1);
        e.encode_WORD(1);
        e.encode_string(str.first);
        e.pad();
        e.encode_string(str.second);
        e.pad();
        e.update_length(string_pos);
    });

    e.update_length(string_table_pos);

    e.update_length(string_file_info_pos);

    size_t var_file_info_pos = e.size();
    e.encode_WORD(0); // VarFileInfo
    e.encode_WORD(0);
    e.encode_WORD(1);
    e.encode_string(L"VarFileInfo");
    e.pad();

    size_t var_pos = e.size();
    e.encode_WORD(0); // Var
    e.encode_WORD(4);
    e.encode_WORD(0);
    e.encode_string(L"Translation");
    e.pad();
    e.encode_WORD(lang_id);
    e.encode_WORD(0x04B0);
    e.update_length(var_pos);

    e.update_length(var_file_info_pos);

    e.update_length(vs_versioninfo_pos);

    // wrire resource
    ResourceUpdate rupdate(pe_path);
    for_each(vi_list.cbegin(), vi_list.cend(), [&] (const IdLang& id_lang) {
        rupdate.update(RT_VERSION, id_lang.id, id_lang.lang_id, nullptr, 0);
    });
    rupdate.update(RT_VERSION, ver_id, lang_id, e.data(), e.size());
    rupdate.finalize();
}
Ejemplo n.º 5
0
void SCStat::PrintPlace() {

	int sizePlace = GetSizeInt(g_allPlaces.size()) + 3;

	unsigned int sizeCap = GetSizeInt( MaxPlaceCapacity() );
	unsigned int sizeVal = GetSizeInt( MaxPlaceStartValue() );
	unsigned int sizeCount = GetSizeInt( MaxPlaceTotal() );
	unsigned int sizeName =  MaxPlaceName();
	unsigned int sizeEnd = GetSizeInt(1);
	char capacity[15] = "capcity";
	if( sizeCap < strlen(capacity) || MaxPlaceCapacity() == UINT_MAX )
		sizeCap = strlen(capacity);
	char value[30] = "final state tags";
	if( sizeVal < strlen(value) )
		sizeVal = strlen(value); 
	char name[30] = "name";
	if( sizeName < strlen(name) )
		sizeName = strlen(name); 
	char end[30] = "start state";
	if( sizeEnd < strlen(end) )
		sizeEnd = strlen(end); 
	char count[30] = "total tags";
	if( sizeCount < strlen(count) )
		sizeCount = strlen(count); 
	unsigned int size = sizeCap + sizeVal + sizeName + sizeEnd + sizeCount + 7 + 11 + 6;
	unsigned int sizeHalf = size/2;

	cout << "* " << setfill('-') << setw(sizeHalf) << "" << " places " << setw(sizeHalf) << "" << endl;
	cout << "*" << endl;
	cout << "*        " << setfill(' ') << setw(sizePlace) << "." << " | " 
						<< setw(sizeName) << name << " | " 
	               << setw(sizeCap) << capacity << " | " 
						<< setw(sizeEnd) << end << " | " 
						<< setw(sizeVal) << value << " | "
						<< setw(sizeCount) << count << endl;
	cout << "*       " << setw(sizePlace) << " " << setfill('.') << setw(size-sizePlace) << "." << endl;

	char p[10] = "PLACES ";
	unsigned int k = 0;

	for(unsigned int i = 0; i != g_allPlaces.size(); i++ )
	{
		cout << "*       "<< p[k] << setfill(' ') << setw(sizePlace) << i+1 << " | " 
		                     << setw(sizeName) << g_allPlaces[i]->GetName().c_str() << " | ";
		if( g_allPlaces[i]->GetArgCapacity() == UINT_MAX )
			cout << setw(sizeCap) << "inf"  << " | ";
		else
			cout << setw(sizeCap) << g_allPlaces[i]->GetArgCapacity()  << " | ";

		cout							<< setw(sizeEnd) << g_allPlaces[i]->GetArgStartVal() <<" | " 
									<< setw(sizeVal) << g_allPlaces[i]->GetArgCurrentVal() << " | " 
									<< setw(sizeCount) << g_allPlaces[i]->GetArgTotal() << endl;
		if( k < 6 )
			k++;
		else if( i > 7 )
			k = 6;
	}

	if( strlen(p) > g_allPlaces.size() )
	{
		for(;k<strlen(p)-1;k++)
		{
			cout << "*       "<< p[k] << endl;
		}
	}

	cout << "*" <<endl;
}
Ejemplo n.º 6
0
result_t loadScanConfigFile(MessageMap* messages, unsigned char address, SymbolString& data, string& relativeFile)
{
	PartType partType;
	if (isMaster(address)) {
		address = (unsigned char)(data[0]+5); // slave address of sending master
		partType = pt_masterData;
		if (data.size()<5+1+5+2+2) // skip QQ ZZ PB SB NN
			return RESULT_EMPTY;
	} else {
		partType = pt_slaveData;
		if (data.size()<1+1+5+2+2) // skip NN
			return RESULT_EMPTY;
	}
	DataFieldSet* identFields = DataFieldSet::getIdentFields();
	// MANUFACTURER/ZZ. ( C.S.H., C.H., C.S., S.H., C., S., H., "" ) .*csv
	string path, prefix, ident, sw, hw; // path: cfgpath/MANUFACTURER, prefix: ZZ., ident: C[C[C[C[C]]]], sw: xxxx, hw: xxxx
	ostringstream out;
	unsigned char offset = 0;
	size_t field = 0;
	result_t result = (*identFields)[field]->read(partType, data, offset, out, 0); // manufacturer name
	if (result==RESULT_ERR_NOTFOUND)
		result = (*identFields)[field]->read(partType, data, offset, out, OF_NUMERIC); // manufacturer name
	if (result==RESULT_OK) {
		path = out.str();
		transform(path.begin(), path.end(), path.begin(), ::tolower);
		path = string(opt.configPath) + "/" + path;
		out.str("");
		out << setw(2) << hex << setfill('0') << nouppercase << static_cast<unsigned>(address) << ".";
		prefix = out.str();
		out.str("");
		out.clear();
		offset = (unsigned char)(offset+(*identFields)[field++]->getLength(partType));
		result = (*identFields)[field]->read(partType, data, offset, out, 0); // identification string
	}
	if (result==RESULT_OK) {
		ident = out.str();
		out.str("");
		offset = (unsigned char)(offset+(*identFields)[field++]->getLength(partType));
		result = (*identFields)[field]->read(partType, data, offset, out, 0); // software version number
	}
	if (result==RESULT_OK) {
		sw = out.str();
		out.str("");
		offset = (unsigned char)(offset+(*identFields)[field++]->getLength(partType));
		result = (*identFields)[field]->read(partType, data, offset, out, 0); // hardware version number
	}
	if (result!=RESULT_OK) {
		logDebug(lf_main, "load scan config files: %s", getResultCode(result));
		return result;
	}
	vector<string> files;
	bool hasTemplates = false;
	if (result==RESULT_OK) {
		hw = out.str();
		result = collectConfigFiles(path, prefix, ".csv", files, NULL, &hasTemplates);
	}
	logDebug(lf_main, "found %d matching scan config files from %s with prefix %s: %s", files.size(), path.c_str(), prefix.c_str(), getResultCode(result));
	if (result!=RESULT_OK)
		return result;
	if (files.empty())
		return RESULT_ERR_NOTFOUND;

	// complete name: cfgpath/MANUFACTURER/ZZ[.C[C[C[C[C]]]]][.SWxxxx][.HWxxxx][.*].csv
	for (string::iterator it = ident.begin(); it!=ident.end(); it++) {
		if (::isspace(*it)) {
			ident.erase(it--);
		} else {
			*it = (char)::tolower(*it);
		}
	}
	size_t prefixLen = path.length()+1+prefix.length()-1;
	size_t bestMatch = 0;
	string best;
	for (vector<string>::iterator it = files.begin(); it!=files.end(); it++) {
		string name = *it;
		name = name.substr(prefixLen, name.length()-prefixLen+1-strlen(".csv")); // .*.
		size_t match = 1;
		if (name.length()>2) { // more than just "."
			size_t pos = name.rfind(".SW"); // check for ".SWxxxx."
			if (pos!=string::npos && name.find(".", pos+1)==pos+7) {
				if (name.substr(pos+3, 4)==sw)
					match += 6;
				else {
					continue; // SW mismatch
				}
			}
			pos = name.rfind(".HW"); // check for ".HWxxxx."
			if (pos!=string::npos && name.find(".", pos+1)==pos+7) {
				if (name.substr(pos+3, 4)==hw)
					match += 6;
				else {
					continue; // HW mismatch
				}
			}
			pos = name.find(".", 1); // check for ".C[C[C[C[C]]]]."
			if (ident.length()>0 && pos!=string::npos && pos>1 && pos<=6) { // up to 5 chars between two "."s, immediately after "ZZ."
				string check = name.substr(1, pos-1);
				string remain = ident;
				bool matches = false;
				while (remain.length()>0 && remain.length()>=check.length()) {
					if (check==remain) {
						matches = true;
						break;
					}
					if (remain[remain.length()-1]!='0')
						break;
					remain.erase(remain.length()-1);
				}
				if (matches)
					match += remain.length();
				else {
					continue; // IDENT mismatch
				}
			}
		}
		if (match>=bestMatch) {
			bestMatch = match;
			best = *it;
		}
	}

	if (best.length()==0)
		return RESULT_ERR_NOTFOUND;

	// found the right file. load the templates if necessary, then load the file itself
	bool readCommon = false;
	DataFieldTemplates* templates = getTemplates(path, ".csv", hasTemplates, false, &readCommon);
	if (readCommon) {
		result = collectConfigFiles(path, "", ".csv", files);
		if (result==RESULT_OK && !files.empty()) {
			for (vector<string>::iterator it = files.begin(); it!=files.end(); it++) {
				string name = *it;
				name = name.substr(path.length()+1, name.length()-path.length()-strlen(".csv")); // *.
				if (name=="_templates.") // skip templates
					continue;
				if (name.length()<3 || name.find_first_of('.')!=2) { // different from the scheme "ZZ."
					name = *it;
					result = messages->readFromFile(name, templates);
					if (result==RESULT_OK)
						logNotice(lf_main, "read common config file %s for scan %s", name.c_str(), ident.c_str());
					else
						logError(lf_main, "error reading common config file %s for scan %s: %s", name.c_str(), ident.c_str(), getResultCode(result));
				}
			}
		}
	}
	result = messages->readFromFile(best, templates);
	if (result!=RESULT_OK) {
		logError(lf_main, "error reading config file %s for scan %s: %s", best.c_str(), ident.c_str(), getResultCode(result));
		return result;
	}
	logNotice(lf_main, "read config file %s for scan %s", best.c_str(), ident.c_str());
	result = messages->resolveConditions(false);
	if (result != RESULT_OK)
		logError(lf_main, "error resolving conditions: %s, %s", getResultCode(result), messages->getLastError().c_str());

	logNotice(lf_main, "found messages: %d (%d conditional on %d conditions, %d poll, %d update)", messages->size(), messages->sizeConditional(), messages->sizeConditions(), messages->sizePoll(), messages->sizePassive());
	relativeFile = best.substr(strlen(opt.configPath)+1);
	return RESULT_OK;
}
Ejemplo n.º 7
0
void TxtLogger::logSync(unsigned insid, unsigned short sync,
                        unsigned turn, 
                        timespec time1, 
                        timespec time2, timespec sched_time, 
                        bool after, ...) {
  assert(sync >= syncfunc::first_sync && sync < syncfunc::num_syncs
    && "trying to log unknown synchronization operation!");

//  if(!syncfunc::isSync(sync))
//  {
    if (sync == syncfunc::tern_thread_begin
      || sync == syncfunc::tern_thread_end)    //  for tests, i need to know the thread_mapping
    {
      va_list args;
      va_start(args, after);
      ouf << syncfunc::getName(sync)
          << " 0x" << hex << insid << dec
          << ' ' << turn
          << " " << dec << time1.tv_sec << ":"
          << setfill('0') << setw(9) << time1.tv_nsec
          << " " << dec << time2.tv_sec << ":"
          << setfill('0') << setw(9) << time2.tv_nsec
          << " " << dec << sched_time.tv_sec << ":"
          << setfill('0') << setw(9) << sched_time.tv_nsec
          << ' ' << tid
          << hex << " 0x" << va_arg(args, uint64_t) << dec;
      va_end(args);
      ouf << "\n";
      ouf.flush();
      return;
    }
//    return;
//  }
  // YJF: why ignore prog_begin/end and thread_begin/end?
  const char *suffix = "";
  if(NumRecordsForSync(sync) == 2)
    suffix = (after?"_second":"_first");

  ouf << syncfunc::getName(sync) << suffix
      << " 0x" << hex << setfill('0') << setw(8) << insid << dec
      << ' ' << turn
      << " " << dec << time1.tv_sec << ":"
      << setfill('0') << setw(9) << time1.tv_nsec
      << " " << dec << time2.tv_sec << ":"
      << setfill('0') << setw(9) << time2.tv_nsec
      << " " << dec << sched_time.tv_sec << ":"
      << setfill('0') << setw(9) << sched_time.tv_nsec
      << ' ' << tid;

  va_list args;
  va_start(args, after);

  switch(sync) {
    // log nothing, mostly for sched point. 
  case syncfunc::accept4:
  case syncfunc::recv:
  case syncfunc::recvfrom:
  case syncfunc::recvmsg:
  case syncfunc::select:
  case syncfunc::poll:
  case syncfunc::bind:
  case syncfunc::listen:
  case syncfunc::getsockopt:
  case syncfunc::setsockopt:
  case syncfunc::pipe:
  case syncfunc::fcntl:
  case syncfunc::shutdown:
  case syncfunc::gethostbyname:
  case syncfunc::gethostbyname_r:
  case syncfunc::getaddrinfo:
  case syncfunc::freeaddrinfo:
  case syncfunc::gethostbyaddr:
  case syncfunc::inet_ntoa:
  case syncfunc::strtok:
  case syncfunc::epoll_wait:
  case syncfunc::epoll_create:
  case syncfunc::epoll_ctl:
  case syncfunc::sigwait:
  case syncfunc::fgets:
  case syncfunc::kill:
  case syncfunc::fork:
  case syncfunc::execv:
  case syncfunc::sched_yield:
  case syncfunc::wait:
  case syncfunc::waitpid:
  case syncfunc::tern_idle:
  case syncfunc::tern_non_det_start:
  case syncfunc::tern_non_det_end:
    break;
    // log one sync var (common case)
  case syncfunc::pthread_mutex_init:
  case syncfunc::pthread_mutex_destroy:
  case syncfunc::pthread_mutex_lock:
  case syncfunc::pthread_mutex_unlock:
  case syncfunc::pthread_barrier_wait:
  case syncfunc::pthread_barrier_destroy:
  case syncfunc::pthread_cond_signal:
  case syncfunc::pthread_cond_broadcast:
  case syncfunc::sem_wait:
  case syncfunc::sem_init:
  case syncfunc::sem_post:
  case syncfunc::pthread_join:
  case syncfunc::pthread_detach:
  case syncfunc::sleep:
  case syncfunc::usleep:
  case syncfunc::nanosleep:
  case syncfunc::pthread_rwlock_rdlock:
  case syncfunc::pthread_rwlock_wrlock:
  case syncfunc::tern_lineup_start:
  case syncfunc::tern_lineup_end:
  case syncfunc::tern_lineup_destroy:
    ouf << hex << " 0x" << va_arg(args, uint64_t) << dec;
    break;

    // log two sync vars for cond_*wait
  case syncfunc::pthread_mutex_timedlock:
  case syncfunc::pthread_cond_wait:
  case syncfunc::pthread_barrier_init:
  case syncfunc::pthread_create:
  case syncfunc::pthread_mutex_trylock:
  case syncfunc::sem_trywait:
  case syncfunc::sem_timedwait:
  case syncfunc::pthread_rwlock_tryrdlock:  //  rwlock, ret
  case syncfunc::pthread_rwlock_trywrlock:
  case syncfunc::pthread_rwlock_unlock:  //  rwlock, ret
    {
      //  notice "<<" operator is expanded from right to left.
      uint64_t a = va_arg(args, uint64_t);
      uint64_t b = va_arg(args, uint64_t);

    ouf << hex
        << " 0x" << a
        << " 0x" << b
        << dec;
    }
    break;
    // log three sync vars
  case syncfunc::pthread_cond_timedwait:  //  cv, mu, ret
  case syncfunc::read:  //  sig, fd, ret
  case syncfunc::fread:  //  sig, ptr, size
  case syncfunc::pread:  //  sig, fd, ret
  case syncfunc::accept:  //  sock(ret), from_port, to_port
  case syncfunc::write: //  sig, fd, ret
  case syncfunc::pwrite: //  sig, fd, ret
  case syncfunc::tern_lineup_init:
    {
      //  notice "<<" operator is explained from right to left.
      uint64_t a = va_arg(args, uint64_t);
      uint64_t b = va_arg(args, uint64_t);
      uint64_t c = va_arg(args, uint64_t);

    ouf << hex
        << " 0x" << a
        << " 0x" << b
        << " 0x" << c
        << dec;
    }
    break;
  case syncfunc::connect: //  fd, from_port, to_port, ret
    {
      //  notice "<<" operator is explained from right to left.
      uint64_t a = va_arg(args, uint64_t);
      uint64_t b = va_arg(args, uint64_t);
      uint64_t c = va_arg(args, uint64_t);
      uint64_t d = va_arg(args, uint64_t);

    ouf << hex
        << " 0x" << a
        << " 0x" << b
        << " 0x" << c
        << " 0x" << d
        << dec;
    }
    break;

  default:
    cerr << "sync " << syncfunc::getName(sync) << " is not yet handled!\n";
    assert(0);
  }

  va_end(args);
  ouf << "\n";
  ouf.flush();
}
Ejemplo n.º 8
0
void MainApplication::runApplication(int argc, char *argv[])
{
    double dt, T, Tbath, tau, L;
    int nSteps, thermostat, N, calculateStatistics, saveStates;

    if (argc != 11)
    {
        cout << endl << "! Usage: 'dt nSteps T(MD) thermostat#(0,1,2) Tbath(MD) tau L(SI) N calculateStatistics saveStates'" << endl;
        if (argc == 1)
        {
            dt = 0.005;
            nSteps = 200;
            T = 1.7; // to get 0.851
            thermostat = 1;
            Tbath = 0.851;
            tau = 15;
            L = 5.720;
            N = 20;
            calculateStatistics = 1;
            saveStates = 0;

            cout << endl << "! Using default of: dt = " << dt << ", nSteps = " << nSteps << ", T = " << T
                 << ", thermostat# = " << thermostat << ", Tbath = " << Tbath
                 << ", tau = " << tau << ", L = " << L
                 << ", N = " << N << ", statistics? = " << calculateStatistics
                 << ", save states? = " << saveStates << endl << endl;
        } else
            exit(1);
    }
    else if (argc == 11)
    {
        dt = atof(argv[1]);
        nSteps = atoi(argv[2]);
        T = atof(argv[3]);
        thermostat = atoi(argv[4]);
        Tbath = atof(argv[5]);
        tau = atof(argv[6]);
        L = atof(argv[7]);
        N = atoi(argv[8]);
        calculateStatistics = atoi(argv[9]);
        saveStates = atoi(argv[10]);
    }

    double tt = 1.0/10;
    long seed = -1;
    cout << "dt                 :    " << dt << endl;
    cout << "Tbath              :    " << Tbath << endl;

    CState state;
    state = initialize(T, L, N, &seed);
    CStatisticsSampler sampler(state);
    sampler.initialize_pairCorrelation(200, 1);

    ostringstream filename;

//    state.load("./output/states/state.1000.xyz");
    for (int i = 0; i < nSteps; i++)
    {
        if (i%50==0) cout << "n = " << i << " of " << nSteps << endl;

        filename.str(string());
        filename << "./output/states/state." << setfill('0') << setw(4) << i << ".xyz";

        if (saveStates) state.save(filename.str(), 1, 1);

        if (calculateStatistics) sampler.sample(state, 1, dt*i);
//        if (i>250) sampler.pairCorrelation();

        if (thermostat == 1 && calculateStatistics) state.berendsen(Tbath, sampler.T, tt);
        else if (thermostat == 2) state.andersen(Tbath, tt, &seed);

        state.move(dt, calculateStatistics);
    }
    sampler.sample(state, 1, nSteps*dt);
//    filename.str(string());
//    filename << "./output/states/state." << setfill('0') << setw(4) << nSteps << ".xyz";
//    state.save(filename.str(), 0, 0);

//    sampler.pairCorrelation_manual("./output/pairCorrelation_final.dat", 1, 200);
}
Ejemplo n.º 9
0
void Options::DisplayVersion()
	{
	cout << "\nDumpSWIRegistry Utility   Version " << KMajorVersion << '.' \
			<< setw(2) << KMinorVersion << setfill('0') <<  "\nCopyright (c) 2005-2006 Symbian Software Limited . All rights reserved.\n\n" << flush;
	}
Ejemplo n.º 10
0
void FlightControlCenter::start(string file, double speed)
{

	string line;
	ifstream myfile(file);
	Clock::speedOfSimClock = speed;

	if (myfile)
	{
		getline(myfile, line);
		cityParser->InitCityData((char*)line.c_str()); //initiate city parser with file on 1st line 

		getline(myfile, line);
		fltParser->InitFlightData((char*)line.c_str()); //initiate flight parser with file on 2nd line 
	};

	cityParser->getCitySymbolsArray(&FlightControlCenter::symbols); //get city symbols array from City Parser
	cityParser->getDistTable(&FlightControlCenter::distances);	//get city Distance Table array from City Parser
	FlightControlCenter::numofCities = cityParser->getCityCount(); // get number of cities for calculating distances

	fltParser->getStartTime(&Clock::curr_hour, &Clock::curr_min); //get start time
	buildManifest(); //get info on all flights
	buildAirplanesList(); // builds airplane list
	buildCitiesList(); //builds cities list 
	buildFlightsList(); // builds flight list

	

	//print sim start time
	cout << "*** Starting simulation at "<< setfill('0') << setw(2) << Clock::curr_hour << ":" << setfill('0') << setw(2)
			<< Clock::curr_min << " ***" << endl << endl;

	
	//timer loop
	_ftime(&Clock::tStruct);	// Get start time
	Clock::startOfSimClock = Clock::tStruct.time + (((double)(Clock::tStruct.millitm)) / 1000.0); // Convert to double
	Clock::thisTime = Clock::tStruct.time + (((double)(Clock::tStruct.millitm)) / 1000.0); // Convert to double
	Clock::outputTime = Clock::thisTime + (5.0/Clock::speedOfSimClock); // Set next (5 second/ simulator speed) interval time

	while (!done)     // Start an eternal loop
	{
		_ftime(&Clock::tStruct);    // Get the current time
		Clock::thisTime = Clock::tStruct.time + (((double)(Clock::tStruct.millitm)) / 1000.0); // Convert to double

		// Check for 5 second interval to print status to screen
		if (Clock::thisTime >= Clock::outputTime)
		{

			 
			Clock::curr_min += 5 * Clock::speedOfSimClock;

			//keeps up with hours and minutes for display
			if (Clock::curr_min > 59)
			{
				++Clock::curr_hour;
				Clock::curr_min %= 60;
				Clock::startOfSimClock = Clock::thisTime;
			}
			else if (Clock::curr_hour > 12)
				Clock::curr_hour = 1;

			// Call functions to perform actions at 5 second intervals
			double t = Clock::curr_hour + ((double)Clock::curr_min / 60);
			Notify(t, Clock::curr_hour, Clock::curr_min);
			report();

			Clock::outputTime = Clock::thisTime + (5.0/Clock::speedOfSimClock); // Set next (5 second/ simulator speed) interval time

		}
		// Do other stuff here
		if ((Clock::curr_hour == SIM_END_HOUR) && (Clock::curr_min == SIM_END_MINUTE))
				done = true;

	}

}
Ejemplo n.º 11
0
void Assembler::PassII() {
	m_err.InitErrorReporting();	// Initializes the error recorder
	string errorMsg = "";		// temp for error message
	int loc = 0;				// location of instructions to be generated
	int opCode = 0, operand = 0;// parsed opcode and operand in a line of code
	int inst = 0;					// Resulting machine language instruction
	m_faccess.rewind();			// Resetting the file to read

	cout << "---------TRANSLATION OF PROGRAM-----------------------------" << endl << endl;
	cout << "LOC\tCONTENT\t\tORIGINAL STATEMENT" << endl;
	
	// Process a line at a time
	for (; ; ) {	
		
		// STEP 1: Read the next line from the source file.
		m_inst.reset();
		string buff;
		if (!m_faccess.GetNextLine(buff)) {
			errorMsg = "File ended without an END statement";
			m_err.RecordError(errorMsg);
			cout << endl << "--------------------------------------------------------" << endl;
			return;
		}

		// STEP 2: Parse the line and get the instruction type.
		Instruction::InstructionType st = m_inst.ParseInstruction(buff);

		// STEP 3: If this is an end statement, determine if the end is the last statement & return
		if (st == Instruction::ST_End) {
			if (m_faccess.GetNextLine(buff)) {
				errorMsg = "Statements found after END opcode";
				m_err.RecordError(errorMsg);
			}
			cout << "\t\t\t" << buff 
				<< endl << endl;
			cout << endl << "--------------------------------------------------------" << endl;
			return;
		}
		
		// STEP 4: Check the validity of parsed opCode
		opCode = m_inst.GetNumOpCode();
		if ((opCode < 0 || opCode > 13) && (st != Instruction::ST_Comment && buff.find_first_not_of(' ') != string::npos)) {
			errorMsg = "Illegal Opcode\r\n" + buff;
			m_err.RecordError(errorMsg);
		}

		// STEP 5: Jump to next line if this is not a machine or assembly instruction
		if (st != Instruction::ST_MachineLanguage && st != Instruction::ST_AssemblerInstr) {
			cout << "\t\t\t" << buff << endl;
			continue;
		}

		cout << loc << "\t";

		// STEP 6: Check the validity of the parsed label name
		if (m_inst.GetLabel() != "") {
			if (strlen(m_inst.GetLabel().c_str()) > 10) {
				errorMsg = "Too Long Labelname\r\n" + buff;
				m_err.RecordError(errorMsg);
			}
			if (!isalpha(m_inst.GetLabel()[0])) {
				errorMsg = "The first letter of the labelname " + m_inst.GetLabel() + " is not a letter\r\n" + buff;
				m_err.RecordError(errorMsg);
			}
		}

		// STEP 7: Get the parsed operand's value
		if (m_inst.isNumericOperand()) {
			operand = m_inst.GetOperandValue();
		}
		else if (m_symtab.LookupSymbol(m_inst.GetOperand())) {
			operand = m_symtab.LookupLocation(m_inst.GetOperand());
		}
		else {
			operand = 0;
		}

		// STEP 8: Check the validity of the parsed operand
		if (operand > 999999) {
			errorMsg = "Operand Value too high\r\n" + buff;
			m_err.RecordError(errorMsg);
		}
		if (operand == 0 && (m_inst.GetOpCode() != "halt" && m_inst.GetOpCode() != "end")) {
			errorMsg = "Operand value cannot be null/undefined\r\n" + buff;
			m_err.RecordError(errorMsg);
		}

		// STEP 9: Generate machine language instruction and store it in memory
		if (operand == -999) {
			errorMsg = "Multiply defined operand found at\r\n" + buff;
			m_err.RecordError(errorMsg);
		}
		else if (m_inst.GetOpCode() == "org" || m_inst.GetOpCode() == "ds") {
			cout << "\t\t";
		}
		else {
			inst = opCode * 10000;
			inst = inst + operand;
			m_emul.insertMemory(loc, inst);
			cout << right << setw(6) << setfill('0') << inst << "\t\t";
		}

		// Print the orginal line of code
		cout << buff << endl;

		// STEP 10: Compute the location of the next instruction.
		loc = m_inst.LocationNextInstruction(loc);
	}
}
Ejemplo n.º 12
0
// Input/Output
ostream &operator<<(ostream &os, Long x) {
  os << x.digit[x.size-1];
  for (int i = x.size-2; i >= 0; --i)
    os << setw(BW) << setfill('0') << x.digit[i];
  return os;
}
Ejemplo n.º 13
0
void Debugger::updateUI()
{
	pthread_mutex_lock(&printingMutex);
	if ((screen.isActive() && state == dsRunning) || state == dsStopped)
	{
		if (wSelectedLineFollowsFlow)
		{
			wSelectedLine = findLine(flow);
		}

		// *** Printing code ***

		if (activeWindow == dawCode)
		{
			screen.SelectForeColor(0, 0, 0);
			screen.SelectBackColor(192, 192, 192);
		}
		else
		{
			screen.SelectForeColor(192, 192, 192);
			screen.SelectBackColor(96, 96, 96);
		}
		printFixed(0, topSpace - 1, L" Code ", screen.getFrameBufferWidth());

		int code_lines = screen.getFrameBufferHeight() - topSpace;
		int up = code_lines / 2;
		int down = code_lines - up - 2;

		int prev_addr = 0;
		for (int i = down; i >= -up; i--)
		{
			int index = wSelectedLine/*findLine(flow)*/ + i;

			int y = topSpace + up + i;

			{
				int colorsCount = 0;
				int bgR = 0, bgG = 0, bgB = 0;
				int fgR = 0, fgG = 0, fgB = 0;

				if (i == 0)	// this line is selected now
				{
					bgR += 192; bgG += 192; bgB += 192;
					colorsCount++;
				}

				for (unsigned int i = 1; i < flowLayers.size(); i++)
				{
					int p = flowLayers.size() - i;
					if (entries[index].memPos == flowLayers[i].lastFlow)
					{
						bgR += 255 / pow(2.0, p);
						bgG += 192 / pow(2.0, p);
						bgB += 64 / pow(2.0, p);
						colorsCount ++;
					}
				}

				if (index == findLine(flow)) // flow is here
				{
					bgR += 255; bgG += 192; bgB += 64;
					colorsCount++;
				}

				if (findBreakpointAt(entries[index].memPos) != breakpoints.end()) // flow is here
				{
					bgR += 192; bgG += 32; bgB += 32;
					colorsCount++;
				}

				if (colorsCount > 0)
				{
					bgR /= colorsCount; bgG /= colorsCount; bgB /= colorsCount;
				}

				if (bgR < 64 && bgG < 64 && bgB < 64)
				{
					fgR = 128; fgG = 128; fgB = 128;
				}
				else
				{
					fgR = 0; fgG = 0; fgB = 0;
				}

				screen.SelectForeColor(fgR, fgG, fgB);
				screen.SelectBackColor(bgR, bgG, bgB);
			}

			wstringstream strs;
			if (index >= 0 && index < (int)entries.size() && entries[index].memPos != prev_addr)
			{
				strs << std::setw(8) << setfill(L'0') << std::hex << uppercase << entries[index].memPos << L" ";
				prev_addr = entries[index].memPos;
			}
			else
			{
				strs << L"         ";
			}
			printFixed(1, y, strs.str().c_str(), 9);


			{
				int colorsCount = 0;
				int bgR = 0, bgG = 0, bgB = 0;
				int fgR = 0, fgG = 0, fgB = 0;

				if (i == 0)	// this line is selected now
				{
					bgR += 192; bgG += 192; bgB += 192;
					colorsCount ++;
				}

				for (unsigned int i = 1; i < flowLayers.size(); i++)
				{
					int p = flowLayers.size() - i;
					if (entries[index].memPos == flowLayers[i].lastFlow)
					{
						bgR += 255 / pow(2.0, p);
						bgG += 192 / pow(2.0, p);
						bgB += 64 / pow(2.0, p);
						colorsCount ++;
					}
				}

				if (index == findLine(flow)) // flow is here
				{
					bgR += 255; bgG += 192; bgB += 64;
					colorsCount++;
				}

				if (findBreakpointAt(entries[index].memPos) != breakpoints.end()) // flow is here
				{
					bgR += 192; bgG += 32; bgB += 32;
					colorsCount++;
				}

				if (colorsCount > 0)
				{
					bgR /= colorsCount; bgG /= colorsCount; bgB /= colorsCount;
				}

				if (bgR < 64 && bgG < 64 && bgB < 64)
				{
					fgR = 192; fgG = 192; fgB = 192;
				}
				else
				{
					fgR = 0; fgG = 0; fgB = 0;
				}

				screen.SelectForeColor(fgR, fgG, fgB);
				screen.SelectBackColor(bgR, bgG, bgB);
			}

			wstringstream strs2;
			if (index >= 0 && index < (int)entries.size())
			{
				//printf("0x%X: %s\n", fl->mem_pos, fl->lines.c_str());
				strs2 << entries[index].codeLine << L"\n";
			}
			else
			{
				//printf("0x%X: <<No such address in debug symbols>>\n");
				wstringstream strs2;
				strs2 << L"<< No such address in debug symbols >>\n";
			}
			printFixed(10, y, strs2.str().c_str(), screen.getFrameBufferWidth() - 11);
		}

		printMenu();


		// ** Printing stack **

		int wStackWindowWidth = 9 + 3 * wStackBytes + wStackBytes + 2;

		if (activeWindow == dawStack)
		{
			screen.SelectForeColor(0, 0, 0);
			screen.SelectBackColor(192, 192, 192);
		}
		else
		{
			screen.SelectForeColor(192, 192, 192);
			screen.SelectBackColor(96, 96, 96);
		}
		printFixed(0, 0, L" Stack ", wStackWindowWidth);

		screen.SelectBackColor(0, 0, 0);

		for (int row = wStackTopRow; row < wStackTopRow + topSpace - 3; row++)
		{
			int stack_addr = row * wStackBytes;

			wstringstream strs;
			strs << std::setw(8) << setfill(L'0') << std::hex << uppercase << stack_addr << L" ";

			screen.SelectForeColor(128, 128, 128);
			printFixed(1, row - wStackTopRow + 1, strs.str().c_str(), 9);

			wstringstream strs2;
			wstringstream strs3;

			for (; stack_addr < (row + 1) * wStackBytes; stack_addr ++)
			{
				if (stack_addr < stackAllocatedSize)
				{
					unsigned char i1 = *((unsigned char*)(&stack[stack_addr]));

					//wstringstream strs;
					//strs << std::setw(2) << setfill(L'0') << std::hex << uppercase << i1 << " ";
					const wchar_t* hexchars = L"0123456789ABCDEF";
					wchar_t num[4];
					num[3] = 0;
					num[2] = L' ';
					num[1] = hexchars[i1 % 16];
					num[0] = hexchars[i1 / 16];

					wchar_t ch[2];
					if (i1 == 0)
					{
						ch[0] = ' ';
					}
					else
					{
						ch[0] = i1;
					}
					ch[1] = 0;

					screen.SelectForeColor(192, 192, 192);

					strs2 << num;
					strs3 << ch;
					//printFixed(9 + 1 + 3 * (stack_addr % wStackBytes), row - wStackTopRow + 1, num, 3);
					//printFixed(9 + 1 + wStackBytes * 3 + (stack_addr % wStackBytes), row - wStackTopRow + 1, ch, 1);

				}
				else
				{
					strs2 << L"   ";
					strs3 << L" ";

					//printFixed(9 + 1 + 3 * (stack_addr % wStackBytes), row - wStackTopRow + 1, L"   ", 3);
					//printFixed(9 + 1 + wStackBytes * 3 + (stack_addr % wStackBytes), row - wStackTopRow + 1, L" ", 1);
				}
			}

			strs2 << strs3.str();
			printFixed(9 + 1, row - wStackTopRow + 1, strs2.str().c_str(), wStackWindowWidth - 9);
		}

		// ** Printing heap **

		int wHeapWindowWidth = 2 + 9 + 3 * wHeapBytes + wHeapBytes;

		if (activeWindow == dawHeap)
		{
			screen.SelectForeColor(0, 0, 0);
			screen.SelectBackColor(192, 192, 192);
		}
		else
		{
			screen.SelectForeColor(192, 192, 192);
			screen.SelectBackColor(96, 96, 96);
		}
		printFixed(wStackWindowWidth + 2, 0, L" Heap ", wHeapWindowWidth);

		screen.SelectBackColor(0, 0, 0);

		for (int row = wHeapTopRow; row < wHeapTopRow + topSpace - 3; row++)
		{
			int heap_addr = row * wHeapBytes;

			wstringstream strs;
			strs << L" " << std::setw(8) << setfill(L'0') << std::hex << uppercase << heap_addr << L" ";

			screen.SelectForeColor(128, 128, 128);
			printFixed(wStackWindowWidth + 2, row - wHeapTopRow + 1, strs.str().c_str(), 9);

			wstringstream strs2;
			wstringstream strs3;

			for (; heap_addr < (row + 1) * wHeapBytes; heap_addr ++)
			{
				if (heap_addr < heapSize)
				{
					unsigned char i1 = *((unsigned char*)(&heap[heap_addr]));
					//wstringstream strs;
					//strs << std::setw(2) << setfill(L'0') << std::hex << uppercase << i1 << " ";
					const wchar_t* hexchars = L"0123456789ABCDEF";
					wchar_t num[4];
					num[3] = 0;
					num[2] = L' ';
					num[1] = hexchars[(i1 / 0x1)  & 0xF];
					num[0] = hexchars[(i1 / 0x10) & 0xF] ;

					wchar_t ch[2];
					if (i1 == 0)
					{
						ch[0] = ' ';
					}
					else
					{
						ch[0] = i1;
					}
					ch[1] = 0;

					screen.SelectForeColor(192, 192, 192);

					strs2 << num;
					strs3 << ch;
					//printFixed(wStackWindowWidth + 3 + 9 + 3 * (heap_addr % wHeapBytes), row - wHeapTopRow + 1, num, 3);
					//printFixed(wStackWindowWidth + 3 + 9 + wHeapBytes * 3 + (heap_addr % wHeapBytes), row - wStackTopRow + 1, ch, 1);
				}
				else
				{
					strs2 << L"   ";
					strs3 << L" ";
					//printFixed(wStackWindowWidth + 3 + 9 + 3 * (heap_addr % wHeapBytes), row - wHeapTopRow + 1, L"   ", 3);
					//printFixed(wStackWindowWidth + 3 + 9 + wHeapBytes * 3 + (heap_addr % wHeapBytes), row - wStackTopRow + 1, L" ", 1);
				}
			}

			strs2 << strs3.str();
			printFixed(wStackWindowWidth + 3 + 9, row - wHeapTopRow + 1, strs2.str().c_str(), wHeapWindowWidth - 9);
		}

	}
	pthread_mutex_unlock(&printingMutex);
}
Ejemplo n.º 14
0
void main()
{
	clrscr();
	cout<<"\n\tHashing Technique used Snefru";
	cout<<"\n\tHash File Test.txt ";
	int32 ip[16],op[16],bitLength[2] = {0,0}, counter=0;
	char str[48],ch;
	int i;

	fstream fin("test.txt",ios::in|ios::binary);
	FILE *hash = fopen("hash.txt","wt");

	while(!fin.eof())
	{

		for(i=0; i<4; i++)
			op[i] = 0;
		fin>>str;
		bitLength[1] = bitLength[0] = 0;
		increment(bitLength,8*strlen(str));

		for(i=0;i<4;i++)
			ip[i] = op[i];

		for(counter=0; (counter+48) <= (bitLength[1]/8); counter+=48)
		{
			convert(str,counter,ip);
			//print(ip,16);
			hash512(op,ip,8);

			for(i=0;i<4;i++)
				ip[i] = op[i];
		}

		if(counter*8 < bitLength[1])
		{
			counter += (bitLength[1]/8);
			while(counter%48!=0)
				str[counter++] = 0;
			convert(str,(counter-48),ip);
			//print(ip,16);
			hash512(op,ip,8);

			for(i=0;i<4;i++)
				ip[i] = op[i];
		}
		//print(ip,16);
		ip[14] = bitLength[0];
		ip[15] = bitLength[1];
		//print(ip,16);
		hash512(op,ip,8);

		cout<<endl<<setw(10)<<setfill(' ')<<str<<" ";
		print(op,4);

		fprintf(hash,"%10s ",str);
		for(int j=0;j<4;j++)
			fprintf(hash,"%08lx ",op[j]);
		fprintf(hash,"\n");
	}
	getch();
}
Ejemplo n.º 15
0
	ostream &operator<<(ostream &stream, const VendorProduct &vendor_product)
	{
		ostream_state_saver state(stream);
		stream << "vendor ID:" << setfill('0') << hex << setw(4) << vendor_product.getVendorId() << ", product ID:" << setw(4) << vendor_product.getProductId();
		return stream;
	}
Ejemplo n.º 16
0
  basic_ostream<charT,traits>& operator<<(basic_ostream<charT,traits>& os, const PROPVARIANT& propvar)
  { switch( propvar.vt )
    {
    case VT_EMPTY:
      os<<_T("\"\"");
      break;
    case VT_NULL:
      os<<_T("NULL");
      break;
    case VT_I2:
      os<<propvar.iVal;
      break;
    case VT_I4:
    case VT_INT:
      os<<propvar.lVal;
      break;
    case VT_I8:
      os<<propvar.hVal.HighPart<<propvar.hVal.LowPart;
      break;
    case VT_UI2:
      os<<propvar.uiVal;
      break;
    case VT_UI4:
    case VT_UINT:
      os<<propvar.ulVal;
      break;
    case VT_UI8:
      os<<propvar.uhVal.HighPart<<propvar.uhVal.LowPart;
      break;
    case VT_R4:
      os<<propvar.fltVal;
      break;
    case VT_R8:
      os<<propvar.dblVal;
      break;
    case VT_BSTR:
      os<<propvar.bstrVal;
      break;
    case VT_ERROR:
      os<<hex<<_T("0x")<<setw(8)<<setfill(_T('0'))<<propvar.scode;
      break;
    case VT_BOOL:
      os<< (VARIANT_TRUE == propvar.boolVal ? _T("True") : _T("False") );
      break;
    case VT_I1:
      os<<propvar.cVal;
      break;
    case VT_UI1:
      os<<propvar.bVal;
      break;
    case VT_VOID:
      os<<_T("void");
      break;
    case VT_LPSTR:
      os<<propvar.pszVal;
      break;
    case VT_LPWSTR:
      os<<propvar.pwszVal;
      break;
    case VT_FILETIME:
      os<<propvar.filetime.dwHighDateTime<<_T(":")<<propvar.filetime.dwLowDateTime;
      break;
    case VT_CLSID:
      os<<((const TString&)CGUID(*propvar.puuid)).c_str();
      break;
    default:
      if( propvar.vt & VT_VECTOR )
      { ULONG count = 0;

        switch( propvar.vt & VT_TYPEMASK )
        {
        case VT_LPSTR:
          count = propvar.calpstr.cElems;
          for( ULONG i=0;i<count;i++ )
            os<<propvar.calpstr.pElems[i]<<_T(",");

          break;
        case VT_LPWSTR:
          count = propvar.calpwstr.cElems;
          for( ULONG i=0;i<count;i++ )
            os<<propvar.calpwstr.pElems[i]<<_T(",");

          break;
        default:
          os<<_T("VT_VECTOR");
          break;
        } // of switch
      } // of if
      else
        os<<_T("...");
      break;
    } // of switch
    
    return os;
  } // of basic_ostream<charT,traits>& operator<<(basic_ostream<charT,traits>& osconst STATPROPSTG& statpropstg)
Ejemplo n.º 17
0
AbstractCommand::PostAction
BanList::doExecute( Context& txt )
{
    // bail if nothing to display
    if (userDB.mapBANTIME.empty()) {
        txt._ebuf << "There are no banned users.";
        return PA_ERROR;
    }

    struct Filter {
        string auth;  
        string ip;
        int    level;
        string name;  
        int    since; 
    };
    Filter filter = { "", "", -1, "", 0 };

    // parse filter options    
    {
        const vector<string>::size_type max = txt._args.size();
        for ( vector<string>::size_type i = 1; i < max; i++ ) {
            // pairs of args are expected
            if ((max - i) < 2)
                return PA_USAGE;

            string s = txt._args[i];
            str::toLower( s );

            if (s == "-auth" ) {
                filter.auth = txt._args[++i];
                str::toLower( filter.auth );
            }
            else if (s == "-ip" ) {
                filter.ip = txt._args[++i];
            }
            else if (s == "-level") {
                const string& s = txt._args[++i];
                string err;
                Level& lev = lookupLEVEL( s, txt );
                if (lev == Level::BAD)
                    return PA_ERROR;
                filter.level = lev.level;
            }
            else if (s == "-name") {
                filter.name = txt._args[++i];
                str::toLower( filter.name );
            }
            else if (s == "-since") {
                filter.since = str::toSeconds( txt._args[++i] );
            }
            else {
                return PA_USAGE;
            }
        }
    }

    InlineText cID      = xheader;
    InlineText cWhen    = xheader;
    InlineText cSubject = xheader;
    InlineText cRemain  = xheader;
    InlineText cAuth    = xheader;

    cID.flags      |= ios::left;
    cWhen.flags    |= ios::left;
    cSubject.flags |= ios::left;

    cID.width      = 8;
    cWhen.width    = 24;
    cSubject.width = 25;
    cRemain.width  = 13;

    cWhen.prefixOutside    = ' ';
    cSubject.prefixOutside = ' ';
    cRemain.prefixOutside  = ' ';
    cAuth.prefixOutside    = ' ';

    Buffer buf;
    buf << cID      ( "ID" )
        << cWhen    ( "WHEN" )
        << cSubject ( "SUBJECT" )
        << cRemain  ( "REMAINING" )
        << cAuth    ( "AUTHORITY" );

    cID.color      = xcnone;
    cWhen.color    = xcnone;
    cSubject.color = xcnone;
    cRemain.color  = xcnone;
    cAuth.color    = xcnone;

    const time_t now = time( NULL );
    string tmp;

    uint32 numExpired = 0;
    uint32 num = 0;
    const UserDB::mapBANTIME_t::const_reverse_iterator max = userDB.mapBANTIME.rend();
    for ( UserDB::mapBANTIME_t::const_reverse_iterator it = userDB.mapBANTIME.rbegin(); it != max; it++ ) {
        const User& user = *it->second;
        const string id = (user.guid.length() == 32) ? user.guid.substr( 24 ) : "";

        const time_t deltaTime = user.banExpiry - now;

        // skip if ban has expired
        if (user.banExpiry && deltaTime < 0) {
            numExpired++;
            continue;
        }

        if (!filter.auth.empty()) {
            tmp = user.banAuthority;
            str::toLower( tmp );
            if (tmp.find( filter.auth ) == string::npos)
                continue;
        }

        if (!filter.ip.empty() && (user.ip.find( filter.ip ) == string::npos))
            continue;

        if (filter.level != -1 && user.authLevel != filter.level)
            continue;

        if (!filter.name.empty()) {
            tmp = user.name;
            str::toLower( tmp );
            if (tmp.find( filter.name ) == string::npos)
                continue;
        }

        if (filter.since > 0 && ((now - user.timestamp) > filter.since))
            continue;

        if (++num > (Page::maxLines * Page::maxPages))
            break;

        // format ban time
        char ftime[32];
        strftime( ftime, sizeof(ftime), "%c", localtime( &user.banTime ));

        buf << '\n'
            << cID      ( id )
            << cWhen    ( ftime )
            << cSubject ( str::etAlignLeft( user.namex, cSubject.width, tmp ));

        ostringstream remain;
        if (!user.banExpiry) {
            remain << "permanent";
        }
        else {
            int secs = (user.banExpiry - now);

            int days = secs / (60*60*24);
            secs -= (days * (60*60*24));

            int hours = secs / (60*60);
            secs -= (hours * (60*60));

            int mins = secs / 60;
            secs -= (mins * 60);

            if (days > 999)
                remain << "999d-";
            else if (days > 0)
                remain << days << "d-";

            remain << setw(2) << setfill('0') << hours
                   << ':' << setw(2) << setfill('0') << mins
                   << ':' << setw(2) << setfill('0') << secs;
        }

        buf << cRemain ( remain.str() )
            << cAuth   ( user.banAuthorityx );
    }

    Page::report( txt._client, buf );

    if (numExpired) {
        buf.reset();
        buf << xcheader << "--there were " << xvalue( numExpired ) << " expired-bans not listed.";
        print( txt._client, buf );
    }

    return PA_NONE;
}
Ejemplo n.º 18
0
  basic_ostream<charT,traits>& operator<<(basic_ostream<charT,traits>& os, IStorage *pStg)
  { COMPtr<IPropertySetStorage> pPropSetStg;
    COMPtr<IEnumSTATSTG>        penum;
    HRESULT                     hr = S_OK;
    STATSTG                     statstg;
    int                         indent;

    LogStream<TCHAR>* logger = dynamic_cast< LogStream<TCHAR>* >(&os);
    
    if( NULL!=logger )
      indent = logger->GetIndent();

    ::memset( &statstg, 0, sizeof(statstg) );

    THROW_COMEXCEPTION( pStg->QueryInterface( IID_IPropertySetStorage,reinterpret_cast<void**>(&pPropSetStg) ) );

    os<<pPropSetStg;

    THROW_COMEXCEPTION( pStg->EnumElements( NULL, NULL, NULL, &penum ) );

    hr = penum->Next( 1, &statstg, 0 );
    THROW_COMEXCEPTION( hr );

    while( S_OK == hr )
    { 
      if( NULL!=logger )
        logger->SetIndent(indent);

      { if( STGTY_STORAGE==statstg.type )
          os<<_T("[");

        if( statstg.pwcsName[0]>_T('\x20') )
          os<<statstg.pwcsName;
        else
          os<<_T("'\\x")<<hex<<setw(2)<<setfill(_T('0'))<<(UINT)(statstg.pwcsName[0])<<_T("'")<<statstg.pwcsName+1;

        if( STGTY_STORAGE==statstg.type )
          os<<_T("]");

        if( _T('\005')==statstg.pwcsName[0] )
        { GUID fmtid;

          if( COM::COPropertySet::PropertySetNameToGuid(_tcslen(statstg.pwcsName),statstg.pwcsName,&fmtid) )
            os<<_T(" --> FMTID=")<<((const TString&)CGUID(fmtid)).c_str();
        } // of if

        os<<endl;
      } // of if

      if( STGTY_STORAGE==statstg.type && _T('\005')!=statstg.pwcsName[0] )
      { COMPtr<IStorage> pStgChild;

        THROW_COMEXCEPTION( pStg->OpenStorage( statstg.pwcsName,NULL,STGM_READ | STGM_SHARE_EXCLUSIVE,NULL, 0,&pStgChild ) );

        if( logger!=NULL )
          logger->SetIndent(indent+1);

        os<<pStgChild;
      } // of if

      ::CoTaskMemFree( statstg.pwcsName );
      statstg.pwcsName = NULL;

      hr = penum->Next( 1, &statstg, 0 );
      THROW_COMEXCEPTION( hr );
    } // of while
    
    return os;
  } // of basic_ostream<charT,traits>& operator<<(basic_ostream<charT,traits>& os, IStorage *pStg)
Ejemplo n.º 19
0
int main(int argc, char **argv) {
	srand(time(0));

	int popNum;
	int indCount;

	fstream simdata;
	simdata.open("simdata.txt");
	simdata >> popNum >> indCount;
	simdata.close();

	cout << "População: " << popNum << endl;
	cout << "Numero de individuos: " << indCount << endl;

	stringstream popOutName;

	popOutName << "popstat." << setw(5) << setfill('0') << popNum << ".txt";

	simdata.open("simdata.txt");
	simdata << (popNum + 1) << ' ' << indCount;
	simdata.close();

	vector<guy> pop;
	map<string, guy> popmap;

	ifstream read;
	read.open("stats.txt");

	Robot r(nullptr, nullptr, nullptr);

	map<string, RobotDescriptor*> descs;

	do {
		string id;
		double score;
		int stall;
		double duration;

		read >> id >> score >> stall >> duration;

		if (!id.length()) {
			break;
		}

		guy g;
		g.id = id;
		g.score = score;

		pop.push_back(g);

		popmap.insert(pair<string, guy>(g.id, g));

		RobotDescriptor *descriptor = new RobotDescriptor();

		stringstream fileName;
		fileName << "robots/desc" << id;

		cout << "READING FILE " << fileName.str() << endl;
		ifstream inputFile;
		inputFile.open(fileName.str());
		descriptor->loadFromFile(inputFile, &r);
		inputFile.close();

		descs.insert(pair<string, RobotDescriptor*>(id, descriptor));
	} while (!read.eof());

	sort(pop.begin(), pop.end());

	ofstream popOut;
	popOut.open(popOutName.str());

	map<string, RobotDescriptor*> newPop;

	vector<guy> newpop;
	map<string, guy> mapunique;
	while (newpop.size() != indCount) {
		vector<string> killed;
		vector<string> chosen;
		tournament(pop, 0, pop.size() - 1, SIZE, chosen, killed);

		newpop.push_back(popmap[chosen[0]]);
		mapunique.insert(pair<string, guy>(chosen[0], popmap[chosen[0]]));
	}

	vector<guy> popunique;

	for (map<string, guy>::iterator it = mapunique.begin();
			it != mapunique.end(); ++it) {
		popunique.push_back(it->second);
	}

	sort(newpop.begin(), newpop.end());
	sort(popunique.begin(), popunique.end());

	vector<double> divs;
	vector<double> oldPopScores;
	vector<double> newPopScores;
	vector<double> newPopScoresUnique;

	for (int i = 0; i < 400; i += 10) {
		divs.push_back(i);
	}

	for (int i = 0; i < pop.size(); i++) {
		oldPopScores.push_back(pop[i].score);
	}

	for (int i = 0; i < newpop.size(); i++) {
		newPopScores.push_back(newpop[i].score);
	}

	for (int i = 0; i < popunique.size(); i++) {
		newPopScoresUnique.push_back(popunique[i].score);
	}

	vector<int> oldPopStats = generateHistogram(divs, oldPopScores);
	vector<int> newPopStats = generateHistogram(divs, newPopScores);
	vector<int> newPopStatsUnique = generateHistogram(divs, newPopScoresUnique);

	popOut << newpop.size() << " chosen, " << popunique.size() << " unique\n";
	popOut << "range\told\tnew\tunique\n";

	for (int i = 0; i < divs.size(); i++) {
		popOut << divs[i] << '\t' << oldPopStats[i] << '\t' << newPopStats[i]
				<< '\t' << newPopStatsUnique[i] << '\n';
	}

	for (int i = 0; i < pop.size(); i++) {
		popOut << pop[i].score << "\t" << pop[i].id << '\n';
	}

	for (int j = 0; j < SURVIVAL_RATE * popunique.size(); j++) {
		string id = popunique[j].id;
		popOut << id << " survived\n";
		cout << "choosing " << id << ", score: " << popunique[j].score << endl;
		newPop.insert(pair<string, RobotDescriptor*>(id, descs[id]));
	}

	popOut.close();

	cout << endl;

	if (argc > 1) {
		return 0;
	}

	ofstream output;
	output.open("generated.txt");
	
	int ammountCross = TAXA_CROSS * (indCount - newPop.size());

	for (int i = 0; i < ammountCross; i++) {
		string parent1 = popunique[rand() % (popunique.size())].id;
		string parent2 = popunique[rand() % (popunique.size())].id;
		RobotDescriptor *p1 = descs[parent1];
		RobotDescriptor *p2 = descs[parent2];

		double point = (rand() % 10) / 10.0;

		if (p1->behaviours.size() < 3 || p2->behaviours.size() < 3) {
			continue;
		}

		RobotDescriptor *ind = new RobotDescriptor();

		int cut1 = std::min(std::max(1, (int) (point * p1->behaviours.size())),
				(int) p1->behaviours.size() - 2);
		int cut2 = std::min(std::max(1, (int) (point * p2->behaviours.size())),
				(int) p2->behaviours.size() - 2);

		//@bug Referência ao descritor pai é mantida!
		for (int i = 0; i < cut1; i++) {
			ind->addBehavior(p1->behaviours[i]);
		}
		for (int i = cut2; i < p2->behaviours.size(); i++) {
			ind->addBehavior(p2->behaviours[i]);
		}
	}

	//Mutação!
	int k = 0;
	while (newPop.size() < indCount) {
		string parentID = popunique[rand() % (popunique.size())].id;
		RobotDescriptor *parent = descs[parentID];
		RobotDescriptor *ind = new RobotDescriptor();

		stringstream fileName;
		fileName << "robots/desc" << parentID;
		ifstream inParent;
		inParent.open(fileName.str());
		ind->loadFromFile(inParent, nullptr);
		inParent.close();

		for (int i = 0; i < ind->behaviours.size(); i++) {
			BehaviourOnObstacleDistance *b =
					static_cast<BehaviourOnObstacleDistance*>(ind->behaviours[i]);
			if (rand() % 100 <= 5) {
				b->angle += rand()%5 - 2;
				b->angle = std::min(std::max(b->angle, 360.0), 0.0);
			}
			if (rand() % 100 <= 5) {
				b->distanceMax += (rand() % 20) / 100.0 - 0.1;
			}
			if (rand() % 100 <= 5) {
				b->distanceMin += (rand() % 20) / 100.0 - 0.1;
			}

			for (int j = 0; j < b->actions.size(); j++) {
				Action *a = b->actions[j];

				if (rand() % 100 <= 5) {
					a->duration += (rand() % 20) / 100.0 - 0.1;
				}
				if (rand() % 100 <= 5) {
					a->duration = std::max(0.0, a->duration);
				}

				if (rand() % 100 <= 5) {
					a->value += (rand() % 20) / 100.0 - 0.1;
				}
			}

			if (!(rand() % 100)) {
				Action *a;
				if (rand() % 2) {
					a = new Action(ACTION_LINEAR_VEL, (rand() % 100) / 100.0,
							(rand() % 100) / 100.0);
				} else {
					a = new Action(ACTION_ANGULAR_VEL,
							(rand() % 200) / 100.0 - 1, (rand() % 100) / 100.0);
				}

				b->addAction(a);
			}
		}

		if (!(rand() % 100)) {
			double minDist = (rand() % 100) / 100.0;
			Behaviour *b = new BehaviourOnObstacleDistance(nullptr,
					rand() % 360, minDist, minDist + (rand() % 400) / 100.0);

			Action *act;
			if (rand() % 2) {
				act = new Action(ACTION_LINEAR_VEL, (rand() % 100) / 100.0,
						(rand() % 100) / 100.0);
			} else {
				act = new Action(ACTION_ANGULAR_VEL, (rand() % 200) / 100.0 - 1,
						(rand() % 100) / 100.0);
			}

			b->addAction(act);
		}

		stringstream generatedID;
		generatedID << setw(5) << setfill('0') << popNum << '.' << setw(5)
				<< setfill('0') << k;

		cout << "New ID: " << generatedID.str() << endl;

		stringstream generatedFile;
		generatedFile << "robots/desc" << generatedID.str();

		cout << "New File: " << generatedFile.str() << endl;

		ofstream saveFile;
		saveFile.open(generatedFile.str());
		ind->saveToFile(saveFile);
		saveFile.close();

		newPop.insert(pair<string, RobotDescriptor*>(generatedID.str(), ind));

		k++;

	}

	for (map<string, RobotDescriptor*>::iterator it = newPop.begin();
			it != newPop.end(); ++it) {
		output << it->first << '\n';
	}

	output.close();

	return 0;
}
Ejemplo n.º 20
0
int Preprocessor::montage(){
    string src = para.mon_src;
    string dst = para.mon_dst;
    string sys_del = para.sys_del;
    unsigned int serial_beg = para.serial_beg, serial_end = para.serial_end, 
                        x_beg = para.x_beg, x_end = para.x_end, 
                        y_beg = para.y_beg, y_end = para.y_end, 
                        block_width = para.block_width, block_height = para.block_height, serial_bits = para.serial_bits,
                        thread_num = para.thread_num;
    unsigned int image_depth = para.image_depth;
    string image_pre = para.mon_in_pre, image_post = para.mon_in_post;
    string out_pre = para.mon_out_pre, out_post = para.mon_out_post; 
#pragma omp parallel for num_threads(thread_num) 
    for(int serial_num = int(serial_beg); serial_num <= int(serial_end); ++ serial_num){
        stringstream string_buffer;
        string serial_string("");
        cv::Mat out_image, block_image, re_block_image;
        cout<<serial_num<<": "<<omp_get_thread_num()<<endl;
        if(image_depth ==  16){
            out_image = cv::Mat((y_end - y_beg + 1) * block_height, (x_end - x_beg + 1) * block_width, CV_16UC1, cv::Scalar(0, 0, 0));
            //cout<<out_image.rows<<" "<<out_image.cols<<" "<<out_image.depth()<<endl;
            block_image = cv::Mat(block_height, block_width, CV_16UC1, cv::Scalar(0, 0, 0));
            re_block_image = cv::Mat(block_height, block_width, CV_16UC1, cv::Scalar(0, 0, 0));        
        }else{
            out_image = cv::Mat((y_end - y_beg + 1) * block_height, (x_end - x_beg + 1) * block_width, CV_8UC1, cv::Scalar(0, 0, 0));
            //cout<<out_image.rows<<" "<<out_image.cols<<" "<<out_image.depth()<<endl;
            block_image = cv::Mat(block_height, block_width, CV_8UC1, cv::Scalar(0, 0, 0));
            re_block_image = cv::Mat(block_height, block_width, CV_8UC1, cv::Scalar(0, 0, 0));    
        
        }
        string x_str, y_str, image_str, out_image_name;       
        string_buffer<<setw(serial_bits)<<setfill('0')<<serial_num;    
        string_buffer>>serial_string;
        string_buffer.clear();
        //cout<<serial_string<<endl;
        for(unsigned int x_in = x_beg; x_in <= x_end; ++ x_in){
            for(unsigned int y_in = y_beg; y_in <= y_end; ++ y_in){
                string_buffer<<setw(2)<<setfill('0')<<x_in;
                string_buffer>>x_str;
                string_buffer.clear();
                string_buffer<<setw(2)<<setfill('0')<<y_in;
                string_buffer>>y_str;
                string_buffer.clear();
                image_str = src + sys_del + serial_string + sys_del +image_pre + serial_string + "_" + x_str + "_" + y_str + image_post;
                block_image = cv::imread(image_str.c_str(), CV_LOAD_IMAGE_UNCHANGED);
                if(!block_image.data){
                    cout<<"----------------------"<<endl;
                    cout<<"Image Loaded Error!"<<endl;
                    cout<<image_str<<endl;
                    cout<<"----------------------"<<endl;
                    if(image_depth == 8){
                        block_image = cv::Mat::zeros(block_height, block_width, CV_8UC1);
                    }else if(image_depth == 16){
                        block_image = cv::Mat::zeros(block_height, block_width, CV_16UC1);
                    }
                    
                }
                for(int y_block = 0; y_block < block_image.cols; ++ y_block){
                    block_image.col(y_block).copyTo(re_block_image.col(block_image.cols - y_block - 1));       
                }
                cv::Rect sub_roi((x_in - x_beg) * block_width, (y_in - y_beg) * block_height, block_width, block_height);                 
                cv::Mat sub_image(out_image, sub_roi);
                re_block_image.clone().copyTo(sub_image);
            }
                        
        }
        
        out_image_name = dst + sys_del + out_pre + serial_string + out_post;
        cout<<out_image_name<<endl;
        cv::imwrite(out_image_name, out_image);            
    }
    
    
    
    return 0;
} 
Ejemplo n.º 21
0
Packet::Packet(PacketCnt *pcnt) {
    packet_cnt_ = pcnt;
    stream_ = NULL;  // default
    l7_content_ = NULL;  // default
    timestamp_ = packet_cnt_->pcap_hdr.ts;
    packet_size_cap_ = packet_cnt_->pcap_hdr.caplen;
    packet_size_org_ = packet_cnt_->pcap_hdr.len;

    error_ = 0;

    packet_ = (unsigned char *)malloc(packet_size_cap_);
    memcpy(packet_, packet_cnt_->pcap_pkt, packet_size_cap_);

    l2_header_size_ = sizeof(struct ether_header);
    eth_header_ = (struct ether_header *) packet_;

    stringstream ss;
    ss.str("");
    ss.clear(stringstream::goodbit);
    for (int i = 0; i < 5; i++) {
        ss << hex << setw(2) << setfill('0')
           << static_cast<int>(eth_header_->ether_shost[i]) << ":";
    }
    ss << hex << setw(2) << setfill('0') << static_cast<int>(eth_header_->ether_shost[5]);
    src_mac_addr_ = ss.str();

    ss.str("");
    ss.clear(stringstream::goodbit);
    for (int i = 0; i < 5; i++) {
        ss << hex << setw(2) << setfill('0')
           << static_cast<int>(eth_header_->ether_dhost[i]) << ":";
    }
    ss << hex << setw(2) << setfill('0') << static_cast<int>(eth_header_->ether_dhost[5]);
    dst_mac_addr_ = ss.str();


    if (ntohs(eth_header_->ether_type) == ETH_P_8021Q) {
        l3_header_ = packet_ + sizeof(struct vlan_ethhdr);
        vlan_eth_header_ = (struct vlan_ethhdr *) packet_;
        ether_proto_ = ntohs(vlan_eth_header_->ether_type);
    } else {
        l3_header_ = packet_ + sizeof(struct ether_header);  // IP header
        ether_proto_ = ntohs(eth_header_->ether_type);
    }

    switch (ether_proto_) {
        case ETH_P_IP:
            version_ = 4;
            ip_header_ = (struct iphdr *)l3_header_;
            inet_v4tov6((struct in_addr *)(&(ip_header_->saddr)), &src_ip_);
            inet_v4tov6((struct in_addr *)(&(ip_header_->daddr)), &dst_ip_);
            protocol_ = ip_header_->protocol;

            l3_header_size_ = ip_header_->ihl*4;

            l4_header_ = l3_header_ + ip_header_->ihl*4;  // TCP/UDP header
            packet_size_ = static_cast<unsigned int>(ntohs(ip_header_->tot_len)) + l2_header_size_;

            struct in_addr v4_src_ip, v4_dst_ip;
            inet_v6tov4(&src_ip_ , &v4_src_ip);
            inet_v6tov4(&dst_ip_ , &v4_dst_ip);

            inet_ntop(AF_INET, &v4_src_ip, src_ip_str_, INET6_ADDRSTRLEN);
            inet_ntop(AF_INET, &v4_dst_ip, dst_ip_str_, INET6_ADDRSTRLEN);

            ip6_header_ = NULL;

            break;

        case ETH_P_IPV6:
            version_ = 6;
            ip6_header_ = (struct ip6_hdr *)l3_header_;
            src_ip_ = ip6_header_->ip6_src;
            dst_ip_ = ip6_header_->ip6_dst;
            protocol_ = ip6_header_->ip6_ctlun.ip6_un1.ip6_un1_nxt;

            l3_header_size_ = 40;  // FIXED Size. no follow about extension header.

            l4_header_ = l3_header_ + 40;  // TCP/UDP header
            // in IPv6, IP Header size is not included in payload length(ip6_un1_plen).
            packet_size_ = static_cast<unsigned int>
                      (ntohs(ip6_header_->ip6_ctlun.ip6_un1.ip6_un1_plen))
                           + l2_header_size_ + l3_header_size_;

            inet_ntop(AF_INET6, &src_ip_, src_ip_str_, INET6_ADDRSTRLEN);
            inet_ntop(AF_INET6, &dst_ip_, dst_ip_str_, INET6_ADDRSTRLEN);

            ip_header_ = NULL;
            break;

        default:
            LOG(ERROR) << "This is not IPv4 not IPv6";
            version_ = 0;
            src_port_ = 0;
            dst_port_ = 0;
            content_size_ = 0;
            error_ = 1;
            return;
    }


    if (protocol_ == IPPROTO_TCP) {
        LOG(INFO) << "TCP Packet";
        tcp_header_ = (struct tcphdr *)l4_header_;
        src_port_ = ntohs(tcp_header_->source);
        dst_port_ = ntohs(tcp_header_->dest);
        seq_no_ = ntohl(tcp_header_->seq);
        ack_ = tcp_header_->ack;
        fin_ = tcp_header_->fin;
        syn_ = tcp_header_->syn;
        urg_ = tcp_header_->urg;
        psh_ = tcp_header_->psh;
        rst_ = tcp_header_->rst;
        l4_header_size_ = tcp_header_->doff*4;
        content_size_ = packet_size_ - l2_header_size_ - l3_header_size_ - l4_header_size_;


    } else if (protocol_ == IPPROTO_UDP) {
        LOG(INFO) << "UCP Packet";
        struct udphdr* udp_header = (struct udphdr *)l4_header_;
        src_port_ = ntohs(udp_header->source);
        dst_port_ = ntohs(udp_header->dest);
        l4_header_size_ = ntohs(udp_header->len);
        content_size_ = packet_size_ - l3_header_size_ - sizeof(struct udphdr);
    } else {
        src_port_ = 0;
        dst_port_ = 0;
        content_size_ = 0;
    }
    if (content_size_ > packet_size_cap_) {
        content_size_ = 0;
    }

    content_ = l4_header_ + l4_header_size_;  // caliculate start iterator of content
    l7_content_ = content_;
    l7_content_size_ = content_size_;

    if (packet_size_cap_ < packet_size_) {
        // Show();
    }

    return;
}
Ejemplo n.º 22
0
int Preprocessor::autoWork()
{
    buildWorkGroup();
    int groupNum = static_cast<int>(workPool.size());
    string tarSrc = para.auto_src, autoDst = para.auto_dst, sysDel = para.sys_del,
             tarDst = autoDst +  sysDel + "src", monSrc = tarDst, monDst = autoDst + sysDel + "montage",
             proSrc = monDst, proDst = autoDst + sysDel + "project", resSrc = monDst, resDst = autoDst + sysDel + "resize",
             tarPre = para.tar_file_pre, tarPost = para.tar_file_post, monInPre = para.mon_in_pre, monInPost = para.mon_in_post;
    u_int xBeg = para.x_beg, xEnd = para.x_end, yBeg = para.y_beg, yEnd = para.y_end, blockWidth = para.block_width, blockHeight = para.block_height;
    u_int monWidth = blockWidth * (xEnd - xBeg + 1);
    u_int monHeght = blockHeight * (yEnd - yBeg + 1);
    if(_access(autoDst.c_str(), 0) == -1){
        _mkdir(autoDst.c_str());
        _mkdir(tarDst.c_str());
        _mkdir(monDst.c_str());
        _mkdir(proDst.c_str());
        _mkdir(resDst.c_str());
    }else{
        if(_access(tarDst.c_str(), 0) == -1){
            _mkdir(tarDst.c_str());
        }
        if(_access(monDst.c_str(), 0) == -1){
            _mkdir(monDst.c_str());
        }
        if(_access(proDst.c_str(), 0) == -1){
            _mkdir(proDst.c_str());
        }
        if(_access(resDst.c_str(), 0) == -1){
            _mkdir(resDst.c_str());
        }
    }
#pragma omp parallel for num_threads(para.thread_num)
    for(int i = 0; i < groupNum; ++i){
        vector<unsigned int> &tmpGroup = workPool.at(i);
        int groupSize = static_cast<int>(tmpGroup.size());
        u_int proIndex = 1;
        string startSerial, endSerial;
        for(int j = 0; j < groupSize; ++j){
            if(proIndex > para.pro_thick){
                proIndex = 1;
            }
            string tmpSerial;
            stringstream tmpStream;   
            tmpStream<<setw(5)<<setfill('0')<<tmpGroup.at(j);
            tmpStream>>tmpSerial;
            tmpStream.clear();
            cv::Mat inImage, proImage, resImage, monImage, blockImage, inverseRowBlockImage;
            if(para.image_depth == 8){
                monImage = cv::Mat::zeros(monHeght, monWidth, CV_8UC1);
                inverseRowBlockImage = cv::Mat::zeros(blockHeight, blockWidth, CV_8UC1);
            }else if(para.image_depth == 16){
                monImage = cv::Mat::zeros(monHeght, monWidth, CV_16UC1);
                inverseRowBlockImage = cv::Mat::zeros(blockHeight, blockWidth, CV_16UC1);
            }
            if(proIndex == 1){
                startSerial = tmpSerial;
                if(para.image_depth == 8){
                    proImage = cv::Mat::zeros(monHeght, monWidth, CV_8UC1);
                }else if(para.image_depth == 16){
                    proImage = cv::Mat::zeros(monHeght, monWidth, CV_16UC1);
                }
            }
            
            string tarName = tarSrc + sysDel + tarPre + tmpSerial + tarPost;
            Tar tmpTar(tarName);
            bool tarFlag = tmpTar.untar(tarDst);
            if(tarFlag){
                cout<<tarName<<" "<<omp_get_thread_num()<<endl;
                for(u_int x = xBeg; x <= xEnd; ++x){
                    for(u_int y = yBeg; y <= yEnd; ++y){
                        string monInName;
                        tmpStream<<monSrc<<sysDel<<tmpSerial<<sysDel<<monInPre<<tmpSerial<<"_"<<setw(2)<<setfill('0')<<x<<"_"<<setw(2)<<setfill('0')<<y<<monInPost;
                        tmpStream>>monInName;
                        tmpStream.clear();
                        blockImage = cv::imread(monInName, CV_LOAD_IMAGE_UNCHANGED);
                        if(!blockImage.data){
                            cout<<"----------------------"<<endl;
                            cout<<"Image Loaded Error!"<<endl;
                            cout<<monInName<<endl;
                            cout<<"----------------------"<<endl;
                            if(para.image_depth == 8){
                                blockImage = cv::Mat::zeros(blockHeight, blockWidth, CV_8UC1);
                            }else if(para.image_depth == 16){
                                blockImage = cv::Mat::zeros(blockHeight, blockWidth, CV_16UC1);
                            }
                        }
                        for(int col = 0; col < blockImage.cols; ++col){
                            blockImage.col(col).copyTo(inverseRowBlockImage.col(blockImage.cols - col - 1));
                        }
                        cv::Rect blockRoi((x - xBeg) * blockWidth, (y - yBeg) * blockHeight, blockWidth, blockHeight);
                        inverseRowBlockImage.copyTo(monImage(blockRoi));
                    }  
                }
                string monOutName = monDst + sysDel + para.mon_out_pre + tmpSerial + para.mon_out_post;
                string resOutName = resDst + sysDel + para.res_out_pre + tmpSerial + para.res_out_post;
                cv::imwrite(monOutName, monImage);
                cout<<monOutName<<" "<<omp_get_thread_num()<<endl;
                cv::resize(monImage, resImage, cv::Size(), para.res_fx, para.res_fy, cv::INTER_AREA);
                cv::imwrite(resOutName, resImage);
                cout<<resOutName<<" "<<omp_get_thread_num()<<endl;
                proImage = cv::max(monImage, proImage);
                if(proIndex == para.pro_thick || j == groupSize - 1){
                    endSerial = tmpSerial;
                    string proOutName = proDst + sysDel + para.pro_out_pre + startSerial + "-" + endSerial + para.pro_out_post;
                    cv::imwrite(proOutName, proImage);
                    cout<<proOutName<<" "<<omp_get_thread_num()<<endl;
                }
                
            }else{
                cout<<"Tar Error!"<<endl;
            }
            ++proIndex;
        }
    }
Ejemplo n.º 23
0
void SCStat::PrintTransition() {

	unsigned int sizePri = GetSizeInt( MaxTransitionPriority() );
	unsigned int sizeTime = 0;
	unsigned int sizePro = GetSizeDouble( MaxTransitionProbability() );
	unsigned int sizeCount = GetSizeInt( MaxTransitionTotalPassedOut() );
	unsigned int sizeCountIn = GetSizeInt( MaxTransitionTotalPassedIn() );
	int sizeTrans = GetSizeInt(g_allTrans.size()) + 3;
	unsigned int sizeName =  MaxTransitionName();
	char priority[15] = "priority";
	if( sizePri < strlen(priority) )
		sizePri = strlen(priority);
	char time[30] = "timed transition";
	if( sizeTime < strlen(time) )
		sizeTime = strlen(time); 
	char probability[30] = "probability";
	if( sizePro < strlen(probability) )
		sizePro = strlen(probability);
	char countIn[19] = "count tags IN";
	if( sizeCountIn < strlen(countIn) )
		sizeCountIn = strlen(countIn);
	char count[19] = "count tags OUT";
	if( sizeCount < strlen(count) )
		sizeCount = strlen(count);
	char name[30] = "name";
	if( sizeName < strlen(name) )
		sizeName = strlen(name);

	int sizeT = sizeName + sizePri + sizeTime +  sizePro + sizeCount + sizeCountIn + 6 + 11 + 6;
	cout << "* " << setfill('-') << setw((sizeT-2)/2) << "" << " transitions " << setw((sizeT-1)/2) << "" << endl;
	cout << "*" << endl;
	cout << "*        " << setfill(' ') << setw(sizeTrans) << "." << " | " 
						<< setw(sizeName) << name << " | " 
	               << setw(sizePri) << priority << " | " 
						<< setw(sizeTime) << time << " | " 
						<< setw(sizePro) << probability << " | "
						<< setw(sizeCountIn) << countIn << " | "
						<< setw(sizeCount) << count << endl;
	cout << "*       " << setw(sizeTrans) << " " << setfill('.') << setw(sizeT-2) << "." << endl;
	char p1[13] = "TRANSITION ";
	unsigned int k = 0;
	for(unsigned int i = 0; i != g_allTrans.size(); i++ )
	{
		cout << "*       "<< p1[k] << setfill(' ') << setw(sizeTrans) << i+1 << " | " 
								<< setw(sizeName) << g_allTrans[i]->GetName().c_str() << " | " 
	               		<< setw(sizePri) << g_allTrans[i]->GetPriority() << " | " 
								<< setw(sizeTime) << GetTransitionTime(i).c_str() << " | " 
								<< setw(sizePro) << g_allTrans[i]->GetProbability() << " | "
								<< setw(sizeCountIn) << g_allTrans[i]->GetTotalPassedIn() << " | "
								<< setw(sizeCount) << g_allTrans[i]->GetTotalPassedOut() << endl;
		if( k < 9 )
			k++;
		else if( i > 8 )
			k = 10;

	}
	if( strlen(p1) > g_allTrans.size() )
	{
		for(; k<strlen(p1)-1; k++)
		{
			cout << "*       "<< p1[k] << endl;
		}
	}
	cout << "*" <<endl;
}
int linkingLoaderPass1(string file, int csaddr)
{
    cout<<endl<<"-----------------"<<endl;
    cout<<"Running pass 1..."<<endl;
	ifstream hex((file+".o").c_str());
	char line[100];
    char* tokens[6];
	int addr = 0, csaddr_as = 0, rel = 0, cslen = 0;
	int no_tokens = 0;
	string cs_name;
	string rec_type, loc, opcode, operand;
	if(hex)
	{
		rec_type.clear(), cs_name.clear(), loc.clear(), opcode.clear(), operand.clear();
		hex.getline(line,100);
		no_tokens = extractTokens(line,tokens,'^');
		rec_type.assign(tokens[0]);
		if(rec_type[0]=='H')
		{
			cs_name.assign(tokens[1]);
			loc.assign(tokens[2]);
			stringstream s(loc.substr(1,loc.length()-1));
			s>>std::hex>>csaddr_as;
			s.str("");s.clear();
			
			addr = csaddr_as;
			rel = addr-csaddr_as;
			operand.assign(tokens[3]);
			s<<operand;
			s>>std::hex>>cslen;
			s.str("");s.clear();
			
            cout<<endl<<"Control Section Name::"<<cs_name<<endl<<"Start Address::"<<setw(4)<<setfill('0')<<uppercase<<std::hex<<(csaddr+rel)<<endl<<"Control Section length::"<<setw(4)<<setfill('0')<<uppercase<<std::hex<<cslen<<endl<<endl;
		}
		else
Ejemplo n.º 25
0
/*
 * 返回一条正常的数据,如果有必要,就获取新的1000条数据   ,否则,直接从内存中获取数据,报警字段均为0
 * LBSU,REAL,ctsm,0000000004,20200000005;20140627113703;A;113.252432;22.564152;30;270;131;0;7,END
 *
 */
string getNormalData(int &minNor_id,int &act_Nor_id,int &serivalnum){
	if(act_Nor_id==0){//
		normalInit();
		db.getData(motorid,lat,lon,dis,a,gprs,speed,dir,gpsLocate,weekday,state_id,sys_state_id,uploadTime,createTime,minNor_id,ArraySize,"normal");
	}

	if(motorid.size()==0)//如果没有取到数据,就直接返回
		return "nodata";

	 //从内存中读,直到ArraySize条都读完
	string result = "";
	stringstream ss; //流水号固定格式
	ss<<setfill('0')<<setw(10)<<serivalnum;
	string serival = ss.str();

	string locate="A";// 定位标志。。偶数的时候表示定位精确
	int locate_int = atoi(gpsLocate[act_Nor_id].c_str());
	if(locate_int%2==0)
		locate = "A";
	else
		locate ="V";
	
	//状态信息,报警信息默认为0
	char nor[8];
	memset(nor,'0',sizeof(nor));
	//1、 状态号码分离   2、 筛选出两边都有的,放在数组中,然后对应,生成2进制数据,再转化为16进制的结果
	vector<string> normalinfors = getSubString(sys_state_id[act_Nor_id],",");
	vector<string>::iterator iter1 = normalinfors.begin(), iter2 = normalinfors.end();
	while (iter1 != iter2)
	{
		if(*iter1=="5")     //ACC开
			nor[5] ='1';
		else if(locate == "A") //判断设备是否准确定位
			nor[6] = '1';
		else if(state_id[act_Nor_id].find("12")>0) //到报警字段中找是否设防
			nor[4] = '1';
		++iter1;
	}
	//车子没有熄火的时候一直保持acc开的,就是状态中有5这个标志位,若没有,则表示车辆熄火,这个记录一下。
	if(nor[5] !='1'){
		nor[0] = '1';
	}
	nor[7]='\0';
	string nor_state = binaryToHex(nor);//传入2进制表示的   char 数组
	if(nor_state=="0"||nor_state==""){
		nor_state = "0";
	}

	result="LBSU,REAL,ctsm,"+serival+","+motorid[act_Nor_id]+";"+uploadTime[act_Nor_id]+";"+locate
			+";"+lon[act_Nor_id]+";"+lat[act_Nor_id]+";"+speed[act_Nor_id]+";"+dir[act_Nor_id]
			+";"+dis[act_Nor_id]+";0;"+nor_state+",END";

	act_Nor_id++;
	serivalnum++;
	if(act_Nor_id==motorid.size()){//内存中的数据都读过了,就重置0,重新到数据库中加载。
		act_Nor_id=0;
	}

//	cout<<motorid[0]<<endl;
//	cout<<lat[0]<<endl;        		//纬度  30.123
//	cout<<lon[0]<<endl;				//经度 120.123
//	cout<<dis[0]<<endl;
//	cout<<a[0]<<endl;
//	cout<<gprs[0]<<endl;
//	cout<<speed[0]<<endl;           //已转换
//	cout<<dir[0]<<endl; 			//已转换
//	cout<<gpsLocate[0]<<endl;     //偶数的时候表示定位精确,反之表示有飘移
//	cout<<weekday[0]<<endl;			//2014-03-25  胡工说明,总为0
//	cout<<state_id[0]<<endl;
//	cout<<sys_state_id[0]<<endl;
//	cout<<uploadTime[0]<<endl;      //设备上传时间
//	cout<<createTime[0]<<endl;		//服务器接收时间
//	cout<<minNor_id<<endl;
//	cout<<ArraySize<<endl;

	return result;
}
Ejemplo n.º 26
0
ostream& operator << (ostream& out, bigint& a) {
    out<<(a.empty() ? 0 : a.back());
    for(int i = sz(a)-2; i >= 0; i--)
        out<<setw(9)<<setfill('0')<<a[i];
    return out;
}
Ejemplo n.º 27
0
/*
 * 获得点名数据,点名数据上的序列号要和收到的序列号是一样的
 */
string getCallData(string str){
	vector<string> strs = getSubString(str,",");
	string ser = strs[3];
	string device = strs[4];

	vector<string> calldata = db.getCallData(device);
	if(calldata.size()==0)
		return "nodata";

	string result = "";
	stringstream ss;
	ss<<setfill('0')<<setw(10)<<ser;
	string serival = ss.str();

	string locate="A";// 定位标志。。偶数的时候表示定位精确
	int locate_int = atoi(calldata[13].c_str());
	if(locate_int%2==0)
		locate = "A";
	else
		locate ="V";

	char al[14];
	memset(al,'0',sizeof(al));
	vector<string> alarminfors = getSubString(strs[5],",");
	vector<string>::iterator iter1 = alarminfors.begin(), iter2 = alarminfors.end();
	while (iter1 != iter2)
	{
		if(*iter1=="6")//超速
			al[11] ='1';
		else if(*iter1=="4")//入界
			al[9] = '1';
		else if(*iter1=="5")//出界
			al[8] = '1';
		else if(*iter1=="10") //疲劳
			al[5] = '1';
		else if(*iter1=="3")//碰撞,震动
			al[4] = '1';
		else if(*iter1=="13")//剪线,断电
			al[2] = '1';
		++iter1;
	}
	al[13]='\0';
	char al_state[8];
	memset(al_state,'0',sizeof(al_state));
	vector<string> al_state_infors = getSubString(strs[6],",");
	vector<string>::iterator iter3 = al_state_infors.begin(), iter4 = al_state_infors.end();
	while (iter3 != iter4)
	{
		if(*iter3=="5")
			al_state[5] ='1';
		else if(locate == "A") //判断设备是否准确定位
			al_state[6] = '1';
		else if(state_id[act_Ala_id].find("12")>0) //到报警字段中找是否设防
			al_state[4] = '1';
		++iter3;
	}
	//车子没有熄火的时候一直保持acc开的,就是状态中有5这个标志位,若没有,则表示车辆熄火,这个记录一下。
	if(al_state[5] !='1'){
		al_state[0] = '1';
	}

	al_state[7]='\0';
	string al_infor = binaryToHex(al);//传入2进制表示的   char 数组
	string al_state_result = binaryToHex(al_state);//传入2进制表示的   char 数组

	if(al_infor=="0"||al_infor==""){
		al_infor = "0";
	}
	if(al_state_result=="0"||al_state_result==""){
		al_state_result = "0";
	}
	result="LBSU,CALL,ctsm,"+serival+","+strs[0]+";"+strs[3]+";"+locate
			+";"+strs[2]+";"+strs[1]+";"+strs[7]+";"+strs[8]
			+";"+strs[11]+";"+al_infor+";"+al_state_result+",END";
	return result;
}
Ejemplo n.º 28
0
string int2str(int i, int ndigits) {
	ostringstream temp;
	temp << setfill('0') << setw(ndigits) << i;
	return temp.str();
}
Ejemplo n.º 29
0
nnob_snd_check_t *NNOBOTExtSnd::UpdateCheckBuf(uint8_t *tocheckseed,
                                               uint8_t *tocheckrcv,
                                               uint64_t otid,
                                               uint64_t numblocks,
                                               channel *check_chan) {
    uint64_t rowbytelen = m_nBlockSizeBytes * numblocks;
    uint64_t checkbytelen = min(rowbytelen, bits_in_bytes(m_nOTs - otid));

    uint8_t *hash_buf = (uint8_t *)malloc(SHA512_DIGEST_LENGTH);
    uint8_t *tmpbuf = (uint8_t *)malloc(rowbytelen);
    uint8_t *idaptr, *idbptr;
    nnob_snd_check_t *check_buf =
        (nnob_snd_check_t *)malloc(sizeof(nnob_snd_check_t));
    // check_buf.rcv_chk_buf = (uint8_t*) malloc(m_nChecks * OWF_BYTES);
    check_buf->chk_buf = (uint8_t *)malloc(m_nChecks * OWF_BYTES);

    uint8_t *chk_buf_ptr = check_buf->chk_buf;
    uint8_t *idatmpbuf = (BYTE *)malloc(sizeof(BYTE) * rowbytelen);
    uint8_t *idbtmpbuf = (BYTE *)malloc(sizeof(BYTE) * rowbytelen);
    uint8_t *seedptr, *rcvptr;

    // uint32_t blockoffset = ceil_divide(otid, NUMOTBLOCKS * m_nBlockSizeBits);
    uint32_t blockid = 0; // TODO bring in as soon as 3-step OT is implemented

    check_buf->otid = otid;
    check_buf->numblocks = numblocks;
    check_buf->perm = (linking_t *)malloc(sizeof(linking_t *) * m_nChecks);
    check_buf->permchoicebits = (BYTE *)malloc(sizeof(uint8_t) * m_nChecks);

    genRandomMapping(check_buf->perm, m_nBaseOTs);

    for (uint32_t i = 0; i < m_nChecks; i++) {
        check_buf->permchoicebits[i] =
            m_vU.GetBit(blockid * m_nBaseOTs + check_buf->perm[i].ida) ^
            m_vU.GetBit(blockid * m_nBaseOTs + check_buf->perm[i].idb);
    }

    // right now the checkbytelen needs to be a multiple of AES_BYTES
    assert(ceil_divide(rowbytelen, OWF_BYTES) * OWF_BYTES == rowbytelen);
#ifdef DEBUG_NNOB_CHECKS
    m_vU.PrintHex();
#endif

    for (uint64_t i = 0; i < m_nChecks; i++, chk_buf_ptr += OWF_BYTES) {
        if (m_vU.GetBit(blockid * m_nBaseOTs + check_buf->perm[i].ida) == 0) {
            memcpy(idatmpbuf, tocheckseed + check_buf->perm[i].ida * rowbytelen,
                   rowbytelen);
        } else {
            seedptr = tocheckseed + check_buf->perm[i].ida * rowbytelen;
            rcvptr = tocheckrcv + check_buf->perm[i].ida * rowbytelen;
            for (int j = 0; j < rowbytelen / sizeof(uint64_t); j++) {
                ((uint64_t *)idatmpbuf)[j] =
                    ((uint64_t *)seedptr)[j] ^ ((uint64_t *)rcvptr)[j];
            }
        }

        if (m_vU.GetBit(blockid * m_nBaseOTs + check_buf->perm[i].idb) == 0) {
            memcpy(idbtmpbuf, tocheckseed + check_buf->perm[i].idb * rowbytelen,
                   rowbytelen);
        } else {
            seedptr = tocheckseed + check_buf->perm[i].idb * rowbytelen;
            rcvptr = tocheckrcv + check_buf->perm[i].idb * rowbytelen;
            for (int j = 0; j < rowbytelen / sizeof(uint64_t); j++) {
                ((uint64_t *)idbtmpbuf)[j] =
                    ((uint64_t *)seedptr)[j] ^ ((uint64_t *)rcvptr)[j];
            }
        }

        /*#ifdef DEBUG_NNOB_CHECKS
                cout << "seedA: " <<  (hex) << ((uint64_t*) (tocheckseed +
        check_buf.perm[i].ida * rowbytelen))[0] <<
                                ", rcvA: " << ((uint64_t*) (tocheckrcv +
        check_buf.perm[i].ida * rowbytelen))[0] << (dec) << endl;
                cout << "seedB: " <<  (hex) << ((uint64_t*) (tocheckseed +
        check_buf.perm[i].idb * rowbytelen))[0] <<
                                ", rcvB: " << ((uint64_t*) (tocheckrcv +
        check_buf.perm[i].idb * rowbytelen))[0] << (dec) << endl;
                cout << "input to owf " <<  (hex) << ((uint64_t*) idatmpbuf)[0]
        << ", " << ((uint64_t*) idbtmpbuf)[0] << (dec) << endl;
        #endif*/

        memset(tmpbuf, 0, rowbytelen);

        for (uint64_t j = 0; j < rowbytelen / sizeof(uint64_t); j++) {
            ((uint64_t *)tmpbuf)[j] = ((uint64_t *)tmpbuf)[j] ^
                                      ((uint64_t *)idatmpbuf)[j] ^
                                      ((uint64_t *)idbtmpbuf)[j];
        }

#ifdef DEBUG_NNOB_CHECKS_INPUT
        cout << "XOR-OWF Input:\t" << (hex);
        for (uint32_t t = 0; t < checkbytelen; t++) {
            cout << setw(2) << setfill('0') << (uint32_t)tmpbuf[t];
        }
        cout << (dec) << endl;
#endif
#ifdef AES_OWF
        owf(&aesowfkey, rowbytelen, tmpbuf, resbuf);
#else
        // m_cCrypt->hash_buf(chk_buf_ptr, OWF_BYTES, tmpbuf, checkbytelen,
        // hash_buf);//hash_buf, rowbytelen, tmpbuf, resbuf, hash_buf);
        sha512_hash(chk_buf_ptr, OWF_BYTES, tmpbuf, checkbytelen, hash_buf);
#endif
#ifdef DEBUG_NNOB_CHECKS_OUTPUT
        cout << "XOR-OWF Output:\t" << (hex);
        for (uint32_t t = 0; t < OWF_BYTES; t++) {
            cout << (uint32_t)chk_buf_ptr[t];
        }
        cout << (dec) << endl;
#endif
        // XORandOWF(idatmpbuf, idbtmpbuf,	checkbytelen, tmpbuf,
        // chk_buf_ptr, hash_buf);
    }

    /*	for(uint64_t i = 0; i < m_nChecks; i++, seedcheckbufptr+=OWF_BYTES,
    rcvcheckbufptr+=OWF_BYTES) {
                    memset(tmpbuf, 0, rowbytelen);
    #ifdef DEBUG_ALSZ_CHECKS
                    cout << i << "-th check between " << check_buf.perm[i].ida
    << " and " << check_buf.perm[i].idb << ": " << endl;
    #endif
                    XORandOWF(tocheckseed + check_buf.perm[i].ida * rowbytelen,
    tocheckseed + check_buf.perm[i].idb * rowbytelen,
                                    rowbytelen, tmpbuf, seedcheckbufptr,
    hash_buf);
                    XORandOWF(tocheckrcv + check_buf.perm[i].ida * rowbytelen,
    tocheckrcv + check_buf.perm[i].idb * rowbytelen,
                                    rowbytelen, tmpbuf, rcvcheckbufptr,
    hash_buf);
            }*/

    free(tmpbuf);
    free(hash_buf);
    free(idatmpbuf);
    free(idbtmpbuf);

    // Send the permutation and the XORed bits over to the receiver
    check_chan->send_id_len((uint8_t *)check_buf->perm,
                            sizeof(linking_t) * m_nChecks, otid, numblocks);
    check_chan->send(check_buf->permchoicebits, m_nChecks);

    return check_buf;
}
Ejemplo n.º 30
0
Archivo: log.cpp Proyecto: 2php/mp4v2
/**
 * Log a buffer as ascii-hex
 *
 * @param indent the number of spaces to indent the buffer
 *
 * @param verbosity the level of detail the message contains
 *
 * @param pBytes the buffer to log
 *
 * @param numBytes the number of bytes to log
 *
 * @param format the format string to use to process the
 * remaining arguments, where the format + remaining args
 * describe @p pBytes.  The resulting string should not
 * contain a newline.  Only the first 255 characters of the
 * resulting string (not including the NUL terminator) make
 * it to the log callback or stdout.
 */
void
Log::hexDump( uint8_t           indent,
              MP4LogLevel       verbosity_,
              const uint8_t*    pBytes,
              uint32_t          numBytes,
              const char*       format,
              ... )
{
    va_list     ap;

    ASSERT(pBytes || (numBytes == 0));
    ASSERT(format);

    if (verbosity_ > this->_verbosity)
    {
        // We're not set verbose enough to log this
        return;
    }

    // Build the description by processing format and the
    // remaining args.  Since we don't have asprintf, pick
    // an arbitrary length for the string and use snprintf.
    // To save a memory allocation, only do this if there's
    // a non-empty format string or non-zero indent
    char *desc = NULL;
    if (format[0] || indent)
    {
        desc = (char *)MP4Calloc(256 + indent);
        sprintf(desc,"%*c",indent,' ');
        va_start(ap,format);
        vsnprintf(desc + indent,255,format,ap);
        va_end(ap);
    }

    // From here we can use the C++ standard lib classes and
    // build a string for each line
    for (uint32_t i = 0;(i < numBytes);i += 16)
    {
        // ios_base::ate means at end.  With out this desc
        // gets overwritten with each << operation
        ostringstream oneLine(desc ? desc : "",ios_base::ate);

        // Append the byte offset this line starts with as
        // an 8 character, leading 0, hex number.  Leave the
        // fill character set to 0 for the remaining
        // operations
        oneLine << ':' << hex << setw(8) << setfill('0') <<
            std::right << i << setw(0) << setfill(' ') << ": ";

        uint32_t curlen = min((uint32_t)16,numBytes - i);
        const uint8_t *b = pBytes + i;
        uint32_t j;

        for (j = 0;(j < curlen);j++)
        {
            oneLine << hex << setw(2) << setfill('0') << right << static_cast<uint32_t>(b[j]);
            oneLine << setw(0) << setfill(' ') << ' ';
        }

        for (; j < 16; j++)
        {
            oneLine << "   ";
        }

        b = pBytes + i;
        for (j = 0;(j < curlen);j++)
        {
            if (isprint(static_cast<int>(b[j])))
            {
                oneLine << static_cast<char>(b[j]);
            }
            else
            {
                oneLine << '.';
            }
        }

        // We can either call the callback directly or use
        // the Log::printf function.  To call the callback
        // directly, we need a va_list.  (I think) we need
        // and extra function call to build that, so we may
        // as well call Log::printf.  It's going to
        // double-check the verbosity and the callback
        // function pointer, but that seems OK (13-feb-09,
        // dbyron)
        this->printf(verbosity_,"%s",oneLine.str().c_str());
    }

    if (desc)
    {
        MP4Free(desc);
        desc = NULL;
    }
}