void QgsServer::handleRequest( QgsServerRequest &request, QgsServerResponse &response ) { QgsMessageLog::MessageLevel logLevel = QgsServerLogger::instance()->logLevel(); QTime time; //used for measuring request time if loglevel < 1 QgsProject::instance()->removeAllMapLayers(); qApp->processEvents(); if ( logLevel == QgsMessageLog::INFO ) { time.start(); } // Pass the filters to the requestHandler, this is needed for the following reasons: // Allow server request to call sendResponse plugin hook if enabled QgsFilterResponseDecorator responseDecorator( sServerInterface->filters(), response ); //Request handler QgsRequestHandler requestHandler( request, response ); try { // TODO: split parse input into plain parse and processing from specific services requestHandler.parseInput(); } catch ( QgsMapServiceException &e ) { QgsMessageLog::logMessage( "Parse input exception: " + e.message(), QStringLiteral( "Server" ), QgsMessageLog::CRITICAL ); requestHandler.setServiceException( e ); } // Set the request handler into the interface for plugins to manipulate it sServerInterface->setRequestHandler( &requestHandler ); // Call requestReady() method (if enabled) responseDecorator.start(); // Plugins may have set exceptions if ( !requestHandler.exceptionRaised() ) { try { QMap<QString, QString> parameterMap = request.parameters(); printRequestParameters( parameterMap, logLevel ); //Config file path QString configFilePath = configPath( *sConfigFilePath, parameterMap ); // load the project if needed and not empty const QgsProject *project = mConfigCache->project( configFilePath ); if ( ! project ) { throw QgsServerException( QStringLiteral( "Project file error" ) ); } sServerInterface->setConfigFilePath( configFilePath ); //Service parameter QString serviceString = parameterMap.value( QStringLiteral( "SERVICE" ) ); if ( serviceString.isEmpty() ) { // SERVICE not mandatory for WMS 1.3.0 GetMap & GetFeatureInfo QString requestString = parameterMap.value( QStringLiteral( "REQUEST" ) ); if ( requestString == QLatin1String( "GetMap" ) || requestString == QLatin1String( "GetFeatureInfo" ) ) { serviceString = QStringLiteral( "WMS" ); } } QString versionString = parameterMap.value( QStringLiteral( "VERSION" ) ); //possibility for client to suggest a download filename QString outputFileName = parameterMap.value( QStringLiteral( "FILE_NAME" ) ); if ( !outputFileName.isEmpty() ) { requestHandler.setResponseHeader( QStringLiteral( "Content-Disposition" ), "attachment; filename=\"" + outputFileName + "\"" ); } // Lookup for service QgsService *service = sServiceRegistry.getService( serviceString, versionString ); if ( service ) { service->executeRequest( request, responseDecorator, project ); } else { throw QgsOgcServiceException( QStringLiteral( "Service configuration error" ), QStringLiteral( "Service unknown or unsupported" ) ) ; } } catch ( QgsServerException &ex ) { responseDecorator.write( ex ); } catch ( QgsException &ex ) { // Internal server error response.sendError( 500, ex.what() ); } } // Terminate the response responseDecorator.finish(); // We are done using requestHandler in plugins, make sure we don't access // to a deleted request handler from Python bindings sServerInterface->clearRequestHandler(); if ( logLevel == QgsMessageLog::INFO ) { QgsMessageLog::logMessage( "Request finished in " + QString::number( time.elapsed() ) + " ms", QStringLiteral( "Server" ), QgsMessageLog::INFO ); } }
// This is called from the AnalyserQueue thread bool AnalyserQueue::doAnalysis(TrackPointer tio, SoundSourceProxy* pSoundSource) { int totalSamples = pSoundSource->length(); //qDebug() << tio->getFilename() << " has " << totalSamples << " samples."; int processedSamples = 0; QTime progressUpdateInhibitTimer; progressUpdateInhibitTimer.start(); // Inhibit Updates for 60 milliseconds int read = 0; bool dieflag = false; bool cancelled = false; int progress; // progress in 0 ... 100 do { ScopedTimer t("AnalyserQueue::doAnalysis block"); read = pSoundSource->read(kAnalysisBlockSize, m_pSamplesPCM); // To compare apples to apples, let's only look at blocks that are the // full block size. if (read != kAnalysisBlockSize) { t.cancel(); } // Safety net in case something later barfs on 0 sample input if (read == 0) { t.cancel(); break; } // If we get more samples than length, ask the analysers to process // up to the number we promised, then stop reading - AD if (read + processedSamples > totalSamples) { qDebug() << "While processing track of length " << totalSamples << " actually got " << read + processedSamples << " samples, truncating analysis at expected length"; read = totalSamples - processedSamples; dieflag = true; } // Normalize the samples from [SHRT_MIN, SHRT_MAX] to [-1.0, 1.0]. // TODO(rryan): Change the SoundSource API to do this for us. for (int i = 0; i < read; ++i) { m_pSamples[i] = static_cast<CSAMPLE>(m_pSamplesPCM[i]) / SHRT_MAX; } QListIterator<Analyser*> it(m_aq); while (it.hasNext()) { Analyser* an = it.next(); //qDebug() << typeid(*an).name() << ".process()"; an->process(m_pSamples, read); //qDebug() << "Done " << typeid(*an).name() << ".process()"; } // emit progress updates // During the doAnalysis function it goes only to 100% - FINALIZE_PERCENT // because the finalise functions will take also some time processedSamples += read; //fp div here prevents insane signed overflow progress = (int)(((float)processedSamples)/totalSamples * (1000 - FINALIZE_PERCENT)); if (m_progressInfo.track_progress != progress) { if (progressUpdateInhibitTimer.elapsed() > 60) { // Inhibit Updates for 60 milliseconds emitUpdateProgress(tio, progress); progressUpdateInhibitTimer.start(); } } // Since this is a background analysis queue, we should co-operatively // yield every now and then to try and reduce CPU contention. The // analyser queue is CPU intensive so we want to get out of the way of // the audio callback thread. //QThread::yieldCurrentThread(); //QThread::usleep(10); //has something new entered the queue? if (deref(m_aiCheckPriorities)) { m_aiCheckPriorities = false; if (isLoadedTrackWaiting(tio)) { qDebug() << "Interrupting analysis to give preference to a loaded track."; dieflag = true; cancelled = true; } } if (m_exit) { dieflag = true; cancelled = true; } // Ignore blocks in which we decided to bail for stats purposes. if (dieflag || cancelled) { t.cancel(); } } while(read == kAnalysisBlockSize && !dieflag); return !cancelled; //don't return !dieflag or we might reanalyze over and over }
// This requires all the Grids be of the same size and all the orbitals to be // of the same spin. Returns true only if something was calculated. bool MolecularOrbitals::computeOrbitalGrids(Data::GridDataList& grids) { if (grids.isEmpty()) return false;; // Check that the grids are all of the same size and Spin Data::GridData* g0(grids[0]); QList<int> orbitals; Data::GridDataList::iterator iter; for (iter = grids.begin(); iter != grids.end(); ++iter) { qDebug() << "Computing grid" << (*iter)->surfaceType().toString() ; (*iter)->size().dump(); if ( ((*iter)->size() != g0->size()) ) { QLOG_ERROR() << "Different sized grids found in molecular orbitals calculator"; return false; } if ( ((*iter)->surfaceType().kind() != Data::SurfaceType::AlphaOrbital) && ((*iter)->surfaceType().kind() != Data::SurfaceType::BetaOrbital) ) { QLOG_ERROR() << "Incorrect grid type found in molecular orbitals calculator"; QLOG_ERROR() << (*iter)->surfaceType().toString(); return false; } orbitals.append((*iter)->surfaceType().index()-1); } QTime time; time.start(); Matrix const* coefficients; if (g0->surfaceType().kind() == Data::SurfaceType::AlphaOrbital) { QLOG_TRACE() << "Setting MO coefficient data to Alpha"; coefficients = &(m_molecularOrbitals.alphaCoefficients()); }else { QLOG_TRACE() << "Setting MO coefficient data to Beta"; coefficients = &(m_molecularOrbitals.betaCoefficients()); } unsigned nOrb(orbitals.size()); unsigned nx, ny, nz; g0->getNumberOfPoints(nx, ny, nz); Vec delta(g0->delta()); Vec origin(g0->origin()); QProgressDialog progressDialog("Calculating orbital grid data", "Cancel", 0, nx, QApplication::activeWindow()); int progress(0); progressDialog.setValue(progress); progressDialog.setWindowModality(Qt::WindowModal); progressDialog.show(); double x, y, z; double* values; double* tmp = new double[nOrb]; unsigned i, j, k; Data::ShellList const& shells(m_molecularOrbitals.shellList()); Data::ShellList::const_iterator shell; for (i = 0, x = origin.x; i < nx; ++i, x += delta.x) { for (j = 0, y = origin.y; j < ny; ++j, y += delta.y) { for (k = 0, z = origin.z; k < nz; ++k, z += delta.z) { Vec gridPoint(x,y,z); for (unsigned orb = 0; orb < nOrb; ++orb) tmp[orb] = 0.0; unsigned count(0); //----------------------------------------------------- for (shell = shells.begin(); shell != shells.end(); ++shell) { if ( (values = (*shell)->evaluate(gridPoint)) ) { for (unsigned s = 0; s < (*shell)->nBasis(); ++s) { for (unsigned orb = 0; orb < nOrb; ++orb) { tmp[orb] += (*coefficients)(orbitals[orb], count) * values[s]; } ++count; } }else { count += (*shell)->nBasis(); } } for (unsigned orb = 0; orb < nOrb; ++orb) { (*grids.at(orb))(i, j, k) = tmp[orb]; } //----------------------------------------------------- } } ++progress; progressDialog.setValue(progress); if (progressDialog.wasCanceled()) return false; } delete [] tmp; double t = time.elapsed() / 1000.0; QLOG_INFO() << "Time to compute orbital grid data:" << t << "seconds"; return true; }
bool GribV2::loadFile(QString fileName) { FILE * fptr=NULL; int msg=0; this->fileName=fileName; QTime tLoad; int m_sec_readCgrib=0; int m_sec_ginfo=0; int m_sec_g2_getfld=0; int m_sec_grecConst=0; int m_sec_endLoop=0; qWarning() << "GV2 loading " << fileName; g2int lskip=0,lgrib=0,iseek=0; unsigned char *cgrib; // msg buffer g2int ierr,listsec0[3],listsec1[13],numfields,numlocal; std::string fname = qPrintable(fileName); if(fileName == "") return false; gribfield *gfld=NULL; ok=false; fptr=fopen(fname.c_str(),"rb"); if(!fptr) { qWarning() << "Can't open Grib2 file (in loadFile): " << fileName; return false; } fseek(fptr,0,SEEK_END); fileSize=ftell(fptr); rewind(fptr); /* clean data structure + iso lines */ clean_all_vectors(); Util::cleanListPointers(listIsobars); Util::cleanListPointers(listIsotherms0); for(;;) { msg++; seekgb(fptr,iseek,32000,&lskip,&lgrib); if (lgrib == 0) break; // end loop at EOF or problem cgrib=(unsigned char *)malloc(lgrib); fseek(fptr,lskip,SEEK_SET); tLoad.start(); fread(cgrib,sizeof(unsigned char),lgrib,fptr); m_sec_readCgrib+=tLoad.elapsed(); //qWarning() << "Size of cgrib: " << lgrib << ", skip=" << lskip; //qWarning() << "Bytes read from file: " << bRead; //qWarning() << "EOF=" << feof(fptr) << ", ferror=" << ferror(fptr); //qWarning() << "File pos=" << ftell(fptr); //qWarning() << "End of grib=" << cgrib[lgrib-4] << cgrib[lgrib-3] << cgrib[lgrib-2] << cgrib[lgrib-1]; iseek=lskip+lgrib; tLoad.start(); ierr=g2_info(cgrib,listsec0,listsec1,&numfields,&numlocal); m_sec_ginfo+=tLoad.elapsed(); if(ierr) { qWarning() << "msg " << msg << ": g2_info error num=" << ierr; fclose(fptr); return false; } // accepting only GRIB2 with discipline=0 => Meteorological product (table 0.0) if(listsec0[1]!=2 || (listsec0[0]!=0 && listsec0[0]!=10)) { qWarning() << "msg " << msg << ": wrong version " << listsec0[1] << ", or discipline: " << listsec0[0]; continue; } if(listsec1[4]!=1) { qWarning() << "msg " << msg << ": wrong reference time type: " << listsec1[4]; continue; } /* loop on th fields => 1 field = 1 GribRecord */ //qWarning() << "nb fields=" << numfields << ", nb locals=" << numlocal; for(int i=0;i<numfields;++i) { tLoad.start(); ierr=g2_getfld(cgrib,i+1,GRB2_UNPACK,GRB2_EXPAND,&gfld); m_sec_g2_getfld+=tLoad.elapsed(); if(ierr) { qWarning() << "msg=" << msg << "- field=" << i << ": g2_getfld error num=" << ierr; continue; } tLoad.start(); GribV2Record * record = new GribV2Record(gfld,msg,i); m_sec_grecConst+=tLoad.elapsed(); tLoad.start(); if(record && record->isOk() && record->isDataKnown()) addRecord(record); else if(record) delete record; g2_free(gfld); m_sec_endLoop+=tLoad.elapsed(); } free(cgrib); } if(fptr) fclose(fptr); qWarning() << "GRIBV2 load finished"; qWarning() << "NB key: " << mapGribRecords.size(); qWarning() << "List:"; std::map <long int, QMap<time_t,GribRecord *>* >::iterator it; int i=0; for(it=mapGribRecords.begin();it!=mapGribRecords.end();++it) { qWarning() << "key " << i << ": key= " << it->first << ", nb elem" << it->second->size(); ++i; } qWarning() << "Time stat:"; qWarning() << "\t read Cgrib: " << m_sec_readCgrib; qWarning() << "\t call gInfo: " << m_sec_ginfo; qWarning() << "\t call getFld: " << m_sec_g2_getfld; qWarning() << "\t const GribRecordV2: " << m_sec_grecConst; qWarning() << "\t End loop: " << m_sec_endLoop; createDewPointData(); ok=true; return true; }
int DataCurve::tableRow(int point) { if (!d_table) return -1; if (d_type == Graph::Pie) { double y_val = y(point); int ycol = d_table->colIndex(title().text()); for (int i = d_start_row; i <= d_end_row; i++ ) { if (d_table->cell(i, ycol) == y_val) return i; } } int xcol = d_table->colIndex(d_x_column); int ycol = d_table->colIndex(title().text()); if (xcol < 0 || ycol < 0) return -1; int xColType = d_table->columnType(xcol); if (xColType == Table::Date) { QString format = d_table->columnFormat(xcol); QDateTime date0 = QDateTime::fromString (d_table->text(d_start_row, xcol), format); for (int i = d_start_row; i <= d_end_row; i++ ) { QDateTime d = QDateTime::fromString (d_table->text(i, xcol), format); if (d.isValid()) { if (d_type == Graph::HorizontalBars && date0.secsTo(d) == y(point) && d_table->cell(i, ycol) == x(point)) return i; else if (date0.secsTo(d) == x(point) && d_table->cell(i, ycol) == y(point)) return i; } } } else if (xColType == Table::Time) { QString format = d_table->columnFormat(xcol); QTime t0 = QTime::fromString (d_table->text(d_start_row, xcol), format); for (int i = d_start_row; i <= d_end_row; i++ ) { QTime t = QTime::fromString (d_table->text(i, xcol), format); if (t.isValid()) { if (d_type == Graph::HorizontalBars && t0.msecsTo(t) == y(point) && d_table->cell(i, ycol) == x(point)) return i; if (t0.msecsTo(t) == x(point) && d_table->cell(i, ycol) == y(point)) return i; } } } else if (xColType == Table::Text) { double y_val = y(point); for (int i = d_start_row; i <= d_end_row; i++ ) { if (d_table->cell(i, ycol) == y_val) return i; } } double x_val = x(point); double y_val = y(point); for (int i = d_start_row; i <= d_end_row; i++ ) { if (d_table->cell(i, xcol) == x_val && d_table->cell(i, ycol) == y_val) return i; } return point; }
bNEVwr::bNEVwr(char file_name[], int num_channels, char typeGrid[], char comment[]) { NEV = fopen(file_name, "wb"); char headerName[8] = {'N','E','U','R','A','L','E','V'}; fwrite(headerName, 1, sizeof(headerName), NEV); unsigned short fileSpec[] = {0x0201,0}; fwrite(fileSpec,sizeof(fileSpec),1,NEV); //64*16bits+8bytes header = 136 unsigned int packetSize = 136; unsigned int timeResolution = 40000; unsigned int Fs = 40000; unsigned int headerSize = 400 + num_channels*32; // 336 + 32 (extended) + 32 (extended) unsigned int bytes[] = {headerSize,packetSize,timeResolution,Fs}; fwrite(bytes,sizeof(bytes),1,NEV); QDate theDate = QDate::currentDate(); short year = theDate.year(); short month = theDate.month(); short day = theDate.day(); short dayOfWeek = theDate.dayOfWeek(); QTime theTime = QTime::currentTime(); short hour = theTime.hour(); short minute = theTime.minute(); short second = theTime.second(); short msec = theTime.msec(); //GetSystemTime(&time); //fwrite(&time,sizeof(time),1,NEV); //short systemTime[2] = {1111111,999999}; //fwrite(fakeSYSTEMTIME,sizeof(fakeSYSTEMTIME),1,NEV); short timeToWrite[8] = {year,month,day,dayOfWeek,hour,minute,second,msec}; fwrite(timeToWrite,sizeof(timeToWrite),1,NEV); char appName[32] = "BIC NEV Writer v1.0"; fwrite(appName,sizeof(char),32,NEV); // Must be NULL terminated char *commentWrite = (char*)malloc(256); strcpy(commentWrite,comment); fwrite(commentWrite,sizeof(char),256,NEV); fwrite(numHead,sizeof(numHead),1,NEV); //////////////////////////////////////////////// char arrayName[8] = {'A','R','R','A','Y','N','M','E'}; fwrite(arrayName, 1, sizeof(arrayName), NEV); char *gridWrite = (char*)malloc(24); strcpy(gridWrite,typeGrid); fwrite(gridWrite,sizeof(char),24,NEV); //////////////////////////////////////////////// char NSASName[8] = {'N','S','A','S','E','X','E','V'}; fwrite(NSASName, 1, sizeof(NSASName), NEV); // No periodic generation - random unsigned short tempShort[1]= {0}; fwrite(tempShort,sizeof(tempShort),1,NEV); // Digital Input Changes should not be ignored... unsigned char tempChar[1]= {1}; fwrite(tempChar,sizeof(tempChar),1,NEV); //Analog Channel 1 tempChar[0] = 2; fwrite(tempChar,sizeof(tempChar),1,NEV); tempShort[0] = 2500; fwrite(tempShort,sizeof(tempShort),1,NEV); //Analog Channel 2 tempChar[0] = 2; fwrite(tempChar,sizeof(tempChar),1,NEV); tempShort[0] = 2500; fwrite(tempShort,sizeof(tempShort),1,NEV); //Analog Channel 3 tempChar[0] = 2; fwrite(tempChar,sizeof(tempChar),1,NEV); tempShort[0] = 2500; fwrite(tempShort,sizeof(tempShort),1,NEV); //Analog Channel 4 tempChar[0] = 2; fwrite(tempChar,sizeof(tempChar),1,NEV); tempShort[0] = 2500; fwrite(tempShort,sizeof(tempShort),1,NEV); //Analog Channel 5 tempChar[0] = 2; fwrite(tempChar,sizeof(tempChar),1,NEV); tempShort[0] = 2500; fwrite(tempShort,sizeof(tempShort),1,NEV); char tempBlanks[6] = {0,0,0,0,0,0}; fwrite(tempBlanks,sizeof(tempBlanks),1,NEV); }
void NewRealTimeSampleArrayWidget::paintEvent(QPaintEvent*) { QPainter painter(this); // //************************************************************************************************************* // //============================================================================================================= // // Draw white background // //============================================================================================================= // // painter.setBrush(Qt::white); // painter.drawRect(0, 0, width(), height()); painter.setPen(QPen(Qt::gray, 1, Qt::DashLine)); //************************************************************************************************************* //============================================================================================================= // Draw grid in X direction (each 100ms) //============================================================================================================= double dNumPixelsX = m_pRTSA->getSamplingRate()/10.0f; double dMinMaxDifference = static_cast<double>(m_pRTSA->getMaxValue()-m_pRTSA->getMinValue()); double dActualPosX = 0.0; unsigned short usNumOfGridsX = (unsigned short)(ui.m_qFrame->width()/dNumPixelsX); unsigned short usPosY = ui.m_qFrame->pos().y()+1; unsigned short usPosX = ui.m_qFrame->pos().x()+1; unsigned short usHeight = ui.m_qFrame->height()-2; unsigned short usWidth = ui.m_qFrame->width()-2; for(unsigned short i = 1; i <= usNumOfGridsX; ++i) { dActualPosX = m_dPosX+i*dNumPixelsX; painter.drawLine((int)dActualPosX, usPosY, (int)dActualPosX, usPosY+usHeight); } //************************************************************************************************************* //============================================================================================================= // Draw grid in Y direction //============================================================================================================= double exponent = (int)floor(log10(dMinMaxDifference))-1;//math.h double dim = pow(10.0, exponent);//respectively at 0.001; 0.01, 0.1, 1, 10, 100 int NumOfLines = (int)floor(dMinMaxDifference/(dim*5)); double dDifferenceToFirstLine = (m_pRTSA->getMaxValue()-floor(m_pRTSA->getMaxValue()/dim)*dim); double dNumPixelsY = usHeight/NumOfLines;//10.0f; double dActualPosY = usPosY + dDifferenceToFirstLine * (usHeight/dMinMaxDifference); for(unsigned char i = 1; i <= NumOfLines; ++i) { painter.drawLine((int)m_dPosX, (int)dActualPosY, usWidth, (int)dActualPosY); dActualPosY += dNumPixelsY; } //Paint middle value // painter.setPen(QPen(Qt::gray, 1, Qt::SolidLine)); // painter.drawText(usWidth-75, usHeight/2, tr("%1%2").arg(m_dMiddle, 0, 'f', 2).arg(m_pRTSA->getUnit())); // painter.setPen(QPen(Qt::gray, 1, Qt::DotLine)); // painter.drawLine(m_dPosX, usHeight/2, usWidth, usHeight/2); painter.setPen(QPen(Qt::blue, 1, Qt::SolidLine)); painter.setRenderHint(QPainter::Antialiasing); //************************************************************************************************************* //============================================================================================================= // Draw real time curve respectively frozen curve //============================================================================================================= if(m_bFrozen) { painter.setPen(QPen(Qt::darkGray, 1, Qt::SolidLine)); painter.drawPath(m_qPainterPath_Freeze); } else { m_qMutex.lock(); painter.drawPath(m_qPainterPath); m_qMutex.unlock(); } //************************************************************************************************************* //============================================================================================================= // Calculates zoom with the help of new minimum/maximum factors. //============================================================================================================= if(m_bScaling) { int iStartX = m_qPointMouseStartPosition.x(); int iEndY = m_qPointMouseEndPosition.y(); int iStartY = m_qPointMouseStartPosition.y(); // Compute pixel difference int iPixelDifferenceY = abs(iStartY - iEndY); double scale = (m_dMaxValue_init-m_dMinValue_init)/usHeight; if(iStartY>iEndY) { double changeValue = scale * iPixelDifferenceY; if(changeValue*2 < m_dMaxValue_init - m_dMinValue_init) { minValueChanged(m_dMinValue_init + changeValue); maxValueChanged(m_dMaxValue_init - changeValue); } else { double maxChange = (m_dMaxValue_init - m_dMinValue_init)*0.499999; minValueChanged(m_dMinValue_init + maxChange); maxValueChanged(m_dMaxValue_init - maxChange); } } else { double changeValue = scale * iPixelDifferenceY*10; minValueChanged(m_dMinValue_init - changeValue); maxValueChanged(m_dMaxValue_init + changeValue); } double factor = (m_dMaxValue_init-m_dMinValue_init)/(m_pRTSA->getMaxValue()-m_pRTSA->getMinValue()); // Draw text painter.setPen(QPen(Qt::darkCyan, 1, Qt::SolidLine)); painter.drawText(iStartX+8, iEndY, tr("Zoom %1x").arg(factor, 0, 'f', 2)); } //************************************************************************************************************* //============================================================================================================= // Draw coordinates at mouse position //============================================================================================================= if(m_bPosition && m_pRTSA->getSamplingRate()) { int iPosX = mapFromGlobal(QCursor::pos()).x(); int iPosY = mapFromGlobal(QCursor::pos()).y(); if(iPosX > usPosX && iPosX < (usPosX + usWidth) && iPosY > usPosY && iPosY < usPosY + usHeight ) { //Vertical Measuring painter.setPen(QPen(Qt::gray, 1, Qt::DashLine)); QPoint start(usPosX, iPosY);//iStartY-5);//paint measure line vertical direction QPoint end(usPosX + usWidth, iPosY);//iStartY+5); painter.drawLine(start, end); start.setX(iPosX); start.setY(usPosY);//iStartY - 5); end.setX(iPosX); end.setY(usPosY + usHeight);//iStartY + 5); painter.drawLine(start, end); // Compute time between MouseStartPosition and MouseEndPosition QTime t = m_pTimeCurrentDisplay->addMSecs((int)(1000*(iPosX-usPosX)/(float)m_pRTSA->getSamplingRate())); float fAbsMag = m_pRTSA->getMinValue()+(usHeight-(iPosY-usPosY))*(dMinMaxDifference/usHeight); // Draw text painter.setPen(QPen(Qt::darkGray, 1, Qt::SolidLine)); painter.drawText(iPosX+8, iPosY-22, tr("%1").arg(t.toString("hh:mm:ss.zzz")));// ToDo Precision should be part of preferences painter.drawText(iPosX+8, iPosY-8, tr("%1%2").arg(fAbsMag, 0, 'e', 3).arg(m_pRTSA->getUnit())); } } //************************************************************************************************************* //============================================================================================================= // Draw the measurement tools of the curve //============================================================================================================= if(m_bMeasurement && m_pRTSA->getSamplingRate()) { int iEndX = m_qPointMouseEndPosition.x(); int iStartX = m_qPointMouseStartPosition.x(); int iEndY = m_qPointMouseEndPosition.y(); int iStartY = m_qPointMouseStartPosition.y(); // Compute pixel difference double iPixelDifferenceX = abs(iStartX - iEndX); double iPixelDifferenceY = abs(iStartY - iEndY); if(iPixelDifferenceX < 5 && iPixelDifferenceY < 5) return; //Vertical Measuring painter.setPen(QPen(Qt::darkCyan, 1, Qt::DashLine)); if(iPixelDifferenceX > iPixelDifferenceY) { // Draw measuring line // QPoint endPosY(iEndX, iStartY); // painter.drawLine(m_qPointMouseStartPosition, endPosY); QPoint start(iStartX, usPosY);//iStartY-5);//paint measure line vertical direction QPoint end(iStartX, usPosY+usHeight);//iStartY+5); painter.drawLine(start, end); start.setX(iEndX); start.setY(usPosY);//iStartY - 5); end.setX(iEndX); end.setY(usPosY+usHeight);//iStartY + 5); painter.drawLine(start, end); // Compute text position if(iEndX > iStartX) iEndX = iEndX + 9; else iEndX = iEndX - 67; // Compute time between MouseStartPosition and MouseEndPosition float iTime = 1000.0f*(float)iPixelDifferenceX/(float)m_pRTSA->getSamplingRate(); float iHz = 1000.0f/(float)iTime; // Draw text painter.setPen(QPen(Qt::darkCyan, 1, Qt::SolidLine)); painter.drawText(iEndX, iEndY-18, tr("%1ms").arg(iTime, 0, 'f', 2));// ToDo Precision should be part of preferences painter.drawText(iEndX, iEndY-4, tr("%1Hz").arg(iHz, 0, 'f', 2)); } else { // Draw measuring line // QPoint endPosX(iStartX, iEndY); // painter.drawLine(endPosX, m_qPointMouseStartPosition); QPoint start(usPosX, iStartY);//iStartY-5);//paint measure line vertical direction QPoint end(usPosX+usWidth, iStartY);//iStartY+5); painter.drawLine(start, end); start.setX(usPosX); start.setY(iEndY);//iStartY - 5); end.setX(usPosX+usWidth); end.setY(iEndY);//iStartY + 5); painter.drawLine(start, end); // Compute text position if(iEndY > iStartY) iEndY = iEndY + 1; else iEndY = iEndY + 23 ; // Compute time between MouseStartPosition and MouseEndPosition float fMagnitude = (float)iPixelDifferenceY * (dMinMaxDifference/usHeight) ; // Draw text painter.setPen(QPen(Qt::darkCyan, 1, Qt::SolidLine)); painter.drawText(iEndX+14, iEndY-8, tr("%1%2").arg(fMagnitude, 0, 'e', 3).arg(m_pRTSA->getUnit()));// ToDo Precision should be part of preferences } } }
void Worker::doWork (InputParametersRS input) { // if the last input is different from this input only in the frame number, // then we can re-use some of the results from previous invocation bool cacheValid = false; if( m_lastInput.fitsLocation.uniqueId() == input.fitsLocation.uniqueId() && ! m_lastInput.isNull && m_lastInput.bottom == input.bottom && m_lastInput.top == input.top && m_lastInput.left == input.left && m_lastInput.right == input.right) { cacheValid = true; } else { cacheValid = false; m_currRes = ResultsRS(); m_currRes.nFramesComputed = 0; } m_lastInput = input; // for null input emit null output if( input.isNull) { m_currRes.status_ = ResultsRS::NullInput; emit done(m_currRes); return; } // initialize the parser if it's not already initialized if( ! m_parser) m_parser = new FitsParser(); // if the parser is working on a different filename, reopen it if( currentFitsLocation_.uniqueId () != input.fitsLocation.uniqueId ()) { bool res = m_parser->loadFile ( input.fitsLocation); if( ! res) throw std::runtime_error("Could not open file"); else currentFitsLocation_ = input.fitsLocation; } // get a reference to the fits header const FitsParser::HeaderInfo & hdr = m_parser->getHeaderInfo (); // check for more input errors now that we have fits header input.left = clamp( input.left, 0, hdr.naxis1-1); input.right = clamp( input.right, 0, hdr.naxis1-1); input.top = clamp( input.top, 0, hdr.naxis2-1); input.bottom = clamp( input.bottom, 0, hdr.naxis2-1); if( input.left > input.right) std::swap( input.left, input.right); if( input.top > input.bottom) std::swap( input.top, input.bottom); // prepare results (partial) m_currRes.input = input; // save reference to (fixed) input m_currRes.width = m_currRes.input.right - m_currRes.input.left + 1; m_currRes.height = m_currRes.input.bottom - m_currRes.input.top + 1; m_currRes.totalPixels = m_currRes.width * m_currRes.height; m_currRes.depth = hdr.totalFrames; m_currRes.currentFrame = m_currRes.input.currentFrame; throwIfInterrupt(); int frame = m_currRes.input.currentFrame; // get the frame results for the current frame, unless we can retrieve this already // from the last time m_currRes.frames.resize( hdr.totalFrames); if( cacheValid && frame < m_currRes.nFramesComputed) { } else { m_currRes.frames[ frame] = computeFrame( input, frame); } ResultsRS::FrameRes & cfr = m_currRes.frames[ frame]; // copy out the relevant bits m_currRes.nanPixels = cfr.nanPixels; m_currRes.min = cfr.min; m_currRes.max = cfr.max; m_currRes.average = cfr.average; m_currRes.sum = cfr.sum; m_currRes.rms = cfr.rms; m_currRes.bkgLevel = cfr.bkgLevel; m_currRes.sumMinusBkg = cfr.sumMinusBkg; m_currRes.maxMinusBkg = cfr.maxMinusBkg; m_currRes.maxPos = cfr.maxPos; { // total flux double bmin = 0.0, bmaj = 0.0; bool ok = true; if( ok) bmin = hdr.bmin.toDouble( & ok); if( ok) bmaj = hdr.bmaj.toDouble( & ok); if( ok) { m_currRes.beamArea = bmin * bmaj * 1.13309003545679845240692073642916670254 / (hdr.cdelt1 * hdr.cdelt2); m_currRes.beamArea = fabs( m_currRes.beamArea); m_currRes.totalFluxDensity = m_currRes.sum / m_currRes.beamArea; m_currRes.aboveBackground = m_currRes.sumMinusBkg / m_currRes.beamArea; } else { m_currRes.totalFluxDensity = std::numeric_limits<double>::quiet_NaN(); m_currRes.aboveBackground = std::numeric_limits<double>::quiet_NaN(); m_currRes.beamArea = std::numeric_limits<double>::quiet_NaN(); } } // if the results are already complete, we are done if( m_currRes.nFramesComputed == hdr.totalFrames) { m_currRes.status_ = ResultsRS::Complete; emit done (m_currRes); return; } // otherwise we'll have to compute the remaining frames, but in any case, // report a partial result right now with the current frame m_currRes.status_ = ResultsRS::Partial; emit progress( m_currRes); // initialize timer for reporting progress QTime progressTimer; progressTimer.restart (); // now extract all the other frames int startFrame = m_currRes.nFramesComputed; for( int i = startFrame ; i < hdr.totalFrames ; i ++ ) { throwIfInterrupt(); if( i == frame) continue; // skip the current frame, we already did that one // compute the frame m_currRes.frames[i] = computeFrame( input, i); m_currRes.nFramesComputed = i + 1; // report progress every second or so, but not for the last frame... if( progressTimer.elapsed () > 1000 && i+1 < hdr.totalFrames) { progressTimer.restart (); throwIfInterrupt (); emit progress( m_currRes); } } // we are done m_currRes.status_ = ResultsRS::Complete; m_currRes.nFramesComputed = m_currRes.depth; throwIfInterrupt (); emit done (m_currRes); }
void Project::load(const QString &newProjectPath) { QTime a;a.start(); ThreadWeaver::Weaver::instance()->dequeue(); kDebug()<<"loading"<<newProjectPath<<"Finishing jobs..."; if (!m_path.isEmpty()) { TM::CloseDBJob* closeDBJob=new TM::CloseDBJob(projectID(),this); connect(closeDBJob,SIGNAL(done(ThreadWeaver::Job*)),closeDBJob,SLOT(deleteLater())); } ThreadWeaver::Weaver::instance()->finish();//more safety kDebug()<<"5..."; setSharedConfig(KSharedConfig::openConfig(newProjectPath, KConfig::NoGlobals)); kDebug()<<"4..."; readConfig(); m_path=newProjectPath; m_desirablePath.clear(); //cache: m_projectDir=KUrl(m_path).directory(); kDebug()<<"3..."; m_localConfig->setSharedConfig(KSharedConfig::openConfig(projectID()+".local", KConfig::NoGlobals,"appdata")); m_localConfig->readConfig(); if (langCode().isEmpty()) setLangCode(KGlobal::locale()->language()); kDebug()<<"2..."; //KConfig config; //delete m_localConfig; m_localConfig=new KConfigGroup(&config,"Project-"+path()); populateDirModel(); kDebug()<<"1..."; //put 'em into thread? //QTimer::singleShot(0,this,SLOT(populateGlossary())); populateGlossary();//we cant postpone it becase project load can be called from define new term function if (newProjectPath.isEmpty()) return; //NOTE do we need to explicitly call it when project id changes? TM::DBFilesModel::instance()->openDB(projectID()); if (QaModel::isInstantiated()) { QaModel::instance()->saveRules(); QaModel::instance()->loadRules(qaPath()); } kDebug()<<"until emitting signal"<<a.elapsed(); emit loaded(); kDebug()<<"loaded!"<<a.elapsed(); }
/* * aLeftPlayer: next in turn * aRightPlayer: prev in turn * 0, 1th * 1th, 2nd */ Card *AlphaBetaPlayer::makeMove (Card *lMove, Card *rMove, Player *aLeftPlayer, Player *aRightPlayer, bool isPassOut) { qDebug() << type() << "("<< mPlayerNo << ") moves"; card_t hands[3][10]; card_t desk[3]; int crdLeft = 0; int trumpSuit = 0; Player *plst[3]; //again: plst[0] = plst[1] = plst[2] = 0; plst[mPlayerNo-1] = this; plst[aLeftPlayer->number()-1] = aLeftPlayer; plst[aRightPlayer->number()-1] = aRightPlayer; // build hands for (int c = 0; c < 3; c++) { Q_ASSERT(plst[c]); CardList *clst = &(plst[c]->mCards); //for (int f = 0; f < 10; f++) hds[c][f] = hands[c][f] = 0; int pos = 0; for (int f = 0; f < clst->size(); f++) { Card *ct = clst->at(f); if (!ct) continue; hands[c][pos++] = CARD(ct->face(), ct->suit()-1); if (pos > crdLeft) crdLeft = pos; } for (int f = pos; f < 10; f++) hands[c][f] = 0; xsortCards(hands[c], pos); } if (!lMove && !rMove && crdLeft == 10) { return AiPlayer::makeMove(lMove, rMove, aLeftPlayer, aRightPlayer, isPassOut); } // find game const eGameBid bid = m_model->currentGame(); gPassOutOrMisere = (bid == g86 || bid == g86catch || bid == raspass); trumpSuit = bid%10-1;//(bid-(bid/10)*10)-1; /* if (bid == g86catch || bid == g86 || bid == raspass) { return Player::moveSelectCard(lMove, rMove, aLeftPlayer, aRightPlayer); } */ if (bid == g86catch || bid == g86 || bid == raspass) { trumpSuit = 4; } if (trumpSuit < 0) trumpSuit = 4; fprintf(stderr, "po:%s; lm:%s, rm:%s\n", isPassOut?"y":"n", lMove?"y":"n", rMove?"y":"n"); if (isPassOut && rMove && !lMove) { // это распасы, первый или второй круг, первый ход gPassOutSuit = rMove->suit()-1; fprintf(stderr, "pass-out: %i\n", gPassOutSuit); rMove = 0; } else gPassOutSuit = -1; // build desk int turn = 0; if (lMove) { desk[turn++] = CARD(lMove->face(), lMove->suit()-1); if (rMove) desk[turn++] = CARD(rMove->face(), rMove->suit()-1); } else if (rMove) { desk[turn++] = CARD(rMove->face(), rMove->suit()-1); } // build hands for (int f = 0; f < 3; f++) { xHands[f].suitCount[0] = xHands[f].suitCount[1] = xHands[f].suitCount[2] = xHands[f].suitCount[3] = 0; xHands[f].suitStart[0] = xHands[f].suitStart[1] = xHands[f].suitStart[2] = xHands[f].suitStart[3] = 11; xHands[f].tricks = plst[f]->tricksTaken(); int st; for (int z = 0; z < 10; z++) { if (hands[f][z]) { xHands[f].faces[z] = FACE(hands[f][z]); st = xHands[f].suits[z] = SUIT(hands[f][z]); if (xHands[f].suitCount[st]++ == 0) xHands[f].suitStart[st] = z; } else xHands[f].faces[z] = 0; } } // build desk for (int f = 0; f < turn; f++) { xDeskFaces[f] = FACE(desk[f]); xDeskSuits[f] = SUIT(desk[f]); } int a, b, c, move; int me = this->number()-1; xCardsLeft = crdLeft; gTrumpSuit = trumpSuit; gIterations = 0; printf("%shand 0:", this->number()==0?"*":" "); printHand(&(xHands[0])); printf("%shand 1:", this->number()==1?"*":" "); printHand(&(xHands[1])); printf("%shand 2:", this->number()==2?"*":" "); printHand(&(xHands[2])); printDesk(turn); // оптимизации /* if (turn > 0) { // можем вообще взять? if (hands[me].suitCount( } */ stTime = QTime::currentTime(); stTime.start(); abcPrune(turn, me, -666, 666, 666, &a, &b, &c, &move); qDebug() << "face:" << FACE(hands[me][move]) << "suit:" << SUIT(hands[me][move])+1 << "move:" << move << "turn:" << turn << "moves:" << crdLeft << "trump:" << trumpSuit << "iters:" << gIterations << ""; /* for (int h = 0; h < 3; h++) { fprintf(stderr, (h == me)?"*":" "); fprintf(stderr, "hand %i:", h); for (int f = 0; f < 10; f++) { if (hands[h][f]) { fprintf(stderr, " %2i.%i(%3i)", FACE(hands[h][f]), SUIT(hands[h][f]), hands[h][f]); } else { fprintf(stderr, " %2i.%i(%3i)", 0, 0, hands[h][f]); } } fprintf(stderr, "\n"); } fprintf(stderr, "desk:"); for (int f = 0; f < turn; f++) { fprintf(stderr, " %2i.%i(%3i)", FACE(desk[f]), SUIT(desk[f]), desk[f]); } fprintf(stderr, "\n"); */ Q_ASSERT(move >= 0); Card *moveCard = getCard(FACE(hands[me][move]), SUIT(hands[me][move])+1); qDebug() << "move:" << moveCard->toString(); mCards.remove(moveCard); mCardsOut.insert(moveCard); return moveCard; }
void Worker::doWorkOld (InputParametersRS input) { ResultsRS r; // for null input emit null output if( input.isNull) { r.status_ = ResultsRS::NullInput; emit done(r); return; } // initialize the parser if it's not already initialized if( ! m_parser) m_parser = new FitsParser(); // if the parser is working on a different filename, reopen it if( currentFitsLocation_.uniqueId () != input.fitsLocation.uniqueId ()) { bool res = m_parser->loadFile ( input.fitsLocation); if( ! res) throw std::runtime_error("Could not open file"); else currentFitsLocation_ = input.fitsLocation; } // get a reference to the fits header const FitsParser::HeaderInfo & hdr = m_parser->getHeaderInfo (); // check for more input errors now that we have fits header input.left = clamp( input.left, 0, hdr.naxis1-1); input.right = clamp( input.right, 0, hdr.naxis1-1); input.top = clamp( input.top, 0, hdr.naxis2-1); input.bottom = clamp( input.bottom, 0, hdr.naxis2-1); if( input.left > input.right) std::swap( input.left, input.right); if( input.top > input.bottom) std::swap( input.top, input.bottom); // prepare results (partial) r.input = input; // save reference to (fixed) input r.width = r.input.right - r.input.left + 1; r.height = r.input.bottom - r.input.top + 1; r.totalPixels = r.width * r.height; r.status_ = ResultsRS::Partial; r.depth = hdr.totalFrames; r.currentFrame = r.input.currentFrame; throwIfInterrupt(); // emit progress (r); int frame = r.input.currentFrame; // get the frame results for the current frame r.frames.resize( hdr.totalFrames); r.frames[ frame] = computeFrame( input, frame); ResultsRS::FrameRes & cfr = r.frames[ frame]; // cfr = computeForFrame( input, frame); // copy out the relevant bits r.nanPixels = cfr.nanPixels; r.min = cfr.min; r.max = cfr.max; r.average = cfr.average; r.sum = cfr.sum; r.rms = cfr.rms; r.bkgLevel = cfr.bkgLevel; r.sumMinusBkg = cfr.sumMinusBkg; r.maxMinusBkg = cfr.maxMinusBkg; r.maxPos = cfr.maxPos; emit progress( r); // initialize timer for reporting progress QTime progressTimer; progressTimer.restart (); // now extract all the other frames for( int i = 0 ; i < hdr.totalFrames ; i ++ ) { throwIfInterrupt(); if( i == frame) continue; // skip the current frame, we already did that one // compute the frame r.frames[i] = computeFrame( input, i); r.nFramesComputed = i + 1; // report progress every second or so, but not for the last frame... if( progressTimer.elapsed () > 1000 && i+1 < hdr.totalFrames) { progressTimer.restart (); throwIfInterrupt (); emit progress( r); } } // we are done r.status_ = ResultsRS::Complete; r.nFramesComputed = r.depth; throwIfInterrupt (); emit done (r); }
/* * карты должны быть отсортированы по мастям в порядке убывания "морды" * a: игрок player набрал максимум вот столько * b: игрок player+1 набрал максимум вот столько * c: игрок player+2 набрал максимум вот столько * возврат: то же самое * * идея и псевдокод взяты отсюда: http://clauchau.free.fr/gamma.html * idea and pseudocode was taken from here: http://clauchau.free.fr/gamma.html */ static void abcPrune ( int turn, int player, int a, int b, int c, int *ra, int *rb, int *rc, int *rm ) { /* * (x, y, z) := some static additive evaluation of Position, * x measuring how good is Position for the Player to move, * y measuring how good is Position for the next Player, * z measuring how good is Position for the further next Player, * the higher the better, -infinite for a defeat, +infinite for a win; * * if the game is over then return (x, y, z, "game over"); * else return ( min(x-y, x-z), min(y-x, y-z), min(z-x, z-y), "static" ); */ /* if (!xCardsLeft) { gIterations++; if (gIterations%8000000 == 0) { cTime = getTimeMs(); fprintf(stderr, "\r%i (%i seconds)\x1b[K", gIterations, (int)((cTime-xStTime)/1000)); } *ra = xHands[player].tricks; *rb = xHands[(player+1)%3].tricks; *rc = xHands[(player+2)%3].tricks; return; } */ //int lmF = lastMoveF, lmS = lastMoveS; #ifdef ABDEBUG printf("cards left: %i; turn: %i\n", xCardsLeft, turn); printStatus(turn, player, 0); #endif tHand *hand = &(xHands[player]); //int bestx = a, worsty = b, worstz = c; int bestx = -666, worsty = 666, worstz = 666; int bestm = -1; int n = 0; // will count equivalent moves int crdFace, crdSuit, tmp, who = -1; int newTurn = turn+1, newPlayer = (player+1)%3; int sDeskFaces[3], sDeskSuits[3]; sDeskFaces[0] = xDeskFaces[0]; sDeskFaces[1] = xDeskFaces[1]; sDeskFaces[2] = xDeskFaces[2]; sDeskSuits[0] = xDeskSuits[0]; sDeskSuits[1] = xDeskSuits[1]; sDeskSuits[2] = xDeskSuits[2]; if (turn == 2) { newTurn = 0; --xCardsLeft; } int crdNo = 0, crdNext, ccc = 0; for (int f = 0; f < 10; f++) if (hand->faces[f]) ccc++; //if (!ccc) { abort(); } Q_ASSERT(ccc); //int movesChecked = 0, firstm = -1; while (crdNo < 10) { crdFace = hand->faces[crdNo]; if (!hand->faces[crdNo]) { crdNo++; continue; } crdNext = crdNo+1; crdSuit = hand->suits[crdNo]; if (turn == 0) { // первый ход может быть любой ваще, если это не первый и не второй круг распасов if (gPassOutSuit >= 0 && crdSuit != gPassOutSuit && hand->suitCount[gPassOutSuit]) { // не, это очень херовая масть, начнём с верной масти tmp = hand->suitStart[gPassOutSuit]; //if (tmp == crdNo) abort(); // а такого не бывает Q_ASSERT(tmp != crdNo); if (tmp < crdNo) break; // ну нет у нас такой, и уже всё, что было, проверили // скипаем и повторяем выборы crdNo = tmp; continue; } goto doMove; } // check for valid move // выход в правильную масть? if (crdSuit == xDeskSuits[0]) goto doMove; // не, не та масть; ну-ка, чо у нас на руках ваще? // нужная масть у нас есть? if (hand->suitCount[xDeskSuits[0]]) { // таки есть, потому это очень хуёвый вариант; ходим сразу с нужной масти tmp = hand->suitStart[xDeskSuits[0]]; if (tmp < crdNo) break; // всё, нечего больше искать if (tmp > crdNo) { // скипаем crdNo = tmp; continue; } // вот этой и ходим goto doMove; } // не, нужной масти нет // а козырь есть? if (gTrumpSuit <= 3) { // игра козырная, есть козыри? if (hand->suitCount[gTrumpSuit]) { // таки есть tmp = hand->suitStart[gTrumpSuit]; if (tmp < crdNo) break; // всё, нечего больше искать if (tmp > crdNo) { // скипаем crdNo = tmp; continue; } // вот этой и ходим goto doMove; } else { // не, и козырей нет, можно кидать чо попало goto doMove; } } else { // игра бескозырная, тут любая карта пойдёт, хули goto doMove; } doMove: /* movesChecked++; if (firstm < 0) firstm = crdNo; */ // проскипаем последовательность из плавно убывающих карт одной масти // очевидно, что при таком раскладе похуй, какой из них ходить int scnt = hand->suitCount[crdSuit]; if (scnt > 1) { // в этой масти есть ещё карты // проверим, есть ли у кого ещё эта масть if (xHands[0].suitCount[crdSuit]+xHands[1].suitCount[crdSuit]+xHands[2].suitCount[crdSuit] <= scnt) { // единственный гордый владелец этой масти; пробуем только одну её карту int tsuit = crdSuit+1; while (tsuit <= 3 && hand->suitCount[tsuit] == 0) tsuit++; crdNext = tsuit>3 ? 11 : hand->suitStart[tsuit]; } else { // такая масть есть ещё у кого-то int tface = crdFace+1; while (crdNext <= 10 && hand->suits[crdNext] == crdSuit && hand->faces[crdNext] == tface) { crdNext++; tface++; } } } // кидаем карту на стол xDeskSuits[turn] = crdSuit; xDeskFaces[turn] = crdFace; // убираем карту из руки hand->suitCount[crdSuit]--; if (crdNo == hand->suitStart[crdSuit]) hand->suitStart[crdSuit]++; hand->faces[crdNo] = 0; //lastMoveF = crdFace; lastMoveS = crdSuit; int y, z, x; if (turn == 2) { // the turn is done, count tricks //who = whoTakes(pdesk, gTrumpSuit); // а кто, собственно, забрал? if (gTrumpSuit <= 3) { // trump game if (xDeskSuits[0] == gTrumpSuit) { // нулевой козырнул who = 0; tmp = xDeskFaces[0]; if (xDeskSuits[1] == xDeskSuits[0] && xDeskFaces[1] > tmp) { tmp = xDeskFaces[1]; who = 1; } if (xDeskSuits[2] == xDeskSuits[0] && xDeskFaces[2] > tmp) who = 2; } else if (xDeskSuits[1] == gTrumpSuit) { // первый козырнул who = 1; tmp = xDeskFaces[0]; if (xDeskSuits[2] == xDeskSuits[1] && xDeskFaces[2] > tmp) who = 2; } else if (xDeskSuits[2] == gTrumpSuit) { // второй козырнул who = 2; } else { // никто не козырял who = 0; tmp = xDeskFaces[0]; if (xDeskSuits[1] == xDeskSuits[0] && xDeskFaces[1] > tmp) { tmp = xDeskFaces[1]; who = 1; } if (xDeskSuits[2] == xDeskSuits[0] && xDeskFaces[2] > tmp) who = 2; } } else { // notrump game who = 0; tmp = xDeskFaces[0]; if (xDeskSuits[1] == xDeskSuits[0] && xDeskFaces[1] > tmp) { tmp = xDeskFaces[1]; who = 1; } if (xDeskSuits[2] == xDeskSuits[0] && xDeskFaces[2] > tmp) who = 2; } who = (who+player+1)%3; xHands[who].tricks++; // прибавили взятку #ifdef ABDEBUG printf("==%i takes; cards left: %i; turn: %i\n", who, xCardsLeft, turn); printStatus(turn, player, 1); #endif //if (xCardsLeft < 0) abort(); Q_ASSERT(xCardsLeft >= 0); if (!xCardsLeft) { // всё, отбомбились, даёшь коэффициенты gIterations++; if (gIterations%1000000 == 0) { if (stTime.elapsed() >= 5000) { stTime.start(); //cTime = getTimeMs(); //fprintf(stderr, "\r%i (%i seconds)\x1b[K", gIterations, (int)((cTime-xStTime)/1000)); fprintf(stderr, "\r%i\x1b[K", gIterations); } } /* y = xHands[newPlayer].tricks; z = xHands[(newPlayer+1)%3].tricks; x = xHands[(newPlayer+2)%3].tricks; */ x = xHands[player].tricks; y = xHands[newPlayer].tricks; z = xHands[(player+2)%3].tricks; if (gPassOutOrMisere) { x = 10-x; y = 10-y; z = 10-z; } #ifdef ADVANCED_RES if (player == gWhoPlays) { // я играю; выиграл ли? if (x < gGameBid) { // нет, обезлаплен x = -gGameBid-1; /*y = z = 666;*/ } else { // да, взял своё x = 20+gGameBid; /* switch (gGameBid) { case 6: if (y < 2) y = -666+y; // bad if (z < 2) z = -666+z; // bad break; case 7: case 8: case 9: if (y < 1) y = -666+y; // bad if (z < 1) z = -666+z; // bad break; } */ } } else { // я вистую; получилось ли? if (xHands[gWhoPlays].tricks < gGameBid) { // по любому засадили чувачка //x = 666-(gGameBid-xHands[gWhoPlays].tricks); // на сколько // чувак в жопе if (gWhoPlays == newPlayer) { //y = -xHands[gWhoPlays].tricks-1; //z = 666; } else { //z = -xHands[gWhoPlays].tricks-1; //y = 666; } } else { // нет, чувак, увы, взял своё; а я? /* switch (gGameBid) { case 6: if (x < 2) x = -15-x; else x = 15+x; break; case 7: case 8: case 9: if (x < 1) x = -15-x; else x = 15+x; break; } if (gWhoPlays == newPlayer) { y = 666; switch (gGameBid) { case 6: if (z < 2) z = -15-z; else z = 15+z; break; case 7: case 8: case 9: if (z < 1) z = -15-z; else z = 15+z; break; } } else { z = 666; switch (gGameBid) { case 6: if (y < 2) y = -15-y; else y = 15+y; break; case 7: case 8: case 9: if (y < 1) y = -15-y; else y = 15+y; break; } } */ } } #endif //printStatus(2, player, 0); } else { // рекурсивно проверяем дальше //abcPrune(newTurn, newPlayer, -c, -a, b, &y, &z, &x, NULL); if (who == player) { // я же и забрал, снова здорово abcPrune(0, player, a, b, c, &x, &y, &z, NULL); } else if (who == newPlayer) { // следующий забрал; красота и благолепие abcPrune(0, newPlayer, -c, -a, b, &y, &z, &x, NULL); } else { // предыдущий забрал; вот такие вот параметры вышли; путём трэйсинга, да abcPrune(0, who, -b, c, -a, &z, &x, &y, NULL); } } // брали взятку? восстановим статус кво xHands[who].tricks--; } else { // рекурсивно проверяем дальше abcPrune(newTurn, newPlayer, -c, -a, b, &y, &z, &x, NULL); } // восстановим стол xDeskFaces[0] = sDeskFaces[0]; xDeskFaces[1] = sDeskFaces[1]; xDeskFaces[2] = sDeskFaces[2]; xDeskSuits[0] = sDeskSuits[0]; xDeskSuits[1] = sDeskSuits[1]; xDeskSuits[2] = sDeskSuits[2]; // вернём в руку карту hand->suitCount[crdSuit]++; hand->faces[crdNo] = crdFace; if (crdNo+1 == hand->suitStart[crdSuit]) hand->suitStart[crdSuit]--; // проверим, чо нашли if (bestm >= 0 && x == bestx) { // we've found an equivalent move //if (bestm < 0) abort(); n++; if (y < worsty) worsty = y; if (z < worstz) worstz = z; //if (myrand()%n == n-1) bestm = crdNo; // hands are sorted, so take the smallest possible card if (bestm < 0 || crdFace < hand->faces[bestm]) bestm = crdNo; } else if (x > bestx) { // we've found a better move n = 1; bestm = crdNo; bestx = x; worsty = y; worstz = z; if (x > b || x > c) break; // всё, дальше искать не надо, всё равно мы крутые; goto done; if (x > a) a = x; } // берём следующую карту crdNo = crdNext; } xDeskFaces[0] = sDeskFaces[0]; xDeskFaces[1] = sDeskFaces[1]; xDeskFaces[2] = sDeskFaces[2]; xDeskSuits[0] = sDeskSuits[0]; xDeskSuits[1] = sDeskSuits[1]; xDeskSuits[2] = sDeskSuits[2]; if (turn == 2) { xCardsLeft++; } *ra = bestx; *rb = worsty; *rc = worstz; if (rm) *rm = bestm; /* if (rm) *rm = bestm>=0?bestm:firstm; if (bestm < 0) { fprintf(stderr, "first: %i (%i)\n", firstm, movesChecked); } */ //lastMoveF = lmF; lastMoveS = lmS; }
/* * BIG MACHINE */ std::list<LabelPosition*>* Pal::labeller( int nbLayers, char **layersName, double *layersFactor, double scale, double bbox[4], PalStat **stats, bool displayAll ) { #ifdef _DEBUG_ std::cout << "LABELLER (selection)" << std::endl; #endif Problem *prob; SearchMethod old_searchMethod = searchMethod; if ( displayAll ) { setSearch( POPMUSIC_TABU ); } #ifdef _VERBOSE_ clock_t start = clock(); double create_time; std::cout << std::endl << "bbox: " << bbox[0] << " " << bbox[1] << " " << bbox[2] << " " << bbox[3] << std::endl; #endif #ifdef _EXPORT_MAP_ // TODO this is not secure std::ofstream svgmap( "pal-map.svg" ); svgmap << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" << std::endl << "<svg" << std::endl << "xmlns:dc=\"http://purl.org/dc/elements/1.1/\"" << std::endl << "xmlns:cc=\"http://creativecommons.org/ns#\"" << std::endl << "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"" << std::endl << "xmlns:svg=\"http://www.w3.org/2000/svg\"" << std::endl << "xmlns=\"http://www.w3.org/2000/svg\"" << std::endl << "xmlns:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"" << std::endl << "xmlns:inkscape=\"http://www.inkscape.org/namespaces/inkscape\"" << std::endl << "width=\"" << convert2pt( bbox[2] - bbox[0], scale, dpi ) << "\"" << std::endl << "height=\"" << convert2pt( bbox[3] - bbox[1], scale, dpi ) << "\">" << std::endl; // TODO xmax ymax #endif QTime t; t.start(); // First, extract the problem // TODO which is the minimum scale? (> 0, >= 0, >= 1, >1 ) if ( scale < 1 || ( prob = extract( nbLayers, layersName, layersFactor, bbox[0], bbox[1], bbox[2], bbox[3], scale, #ifdef _EXPORT_MAP_ & svgmap #else NULL #endif ) ) == NULL ) { #ifdef _VERBOSE_ if ( scale < 1 ) std::cout << "Scale is 1:" << scale << std::endl; else std::cout << "empty problem... finishing" << std::endl; #endif #ifdef _EXPORT_MAP_ svgmap << "</svg>" << std::endl; svgmap.close(); #endif // nothing to be done => return an empty result set if ( stats ) ( *stats ) = new PalStat(); return new std::list<LabelPosition*>(); } std::cout << "PAL EXTRACT: " << t.elapsed() / 1000.0 << " s" << std::endl; t.restart(); // reduce number of candidates // (remove candidates which surely won't be used) prob->reduce(); #ifdef _VERBOSE_ std::cerr << prob->nblp << "\t" << prob->nbOverlap; #endif prob->displayAll = displayAll; #ifdef _VERBOSE_ create_time = double( clock() - start ) / double( CLOCKS_PER_SEC ); std::cout << std::endl << "Problem : " << prob->nblp << " candidates for " << prob->nbft << " features makes " << prob->nbOverlap << " overlaps" << std::endl; std::cout << std::endl << "Times:" << std::endl << " to create problem: " << create_time << std::endl; #endif // search a solution if ( searchMethod == FALP ) prob->init_sol_falp(); else if ( searchMethod == CHAIN ) prob->chain_search(); else prob->popmusic(); std::cout << "PAL SEARCH (" << searchMethod << "): " << t.elapsed() / 1000.0 << " s" << std::endl; t.restart(); // Post-Optimization //prob->post_optimization(); std::list<LabelPosition*> * solution = prob->getSolution( displayAll ); if ( stats ) *stats = prob->getStats(); #ifdef _EXPORT_MAP_ prob->drawLabels( svgmap ); svgmap << "</svg>" << std::endl; svgmap.close(); #endif #ifdef _VERBOSE_ clock_t total_time = clock() - start; std::cout << " Total time: " << double( total_time ) / double( CLOCKS_PER_SEC ) << std::endl; std::cerr << "\t" << create_time << "\t" << double( total_time ) / double( CLOCKS_PER_SEC ) << std::endl; #endif delete prob; if ( displayAll ) { setSearch( old_searchMethod ); } return solution; }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); //Command line arguments TCLAP::CmdLine cmd("GOBLET (c) 2012, International Livestock Research Institute (ILRI) \n Developed by Carlos Quiros ([email protected])", ' ', "1.0 (Beta 1)"); //Required arguments TCLAP::ValueArg<std::string> databaseArg("d","database","Database name",true,"","string"); TCLAP::ValueArg<std::string> datasetArg("t","datasets","Datasets to combine. For example: 'dataset1,dataset2,dataset3,....'",true,"","string"); //Non required arguments TCLAP::ValueArg<std::string> pathArg("a","path","Path to database. Default .",false,".","string"); TCLAP::ValueArg<std::string> hostArg("H","host","Connect to host. Default localhost",false,"localhost","string"); TCLAP::ValueArg<std::string> portArg("P","port","Port number to use. Default 3306",false,"3306","string"); TCLAP::ValueArg<std::string> userArg("u","user","User. Default empty",false,"","string"); TCLAP::ValueArg<std::string> passArg("p","password","Passwork. Default no password",false,"","string"); TCLAP::ValueArg<std::string> extentArg("e","extent","Extent: '(upperLeft degrees lat,log) (lowerRight degrees lat,log)'",false,"","string"); TCLAP::ValueArg<std::string> shpConstraintArg("S","constraintbyshapes","Constraint classification using shapes: ShapeDataSet:shapeID,ShapeID,....",false,"","string"); TCLAP::ValueArg<std::string> functionArg("f","combfunction","Combination function sum or (mul)tiplication Default sum",false,"sum","string"); TCLAP::ValueArg<std::string> targetDatasetArg("T","targetDataset","Target dataset if stored. Default combinationoutput",false,"combinationoutput","string"); TCLAP::ValueArg<std::string> targetDatasetDescArg("s","targetDatasetDesc","Description of target dataset if stored. Default: Result of combination ...",false,"Result of combination ...","string"); //Switches TCLAP::SwitchArg remoteSwitch("r","remote","Connect to remote host", cmd, false); TCLAP::SwitchArg storeSwitch("o","store","Store the combination as a dataset", cmd, false); TCLAP::SwitchArg overWriteSwitch("O","overwrite","Overwrite dataset if exists", cmd, false); cmd.add(databaseArg); cmd.add(datasetArg); cmd.add(pathArg); cmd.add(hostArg); cmd.add(portArg); cmd.add(userArg); cmd.add(passArg); cmd.add(extentArg); cmd.add(shpConstraintArg); cmd.add(functionArg); cmd.add(targetDatasetArg); cmd.add(targetDatasetDescArg); //Parsing the command lines cmd.parse( argc, argv ); //Getting the variables from the command bool remote = remoteSwitch.getValue(); bool store = storeSwitch.getValue(); bool overwrite = overWriteSwitch.getValue(); QString path = QString::fromUtf8(pathArg.getValue().c_str()); QString dbName = QString::fromUtf8(databaseArg.getValue().c_str()); QString host = QString::fromUtf8(hostArg.getValue().c_str()); QString port = QString::fromUtf8(portArg.getValue().c_str()); QString userName = QString::fromUtf8(userArg.getValue().c_str()); QString password = QString::fromUtf8(passArg.getValue().c_str()); QString tableName = QString::fromUtf8(datasetArg.getValue().c_str()); QString extent = QString::fromUtf8(extentArg.getValue().c_str()); QString shapes = QString::fromUtf8(shpConstraintArg.getValue().c_str()); QString function = QString::fromUtf8(functionArg.getValue().c_str()); QString targetDataset = QString::fromUtf8(targetDatasetArg.getValue().c_str()); QString targetDatasetDesc = QString::fromUtf8(targetDatasetDescArg.getValue().c_str()); myDBConn con; QSqlDatabase mydb; if (!remote) { QDir dir; dir.setPath(path); if (con.connectToDB(dir.absolutePath()) == 1) { if (!dir.cd(dbName)) { gbtLog(QObject::tr("The database does not exists")); con.closeConnection(); return 1; } mydb = QSqlDatabase::addDatabase(con.getDriver(),"connection1"); } } else { mydb = QSqlDatabase::addDatabase("QMYSQL","connection1"); mydb.setHostName(host); mydb.setPort(port.toInt()); if (!userName.isEmpty()) mydb.setUserName(userName); if (!password.isEmpty()) mydb.setPassword(password); } mydb.setDatabaseName(dbName); if (!mydb.open()) { gbtLog(QObject::tr("Cannot open database")); con.closeConnection(); return 1; } else { if (function.isEmpty()) function = "sum"; if (function != "sum" && function != "mul") { gbtLog(QObject::tr("Invalid function.")); return 1; } if (!tableName.contains(",")) { gbtLog(QObject::tr("You need to indicate two or more classified datasets")); mydb.close(); con.closeConnection(); return 1; } QStringList dataSets; getDataSetList(tableName,dataSets); if (dataSets.count() < 2) { gbtLog(QObject::tr("You need to indicate two or more classified datasets")); mydb.close(); con.closeConnection(); return 1; } if (dataSets.count() > 20 && function == "sum") { gbtLog(QObject::tr("You cannot classify more than 20 datasets using sum as function")); mydb.close(); con.closeConnection(); return 1; } QStringList letters; letters.append("A"); letters.append("B"); letters.append("C"); letters.append("D"); letters.append("E"); letters.append("F"); letters.append("G"); letters.append("H"); letters.append("I"); letters.append("J"); letters.append("K"); letters.append("L"); letters.append("M"); letters.append("N"); letters.append("O"); letters.append("P"); letters.append("Q"); letters.append("R"); letters.append("S"); letters.append("T"); QTime procTime; procTime.start(); QString sqlSelect; QSqlQuery qry(mydb); sqlSelect = "SELECT T" + letters[0] + ".geokey,"; sqlSelect = sqlSelect + "T" + letters[0] + ".xpos,"; sqlSelect = sqlSelect + "T" + letters[0] + ".ypos,"; sqlSelect = sqlSelect + "("; int pos; for (pos = 0; pos <= dataSets.count()-1;pos++) { if (function == "sum") sqlSelect = sqlSelect + "T" + letters[pos] + ".classCode + "; else sqlSelect = sqlSelect + "T" + letters[pos] + ".classCode * "; } sqlSelect = sqlSelect.left(sqlSelect.length()-3) + ") as comCode"; QString sqlFrom; sqlFrom = " FROM "; for (pos = 0; pos <= dataSets.count()-1;pos++) { sqlFrom = sqlFrom + dataSets[pos] + " T" + letters[pos] + ","; } sqlFrom = sqlFrom.left(sqlFrom.length()-1); QString extentWhere; if (!extent.isEmpty()) extentWhere = getWhereClauseFromExtent(extent,mydb,dataSets[0]); QString shapeFromSQL; QString shapeWhereSQL; QString shapeClause; if (!shapes.isEmpty()) { shapeClause = getShapeClause(shapes,mydb); if (!shapeClause.isEmpty()) { QString sqlcreate; sqlcreate = "CREATE TEMPORARY TABLE tmpshapes ("; sqlcreate = sqlcreate + "geokey VARCHAR(14) NOT NULL ,"; sqlcreate = sqlcreate + "PRIMARY KEY (geokey))"; sqlcreate = sqlcreate + " ENGINE = MyISAM"; if (qry.exec(sqlcreate)) { QString extentClause; extentClause = extentWhere; extentClause.replace("TA.",""); if (!extentClause.isEmpty()) sqlcreate = "INSERT INTO tmpshapes " + shapeClause + " AND " + extentClause; else sqlcreate = "INSERT INTO tmpshapes " + shapeClause; gbtLog(QObject::tr("Preselecting shapes")); if (qry.exec(sqlcreate)) { shapeFromSQL = ", tmpshapes TK"; shapeWhereSQL = " TA.geokey = TK.geokey"; } else { gbtLog(QObject::tr("Cannot insert temporary shapes.")); gbtLog(qry.lastError().databaseText()); } } else { gbtLog(QObject::tr("Cannot shapes temporary table.")); gbtLog(qry.lastError().databaseText()); } } } sqlFrom = sqlFrom + shapeFromSQL; //Link the tables QString sqlWhere; sqlWhere = " WHERE "; for (pos = 1; pos <= dataSets.count()-1;pos++) { sqlWhere = sqlWhere + "T" + letters[pos-1] + ".geokey = ";\ sqlWhere = sqlWhere + "T" + letters[pos] + ".geokey AND "; } if (!extentWhere.isEmpty()) sqlWhere = sqlWhere + extentWhere + " AND "; if (!shapeWhereSQL.isEmpty()) sqlWhere = sqlWhere + shapeWhereSQL + " AND "; ////Append the not null //for (pos = 0; pos <= dataSets.count()-1;pos++) // { // sqlWhere = sqlWhere + "T" + letters[pos] + ".classCode IS NOT NULL AND "; // } sqlWhere = sqlWhere.left(sqlWhere.length()-5); QString sql; sql = sqlSelect + sqlFrom + sqlWhere; sql = "INSERT INTO combdataset (geokey,xpos,ypos,comCode) " + sql; gbtLog("Deleting previous combination"); QString sql2; sql2 = "DELETE FROM combdataset"; if (qry.exec(sql2)) { sql2 = "ALTER TABLE combdataset DISABLE KEYS"; if (qry.exec(sql2)) { bool error; QString dberror; gbtLog("Combining datasets. Please wait...."); if (qry.exec(sql)) { error = false; sql2 = "ALTER TABLE combdataset ENABLE KEYS"; if (!qry.exec(sql2)) { gbtLog("Unable to enable keys in combination table"); mydb.close(); con.closeConnection(); return 1; } } else { dberror = qry.lastError().databaseText(); error = true; } if (error) { sql2 = "ALTER TABLE combdataset ENABLE KEYS"; if (!qry.exec(sql2)) { gbtLog("Unable to enable keys in combination table"); mydb.close(); con.closeConnection(); return 1; } gbtLog("Unable to combine datasets"); gbtLog(dberror); mydb.close(); con.closeConnection(); return 1; } } else { gbtLog("Unable to disable keys in combination table"); mydb.close(); con.closeConnection(); return 1; } } else { gbtLog("Unable to delete preivous combinations"); mydb.close(); con.closeConnection(); return 1; } if (store) { gbtLog("Storing combination as a dataset"); if (overwrite) { sql = "DROP TABLE IF EXISTS " + targetDataset; qry.exec(sql); sql = "DELETE FROM datasetinfo WHERE dataset_id = '" + targetDataset + "'"; if (!qry.exec(sql)) { gbtLog(QObject::tr("Cannot remove previous dataset.")); gbtLog(qry.lastError().databaseText()); mydb.close(); con.closeConnection(); return 1; } } sql = "CREATE TABLE " + targetDataset + " ("; sql = sql + "geokey VARCHAR(14) NOT NULL ,"; sql = sql + "xpos DECIMAL(7) NULL ,"; sql = sql + "ypos DECIMAL(7) NULL ,"; sql = sql + "cellvalue DECIMAL(14,5) NULL DEFAULT -9999 ,"; sql = sql + "classCode BIGINT NULL DEFAULT NULL ,"; //sql = sql + "classColour VARCHAR(9) NULL DEFAULT NULL ,"; //, sql = sql + "PRIMARY KEY (geokey) ,"; sql = sql + "INDEX " + targetDataset + "_IDXVALUE (cellvalue ASC)) ENGINE = MyISAM"; if (!qry.exec(sql)) { gbtLog(QObject::tr("Cannot create dataset. It might already exists")); gbtLog(qry.lastError().databaseText()); mydb.close(); con.closeConnection(); return 1; } sql = "ALTER TABLE " + targetDataset + " DISABLE KEYS"; if (!qry.exec(sql)) { gbtLog(QObject::tr("Cannot disable keys")); gbtLog(qry.lastError().databaseText()); mydb.close(); con.closeConnection(); return 1; } sql = "INSERT INTO " + targetDataset + " (geokey,xpos,ypos,cellvalue) SELECT geokey,xpos,ypos,comCode FROM combdataset"; if (!qry.exec(sql)) { gbtLog(QObject::tr("Unable to store combination")); gbtLog(qry.lastError().databaseText()); mydb.close(); con.closeConnection(); return 1; } sql = "ALTER TABLE " + targetDataset + " ENABLE KEYS"; if (!qry.exec(sql)) { gbtLog(QObject::tr("Cannot enable keys")); gbtLog(qry.lastError().databaseText()); mydb.close(); con.closeConnection(); return 1; } int ncols; int nrows; double xllCenter; double yllCenter; double dbCellSize; int bottom; int left; if (!extent.isEmpty()) { if (getGridValuesFromExtent(extent,mydb,dbCellSize,xllCenter,yllCenter,ncols,nrows,bottom,left)) { gbtLog(QObject::tr("Error in extent")); gbtLog(qry.lastError().databaseText()); mydb.close(); con.closeConnection(); return 1; } } else { if (!shapes.isEmpty()) { if (calcBoundFromShapes(shapes,mydb,dbCellSize,xllCenter,yllCenter,ncols,nrows,bottom,left)) { gbtLog(QObject::tr("Error in constraining shapes")); gbtLog(qry.lastError().databaseText()); mydb.close(); con.closeConnection(); return 1; } } else { if (calcExtendFromGrid(firstGrid,mydb,dbCellSize,xllCenter,yllCenter,ncols,nrows,bottom,left)) { gbtLog(QObject::tr("Error in grid extent")); gbtLog(qry.lastError().databaseText()); mydb.close(); con.closeConnection(); return 1; } } } sql = "select count(distinct xpos),count(distinct ypos) from " + targetDataset; if (!qry.exec(sql)) { gbtLog(QObject::tr("Cannot read dataset.")); gbtLog(qry.lastError().databaseText()); mydb.close(); con.closeConnection(); return 1; } qry.first(); ncols = qry.value(0).toInt(); nrows = qry.value(1).toInt(); sql = "select min(xpos),max(ypos) from " + targetDataset; if (!qry.exec(sql)) { gbtLog(QObject::tr("Cannot read dataset.")); gbtLog(qry.lastError().databaseText()); mydb.close(); con.closeConnection(); return 1; } qry.first(); int xpos; int ypos; xpos = qry.value(0).toInt() -1; ypos = qry.value(1).toInt() -1; sql = "INSERT INTO datasetinfo (dataset_id,dataset_desc,dataset_type,ncols,nrows,xllcenter,yllcenter)"; sql = sql + " VALUES ('" + targetDataset +"',"; sql = sql + "'" + targetDatasetDesc +"',1,"; sql = sql + QString::number(ncols) + ","; sql = sql + QString::number(nrows) + ","; sql = sql + QString::number(((xpos * dbCellSize) - 180),'f',15) + ","; sql = sql + QString::number((90 - (ypos * dbCellSize)),'f',15) + ")"; // + 0.0200 so its reduce if (!qry.exec(sql)) { gbtLog(QObject::tr("Cannot insert dataset.")); gbtLog(qry.lastError().databaseText()); mydb.close(); con.closeConnection(); return 1; } } int Hours; int Minutes; int Seconds; int Milliseconds; Milliseconds = procTime.elapsed(); Hours = Milliseconds / (1000*60*60); Minutes = (Milliseconds % (1000*60*60)) / (1000*60); Seconds = ((Milliseconds % (1000*60*60)) % (1000*60)) / 1000; gbtLog("Finished in " + QString::number(Hours) + " Hours," + QString::number(Minutes) + " Minutes and " + QString::number(Seconds) + " Seconds."); mydb.close(); con.closeConnection(); return 0; } return 0; }
//////////////////////////////////////////////////////////////////////////////// // M A I N //////////////////////////////////////////////////////////////////////////////// int main(int argc, char **argv) { QString mode; QStringList Argv; for (int i = 1; i <= argc; i++) { Argv << argv[i]; } if( argc < 2 ) { char *prog = basename(argv[0]); cout << "NMEA GPS Simulator 1.6.0 for Cumulus, 2003-2008 E. Voellm, 2009-2014 A. Pauli (GPL)" << endl << endl << "Usage: " << prog << " str|cir|pos|gpos|nplay|iplay [params]" << endl << endl << "Parameters: str: Straight Flight "<< endl << " cir: Circling "<< endl << " pos: Fixed Position e.g. standstill in a wave (climb works)"<< endl << " gpos: Fixed Position on ground "<< endl << " nplay: Plays a recorded NMEA file. GPRMC is required to be contained!" << endl << " iplay: Plays a recorded IGC file." << endl << " params:"<< endl << " lat=dd:mm:ss[N|S] or lat=dd.mmmm Initial Latitude" << endl << " lon=ddd:mm:ss[E|W] or lon=dd.mmmm Initial Longitude" << endl << " speed=[km/h] head=[deg]: Glider speed and heading" << endl << " wind=[km/h] winddir=[deg]: Wind force and direction" << endl << " radius=[m]: needed for circling" << endl << " dir=[right|left]: Direction of Circle" << endl << " alt=[m]: Altitude of Glider" << endl << " climb=[m/s]: Climbrate" << endl << " sentence0...9='NMEA sentence without checksum': $ and * can be omitted" << endl << " time=[s]: duration of operation" << endl << " pause=[ms]: pause between to send periods" << endl << " device=[path to named pipe]: write into this pipe, default is /tmp/nmeasim" << endl << " device=[ttySx,<speed>]: write to device ttySx with the given speed" << endl << " file=[path to file]: to be played" << endl << " skip=[number]: lines to be skipped in the play file" << endl << " start=[HHMMSS]: goto B-Record start time in the IGC play file" << endl << " factor=[number]: time factor used by IGC file play, default is 1" << endl << " Note: all values can also be specified as float, like 110.5 " << endl << endl << "Example: " << prog << " str lat=48:31:48N lon=009:24:00E speed=125 winddir=270" << endl << endl << "NMEA output is written into named pipe '" << device.toLatin1().data() << "'." << endl << "Cumulus should use the same device name to get these data." << endl; exit (0); } mode = Argv[0]; qDebug() << "mode=" << mode; // @AP: Reset the locale that is used for number formatting to "C" locale. setlocale( LC_ALL, "" ); setlocale( LC_NUMERIC, "C" ); setenv( "LC_NUMERIC", "C", 1 ); setenv( "LANG", "C", 1 ); // First of all read command configuration from file. // Determine configuration file position. It is normally stored in the home // directory of the user. const char *home = getenv("HOME"); if( home ) { confFile = QString(home) + "/nmea.cfg"; } else { confFile = "./nmea.cfg"; } readConfig(); // Override by things given at command line cout << "\nParameters from command line:" << endl; for (int i = 1; i < argc; i++) { cout << Argv[i].toLatin1().data() << endl; scanConfig( Argv[i] ); } // calculate Wind as it was given cout << "Parameters for operation:" << endl; float winddirTrue = winddir+180; if ( winddirTrue > 360.0 ) winddirTrue -= 360.0; if( mode == "str" ) cout << "Mode: Straight Flight " << endl; if( mode == "cir" ) cout << "Mode: Circling " << endl; if( mode == "gpos" ) { cout << "Mode: Fixed Ground Position " << endl; if( !gotAltitude) altitude = 100.0; // lower default Altitude } if( mode == "pos" ) { cout << "Mode: Fixed Position in Flight (Standstill in a wave) " << endl; } const int fifo = init_io(); if( fifo < 0 ) { return -1; // device error } if( mode == "nplay" ) { cout << "Mode: Play a recorded NMEA file" << endl; cout << "File: " << playFile.toLatin1().data() << endl; cout << "Skip: " << skip << endl; cout << "Pause: " << Pause << " ms" << endl; cout << "Device: " << device.toLatin1().data() << endl; NmeaPlay play( playFile, fifo ); play.startPlaying(skip, Pause); close( fifo ); // safe current parameters to file safeConfig(); return 0; } else if( mode == "iplay" ) { cout << "Mode: Play a recorded IGC file" << endl; cout << "File: " << playFile.toLatin1().data() << endl; cout << "Skip: " << skip << endl; cout << "Start: " << igcStartTime.toLatin1().data() << endl; cout << "Factor: " << playFactor << endl; cout << "Device: " << device.toLatin1().data() << endl; IgcPlay play( playFile, fifo ); play.startPlaying( igcStartTime, skip, playFactor ); // safe current parameters to file safeConfig(); return 0; } cout << "Latitude: " << lat << endl; cout << "Longitude: " << lon << endl; cout << "Speed: " << speed << " km/h" << endl; cout << "Heading: " << heading << " deg" << endl; cout << "Wind: " << wind << " km/h" << endl; cout << "Winddir: " << winddir << " deg" << endl; cout << "Altitude: " << altitude << " m" << endl; cout << "Radius: " << radius << " m (if circling)" << endl; cout << "Direction: " << direction.toLatin1().data() << " Turn" << endl; cout << "Climbrate: " << climb << " m/s" << endl; cout << "Time: " << Time << " sec" << endl; cout << "Pause: " << Pause << " ms" << endl; cout << "Device: " << device.toLatin1().data() << endl; for( int i = 0; i < 10; i++ ) { QString key = QString("sentence%1: ").arg(i); if( ! sentences[i].isEmpty() ) { key += sentences[i]; cout << key.toLatin1().data() << endl; } } cout << endl; glider myGl( lat, lon, speed, heading, wind, winddirTrue, altitude, climb ); myGl.setFd( fifo ); myGl.setCircle( radius, direction ); // @AP: This is used for the GSA output simulation uint gsa = 0; QStringList satIds; satIds << "14" << "32" << "17" << "20" << "11" << "23" << "28" << "25" << "35"; QString pdop = "1.7"; QString hdop = "1.1"; QString vdop = "1.2"; QTime start = QTime::currentTime(); if( Pause < 100 ) { // Minimum is set to 100ms Pause = 100; } int nextTimeReporting = 0; while( start.elapsed() < Time*1000 ) { gsa++; if( nextTimeReporting < start.elapsed() ) { nextTimeReporting = start.elapsed() + 1000; cout << "Seconds remaining: " << Time - start.elapsed()/1000 << endl; } usleep( Pause * 1000 ); if( mode == "str" ) myGl.Straight(); if( mode == "cir" ) myGl.Circle(); if( mode == "pos" ) myGl.FixedPos(); if( mode == "gpos" ) myGl.FixedPosGround(); // GSA output simulation if( ! (gsa % 40) ) { satIds.clear(); satIds << "14" << "32" << "17" << "20" << "11" << "23" << "28" << "25" << "35"; pdop = "1.7"; hdop = "1.1"; vdop = "1.2"; } else if( ! (gsa % 30) ) { satIds.clear(); satIds << "32" << "17" << "20" << "11" << "23" << "28" << "25" << "35"; pdop = "1.5"; hdop = "1.3"; vdop = "1.7"; } else if( ! (gsa % 20) ) { satIds.clear(); satIds << "10" << "15" << "33" << "17" << "19" << "11" << "23" << "28" << "25" << "36"; pdop = "1.2"; hdop = "1.4"; satIds.clear(); satIds << "14" << "32" << "17" << "20" << "11" << "23" << "28" << "25" << "35"; pdop = "1.7"; hdop = "1.1"; vdop = "1.2"; vdop = "1.3"; } else if( ! (gsa % 10) ) { satIds.clear(); satIds << "14" << "32" << "17" << "20" << "11" << "23" << "28"; pdop = "1.9"; hdop = "1.3"; vdop = "1.5"; } GPGSA myGPGSA; myGPGSA.send( satIds, pdop, hdop, vdop, fifo ); for( int i = 0; i < 10; i++ ) { if( ! sentences[i].isEmpty() ) { Sentence mySentence; mySentence.send( sentences[i], fifo ); } } } // safe current parameters to file safeConfig(); close( fifo ); return 0; }
long long PrePostRollFlagger::findBreakInrange(long long startFrame, long long stopFrame, long long totalFrames, long long &framesProcessed, QTime &flagTime, bool findLast) { float flagFPS; int requiredBuffer = 30; long long currentFrameNumber; int prevpercent = -1; if(startFrame > 0) startFrame--; else startFrame = 0; player->DiscardVideoFrame(player->GetRawVideoFrame(0)); long long tmpStartFrame = startFrame; VideoFrame* f = player->GetRawVideoFrame(tmpStartFrame); float aspect = player->GetVideoAspect(); currentFrameNumber = f->frameNumber; LOG(VB_COMMFLAG, LOG_INFO, QString("Starting with frame %1") .arg(currentFrameNumber)); player->DiscardVideoFrame(f); long long foundFrame = 0; while (!player->GetEof()) { struct timeval startTime; if (stillRecording) gettimeofday(&startTime, NULL); VideoFrame* currentFrame = player->GetRawVideoFrame(); currentFrameNumber = currentFrame->frameNumber; if(currentFrameNumber % 1000 == 0) { LOG(VB_COMMFLAG, LOG_INFO, QString("Processing frame %1") .arg(currentFrameNumber)); } if(currentFrameNumber > stopFrame || (!findLast && foundFrame)) { player->DiscardVideoFrame(currentFrame); break; } double newAspect = currentFrame->aspect; if (newAspect != aspect) { SetVideoParams(aspect); aspect = newAspect; } if (((currentFrameNumber % 500) == 0) || (((currentFrameNumber % 100) == 0) && (stillRecording))) { emit breathe(); if (m_bStop) { player->DiscardVideoFrame(currentFrame); return false; } } while (m_bPaused) { emit breathe(); sleep(1); } // sleep a little so we don't use all cpu even if we're niced if (!fullSpeed && !stillRecording) usleep(10000); if (((currentFrameNumber % 500) == 0) || ((showProgress || stillRecording) && ((currentFrameNumber % 100) == 0))) { float elapsed = flagTime.elapsed() / 1000.0; if (elapsed) flagFPS = framesProcessed / elapsed; else flagFPS = 0.0; int percentage; if (stopFrame) percentage = framesProcessed * 100 / totalFrames; else percentage = 0; if (percentage > 100) percentage = 100; if (showProgress) { if (stopFrame) { QString tmp = QString("\b\b\b\b\b\b\b\b\b\b\b%1%/%2fps") .arg(percentage, 3).arg((int)flagFPS, 3); QByteArray ba = tmp.toAscii(); cerr << ba.constData() << flush; } else { QString tmp = QString("\b\b\b\b\b\b\b\b\b\b\b\b\b%1/%2fps") .arg(currentFrameNumber, 6).arg((int)flagFPS, 3); QByteArray ba = tmp.toAscii(); cerr << ba.constData() << flush; } cerr.flush(); } if (stopFrame) emit statusUpdate(QObject::tr("%1% Completed @ %2 fps.") .arg(percentage).arg(flagFPS)); else emit statusUpdate(QObject::tr("%1 Frames Completed @ %2 fps.") .arg((long)currentFrameNumber).arg(flagFPS)); if (percentage % 10 == 0 && prevpercent != percentage) { prevpercent = percentage; LOG(VB_GENERAL, LOG_INFO, QString("%1%% Completed @ %2 fps.") .arg(percentage) .arg(flagFPS)); } } ProcessFrame(currentFrame, currentFrameNumber); if(frameInfo[currentFrameNumber].flagMask & (COMM_FRAME_SCENE_CHANGE | COMM_FRAME_BLANK)) { foundFrame = currentFrameNumber; } if (stillRecording) { int secondsRecorded = recordingStartedAt.secsTo(MythDate::current()); int secondsFlagged = (int)(framesProcessed / fps); int secondsBehind = secondsRecorded - secondsFlagged; long usecPerFrame = (long)(1.0 / player->GetFrameRate() * 1000000); struct timeval endTime; gettimeofday(&endTime, NULL); long long usecSleep = usecPerFrame - (((endTime.tv_sec - startTime.tv_sec) * 1000000) + (endTime.tv_usec - startTime.tv_usec)); if (secondsBehind > requiredBuffer) { if (fullSpeed) usecSleep = 0; else usecSleep = (long)(usecSleep * 0.25); } else if (secondsBehind < requiredBuffer) usecSleep = (long)(usecPerFrame * 1.5); if (usecSleep > 0) usleep(usecSleep); } player->DiscardVideoFrame(currentFrame); framesProcessed++; } return foundFrame; }
FlowField_sV* FlowSourceOpenCV_sV::buildFlow(uint leftFrame, uint rightFrame, FrameSize frameSize) throw(FlowBuildingError) { #if CV_MAJOR_VERSION == 2 #ifdef HAVE_OPENCV_OCL if (ocl_device_index >= 0) { setupOclDevice(); } #endif #endif QString flowFileName(flowPath(leftFrame, rightFrame, frameSize)); /// \todo Check if size is equal if (!QFile(flowFileName).exists()) { QTime time; time.start(); QString prevpath = project()->frameSource()->framePath(leftFrame, frameSize); QString path = project()->frameSource()->framePath(rightFrame, frameSize); qDebug() << "Building flow for left frame " << leftFrame << " to right frame " << rightFrame << "; Size: " << frameSize; // check if file have been generated ! //TODO: maybe better error handling ? if (!QFile(prevpath).exists()) throw FlowBuildingError(QString("Could not read image " + prevpath)); if (!QFile(path).exists()) throw FlowBuildingError(QString("Could not read image " + path)); cv::Mat prevgray, gray; prevgray = cv::imread(prevpath.toStdString(), CV_LOAD_IMAGE_ANYDEPTH); gray = cv::imread(path.toStdString(), CV_LOAD_IMAGE_ANYDEPTH); #if CV_MAJOR_VERSION == 3 cv::UMat uprevgray, ugray; prevgray.copyTo(uprevgray); gray.copyTo(ugray); #endif { if (!prevgray.empty()) { #if CV_MAJOR_VERSION == 3 buildFlowOpenCV_3(uprevgray, ugray, flowFileName.toStdString()); #else #ifdef HAVE_OPENCV_OCL if (ocl_device_index >= 0) { buildFlowOpenCV_OCL(prevgray, gray, flowFileName.toStdString()); } else { buildFlowOpenCV_CPU(prevgray, gray, flowFileName.toStdString()); } #else buildFlowOpenCV_CPU(prevgray, gray, flowFileName.toStdString()); #endif #endif } else { qDebug() << "imread: Could not read image " << prevpath; throw FlowBuildingError(QString("imread: Could not read image " + prevpath)); } } qDebug() << "Optical flow built for " << flowFileName << " in " << time.elapsed() << " ms."; } else { qDebug().nospace() << "Re-using existing flow image for left frame " << leftFrame << " to right frame " << rightFrame << ": " << flowFileName; } try { return FlowRW_sV::load(flowFileName.toStdString()); } catch (FlowRW_sV::FlowRWError &err) { throw FlowBuildingError(err.message.c_str()); } }
bool PrePostRollFlagger::go() { int secsSince = 0; int requiredBuffer = 120; int requiredHeadStart = requiredBuffer; bool wereRecording = stillRecording; secsSince = startedAt.secsTo(MythDate::current()); while (stillRecording && (secsSince < requiredHeadStart)) { emit statusUpdate(QObject::tr("Waiting to pass preroll + head start")); emit breathe(); if (m_bStop) return false; sleep(5); secsSince = startedAt.secsTo(MythDate::current()); } if (player->OpenFile() < 0) return false; Init(); // Don't bother flagging short ~realtime recordings if ((wereRecording) && (!stillRecording) && (secsSince < requiredHeadStart)) return false; aggressiveDetection = gCoreContext->GetNumSetting("AggressiveCommDetect", 1); if (!player->InitVideo()) { LOG(VB_GENERAL, LOG_ERR, "NVP: Unable to initialize video for FlagCommercials."); return false; } player->EnableSubtitles(false); emit breathe(); if (m_bStop) return false; QTime flagTime; flagTime.start(); if (recordingStopsAt < MythDate::current() ) myTotalFrames = player->GetTotalFrameCount(); else myTotalFrames = (long long)(player->GetFrameRate() * (recordingStartedAt.secsTo(recordingStopsAt))); if (showProgress) { if (myTotalFrames) cerr << " 0%/ "; else cerr << " 0/ "; cerr.flush(); } float aspect = player->GetVideoAspect(); SetVideoParams(aspect); emit breathe(); long long stopFrame = preRoll + fps * 120; //look up to 2 minutes past long long framesToProcess = 0; if(preRoll) framesToProcess += stopFrame; if(postRoll) //guess two minutes before framesToProcess += myTotalFrames - postRoll + fps * 120; long long framesProcessed = 0; if(preRoll > 0) { //check from preroll after LOG(VB_COMMFLAG, LOG_INFO, QString("Finding closest after preroll(%1-%2)") .arg(preRoll).arg(stopFrame)); closestAfterPre = findBreakInrange(preRoll, stopFrame, framesToProcess, framesProcessed, flagTime, false); LOG(VB_COMMFLAG, LOG_INFO, QString("Closest after preroll: %1") .arg(closestAfterPre)); //check before preroll long long startFrame = 0; if(closestAfterPre) startFrame = preRoll - (closestAfterPre - preRoll) - 1; LOG(VB_COMMFLAG, LOG_INFO, QString("Finding before preroll (%1-%2)") .arg(startFrame).arg(preRoll)); closestBeforePre = findBreakInrange(startFrame, preRoll, framesToProcess, framesProcessed, flagTime, true); LOG(VB_COMMFLAG, LOG_INFO, QString("Closest before preroll: %1") .arg(closestBeforePre)); if(closestBeforePre || closestAfterPre) emit gotNewCommercialBreakList(); // for better processing percent framesToProcess -= (stopFrame - framesProcessed); } if(stillRecording) { while (MythDate::current() <= recordingStopsAt) { emit breathe(); if (m_bStop) return false; emit statusUpdate(QObject::tr("Waiting for recording to finish")); sleep(5); } stillRecording = false; myTotalFrames = player->GetTotalFrameCount(); } if(postRoll > 0) { //check from preroll after long long postRollStartLoc = myTotalFrames - postRoll; LOG(VB_COMMFLAG, LOG_INFO, QString("Finding closest after postroll(%1-%2)") .arg(postRollStartLoc).arg(myTotalFrames)); closestAfterPost = findBreakInrange(postRollStartLoc, myTotalFrames, framesToProcess, framesProcessed, flagTime, false); LOG(VB_COMMFLAG, LOG_INFO, QString("Closest after postRoll: %1") .arg(closestAfterPost)); //check before preroll long long startFrame = 0; if(closestAfterPost) startFrame = postRollStartLoc - (closestAfterPost - postRollStartLoc) - 1; LOG(VB_COMMFLAG, LOG_INFO, QString("finding closest before preroll(%1-%2)") .arg(startFrame).arg(postRollStartLoc)); closestBeforePost = findBreakInrange(startFrame, postRollStartLoc, framesToProcess, framesProcessed, flagTime, true); LOG(VB_COMMFLAG, LOG_INFO, QString("Closest before postroll: %1") .arg(closestBeforePost)); framesToProcess = framesProcessed; } if (showProgress) { //float elapsed = flagTime.elapsed() / 1000.0; //float flagFPS = (elapsed > 0.0f) ? (framesProcessed / elapsed) : 0.0f; if (myTotalFrames) cerr << "\b\b\b\b\b\b \b\b\b\b\b\b"; else cerr << "\b\b\b\b\b\b\b\b\b\b\b\b\b " "\b\b\b\b\b\b\b\b\b\b\b\b\b"; cerr.flush(); } return true; }
AlarmListViewItem::AlarmListViewItem(AlarmListView *parent, const KAEvent &event, const QDateTime &now) : EventListViewItemBase(parent, event), mMessageTruncated(false), mTimeToAlarmShown(false) { setLastColumnText(); // set the message column text DateTime dateTime = event.expired() ? event.startDateTime() : event.displayDateTime(); if(parent->column(AlarmListView::TIME_COLUMN) >= 0) setText(parent->column(AlarmListView::TIME_COLUMN), alarmTimeText(dateTime)); if(parent->column(AlarmListView::TIME_TO_COLUMN) >= 0) { QString tta = timeToAlarmText(now); setText(parent->column(AlarmListView::TIME_TO_COLUMN), tta); mTimeToAlarmShown = !tta.isNull(); } QTime t = dateTime.time(); mDateTimeOrder.sprintf("%04d%03d%02d%02d", dateTime.date().year(), dateTime.date().dayOfYear(), t.hour(), t.minute()); int repeatOrder = 0; int repeatInterval = 0; QString repeatText = event.recurrenceText(true); // text displayed in Repeat column if(repeatText.isEmpty()) repeatText = event.repetitionText(true); if(event.repeatAtLogin()) repeatOrder = 1; else { repeatInterval = event.recurInterval(); switch(event.recurType()) { case KARecurrence::MINUTELY: repeatOrder = 2; break; case KARecurrence::DAILY: repeatOrder = 3; break; case KARecurrence::WEEKLY: repeatOrder = 4; break; case KARecurrence::MONTHLY_DAY: case KARecurrence::MONTHLY_POS: repeatOrder = 5; break; case KARecurrence::ANNUAL_DATE: case KARecurrence::ANNUAL_POS: repeatOrder = 6; break; case KARecurrence::NO_RECUR: default: break; } } setText(parent->column(AlarmListView::REPEAT_COLUMN), repeatText); mRepeatOrder.sprintf("%c%08d", '0' + repeatOrder, repeatInterval); bool showColour = (event.action() == KAEvent::MESSAGE || event.action() == KAEvent::FILE); mColourOrder.sprintf("%06u", (showColour ? event.bgColour().rgb() : 0)); mTypeOrder.sprintf("%02d", event.action()); }
void AutoThread::run(){ QTime rate; qDebug() << "automatic from: " << QThread::currentThreadId(); MavState previous = g::state; MavState previous_platform = g::platform; MavState next, next_platform; land_count = 0; rot_count = 0; double vz = 0; double vx = 0; double vy = 0; double e_x = 0; double e_y = 0; double e_z = 0; float vy_platform = 0; rate.start(); while (true) { next = g::state; next_platform = g::platform; e_x = g::setPoint.x() - g::state.x(); e_y = g::setPoint.y() - g::state.y(); e_z = g::setPoint.z() - g::state.z(); vz = r_auto * (next.z() - previous.z()) ; vx = r_auto * (next.x() - previous.x()) ; vy = r_auto * (next.y() - previous.y()) ; vy_platform = r_auto * (next_platform.y() - previous_platform.y()) ; //takeoff if(executioner::take_off::take_off_sig){ takeOff(); } //land if(executioner::land::land_sig){ position state; state.x = g::state.x(); state.y = g::state.y(); state.z = g::state.z(); position p; p.x = nodeList[actualNode].p.x; p.y = nodeList[actualNode].p.y; float vel = nodeList[actualNode].a.params[0]; land(vel,(float)1/r_auto,vz,p,state); } //move if(executioner::move::move_sig){ position target; target.x = nodeList[actualNode].p.x; target.y = nodeList[actualNode].p.y; target.z = nodeList[actualNode].p.z; target.yaw = nodeList[actualNode].p.yaw; float alpha = nodeList[actualNode].a.params[0]; position state; state.x = g::state.x(); state.y = g::state.y(); state.z = g::state.z(); move(alpha,target,state); } //Land on moving platform (experimental) if(executioner::land::land_plat_sig){ land_plat(g::platform,g::state,2); } //rotate if(executioner::rotate::rotate_sig){ rotate(); } //Trajectory if(executioner::trajectory::traj_sig){ if(!executioner::trajectory::was_executing){ t_traj = 0; executioner::trajectory::was_executing = true; } else{ t_traj += (float)1/r_auto; double omega = nodeList[actualNode].a.params[0]; double radius = nodeList[actualNode].a.params[1]; double secs = nodeList[actualNode].a.params[2]; double look = nodeList[actualNode].a.params[3]; double c[2] = {nodeList[actualNode].p.x,nodeList[actualNode].p.y}; trajectory(omega,radius,c,t_traj,secs,look); } } //Writing output file float roll,pitch,yaw; g::state.orientation2(&roll,&pitch,&yaw); output <<g::state.x()<<" "<<g::state.y()<<" "<<g::state.z()<< //Position " "<<g::setPoint.x()<<" "<<g::setPoint.y()<<" "<<g::setPoint.z()<< //Position SetPoint " "<<e_x<<" "<<e_y<<" "<<e_z<<" "<< //Position error vx <<" "<<vy<<" "<<vz<<" "<< //Velocity roll<<" "<<pitch << " " << yaw //Attitude <<" "<<plat_error[0]<<" "<<plat_error[1]; //platform allignement error output << ";\n"; previous = next; previous_platform = next_platform; msleep(1000/r_auto - (float)rate.elapsed()); rate.restart(); } }
void Timelapse::setDuration(const QTime &time){ long duration = time.hour()*60*60*1000 +time.minute()*60*1000 +time.second()*1000; LOG_TIMELAPSE_DEBUG << "Timelapse setDuration: " << time.hour() << time.minute() << time.second() << duration; _duration = duration; }
void Solution::run() { // for ( count = 0; count < _myInstance->numPoints(); ++count ) { // _pointsType[count] = CCP::Consumer;//Everyone is consumer at begin... // } // if (!_lock.tryLock()){ // return; // } // QProgressDialog dialog ("Progress of algorithm", "cancel", 0,100); // // dialog.setWindowModality(Qt::WindowModal); if (_centers != 0){ delete [] _centers; } QTime count; count.start(); switch (_type){ case Farthest: { FarthestCluster far(_myInstance); // connect (&far, SIGNAL(complete(int)), &dialog, SLOT(setValue(int))); _centers = far.buildClusters(); _myAlgorithmName = "Farthest"; _myIterations = far.iterations(); _history = far.history(); } break; case Density: { DensityCluster density(_myInstance); // connect (&density, SIGNAL(complete(int)), &dialog, SLOT(setValue(int))); _centers = density.buildClusters(); _myAlgorithmName = "Density"; _myIterations = density.iterations(); _history = density.history(); } break; case HMeans: { HMeansCluster hmean(_myInstance); // connect (&hmean, SIGNAL(complete(int)), &dialog, SLOT(setValue(int))); _centers = hmean.buildClusters(); _myAlgorithmName = "HMeans"; _myIterations = hmean.iterations(); _history = hmean.history(); }break; case JMeans: { JMeansCluster jmean(_myInstance); // connect (&jmean, SIGNAL(complete(int)), &dialog, SLOT(setValue(int))); _centers = jmean.buildClusters(); _myAlgorithmName = "JMeans"; _myIterations = jmean.iterations(); _history = jmean.history(); }break; case RandonDensity: { RandomDensityCluster randomD(_myInstance); _centers = randomD.buildClusters(); _myAlgorithmName = "Randon Density"; _history = randomD.history(); }break; case DensityHMeans: { HMeansWithDensity hd(_myInstance); _centers = hd.buildClusters(); _myAlgorithmName = "HMeans With Density"; _history = hd.history(); }break; case DensityJMeans: { JMeansWithDensity jd(_myInstance); _centers = jd.buildClusters(); _myAlgorithmName = "JMeans With Density"; _history = jd.history(); }break; } _myTime = count.elapsed()/1000.0; // dialog.setValue(100); // _lock.unlock(); // emit finished(); }
void UserManagement::on_commandLinkButton_forceCLockOut_clicked() { QDate currentDate = QDate::currentDate(); QTime currentTime = QTime::currentTime(); int hour = currentTime.toString("HH").toInt(); int minutes = currentTime.toString("mm").toInt(); if(minutes > 30) { hour++; } currentTime = currentTime.fromString(QString::number(hour) + ":" + "00", "HH:mm"); QString date = currentDate.toString("yyyy-MM-dd"); QString time = currentTime.toString("HH:mm"); { Database conn; conn.connOpen("Clock"); QSqlQuery * qry = new QSqlQuery(conn.mydb); QString queryString; QTextStream queryStream(&queryString); queryStream << "UPDATE '" << currentEmpId <<"'" << " SET 'Time Out' = '" << time << "' where Date ='" << date << "'"; qry->prepare(queryString); if(!qry->exec()) { QMessageBox::critical(this, tr("Error"), qry->lastError().text()); } else {} conn.connClose(); } { Database conn; if(!conn.connOpen("Employee")) { qDebug () << "Database Connection Fatal Error"; } QSqlQuery * qry = new QSqlQuery(conn.mydb); QString queryString; QTextStream queryStream(&queryString); queryStream << "UPDATE 'Employees'" << " SET ONCLOCK = '0' where ID = '" << currentEmpId << "'"; qry->prepare(queryString); if(!qry->exec()) { QMessageBox::critical(this, tr("Error"), qry->lastError().text()); } else {} conn.connClose(); } this->setup(); }
void SplitVideo::startMencoder() { QTime t; int startTime = t.secsTo( ui->teFrom->time() ); int endTime = t.secsTo( ui->teTo->time() ); QFileInfo fi; QString inputFile = m_core->mdat.filename; QString outputFile; fi.setFile( m_core->mdat.filename ); if ( m_core->mdat.type == TYPE_DVD || m_core->mdat.type == TYPE_VCD ) { outputFile = QDesktopServices::storageLocation( QDesktopServices::MoviesLocation ) + tr( "/Movie_" ) + QString::number( startTime ) + "_" + QString::number( endTime ) + ".avi"; } else { outputFile = fi.absolutePath() + "/" + fi.baseName() + "_" + QString::number( startTime ) + "_" + QString::number( endTime ) + "." + fi.suffix(); } outputFile = getNewFileName( outputFile ); if ( !canWriteTo( outputFile ) ) { qDebug("SplitVideo::startMencoder(): cannot trim video ( maybe your disk is mounted read-only? )"); outputFile = QDesktopServices::storageLocation( QDesktopServices::MoviesLocation ) + "/" + fi.baseName() + "_" + QString::number( startTime ) + "_" + QString::number( endTime ) + "." + fi.suffix(); outputFile = getNewFileName( outputFile ); } qDebug("SplitVideo::startMencoder(): outputFile is %s", outputFile.toLocal8Bit().data() ); // we cannot splitting if time is not valid if ( !checkTime( startTime, endTime ) ) return; if ( !checkDiskSpace( outputFile, endTime - startTime, m_core->mdat.duration ) ) { ui->labelError->setText( tr( "Cannot trim video ( maybe you have no enough disk space? )" ) ); return; } m_isStopMencoder = false; m_error = -1; m_startTime = startTime; m_endTime = endTime; m_inputFile = inputFile; m_outputFile = outputFile; // Use absolute path, otherwise after changing to the screenshot directory // the mencoder path might not be found if it's a relative path // (seems to be necessary only for linux) QString mencoder_bin = pref->mencoder_bin; fi.setFile( mencoder_bin ); if ( fi.exists() && fi.isExecutable() && !fi.isDir() ) { mencoder_bin = fi.absoluteFilePath(); } m_proc->clearArguments(); m_proc->addArgument( mencoder_bin ); m_proc->addArgument( m_inputFile ); m_proc->addArgument( "-oac" ); if ( m_isCutError ) m_proc->addArgument( "pcm" ); else m_proc->addArgument( "copy" ); m_proc->addArgument( "-ovc" ); m_proc->addArgument( "copy" ); m_proc->addArgument( "-ss" ); m_proc->addArgument( QString::number( m_startTime ) ); m_proc->addArgument( "-endpos" ); m_proc->addArgument( QString::number( m_endTime - m_startTime ) ); m_proc->addArgument( "-o" ); m_proc->addArgument( m_outputFile ); QString commandline = m_proc->arguments().join(" "); qDebug("SplitVideo::startMencoder: command: '%s'", commandline.toUtf8().data()); if ( !m_proc->start() ) { // error handling qWarning("SplitVideo::startMencoder: mencoder process didn't start"); } updateControls(); }
void AndroidRetracer::run() { m_androidUtils.reloadAdb(); QString errorStr; bool setupRet; QMetaObject::invokeMethod(this, "setup", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, setupRet), Q_ARG(QString *, &errorStr)); if (!setupRet) { emit finished(errorStr); return; } if (!m_androidUtils.runAdb(QStringList() << _("shell") << _("am") << _("start") << _("-n") << packageName + activityName)) { emit finished(tr("Can't start apitrace application")); return; } QByteArray which; if (!m_androidUtils.runAdb(QStringList() << _("shell") << _("readlink") << _("$(which ps)") , &which)) { emit finished(tr("Can't start adb")); return; } bool isBusyBox = which.startsWith("busybox"); QStringList psArgs; psArgs << _("shell") << _("ps"); if (isBusyBox) psArgs << _("-w"); qint64 processPID; bool wasStarted = false; QTime startTime; startTime.start(); QTcpSocket stdoutSocket; QTcpSocket stderrSocket; ImageHash thumbnails; QVariantMap parsedJson; trace::Profile* profile = isProfiling() ? new trace::Profile() : NULL; QList<ApiTraceError> errors; QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$"); QString msg = QLatin1String("Replay finished!"); QByteArray jsonBuffer; QByteArray outputBuffer; bool keepGoing = true; while(keepGoing) { if (!wasStarted || startTime.elapsed() > 1000) { QByteArray psOut; m_androidUtils.runAdb(psArgs, &psOut); processPID = extractPid(psOut); if (wasStarted) startTime.restart(); } if (processPID == -1) { if (wasStarted) { break; } else { if (startTime.elapsed() > 3000) { // wait 3 seconds to start emit finished(tr("Unable to start retrace on device.")); return; } } msleep(100); continue; } // we have a valid pid, it means the application started if (!wasStarted) { // connect the sockets int tries = 0; do { stdoutSocket.connectToHost(QHostAddress::LocalHost, m_stdoutPort); } while (!stdoutSocket.waitForConnected(100) && ++tries < 10); if (stdoutSocket.state() != QAbstractSocket::ConnectedState) { emit finished(tr("Can't connect to stdout socket.")); return; } // Android doesn't suport GPU and PPD profiling (at leats not on my devices) //setProfiling(false, isProfilingCpu(), false); QString args = (retraceArguments() << m_androdiFileName).join(" ") + _("\n"); stdoutSocket.write(args.toUtf8()); if (!stdoutSocket.waitForBytesWritten()) { emit finished(tr("Can't send params.")); return; } stderrSocket.connectToHost(QHostAddress::LocalHost, m_stderrPort); stderrSocket.waitForConnected(100); if (stderrSocket.state() != QAbstractSocket::ConnectedState) { emit finished(tr("Can't connect to stderr socket.")); return; } wasStarted = true; } // We are going to read both channels at the same time // read stdout channel if (stdoutSocket.waitForReadyRead(100)) { if (captureState()) jsonBuffer.append(stdoutSocket.readAll()); else if (captureThumbnails()) { // read one image image::PNMInfo info; QByteArray header; int headerLines = 3; // assume no optional comment line for (int headerLine = 0; headerLine < headerLines; ++headerLine) { QByteArray line = readLine(stdoutSocket); if (line.isEmpty()) { keepGoing = false; break; } header += line; // if header actually contains optional comment line, ... if (headerLine == 1 && line[0] == '#') { ++headerLines; } } const char *headerEnd = image::readPNMHeader(header.constData(), header.size(), info); // if invalid PNM header was encountered, ... if (headerEnd == NULL || info.channelType != image::TYPE_UNORM8) { qDebug() << "error: invalid snapshot stream encountered"; keepGoing = false; break; } unsigned channels = info.channels; unsigned width = info.width; unsigned height = info.height; // qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height"; QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888); int rowBytes = channels * width; for (int y = 0; y < height; ++y) { unsigned char *scanLine = snapshot.scanLine(y); if (!read(stdoutSocket, (char *) scanLine, rowBytes)) { keepGoing = false; break; } } QImage thumb = thumbnail(snapshot); thumbnails.insert(info.commentNumber, thumb); } else if (isProfiling()) { QByteArray line = readLine(stdoutSocket); if (line.isEmpty()) { keepGoing = false; break; } line.append('\0'); trace::Profiler::parseLine(line.constData(), profile); } else { outputBuffer.append(stdoutSocket.readAll()); } } // read stderr channel if (stderrSocket.waitForReadyRead(5) && stderrSocket.canReadLine()) { QString line = stderrSocket.readLine(); if (regexp.indexIn(line) != -1) { ApiTraceError error; error.callIndex = regexp.cap(1).toInt(); error.type = regexp.cap(2); error.message = regexp.cap(3); errors.append(error); } else if (!errors.isEmpty()) { // Probably a multiligne message ApiTraceError &previous = errors.last(); if (line.endsWith("\n")) { line.chop(1); } previous.message.append('\n'); previous.message.append(line); } } } if (outputBuffer.size() < 80) msg = outputBuffer; if (captureState()) { QJsonParseError error; QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonBuffer, &error); if (error.error != QJsonParseError::NoError) msg = error.errorString(); parsedJson = jsonDoc.toVariant().toMap(); ApiTraceState *state = new ApiTraceState(parsedJson); emit foundState(state); } if (captureThumbnails() && !thumbnails.isEmpty()) { emit foundThumbnails(thumbnails); } if (isProfiling() && profile) { emit foundProfile(profile); } if (!errors.isEmpty()) { emit retraceErrors(errors); } emit finished(msg); }
// Refresh not up to date metrics and metrics after date void MetricAggregator::refreshMetrics(QDateTime forceAfterThisDate) { // only if we have established a connection to the database if (dbaccess == NULL || context->athlete->isclean==true) return; // first check db structure is still up to date // this is because metadata.xml may add new fields dbaccess->checkDBVersion(); // Get a list of the ride files QRegExp rx = RideFileFactory::instance().rideFileRegExp(); QStringList filenames = RideFileFactory::instance().listRideFiles(context->athlete->home); QStringListIterator i(filenames); // get a Hash map of statistic records and timestamps QSqlQuery query(dbaccess->connection()); QHash <QString, status> dbStatus; bool rc = query.exec("SELECT filename, timestamp, fingerprint FROM metrics ORDER BY ride_date;"); while (rc && query.next()) { status add; QString filename = query.value(0).toString(); add.timestamp = query.value(1).toInt(); add.fingerprint = query.value(2).toInt(); dbStatus.insert(filename, add); } // begin LUW -- byproduct of turning off sync (nosync) dbaccess->connection().transaction(); // Delete statistics for non-existant ride files QHash<QString, status>::iterator d; for (d = dbStatus.begin(); d != dbStatus.end(); ++d) { if (QFile(context->athlete->home.absolutePath() + "/" + d.key()).exists() == false) { dbaccess->deleteRide(d.key()); #ifdef GC_HAVE_LUCENE context->athlete->lucene->deleteRide(d.key()); #endif } } unsigned long zoneFingerPrint = static_cast<unsigned long>(context->athlete->zones()->getFingerprint()) + static_cast<unsigned long>(context->athlete->hrZones()->getFingerprint()); // checksum of *all* zone data (HR and Power) // update statistics for ride files which are out of date // showing a progress bar as we go QTime elapsed; elapsed.start(); QString title = tr("Updating Statistics\nStarted"); QProgressDialog *bar = NULL; int processed=0; QApplication::processEvents(); // get that dialog up! // log of progress QFile log(context->athlete->home.absolutePath() + "/" + "metric.log"); log.open(QIODevice::WriteOnly); log.resize(0); QTextStream out(&log); out << "METRIC REFRESH STARTS: " << QDateTime::currentDateTime().toString() + "\r\n"; while (i.hasNext()) { QString name = i.next(); QFile file(context->athlete->home.absolutePath() + "/" + name); // if it s missing or out of date then update it! status current = dbStatus.value(name); unsigned long dbTimeStamp = current.timestamp; unsigned long fingerprint = current.fingerprint; RideFile *ride = NULL; processed++; // create the dialog if we need to show progress for long running uodate long elapsedtime = elapsed.elapsed(); if ((first || elapsedtime > 6000) && bar == NULL) { bar = new QProgressDialog(title, tr("Abort"), 0, filenames.count()); // not owned by mainwindow bar->setWindowFlags(bar->windowFlags() | Qt::FramelessWindowHint); bar->setWindowModality(Qt::WindowModal); bar->setMinimumDuration(0); bar->show(); // lets hide until elapsed time is > 6 seconds } // update the dialog always after 6 seconds if (first || elapsedtime > 6000) { // update progress bar QString elapsedString = QString("%1:%2:%3").arg(elapsedtime/3600000,2) .arg((elapsedtime%3600000)/60000,2,10,QLatin1Char('0')) .arg((elapsedtime%60000)/1000,2,10,QLatin1Char('0')); QString title = tr("%1\n\nUpdate Statistics\nElapsed: %2\n\n%3").arg(context->athlete->cyclist).arg(elapsedString).arg(name); bar->setLabelText(title); bar->setValue(processed); } QApplication::processEvents(); if (dbTimeStamp < QFileInfo(file).lastModified().toTime_t() || zoneFingerPrint != fingerprint || (!forceAfterThisDate.isNull() && name >= forceAfterThisDate.toString("yyyy_MM_dd_hh_mm_ss"))) { QStringList errors; // log out << "Opening ride: " << name << "\r\n"; // read file and process it if we didn't already... if (ride == NULL) ride = RideFileFactory::instance().openRideFile(context, file, errors); out << "File open completed: " << name << "\r\n"; if (ride != NULL) { out << "Getting weight: " << name << "\r\n"; ride->getWeight(); out << "Updating statistics: " << name << "\r\n"; importRide(context->athlete->home, ride, name, zoneFingerPrint, (dbTimeStamp > 0)); } } // update cache (will check timestamps itself) // if ride wasn't opened it will do it itself // we only want to check so passing check=true // because we don't actually want the results now RideFileCache updater(context, context->athlete->home.absolutePath() + "/" + name, ride, true); // free memory - if needed if (ride) delete ride; if (bar && bar->wasCanceled()) { out << "METRIC REFRESH CANCELLED\r\n"; break; } } // now zap the progress bar if (bar) delete bar; // end LUW -- now syncs DB out << "COMMIT: " << QDateTime::currentDateTime().toString() + "\r\n"; dbaccess->connection().commit(); #ifdef GC_HAVE_LUCENE #ifndef WIN32 // windows crashes here.... out << "OPTIMISE: " << QDateTime::currentDateTime().toString() + "\r\n"; context->athlete->lucene->optimise(); #endif #endif context->athlete->isclean = true; // stop logging out << "SIGNAL DATA CHANGED: " << QDateTime::currentDateTime().toString() + "\r\n"; dataChanged(); // notify models/views out << "METRIC REFRESH ENDS: " << QDateTime::currentDateTime().toString() + "\r\n"; log.close(); first = false; }
void Interpreter::run() { int res; QTime time; // init try { ChirpProc versionProc; uint16_t *version; uint32_t verLen, responseInt; if (m_link.open()<0) throw std::runtime_error("Unable to open USB device."); m_chirp = new ChirpMon(this, &m_link); // get version and compare versionProc = m_chirp->getProc("version"); if (versionProc<0) throw std::runtime_error("Can't get firmware version."); res = m_chirp->callSync(versionProc, END_OUT_ARGS, &responseInt, &verLen, &version, END_IN_ARGS); if (res<0) throw std::runtime_error("Can't get firmware version."); memcpy(m_version, version, 3*sizeof(uint16_t)); if (m_version[0]!=VER_MAJOR || m_version[1]>VER_MINOR) { char buf[0x100]; sprintf(buf, "This Pixy's firmware version (%d.%d.%d) is not compatible with this PixyMon version (%d.%d.%d).", m_version[0], m_version[1], m_version[2], VER_MAJOR, VER_MINOR, VER_BUILD); throw std::runtime_error(buf); } m_exec_run = m_chirp->getProc("run"); m_exec_running = m_chirp->getProc("running"); m_exec_stop = m_chirp->getProc("stop"); m_exec_get_action = m_chirp->getProc("getAction"); m_get_param = m_chirp->getProc("prm_get"); m_getAll_param = m_chirp->getProc("prm_getAll"); m_set_param = m_chirp->getProc("prm_set"); if (m_exec_run<0 || m_exec_running<0 || m_exec_stop<0 || m_exec_get_action<0 || m_get_param<0 || m_getAll_param<0 || m_set_param<0) throw std::runtime_error("Communication error with Pixy."); } catch (std::runtime_error &exception) { emit error(QString(exception.what())); return; } qDebug() << "*** init done"; time.start(); getRunning(); handleLoadParams(); // load params upon initialization while(m_run) { if (!m_programming && ((m_fastPoll && time.elapsed()>RUN_POLL_PERIOD_FAST) || (!m_fastPoll && time.elapsed()>RUN_POLL_PERIOD_SLOW))) { getRunning(); time.start(); } else { m_chirp->service(false); msleep(1); // give config thread time to run } handlePendingCommand(); if (!m_running) { if (m_localProgramRunning) execute(); else { Sleeper::msleep(10); if (m_mutexProg.tryLock()) { if (m_argv.size()) { if (m_externalCommand!="") // print command to make things explicit and all pretty emit textOut(PROMPT " " + m_externalCommand); if (m_argv[0]=="help") handleHelp(); else { res = call(m_argv, true); if (res<0) { if (m_programming) { endLocalProgram(); clearLocalProgram(); } m_commandList.clear(); // abort our little scriptlet } } m_argv.clear(); if (m_externalCommand=="") prompt(); // print prompt only if we expect an actual human to be typing into the command window else m_externalCommand = ""; // check quickly to see if we're running after this command if (!m_programming) getRunning(); // is there another command in our little scriptlet? if (m_commandList.size()) { execute(m_commandList[0]); m_commandList.removeFirst(); } } m_mutexProg.unlock(); } } } } sendStop(); msleep(200); // let things settle a bit qDebug("worker thead exiting"); }
void BatteryWatcher::batteryChanged() { static QTime actionTime; static LxQt::Notification *notification = 0; qDebug() << "BatteryChanged" << "discharging:" << mBattery.discharging() << "chargeLevel:" << mBattery.chargeLevel() << "powerlow:" << mBattery.powerLow() << "actionTime:" << actionTime; if (mBattery.powerLow() && mSettings.getPowerLowAction() > 0) { if (actionTime.isNull()) { actionTime = QTime::currentTime().addMSecs(mSettings.getPowerLowWarningTime()*1000); } if (notification == 0) { notification = new LxQt::Notification(tr("Power low!"), this); notification->setTimeout(2000); } int milliSecondsToAction = QTime::currentTime().msecsTo(actionTime); if (milliSecondsToAction > 0) { int secondsToAction = milliSecondsToAction/1000; switch (mSettings.getPowerLowAction()) { case LxQt::Power::PowerSuspend: notification->setBody(tr("Suspending in %1 seconds").arg(secondsToAction)); break; case LxQt::Power::PowerHibernate: notification->setBody(tr("Hibernating in %1 seconds").arg(secondsToAction)); break; case LxQt::Power::PowerShutdown: notification->setBody(tr("Shutting down in %1 seconds").arg(secondsToAction)); break; } notification->update(); QTimer::singleShot(200, this, SLOT(batteryChanged())); } else { doAction(mSettings.getPowerLowAction()); } } else { if (!actionTime.isNull()) { actionTime = QTime(); } if (notification) { delete notification; notification = 0; } } mBatteryInfo.updateInfo(&mBattery); if (mSettings.isShowIcon()) mTrayIcon->update(mBattery.discharging(), mBattery.chargeLevel(), mSettings.getPowerLowLevel()); }
bool MolecularOrbitals::computeDensityGrids(Data::GridData*& alpha, Data::GridData*& beta) { QTime time; time.start(); unsigned nx, ny, nz; alpha->getNumberOfPoints(nx, ny, nz); Vec delta(alpha->delta()); Vec origin(alpha->origin()); // We take a two pass approach, the first computes data on a grid with half // the number of points for each dimension (so a factor of 8 fewer points // than the target grid). We then used these values in a subsequent pass to // refine only those parts with significant density. unsigned totalProgress(8*nx); // first and second passes unsigned progress(0); unsigned i, j, k; double x, y, z; QProgressDialog progressDialog("Calculating density grid data", "Cancel", 0, totalProgress, QApplication::activeWindow()); progressDialog.setValue(progress); progressDialog.setWindowModality(Qt::WindowModal); progressDialog.show(); for (i = 0, x = origin.x; i < nx; i += 2, x += 2*delta.x) { for (j = 0, y = origin.y; j < ny; j += 2, y += 2*delta.y) { for (k = 0, z = origin.z; k < nz; k += 2, z += 2*delta.z) { Vec gridPoint(x, y, z); computeShellPairs(gridPoint); (*alpha)(i, j, k) = inner_prod(m_alphaDensity, m_shellPairValues); (*beta )(i, j, k) = inner_prod(m_betaDensity, m_shellPairValues); } } ++progress; progressDialog.setValue(progress); if (progressDialog.wasCanceled()) return false; } double a000, a001, a010, a011, a100, a101, a110, a111, aTot; double b000, b001, b010, b011, b100, b101, b110, b111, bTot; double thresh(0.125*Data::Shell::thresh()); origin += delta; for (i = 1, x = origin.x; i < nx-1; i += 2, x += 2*delta.x) { for (j = 1, y = origin.y; j < ny-1; j += 2, y += 2*delta.y) { for (k = 1, z = origin.z; k < nz-1; k += 2, z += 2*delta.z) { a000 = (*alpha)(i-1, j-1, k-1); a001 = (*alpha)(i-1, j-1, k+1); a010 = (*alpha)(i-1, j+1, k-1); a011 = (*alpha)(i-1, j+1, k+1); a100 = (*alpha)(i+1, j-1, k-1); a101 = (*alpha)(i+1, j-1, k+1); a110 = (*alpha)(i+1, j+1, k-1); a111 = (*alpha)(i+1, j+1, k+1); aTot = a000+a001+a010+a011+a100+a101+a110+a111; b000 = (*beta)(i-1, j-1, k-1); b001 = (*beta)(i-1, j-1, k+1); b010 = (*beta)(i-1, j+1, k-1); b011 = (*beta)(i-1, j+1, k+1); b100 = (*beta)(i+1, j-1, k-1); b101 = (*beta)(i+1, j-1, k+1); b110 = (*beta)(i+1, j+1, k-1); b111 = (*beta)(i+1, j+1, k+1); bTot = b000+b001+b010+b011+b100+b101+b110+b111; if (std::abs(aTot) > thresh || std::abs(bTot) > thresh) { computeShellPairs(Vec(x, y, z)); (*alpha)(i, j, k ) = inner_prod(m_alphaDensity, m_shellPairValues); (*beta )(i, j, k ) = inner_prod(m_betaDensity, m_shellPairValues); computeShellPairs(Vec(x, y, z-delta.z)); (*alpha)(i, j, k-1) = inner_prod(m_alphaDensity, m_shellPairValues); (*beta )(i, j, k-1) = inner_prod(m_betaDensity, m_shellPairValues); computeShellPairs(Vec(x, y-delta.y, z)); (*alpha)(i, j-1,k ) = inner_prod(m_alphaDensity, m_shellPairValues); (*beta )(i, j-1,k ) = inner_prod(m_betaDensity, m_shellPairValues); computeShellPairs(Vec(x, y-delta.y, z-delta.z)); (*alpha)(i, j-1,k-1) = inner_prod(m_alphaDensity, m_shellPairValues); (*beta )(i, j-1,k-1) = inner_prod(m_betaDensity, m_shellPairValues); computeShellPairs(Vec(x-delta.x, y, z)); (*alpha)(i-1,j, k ) = inner_prod(m_alphaDensity, m_shellPairValues); (*beta )(i-1,j, k ) = inner_prod(m_betaDensity, m_shellPairValues); computeShellPairs(Vec(x-delta.x, y, z-delta.z)); (*alpha)(i-1,j, k-1) = inner_prod(m_alphaDensity, m_shellPairValues); (*beta )(i-1,j, k-1) = inner_prod(m_betaDensity, m_shellPairValues); computeShellPairs(Vec(x-delta.x, y-delta.y, z)); (*alpha)(i-1,j-1,k ) = inner_prod(m_alphaDensity, m_shellPairValues); (*beta )(i-1,j-1,k ) = inner_prod(m_betaDensity, m_shellPairValues); }else { (*alpha)(i, j, k ) = 0.125*aTot; (*beta )(i, j, k ) = 0.125*bTot; (*alpha)(i, j, k-1) = 0.25*(a000+a010+a100+a110); (*beta )(i, j, k-1) = 0.25*(b000+b010+b100+b110); (*alpha)(i, j-1,k ) = 0.25*(a000+a001+a100+a101); (*beta )(i, j-1,k ) = 0.25*(b000+b001+b100+b101); (*alpha)(i, j-1,k-1) = 0.50*(a000+a100); (*beta )(i, j-1,k-1) = 0.50*(b000+b100); (*alpha)(i-1,j, k ) = 0.25*(a000+a001+a010+a011); (*beta )(i-1,j, k ) = 0.25*(b000+b001+b010+b011); (*alpha)(i-1,j, k-1) = 0.50*(a000+a010); (*beta )(i-1,j, k-1) = 0.50*(b000+b010); (*alpha)(i-1,j-1,k ) = 0.50*(a000+a001); (*beta )(i-1,j-1,k ) = 0.50*(b000+b001); } } } progress += 7; progressDialog.setValue(progress); if (progressDialog.wasCanceled()) return false; } // qDebug() << "End of calculation" << nPoints << count << progress; double t = time.elapsed() / 1000.0; QLOG_INFO() << "Time to compute density grid data:" << t << "seconds"; return true; }
void Polyhedron_demo_nef_plugin::boolean_operation(const Boolean_operation operation) { const int indexA = scene->selectionAindex(); const int indexB = scene->selectionBindex(); if(indexA < 0 || indexB < 0) return; if(indexA == indexB) return; if(qobject_cast<Scene_polyhedron_item*>(scene->item(indexA)) || qobject_cast<Scene_polyhedron_item*>(scene->item(indexB))) { QMenu* menu = mw->findChild<QMenu*>("menu_Boolean_operations"); if(!menu) qWarning("Do not find object named \"menu_Boolean_operations\"!"); QMessageBox::warning(mw, tr("Boolean operation cannot be applied on normal polyhedron"), tr("You need to call the operation \"%1\" in the menu \"%2\".") .arg(actions_map["actionToNef"]->text()) .arg(menu ? menu->title() : "Boolean operations")); } Scene_nef_polyhedron_item* itemA = qobject_cast<Scene_nef_polyhedron_item*>(scene->item(indexA)); Scene_nef_polyhedron_item* itemB = qobject_cast<Scene_nef_polyhedron_item*>(scene->item(indexB)); if(!itemA || !itemB) return; QApplication::setOverrideCursor(Qt::WaitCursor); // copy itemA Scene_nef_polyhedron_item* new_item = 0; if(operation != MINKOWSKI_SUM) { new_item = new Scene_nef_polyhedron_item(*itemA->nef_polyhedron()); }; // perform Boolean operation std::cout << "Boolean operation..."; QTime time; time.start(); switch(operation) { case BOOLEAN_UNION: (*new_item) += (*itemB); break; case BOOLEAN_INTERSECTION: (*new_item) *= (*itemB); break; case BOOLEAN_DIFFERENCE: (*new_item) -= (*itemB); break; case MINKOWSKI_SUM: new_item = Scene_nef_polyhedron_item::sum(*itemA, *itemB); } std::cout << "ok (" << time.elapsed() << " ms)" << std::endl; QString name; switch(operation) { case BOOLEAN_UNION: name = tr("%1 union %2"); break; case BOOLEAN_INTERSECTION: name = tr("%1 intersection %2"); break; case BOOLEAN_DIFFERENCE: name = tr("%1 minus %2"); break; case MINKOWSKI_SUM: name = tr("Minkowski sum of %1 and %2"); } new_item->setName(name.arg(itemA->name(), itemB->name())); new_item->setColor(Qt::green); new_item->setRenderingMode(FlatPlusEdges); itemA->setRenderingMode(Wireframe); itemB->setRenderingMode(Wireframe); scene->addItem(new_item); scene->itemChanged(indexA); scene->itemChanged(indexB); QApplication::restoreOverrideCursor(); }