void MiningPage::readProcessOutput() { QByteArray output; minerProcess->reset(); output = minerProcess->readAll(); QString outputString(output); if (!outputString.isEmpty()) { QStringList list = outputString.split("\n", QString::SkipEmptyParts); int i; for (i=0; i<list.size(); i++) { QString line = list.at(i); // Ignore protocol dump if (!line.startsWith("[") || line.contains("JSON protocol") || line.contains("HTTP hdr")) continue; if (ui->debugCheckBox->isChecked()) { ui->list->addItem(line.trimmed()); ui->list->scrollToBottom(); } if (line.contains("(yay!!!)")) reportToList("Share accepted", SHARE_SUCCESS, getTime(line)); else if (line.contains("(booooo)")) reportToList("Share rejected", SHARE_FAIL, getTime(line)); else if (line.contains("LONGPOLL detected new block")) reportToList("LONGPOLL detected a new block", LONGPOLL, getTime(line)); else if (line.contains("Supported options:")) reportToList("Miner didn't start properly. Try checking your settings.", ERROR, NULL); else if (line.contains("The requested URL returned error: 403")) reportToList("Couldn't connect. Please check your username and password.", ERROR, NULL); else if (line.contains("HTTP request failed")) reportToList("Couldn't connect. Please check pool server and port.", ERROR, NULL); else if (line.contains("JSON-RPC call failed")) reportToList("Couldn't communicate with server. Retrying in 30 seconds.", ERROR, NULL); else if (line.contains("thread ") && line.contains("khash/s")) { QString threadIDstr = line.at(line.indexOf("thread ")+7); int threadID = threadIDstr.toInt(); int threadSpeedindx = line.indexOf(","); QString threadSpeedstr = line.mid(threadSpeedindx); threadSpeedstr.chop(8); threadSpeedstr.remove(", "); threadSpeedstr.remove(" "); threadSpeedstr.remove('\n'); double speed=0; speed = threadSpeedstr.toDouble(); threadSpeed[threadID] = speed; updateSpeed(); } } } }
void Time::init() { lastTime = getTime(); currentTime = getTime(); }
double toggleEnd() { return end=getTime(); }
int EventLoop::processTimeEvents(){ time_t now = time(NULL); /* If the system clock is moved to the future, and then set back to the * right value, time events may be delayed in a random way. Often this * means that scheduled operations will not be performed soon enough. * * Here we try to detect system clock skews, and force all the time * events to be processed ASAP when this happens: the idea is that * processing events earlier is less dangerous than delaying them * indefinitely, and practice suggests it is. */ if (now < this->lastTime) { for (TimeEventVector_t::iterator itr = this->timers.begin(), end = this->timers.end(); itr != end; ++ itr) { (*itr)->when_sec = 0; } } this->lastTime = now; int processed = 0; long maxId = this->timeEventNextId-1; for (TimeEventVector_t::iterator itr = this->timers.begin(), end = this->timers.end(); itr != end; ++ itr) { TimeEvent* te = *itr; if (te->id > maxId) { continue; } long now_sec = 0; long now_ms = 0; getTime(&now_sec, &now_ms); if (now_sec > te->when_sec || (now_sec == te->when_sec && now_ms >= te->when_ms)) { long id = te->id; int retval = te->onTimer(this, id); processed++; /* After an event is processed our time event list may * no longer be the same, so we restart from head. * Still we make sure to don't process events registered * by event handlers itself in order to don't loop forever. * To do so we saved the max ID we want to handle. * * FUTURE OPTIMIZATIONS: * Note that this is NOT great algorithmically. Redis uses * a single time event so it's not a problem but the right * way to do this is to add the new elements on head, and * to flag deleted elements in a special way for later * deletion (putting references to the nodes to delete into * another linked list). */ if (retval != AE_NOMORE) { addMillisecondsToNow(retval,&te->when_sec,&te->when_ms); } else { this->deleteTimeEvent(id); end = this->timers.end(); } itr = this->timers.begin(); } } return processed; }
void end_time() { secs = getTime() - startSecs; return; }
/** Find the position (rank) of every kart. ATM it uses a stable O(n^2) * algorithm by counting for each kart how many other karts are ahead of * it. */ void LinearWorld::updateRacePosition() { // Mostly for debugging: beginSetKartPositions(); const unsigned int kart_amount = m_karts.size(); #ifdef DEBUG bool rank_changed = false; #endif // NOTE: if you do any changes to this loop, the next loop (see // DEBUG_KART_RANK below) needs to have the same changes applied // so that debug output is still correct!!!!!!!!!!! for (unsigned int i=0; i<kart_amount; i++) { AbstractKart* kart = m_karts[i]; // Karts that are either eliminated or have finished the // race already have their (final) position assigned. If // these karts would get their rank updated, it could happen // that a kart that finished first will be overtaken after // crossing the finishing line and become second! if(kart->isEliminated() || kart->hasFinishedRace()) { // This is only necessary to support debugging inconsistencies // in kart position parameters. setKartPosition(i, kart->getPosition()); continue; } KartInfo& kart_info = m_kart_info[i]; int p = 1 ; const unsigned int my_id = kart->getWorldKartId(); const float my_distance = m_kart_info[my_id].m_overall_distance; // Count karts ahead of the current kart, i.e. kart that are // already finished or have covered a larger overall distance. for (unsigned int j = 0 ; j < kart_amount ; j++) { // don't compare a kart with itself and ignore eliminated karts if(j == my_id || m_karts[j]->isEliminated()) continue; // If the other kart has: // - finished the race (but this kart hasn't) // - or is ahead // - or has the same distance (very unlikely) but started earlier // it is ahead --> increase position if((!kart->hasFinishedRace() && m_karts[j]->hasFinishedRace()) || m_kart_info[j].m_overall_distance > my_distance || (m_kart_info[j].m_overall_distance == my_distance && m_karts[j]->getInitialPosition()<kart->getInitialPosition() ) ) { p++; } } //next kart #ifndef DEBUG setKartPosition(i, p); #else rank_changed |= kart->getPosition()!=p; if (!setKartPosition(i,p)) { std::cerr << "ERROR, same rank used twice!!\n"; std::cerr << "Info used to decide ranking :\n"; for (unsigned int d=0; d<kart_amount; d++) { std::cerr << " kart " << m_karts[d]->getIdent() << " has finished(" << m_karts[d]->hasFinishedRace() << "), is at lap (" << getLapForKart(d) << "), is at distance(" << m_kart_info[d].m_overall_distance << "), is eliminated(" << m_karts[d]->isEliminated() << ")" << std::endl; } std::cerr << "Who has each ranking so far :\n"; for (unsigned int d=0; d<i; d++) { std::cerr << " " << m_karts[d]->getIdent() << " has rank " << m_karts[d]->getPosition() << std::endl; } std::cerr << " --> And " << kart->getIdent() << " is being set at rank " << p << std::endl; history->Save(); assert(false); } #endif // Switch on faster music if not already done so, if the // first kart is doing its last lap, and if the estimated // remaining time is less than 30 seconds. if(!m_faster_music_active && kart_info.m_race_lap == race_manager->getNumLaps()-1 && p==1 && useFastMusicNearEnd() && kart_info.m_estimated_finish > 0 && kart_info.m_estimated_finish - getTime() < 30.0f ) { music_manager->switchToFastMusic(); m_faster_music_active=true; } } // for i<kart_amount // Define this to get a detailled analyses each time a race position // changes. #ifdef DEBUG #undef DEBUG_KART_RANK #ifdef DEBUG_KART_RANK if(rank_changed) { std::cout << "Counting laps at "<<getTime()<<" seconds.\n"; for (unsigned int i=0; i<kart_amount; i++) { AbstractKart* kart = m_karts[i]; std::cout << "counting karts ahead of " << kart->getIdent() << " (laps " << m_kart_info[i].m_race_lap << ", progress " << m_kart_info[i].m_overall_distance << " finished " << kart->hasFinishedRace() << " eliminated " << kart->isEliminated() << " initial position "<< kart->getInitialPosition() << ").\n"; // Karts that are either eliminated or have finished the // race already have their (final) position assigned. If // these karts would get their rank updated, it could happen // that a kart that finished first will be overtaken after // crossing the finishing line and become second! if(kart->isEliminated() || kart->hasFinishedRace()) continue; KartInfo& kart_info = m_kart_info[i]; int p = 1 ; const int my_id = kart->getWorldKartId(); const float my_distance = m_kart_info[my_id].m_overall_distance; for (unsigned int j = 0 ; j < kart_amount ; j++) { if(j == my_id) continue; if(m_karts[j]->isEliminated()) { std::cout << " " << p << " : " << m_karts[j]->getIdent() << " because it is eliminated.\n"; continue; } if(!kart->hasFinishedRace() && m_karts[j]->hasFinishedRace()) { p++; std::cout << " " << p << " : " << m_karts[j]->getIdent() << " because it has finished the race.\n"; continue; } if(m_kart_info[j].m_overall_distance > my_distance) { p++; std::cout << " " << p << " : " << m_karts[j]->getIdent() << " because it is ahead " << m_kart_info[j].m_overall_distance <<".\n"; continue; } if(m_kart_info[j].m_overall_distance == my_distance && m_karts[j]->getInitialPosition()<kart->getInitialPosition()) { p++; std::cout << " " << p << " : " << m_karts[j]->getIdent() << " has same distance, but started ahead " << m_karts[j]->getInitialPosition()<<".\n"; } } // next kart j } // for i<kart_amount std::cout << "-------------------------------------------\n"; } // if rank_changed #endif #endif endSetKartPositions(); } // updateRacePosition
UInteger16 msgPackManagementResponse(void *buf, MsgHeader * header, MsgManagement * manage, PtpClock * ptpClock) { TimeInternal internalTime; TimeRepresentation externalTime; *(UInteger8 *) (buf + 20) = 2; /* messageType */ *(Integer32 *) (buf + 28) = shift16(flip16(ptpClock->port_id_field), 0) | shift16(flip16(ptpClock->last_general_event_sequence_number), 1); *(UInteger8 *) (buf + 32) = PTP_MANAGEMENT_MESSAGE; /* control */ clearFlag((buf + 34), PTP_SYNC_BURST); clearFlag((buf + 34), PARENT_STATS); *(Integer32 *) (buf + 40) = shift8(header->sourceCommunicationTechnology, 1); memcpy(buf + 42, header->sourceUuid, 6); *(Integer32 *) (buf + 48) = shift16(flip16(header->sourcePortId), 0) | shift16(flip16(MM_STARTING_BOUNDARY_HOPS), 1); *(Integer32 *) (buf + 52) = shift16(flip16(manage->startingBoundaryHops - manage->boundaryHops + 1), 0); switch (manage->managementMessageKey) { case PTP_MM_OBTAIN_IDENTITY: *(UInteger8 *) (buf + 55) = PTP_MM_CLOCK_IDENTITY; *(Integer32 *) (buf + 56) = shift16(flip16(64), 1); *(Integer32 *) (buf + 60) = shift8(ptpClock->clock_communication_technology, 3); memcpy(buf + 64, ptpClock->clock_uuid_field, 6); *(Integer32 *) (buf + 72) = shift16(flip16(ptpClock->clock_port_id_field), 1); memcpy((buf + 76), MANUFACTURER_ID, 48); return 124; case PTP_MM_GET_DEFAULT_DATA_SET: *(UInteger8 *) (buf + 55) = PTP_MM_DEFAULT_DATA_SET; *(Integer32 *) (buf + 56) = shift16(flip16(76), 1); *(Integer32 *) (buf + 60) = shift8(ptpClock->clock_communication_technology, 3); memcpy(buf + 64, ptpClock->clock_uuid_field, 6); *(Integer32 *) (buf + 72) = shift16(flip16(ptpClock->clock_port_id_field), 1); *(Integer32 *) (buf + 76) = shift8(ptpClock->clock_stratum, 3); memcpy(buf + 80, ptpClock->clock_identifier, 4); *(Integer32 *) (buf + 84) = shift16(flip16(ptpClock->clock_variance), 1); *(Integer32 *) (buf + 88) = shift8(ptpClock->clock_followup_capable, 3); *(Integer32 *) (buf + 92) = shift8(ptpClock->preferred, 3); *(Integer32 *) (buf + 96) = shift8(ptpClock->initializable, 3); *(Integer32 *) (buf + 100) = shift8(ptpClock->external_timing, 3); *(Integer32 *) (buf + 104) = shift8(ptpClock->is_boundary_clock, 3); *(Integer32 *) (buf + 108) = shift8(ptpClock->sync_interval, 3); memcpy(buf + 112, ptpClock->subdomain_name, 16); *(Integer32 *) (buf + 128) = shift16(flip16(ptpClock->number_ports), 1); *(Integer32 *) (buf + 132) = shift16(flip16(ptpClock->number_foreign_records), 1); return 136; case PTP_MM_GET_CURRENT_DATA_SET: *(UInteger8 *) (buf + 55) = PTP_MM_CURRENT_DATA_SET; *(Integer32 *) (buf + 56) = shift16(flip16(20), 1); *(Integer32 *) (buf + 60) = shift16(flip16(ptpClock->steps_removed), 1); fromInternalTime(&ptpClock->offset_from_master, &externalTime, 0); *(Integer32 *) (buf + 64) = flip32(externalTime.seconds); *(Integer32 *) (buf + 68) = flip32(externalTime.nanoseconds); fromInternalTime(&ptpClock->one_way_delay, &externalTime, 0); *(Integer32 *) (buf + 72) = flip32(externalTime.seconds); *(Integer32 *) (buf + 76) = flip32(externalTime.nanoseconds); return 80; case PTP_MM_GET_PARENT_DATA_SET: *(UInteger8 *) (buf + 55) = PTP_MM_PARENT_DATA_SET; *(Integer32 *) (buf + 56) = shift16(flip16(90), 1); *(Integer32 *) (buf + 60) = shift8(ptpClock->parent_communication_technology, 3); memcpy(buf + 64, ptpClock->parent_uuid, 6); *(Integer32 *) (buf + 72) = shift16(flip16(ptpClock->parent_port_id), 1); *(Integer32 *) (buf + 76) = shift16(flip16(ptpClock->parent_last_sync_sequence_number), 1); *(Integer32 *) (buf + 80) = shift8(ptpClock->parent_followup_capable, 1); *(Integer32 *) (buf + 84) = shift8(ptpClock->parent_external_timing, 3); *(Integer32 *) (buf + 88) = shift16(flip16(ptpClock->parent_variance), 1); *(Integer32 *) (buf + 92) = shift8(ptpClock->parent_stats, 3); *(Integer32 *) (buf + 96) = shift16(flip16(ptpClock->observed_variance), 1); *(Integer32 *) (buf + 100) = flip32(ptpClock->observed_drift); *(Integer32 *) (buf + 104) = shift8(ptpClock->utc_reasonable, 3); *(Integer32 *) (buf + 108) = shift8(ptpClock->grandmaster_communication_technology, 3); memcpy(buf + 112, ptpClock->grandmaster_uuid_field, 6); *(Integer32 *) (buf + 120) = shift16(flip16(ptpClock->grandmaster_port_id_field), 1); *(Integer32 *) (buf + 124) = shift8(ptpClock->grandmaster_stratum, 3); memcpy(buf + 128, ptpClock->grandmaster_identifier, 4); *(Integer32 *) (buf + 132) = shift16(flip16(ptpClock->grandmaster_variance), 1); *(Integer32 *) (buf + 136) = shift8(ptpClock->grandmaster_preferred, 3); *(Integer32 *) (buf + 140) = shift8(ptpClock->grandmaster_is_boundary_clock, 3); *(Integer32 *) (buf + 144) = shift16(flip16(ptpClock->grandmaster_sequence_number), 1); return 148; case PTP_MM_GET_PORT_DATA_SET: if (manage->targetPortId && manage->targetPortId != ptpClock->port_id_field) { *(UInteger8 *) (buf + 55) = PTP_MM_NULL; *(Integer32 *) (buf + 56) = shift16(flip16(0), 1); return 0; } *(UInteger8 *) (buf + 55) = PTP_MM_PORT_DATA_SET; *(Integer32 *) (buf + 56) = shift16(flip16(52), 1); *(Integer32 *) (buf + 60) = shift16(flip16(ptpClock->port_id_field), 1); *(Integer32 *) (buf + 64) = shift8(ptpClock->port_state, 3); *(Integer32 *) (buf + 68) = shift16(flip16(ptpClock->last_sync_event_sequence_number), 1); *(Integer32 *) (buf + 72) = shift16(flip16(ptpClock->last_general_event_sequence_number), 1); *(Integer32 *) (buf + 76) = shift8(ptpClock->port_communication_technology, 3); memcpy(buf + 80, ptpClock->port_uuid_field, 6); *(Integer32 *) (buf + 88) = shift16(flip16(ptpClock->port_id_field), 1); *(Integer32 *) (buf + 92) = shift8(ptpClock->burst_enabled, 3); *(Integer32 *) (buf + 96) = shift8(4, 1) | shift8(2, 2) | shift8(2, 3); memcpy(buf + 100, ptpClock->subdomain_address, 4); memcpy(buf + 106, ptpClock->event_port_address, 2); memcpy(buf + 110, ptpClock->general_port_address, 2); return 112; case PTP_MM_GET_GLOBAL_TIME_DATA_SET: *(UInteger8 *) (buf + 55) = PTP_MM_GLOBAL_TIME_DATA_SET; *(Integer32 *) (buf + 56) = shift16(flip16(24), 1); getTime(&internalTime); fromInternalTime(&internalTime, &externalTime, ptpClock->halfEpoch); *(Integer32 *) (buf + 60) = flip32(externalTime.seconds); *(Integer32 *) (buf + 64) = flip32(externalTime.nanoseconds); *(Integer32 *) (buf + 68) = shift16(flip16(ptpClock->current_utc_offset), 1); *(Integer32 *) (buf + 72) = shift8(ptpClock->leap_59, 3); *(Integer32 *) (buf + 76) = shift8(ptpClock->leap_61, 3); *(Integer32 *) (buf + 80) = shift16(flip16(ptpClock->epoch_number), 1); return 84; case PTP_MM_GET_FOREIGN_DATA_SET: if ((manage->targetPortId && manage->targetPortId != ptpClock->port_id_field) || !manage->recordKey || manage->recordKey > ptpClock->number_foreign_records) { *(UInteger8 *) (buf + 55) = PTP_MM_NULL; *(Integer32 *) (buf + 56) = shift16(flip16(0), 1); return 0; } *(UInteger8 *) (buf + 55) = PTP_MM_FOREIGN_DATA_SET; *(Integer32 *) (buf + 56) = shift16(flip16(28), 1); *(Integer32 *) (buf + 60) = shift16(flip16(ptpClock->port_id_field), 1); *(Integer32 *) (buf + 64) = shift16(flip16(manage->recordKey - 1), 1); *(Integer32 *) (buf + 68) = shift8(ptpClock->foreign[manage->recordKey - 1].foreign_master_communication_technology, 3); memcpy(buf + 72, ptpClock->foreign[manage->recordKey - 1].foreign_master_uuid, 6); *(Integer32 *) (buf + 80) = shift16(flip16(ptpClock->foreign[manage->recordKey - 1].foreign_master_port_id), 1); *(Integer32 *) (buf + 84) = shift16(flip16(ptpClock->foreign[manage->recordKey - 1].foreign_master_syncs), 1); return 88; default: return 0; } }
void messageOutputFunc(string from, int id, string msg, myTime_t interval) { // fast skip if((id!=DM_FATAL)&&(gDebugLevel<=0)) return; if(interval>0) { myTime_t currTime = getTime(); if((currTime - globalIntervalTime)>interval) { globalIntervalTime = getTime(); } else { return; } } // colors off? if( (globalColorSetting == -1) || // off for e.g. win32 ((globalColorSetting==1) && ((id==DM_FATAL)||( getenv("ELBEEM_NOCOLOROUT") )) ) ) { // only reset once col_std = col_black = col_dark_gray = col_bright_gray = col_red = col_bright_red = col_green = col_bright_green = col_bright_yellow = col_yellow = col_cyan = col_bright_cyan = col_purple = col_bright_purple = col_neutral = ""; globalColorSetting = 0; } std::ostringstream sout; if(id==DM_DIRECT) { sout << msg; } else { sout << col_cyan<< from; switch(id) { case DM_MSG: sout << col_std << " message:"; break; case DM_NOTIFY: sout << col_bright_cyan << " note:" << col_std; break; case DM_IMPORTANT: sout << col_yellow << " important:" << col_std; break; case DM_WARNING: sout << col_bright_red << " warning:" << col_std; break; case DM_ERROR: sout << col_red << " error:" << col_red; break; case DM_FATAL: sout << col_red << " fatal("<<gElbeemState<<"):" << col_red; break; case DM_NONE: // only internal debugging msgs break; default: // this shouldnt happen... sout << col_red << " --- messageOutputFunc error: invalid id ("<<id<<") --- aborting... \n\n" << col_std; break; } sout <<" "<< msg << col_std; } if(id==DM_FATAL) { strncpy(gElbeemErrorString,sout.str().c_str(), 256); // dont print? if(gDebugLevel==0) return; sout << "\n"; // add newline for output } // determine output - file==1/stdout==0 / globstr==2 char filen[256]; strcpy(filen,"debug_unini.txt"); int fileout = false; #if ELBEEM_MPI==1 std::ostringstream mpin; if(glob_mpindex>=0) { mpin << "elbeem_log_"<< glob_mpindex <<".txt"; } else { mpin << "elbeem_log_ini.txt"; } fileout = 1; strncpy(filen, mpin.str().c_str(),255); filen[255]='\0'; #else strncpy(filen, "elbeem_debug_log.txt",255); #endif #ifdef WIN32 // windows causes trouble with direct output fileout = 1; #endif // WIN32 #if PARALLEL==1 fileout = 2;// buffer out, switch off again... if(globOutstrForce) fileout=1; #endif if(getenv("ELBEEM_FORCESTDOUT")) { fileout = 0;// always direct out } //fprintf(stdout,"out deb %d, %d, '%s',l%d \n",globOutstrForce,fileout, filen, globOutstr.str().size() ); #if PARALLEL==1 #pragma omp critical #endif // PARALLEL==1 { if(fileout==1) { // debug level is >0 anyway, so write to file... FILE *logf = fopen(filen,"a+"); // dont complain anymore here... if(logf) { if(globOutstrForce) { fprintf(logf, "%s",globOutstr.str().c_str() ); globOutstr.str(""); // reset } fprintf(logf, "%s",sout.str().c_str() ); fclose(logf); } } else if(fileout==2) { globOutstr << sout.str(); } else { // normal stdout output fprintf(stdout, "%s",sout.str().c_str() ); if(id!=DM_DIRECT) fflush(stdout); } } // omp crit }
void PurchaseEditor::doPurchase() { if (!db.isOpen()) db.open(); if (!db.isOpen()) {return;} QStringList items; items.clear(); //temporal items list items.append("empty list"); //just a tweak for creating the transaction, cleaning after creating it. Azahar *myDb = new Azahar; myDb->setDatabase(db); qDebug()<<"doPurchase..."; qDebug()<<"DATE:"<<getDate().toString()<<getTime().toString(); TransactionInfo tInfo; if (getPurchased()) { tInfo.type = tBuy; } else { tInfo.type = tDonation; } tInfo.amount = getTotalBuy(); tInfo.date = getDate(); tInfo.time = getTime(); tInfo.paywith = 0.0; tInfo.changegiven = 0.0; tInfo.paymethod = pCash; tInfo.state = tCompleted; tInfo.userid = loggedUserId; tInfo.clientid= 0; tInfo.cardnumber = "-NA-"; tInfo.cardauthnum = "-NA-"; tInfo.itemcount = getItemCount(); tInfo.itemlist = items.join(";"); tInfo.utility = 0; //FIXME: utility is calculated until products are sold, not before. tInfo.terminalnum = 0; //NOTE: Not really a terminal... from admin computer. tInfo.providerid = 1; //FIXME! tInfo.specialOrders = ""; tInfo.balanceId = 0; tInfo.donor = getDonor(); tInfo.note= getNote(); qulonglong trnum = myDb->insertTransaction(tInfo); //to get the transaction number to insert in the log. if ( trnum <= 0 ) { qDebug()<<"ERROR: Could not create a Purchase Transaction ::doPurchase()"; qDebug()<<"Error:"<<myDb->lastError(); //TODO: Notify the user about the error. } //Now cleaning the items to fill with real items... items.clear(); //assigning new transaction id to the tInfo. tInfo.id = trnum; QHash<QString, ProductInfo> hash = getHash(); ProductInfo info; TransactionItemInfo tItemInfo; //Iterate the hash QHashIterator<QString, ProductInfo> i(hash); int j=-1; while (i.hasNext()) { j+=1; i.next(); info = i.value(); double oldstockqty = info.stockqty; info.stockqty = info.purchaseQty+oldstockqty; //Modify data on mysql... //validDiscount is for checking if product already exists on db. see line # 396 of purchaseeditor.cpp if (info.validDiscount) { if (!myDb->updateProduct(info, info.code)) qDebug()<<myDb->lastError(); else { //FIXME: loggedUserId, logging in widgets!? myDb->insertLog(loggedUserId, QDate::currentDate(), QTime::currentTime(), "[PURCHASE] "+i18n("Purchase #%4 - %1 x %2 (%3)", info.purchaseQty, info.desc, info.code, trnum)); qDebug()<<"Product updated [purchase] ok..."<<i18n("Purchase #%4 - %1 x %2 (%3)", info.purchaseQty, info.desc, info.code, trnum); } } else { if (!myDb->insertProduct(info)) qDebug()<<myDb->lastError(); else { myDb->insertLog(loggedUserId, QDate::currentDate(), QTime::currentTime(), "[PURCHASE] "+i18n("Purchase #%4 - [new] - %1 x %2 (%3)", info.purchaseQty, info.desc, info.code, trnum) ); qDebug()<<i18n("Purchase #%4 - [new] - %1 x %2 (%3)", info.purchaseQty, info.desc, info.code, trnum); } } ui->p->m_model->select(); items.append(info.code+"/"+QString::number(info.purchaseQty)); // Compiling transactionitems tItemInfo.transactionid = tInfo.id; tItemInfo.position = j; tItemInfo.productCode = i.key(); tItemInfo.unitStr = info.unitStr; tItemInfo.qty = info.purchaseQty; tItemInfo.cost = info.cost; tItemInfo.price = info.price; tItemInfo.disc = info.disc * info.purchaseQty; tItemInfo.total = info.cost * info.purchaseQty; tItemInfo.completePayment = true; if (info.isAGroup) tItemInfo.name = info.desc.replace("\n", "|"); else tItemInfo.name = info.desc; tItemInfo.isGroup = info.isAGroup; myDb->insertTransactionItem(tItemInfo); } //update items in transaction data tInfo.itemlist = items.join(";"); myDb->updateTransaction(tInfo); delete myDb; }
/*---------------------------------------------------------------*/ void engine::resetTime(){ start_time = getTime(); }
inline void ObjectWrapper::reset(boost::shared_ptr<Object> object) { object_ = object; dirty_ = false; updateTime_ = getTime(); notifyObservers(); }
/*---------------------------------------------------------------------------------*/ TimeUnit engine::elapsedTime(int scale){ TimeUnit t = getTime(); return ( t - start_time)/scale; }
// Must delete this pointer in parent class void LicensePlateCandidate::recognize() { charSegmenter = NULL; pipeline_data->plate_area_confidence = 0; pipeline_data->isMultiline = config->multiline; Rect expandedRegion = this->pipeline_data->regionOfInterest; pipeline_data->crop_gray = Mat(this->pipeline_data->grayImg, expandedRegion); resize(pipeline_data->crop_gray, pipeline_data->crop_gray, Size(config->templateWidthPx, config->templateHeightPx)); CharacterAnalysis textAnalysis(pipeline_data); if (textAnalysis.confidence > 10) { EdgeFinder edgeFinder(pipeline_data); pipeline_data->plate_corners = edgeFinder.findEdgeCorners(); if (edgeFinder.confidence > 0) { timespec startTime; getTime(&startTime); Mat originalCrop = pipeline_data->crop_gray; Transformation imgTransform(this->pipeline_data->grayImg, pipeline_data->crop_gray, expandedRegion); Size cropSize = imgTransform.getCropSize(pipeline_data->plate_corners, Size(pipeline_data->config->ocrImageWidthPx, pipeline_data->config->ocrImageHeightPx)); Mat transmtx = imgTransform.getTransformationMatrix(pipeline_data->plate_corners, cropSize); pipeline_data->crop_gray = imgTransform.crop(cropSize, transmtx); if (this->config->debugGeneral) displayImage(config, "quadrilateral", pipeline_data->crop_gray); // Apply a perspective transformation to the TextLine objects // to match the newly deskewed license plate crop vector<TextLine> newLines; for (unsigned int i = 0; i < pipeline_data->textLines.size(); i++) { vector<Point2f> textArea = imgTransform.transformSmallPointsToBigImage(pipeline_data->textLines[i].textArea); vector<Point2f> linePolygon = imgTransform.transformSmallPointsToBigImage(pipeline_data->textLines[i].linePolygon); vector<Point2f> textAreaRemapped; vector<Point2f> linePolygonRemapped; textAreaRemapped = imgTransform.remapSmallPointstoCrop(textArea, transmtx); linePolygonRemapped = imgTransform.remapSmallPointstoCrop(linePolygon, transmtx); newLines.push_back(TextLine(textAreaRemapped, linePolygonRemapped)); } pipeline_data->textLines.clear(); for (unsigned int i = 0; i < newLines.size(); i++) pipeline_data->textLines.push_back(newLines[i]); if (config->debugTiming) { timespec endTime; getTime(&endTime); cout << "deskew Time: " << diffclock(startTime, endTime) << "ms." << endl; } charSegmenter = new CharacterSegmenter(pipeline_data); pipeline_data->plate_area_confidence = 100; } } }
int main(int argc, char *argv[]) { if (argc != 7){ // Test for correct number of arguments DieWithUserMessage("Parameter(s)","<dstAddress> <dstPortNumber> <IterationDelay> <dataSize> <burstSize> <TestDuration>"); } char* server = argv[1]; // First arg: server address/name char *servPort = argv[2]; // Server port/service double iteration_delay = atof(argv[3]); // Iteration Delay in sending messages to Server int data_size = atoi(argv[4]); // Data size of packets int burst_size = atoi(argv[5]); // The number of packets to be sent back-to-back int test_duration = atoi(argv[6]); // Duration for which the client program will run char tmpLine[128]; //Store all the rtt, used for calculating STD double *allRtt=(double *)malloc(DEFAULT_ARRAY_LEN * sizeof(double)); if(allRtt == NULL){ DieWithSystemMessage("Alocate memorry failed!"); } // Store the loss rate per burst double *burstPac_dropRate = (double *)malloc(DEFAULT_ARRAY_LEN * sizeof(double)); if(burstPac_dropRate == NULL){ DieWithSystemMessage("Alocate memorry failed!"); } //Capture the send and receive times of the UDP packets, required for calculating RTTs double *udpSendTime = (double *)malloc(burst_size * sizeof(double)); double *udpReceiveTime = (double *)malloc(burst_size * sizeof(double)); //Array to indicate which UDP packets have been captured int *udpCapture = calloc(burst_size, sizeof(int)); unsigned int curLen = DEFAULT_ARRAY_LEN; //The current length of allRtt unsigned int curLen2 = DEFAULT_ARRAY_LEN; //The current length of burstPac_dropCount double rtt_min, rtt_max, rtt_avg; // variables for analyzing rtt statistics double rttMeanDev=0.0; // The mean deviation of rtt double start_time, end_time; // To measure the elapsed time of the experiment int burst_count = 0; // Number of burst sent int seq_number = 0; // Sequence numbers to be sent and received via UDP uint32_t packet_transmitted = 0; // Count of the packets transmitted uint32_t packet_received = 0; // Count of the packets received // Tell the system what kind(s) of address info we want struct addrinfo addrCriteria; // Criteria for address match memset(&addrCriteria, 0, sizeof(addrCriteria)); // Zero out structure addrCriteria.ai_family = AF_UNSPEC; // Any address family // For the following fields, a zero value means "don't care" addrCriteria.ai_socktype = SOCK_DGRAM; // Only datagram sockets addrCriteria.ai_protocol = IPPROTO_UDP; // Only UDP protocol // Get address(es) struct addrinfo *servAddr; // List of server addresses int rtnVal = getaddrinfo(server, servPort, &addrCriteria, &servAddr); if (rtnVal != 0) DieWithUserMessage("getaddrinfo() failed", gai_strerror(rtnVal)); // Create a datagram/UDP socket int sock = socket(servAddr->ai_family, servAddr->ai_socktype, servAddr->ai_protocol); // Socket descriptor for client if (sock < 0) DieWithSystemMessage("socket() failed"); struct sigaction sig; /* setup signals */ memset(&sig,0,sizeof(sig)); sig.sa_handler = signal_handler; sigaction (SIGINT, &sig, NULL); sigaction (SIGALRM, &sig, NULL); double time = 0.0; int counter = burst_size; // To keep track of packet lost per burst rtt_max = 0; rtt_min = TIMEOUT_SECS; rtt_avg = 0; start_time = getTime(); while(flag && (getTime() < test_duration + start_time)) { // While loop terminates when flag sets to zero if(flag==0) { break; } int k; for(k = 0; k < burst_size; k++) { //Insertion of sequence number in UDP packet in network byte order unsigned char* echoString = (unsigned char*)calloc(data_size,sizeof(char)); uint32_t translated_int = htonl(seq_number); memcpy(echoString, &translated_int, sizeof(uint32_t)); // Send the string to the server ssize_t numBytes = sendto(sock, echoString, data_size, 0, servAddr->ai_addr, servAddr->ai_addrlen); if (numBytes < 0) DieWithSystemMessage("sendto() failed"); else if (numBytes != data_size) DieWithUserMessage("sendto() error", "sent unexpected number of bytes"); udpSendTime[seq_number] = getTime(); seq_number++; packet_transmitted++; } alarm(TIMEOUT_SECS); for(k = 0; k < burst_size; k++) { // Receive a response struct sockaddr_storage fromAddr; // Source address of server // Set length of from address structure (in-out parameter) socklen_t fromAddrLen = sizeof(fromAddr); char *buffer = (char*)calloc(data_size,sizeof(char)); // I/O buffer ssize_t numBytes = recvfrom(sock, buffer, data_size, 0, (struct sockaddr *) &fromAddr, &fromAddrLen); if(numBytes > 0) { uint32_t trans_int, received_int; memcpy(&trans_int, buffer, sizeof trans_int); received_int = ntohl(trans_int); udpReceiveTime[received_int] = getTime(); udpCapture[received_int] = 1; } if(numBytes < 0) { if(alarmFlag == 0) { break; } } } alarm(0); for(k = 0; k < burst_size; k++) { if(udpCapture[k] == 1) { packet_received++; counter--; time = udpReceiveTime[k] - udpSendTime[k]; //No available memory to use to store in allRtt if(packet_received > curLen-1) { curLen += DEFAULT_ARRAY_LEN; allRtt=(double *)realloc(allRtt, curLen*sizeof(double)); if(allRtt == NULL) { DieWithSystemMessage("Allocate memorry failed!"); } } // Record each rtt allRtt[packet_received]= time; // Rtt Statistics if(rtt_max < time) rtt_max = time; if(rtt_min > time) rtt_min = time; rtt_avg += time; getCurTime(tmpLine); printf("%s %3.6f %u\n",tmpLine,time,k); } } memset(udpCapture, 0, burst_size * sizeof(int)); burst_count++; if(burst_count > curLen2 -1) { curLen2 += DEFAULT_ARRAY_LEN; burstPac_dropRate = (double *)realloc(burstPac_dropRate, curLen2*sizeof(double)); if(burstPac_dropRate == NULL) { DieWithSystemMessage("Allocate memory failed!"); } } //The packet drop count per burst burstPac_dropRate[burst_count] = ((double)counter/burst_size); printf("Burst of packet:Done!!!\n"); printf("%d%% burst loss rate\n",(int)(burstPac_dropRate[burst_count]*100)); // Resetting sequence number seq_number = 0; // Resetting the counter counter = burst_size; // Delay after sending a burst double burst_hold = iteration_delay*1000*1000; usleep(burst_hold); } // The total time elapsed end_time = getTime() - start_time; // The average RTT rtt_avg = rtt_avg/packet_received; // Standard deviation rttMeanDev=calMeanDev(allRtt, packet_received,rtt_avg); // Mean burst loss Rate double burstMeanLoss = calBurstLossRate(burstPac_dropRate,burst_count); //Display of the statistics printf("\n"); printf("--- %s ping statistics ---\n",server); printf("%u packets transmitted, %u packets received,", packet_transmitted, packet_received); printf("%d%% packet loss, time %f ms \n",(int)(((float)(packet_transmitted-packet_received)/packet_transmitted)*100), end_time*1000); printf("rtt min/avg/max/mdev = %3.6f/%3.6f/%3.6f/%3.6f ms\n",rtt_min*1000,rtt_avg*1000,rtt_max*1000,rttMeanDev*1000); printf("%d burst size, %d%% overall burst loss rate\n", burst_size, (int)(burstMeanLoss*100)); freeaddrinfo(servAddr); close(sock); exit(0); }
/** Is called by check structures if a kart starts a new lap. * \param kart_index Index of the kart. */ void LinearWorld::newLap(unsigned int kart_index) { KartInfo &kart_info = m_kart_info[kart_index]; AbstractKart *kart = m_karts[kart_index]; // Only update the kart controller if a kart that has already finished // the race crosses the start line again. This avoids 'fastest lap' // messages if the end controller does a fastest lap, but especially // allows the end controller to switch end cameras if(kart->hasFinishedRace()) { kart->getController()->newLap(kart_info.m_race_lap); return; } const int lap_count = race_manager->getNumLaps(); // Only increase the lap counter and set the new time if the // kart hasn't already finished the race (otherwise the race_gui // will begin another countdown). if(kart_info.m_race_lap+1 <= lap_count) { assert(kart->getWorldKartId()==kart_index); kart_info.m_time_at_last_lap=getTime(); kart_info.m_race_lap++; m_kart_info[kart_index].m_overall_distance = m_kart_info[kart_index].m_race_lap * m_track->getTrackLength() + getDistanceDownTrackForKart(kart->getWorldKartId()); } // Last lap message (kart_index's assert in previous block already) if (raceHasLaps() && kart_info.m_race_lap+1 == lap_count) { m_race_gui->addMessage(_("Final lap!"), kart, 3.0f, video::SColor(255, 210, 100, 50), true); if(!m_last_lap_sfx_played && lap_count > 1) { if (UserConfigParams::m_music) { m_last_lap_sfx->play(); m_last_lap_sfx_played = true; m_last_lap_sfx_playing = true; // In case that no music is defined if(music_manager->getCurrentMusic() && music_manager->getMasterMusicVolume() > 0.2f) { music_manager->getCurrentMusic()->setTemporaryVolume(0.2f); } } else { m_last_lap_sfx_played = true; m_last_lap_sfx_playing = false; } } } else if (raceHasLaps() && kart_info.m_race_lap > 0 && kart_info.m_race_lap+1 < lap_count) { m_race_gui->addMessage(_("Lap %i", kart_info.m_race_lap+1), kart, 3.0f, video::SColor(255, 210, 100, 50), true); } // The race positions must be updated here: consider the situation where // the first kart does not cross the finish line in its last lap, instead // it passes it, the kart reverses and crosses the finishing line // backwards. Just before crossing the finishing line the kart will be on // the last lap, but with a distance along the track close to zero. // Therefore its position will be wrong. If the race position gets updated // after increasing the number of laps (but before tagging the kart to have // finished the race) the position will be correct (since the kart now // has one additional lap it will be ahead of the other karts). // Without this call the incorrect position for this kart would remain // (since a kart that has finished the race does not get its position // changed anymore), potentially resulting in a duplicated race position // (since the first kart does not have position 1, no other kart can get // position 1, so one rank will be duplicated). // Similarly the situation can happen if the distance along track should // go back to zero before actually crossing the finishing line. While this // should not happen, it could potentially be caused by floating point // errors. In this case the call to updateRacePosition will avoid // duplicated race positions as well. updateRacePosition(); // Race finished if(kart_info.m_race_lap >= race_manager->getNumLaps() && raceHasLaps()) { kart->finishedRace(getTime()); } float time_per_lap; if (kart_info.m_race_lap == 1) // just completed first lap { time_per_lap=getTime(); } else //completing subsequent laps { time_per_lap=getTime() - kart_info.m_lap_start_time; } // if new fastest lap if(time_per_lap < m_fastest_lap && raceHasLaps() && kart_info.m_race_lap>0) { m_fastest_lap = time_per_lap; std::string s = StringUtils::timeToString(time_per_lap); irr::core::stringw m_fastest_lap_message; //I18N: as in "fastest lap: 60 seconds by Wilber" m_fastest_lap_message += _C("fastest_lap", "%s by %s", s.c_str(), core::stringw(kart->getName())); m_race_gui->addMessage(m_fastest_lap_message, NULL, 3.0f, video::SColor(255, 255, 255, 255), false); m_race_gui->addMessage(_("New fastest lap"), NULL, 3.0f, video::SColor(255, 255, 255, 255), false); } // end if new fastest lap kart_info.m_lap_start_time = getTime(); kart->getController()->newLap(kart_info.m_race_lap); } // newLap
// LEARNING FUNCTION: add new patterns and run optimization steps selected with adaptative schedule virtual int add (int x_id, int yi) { ++nb_seen_examples; // create a new output object if this one has never been seen before if (!getOutput (yi)) { outputs.insert (std::make_pair (yi, LaRankOutput ())); LaRankOutput *cur = getOutput (yi); cur->initialize (kfunc, cache); if (outputs.size () == 1) y0 = outputs.begin ()->first; // link the cache of this new output to a buddy if (outputs.size () > 1) { LaRankOutput *out0 = getOutput (y0); cur->set_kernel_buddy (out0->getKernel ()); } } LaRankPattern tpattern (x_id, yi); LaRankPattern & pattern = (patterns.isPattern (x_id)) ? patterns.getPattern (x_id) : tpattern; // ProcessNew with the "fresh" pattern double time1 = getTime (); process_return_t pro_ret = process (pattern, processNew); double dual_increase = pro_ret.dual_increase; double duration = (getTime () - time1); double coeff = dual_increase / (0.00001 + duration); dual += dual_increase; n_pro++; w_pro = 0.05 * coeff + (1 - 0.05) * w_pro; // ProcessOld & Optimize until ready for a new processnew // (Adaptative schedule here) for (;;) { double w_sum = w_pro + w_rep + w_opt; double prop_min = w_sum / 20; if (w_pro < prop_min) w_pro = prop_min; if (w_rep < prop_min) w_rep = prop_min; if (w_opt < prop_min) w_opt = prop_min; w_sum = w_pro + w_rep + w_opt; double r = rand () / (double) RAND_MAX * w_sum; if (r <= w_pro) { break; } else if ((r > w_pro) && (r <= w_pro + w_rep)) // ProcessOld here { double time1 = getTime (); double dual_increase = reprocess (); double duration = (getTime () - time1); double coeff = dual_increase / (0.00001 + duration); dual += dual_increase; n_rep++; w_rep = 0.05 * coeff + (1 - 0.05) * w_rep; } else // Optimize here { double time1 = getTime (); double dual_increase = optimize (); double duration = (getTime () - time1); double coeff = dual_increase / (0.00001 + duration); dual += dual_increase; n_opt++; w_opt = 0.05 * coeff + (1 - 0.05) * w_opt; } } if (nb_seen_examples % 100 == 0) // Cleanup useless Support Vectors/Patterns sometimes nb_removed += cleanup (); return pro_ret.ypred; }
//----------------------------------------------------------------------------- void LinearWorld::getKartsDisplayInfo( std::vector<RaceGUIBase::KartIconDisplayInfo> *info) { int laps_of_leader = -1; float time_of_leader = -1; // Find the best time for the lap. We can't simply use // the time of the kart at position 1, since the kart // might have been overtaken by now const unsigned int kart_amount = getNumKarts(); for(unsigned int i = 0; i < kart_amount ; i++) { RaceGUIBase::KartIconDisplayInfo& rank_info = (*info)[i]; AbstractKart* kart = m_karts[i]; // reset color rank_info.m_color = video::SColor(255, 255, 255, 255); rank_info.lap = -1; if(kart->isEliminated()) continue; const float lap_time = getTimeAtLapForKart(kart->getWorldKartId()); const int current_lap = getLapForKart( kart->getWorldKartId() ); rank_info.lap = current_lap; if(current_lap > laps_of_leader) { // more laps than current leader --> new leader and // new time computation laps_of_leader = current_lap; time_of_leader = lap_time; } else if(current_lap == laps_of_leader) { // Same number of laps as leader: use fastest time time_of_leader=std::min(time_of_leader,lap_time); } } // we now know the best time of the lap. fill the remaining bits of info for(unsigned int i = 0; i < kart_amount ; i++) { RaceGUIBase::KartIconDisplayInfo& rank_info = (*info)[i]; KartInfo& kart_info = m_kart_info[i]; AbstractKart* kart = m_karts[i]; const int position = kart->getPosition(); // Don't compare times when crossing the start line first if(laps_of_leader>0 && (getTime() - getTimeAtLapForKart(kart->getWorldKartId())<5.0f || rank_info.lap != laps_of_leader) && raceHasLaps()) { // Display for 5 seconds std::string str; if(position == 1) { str = " " + StringUtils::timeToString( getTimeAtLapForKart(kart->getWorldKartId()) ); } else { float timeBehind; timeBehind = (kart_info.m_race_lap==laps_of_leader ? getTimeAtLapForKart(kart->getWorldKartId()) : getTime()) - time_of_leader; str = "+" + StringUtils::timeToString(timeBehind); } rank_info.m_text = irr::core::stringw(str.c_str()); } else { rank_info.m_text = ""; } int numLaps = race_manager->getNumLaps(); if(kart_info.m_race_lap>=numLaps) { // kart is finished, display in green rank_info.m_color.setGreen(0); rank_info.m_color.setBlue(0); } else if(kart_info.m_race_lap>=0 && numLaps>1) { int col = (int)(255*(1.0f-(float)kart_info.m_race_lap /((float)numLaps-1.0f) )); rank_info.m_color.setBlue(col); rank_info.m_color.setGreen(col); } } // next kart } // getKartsDisplayInfo
void Interface::innerNormalPhase () { Real oldnormc = normc; Int fail = 0; Int oldAcnt = 0; while ( (normc > rho) && (nRest <= maxrest) && (NormalFlag == 0) && (current_time < max_time) ) { #ifdef VERBOSE if (verbosity_level > 1) { std::cout << "Going to innerNormalStep: nRest " << nRest << std::endl << std::endl << "|c| = " << normc << std::endl << "rho = " << rho << std::endl << std::endl; if ( (nvar < 10) && (ncon < 10) ) { std::cout << "A = " << std::endl; full(*J).print_more (); std::cout << "xc = " << std::endl; xc->print_more (); } } GDBSTOP (); #endif nRest++; call_ccfsg_xc(dciTrue, dciFalse); cholesky(); infeasible_gradient = 1.0; innerNormalDirection(infeasible_gradient); #ifdef ITER_MATLAB iter_file << "X(:,size(X,2)+1) = [" << xcx[0] << ";" << xcx[1] << "];" << std::endl; #endif #ifdef VERBOSE if (verbosity_level > 1) { std::cout << "After innerNormalStep" << std::endl; std::cout << "|c| = " << normc << std::endl; std::cout << "rho = " << rho << std::endl; if ( (nvar < 10) && (ncon < 10) ) { std::cout << "xc = " << std::endl; xc->print_more(); } } #endif #ifndef NDEBUG checkInfactibility(); #endif gavail = dciFalse; if (normc > phi2*oldnormc) { fail = fail + 1; } else fail = 0; if (fail >= nfailv) { #ifdef VERBOSE if (verbosity_level > 1) { std::cout << "Going to Safe Guard " << std::endl << std::endl; if ( (nvar < 10) && (ncon < 10) ) { std::cout << "A = " << std::endl; full(*J).print_more (); } GDBSTOP (); } #endif if (normc > 0 && infeasible_gradient/normc < infeasibility_tol) NormalFlag = 2; if (use_normal_safe_guard && NormalFlag == 0) { Vector ssoc(*env, nvar + nconI); Real asoc; call_ccfsg_xc(dciTrue, dciTrue); cholesky(); StepFlag = naStep (*c, ssoc); scale_xc (ssoc); // Arrumar tamanho do ssoc a partir do x Real alphassoc = 1; pReal ssocx = ssoc.get_doublex(); for (Int i = 0; i < nvar+nconI; i++) { Real xi = xcx[i], bli = l_bndx[i], bui = u_bndx[i], di = ssocx[i]; if (di == 0) continue; if (di < 0) { Real val = (bli - xi)*(1 - epsmu)/di; alphassoc = Min (alphassoc, val); } else { Real val = (bui - xi)*(1 - epsmu)/di; alphassoc = Min (alphassoc, val); } } if (alphassoc < 1) ssoc.scale (alphassoc); asoc = ssoc.norm (0); if (asoc > DeltaV) xc->saxpy(ssoc, DeltaV/asoc); else xc->saxpy(ssoc, 1.0); call_fn (); normc = c->norm (); } fail = 0; if (normal_fail_reboot && normc > rho && NormalFlag == 0) { // Has failed but is not infeasible Real constr[ncon], funval; (*cfn) (&cuter_status, &nvar, &ncon, xcx, &funval, constr); Int numI = nvar; for (Int i = 0; i < ncon; i++) { if (equatn[i] == dciFalse) { if (constr[i] > clx[i] && constr[i] < cux[i]) xcx[numI] = constr[i]/constraint_scaling[i]; numI++; } } normc = c->norm(); } } else if ( ( (normc > thetaR*oldnormc) && (oldAcnt > 0) ) || (oldAcnt > 5) ) { // Failed. Recompute A if (!is_linear) { call_ccfsg_xc (dciTrue, dciFalse); //CuterJacob } Aavail = dciTrue; oldAcnt = 0; if (!is_linear) { this->cholesky (); } } else { oldAcnt++; Aavail = dciFalse; } oldnormc = normc; DeltaV = Max (DeltaV, DeltaMin); current_time = getTime() - start_time; } //Fim do While }
static ssize_t netRecv(octet_t *buf, TimeInternal *time, BufQueue *msgQueue) { int i; int j; u16_t length; struct pbuf *p; struct pbuf *pcopy; /* Get the next buffer from the queue. */ if ((p = (struct pbuf*) netQGet(msgQueue)) == NULL) { return 0; } /* Verify that we have enough space to store the contents. */ if (p->tot_len > PACKET_SIZE) { ERROR("netRecv: received truncated message\n"); pbuf_free(p); return 0; } /* Verify there is contents to copy. */ if (p->tot_len == 0) { ERROR("netRecv: received empty packet\n"); pbuf_free(p); return 0; } if (time != NULL) { #if LWIP_PTP time->seconds = p->time_sec; time->nanoseconds = p->time_nsec; #else getTime(time); #endif } /* Get the length of the buffer to copy. */ length = p->tot_len; /* Copy the pbuf payload into the buffer. */ pcopy = p; j = 0; for (i = 0; i < length; i++) { // Copy the next byte in the payload. buf[i] = ((u8_t *)pcopy->payload)[j++]; // Skip to the next buffer in the payload? if (j == pcopy->len) { // Move to the next buffer. pcopy = pcopy->next; j = 0; } } /* Free up the pbuf (chain). */ pbuf_free(p); return length; }
Int Interface::innerNormalDirection (Real & infeasible_gradient) { Real oldnormc = c->norm(); Vector d(*env), dcp(*env), dn(*env); Real ndn; Real alpha, Ared, Pred; Real one[2] = {1,0}; Real zero[2] = {0,0}; Int iout, naflag; Bool dnavail; Vector gtmp (*env); Vector xtmp (*xc), ctmp (*c), stmp (*env); Real normgtmp = 0; Aavail = dciFalse; Real scalingMatrix[nvar + nconI]; gtmp.sdmult (*J, 1, one, zero, ctmp); // g = J'*c pReal gtmpx = gtmp.get_doublex(); for (Int i = 0; i < nvar+nconI; i++) { Real gi = gtmpx[i], zi = xcx[i], ui = u_bndx[i], li = l_bndx[i]; if ( (gi < 0) && (ui < dciInf) ) { scalingMatrix[i] = 1.0/sqrt(ui - zi); } else if ( (gi > 0) && (li > -dciInf) ) { scalingMatrix[i] = 1.0/sqrt(zi - li); } else { scalingMatrix[i] = 1; } } normgtmp = gtmp.norm (); Vector gtmp_proj(*env); gtmp_proj.scale(gtmp, -1.0); projectBounds_xc(gtmp_proj); infeasible_gradient = gtmp_proj.norm(); // DeltaV = normgtmp; if (normgtmp < dciTiny) { normc = oldnormc; iout = 6; // std::cout << "iout = 6" << std::endl; return iout; } //Now with the infinity norm Real lower[nvar + nconI], upper[nvar + nconI]; for (Int i = 0; i < nvar+nconI; i++) { Real zi = xcx[i], li = l_bndx[i], ui = u_bndx[i]; lower[i] = Max( -DeltaV, (li > -dciInf ? (li - zi) * (1 - epsmu) : -dciInf) ); upper[i] = Min( DeltaV, (ui < dciInf ? (ui - zi) * (1 - epsmu) : dciInf) ); } Vector aux(*env); d = gtmp; pReal dx = 0; gtmpx = gtmp.get_doublex(); dx = d.get_doublex(); for (Int i = 0; i < nvar + nconI; i++) { gtmpx[i] /= scalingMatrix[i]; dx[i] = -dx[i]/pow(scalingMatrix[i], 2); } aux.sdmult(*J, 0, one, zero, d); alpha = Min(gtmp.dot(gtmp)/aux.dot(aux), DeltaV/gtmp.norm()); dcp.scale (d, alpha); pReal dcpx = dcp.get_doublex(); // alpha = -d.dot(gtmp)/aux.dot(aux); // alpha = Min(alpha, DeltaV/d.norm()); alpha = 1.0; for (int i = 0; i < nvar + nconI; i++) { Real di = dcpx[i], ui = upper[i], li = lower[i]; if (di > dciEps) { alpha = Min(alpha, ui/(di)); } else if (di < -dciEps) { alpha = Min(alpha, li/(di)); } else dcpx[i] = 0; } Real theta = 0.99995; if (alpha < 1) { alpha = Max(theta, 1 - dcp.norm())*alpha; dcp.scale(alpha); } /* for (Int i = 0; i < nvar + nconI; i++) * dcpx[i] *= scalingMatrix[i]; */ dnavail = dciFalse; ndn = 0; Ared = 0; Pred = 1; // DeltaV = DeltaV/kappa2; iout = 0; // For the inequalities pReal dnx = 0; dnavail = dciFalse; if (!dnavail) { naflag = naStep (*c, dn); dnavail = dciTrue; dnx = dn.get_doublex(); //Project this step alpha = 1.0; for (Int i = 0; i < nvar + nconI; i++) { Real di = dnx[i], ui = upper[i], li = lower[i]; if (di > dciEps) { alpha = Min(alpha, ui/di); } else if (di < -dciEps) { alpha = Min(alpha, li/di); } else di = 0; } if (alpha < 1) { alpha = Max(theta, 1 - dn.norm())*alpha; dn.scale(alpha); } if (naflag > 1) ndn = 0; else ndn = dn.norm (0); assert(ndn <= DeltaV || "ndn > DeltaV"); } /* ||a + b||^2 = <a+b,a+b> = <a,a> + 2*<a,b> + <b,b> */ /* m(d) = 0.5*||J*d + h||^2 * dtr = t*dn + (1 - t)*dcp * m(dtr) = 0.5*||J*(t*dn + (1-t)*dcp) + h||^2 * = 0.5*||J*dcp + h + t*J*(dn - dcp)||^2 * = 0.5*||J*dcp + h||^2 + t*(J*dcp + h)'*J*(dn - dcp) + 0.5*t^2*||J*(dn - dcp)||^2 */ Vector Adcph(*c), difdcdn(dn), Adif(*env); Adcph.sdmult(*J, 0, one, one, dcp); difdcdn.saxpy(dcp, -1); Adif.sdmult(*J, 0, one, zero, difdcdn); Real objValAdcph = 0.5*Adcph.dot(Adcph); Real dotAdcphAdif = Adcph.dot(Adif); Real halfSqrNormAdif = 0.5*Adif.dot(Adif); Real cauchyReduction = 0.5*oldnormc*oldnormc - objValAdcph; Real newtonReduction = cauchyReduction - dotAdcphAdif - halfSqrNormAdif; Real factor = 1.0; while (newtonReduction/cauchyReduction < beta1) { // Line search among from newton to cauchy factor *= 0.9; newtonReduction = cauchyReduction - factor*dotAdcphAdif - pow(factor,2)*halfSqrNormAdif; if (factor < 1e-8) { factor = 0; break; } } Vector xtemp(*xc); for (Int i = 0; i < nvar+nconI; i++) { if (l_bndx[i] - u_bndx[i] > -dciEps) continue; xcx[i] += (factor*dnx[i] + (1 - factor)*dcpx[i]); if (xcx[i] >= u_bndx[i]) xcx[i] = u_bndx[i] - dciEps; else if (xcx[i] <= l_bndx[i]) xcx[i] = l_bndx[i] + dciEps; } #ifndef NDEBUG checkInfactibility(); #endif call_ccfsg_xc(dciFalse); normc = c->norm (); Ared = 0.5*(oldnormc*oldnormc - normc*normc); Pred = newtonReduction; if (Ared/Pred < beta2) { DeltaV /= 4; *xc = xtmp; call_ccfsg_xc(dciFalse); normc = c->norm(); } else if (Ared/Pred > 0.75) { DeltaV *= 2; } if (normc < rho) return 0; current_time = getTime() - start_time; return 0; }
int EventLoop::processEvents(int flags){ /* Nothing to do? return ASAP */ if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS)) { return 0; } int processed = 0; /* Note that we want call select() even if there are no * file events to process as long as we want to process time * events, in order to sleep until the next time event is ready * to fire. */ if (this->maxfd != -1 || ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) { TimeEvent *shortest = NULL; struct timeval tv; struct timeval* tvp = NULL; if (flags & AE_TIME_EVENTS && !(flags & AE_DONT_WAIT)) shortest = this->searchNearestTimer(); if (shortest) { long now_sec, now_ms; /* Calculate the time missing for the nearest * timer to fire. */ getTime(&now_sec, &now_ms); tvp = &tv; tvp->tv_sec = shortest->when_sec - now_sec; if (shortest->when_ms < now_ms) { tvp->tv_usec = ((shortest->when_ms+1000) - now_ms)*1000; tvp->tv_sec --; } else { tvp->tv_usec = (shortest->when_ms - now_ms)*1000; } if (tvp->tv_sec < 0) tvp->tv_sec = 0; if (tvp->tv_usec < 0) tvp->tv_usec = 0; } else { /* If we have to check for events but need to return * ASAP because of AE_DONT_WAIT we need to set the timeout * to zero */ if (flags & AE_DONT_WAIT) { tv.tv_sec = tv.tv_usec = 0; tvp = &tv; } else { /* Otherwise we can block */ tvp = NULL; /* wait forever */ } } FileEventVector_t& events = this->poll->getFileEvents(); FiredEventVector_t& fired = this->poll->getFiredEvents(); int numevents = this->poll->poll(tvp,this->maxfd); for (int j = 0; j < numevents; j ++) { FileEvent *fe = events[fired[j].fd]; int mask = fired[j].mask; int fd = fired[j].fd; int rfired = 0; /* note the fe->mask & mask & ... code: maybe an already processed * event removed an element that fired and we still didn't * processed, so we check if the event is still valid. */ if (fe->mask & mask & AE_READABLE) { rfired = 1; fe->onRead(this,fd,mask); } if (fe->mask & mask & AE_WRITABLE) { if (!rfired || !fe->isSameForIO()){ fe->OnWrite(this,fd,mask); } } processed ++; } } /* Check time events */ if (flags & AE_TIME_EVENTS){ processed += this->processTimeEvents(); } return processed; /* return the number of processed file/time events */ }
int main(int argc, char *argv[]) { QApplication a(argc, argv); // No CLI arguments if (argc == 1) { try{ MainWindow w; w.show(); return a.exec(); } catch(std::out_of_range e) { std::cout<<"Out-of-range: "<<e.what()<<std::endl; } catch(const char e[]) { qDebug() << "EXCEPTION: "<<e; } catch(QString e) { qDebug() << "EXCEPTION: "<<e; } return -1; } // COMMAND-LINE INTERFACE // Common variables QString imagePath(QDir::currentPath()), featureName, indexer("Sequential indexer"), trainingSet("training_set.txt"), params, queryImage; QStringList optimizeVars; int useIndex(-1); int verbosityLevel(0); QStringList qargv = a.arguments(); // Shortcut for argv as QStringList // Arguments parser for (int i(1); i<argc; i++) { if (qargv[i] == "-help") { usage(); return 0; } else if (qargv[i] == "-path") { if (i+1 == argc) { std::cerr << "Error: -path requires an argument: path to images\n\n"; usage(); return -1; } imagePath = qargv[i+1]; i++; //std::cerr << "Path " << imagePath.constData()-> << "\n\n"; //qDebug() << "Path" << imagePath; } else if (qargv[i] == "-feature") { if (i+1 == argc) { std::cerr << "Error: -feature requires an argument: name of feature\n\n"; usage(); return -1; } featureName = qargv[i+1]; i++; //qDebug() << "Ft" << featureName; } else if (qargv[i] == "-indexer") { if (i+1 == argc) { std::cerr << "Error: -indexer requires an argument: name of indexer\n\n"; usage(); return -1; } indexer = qargv[i+1]; i++; } else if (qargv[i] == "-optimize") { if (i+1 == argc) { std::cerr << "Error: -optimize requires an argument: comma separated list of variables to optimize\n\n"; usage(); return -1; } optimizeVars = qargv[i+1].split(','); i++; //qDebug() << "Optimize" << optimizeVars; } else if (qargv[i] == "-trainingset") { if (i+1 == argc) { std::cerr << "Error: -trainingset requires an argument: filename of list of files for optimizer training\n\n"; usage(); return -1; } trainingSet = qargv[i+1]; i++; } else if (qargv[i] == "-reuseindex") { int idx(0); // Check if second parameter is index number if (i+1 < argc) { bool ok; idx = qargv[i+1].toInt(&ok); if (!ok) idx=0; else i++; } useIndex = idx; } else if (qargv[i] == "-params") { if (i+1 == argc) { std::cerr << "Error: -params requires an argument: semicolon separated list of params\n\n"; usage(); return -1; } params = qargv[i+1]; i++; } else if (qargv[i] == "-query") { if (i+1 == argc) { std::cerr << "Error: -query requires an argument: path to query image\n\n"; usage(); return -1; } queryImage = qargv[i+1]; i++; } else if (qargv[i] == "-verbose") { verbosityLevel++; // TODO: add more levels } else { std::cerr << "Error: argument not recognized: "<<argv[i]<<"\n\n"; usage(); return -1; } } // No feature name given - nothing to do if (useIndex == -1 && featureName.isEmpty()) { std::cerr << "Error: you must specify -featurename with that option\n\n"; usage(); return -1; } // Start work Indexer* idx; ImageFeatures* feature; try { if (useIndex == -1) { feature = ImageFeatures::factory(featureName); if (!params.isEmpty()) { // Check for invalid params try { feature->setParams(params); } catch (QString s) { qDebug() << s; return -1; } catch (const char e[]) { std::cerr << e << std::endl; return -1; } } idx = Indexer::factory(indexer, feature, imagePath); if (verbosityLevel>0) std::cerr << "Building first index...\n"; double t1 = getTime(); idx->buildIndex(); double t2 = getTime(); if (verbosityLevel>0) std::cerr << "Indexing time: " << t2 << " ms\n"; } else { idx = Indexer::createIndex(imagePath, useIndex); feature = idx->getAlgorithm(); } // Query a single image if (!queryImage.isEmpty()) { QVector<Indexer::Result> results = idx->search(queryImage); for (int i(0); i<results.size(); i++) std::cout << results[i].fileName.toAscii().data() << " " << results[i].distance << std::endl; return 0; } PRTest prtest(imagePath, feature, idx); if (!prtest.loadCategories()) { std::cerr << "Error: failed to load categories.\nDo you have a file named categories.txt in work path?\n"; return -2; } // If not optimize, do a simple PR test if (optimizeVars.isEmpty()) { if (verbosityLevel>0) std::cerr << "Starting PRtest...\n"; double t1 = getTime(); prtest.execute(); double t2 = getTime(); std::cout << "MAP = "<<prtest.MAP << " AP16 = "<<prtest.AP16<<" AWP16 = "<<prtest.AWP16<<" ANMRR = "<<prtest.ANMRR<<std::endl; if (verbosityLevel>0) std::cerr << "PRtest time: " << t2 << " ms\n"; } // Do optimize run else { // TODO: use signals-slots to read values from PRtest class and output while using verbosity level etc. prtest.optimize(optimizeVars, trainingSet); } } catch(std::out_of_range e) { std::cout<<"Out-of-range: "<<e.what()<<std::endl; } catch(const char e[]) { qDebug() << "EXCEPTION: "<<e; } catch(QString e) { qDebug() << "EXCEPTION: "<<e; } return 0; }
void start_time() { startSecs = getTime(); return; }
void Robot::keepGoal() { int v_level = 0; abort = false; bool rotating=false; bool kmt_abort = false; cv::Point2f ballVelocity,ballPosition; bool vt_ballLocated; cv::Point2f keeper_center = ownGoal_coord + ownGoal_frontDir*KEEPER_DIST2GOAL; cv::Point2f keeper_dir(ownGoal_frontDir.y,-ownGoal_frontDir.x); moveTo(keeper_center,30); rotateTo(keeper_dir); void *kmt_params[6]; float targetDist = BOT_CENTER2CAM_CENTER; float moveDist = 0; kmt_params[0] = &targetDist; kmt_params[1] = &moveDist; kmt_params[2] = &v_level; kmt_params[3] = this; kmt_params[4] = &kmt_abort; kmt_params[5] = &rotating; pthread_t km_thread; pthread_create(&km_thread,NULL,&keeperMotionThread,(void*)kmt_params); usleep(1000); while(!kmt_abort) { if(v_level==0 && !rotating) { adjustWorldCoordinate(image_r,1); } float temp_dist = moveDist; cv::Point2f shift = temp_dist*cv::Point2f(ownGoal_frontDir.y,-ownGoal_frontDir.x); x = keeper_center.x+shift.x; y = keeper_center.y+shift.y; float temp_v_level = v_level; cv::Point2f robot_velocity(temp_v_level*DELTA_V*sin(ori),temp_v_level*DELTA_V*cos(ori)); updateBallStatus(); updateRadar(); if(!ballLocated) { continue; } if(length(ball_velocity)<MIN_BALL_SPEED_TO_KEEP || ball_velocity.dot(ownGoal_frontDir)/length(ball_velocity)>-0.1) { //targetDist = 0; continue; } float ball2goal_time = getTime(ball_coord,ball_velocity,ownGoal_coord,keeper_dir); float ball2keepline_time = getTime(ball_coord,ball_velocity,keeper_center,keeper_dir); cv::Point2f goalPoint = ball_coord + ball2goal_time*ball_velocity; cv::Point2f moveToPoint = ball_coord + ball2keepline_time*ball_velocity; if(ball2keepline_time<0 || length(goalPoint-ownGoal_coord)>ownGoal_width/2+GOAL_WIDTH_DELTA) { //targetDist = 0; continue; } shootRoute.clear(); shootRoute.push_back(cv::Point(x,y)); shootRoute.push_back(moveToPoint); targetDist = (moveToPoint - keeper_center).dot(keeper_dir)+BOT_CENTER2CAM_CENTER; } }
int initRegistrar() { struct sockaddr *addrs; struct sockaddr *addr; struct sockaddr_in6 *pin6; struct sockaddr_in *pin4; char *offset; char addrBuf[INET6_ADDRSTRLEN + 1]; struct timeval now; unsigned int seed; int addrCnt = 0; int i; logDebug("initializing own registrar"); /* init own id */ if (ownId == 0) { getTime(&now); seed = now.tv_sec | now.tv_usec; srand(seed); ownId = (uint32) rand(); logDebug("server id is: 0x%08x", ownId); } this = registrarServerNew(ownId); registrarServerListAddServer(this); this->rsEnrpPort = enrpLocalPort; this->rsAsapPort = asapLocalPort; /* don't need a timeout timer for us */ timerStop(this->rsLastHeardTimeout); timerDelete(this->rsLastHeardTimeout); this->rsLastHeardTimeout = NULL; this->rsLastHeardTimeoutCnt = 0; /* parse enrp sctp addrs */ if ((addrCnt = sctp_getladdrs(enrpSctpFd, 0, &addrs)) > 0) { offset = (char *) addrs; logDebug("enrp sctp: we are locally bound to %d adresses", addrCnt); for (i = 0; i < addrCnt && i < MAX_ADDR_CNT; i++) { addr = (struct sockaddr *) offset; pin4 = (struct sockaddr_in *) offset; pin6 = (struct sockaddr_in6 *) offset; if (addr->sa_family == AF_INET) { if (!useLoopback && pin4->sin_addr.s_addr == INADDR_LOOPBACK) continue; this->rsEnrpAddr[i].type = AF_INET; memcpy(&this->rsEnrpAddr[i].addr.in4, &pin4->sin_addr, sizeof(struct in_addr)); logDebug("addrs[%d]: AF_INET %s", i, inet_ntop(AF_INET, (void *) &pin4->sin_addr, addrBuf, INET6_ADDRSTRLEN)); offset += sizeof(struct sockaddr_in); } else if (addr->sa_family == AF_INET6) { if (!useLoopback && memcmp((const void *) &pin6->sin6_addr, (const void *) &in6addr_loopback, sizeof(struct in6_addr)) == 0) continue; this->rsEnrpAddr[i].type = AF_INET6; memcpy(&this->rsEnrpAddr[i].addr.in6, &pin6->sin6_addr, sizeof(struct in6_addr)); logDebug("addrs[%d]: AF_INET6 %s", i, inet_ntop(AF_INET6, (void *) &pin6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)); offset += sizeof(struct sockaddr_in6); } } sctp_freeladdrs(addrs); } /* parse asap sctp addrs */ if ((addrCnt = sctp_getladdrs(asapSctpFd, 0, &addrs)) > 0) { offset = (char *) addrs; logDebug("asap sctp: we are locally bound to %d adresses", addrCnt); for (i = 0; i < addrCnt && i < MAX_ADDR_CNT; i++) { addr = (struct sockaddr *) offset; pin4 = (struct sockaddr_in *) offset; pin6 = (struct sockaddr_in6 *) offset; if (addr->sa_family == AF_INET) { if (!useLoopback && pin4->sin_addr.s_addr == INADDR_LOOPBACK) continue; this->rsAsapAddr[i].type = AF_INET; memcpy(&this->rsAsapAddr[i].addr.in4, &pin4->sin_addr, sizeof(struct in_addr)); logDebug("addrs[%d]: AF_INET %s", i, inet_ntop(AF_INET, (void *) &pin4->sin_addr, addrBuf, INET6_ADDRSTRLEN)); offset += sizeof(struct sockaddr_in); } else if (addr->sa_family == AF_INET6) { if (!useLoopback && memcmp((const void *) &pin6->sin6_addr, (const void *) &in6addr_loopback, sizeof(struct in6_addr)) == 0) continue; this->rsAsapAddr[i].type = AF_INET6; memcpy(&this->rsAsapAddr[i].addr.in6, &pin6->sin6_addr, sizeof(struct in6_addr)); logDebug("addrs[%d]: AF_INET6 %s", i, inet_ntop(AF_INET6, (void *) &pin6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)); offset += sizeof(struct sockaddr_in6); } } sctp_freeladdrs(addrs); } return 1; }
/** * @brief TimeToString Method to convert the time to some good-looking string. * @return A std::string representing the time in HH:MM:SS.MM format. * The starting HH:MM: part is left out if not needed. */ std::string toString() const { return TimeToString(getTime()); }
void Time::update() { lastTime = currentTime; currentTime = getTime(); }
void Layer3::Run (pth_sem_t * stop1) { pth_event_t stop = pth_event (PTH_EVENT_SEM, stop1); unsigned i; running = true; for (i = 0; i < layer2 (); i++) layer2[i].Start (); TRACEPRINTF (t, 3, this, "L3 started"); while (pth_event_status (stop) != PTH_STATUS_OCCURRED) { pth_event_t bufev = pth_event (PTH_EVENT_SEM, &bufsem); pth_event_concat (bufev, stop, NULL); pth_wait (bufev); pth_event_isolate (bufev); if (pth_event_status (bufev) != PTH_STATUS_OCCURRED) { pth_event_free (bufev, PTH_FREE_THIS); continue; } pth_event_free (bufev, PTH_FREE_THIS); pth_sem_dec (&bufsem); LPDU *l = buf.get (); if (!l) continue; if (l->getType () == L_Busmonitor) { L_Busmonitor_PDU *l1, *l2; l1 = (L_Busmonitor_PDU *) l; TRACEPRINTF (t, 3, this, "Recv %s", l1->Decode ()()); for (i = 0; i < busmonitor (); i++) { l2 = new L_Busmonitor_PDU (*l1); busmonitor[i].cb->Send_L_Busmonitor (l2); } for (i = 0; i < vbusmonitor (); i++) { l2 = new L_Busmonitor_PDU (*l1); vbusmonitor[i].cb->Send_L_Busmonitor (l2); } } if (l->getType () == L_Data) { L_Data_PDU *l1; l1 = (L_Data_PDU *) l; if (l1->repeated) { CArray d1 = l1->ToPacket (); for (i = 0; i < ignore (); i++) if (d1 == ignore[i].data) { TRACEPRINTF (t, 3, this, "Repeated discareded"); goto wt; } } l1->repeated = 1; ignore.resize (ignore () + 1); ignore[ignore () - 1].data = l1->ToPacket (); ignore[ignore () - 1].end = getTime () + 1000000; l1->repeated = 0; if (l1->AddrType == IndividualAddress && l1->dest == defaultAddr) l1->dest = 0; TRACEPRINTF (t, 3, this, "Recv %s", l1->Decode ()()); if (l1->AddrType == GroupAddress && l1->dest == 0) { for (i = 0; i < broadcast (); i++) broadcast[i].cb->Send_L_Data (new L_Data_PDU (*l1)); } if (l1->AddrType == GroupAddress && l1->dest != 0) { for (i = 0; i < group (); i++) { Group_Info &grp = group[i]; if (grp.dest == l1->dest || grp.dest == 0) grp.cb->Send_L_Data (new L_Data_PDU (*l1)); } } if (l1->AddrType == IndividualAddress) { for (i = 0; i < individual (); i++) { Individual_Info &indiv = individual[i]; if (indiv.dest == l1->dest || indiv.dest == 0) if (indiv.src == l1->source || indiv.src == 0) indiv.cb->Send_L_Data (new L_Data_PDU (*l1)); } } // finally, send to all (other(?)) L2 interfaces // TODO: filter by addresses send_L_Data(l1); } // ignore[] is ordered, any timed-out items are at the front for (i = 0; i < ignore (); i++) if (ignore[i].end >= getTime ()) break; if (i) ignore.deletepart (0, i); wt: delete l; } TRACEPRINTF (t, 3, this, "L3 stopping"); running = false; for (i = 0; i < layer2 (); i++) layer2[i].Stop (); pth_event_free (stop, PTH_FREE_THIS); }
inline ObjectWrapper::ObjectWrapper(const boost::shared_ptr<Object>& object) : object_(object), dirty_(false) { creationTime_ = updateTime_ = getTime(); }
double toggleStart() { return start=getTime(); }