QString toListViewFormatterText::getFormattedString(toExportSettings &settings, //const toResultModel *model); const QAbstractItemModel * model) { int columns = model->columnCount(); int rows = model->rowCount(); QString output; QVector<int> sizes(columns); QVector<int> rlist = selectedRows(settings.selected); QVector<int> clist = selectedColumns(settings.selected); // must get widest length for each column // zero array or (if writing headers, set their size) for (int i = 0; i < columns - 1; i++) { if (settings.columnsHeader) { if (settings.columnsExport == toExportSettings::ColumnsSelected && !clist.contains(i)) continue; sizes[i] = model->headerData( i, Qt::Horizontal, Qt::DisplayRole).toString().length(); } else sizes[i] = 0; } sizes[columns - 1] = 1; // loop through model and get column widths QModelIndex mi; for (int row = 0; row < rows; row++) { for (int column = 0; column < columns - 1; column++) { if (settings.columnsExport == toExportSettings::ColumnsSelected && !clist.contains(column)) continue; if (!settings.rowsHeader && column == 0) continue; mi = model->index(row, column); QVariant data = model->data(mi, Qt::EditRole); QString v; if (data.isNull()) v = "{null}"; else v = data.toString(); int len = v.length(); if (len > sizes[column]) sizes[column] = len; } } // write header data to fixed widths if (settings.columnsHeader) { for (int column = 0; column < columns; column++) { if (settings.columnsExport == toExportSettings::ColumnsSelected && !clist.contains(column)) continue; if (!settings.rowsHeader && column == 0) continue; QString value = model->headerData( column, Qt::Horizontal, Qt::DisplayRole).toString(); output += value; for (int left = value.length(); left <= sizes[column]; left++) output += ' '; } endLine(output); // write ==== border for (int column = 0; column < columns; column++) { if (settings.columnsExport == toExportSettings::ColumnsSelected && !clist.contains(column)) continue; if (!settings.rowsHeader && column == 0) continue; for (int left = 0; left < sizes[column]; left++) output += '='; output += ' '; } endLine(output); } // write data for (int row = 0; row < rows; row++) { if (settings.rowsExport == toExportSettings::RowsSelected && !rlist.contains(row)) continue; for (int column = 0; column < columns; column++) { if (settings.columnsExport == toExportSettings::ColumnsSelected && !clist.contains(column)) continue; if (!settings.rowsHeader && column == 0) continue; mi = model->index(row, column); QVariant data = model->data(mi, Qt::EditRole); QString value; if (data.isNull()) value = "{null}"; else value = data.toString(); output += value; for (int left = value.length(); left <= sizes[column]; left++) output += ' '; } endLine(output); } return output; }
static inline QVector<QString> names(QVector<Node> nodes) { QVector<QString> names; for (const Node &node : nodes) names.append(node._name); return names; }
/// TODO:名称和路径需要联系起来 // 不能使用QHash ,会出现string相同的情况,那用什么方法呢 // QMultiMap?? void QJDMainWindow::setHomeDir(QString homePath) { areaWidget->clear(); /// 第一层 -- 工区 QDir dir1; // 这个需要能设置,程序需要有settings.ini dir1.setPath(homePath); QStringList dirLev1; dirLev1<<dir1.entryList(QDir::NoDotAndDotDot|QDir::Dirs); // qDebug()<<dir1.count(); // 包含./.. /// 第二层 -- 线, 目前要向里面加入data文件夹,data文件夹与flow并列并且继续有往下的选择,可以不用descname QStringList areaStringList; QStringList areaPathList; QStringList lineStringList; QStringList linePathList; QVector<QStringList> flowStringList; QVector<QStringList> flowPathList; QVector<QVector<QStringList> > dataStringList; QVector<QVector<QStringList> > dataPathList; for(int i=0; i<dirLev1.count(); i++) { // 遍历 QDir dir2; QString dir2path=dir1.path()+"/"+dirLev1.at(i); dir2.setPath(dir2path); QStringList dirLev2; dirLev2=dir2.entryList(QDir::NoDotAndDotDot|QDir::Dirs); // 解析 DescName -- 工区名称 QFile file2; file2.setFileName(dir2path+"/DescName"); if(!file2.exists()) { continue; } areaPathList<<dir2path; file2.open(QFile::ReadOnly); QTextStream stream2(&file2); QString areatmp=stream2.readAll(); areatmp.chop(1); areaStringList<<areatmp; // 路径就是dir2path // qDebug()<<dir2path; file2.close(); /// 第三层 -- 流程/Data, 同一层的data文件夹需要特殊处理 for(int j=0; j<dirLev2.count(); j++) { QDir dir3; QString dir3path=dir2.path()+"/"+dirLev2.at(j); dir3.setPath(dir3path); QStringList dirLev3; dirLev3=dir3.entryList(QDir::NoDotAndDotDot|QDir::Dirs); // 线名 // 解析 DescName -- 线名称 QFile file3; file3.setFileName(dir3path+"/DescName"); if(!file3.exists()) { continue; } linePathList<<dir3path; file3.open(QFile::ReadOnly); QTextStream stream3(&file3); QString linetmp=stream3.readAll(); linetmp.chop(1); lineStringList<<linetmp; file3.close(); // qDebug()<<"line::"<<lineStringList; /// 第四层 -- 具体流程 flowStringList.resize(dirLev2.count()); flowPathList.resize(dirLev2.count()); dataStringList.resize(dirLev2.count()); dataPathList.resize(dirLev2.count()); for(int k=0; k<dirLev3.count(); k++) { // 应当没有文件夹了,只剩下文件了 QDir dir4; QString dir4path=dir3.path()+"/"+dirLev3.at(k); dir4.setPath(dir4path); QStringList dirLev4; dirLev4=dir4.entryList(QDir::NoDotAndDotDot|QDir::Files); // 文件名列表了 flowPathList[j]<<dir4path; /// 底下应当有个记录流程xml文件 // 解析 DescName -- 线名称 QFile file4; file4.setFileName(dir4path+"/DescName"); if(!file4.exists()) { continue; } file4.open(QFile::ReadOnly); QTextStream stream4(&file4); QString flowtmp=stream4.readAll(); flowtmp.chop(1); flowStringList[j]<<flowtmp; // 只有在流程里才会有,其他的文件夹内不会有这个 file4.close(); // qDebug()<<"flow::"<<flowStringList; /// 第五层 -- 数据存放,不应当再像前面一样完全扫描了.需要列出文件类型目录即可 //! !! 如何准确放到某条线下面去,每条线都有,目前还是没有解决这个问题 // 也就是说需要二维数组来确定 if(flowtmp=="Data") { dataStringList[j].resize(dirLev3.count()); dataPathList[j].resize(dirLev3.count()); for(int l=0; l<dirLev4.count(); l++) { // 应当没有文件夹了,只剩下文件了 QDir dir5; dir5.setPath(dir4.path()); QStringList dirLev5; dirLev5=dir5.entryList(QDir::NoDotAndDotDot|QDir::AllDirs); // 文件名列表了 // qDebug()<<dir4.path()<<"dirLev5::"<<dirLev5; // 怎么是空的?? dataStringList[j][k].append(dirLev5); /// 底下应当有个记录流程xml文件 for(int m=0; m<dirLev5.size(); m++) { QString dataPath=dir4.path()+"/"+dirLev5.at(m); dataPathList[j][k].append(dataPath); } } // dataString为空 path为data descName的path // qDebug()<<"!!!!!!!!!!!!!!!!!!!!!!!!!!"<<dirLev4.count()<<dataStringList; } } } // qDebug()<<"\nstart set:::"<<areaStringList.at(i)<<lineStringList<<flowStringList; // qDebug()<<"Data:::"<<dataStringList; setAreaWidget(areaStringList.at(i),areaPathList.at(i),lineStringList, linePathList,flowStringList,flowPathList,dataStringList,dataPathList); /// 清理 flowStringList.clear(); flowPathList.clear(); lineStringList.clear(); linePathList.clear(); dataStringList.clear(); dataPathList.clear(); } if(!areaStringList.isEmpty()) { // qDebug()<<areaWidget->topLevelItem(0)->text(0); areaWidget->setCurrentItem(areaWidget->topLevelItem(0)); areaWidget->returnPath(areaWidget->currentItem(),areaWidget->currentColumn()); } }
void SerialConnection::open() { QString status_msg = "connected."; QString theport = portname; if (context != NULL) { close(); } if (theport.length() == 0) { QVector<QString> ports = enumerate(); if (ports.size() > 0) { theport = ports[0]; } else { emit status("no serial port found"); return; } } #ifdef _WIN32 HANDLE handle = CreateFile(theport.toStdWString().c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); DCB dcbSerialParams = {0}; if (handle == INVALID_HANDLE_VALUE) { status_msg = QString("unable to open %1. check if device is already in use.").arg(theport); } else if (!GetCommState(handle, &dcbSerialParams)) { status_msg = QString("unable to get device attributes"); } else { //Define serial connection parameters for the arduino board dcbSerialParams.BaudRate=CBR_38400; dcbSerialParams.ByteSize=8; dcbSerialParams.StopBits=ONESTOPBIT; dcbSerialParams.Parity=NOPARITY; //Set the parameters and check for their proper application if(!SetCommState(handle, &dcbSerialParams)) status_msg = QString("unable to set device attributes"); else { context = new HANDLE(handle); } } #else int fd = ::open(theport.toStdString().c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK); struct termios toptions; if (fd == -1) { status_msg = QString("unable to open %1. check if device is already in use.").arg(theport); } else if (ioctl(fd, TIOCEXCL) == -1) { status_msg = QString("unable to get exclusive access"); } else if (fcntl(fd, F_SETFL, 0) == -1) { status_msg = QString("unable to restore blocking access"); } else if (tcgetattr(fd, &toptions) < 0) { status_msg = QString("unable to get device attributes"); } else { cfsetispeed(&toptions, B38400); cfsetospeed(&toptions, B38400); // 8N1 toptions.c_cflag &= ~PARENB; toptions.c_cflag &= ~CSTOPB; toptions.c_cflag &= ~CSIZE; toptions.c_cflag |= CS8; // no flow control toptions.c_cflag &= ~CRTSCTS; //toptions.c_cflag &= ~HUPCL; // disable hang-up-on-close to avoid reset toptions.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines toptions.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw toptions.c_oflag &= ~OPOST; // make raw // see: http://unixwiz.net/techtips/termios-vmin-vtime.html toptions.c_cc[VMIN] = 0; toptions.c_cc[VTIME] = 0; tcsetattr(fd, TCSANOW, &toptions); if (tcsetattr(fd, TCSAFLUSH, &toptions) < 0) { status_msg = QString("unable to set device attributes"); } else { tcflush(fd, TCIOFLUSH); context = new int(fd); } } #endif emit status(status_msg); }
void TraceLoader::parseTrace() { QList<ApiTraceFrame*> frames; ApiTraceFrame *currentFrame = 0; int frameCount = 0; QStack<ApiTraceCall*> groups; QVector<ApiTraceCall*> topLevelItems; QVector<ApiTraceCall*> allCalls; quint64 binaryDataSize = 0; int lastPercentReport = 0; trace::Call *call = m_parser.parse_call(); while (call) { //std::cout << *call; if (!currentFrame) { currentFrame = new ApiTraceFrame(); currentFrame->number = frameCount; ++frameCount; } ApiTraceCall *apiCall = apiCallFromTraceCall(call, m_helpHash, currentFrame, groups.isEmpty() ? 0 : groups.top(), this); allCalls.append(apiCall); if (groups.count() == 0) { topLevelItems.append(apiCall); } if (call->flags & trace::CALL_FLAG_MARKER_PUSH) { groups.push(apiCall); } else if (call->flags & trace::CALL_FLAG_MARKER_POP) { groups.top()->finishedAddingChildren(); groups.pop(); } if (!groups.isEmpty()) { groups.top()->addChild(apiCall); } if (apiCall->hasBinaryData()) { QByteArray data = apiCall->arguments()[apiCall->binaryDataIndex()].toByteArray(); binaryDataSize += data.size(); } if (call->flags & trace::CALL_FLAG_END_FRAME) { allCalls.squeeze(); topLevelItems.squeeze(); if (topLevelItems.count() == allCalls.count()) { currentFrame->setCalls(allCalls, allCalls, binaryDataSize); } else { currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize); } allCalls.clear(); groups.clear(); topLevelItems.clear(); frames.append(currentFrame); currentFrame = 0; binaryDataSize = 0; if (frames.count() >= FRAMES_TO_CACHE) { emit framesLoaded(frames); frames.clear(); } if (m_parser.percentRead() - lastPercentReport >= 5) { emit parsed(m_parser.percentRead()); lastPercentReport = m_parser.percentRead(); } } delete call; call = m_parser.parse_call(); } //last frames won't have markers // it's just a bunch of Delete calls for every object // after the last SwapBuffers if (currentFrame) { allCalls.squeeze(); if (topLevelItems.count() == allCalls.count()) { currentFrame->setCalls(allCalls, allCalls, binaryDataSize); } else { currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize); } frames.append(currentFrame); currentFrame = 0; } if (frames.count()) { emit framesLoaded(frames); } }
bool QDirIteratorPrivate::matchesFilters(const QString &fileName, const QFileInfo &fi) const { Q_ASSERT(!fileName.isEmpty()); // filter . and ..? const int fileNameSize = fileName.size(); const bool dotOrDotDot = fileName[0] == QLatin1Char('.') && ((fileNameSize == 1) ||(fileNameSize == 2 && fileName[1] == QLatin1Char('.'))); if ((filters & QDir::NoDot) && dotOrDotDot && fileNameSize == 1) return false; if ((filters & QDir::NoDotDot) && dotOrDotDot && fileNameSize == 2) return false; if ((filters & QDir::NoDotAndDotDot) && dotOrDotDot) // ### Qt5 remove (NoDotAndDotDot == NoDot|NoDotDot) return false; // name filter #ifndef QT_NO_REGEXP // Pass all entries through name filters, except dirs if the AllDirs if (!nameFilters.isEmpty() && !((filters & QDir::AllDirs) && fi.isDir())) { bool matched = false; for (QVector<QRegExp>::const_iterator iter = nameRegExps.constBegin(), end = nameRegExps.constEnd(); iter != end; ++iter) { if (iter->exactMatch(fileName)) { matched = true; break; } } if (!matched) return false; } #endif // skip symlinks const bool skipSymlinks = (filters & QDir::NoSymLinks); const bool includeSystem = (filters & QDir::System); if(skipSymlinks && fi.isSymLink()) { // The only reason to save this file is if it is a broken link and we are requesting system files. if(!includeSystem || fi.exists()) return false; } // filter hidden const bool includeHidden = (filters & QDir::Hidden); if (!includeHidden && !dotOrDotDot && fi.isHidden()) return false; // filter system files if (!includeSystem && (!(fi.isFile() || fi.isDir() || fi.isSymLink()) || (!fi.exists() && fi.isSymLink()))) return false; // skip directories const bool skipDirs = !(filters & (QDir::Dirs | QDir::AllDirs)); if (skipDirs && fi.isDir()) return false; // skip files const bool skipFiles = !(filters & QDir::Files); if (skipFiles && fi.isFile()) // Basically we need a reason not to exclude this file otherwise we just eliminate it. return false; // filter permissions const bool filterPermissions = ((filters & QDir::PermissionMask) && (filters & QDir::PermissionMask) != QDir::PermissionMask); const bool doWritable = !filterPermissions || (filters & QDir::Writable); const bool doExecutable = !filterPermissions || (filters & QDir::Executable); const bool doReadable = !filterPermissions || (filters & QDir::Readable); if (filterPermissions && ((doReadable && !fi.isReadable()) || (doWritable && !fi.isWritable()) || (doExecutable && !fi.isExecutable()))) { return false; } return true; }
void OptimizationPasses::Coordinator::init() { static bool isInitialized = false; // STATIC DATA if(isInitialized) return; isInitialized = true; /* Note, below is many of the building blocks re-used in several passes * in order to reduce memory use. Thus, when changing one building block * it potentially affects many passes. */ /* ****************************************************** */ /* Rewrite "count(<expr>) ge 1" into "exists(<expr>)" */ OptimizationPass::ExpressionMarker firstFirstChild; firstFirstChild.append(0); firstFirstChild.append(0); ExpressionIdentifier::List geOpIDs; const ExpressionIdentifier::Ptr countFN(new ByIDIdentifier(Expression::IDCountFN)); geOpIDs.append(countFN); geOpIDs.append(ExpressionIdentifier::Ptr(new IntegerIdentifier(1))); QVector<Expression::ID> geMatcher; geMatcher.append(Expression::IDValueComparison); geMatcher.append(Expression::IDGeneralComparison); const ExpressionIdentifier::Ptr ge(new ComparisonIdentifier(geMatcher, AtomicComparator::OperatorGreaterOrEqual)); const ExpressionCreator::Ptr existsFN(new ByIDCreator(Expression::IDExistsFN)); const OptimizationPass::Ptr geToExists(new OptimizationPass(ge, geOpIDs, firstFirstChild, existsFN)); comparisonPasses.append(geToExists); /* ****************************************************** */ /* ****************************************************** */ /* Rewrite "count(<expr>) gt 0" into "exists(<expr>)" */ ExpressionIdentifier::List countAndIntZero; countAndIntZero.append(countFN); const ExpressionIdentifier::Ptr zeroInteger(new IntegerIdentifier(0)); countAndIntZero.append(zeroInteger); const ExpressionIdentifier::Ptr gt(new ComparisonIdentifier(geMatcher, AtomicComparator::OperatorGreaterThan)); const OptimizationPass::Ptr gtToExists(new OptimizationPass(gt, countAndIntZero, firstFirstChild, existsFN)); comparisonPasses.append(gtToExists); /* ****************************************************** */ /* ****************************************************** */ /* Rewrite "count(<expr>) ne 0" into "exists(<expr>)" */ const ExpressionIdentifier::Ptr ne(new ComparisonIdentifier(geMatcher, AtomicComparator::OperatorNotEqual)); const OptimizationPass::Ptr neToExists(new OptimizationPass(ne, countAndIntZero, firstFirstChild, existsFN, OptimizationPass::AnyOrder)); comparisonPasses.append(neToExists); /* ****************************************************** */ /* ****************************************************** */ /* Rewrite "count(<expr>) eq 0" into "empty(<expr>)" */ ExpressionIdentifier::List eqOpIDs; eqOpIDs.append(countFN); eqOpIDs.append(zeroInteger); const ExpressionCreator::Ptr emptyFN(new ByIDCreator(Expression::IDEmptyFN)); const ExpressionIdentifier::Ptr eq(new ComparisonIdentifier(geMatcher, AtomicComparator::OperatorEqual)); const OptimizationPass::Ptr eqToEmpty(new OptimizationPass(eq, eqOpIDs, firstFirstChild, emptyFN, OptimizationPass::AnyOrder)); comparisonPasses.append(eqToEmpty); /* ****************************************************** */ /* ****************************************************** */ /* Rewrite "for $var in <expr> return $var" into "<expr>" */ ExpressionIdentifier::List forOps; OptimizationPass::ExpressionMarker firstChild; firstChild.append(0); forOps.append(ExpressionIdentifier::Ptr()); forOps.append(ExpressionIdentifier::Ptr(new ByIDIdentifier(Expression::IDRangeVariableReference))); const OptimizationPass::Ptr simplifyFor(new OptimizationPass(ExpressionIdentifier::Ptr(), forOps, firstChild, ExpressionCreator::Ptr())); forPasses.append(simplifyFor); /* ****************************************************** */ /* ****************************************************** */ /* Rewrite "if(<expr>) then true() else false()" to "<expr>" */ OptimizationPass::ExpressionMarker marker; marker.append(0); ExpressionIdentifier::List opIDs; opIDs.append(ExpressionIdentifier::Ptr(new BySequenceTypeIdentifier( CommonSequenceTypes::ExactlyOneBoolean))); opIDs.append(ExpressionIdentifier::Ptr(new BooleanIdentifier(true))); opIDs.append(ExpressionIdentifier::Ptr(new BooleanIdentifier(false))); const OptimizationPass::Ptr pass(new OptimizationPass(ExpressionIdentifier::Ptr(), opIDs, marker)); ifThenPasses.append(pass); /* ****************************************************** */ /* ****************************************************** */ /* Rewrite "not(exists(X))" into "empty(X)" */ ExpressionIdentifier::List idExistsFN; idExistsFN.append(ExpressionIdentifier::Ptr(new ByIDIdentifier(Expression::IDExistsFN))); notFN.append(OptimizationPass::Ptr(new OptimizationPass(ExpressionIdentifier::Ptr(), idExistsFN, firstFirstChild, emptyFN))); /* Rewrite "not(empty(X))" into "exists(X)" */ ExpressionIdentifier::List idEmptyFN; idEmptyFN.append(ExpressionIdentifier::Ptr(new ByIDIdentifier(Expression::IDEmptyFN))); notFN.append(OptimizationPass::Ptr(new OptimizationPass(ExpressionIdentifier::Ptr(), idEmptyFN, firstFirstChild, existsFN))); /* ****************************************************** */ }
QVector<ushort> CryptXOR::crypt(const QVector<ushort> input) { QVector<ushort> output = input; for (int i = 0; i < input.size(); i++) output[i] ^= m_key[i % (sizeof(m_key) / sizeof(char)) ]; return output; }
QString CryptXOR::toString(QVector<ushort> vector){ QString result = ""; for (QVector<ushort>::iterator i = vector.begin();i != vector.end() ;++i) result += uchar(*i); return result; }
void FuzzySearchImpl::query(const QString &req, QVector<Service::Item *> *res) const { QVector<QString> words; for (QString &word : req.split(QRegExp("\\W+"), QString::SkipEmptyParts)) words.append(word.toLower()); QVector<QMap<Service::Item *, unsigned int>> resultsPerWord; // Quit if there are no words in query if (words.empty()) return; // Split the query into words for (QString &word : words) { unsigned int delta = word.size()/3; // Get qGrams with counts of this word QMap<QString, unsigned int> qGrams; QString spaced(_q-1,' '); spaced.append(word.toLower()); for (unsigned int i = 0 ; i < static_cast<unsigned int>(word.size()); ++i) ++qGrams[spaced.mid(i,_q)]; // Get the words referenced by each qGram an increment their // reference counter QMap<QString, unsigned int> wordMatches; // Iterate over the set of qgrams in the word for (QMap<QString, unsigned int>::const_iterator it = qGrams.cbegin(); it != qGrams.end(); ++it) { // Iterate over the set of words referenced by this qGram for (QMap<QString, unsigned int>::const_iterator wit = _qGramIndex[it.key()].begin(); wit != _qGramIndex[it.key()].cend(); ++wit) { // CRUCIAL: The match can contain only the commom amount of qGrams wordMatches[wit.key()] += (it.value() < wit.value()) ? it.value() : wit.value(); } } // Allocate a new set resultsPerWord.push_back(QMap<Service::Item *, unsigned int>()); QMap<Service::Item *, unsigned int>& resultsRef = resultsPerWord.back(); // Unite the items referenced by the words accumulating their #matches for (QMap<QString, unsigned int>::const_iterator wm = wordMatches.begin(); wm != wordMatches.cend(); ++wm) { // // Do some kind of (cheap) preselection by mathematical bound // if (wm.value() < qGrams.size()-delta*_q) // continue; // Now check the (expensive) prefix edit distance if (!checkPrefixEditDistance(word, wm.key(), delta)) continue; for(Service::Item * item: _invertedIndex[wm.key()]) { resultsRef[item] += wm.value(); } } } // Intersect the set of items references by the (referenced) words // This assusmes that there is at least one word (the query would not have // been started elsewise) QVector<QPair<Service::Item *, unsigned int>> finalResult; if (resultsPerWord.size() > 1) { // Get the smallest list for intersection (performance) unsigned int smallest=0; for (unsigned int i = 1; i < static_cast<unsigned int>(resultsPerWord.size()); ++i) if (resultsPerWord[i].size() < resultsPerWord[smallest].size()) smallest = i; bool allResultsContainEntry; for (QMap<Service::Item *, unsigned int>::const_iterator r = resultsPerWord[smallest].begin(); r != resultsPerWord[smallest].cend(); ++r) { // Check if all results contain this entry allResultsContainEntry=true; unsigned int accMatches = resultsPerWord[smallest][r.key()]; for (unsigned int i = 0; i < static_cast<unsigned int>(resultsPerWord.size()); ++i) { // Ignore itself if (i==smallest) continue; // If it is in: check next relutlist if (resultsPerWord[i].contains(r.key())) { // Accumulate matches accMatches += resultsPerWord[i][r.key()]; continue; } allResultsContainEntry = false; break; } // If this is not common, check the next entry if (!allResultsContainEntry) continue; // Finally this match is common an can be put into the results finalResult.append(QPair<Service::Item *, unsigned int>(r.key(), accMatches)); } } else // Else do it without intersction { for (QMap<Service::Item *, unsigned int>::const_iterator r = resultsPerWord[0].begin(); r != resultsPerWord[0].cend(); ++r) finalResult.append(QPair<Service::Item *, unsigned int>(r.key(), r.value())); } // Sort em by relevance std::sort(finalResult.begin(), finalResult.end(), [&](QPair<Service::Item *, unsigned int> x, QPair<Service::Item *, unsigned int> y) {return x.second > y.second;}); for (QPair<Service::Item *, unsigned int> pair : finalResult){ res->append(pair.first); } }
// plots heart-rate data void MainWindow::setupDemo(QCustomPlot *customPlot) { // opens heart-rate data and checks if something selected dataname = QFileDialog::getOpenFileName(this,"Open a Heart-Rate Data Text File","","*.txt"); if(dataname.isEmpty()){ QMessageBox::information(this, "File Status", "No heart-rate data was loaded."); return; } // parses heart-rate data text file and plots it into ui->customPlot (for heart rate) QVector<QString> v; QFile textFile(dataname); QFile d(dataname); QFileInfo dInfo(d.fileName()); QString dataname_display(dInfo.fileName()); if(textFile.open(QIODevice::ReadOnly)) { QString all; QTextStream textStream(&textFile); while (!textStream.atEnd()) { textStream >> all; if(textStream.status() == QTextStream::Ok){ v.append(all); } else break; } if (heart_rate_plots_count == 0){ a.resize(v.size()-1), b.resize(v.size()-1); } if (heart_rate_plots_count == 1){ a2.resize(v.size()-1), b2.resize(v.size()-1); } if (heart_rate_plots_count == 2){ a3.resize(v.size()-1), b3.resize(v.size()-1); } if (heart_rate_plots_count == 3){ a4.resize(v.size()-1), b4.resize(v.size()-1); } if (heart_rate_plots_count == 4){ a5.resize(v.size()-1), b5.resize(v.size()-1); } if (heart_rate_plots_count == 5){ a6.resize(v.size()-1), b6.resize(v.size()-1); } if (heart_rate_plots_count == 6){ a7.resize(v.size()-1), b7.resize(v.size()-1); } if (heart_rate_plots_count == 7){ a8.resize(v.size()-1), b8.resize(v.size()-1); } if (heart_rate_plots_count == 8){ a9.resize(v.size()-1), b9.resize(v.size()-1); } if (heart_rate_plots_count == 9){ a10.resize(v.size()-1), b10.resize(v.size()-1); } for(int i=1; i<v.size(); ++i) { string v_i_as_string = v[i].toUtf8().constData(); int comma_pos = v_i_as_string.find(","); double x_double = stod(v_i_as_string.substr(0,comma_pos)); double y_double = stod(v_i_as_string.substr(comma_pos+1,v_i_as_string.length())); if (heart_rate_plots_count == 0){ a[i-1] = x_double; b[i-1] = y_double; } if (heart_rate_plots_count == 1){ a2[i-1] = x_double; b2[i-1] = y_double; } if (heart_rate_plots_count == 2){ a3[i-1] = x_double; b3[i-1] = y_double; } if (heart_rate_plots_count == 3){ a4[i-1] = x_double; b4[i-1] = y_double; } if (heart_rate_plots_count == 4){ a5[i-1] = x_double; b5[i-1] = y_double; } if (heart_rate_plots_count == 5){ a6[i-1] = x_double; b6[i-1] = y_double; } if (heart_rate_plots_count == 6){ a7[i-1] = x_double; b7[i-1] = y_double; } if (heart_rate_plots_count == 7){ a8[i-1] = x_double; b8[i-1] = y_double; } if (heart_rate_plots_count == 8){ a9[i-1] = x_double; b9[i-1] = y_double; } if (heart_rate_plots_count == 9){ a10[i-1] = x_double; b10[i-1] = y_double; } } //sets ending point to the duration of video ending_point = (mMediaPlayer->duration())/1000; // add and color the graphs customPlot->addGraph(); QPen graphPen; if (heart_rate_plots_count == 0){ customPlot->graph()->setData(a, b); graphPen.setColor(Qt::red); hr_legend_qstring += "Legend\nRed: " + dataname_display; } if (heart_rate_plots_count == 1){ customPlot->graph()->setData(a2, b2); graphPen.setColor(Qt::darkGreen); hr_legend_qstring += "\nDark Green: " + dataname_display; } if (heart_rate_plots_count == 2){ customPlot->graph()->setData(a3, b3); graphPen.setColor(Qt::blue); hr_legend_qstring += "\nBlue: " + dataname_display; } if (heart_rate_plots_count == 3){ customPlot->graph()->setData(a4, b4); graphPen.setColor(Qt::black); hr_legend_qstring += "\nBlack: " + dataname_display; } if (heart_rate_plots_count == 4){ customPlot->graph()->setData(a5, b5); graphPen.setColor(Qt::darkCyan); hr_legend_qstring += "\nDark Cyan: " + dataname_display; } if (heart_rate_plots_count == 5){ customPlot->graph()->setData(a6, b6); graphPen.setColor(Qt::darkMagenta); hr_legend_qstring += "\nDark Magenta: " + dataname_display; } if (heart_rate_plots_count == 6){ customPlot->graph()->setData(a7, b7); graphPen.setColor(Qt::darkYellow); hr_legend_qstring += "\nDark Yellow: " + dataname_display; } if (heart_rate_plots_count == 7){ customPlot->graph()->setData(a8, b8); graphPen.setColor(Qt::darkRed); hr_legend_qstring += "\nDark Red: " + dataname_display; } if (heart_rate_plots_count == 8){ customPlot->graph()->setData(a9, b9); graphPen.setColor(Qt::darkGray); hr_legend_qstring += "\nDark Gray: " + dataname_display; } if (heart_rate_plots_count == 9){ customPlot->graph()->setData(a10, b10); graphPen.setColor(Qt::darkBlue); hr_legend_qstring += "\nDark Blue: " + dataname_display; } ui->hr_legend->setText(hr_legend_qstring); heart_rate_plots_count++; graphPen.setWidthF(1); customPlot->graph()->setPen(graphPen); // rescales time axis to match video length customPlot->graph()->rescaleAxes(); customPlot->xAxis->setRangeLower(0); customPlot->xAxis->setRangeUpper((mMediaPlayer->duration())/1000); // makes ui->customPlot (heart rate) zoomable and draggable customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom); customPlot->replot(); //Message showing user heart-rate data has been loaded. QMessageBox::information(this, "File Status", dataname_display + " has been loaded."); }
void BikerHttpRequestProcessor::processRequest() { std::cerr << "processing request..." << std::endl; QRegExp numberRegExp("(\\d+(?:.\\d+)?)"); //Es wird nur GET unterstützt, der Rest nicht. Bei was anderem: Grantig sein und 405 antworten. if (_requestType != "GET") { this->send405(); return; } if (_requestPath.contains("..")) { //".." im Pfad ist ein falscher Request. Damit könnte man ins Dateisystem gelangen. std::cerr << "\"..\" in request: not allowed." << std::endl; this->send400(); } std::cerr << "request file: " << _requestPath << std::endl; if (_requestPath.startsWith("/files/")) { if (! ProgramOptions::getInstance()->webserver_no_serve_files) { //"/files/" entfernen! QString _myRequestPath = _requestPath.remove(0, 7); QDir mainDir((ProgramOptions::getInstance()->webserver_public_html_folder).c_str()); if ((ProgramOptions::getInstance()->webserver_public_html_folder == "") || !mainDir.exists()) { this->send404(); return; } QFile file(QString(ProgramOptions::getInstance()->webserver_public_html_folder.c_str()) + "/" + _myRequestPath); QDir dir(QString(ProgramOptions::getInstance()->webserver_public_html_folder.c_str()) + "/" + _myRequestPath); //Wenn die Datei existiert, und alle sie lesen dürfen (nicht nur // Benutzer oder Gruppe): Datei senden. Sonst: 404 Not found. if ((!dir.exists()) && file.exists() && (file.permissions() & QFile::ReadOther)) { std::cerr << "serving file: \"" << file.fileName() << "\"" << std::endl; this->sendFile(file); } else { if (dir.exists()) std::cerr << "file is a directory: \"" << file.fileName() << "\". Not serving." << std::endl; else if (!file.exists()) std::cerr << "file not found: \"" << file.fileName() << "\". Not serving." << std::endl; else if (file.permissions() & QFile::ReadOther) std::cerr << "file does not have read permissions for everybody: \"" << file.fileName() << "\". Not serving." << std::endl; //In jedem Fall: 404 senden. this->send404(); } return; } else { //Dateien ausliefern durch Einstellungen verboten: Nicht ausliefern. std::cerr << "webserver configured not to serve files." << std::endl; this->send404(); return; } } else { /** * @todo RegExp nur einmal erzeugen und dann wiederverwenden! */ QRegExp cloudmadeApiKeyRegExp("^/([\\da-fA-F]{1,64})/(?:api|API)/0.(\\d)"); //QRegExp cloudmadeApiPointListRegExp("^/(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16})),(?:\\[(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))(?:,(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))){0,20}\\],)?(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))"); QRegExp cloudmadeApiPointListRegExp("^/(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16})),(?:\\[(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))(?:,(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16})){0,200}\\],)?(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))"); QRegExp cloudmadeApiPointListExtractor("(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))"); QRegExp cloudmadeApiRouteTypeRegExp("^/([a-zA-Z0-9]{1,64})(?:/([a-zA-Z0-9]{1,64}))?.(gpx|GPX|js|JS)$"); QString apiKey=""; int apiVersion=0; QVector<GPSPosition> routePointList; QString routeType=""; QString routeModifier=""; QString routeDataType=""; int position=0; if ((position=cloudmadeApiKeyRegExp.indexIn(_requestPath)) != -1) { apiKey = cloudmadeApiKeyRegExp.cap(1).toLower(); apiVersion = cloudmadeApiKeyRegExp.cap(2).toInt(); //API-Key gefunden. Falls uns der interessiert, hier was damit machen! if (ProgramOptions::getInstance()->webserver_apikey != "") { if (ProgramOptions::getInstance()->webserver_apikey != apiKey.toStdString()) { std::cerr << "api key \"" << apiKey << "\" is not valid." << std::endl; this->send403(); return; } } if (apiVersion != 3) { std::cerr << "requested api version 0." << apiVersion << ", which is not supported." << std::endl; this->send405(); return; } position += cloudmadeApiKeyRegExp.cap(0).length(); } else { this->send400(); return; } position+=cloudmadeApiPointListRegExp.indexIn(_requestPath.mid(position)); if (cloudmadeApiPointListRegExp.cap(0).length() != 0) { //Punktliste gefunden. Auswerten! //Neue RegExp zum Punkte herausholen... cloudmadeApiPointListExtractor.indexIn(cloudmadeApiPointListRegExp.cap(0)); QString strLat, strLon; routePointList.clear(); for (int pos=0; pos>=0; pos=cloudmadeApiPointListExtractor.indexIn(cloudmadeApiPointListRegExp.cap(0), cloudmadeApiPointListExtractor.cap(0).length()+pos)) { strLat = cloudmadeApiPointListExtractor.cap(1); strLon = cloudmadeApiPointListExtractor.cap(2); GPSPosition point(strLat.toDouble(), strLon.toDouble()); routePointList << point; } position += cloudmadeApiPointListRegExp.cap(0).length(); } else { this->send400(); return; } position+=cloudmadeApiRouteTypeRegExp.indexIn(_requestPath.mid(position)); if (cloudmadeApiRouteTypeRegExp.cap(0).length() != 0) { routeType = cloudmadeApiRouteTypeRegExp.cap(1).toLower(); routeModifier = cloudmadeApiRouteTypeRegExp.cap(2).toLower(); routeDataType = cloudmadeApiRouteTypeRegExp.cap(3).toLower(); //Routentyp gefunden. Auswerten! } else { this->send400(); return; } //this->send102(); boost::shared_ptr<RoutingMetric> metric; boost::shared_ptr<Router> router; boost::shared_ptr<DatabaseConnection> dbA; boost::shared_ptr<DatabaseConnection> dbB; boost::shared_ptr<AltitudeProvider> altitudeProvider; #ifdef ZZIP_FOUND altitudeProvider.reset(new SRTMProvider()); #else altitudeProvider.reset(new ZeroAltitudeProvider()); #endif if ((routeType == "bicycle") || (routeType == "bike")) { //altitudeProvider.reset(new ZeroAltitudeProvider()); //Routingmetrik festlegen anhand der Benutzerwahl if ((routeModifier == "euclidean")) { metric.reset(new EuclideanRoutingMetric(altitudeProvider)); } else if ((routeModifier == "simpleheight") || (routeModifier == "shortest")) { float detourPerHeightMeter = 100.0f; if (numberRegExp.indexIn(_parameterMap["detourperheightmeter"]) != -1) { detourPerHeightMeter = numberRegExp.cap(1).toFloat(); } metric.reset(new SimpleHeightRoutingMetric(altitudeProvider, detourPerHeightMeter)); } else if (routeModifier == "advancedheight") { float punishment = 1.0f; float detourPerHeightMeter = 200.0f; if (numberRegExp.indexIn(_parameterMap["punishment"]) != -1) { punishment = numberRegExp.cap(1).toFloat(); } if (numberRegExp.indexIn(_parameterMap["detourperheightmeter"]) != -1) { detourPerHeightMeter = numberRegExp.cap(1).toFloat(); } metric.reset(new AdvancedHeightRoutingMetric(altitudeProvider, detourPerHeightMeter, punishment)); } else if (routeModifier == "simplepower") { double weight = 90.0; double efficiency = 3 * weight; if (numberRegExp.indexIn(_parameterMap["weight"]) != -1) weight = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["efficiency"]) != -1) efficiency = numberRegExp.cap(1).toDouble(); metric.reset(new SimplePowerRoutingMetric(altitudeProvider, weight, efficiency)); } else if ((routeModifier == "power") || (routeModifier == "") || (routeModifier == "fastest")) { double weight = 90.0; //double maxPower = 140.0; double maxPower = 150.0; double minSpeed = 2.5; double pushBikeSpeed = 0.5; double haltungskorrekturfaktor = 0.4; double maxSpeed = -1.0; double noCyclewayPunishmentFactor = 5; if (numberRegExp.indexIn(_parameterMap["weight"]) != -1) weight = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["maxpower"]) != -1) maxPower = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["minspeed"]) != -1) minSpeed = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["maxspeed"]) != -1) maxSpeed = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["pushbikespeed"]) != -1) pushBikeSpeed = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["nocyclewaypunishmentfactor"]) != -1) noCyclewayPunishmentFactor = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["haltungskorrekturfaktor"]) != -1) haltungskorrekturfaktor = numberRegExp.cap(1).toDouble(); metric.reset(new PowerRoutingMetric(altitudeProvider, weight, maxPower, minSpeed, pushBikeSpeed, haltungskorrekturfaktor, noCyclewayPunishmentFactor ,maxSpeed)); } else if ((routeModifier == "biketourpower") || (routeModifier == "biketour")) { double weight = 90.0; //double maxPower = 140.0; double maxPower = 100.0; double minSpeed = 2.5; double pushBikeSpeed = 0.5; double haltungskorrekturfaktor = 0.4; double maxSpeed = -1.0; double noCyclewayPunishmentFactor = 7; if (numberRegExp.indexIn(_parameterMap["weight"]) != -1) weight = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["maxpower"]) != -1) maxPower = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["minspeed"]) != -1) minSpeed = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["maxspeed"]) != -1) maxSpeed = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["pushbikespeed"]) != -1) pushBikeSpeed = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["nocyclewaypunishmentfactor"]) != -1) noCyclewayPunishmentFactor = numberRegExp.cap(1).toDouble(); if (numberRegExp.indexIn(_parameterMap["haltungskorrekturfaktor"]) != -1) haltungskorrekturfaktor = numberRegExp.cap(1).toDouble(); metric.reset(new BikeTourPowerRoutingMetric(altitudeProvider, weight, maxPower, minSpeed, pushBikeSpeed, haltungskorrekturfaktor, noCyclewayPunishmentFactor ,maxSpeed)); } else { std::cerr << "routeModifier \"" << routeModifier << "\" not supported." << std::endl; this->send405(); return; } } else if (routeType == "car") { //TODO this->send405(); return; } else if (routeType == "foot") { if ((routeModifier == "euclidean") || (routeModifier == "") || (routeModifier == "shortest") || (routeModifier == "fastest")) { metric.reset(new EuclideanRoutingMetric(altitudeProvider)); } } else { std::cerr << "requested routeType=" << routeType << ", which is not supported." << std::endl; this->send405(); return; } #ifdef SPATIALITE_FOUND if (ProgramOptions::getInstance()->dbBackend == "spatialite") { dbA.reset(new SpatialiteDatabaseConnection()); dbB.reset(new SpatialiteDatabaseConnection()); } else #endif if (ProgramOptions::getInstance()->dbBackend == "sqlite") { dbA.reset(new SQLiteDatabaseConnection()); dbB.reset(new SQLiteDatabaseConnection()); } //Datenbank ist die globale DB... dbA->open(ProgramOptions::getInstance()->dbFilename.c_str()); dbB->open(ProgramOptions::getInstance()->dbFilename.c_str()); //TODO: Testen, ob das mit dem Cache überhaupt was bringt... dbA = boost::shared_ptr<DatabaseConnection>(new DatabaseRAMCache(dbA, ProgramOptions::getInstance()->dbCacheSize)); dbB = boost::shared_ptr<DatabaseConnection>(new DatabaseRAMCache(dbB, ProgramOptions::getInstance()->dbCacheSize)); //Routingalgorithmus heraussuchen, je nach Angabe. Standard: Mehrthread-A* oder Mehrthread-Dijkstra - je nach Metrik. if (_parameterMap["algorithm"] == "multithreadeddijkstra") router.reset(new MultithreadedDijkstraRouter(dbA, dbB, metric)); else if (_parameterMap["algorithm"] == "dijkstra") router.reset(new DijkstraRouter(dbA, metric)); else if (_parameterMap["algorithm"] == "astar") router.reset(new AStarRouter(dbA, metric)); else if (_parameterMap["algorithm"] == "multithreadedastar") router.reset(new MultithreadedAStarRouter(dbA, dbB, metric)); else { if (metric->getMeasurementUnit() == DISTANCE) router.reset(new MultithreadedAStarRouter(dbA, dbB, metric)); else router.reset(new MultithreadedDijkstraRouter(dbA, dbB, metric)); } //Route berechnen GPSRoute route = router->calculateShortestRoute(routePointList); //Keine Route gefunden? 404 senden. if (route.isEmpty()) { std::cerr << "no route found." << std::endl; this->send404(); return; } else { std::cerr << "found route." << std::endl << " length: " << route.calcLength()/1000.0 << "km" << std::endl << " duration: " << route.getDuration()/60.0 << "min" << std::endl << " has " << route.getSize() << " points." << std::endl; } //Antwort entsprechend des Routentypen senden. if (routeDataType == "gpx") this->sendFile(route.exportGPXString(altitudeProvider)); else if (routeDataType == "js") this->sendFile(route.exportJSONString()); else std::cerr << "route datatype \"" << routeDataType << "\" not supported." << std::endl; return; } }
void DiagramScene::setValues(QMap<QString, QVector<QPointF> > values) { if(!values.keys().size()) { mouseline=0; clear(); return; } if(!values[values.keys().at(0)].size()) { mouseline=0; clear(); return; } bool dirty = true; int searchiteration=0; while(dirty && searchiteration<1000) { searchiteration++; mouseline=0; clear(); for(int index=0; index < value.size(); index++) delete value[value.keys().at(index)]; value.clear(); minvaluex=0.0; maxvaluex=0.0; minvaluey=0.0; maxvaluey=0.0; if(!yscale) yscale=1; data=values; if(!values.size()) return; for(int index=0; index < values.size(); index++) { QPen pen(QColor(((index+1)*948)%200+50,((index+1)*123)%200+50,((index+1)*11)%200+50)); QPainterPath tmppath; QVector<QPointF> result = values[values.keys().at(index)]; value[data.keys().at(index)] = new QMap<qreal,qreal>(); for(int pointindex=0; pointindex < result.size(); pointindex++) { qreal x = (qreal)(result[pointindex].x()); qreal y = (qreal)(result[pointindex].y()); (*value[data.keys().at(index)])[x]=y; if(!pointindex && !index) { minvaluex=x; maxvaluex=x; minvaluey=(double)y/(double)yscale; maxvaluey=(double)y/(double)yscale; } if(!pointindex) tmppath.moveTo(x*prec,(-y/yscale)*prec); else tmppath.lineTo(x*prec,(-y/yscale)*prec); if(x > maxvaluex) maxvaluex=(double)x; if(x < minvaluex) minvaluex=(double)x; if((double)y/yscale > maxvaluey) maxvaluey=(double)y/yscale; if((double)y/yscale < minvaluey) minvaluey=(double)y/yscale; } addPath(tmppath,pen); } dirty = false; qreal maxyvalue = maxvaluey-minvaluey; if(maxvaluey==minvaluey) maxyvalue = qAbs(maxvaluey); qreal LOWY = 20.0; qreal UPPERY = 80.0; if(maxyvalue < LOWY || maxyvalue > UPPERY) { yscale *=maxyvalue/((double)(UPPERY-LOWY)/2.0 + LOWY); dirty = true; } } showGrid(); qreal w , h; h = maxvaluey-minvaluey; w = maxvaluex-minvaluex; if(w < h * 3) w = h * 3; setSceneRect(minvaluex*prec,-maxvaluey*prec,w*prec, h*prec); QList<QGraphicsView*> viewers = views(); for(int index=0; index < viewers.size(); index++) { viewers.at(index)->fitInView(sceneRect(),Qt::KeepAspectRatioByExpanding); viewers.at(index)->centerOn(maxvaluex*prec,qRound(sceneRect().topRight().y())); } }
QString MyString::dataToDotString(Data *data, int type) { QString s; //select edges/titles based on type QVector<Arrow> *edgesPtr; QHash<int, QString> *titlesPtr; QString filter; switch (type) { case DOT_TYPE_AFFORDANCE: titlesPtr = &(data->affordanceStateTitles); edgesPtr = &(data->affordanceEdges); filter = data->affordanceFilter; break; case DOT_TYPE_ACTION: titlesPtr = &(data->actionStateTitles); edgesPtr = &(data->actionEdges); filter = data->actionFilter; break; case DOT_TYPE_ABSTRACT: titlesPtr = &(data->abstractStateTitles); edgesPtr = &(data->abstractEdges); break; default: return s; break; } //parse filter string QStringList stateNos = filter.split(","); QSet<int> filteredSet; int filteredSetSize = stateNos.count(); //build set of filtered states for (int index = 0; index < filteredSetSize; index++) { int value = stateNos.at(index).toInt(); if (!value) continue; filteredSet.insert(value); } s += ("digraph d {\n"); s += ("graph [ bgcolor=\"white\", resolution=\"128\", fontname=\"Helvetica\", fontcolor=\"black\", fontsize=\"10\" ];"); s += ("node [ fontname=\"Helvetica\", penwidth=\"0.25\", fontcolor=\"gray32\", fontsize=\"8\"];"); s += ("edge [ color=\"gray32\", arrowsize=\"0.75\", penwidth=\"0.25\", fontname=\"Helvetica\", fontcolor=\"dodgerblue4\", fontsize=\"8\", arrowhead=\"vee\" ];"); //states std::map<int, QString> states; //tbd: check if necessary int size = edgesPtr->count(); for (int i = 1; i < size; i++) //omit initial state 0 { int sourceId, targetId; sourceId = edgesPtr->at(i).source; targetId = edgesPtr->at(i).target; QString source, target; source = MyString::makeState(sourceId, (*titlesPtr)[sourceId]); target = MyString::makeState(targetId, (*titlesPtr)[targetId]); states.insert(std::make_pair(sourceId, source)); states.insert(std::make_pair(targetId, target)); } std::map<int, QString>::iterator it; for (it = states.begin(); it != states.end(); it++) { bool active = true; if (!filter.isEmpty() && !filteredSet.contains(it->first)) { active = false; } QString state; if (!active) { state += "//"; } state += QString::number(it->first); state += " [label=\""; state += it->second; state += "\"]\n"; s += state; } //arrows size = edgesPtr->count(); int source, target; for (int i = 1; i < size; i++) //omit initial state 0 { Arrow a = edgesPtr->at(i); source = a.source; target = a.target; bool active = true; if (!filter.isEmpty() && ((!filteredSet.contains(source) || !filteredSet.contains(target)))) { active = false; } QString arrow; if (!active) { arrow += "//"; } arrow += a.toString(); s += arrow; } //end dot structure s += "}\n"; return s; }
/*! \fn void QTextTable::removeColumns(int index, int columns) Removes a number of \a columns starting with the column at the specified \a index. \sa insertRows() insertColumns() removeRows() resize() appendRows() appendColumns() */ void QTextTable::removeColumns(int pos, int num) { Q_D(QTextTable); // qDebug() << "-------- removeCols" << pos << num; if (num <= 0 || pos < 0) return; if (d->dirty) d->update(); if (pos >= d->nCols) return; if (pos + num > d->nCols) pos = d->nCols - num; QTextDocumentPrivate *p = d->pieceTable; QTextFormatCollection *collection = p->formatCollection(); p->beginEditBlock(); // delete whole table? if (pos == 0 && num == d->nCols) { const int pos = p->fragmentMap().position(d->fragment_start); p->remove(pos, p->fragmentMap().position(d->fragment_end) - pos + 1); p->endEditBlock(); return; } p->aboutToRemoveCell(cellAt(0, pos).firstPosition(), cellAt(d->nRows - 1, pos + num - 1).lastPosition()); QList<int> touchedCells; for (int r = 0; r < d->nRows; ++r) { for (int c = pos; c < pos + num; ++c) { int cell = d->grid[r*d->nCols + c]; QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell); QTextCharFormat fmt = collection->charFormat(it->format); int span = fmt.tableCellColumnSpan(); if (touchedCells.contains(cell) && span <= 1) continue; touchedCells << cell; if (span > 1) { fmt.setTableCellColumnSpan(span - 1); p->setCharFormat(it.position(), 1, fmt); } else { // remove cell int index = d->cells.indexOf(cell) + 1; int f_end = index < d->cells.size() ? d->cells.at(index) : d->fragment_end; p->remove(it.position(), p->fragmentMap().position(f_end) - it.position()); } } } QTextTableFormat tfmt = format(); tfmt.setColumns(tfmt.columns()-num); QVector<QTextLength> columnWidths = tfmt.columnWidthConstraints(); if (columnWidths.count() > pos) { columnWidths.remove(pos, num); tfmt.setColumnWidthConstraints (columnWidths); } QTextObject::setFormat(tfmt); p->endEditBlock(); // qDebug() << "-------- end removeCols" << pos << num; }
void SurfaceItem::render(const Map &map, const Camera &camera) { int zone = map.zone(vertices().at(0)); GLuint tex = textureId(); if (zone < 0) return; m_program->bind(); m_program->setUniformValue(m_matrixUniform, camera.viewProjectionMatrix()); QSize size = surface()->size(); m_program->setUniformValue(m_pixelSizeUniform, 5. / size.width(), 5. / size.height()); m_program->setUniformValue(m_eyeUniform, camera.viewPos()); m_program->setUniformValue(m_focusColorUniform, GLfloat(m_opacity)); m_program->setUniformValueArray(m_lightsUniform, map.lights(zone).constData(), map.lights(zone).size()); m_program->setUniformValue(m_numLightsUniform, map.lights(zone).size()); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, tex); QVector<QVector3D> v = vertices(); QVector3D va = v[0]; QVector3D vb = v[1]; QVector3D vc = v[2]; QVector3D vd = v[3]; QVector<QVector3D> vertexBuffer; vertexBuffer << va << vb << vd << vd << vb << vc; qreal y1 = 0; qreal y2 = 1; if (surface()->origin() == QWaylandSurface::OriginTopLeft) qSwap(y1, y2); QVector<QVector2D> texCoordBuffer; texCoordBuffer << QVector2D(0, y2) << QVector2D(1, y2) << QVector2D(0, y1) << QVector2D(0, y1) << QVector2D(1, y2) << QVector2D(1, y1); m_program->setUniformValue(m_normalUniform, -QVector3D::crossProduct(vb - va, vc - va).normalized()); m_program->enableAttributeArray(m_vertexAttr); m_program->setAttributeArray(m_vertexAttr, vertexBuffer.constData()); m_program->enableAttributeArray(m_texCoordAttr); m_program->setAttributeArray(m_texCoordAttr, texCoordBuffer.constData()); glEnable(GL_BLEND); glDisable(GL_CULL_FACE); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glDrawArrays(GL_TRIANGLES, 0, 6); glDisable(GL_BLEND); m_program->disableAttributeArray(m_texCoordAttr); m_program->disableAttributeArray(m_vertexAttr); #if 0 QOpenGLPaintDevice device(camera.viewSize()); QPainter p(&device); va = camera.viewProjectionMatrix().map(va); vb = camera.viewProjectionMatrix().map(vb); vc = camera.viewProjectionMatrix().map(vc); vd = camera.viewProjectionMatrix().map(vd); QVector3D c(camera.viewSize().width() * 0.5, camera.viewSize().height() * 0.5, 0); va = c + c * va * QVector3D(1, -1, 0); vb = c + c * vb * QVector3D(1, -1, 0); vc = c + c * vc * QVector3D(1, -1, 0); vd = c + c * vd * QVector3D(1, -1, 0); QPointF pa(va.x(), va.y()); QPointF pb(vb.x(), vb.y()); QPointF pc(vc.x(), vc.y()); QPointF pd(vd.x(), vd.y()); p.drawLine(pa, pb); p.drawLine(pb, pc); p.drawLine(pc, pd); p.drawLine(pd, pa); extern QVector3D debug; QVector3D d = camera.viewProjectionMatrix().map(debug); d = c + c * d * QVector3D(1, -1, 0); static QVector3D old; if (debug != old) old = debug; p.setPen(Qt::NoPen); p.setBrush(Qt::red); p.drawEllipse(QRectF(d.x() - 2, d.y() - 2, 4, 4)); p.end(); #endif }
void QgsSimpleLineSymbolLayerV2::applyDataDefinedSymbology( QgsSymbolV2RenderContext& context, QPen& pen, QPen& selPen, double& offset ) { if ( mDataDefinedProperties.isEmpty() ) return; // shortcut //data defined properties QgsExpression* strokeWidthExpression = expression( "width" ); if ( strokeWidthExpression ) { double scaledWidth = strokeWidthExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble() * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mWidthUnit, mWidthMapUnitScale ); pen.setWidthF( scaledWidth ); selPen.setWidthF( scaledWidth ); } //color QgsExpression* strokeColorExpression = expression( "color" ); if ( strokeColorExpression ) { pen.setColor( QgsSymbolLayerV2Utils::decodeColor( strokeColorExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString() ) ); } //offset QgsExpression* lineOffsetExpression = expression( "offset" ); if ( lineOffsetExpression ) { offset = lineOffsetExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble(); } //dash dot vector QgsExpression* dashPatternExpression = expression( "customdash" ); if ( dashPatternExpression ) { double scaledWidth = mWidth * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mWidthUnit, mWidthMapUnitScale ); double dashWidthDiv = mPen.widthF(); if ( strokeWidthExpression ) { dashWidthDiv = pen.widthF(); scaledWidth = pen.widthF(); } //fix dash pattern width in Qt 4.8 QStringList versionSplit = QString( qVersion() ).split( "." ); if ( versionSplit.size() > 1 && versionSplit.at( 1 ).toInt() >= 8 && ( scaledWidth * context.renderContext().rasterScaleFactor() ) < 1.0 ) { dashWidthDiv = 1.0; } QVector<qreal> dashVector; QStringList dashList = dashPatternExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString().split( ";" ); QStringList::const_iterator dashIt = dashList.constBegin(); for ( ; dashIt != dashList.constEnd(); ++dashIt ) { dashVector.push_back( dashIt->toDouble() * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mCustomDashPatternUnit, mCustomDashPatternMapUnitScale ) / dashWidthDiv ); } pen.setDashPattern( dashVector ); } //line style QgsExpression* lineStyleExpression = expression( "line_style" ); if ( lineStyleExpression ) { QString lineStyleString = lineStyleExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString(); pen.setStyle( QgsSymbolLayerV2Utils::decodePenStyle( lineStyleString ) ); } //join style QgsExpression* joinStyleExpression = expression( "joinstyle" ); if ( joinStyleExpression ) { QString joinStyleString = joinStyleExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString(); pen.setJoinStyle( QgsSymbolLayerV2Utils::decodePenJoinStyle( joinStyleString ) ); } //cap style QgsExpression* capStyleExpression = expression( "capstyle" ); if ( capStyleExpression ) { QString capStyleString = capStyleExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString(); pen.setCapStyle( QgsSymbolLayerV2Utils::decodePenCapStyle( capStyleString ) ); } }
void GraphUtils::minCut(QList<ConnectorItem *> & connectorItems, QList<SketchWidget *> & foreignSketchWidgets, ConnectorItem * source, ConnectorItem * sink, QList<ConnectorEdge *> & minCut) { // this helped: http://boost.2283326.n4.nabble.com/graph-edmund-karp-max-flow-vs-kolmogorov-max-flow-color-map-td2565611.html using namespace boost; typedef adjacency_list_traits < vecS, vecS, directedS > Traits; typedef property < vertex_color_t, boost::default_color_type > COLOR; typedef property < vertex_index_t, long, COLOR > VERTEX; typedef property < edge_reverse_t, Traits::edge_descriptor > REVERSE; typedef property < edge_residual_capacity_t, long, REVERSE > RESIDUAL; typedef property < edge_capacity_t, long, RESIDUAL > EDGE; typedef adjacency_list < listS, vecS, directedS, VERTEX, EDGE > Graph; Graph g; property_map < Graph, edge_capacity_t >::type capacity = get(edge_capacity, g); property_map < Graph, edge_residual_capacity_t >::type residual_capacity = get(edge_residual_capacity, g); property_map < Graph, edge_reverse_t >::type reverse = get(edge_reverse, g); property_map < Graph, vertex_color_t >::type color = get(vertex_color, g); property_map < Graph, vertex_index_t >::type index = get(vertex_index, g); Traits::vertex_descriptor s, t; QList<Wire *> visitedWires; QList<int> indexes; QHash<ConnectorItem *, int> vertices; QList<ConnectorEdge *> edges; QVector<Traits::vertex_descriptor> verts; vertices.insert(source, 0); vertices.insert(sink, 1); verts.append(s = add_vertex(g)); verts.append(t = add_vertex(g)); foreach (ConnectorItem * connectorItem, connectorItems) { //connectorItem->debugInfo("input"); if (connectorItem->attachedToItemType() == ModelPart::Wire) { Wire * wire = qobject_cast<Wire *>(connectorItem->attachedTo()); if (visitedWires.contains(wire)) continue; QList<Wire *> wires; QList<ConnectorItem *> ends; wire->collectChained(wires, ends); visitedWires.append(wires); if (ends.count() < 2) continue; foreach (ConnectorItem * end, ends) { appendVertIf(end, vertices, verts); } for (int i = 0; i < ends.count(); i++) { ConnectorItem * end = ends[i]; for (int j = i + 1; j < ends.count(); j++) { ConnectorEdge * connectorEdge = makeConnectorEdge(edges, end, ends[j], 1000, wire); connectorEdge->setHeadTail(vertices.value(connectorEdge->c0), vertices.value(connectorEdge->c1)); } } continue; }
const OperateurDiff& OperateurDiff::evaluate(Pile& pile) const { if (pile.taille() >= getArite()) { try { dynamic_cast<Number&>(pile.top()); } catch(exception&) { throw ComputerException("Erreur : mauvais arguments"); } Number& N2 = dynamic_cast<Number&>(pile.top()); pile.pop(); try { dynamic_cast<Number&>(pile.top()); } catch(exception&) { pile.push(N2); throw ComputerException("Erreur : mauvais arguments"); } Number& N1 = dynamic_cast<Number&>(pile.top()); pile.pop(); double Re1, Re2, Im1, Im2; bool bRe, bIm; //calcul de la partie réelle Re1 = N1.getRe().getNumerateur().getValue()/N1.getRe().getDenominateur().getValue(); Re2 = N2.getRe().getNumerateur().getValue()/N2.getRe().getDenominateur().getValue(); //calcul de la partie réelle Im1 = N1.getIm().getNumerateur().getValue()/N1.getIm().getDenominateur().getValue(); Im2 = N2.getIm().getNumerateur().getValue()/N2.getIm().getDenominateur().getValue(); bRe = Re1 != Re2; bIm = Im1 != Im2; QString res; if(bRe || bIm) { res = "1"; } else { res = "0"; } Expression& e = ExpressionManager::getInstance().addExpression(res); //ajout sur la pile pile.push(e); QString message; message = N1.toString() + " " + this->getSymbole() + " " + N2.toString() + " : " + res; pile.setMessage(message); //sauvegarde des arguments QVector<QString> args; args.push_back(N1.toString()); args.push_back(N2.toString()); pile.setLastArgs(args); } else { throw ComputerException("Erreur : pas assez d'arguments"); } return *this; }
bool FastConvexFitting::getFitting(Geometry & geometry) { if(initflag) { assert(getConfigurations()); initflag=0; } if(configurations.size()==0) { return 0; } centerposition=-(orientation.inverse()*position); int i,n=configurations.size(); for(i=0;i<n;i++) { int j,m=configurations[i].edges.size(); for(j=0;j<m;j++) { configurations[i].globaledges[j].startcorner=position+orientation*configurations[i].edges[j].startcorner; configurations[i].globaledges[j].endcorner=position+orientation*configurations[i].edges[j].endcorner; } } G.score=0; for(i=0;i<n;i++) { if(getEvaluation(configurations[i])&&G.score<configurations[i].score) { G=configurations[i]; } } if(G.score>0) { int j,m=G.geometry.size(); G.sigma.fill(0,m); QVector<double> sum; sum.fill(0,m); for(i=0;i<n;i++) { int diffcount=0; int diffid; for(j=0;j<m;j++) { if(configurations[i].geometry[j]!=G.geometry[j]) { diffcount++; diffid=j; } if(diffcount>=2) { break; } } if(diffcount==1) { G.sigma[diffid]+=configurations[i].score*pow(configurations[i].geometry[diffid]-G.geometry[diffid],2); sum[diffid]+=configurations[i].score; } else if(diffcount==0) { for(j=0;j<m;j++) { sum[j]+=configurations[i].score; } } } for(j=0;j<m;j++) { if(sum[j]>0) { G.sigma[j]/=sum[j]; } if(G.sigma[j]<=0) { G.sigma[j]=100; } } geometry=G; return 1; } else { return 0; } }
QString transform(const QString &pat, const QString &tss, const QVector<const char *> ¶ms) { QString parsed; INFO(i18n("Parsing stylesheet")); #if defined (SIMPLE_XSLT) && defined(Q_OS_WIN) // prepare use of local available dtd versions instead of fetching every time from the internet // this approach is url based if (!defaultEntityLoader) { defaultEntityLoader = xmlGetExternalEntityLoader(); xmlSetExternalEntityLoader(xsltprocExternalEntityLoader); replaceURLList[QLatin1String("http://www.oasis-open.org/docbook/xml/4.5")] = QString("file:///%1").arg(DOCBOOK_XML_CURRDTD); } #endif xsltStylesheetPtr style_sheet = xsltParseStylesheetFile((const xmlChar *)QFile::encodeName(tss).constData()); if (!style_sheet) { return parsed; } if (style_sheet->indent == 1) { xmlIndentTreeOutput = 1; } else { xmlIndentTreeOutput = 0; } INFO(i18n("Parsing document")); xmlParserCtxtPtr pctxt; pctxt = xmlNewParserCtxt(); if ( pctxt == NULL ) { return parsed; } xmlDocPtr doc = xmlCtxtReadFile(pctxt, QFile::encodeName(pat).constData(), NULL, XML_PARSE_NOENT|XML_PARSE_DTDLOAD|XML_PARSE_NONET); /* Clean the context pointer, now useless */ const bool context_valid = (pctxt->valid == 0); xmlFreeParserCtxt(pctxt); /* Check both the returned doc (for parsing errors) and the context (for validation errors) */ if (doc == NULL) { return parsed; } else { if (context_valid) { xmlFreeDoc(doc); return parsed; } } INFO(i18n("Applying stylesheet")); QVector<const char *> p = params; p.append(NULL); xmlDocPtr res = xsltApplyStylesheet(style_sheet, doc, const_cast<const char **>(&p[0])); xmlFreeDoc(doc); if (res != NULL) { xmlOutputBufferPtr outp = xmlOutputBufferCreateIO(writeToQString, 0, &parsed, 0); outp->written = 0; INFO(i18n("Writing document")); xsltSaveResultTo(outp, res, style_sheet); xmlOutputBufferClose(outp); xmlFreeDoc(res); } xsltFreeStylesheet(style_sheet); if (parsed.isEmpty()) { parsed = QLatin1Char(' '); // avoid error message } return parsed; }
bool FastRectangleFitting::getBeamRange(Geometry &configuration, QVector<int> &edgeID, QVector<int> &startID, QVector<int> &endID) { if(centerposition(0)>configuration.geometry[0]/2.0) { if(centerposition(1)>configuration.geometry[1]/2.0) { edgeID.resize(2); edgeID[0]=0; edgeID[1]=3; } else if(centerposition(1)<-configuration.geometry[1]/2.0) { edgeID.resize(2); edgeID[0]=0; edgeID[1]=1; } else { edgeID.resize(1); edgeID[0]=0; } } else if(centerposition(0)<-configuration.geometry[0]/2.0) { if(centerposition(1)>configuration.geometry[1]/2.0) { edgeID.resize(2); edgeID[0]=2; edgeID[1]=3; } else if(centerposition(1)<-configuration.geometry[1]/2.0) { edgeID.resize(2); edgeID[0]=1; edgeID[1]=2; } else { edgeID.resize(1); edgeID[0]=2; } } else { if(centerposition(1)>configuration.geometry[1]/2.0) { edgeID.resize(1); edgeID[0]=3; } else if(centerposition(1)<-configuration.geometry[1]/2.0) { edgeID.resize(1); edgeID[0]=1; } else { return 0; } } double PI=3.141592654; double density=2*PI/beamsnum; int i,n=edgeID.size(); startID.resize(n); endID.resize(n); for(i=0;i<n;i++) { startID[i]=(atan2(configuration.globaledges[edgeID[i]].startcorner(1),configuration.globaledges[edgeID[i]].startcorner(0))+PI)/density; startID[i]=startID[i]>=0?startID[i]:0; startID[i]=startID[i]<beamsnum?startID[i]:beamsnum-1; endID[i]=(atan2(configuration.globaledges[edgeID[i]].endcorner(1),configuration.globaledges[edgeID[i]].endcorner(0))+PI)/density; endID[i]=endID[i]>=0?endID[i]:0; endID[i]=endID[i]<beamsnum?endID[i]:beamsnum-1; } return 1; }
QT_BEGIN_NAMESPACE /*! \class QVersionNumber \inmodule QtCore \since 5.6 \brief The QVersionNumber class contains a version number with an arbitrary number of segments. \snippet qversionnumber/main.cpp 0 */ /*! \fn QVersionNumber::QVersionNumber() Produces a null version. \sa isNull() */ /*! \fn QVersionNumber::QVersionNumber(int maj) Constructs a QVersionNumber consisting of just the major version number \a maj. */ /*! \fn QVersionNumber::QVersionNumber(int maj, int min) Constructs a QVersionNumber consisting of the major and minor version numbers \a maj and \a min, respectively. */ /*! \fn QVersionNumber::QVersionNumber(int maj, int min, int mic) Constructs a QVersionNumber consisting of the major, minor, and micro version numbers \a maj, \a min and \a mic, respectively. */ /*! \fn QVersionNumber::QVersionNumber(const QVector<int> &seg) Constructs a version number from the list of numbers contained in \a seg. */ /*! \fn QVersionNumber::QVersionNumber(QVector<int> &&seg) Move-constructs a version number from the list of numbers contained in \a seg. This constructor is only enabled if the compiler supports C++11 move semantics. */ /*! \fn QVersionNumber::QVersionNumber(std::initializer_list<int> args) Construct a version number from the std::initializer_list specified by \a args. This constructor is only enabled if the compiler supports C++11 initializer lists. */ /*! \fn bool QVersionNumber::isNull() const Returns \c true if there are zero numerical segments, otherwise returns \c false. \sa segments() */ /*! \fn bool QVersionNumber::isNormalized() const Returns \c true if the version number does not contain any trailing zeros, otherwise returns \c false. \sa normalized() */ /*! \fn int QVersionNumber::majorVersion() const Returns the major version number, that is, the first segment. This function is equivalent to segmentAt(0). If this QVersionNumber object is null, this function returns 0. \sa isNull(), segmentAt() */ /*! \fn int QVersionNumber::minorVersion() const Returns the minor version number, that is, the second segment. This function is equivalent to segmentAt(1). If this QVersionNumber object does not contain a minor number, this function returns 0. \sa isNull(), segmentAt() */ /*! \fn int QVersionNumber::microVersion() const Returns the micro version number, that is, the third segment. This function is equivalent to segmentAt(2). If this QVersionNumber object does not contain a micro number, this function returns 0. \sa isNull(), segmentAt() */ /*! \fn const QVector<int>& QVersionNumber::segments() const Returns all of the numerical segments. \sa majorVersion(), minorVersion(), microVersion() */ QVector<int> QVersionNumber::segments() const { if (m_segments.isUsingPointer()) return *m_segments.pointer_segments; QVector<int> result; result.resize(segmentCount()); for (int i = 0; i < segmentCount(); ++i) result[i] = segmentAt(i); return result; }
void MainWindow::orEClicked() { QList<QGraphicsItem *> selected_list = scene->selectedItems(); Node* selected = (Node*)(selected_list.at(0)); selected->setRule("orE"); selected->update(); int rect_x; int rect_y; bool ok; while(1){ QString tekst = QInputDialog::getText(this, tr("QInputDialog::getText()"), tr("Unesite formulu:"), QLineEdit::Normal, QDir::home().dirName(), &ok); if (ok && !tekst.isEmpty()){ qDebug() << "radi"; } std::string formula = tekst.toUtf8().constData(); formula += " ;"; std::ostringstream stream; qDebug() << QString::fromStdString(formula); YY_BUFFER_STATE buffer = yy_scan_string(formula.c_str()); if(yyparse() == 1){ qDebug() << "Pa to ti ne radi"; } if(parsed_formula->getType() == BaseFormula::T_OR){ break; } } std::ostringstream stream; parsed_formula->printFormula(stream); qreal rect_width = stream.str().length()*PARAMETER; qreal rect_height = 20; rect_x = selected->getx() - 20 - depth/2; rect_y = selected->gety() - 20 - depth/2; QVector<Formula> assumptions = selected->getAssumptions(); assumptions.push_back(parsed_formula); Node* item3 = new Node( parsed_formula, rect_width, rect_height, rect_x, rect_y, selected_list.at(0), assumptions); scene->addNode(item3); Formula op1 = ((Or*)parsed_formula.get())->getOperand1(); Formula op2 = ((Or*)parsed_formula.get())->getOperand2(); rect_x = selected->getx() + 25 + depth/2; rect_y = selected->gety() - 20 - depth/2; assumptions.push_back(op1); assumptions.push_back(op2); op1->printFormula(stream); rect_width = stream.str().length()*PARAMETER; Node* item1 = new Node( selected->getFormula(), rect_width, rect_height, rect_x, rect_y, selected_list.at(0), assumptions); scene->addNode(item1); rect_x = selected->getx() + 50 + depth/2; rect_y = selected->gety() - 20 - depth/2; op2->printFormula(stream); rect_width = stream.str().length()*PARAMETER; Node* item2 = new Node(selected->getFormula(), rect_width, rect_height, rect_x, rect_y, selected_list.at(0), assumptions); scene->addNode(item2); }
QVector<ApiTraceCall*> TraceLoader::fetchFrameContents(ApiTraceFrame *currentFrame) { Q_ASSERT(currentFrame); if (currentFrame->isLoaded()) { return currentFrame->calls(); } if (m_parser.supportsOffsets()) { unsigned frameIdx = currentFrame->number; int numOfCalls = numberOfCallsInFrame(frameIdx); if (numOfCalls) { quint64 binaryDataSize = 0; QStack<ApiTraceCall*> groups; QVector<ApiTraceCall*> topLevelItems; QVector<ApiTraceCall*> allCalls(numOfCalls); const FrameBookmark &frameBookmark = m_frameBookmarks[frameIdx]; m_parser.setBookmark(frameBookmark.start); trace::Call *call; int parsedCalls = 0; while ((call = m_parser.parse_call())) { ApiTraceCall *apiCall = apiCallFromTraceCall(call, m_helpHash, currentFrame, groups.isEmpty() ? 0 : groups.top(), this); Q_ASSERT(apiCall); Q_ASSERT(parsedCalls < allCalls.size()); allCalls[parsedCalls++] = apiCall; if (groups.count() == 0) { topLevelItems.append(apiCall); } else { groups.top()->addChild(apiCall); } if (call->flags & trace::CALL_FLAG_MARKER_PUSH) { groups.push(apiCall); } else if (call->flags & trace::CALL_FLAG_MARKER_POP) { if (groups.count()) { groups.top()->finishedAddingChildren(); groups.pop(); } } if (apiCall->hasBinaryData()) { QByteArray data = apiCall->arguments()[ apiCall->binaryDataIndex()].toByteArray(); binaryDataSize += data.size(); } delete call; if (apiCall->flags() & trace::CALL_FLAG_END_FRAME) { break; } } // There can be fewer parsed calls when call in different // threads cross the frame boundary Q_ASSERT(parsedCalls <= numOfCalls); Q_ASSERT(parsedCalls <= allCalls.size()); allCalls.resize(parsedCalls); allCalls.squeeze(); Q_ASSERT(parsedCalls <= currentFrame->numChildrenToLoad()); if (topLevelItems.count() == allCalls.count()) { emit frameContentsLoaded(currentFrame, allCalls, allCalls, binaryDataSize); } else { emit frameContentsLoaded(currentFrame, topLevelItems, allCalls, binaryDataSize); } return allCalls; } } return QVector<ApiTraceCall*>(); }
bool FilterIO::readFilter(QString path, FilterData &filter) { //Open .txt file if(!path.contains(".txt")) return false; QFile file(path); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug()<<"Error opening filter txt file for reading"; return false; } //Start reading from file QTextStream in(&file); QVector<double> coefficientsTemp; while(!in.atEnd()) { QString line = in.readLine(); QStringList fields = line.split(QRegExp("\\s+")); //Delete last element if it is a blank character if(fields.at(fields.size()-1) == "") fields.removeLast(); if(line.contains("#")) //Filter meta information commented areas in file { //Read filter sFreq if(line.contains("sFreq") && fields.size()==2) filter.m_sFreq = fields.at(1).toDouble(); //Read filter name if(line.contains("name")) { filter.m_sName.clear(); for(int i=1; i<fields.size(); i++) filter.m_sName.append(fields.at(i)); } //Read the filter order if(line.contains("order") && fields.size()==2) filter.m_iFilterOrder = fields.at(1).toInt(); //Read the filter type if(line.contains("type") && fields.size()==2) filter.m_Type = FilterData::getFilterTypeForString(fields.at(1)); //Read the filter LPFreq if(line.contains("LPFreq") && fields.size()==2) filter.m_dLowpassFreq = fields.at(1).toDouble(); //Read the filter HPFreq if(line.contains("HPFreq") && fields.size()==2) filter.m_dHighpassFreq = fields.at(1).toDouble(); //Read the filter CenterFreq if(line.contains("CenterFreq") && fields.size()==2) filter.m_dCenterFreq = fields.at(1).toDouble(); //Read the filter DesignMethod if(line.contains("DesignMethod") && fields.size()==2) filter.m_designMethod = FilterData::getDesignMethodForString(fields.at(1)); } else // Read filter coefficients coefficientsTemp.push_back(fields.join("").toDouble()); } // Check if reading was successful and correct if(filter.m_iFilterOrder != coefficientsTemp.size()) filter.m_iFilterOrder = coefficientsTemp.size(); // if(filter.m_sFreq) // if(filter.m_sName) // if(filter.m_Type) // if(filter.m_dLowpassFreq) // if(filter.m_dHighFreq) // if(filter.m_designMethod) filter.m_dCoeffA = RowVectorXd::Zero(coefficientsTemp.size()); for(int i=0; i<filter.m_dCoeffA.cols(); i++) filter.m_dCoeffA(i) = coefficientsTemp.at(i); //Compute fft of filtercoeeficients filter.fftTransformCoeffs(); file.close(); return true; }
// LATER make read and write timeout parameters bool PfParser::parse(QIODevice *source, PfOptions options) { bool lazyBinaryFragments = options.shouldLazyLoadBinaryFragments(); if (!_handler) { qWarning() << "PfParser::parse called before setting a handler"; return false; } _handler->setErrorString(tr("unknown handler error")); int line = 1, column = 0, arrayColumn = 0; quint8 c, quote = 0, escapeshift = 0; quint16 escaped = 0; qint8 digit; State state = TopLevel; // current state State quotedState = TopLevel; // saved state for quotes and comments State escapedState = TopLevel; // saved state for escapes QByteArray content, comment, surface; QVector<Node> nodes; bool firstNode = true; PfArray array; if (!source->isOpen() && !source->open(QIODevice::ReadOnly)) { _handler->setErrorString(tr("cannot open document : %1") .arg(source->errorString())); goto error; } if (!_handler->startDocument(options)) { _handler->setErrorString(tr("cannot handle start of document")); goto error; } while (source->bytesAvailable() || source->waitForReadyRead(options.readTimeout()), source->getChar((char*)&c)) { ++column; switch(state) { case TopLevel: if (c == '(') { state = Name; } else if (c == '\n') { ++line; column = 0; } else if (pfisspace(c)) { } else if (c == '#') { state = Comment; quotedState = TopLevel; } else { _handler->setErrorString(tr("unexpected character '%1' " "(in TopLevel state)") .arg(pfquotechar(c))); goto error; } break; case Name: if (pfisendofname(c) && content.isEmpty()) { _handler->setErrorString(tr("anonymous node")); goto error; } else if (c == '(') { nodes.append(QString::fromUtf8(content)); content.clear(); if (!_handler->startNode(names(nodes))) { _handler->setErrorString(tr("cannot handle start of node")); goto error; } } else if (c == ')') { nodes.append(QString::fromUtf8(content)); content.clear(); QVector<QString> names = ::names(nodes); if (!_handler->startNode(names) || !_handler->endNode(names)) { _handler->setErrorString(tr("cannot handle end of node")); goto error; } nodes.removeLast(); state = nodes.size() ? Content : TopLevel; if (nodes.isEmpty()) { switch (options.rootNodesParsingPolicy()) { case StopAfterFirstRootNode: if (firstNode) goto stop_parsing; break; case FailAtSecondRootNode: if (!firstNode) { _handler->setErrorString(tr("only one root node is allowed " "(by option)")); goto error; } break; case ParseEveryRootNode: ; } } } else if (pfisspace(c)) { if (c == '\n') { ++line; column = 0; } nodes.append(QString::fromUtf8(content)); content.clear(); if (!_handler->startNode(names(nodes))) { _handler->setErrorString(tr("cannot handle start of node")); goto error; } state = Content; } else if (c == '#') { nodes.append(QString::fromUtf8(content)); content.clear(); if (!_handler->startNode(names(nodes))) { _handler->setErrorString(tr("cannot handle start of node")); goto error; } state = Comment; quotedState = Content; } else if (c == '|') { nodes.append(QString::fromUtf8(content)); content.clear(); if (!_handler->startNode(names(nodes))) { _handler->setErrorString(tr("cannot handle start of node")); goto error; } state = BinarySurfaceOrLength; } else if (c == ';') { nodes.append(QString::fromUtf8(content)); array.clear(); content.clear(); if (!_handler->startNode(names(nodes))) { _handler->setErrorString(tr("cannot handle start of node")); goto error; } array.appendHeader("0"); arrayColumn = 1; state = ArrayHeader; } else if (pfisquote(c)) { quote = c; state = Quote; quotedState = Name; } else if (c == '\\') { state = Escape; escapedState = Name; } else if (pfisspecial(c)) { _handler->setErrorString(tr("unexpected character '%1' (in Name state)") .arg(pfquotechar(c))); goto error; } else { content.append(c); } break; case SpaceInContent: if (pfisspace(c)) { if (c == '\n') { ++line; column = 0; } else { ++column; } break; } // otherwise process as Content by falling into Content: label case Content: if (c == ';') { // LATER warn if an array node has text or binary content array.clear(); if (!content.isEmpty()) { array.appendHeader(content); content.clear(); } else array.appendHeader("0"); arrayColumn = 1; state = ArrayHeader; } else if (c == '(') { if (content.size()) { if (!_handler->text(QString::fromUtf8(content))) { _handler->setErrorString(tr("cannot handle text fragment")); goto error; } content.clear(); nodes.last()._hasContent = true; } state = Name; } else if (c == ')') { if (content.size()) { if (!_handler->text(QString::fromUtf8(content))) { _handler->setErrorString(tr("cannot handle text fragment")); goto error; } content.clear(); nodes.last()._hasContent = true; } if (!_handler->endNode(names(nodes))) { _handler->setErrorString(tr("cannot handle end of node")); goto error; } nodes.removeLast(); state = nodes.size() ? Content : TopLevel; if (nodes.isEmpty()) { switch (options.rootNodesParsingPolicy()) { case StopAfterFirstRootNode: if (firstNode) goto stop_parsing; break; case FailAtSecondRootNode: if (!firstNode) { _handler->setErrorString(tr("only one root node is allowed " "(by option)")); goto error; } break; case ParseEveryRootNode: ; } } } else if (pfisspace(c)) { if (c == '\n') { ++line; column = 0; } else { ++column; } state = SpaceInContent; } else if (c == '#') { if (content.size()) { if (!_handler->text(QString::fromUtf8(content))) { _handler->setErrorString(tr("cannot handle text fragment")); goto error; } content.clear(); nodes.last()._hasContent = true; } state = Comment; quotedState = Content; } else if (c == '|') { if (content.size()) { if (!_handler->text(QString::fromUtf8(content))) { _handler->setErrorString(tr("cannot handle text fragment")); goto error; } content.clear(); nodes.last()._hasContent = true; } state = BinarySurfaceOrLength; } else if (pfisquote(c)) { if (state == SpaceInContent) content.append(' '); quote = c; state = Quote; quotedState = Content; } else if (c == '\\') { if (state == SpaceInContent) content.append(' '); state = Escape; escapedState = Content; } else if (pfisspecial(c)) { _handler->setErrorString(tr("unexpected character '%1' " "(in Content state)") .arg(pfquotechar(c))); goto error; } else { if (state == SpaceInContent) { if (!content.isEmpty() || nodes.last()._hasContent) content.append(' '); state = Content; } content.append(c); } break; case Comment: if (c == '\n') { if (!options.shouldIgnoreComment()) { if (!_handler->comment(comment)) { _handler->setErrorString(tr("cannot handle comment")); goto error; } } comment.clear(); ++line; column = 0; state = quotedState; } else { if (!options.shouldIgnoreComment()) comment.append(c); ++column; } break; case Quote: if (c == quote) { state = quotedState; ++column; } else if (c == '\\' && quote == '"') { state = Escape; escapedState = Quote; ++column; } else { if (c == '\n') { ++line; column = 0; } else ++column; content.append(c); } break; case BinarySurfaceOrLength: if (c == '\n') { if (content.size() == 0) { _handler->setErrorString(tr("binary fragment without length")); goto error; } bool ok; qint64 l = content.toLongLong(&ok); if (!ok) { _handler->setErrorString(tr("binary fragment with incorrect length")); goto error; } if (!readAndFinishBinaryFragment(source, &lazyBinaryFragments, "", l, options)) goto error; content.clear(); nodes.last()._hasContent = true; line = 10000000; // LATER hide line numbers after first binary fragment column = 0; state = Content; } else { if (std::isspace(c)) { // ignore whitespace, incl. \r } else if (c == '|') { surface = content; content.clear(); state = BinaryLength; } else if (std::isdigit(c) || std::islower(c) || std::isupper(c) || c == ':') { content.append(c); } else { _handler->setErrorString(tr("unexpected character '%1' " "(in BinarySurfaceOrLength state)") .arg(pfquotechar(c))); goto error; } ++column; } break; case BinaryLength: if (c == '\n') { if (content.size() == 0) { _handler->setErrorString(tr("binary fragment without length")); goto error; } bool ok; qint64 l = content.toLongLong(&ok); if (!ok) { _handler->setErrorString(tr("binary fragment with incorrect length")); goto error; } if (!readAndFinishBinaryFragment(source, &lazyBinaryFragments, surface, l, options)) goto error; content.clear(); nodes.last()._hasContent = true; line = 10000000; // LATER hide line numbers after first binary fragment column = 0; state = Content; } else { if (std::isspace(c)) { // ignore whitespace, incl. \r } else if (std::isdigit(c)) { content.append(c); } else { _handler->setErrorString(tr("unexpected character '%1' " "(in BinaryLength state)") .arg(pfquotechar(c))); goto error; } ++column; } break; case ArrayHeader: if (c == '\n') { if (!content.isEmpty()) { array.appendHeader(QString::fromUtf8(content)); content.clear(); } else array.appendHeader(QString::number(arrayColumn)); ++line; column = 0; state = ArrayBody; } else { if (c == ';') { if (!content.isEmpty()) { array.appendHeader(QString::fromUtf8(content)); content.clear(); } else array.appendHeader(QString::number(arrayColumn)); ++arrayColumn; } else if (c == ')') { content.clear(); if (!finishArray(_handler, &array, &nodes)) goto error; state = nodes.size() ? Content : TopLevel; if (nodes.isEmpty()) { switch (options.rootNodesParsingPolicy()) { case StopAfterFirstRootNode: if (firstNode) goto stop_parsing; break; case FailAtSecondRootNode: if (!firstNode) { _handler->setErrorString(tr("only one root node is allowed " "(by option)")); goto error; } break; case ParseEveryRootNode: ; } } } else if (c == '#') { if (!content.isEmpty()) { array.appendHeader(QString::fromUtf8(content)); content.clear(); } else array.appendHeader(QString::number(arrayColumn)); ++column; state = Comment; quotedState = ArrayBody; } else if (pfisspace(c)) { // ignore } else if (pfisquote(c)) { quote = c; state = Quote; quotedState = ArrayHeader; } else if (c == '\\') { state = Escape; escapedState = ArrayHeader; } else if (pfisspecial(c)) { _handler->setErrorString(tr("unexpected character '%1'" " (in ArrayHeader state)") .arg(pfquotechar(c))); goto error; } else { content.append(c); } ++column; } break; case ArrayBody: if (c == '\n') { array.appendCell(QString::fromUtf8(content)); content.clear(); array.appendRow(); ++line; column = 0; } else { if (c == ';') { array.appendCell(QString::fromUtf8(content)); content.clear(); } else if (c == ')') { if (content.size()) array.appendCell((QString::fromUtf8(content))); array.removeLastRowIfEmpty(); content.clear(); if (!finishArray(_handler, &array, &nodes)) goto error; state = nodes.size() ? Content : TopLevel; if (nodes.isEmpty()) { switch (options.rootNodesParsingPolicy()) { case StopAfterFirstRootNode: if (firstNode) goto stop_parsing; break; case FailAtSecondRootNode: if (!firstNode) { _handler->setErrorString(tr("only one root node is allowed " "(by option)")); goto error; } break; case ParseEveryRootNode: ; } } } else if (c == '#') { if (content.size()) array.appendCell((QString::fromUtf8(content))); content.clear(); ++column; state = Comment; quotedState = ArrayBody; } else if (pfisspace(c)) { // ignore } else if (pfisquote(c)) { quote = c; state = Quote; quotedState = ArrayBody; } else if (c == '\\') { state = Escape; escapedState = ArrayBody; } else if (pfisspecial(c)) { _handler->setErrorString(tr("unexpected character '%1'" " (in ArrayBody state)") .arg(pfquotechar(c))); goto error; } else { content.append(c); } ++column; } break; case Escape: if (c == '\n') { column = 0; ++line; } else { if (c == 'n') c = '\n'; else if (c == 'r') c = '\r'; else if (c == 't') c = '\t'; else if (c == '0') c = 0; else if (c == 'x') { state = EscapeHex; escapeshift = 4; escaped = 0; break; } else if (c == 'u') { state = EscapeHex; escapeshift = 12; escaped = 0; break; } ++column; } content.append(c); state = escapedState; break; case EscapeHex: digit = hexdigits[c]; if (digit < 0) { _handler->setErrorString("bad hexadecimal digit in escape sequence"); goto error; } if (escapeshift) { escaped |= digit << escapeshift; escapeshift -= 4; } else { if (escaped > 0x7f) content.append(QString(QChar(escaped|digit)).toUtf8()); else content.append(QChar(escaped|digit)); state = escapedState; } ++column; break; } } stop_parsing: if (state != TopLevel) { _handler->setErrorString(tr("unexpected end of document")); goto error; } if (!_handler->endDocument()) { _handler->setErrorString(tr("cannot handle end of document")); goto error; } return true; error: _handler->error(line, column); return false; }
/*! \fn void QTextTable::insertColumns(int index, int columns) Inserts a number of \a columns before the column with the specified \a index. \sa insertRows() resize() removeRows() removeColumns() appendRows() appendColumns() */ void QTextTable::insertColumns(int pos, int num) { Q_D(QTextTable); if (num <= 0) return; if (d->dirty) d->update(); if (pos > d->nCols || pos < 0) pos = d->nCols; // qDebug() << "-------- insertCols" << pos << num; QTextDocumentPrivate *p = d->pieceTable; QTextFormatCollection *c = p->formatCollection(); p->beginEditBlock(); QList<int> extendedSpans; for (int i = 0; i < d->nRows; ++i) { int cell; if (i == d->nRows - 1 && pos == d->nCols) { cell = d->fragment_end; } else { int logicalGridIndexBeforePosition = pos > 0 ? d->findCellIndex(d->grid[i*d->nCols + pos - 1]) : -1; // Search for the logical insertion point by skipping past cells which are not the first // cell in a rowspan. This means any cell for which the logical grid index is // less than the logical cell index of the cell before the insertion. int logicalGridIndex; int gridArrayOffset = i*d->nCols + pos; do { cell = d->grid[gridArrayOffset]; logicalGridIndex = d->findCellIndex(cell); gridArrayOffset++; } while (logicalGridIndex < logicalGridIndexBeforePosition && gridArrayOffset < d->nRows*d->nCols); if (logicalGridIndex < logicalGridIndexBeforePosition && gridArrayOffset == d->nRows*d->nCols) cell = d->fragment_end; } if (pos > 0 && pos < d->nCols && cell == d->grid[i*d->nCols + pos - 1]) { // cell spans the insertion place, extend it if (!extendedSpans.contains(cell)) { QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell); QTextCharFormat fmt = c->charFormat(it->format); fmt.setTableCellColumnSpan(fmt.tableCellColumnSpan() + num); p->setCharFormat(it.position(), 1, fmt); d->dirty = true; extendedSpans << cell; } } else { /* If the next cell is spanned from the row above, we need to find the right position to insert to */ if (i > 0 && pos < d->nCols && cell == d->grid[(i-1) * d->nCols + pos]) { int gridIndex = i*d->nCols + pos; const int gridEnd = d->nRows * d->nCols - 1; while (gridIndex < gridEnd && cell == d->grid[gridIndex]) { ++gridIndex; } if (gridIndex == gridEnd) cell = d->fragment_end; else cell = d->grid[gridIndex]; } QTextDocumentPrivate::FragmentIterator it(&p->fragmentMap(), cell); QTextCharFormat fmt = c->charFormat(it->format); fmt.setTableCellRowSpan(1); fmt.setTableCellColumnSpan(1); Q_ASSERT(fmt.objectIndex() == objectIndex()); int position = it.position(); int cfmt = p->formatCollection()->indexForFormat(fmt); int bfmt = p->formatCollection()->indexForFormat(QTextBlockFormat()); for (int i = 0; i < num; ++i) p->insertBlock(QTextBeginningOfFrame, position, bfmt, cfmt, QTextUndoCommand::MoveCursor); } } QTextTableFormat tfmt = format(); tfmt.setColumns(tfmt.columns()+num); QVector<QTextLength> columnWidths = tfmt.columnWidthConstraints(); if (! columnWidths.isEmpty()) { for (int i = num; i > 0; --i) columnWidths.insert(pos, columnWidths[qMax(0, pos-1)]); } tfmt.setColumnWidthConstraints (columnWidths); QTextObject::setFormat(tfmt); // qDebug() << "-------- end insertCols" << pos << num; p->endEditBlock(); }
bool SQLiteResultPrivate::fetchNext(SqlCachedResult::ValueCache &values, int idx, bool initialFetch) { int res; int i; if (skipRow) { // already fetched Q_ASSERT(!initialFetch); skipRow = false; for(int i=0;i<firstRow.count();i++) values[i]=firstRow[i]; return skippedStatus; } skipRow = initialFetch; if(initialFetch) { firstRow.clear(); firstRow.resize(sqlite3_column_count(stmt)); } if (!stmt) { q->setLastError(QSqlError(QCoreApplication::translate("SQLiteResult", "Unable to fetch row"), QCoreApplication::translate("SQLiteResult", "No query"), QSqlError::ConnectionError)); q->setAt(QSql::AfterLastRow); return false; } res = sqlite3_step(stmt); switch(res) { case SQLITE_ROW: // check to see if should fill out columns if (rInf.isEmpty()) // must be first call. initColumns(false); if (idx < 0 && !initialFetch) return true; for (i = 0; i < rInf.count(); ++i) { switch (sqlite3_column_type(stmt, i)) { case SQLITE_BLOB: values[i + idx] = QByteArray(static_cast<const char *>( sqlite3_column_blob(stmt, i)), sqlite3_column_bytes(stmt, i)); break; case SQLITE_INTEGER: values[i + idx] = sqlite3_column_int64(stmt, i); break; case SQLITE_FLOAT: switch(q->numericalPrecisionPolicy()) { case QSql::LowPrecisionInt32: values[i + idx] = sqlite3_column_int(stmt, i); break; case QSql::LowPrecisionInt64: values[i + idx] = sqlite3_column_int64(stmt, i); break; case QSql::LowPrecisionDouble: case QSql::HighPrecision: default: values[i + idx] = sqlite3_column_double(stmt, i); break; }; break; case SQLITE_NULL: values[i + idx] = QVariant(QVariant::String); break; default: values[i + idx] = QString(reinterpret_cast<const QChar *>( sqlite3_column_text16(stmt, i)), sqlite3_column_bytes16(stmt, i) / sizeof(QChar)); break; } } return true; case SQLITE_DONE: if (rInf.isEmpty()) // must be first call. initColumns(true); q->setAt(QSql::AfterLastRow); sqlite3_reset(stmt); return false; case SQLITE_CONSTRAINT: case SQLITE_ERROR: // SQLITE_ERROR is a generic error code and we must call sqlite3_reset() // to get the specific error message. res = sqlite3_reset(stmt); q->setLastError(qMakeError(access, QCoreApplication::translate("SQLiteResult", "Unable to fetch row"), QSqlError::ConnectionError, res)); q->setAt(QSql::AfterLastRow); return false; case SQLITE_MISUSE: case SQLITE_BUSY: default: // something wrong, don't get col info, but still return false q->setLastError(qMakeError(access, QCoreApplication::translate("SQLiteResult", "Unable to fetch row"), QSqlError::ConnectionError, res)); sqlite3_reset(stmt); q->setAt(QSql::AfterLastRow); return false; } return false; }
void Plotter::drawCurves(QPainter *painter) { //~~~~~~~~Adjust X-y Axis ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ QStringList stringList; bool ok=true; QFile textFile("AdjustXYaxisVI.txt"); if (textFile.open(QIODevice::ReadOnly)) { QTextStream textStream(&textFile); while (!textStream.atEnd()) { stringList.append(textStream.readLine()); } adjustXaxis=stringList.value(0).toDouble(&ok); adjustYaxis=stringList.value(1).toDouble(&ok); }else{ adjustXaxis=5.5; adjustYaxis=0; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ static const QColor colorForIds[8] = {Qt::red,Qt::green,Qt::cyan,Qt::magenta,Qt::yellow,Qt::white,Qt::gray,Qt::black}; PlotSettings settings = zoomStack[curZoom]; if( m_moveFlag == true) { settings.maxX = m_ZoomSettings->maxX; settings.maxY = m_ZoomSettings->maxY; settings.minX = m_ZoomSettings->minX; settings.minY = m_ZoomSettings->minY; settings.m_nOffset = m_ZoomSettings->m_nOffset; settings.numXTicks = m_ZoomSettings->numXTicks; settings.numYTicks = m_ZoomSettings->numYTicks; } QRect rect(Margin,Margin,width()-(2*Margin),height()-(2*Margin)); if(m_bshowZoomRect == true) { painter->setPen(colorForIds[6]); painter->drawRect(rubberBandRect); } if(!rect.isValid()) return; painter->setClipRect(rect.adjusted(+1,+1,-1,-1)); QMapIterator<int, QVector<QPointF> > i(curveMap); // printf("Rect Left: %d\n",rect.left()); // printf("Rect Height: %d\n",rect.height()); // printf("Rect width: %d\n",rect.width()); // printf("Rect Bottom: %d\n",rect.bottomLeft().y()); // printf("Rect Top: %d\n",rect.top()); double dx,dy; while(i.hasNext()){ i.next(); int id = i.key(); // qDebug() << "Curve ID" << id; QVector<QPointF> data = i.value(); QPolygonF polyline(data.count()); double y =0.0,x=0.0; int l_nCounter =0; //printf("MinY:%f\n",settings.minY); //printf("Offset:%f\n",m_nOffset); m_nOffset =0.0; for(int j=0; j< data.count();++j) { dx = data[j].x(); dy = data[j].y(); if(m_bUniPolar == true) { float l_nDiv = (dy/2.0); // printf("UniPolar %f->%f\n",l_nDiv,dy - l_nDiv); } if(( data[j].x()>=settings.minX && data[j].x()<=settings.maxX)) { //printf("X:%f Y:%f\n",dx,dy); } y =0.0,x=0.0; if(m_ZoomFlag == false) { if(m_bVIMode == true) x = ((rect.width()/2)+adjustXaxis + ((dx)*(((rect.width()-1)))/(settings.spanX()))); else x = (rect.left()+ ((dx)*(((rect.width()-1)))/(settings.spanX()))); if( m_bUniPolar == true){ y = ((Margin+rect.bottom()) - (((dy/2.0)+settings.m_nOffset)*((rect.height()-1))/(settings.spanY()))); //y+=10; // printf(" Coord-Y %f\n",dy/2.0); } else y = (((Margin+rect.height()/2)+adjustYaxis) - ((dy+m_nOffset)*((rect.height()-1))/(settings.spanY())));//TO CHANGE THE Y AXIS IN THE GRAPH // printf(" Coord- X & Y %f %f\n",x,y); } else if(m_ZoomFlag == true) { x = (rect.left() + ((dx-settings.minX)*(((rect.width()-1)))/(settings.spanX()))); y = ((Margin+rect.height()) - (((dy-settings.minY)+settings.m_nOffset)*((rect.height()-1))/(settings.spanY()))); } if(( data[j].x()>=settings.minX && data[j].x()<=settings.maxX)&&(( data[j].y()>=settings.minY && data[j].y()<=settings.maxY))) { polyline[j] = QPointF(x,y); l_nCounter++; } } QPolygonF zoomPolyline(l_nCounter); y =0.0,x=0.0; int l_nIndex1 =0; for(int l_nIndex=0;l_nIndex< data.count();l_nIndex++) { QPointF(x,y); x = polyline.at(l_nIndex).x(); y = polyline.at(l_nIndex).y(); //qDebug()<<x<<y; if(x!=0.0 || y!=0.0 ) { zoomPolyline[l_nIndex1] = QPointF(x,y); l_nIndex1++; } } // if( m_nClearID == id) // painter->setPen(Qt::black); //else QPen pen; painter->setPen(colorForIds[uint(id) %6]); // pen.setColor(colorForIds[uint(id) %6]); // pen.setWidth(20); // painter->setPen(pen); if(m_ZoomFlag == false) { painter->setPen(colorForIds[uint(id) %6]); painter->drawPolyline(polyline); // qDebug()<<"Band:"<<m_objPlotData->m_nEnvelopBand; //compareCurvePoints(polyline1); } else painter->drawPolyline(zoomPolyline); } // qDebug() << "Exit Draw Cruves."; }