Пример #1
0
int main(int argc, char **argv) {
	if(argc != 2) {
		std::cout << "Usage:" << std::endl
				<< argv[0] << " {port name}" << std::endl;
		return -1;
	}
	std::string port = argv[1];

	auto logger = std::make_shared<util::Logger>();
	logger->addLog(std::make_shared<util::LogFile>("ntpc-comm", util::LogSeverity::TRACE, "ntpc-comm.log"));
	logger->addLog(std::make_shared<util::LogStream>("ntpc-comm", util::LogSeverity::ERROR, std::cerr.rdbuf()));

	try {
		comm::SerialComm serial(port);

		std::vector<uint16_t> rdbuf(20);

		serial.read(rdbuf.begin(), rdbuf.end());

	} catch(const util::posix_error_exception &e) {
		logger->logPosixError(e.getErrno(), e.getWhile());
	} catch(const std::exception &e) {
		logger->logException(e);
	} catch(const char *str) {
		logger->logException(str);
	} catch(const std::string &s) {
		logger->logException(s);
	}

	return 0;
}
Пример #2
0
int isMatchedString(const char* string,const char* keyword){
    if(string == NULL){
        return REGEX_PARAM_ERROR;
    }else if(keyword == NULL){
        return REGEX_PARAM_ERROR;
    }
    regex_t reg;
    int result = 0; 
    int ret = regcomp(&reg, keyword, REG_EXTENDED);
    if(!ret){
        ret = regexec(&reg, string, 0, NULL, 0);
        if(ret == 0){
            result = 1;
        }else if(ret == REG_NOMATCH){
            result = REGEX_NOMATCH;
        }else{
            result = REGEX_ERROR;
            char msgbuf[256];
            regerror(ret, &reg, msgbuf, sizeof(msgbuf));
            addLog(LOG_ERROR,LOG_LAYER_UTIL,REGEX_LOG_POSITION_NAME,"regex error :%s",msgbuf);
        }
    }else{
        char msgbuf[256];
        regerror(ret, &reg, msgbuf, sizeof(msgbuf));
        addLog(LOG_ERROR,LOG_LAYER_UTIL,REGEX_LOG_POSITION_NAME,"regex error :%s",msgbuf);
        result = REGEX_ERROR;
    }
    regfree(&reg);
    return result;  
}
Пример #3
0
void trellis::update_transitions() {

    std::cout << "Transitions to Start:\n";
    double updated(-INFINITY);
    for(size_t st = 0 ; st < state_size ; st++) {
        updated = ((*dbl_backward_score)[0][st] + (*dbl_forward_score)[0][st])-ending_forward_prob;
        std::cout << hmm->getStateName(st) << "\t" << exp(updated) << std::endl;
    }

    float_2D numerator(state_size, std::vector<float>(state_size,-INFINITY));
    float_2D denominator(state_size, std::vector<float>(state_size,-INFINITY));

    for (size_t position = 0; position < seq_size-1; position++) {
        for (size_t i = 0; i < state_size; i++) {
            for (size_t j = 0; j < state_size; j++) {
                numerator[i][j]= addLog((double)numerator[i][j], (*dbl_baum_welch_score)[position][i][j]);
                denominator[i][j] = addLog((double)denominator[i][j], ((*dbl_forward_score)[position][i] + (*dbl_backward_score)[position][i])-ending_forward_prob);
            }
        }
    }

    for (size_t i = 0; i < state_size; i++) {
        std::cout << hmm->getStateName(i) << "\t";
        for (size_t j = 0; j < state_size; j++) {
            std::cout << exp((numerator[i][j]-denominator[i][j])) << "\t";
        }
        std::cout << std::endl;
    }
}
Пример #4
0
//  Run a Process for some time
//  The process would like to complete its current CPU burst,
//  but is currently only allowed what is granted to it.
//  Parameters:
//      clock           (modified int)  time on simulation clock
//      allowance       (input int)     time allowed to run with
//      next            (output Device) what device should be used next
//next is from { disk, net, console, cpu )
//  Post-Condition:
//      the clock will have advanced until either the allowed time
//      has been used up, or the current CPU burst is complete
//      (whichever happens earlier).  There will be no idle CPU time.
//  Also:  The history log for this Process will record what is known
//      at this time
void Process::run( int &clock, int allowance, Device *&next)
{
  addLog(clock, 'X');
  if(allowance < remainingTime) {
    clock += allowance;
    remainingTime -= allowance;
    next = &cpu;
  }
  else {
    clock += remainingTime;
    if(currentCycle < bursts) {
      next = nextRequest[currentCycle++];
      remainingTime = usages[currentCycle];
    }
    else {
      next = NULL;
    }
    /*    clock += remainingTime;
    next = nextRequest[currentCycle];
    if(next == NULL) {
      addLog(clock, 'Q');
    }
    currentCycle++;
    remainingTime = usages[currentCycle];*/
  }
  addLog(clock, '-');
  //cout << "\tRUN METHOD COMPLETE" << endl;
}
Пример #5
0
VOID WINAPI ServiceCtrlHandler (DWORD CtrlCode)
{
    addLog("Print Service: ServiceCtrlHandler: Entry","serh.txt");

    switch (CtrlCode)
    {
     case SERVICE_CONTROL_STOP :
       addLog("Print Service: ServiceCtrlHandler: SERVICE_CONTROL_STOP Request", "serh.txt");
        if (g_ServiceStatus.dwCurrentState != SERVICE_RUNNING)
           break;

        g_ServiceStatus.dwControlsAccepted = 0;
        g_ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
        g_ServiceStatus.dwWin32ExitCode = 0;
        g_ServiceStatus.dwCheckPoint = 4;

        if (SetServiceStatus (g_StatusHandle, &g_ServiceStatus) == FALSE)
        {
            addLog("Print Service: ServiceCtrlHandler: SetServiceStatus returned error", "serh.txt");
        }
        SetEvent (g_ServiceStopEvent);
        break;
     default:
         break;
    }
   addLog("Print Service: ServiceCtrlHandler: Exit","serh.txt");
}
Пример #6
0
void MainWindow::newRequest(){
    RequestConfig* reqconf = new RequestConfig(this);
    reqconf->setNetworkAccessManager(netAccessMan);
    connect(reqconf, SIGNAL(addLog(QString)), consoleLog, SLOT(addLog(QString)));

    mdiArea->addSubWindow(reqconf);
    reqconf->show();
}
Пример #7
0
void AGIPane::mouseDown(wxMouseEvent& event) {
	std::cerr << "MouseDown " << std::endl;
    //マウスがクリックされたときの処理?
    double x = event.GetX();
    double y = event.GetY();
    if(!isMoved){
    	if(!isPoly){
    		//このxとyが点の2次元配列に含まれるならOK
    		//もちろんある程度の誤差は許容しなければならない
    		nowindex = getindex(x,y);
    		if(nowindex != -1 && nowindex < data->aginum){
    	 		std::cerr << data->name.at(nowindex) << std::endl;
	    		_pre[0] = ag->getB(nowindex, 0);
    			_pre[1] = ag->getB(nowindex, 1);
    			isMoved = true;
    			data->setSIndex(nowindex);
    			data->selectedcoord = -1;
				md->setText(nowindex);
				Refresh();
				pcp->Refresh();
				addLog(nowindex,_pre[0],_pre[1]);
			}
			else if(data->isPCA && nowindex != -1 && nowindex < data->num+data->atr){
				int index = nowindex - data->num;
				data->selectedcoord = index;  
				std::cerr << data->atrname.at(index)<< std::endl;
				_pre[0] = ag->getV(index,0);
    			_pre[1]  =ag->getV(index,1);
    			isMoved = true;
				addLog(nowindex,_pre[0],_pre[1]);
				}
	
			//どのノードも近くないときは複数選択
			else{
				xfrom = x;
				yfrom = y;
				rangeselect = true;
			}
   		}
   		// 投げ縄選択はボタンを押して発動させるようにする
		//2点以上クリックで選んだのち右クリックして終了
		// mouse release後も処理が続くので注意	
		else if(isPoly){
			if(!polystart){
				polyvector.clear();
				polystart = true;
			}
			auto from = pair<int,int>(x,y);
			polyvector.push_back(from);
		}	
	}
}
/* 下拉控件-加窗类型-回调函数 */
int CVICALLBACK windowTypeCallback(int panel, int control, int event,
		void *callbackData, int eventData1, int eventData2){
	int i; 
	GetCtrlVal(panel, PopupPanel_RingWindowType, &i);
	switch(event){
		case EVENT_COMMIT:
			drawAnalysisResult(panel);
			char msg[256];msg[0] = '\0';
			sprintf(msg, "添加-");
			switch(i){
				case 0:
					strcat(msg, "海宁窗");
					break;
				case 1:
					strcat(msg, "海明窗");
					break;
				case 2:
					strcat(msg, "布拉克曼窗");
					break;
			  	case 3:
					strcat(msg, "指数窗");
					break;
				case 4:
					strcat(msg, "高斯窗");
					break;
				case 5:
					strcat(msg, "三角窗");
					break;
			}
			strcat(msg, "-函数");
			addLog(msg, 1, panel);
			break;
	}
	return 0;
}
Пример #9
0
void SVNManager::CommitJob::run()
{
    QString command;
    FILE *fp;
    char buffer[256];

    command += "svn ci ";

    foreach(const SVNEntry *entry, SVNManager::getInstance().entryList) {
        if(entry->isSelected()) {
            command += "\"" + entry->getRelativePath() + "\" ";
        }
    }

    command += "-m \"" + message + "\"";

    fp = pipeOpen(command.toAscii(), "r");

    if (fp == NULL)
        return;

    while (fgets(buffer, 256, fp) != NULL) {
        addLog(buffer);
    }

    pipeClose(fp);

    QMetaObject::invokeMethod(&MainWindow::getInstance(), "commitTerminated", Qt::QueuedConnection, Q_ARG(bool, true));
}
Пример #10
0
void loadResults()
{
	ifstream f("save.dat");
	if (!f)
	{
		addLog("Save file not found");
		return;
	}
	while (!f.eof())
	{
		char buffer [1024];
		f.getline(buffer, 1024);
		string path(buffer);
		if (path=="")
			return;
		f.getline(buffer, 1024);
		SaveInformation info;
		info.result=string(buffer);
		f.getline(buffer, 1024);
		info.score=atof(buffer);
		f.getline(buffer, 1024);
		info.checkFileTime=atoi(buffer);
		saving[path]=info;
	}
	f.close();
	return;

}
Пример #11
0
void logInfo(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    addLog(MOJOSETUP_LOG_INFO, '*', fmt, ap);
    va_end(ap);
} // logInfo
Пример #12
0
void logError(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    addLog(MOJOSETUP_LOG_ERRORS, '!', fmt, ap);
    va_end(ap);
} // logError
Пример #13
0
//!Calculate the ending cell Viterbi and Forward scores
void simpleTrellis::calcEndForwardViterbi() {
    size_t stateSize=hmm->state_size();
    size_t seqSize=seq->getLength();

    for(int previousSt=0; previousSt<stateSize; previousSt++) {
        double transitionValue=getEndingTransition(previousSt);

        double finalViterbiScore=transitionValue+trell[seqSize-1][previousSt].viti;
        double finalForwardScore=transitionValue+trell[seqSize-1][previousSt].forw;

        if (finalViterbiScore>-INFINITY) {
            if (finalViterbiScore>ending.viti) {
                ending.viti=finalViterbiScore;
                ending.ptr=previousSt;
            }
        }

        if (finalForwardScore>-INFINITY) {
            ending.forw=addLog(ending.forw, finalForwardScore);
        }
    }

    probabilityOfSequence=ending.forw;

    return;
}
Пример #14
0
void SVNManager::AnalyzeJob::run()
{
    QString command;
    FILE *fp;
    char buffer[256];

    addLogLine("Analyzing " + path + " ..." );

    command += "svn st";

    fp = pipeOpen(command.toAscii(), "r");

    if (fp == NULL)
        return;

    while (fgets(buffer, 256, fp) != NULL) {
        SVNManager::getInstance().parseLine(buffer);
        addLog(".");
    }

    pipeClose(fp);


    SVNManager::getInstance().currentPath = path;

    QMetaObject::invokeMethod(&MainWindow::getInstance(), "analyzeTerminated", Qt::QueuedConnection, Q_ARG(bool, true));
}
Пример #15
0
void logWarning(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    addLog(MOJOSETUP_LOG_WARNINGS, '-', fmt, ap);
    va_end(ap);
} // logWarning
Пример #16
0
bool CLog::init(const std::string& path)
{
    current_date = boost::gregorian::day_clock::local_day();
    addLog(this, "CLog::init done");

	return(true);
}
Пример #17
0
void FormGame::circleOfPowerDesactive(ITank* killer)
{
    CircleOfPower* circle_of_power = (CircleOfPower*)sender();
    circle_of_power->team() == 1 ? ++_green_circles_destroyers:++_red_circles_destroyers;

    PlayerData pd1 = _players_data.at(_tanks.indexOf(killer));
    PlayerData pd2 = _players_data.at(_tanks.indexOf(circle_of_power->tank()));

    if(killer->isEnemy() != circle_of_power->tank()->isEnemy())
    {
        KillsDeaths kills = _results.value(pd1).value(pd2);
        kills._circle_of_power_destroyed = true;
        QMap<PlayerData , KillsDeaths> value;
        value.insert(pd2, kills);
        _results.insert(pd1, value);
    }

    if(_green_circles_destroyers == _game->getTeam1()->getTanks().size())
    {
        showResults(2);
    }
    else if (_red_circles_destroyers == _game->getTeam2()->getTanks().size())
    {
        showResults(1);
    }
    else
    {
        QString pd1_team = pd1._team == 1?"g":"r";
        QString pd2_team = pd2._team == 1?"g":"r";
        QString log("<span class='%1'>%2</span><span> ha destruido el centro de energía de </span><span class='%3'>%4</span>");
        addLog(_text_style_template.arg(log.arg(pd1_team).arg(pd1._nick).arg(pd2_team).arg(pd2._nick)));
    }
}
Пример #18
0
void logDebug(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    addLog(MOJOSETUP_LOG_DEBUG, '#', fmt, ap);
    va_end(ap);
} // logDebug
Пример #19
0
void trellis::naive_baum_welch() {
    if (dbl_forward_score == NULL) {
        naive_forward();
    }

    if (dbl_backward_score == NULL) {
        naive_backward();
    }

    dbl_baum_welch_score = new (std::nothrow) double_3D(seq_size, std::vector<std::vector<double> >(state_size, std::vector<double>(state_size, -INFINITY)));

    if (dbl_baum_welch_score == NULL) {
        std::cerr << "Can't allocate memory. OUT OF MEMORY\t" << __FUNCTION__ << std::endl;
        exit(2);
    }


    double sum(-INFINITY);

    for(size_t position = 0; position < seq_size-1; position++) { // Time(t)
        sum = (-INFINITY);
        for (size_t previous = 0; previous < state_size ; previous++) { // state(i)
            for (size_t current = 0; current < state_size; current++) { // state(j)
                (*dbl_baum_welch_score)[position][previous][current] = (*dbl_forward_score)[position][previous] + getTransition(hmm->getState(previous), current, position) + (*hmm)[current]->get_emission_prob(*seqs, position+1) + (*dbl_backward_score)[position+1][current];
                sum = addLog((*dbl_baum_welch_score)[position][previous][current], sum);
            }
        }
        for (size_t previous = 0; previous < state_size ; previous++) { // state(i)
            for (size_t current = 0; current < state_size; current++) { // state(j)
                (*dbl_baum_welch_score)[position][previous][current] -= sum;
            }
        }
    }
    return;
}
Пример #20
0
bool DialogUpdateDb::checkConnection()
{
    addLog("Подключаемся к БД...");
    db->close();
    db->setUserName(ui->lineEditName->text());
    db->setPassword(ui->lineEditPassword->text());
    if( db->open() )
    {
        addLog("ok\n");
        return true;
    }
    else
    {
        addLog("неудача.\n");
        return false;
    }
}
void pauseDataAcq(void){
	receiveFlag = 0;
	//如果 write to TSQ process 没有完成,则等待完成
	while( writeTSQEndFlag != 0)
		Delay(0.005);
	addLog("Pause Signal Acq !", 0, panelHdl);
	isDataAcqRunning = 0;
}
void stopDataAcq(void){
	receiveFlag = 0;
	while( writeTSQEndFlag != 0)
		Delay(0.005);
	writeFPP = 0;
	addLog("Stop Signal Acq !", 0, panelHdl);
	isDataAcqRunning = 0;
}
/* 系统辅助函数-Init [Directory Sets] this System needs */
void initDirectorySets(void){
	char dirName[MAX_PATHNAME_LEN];
	char DataDirPath[MAX_PATHNAME_LEN];
	char LogDirPath[MAX_PATHNAME_LEN];
	GetProjectDir(dirName);
	sprintf(DataDirPath, "%s\\DataStorage", dirName);
	sprintf(LogDirPath, "%s\\Logs", dirName);
	int oldValue;
	oldValue = SetBreakOnLibraryErrors(0);
	int isDataDirExisted = MakeDir(DataDirPath);
	int isLogDirExisted = MakeDir(LogDirPath);
	SetBreakOnLibraryErrors (oldValue);
	if(isDataDirExisted == 0)
		addLog("Successfully create the Directory:\n\"DataStorage\" and \"Logs\"", 0, panelHdl);
	else if( isDataDirExisted == -9)
		addLog("\"DataStorage\" and \"Logs\" \nDirectory has already existed!", 0, panelHdl);
	
}
void Attack::_log(int num){
  openLog();
  addLog((String)attackNames[num]);
  for(int a=0;a<apScan.results;a++){
    if(apScan.isSelected(a)){
      Mac _ap;
      _ap.set(apScan.aps._get(a));
      addLog(_ap.toString());
    }
  }
  addLog("-");
  for(int i=0;i<clientScan.results; i++) {
    if(clientScan.getClientSelected(i)) {
      addLog(clientScan.getClientMac(i).toString());
    }
  }
  closeLog();
}
Пример #25
0
//!Set the Backward score for the given cell
//!\param seqPos Sequence position
//!\param currState State index
//!\param value Forward score
void simpleTrellis::setBackward(size_t seqPos, size_t currState,double& value) {
    if (getBackward(seqPos,currState)==-INFINITY) {
        trell[seqPos][currState].back=value;
    }
    else {
        trell[seqPos][currState].back=addLog(trell[seqPos][currState].back, value);
    }
    return;
}
Пример #26
0
//!Set the Forward score for the given cell
//!\param seqPos Sequence position
//!\param currState State index
//!\param value Forward score
void simpleTrellis::setForward(size_t seqPos, size_t currState,double& value) {
    if (getForward()==-INFINITY) {
        trell[seqPos][currState].forw=value;
    }
    else {
        trell[seqPos][currState].forw=addLog(trell[seqPos][currState].forw, value);
    }
    return;
}
Пример #27
0
int main()
{
	addLog("===========================================================");
	addLog("NWChecker started");
	string curdir=getCurrentDir();
	loadResults();
	if (parseConfig())
		return 1;
	checkAll();
	SetCurrentDirectory(curdir.c_str());
	generateHTML();
	saveResults();
	if(silentMode) {
		int i;
		cin>>i;
	}
	return 0;
}
/* 系统功能-暂停、开始及结束数据采集 */	
void startDataAcq(void){
	if(tsqHdl > 0)
		CmtFlushTSQ(tsqHdl, TSQ_FLUSH_ALL, NULL);
	receiveFlag = 1;
	if(isDataAcqRunning != 1){
		runSecondThread(beginDataAcqType, NULL);
		isDataAcqRunning = 1;
	}
	addLog("Begin Signal Acq !", 0, panelHdl);
}
void testEncoder(int daisychain, int motornumber)
{
	int encoderposition = I2C_GetEncoderPosition(S1, daisychain, motornumber);

	// if it's not 0 it must have moved sometime earlier, indicating that the encoder is working
	if (encoderposition != 0) return;

	I2C_SetMotorSpeed(S1, daisychain, motornumber, 10);
	Sleep(150);
	I2C_SetMotorSpeed(S1, daisychain, motornumber, 0);
	if (encoderposition == I2C_GetEncoderPosition(S1, daisychain, motornumber))
	{
		textToAdd = "FATAL: encoder test failed. aborting.";
		addLog();
		StopAllTasks();
	}
	textToAdd = "success: encoder test passed. continuing.";
	addLog();
}
Пример #30
0
int
sockinit(void)
{
    int epfd = epoll_create(1);
    if (epfd == -1) {
        addLog(LOG_WARNING,LOG_LAYER_TRANSFAR,TRANSFAR_SOCKET_POSITION_NAME,"epoll_create");
        return -1;
    }
    return epfd;
}