void rsmFilter(QDjangoQuerySet<T1> &qs, const QXmppResultSetQuery &rsmQuery, QList<T2> &results, QXmppResultSetReply &rsmReply) { // if count was requested, stop here if (rsmQuery.max() == 0) { rsmReply.setCount(qs.count()); return; } rsmReply.setCount(qs.size()); T1 result; if (rsmQuery.before().isNull()) { // page forwards bool rsmAfterReached = rsmQuery.after().isEmpty(); for (int i = 0; i < qs.size(); ++i) { if (rsmQuery.max() >= 0 && results.size() >= rsmQuery.max()) break; // fetch from database if (!qs.at(i, &result)) break; const QString uid = result.pk().toString(); // if an "after" was specified, check it was reached if (!rsmAfterReached) { if (uid == rsmQuery.after()) rsmAfterReached = true; continue; } if (results.isEmpty()) { rsmReply.setFirst(uid); rsmReply.setIndex(i); } rsmReply.setLast(uid); results << result; } } else { // page backwards bool rsmBeforeReached = rsmQuery.before().isEmpty(); for (int i = qs.size() - 1; i >= 0; --i) { if (rsmQuery.max() >= 0 && results.size() >= rsmQuery.max()) break; // fetch from database if (!qs.at(i, &result)) break; const QString uid = result.pk().toString(); // if a "before" was specified, check it was reached if (!rsmBeforeReached) { if (uid == rsmQuery.before()) rsmBeforeReached = true; continue; } if (results.isEmpty()) rsmReply.setLast(uid); rsmReply.setFirst(uid); rsmReply.setIndex(i); results.prepend(result); } } }
void HistoryManager::load() { loadSettings(); QFile historyFile(QDesktopServices::storageLocation(QDesktopServices::DataLocation) + QLatin1String("/history")); if (!historyFile.exists()) return; if (!historyFile.open(QFile::ReadOnly)) { qWarning() << "Unable to open history file" << historyFile.fileName(); return; } QList<HistoryEntry> list; QDataStream in(&historyFile); // Double check that the history file is sorted as it is read in bool needToSort = false; HistoryEntry lastInsertedItem; QByteArray data; QDataStream stream; QBuffer buffer; QString string; stream.setDevice(&buffer); while (!historyFile.atEnd()) { in >> data; buffer.close(); buffer.setBuffer(&data); buffer.open(QIODevice::ReadOnly); quint32 ver; stream >> ver; if (ver != HISTORY_VERSION) continue; HistoryEntry item; stream >> string; item.url = atomicString(string); stream >> item.dateTime; stream >> string; item.title = atomicString(string); if (!item.dateTime.isValid()) continue; if (item == lastInsertedItem) { if (lastInsertedItem.title.isEmpty() && !list.isEmpty()) list[0].title = item.title; continue; } if (!needToSort && !list.isEmpty() && lastInsertedItem < item) needToSort = true; list.prepend(item); lastInsertedItem = item; } if (needToSort) qSort(list.begin(), list.end()); setHistory(list, true); // If we had to sort re-write the whole history sorted if (needToSort) { m_lastSavedUrl.clear(); m_saveTimer->changeOccurred(); } }
QHostInfo QHostInfoAgent::fromName(const QString &hostName) { QHostInfo results; #if defined(QHOSTINFO_DEBUG) qDebug("QHostInfoAgent::fromName(%s) looking up...", hostName.toLatin1().constData()); #endif // Load res_init on demand. static QBasicAtomicInt triedResolve = Q_BASIC_ATOMIC_INITIALIZER(false); if (!triedResolve.loadAcquire()) { QMutexLocker locker(QMutexPool::globalInstanceGet(&local_res_init)); if (!triedResolve.load()) { resolveLibrary(); triedResolve.storeRelease(true); } } // If res_init is available, poll it. if (local_res_init) local_res_init(); QHostAddress address; if (address.setAddress(hostName)) { // Reverse lookup // Reverse lookups using getnameinfo are broken on darwin, use gethostbyaddr instead. #if !defined (QT_NO_GETADDRINFO) && !defined (Q_OS_DARWIN) sockaddr_in sa4; sockaddr_in6 sa6; sockaddr *sa = 0; QT_SOCKLEN_T saSize = 0; if (address.protocol() == QAbstractSocket::IPv4Protocol) { sa = (sockaddr *)&sa4; saSize = sizeof(sa4); memset(&sa4, 0, sizeof(sa4)); sa4.sin_family = AF_INET; sa4.sin_addr.s_addr = htonl(address.toIPv4Address()); } else { sa = (sockaddr *)&sa6; saSize = sizeof(sa6); memset(&sa6, 0, sizeof(sa6)); sa6.sin6_family = AF_INET6; memcpy(sa6.sin6_addr.s6_addr, address.toIPv6Address().c, sizeof(sa6.sin6_addr.s6_addr)); } char hbuf[NI_MAXHOST]; if (sa && getnameinfo(sa, saSize, hbuf, sizeof(hbuf), 0, 0, 0) == 0) results.setHostName(QString::fromLatin1(hbuf)); #else in_addr_t inetaddr = qt_safe_inet_addr(hostName.toLatin1().constData()); struct hostent *ent = gethostbyaddr((const char *)&inetaddr, sizeof(inetaddr), AF_INET); if (ent) results.setHostName(QString::fromLatin1(ent->h_name)); #endif if (results.hostName().isEmpty()) results.setHostName(address.toString()); results.setAddresses(QList<QHostAddress>() << address); return results; } // IDN support QByteArray aceHostname = QUrl::toAce(hostName); results.setHostName(hostName); if (aceHostname.isEmpty()) { results.setError(QHostInfo::HostNotFound); results.setErrorString(hostName.isEmpty() ? QCoreApplication::translate("QHostInfoAgent", "No host name given") : QCoreApplication::translate("QHostInfoAgent", "Invalid hostname")); return results; } #if !defined (QT_NO_GETADDRINFO) // Call getaddrinfo, and place all IPv4 addresses at the start and // the IPv6 addresses at the end of the address list in results. addrinfo *res = 0; struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; #ifdef Q_ADDRCONFIG hints.ai_flags = Q_ADDRCONFIG; #endif int result = getaddrinfo(aceHostname.constData(), 0, &hints, &res); # ifdef Q_ADDRCONFIG if (result == EAI_BADFLAGS) { // if the lookup failed with AI_ADDRCONFIG set, try again without it hints.ai_flags = 0; result = getaddrinfo(aceHostname.constData(), 0, &hints, &res); } # endif if (result == 0) { addrinfo *node = res; QList<QHostAddress> addresses; while (node) { #ifdef QHOSTINFO_DEBUG qDebug() << "getaddrinfo node: flags:" << node->ai_flags << "family:" << node->ai_family << "ai_socktype:" << node->ai_socktype << "ai_protocol:" << node->ai_protocol << "ai_addrlen:" << node->ai_addrlen; #endif if (node->ai_family == AF_INET) { QHostAddress addr; addr.setAddress(ntohl(((sockaddr_in *) node->ai_addr)->sin_addr.s_addr)); if (!addresses.contains(addr)) addresses.append(addr); } else if (node->ai_family == AF_INET6) { QHostAddress addr; sockaddr_in6 *sa6 = (sockaddr_in6 *) node->ai_addr; addr.setAddress(sa6->sin6_addr.s6_addr); if (sa6->sin6_scope_id) addr.setScopeId(QString::number(sa6->sin6_scope_id)); if (!addresses.contains(addr)) addresses.append(addr); } node = node->ai_next; } if (addresses.isEmpty() && node == 0) { // Reached the end of the list, but no addresses were found; this // means the list contains one or more unknown address types. results.setError(QHostInfo::UnknownError); results.setErrorString(tr("Unknown address type")); } results.setAddresses(addresses); freeaddrinfo(res); } else if (result == EAI_NONAME || result == EAI_FAIL #ifdef EAI_NODATA // EAI_NODATA is deprecated in RFC 3493 || result == EAI_NODATA #endif ) { results.setError(QHostInfo::HostNotFound); results.setErrorString(tr("Host not found")); } else { results.setError(QHostInfo::UnknownError); results.setErrorString(QString::fromLocal8Bit(gai_strerror(result))); } #else // Fall back to gethostbyname for platforms that don't define // getaddrinfo. gethostbyname does not support IPv6, and it's not // reentrant on all platforms. For now this is okay since we only // use one QHostInfoAgent, but if more agents are introduced, locking // must be provided. QMutexLocker locker(&getHostByNameMutex); hostent *result = gethostbyname(aceHostname.constData()); if (result) { if (result->h_addrtype == AF_INET) { QList<QHostAddress> addresses; for (char **p = result->h_addr_list; *p != 0; p++) { QHostAddress addr; addr.setAddress(ntohl(*((quint32 *)*p))); if (!addresses.contains(addr)) addresses.prepend(addr); } results.setAddresses(addresses); } else { results.setError(QHostInfo::UnknownError); results.setErrorString(tr("Unknown address type")); } #if !defined(Q_OS_VXWORKS) } else if (h_errno == HOST_NOT_FOUND || h_errno == NO_DATA || h_errno == NO_ADDRESS) { results.setError(QHostInfo::HostNotFound); results.setErrorString(tr("Host not found")); #endif } else { results.setError(QHostInfo::UnknownError); results.setErrorString(tr("Unknown error")); } #endif // !defined (QT_NO_GETADDRINFO) #if defined(QHOSTINFO_DEBUG) if (results.error() != QHostInfo::NoError) { qDebug("QHostInfoAgent::fromName(): error #%d %s", h_errno, results.errorString().toLatin1().constData()); } else { QString tmp; QList<QHostAddress> addresses = results.addresses(); for (int i = 0; i < addresses.count(); ++i) { if (i != 0) tmp += ", "; tmp += addresses.at(i).toString(); } qDebug("QHostInfoAgent::fromName(): found %i entries for \"%s\": {%s}", addresses.count(), hostName.toLatin1().constData(), tmp.toLatin1().constData()); } #endif return results; }
QList<QByteArray> QAudioDeviceInfoInternal::availableDevices(QAudio::Mode mode) { QList<QByteArray> devices; QByteArray filter; #if(SND_LIB_MAJOR == 1 && SND_LIB_MINOR == 0 && SND_LIB_SUBMINOR >= 14) // Create a list of all current audio devices that support mode void **hints, **n; char *name, *descr, *io; if(snd_device_name_hint(-1, "pcm", &hints) < 0) { qWarning() << "no alsa devices available"; return devices; } n = hints; if(mode == QAudio::AudioInput) { filter = "Input"; } else { filter = "Output"; } while (*n != NULL) { name = snd_device_name_get_hint(*n, "NAME"); if (name != 0 && qstrcmp(name, "null") != 0) { descr = snd_device_name_get_hint(*n, "DESC"); io = snd_device_name_get_hint(*n, "IOID"); if ((descr != NULL) && ((io == NULL) || (io == filter))) { QString deviceName = QLatin1String(name); QString deviceDescription = QLatin1String(descr); if (deviceDescription.contains(QLatin1String("Default Audio Device"))) devices.prepend(deviceName.toLocal8Bit().constData()); else devices.append(deviceName.toLocal8Bit().constData()); } free(name); if (descr != NULL) free(descr); if (io != NULL) free(io); } ++n; } snd_device_name_free_hint(hints); #else int idx = 0; char* name; while(snd_card_get_name(idx,&name) == 0) { devices.append(name); idx++; } #endif if (devices.size() > 0) devices.append("default"); return devices; }
QList<HtmlExporter::tag> HtmlExporter::emitCharFormatStyle( const QTextCharFormat &charFormat, const QTextBlockFormat &blockFormat ) { // kDebug() << "html" << html; QList<HtmlExporter::tag> tags; bool attributesEmitted = false; QLatin1String styleTag( "<span style=\"" ); const QString family = charFormat.fontFamily(); //if (!family.isEmpty() && family != defaultCharFormat.fontFamily()) { // NOTE the above line replaced with the bottom line to use default charFormat, which can be set from outside. if ( charFormat.hasProperty( BilboTextFormat::HasCodeStyle ) && charFormat.boolProperty( BilboTextFormat::HasCodeStyle ) ) { tags << code; } else if ( !family.isEmpty() && family != mDefaultCharFormat.fontFamily() ) { // if ( family.right( 7 ) == "courier" ) { // tags << code; // } else { if ( ! attributesEmitted ) { html += styleTag; } html += QLatin1String( " font-family:'" ); html += family; html += QLatin1String( "';" ); attributesEmitted = true; // } } // if (format.hasProperty(QTextFormat::FontPointSize) // && format.fontPointSize() != defaultCharFormat.fontPointSize()) { // NOTE the above line replaced with the bottom line to use default charFormat, which can be set from outside. if ( charFormat.hasProperty( QTextFormat::FontPointSize ) && charFormat.fontPointSize() != mDefaultCharFormat.fontPointSize() ) { if ( ! attributesEmitted ) { html += styleTag; } html += QLatin1String( " font-size:" ); html += QString::number( charFormat.fontPointSize() ); html += QLatin1String( "pt;" ); attributesEmitted = true; } else if ( charFormat.hasProperty( QTextFormat::FontSizeAdjustment ) && !( blockFormat.hasProperty( BilboTextFormat::HtmlHeading ) && blockFormat.intProperty( BilboTextFormat::HtmlHeading ) ) ) { ///To use <h1-5> tags for font size // const int idx = format.intProperty(QTextFormat::FontSizeAdjustment) + 1; // // switch (idx) { // case 0: tags << h5; break; // //case 1: tags << h4; break; //NOTE h4 will be the normal text! // case 2: tags << h3; break; // case 3: tags << h2; break; // case 4: tags << h1; break; // } ///To use <span> tags for font size static const char * const sizeNames[] = { "small", "medium", "large", "x-large", "xx-large" }; const char *name = 0; const int idx = charFormat.intProperty( QTextFormat::FontSizeAdjustment ) + 1; if ( idx == 1 ) { // assume default to not bloat the html too much } else if ( idx >= 0 && idx <= 4 ) { name = sizeNames[idx]; } if ( name ) { if ( ! attributesEmitted ) { html += styleTag; } html += QLatin1String( " font-size:" ); html += QLatin1String( name ); html += QLatin1Char( ';' ); attributesEmitted = true; } } // if (format.fontWeight() > defaultCharFormat.fontWeight()) { // NOTE the above line replaced with the bottom line to use default charFormat, which can be set from outside. if ( charFormat.fontWeight() > mDefaultCharFormat.fontWeight() && !( blockFormat.hasProperty( BilboTextFormat::HtmlHeading ) && blockFormat.intProperty( BilboTextFormat::HtmlHeading ) ) ) { tags << strong; /*if (! attributesEmitted ) html += styleTag; html += QLatin1String(" font-weight:"); html += QString::number(format.fontWeight() * 8); html += QLatin1Char(';'); attributesEmitted = true;*/ } // if (format.fontItalic() != defaultCharFormat.fontItalic()) { // NOTE the above line replaced with the bottom line to use default charFormat, which can be set from outside. if ( charFormat.fontItalic() != mDefaultCharFormat.fontItalic() ) { tags << em; /* if (! attributesEmitted ) html += styleTag; html += QLatin1String(" font-style:"); html += (format.fontItalic() ? QLatin1String("italic") : QLatin1String("normal")); html += QLatin1Char(';'); attributesEmitted = true;*/ } // if (format.fontUnderline() != defaultCharFormat.fontUnderline()) { // NOTE the above line replaced with the bottom line to use default charFormat, which can be set from outside. if ( charFormat.fontUnderline() != mDefaultCharFormat.fontUnderline() ) { tags << u; } // if (format.fontStrikeOut() != defaultCharFormat.fontStrikeOut()) { // NOTE the above line replaced with the bottom line to use default charFormat, which can be set from outside. if ( charFormat.fontStrikeOut() != mDefaultCharFormat.fontStrikeOut() ) { tags << s; } // if (format.fontOverline() != defaultCharFormat.fontOverline()) { // NOTE the above line replaced with the bottom line to use default charFormat, which can be set from outside. if ( charFormat.fontOverline() != mDefaultCharFormat.fontOverline() ) { if ( charFormat.fontOverline() ) { if ( ! attributesEmitted ) { html += styleTag; } html += QLatin1String( " text-decoration: overline;" ); attributesEmitted = true; } } /* bool hasDecoration = false; bool atLeastOneDecorationSet = false; QLatin1String decorationTag(" text-decoration:"); if (format.fontUnderline() != defaultCharFormat.fontUnderline() || format.fontOverline() != defaultCharFormat.fontOverline() || format.fontStrikeOut() != defaultCharFormat.fontStrikeOut() ) { if (! attributesEmitted ) html += styleTag; html += decorationTag; } if (format.fontUnderline() != defaultCharFormat.fontUnderline()) { hasDecoration = true; if (format.fontUnderline()) { html += QLatin1String(" underline"); atLeastOneDecorationSet = true; } } if (format.fontOverline() != defaultCharFormat.fontOverline()) { hasDecoration = true; if (format.fontOverline()) { html += QLatin1String(" overline"); atLeastOneDecorationSet = true; } } if (format.fontStrikeOut() != defaultCharFormat.fontStrikeOut()) { hasDecoration = true; if (format.fontStrikeOut()) { html += QLatin1String(" line-through"); atLeastOneDecorationSet = true; } } if (hasDecoration) { if (!atLeastOneDecorationSet) html += QLatin1String("none"); html += QLatin1Char(';'); attributesEmitted = true; }*/ /* else { html.chop(qstrlen(decorationTag.latin1())); }*/ // QBrush linkColor = KColorScheme(QPalette::Active, KColorScheme::Window).foreground(KColorScheme::LinkText); // if ( format.foreground() != defaultCharFormat.foreground() && // format.foreground().style() != Qt::NoBrush) { // NOTE the above line replaced with the bottom line to use default charFormat, which can be set from outside. if ( charFormat.foreground() != mDefaultCharFormat.foreground() && charFormat.foreground().style() != Qt::NoBrush && !charFormat.isAnchor() ) { // if ( format.foreground() != linkColor ) { // if ( format.anchorHref().isNull() ) { if ( ! attributesEmitted ) { html += styleTag; attributesEmitted = true; } // } else { // html += QLatin1String(" style=\""); // } html += QLatin1String( " color:" ); html += charFormat.foreground().color().name(); html += QLatin1Char( ';' ); // if ( !format.anchorHref().isNull() ) { // html += QLatin1String("\""); // } // attributesEmitted = true; // } } // if (format.background() != defaultCharFormat.background() // && format.background().style() != Qt::NoBrush) { // NOTE the above line replaced with the bottom line to use default charFormat, which can be set from outside. if ( !( charFormat.hasProperty( BilboTextFormat::HasCodeStyle ) && charFormat.boolProperty( BilboTextFormat::HasCodeStyle ) ) ) { if ( charFormat.background() != mDefaultCharFormat.background() && charFormat.background().style() != Qt::NoBrush ) { if ( ! attributesEmitted ) { html += styleTag; } html += QLatin1String( " background-color:" ); html += charFormat.background().color().name(); html += QLatin1Char( ';' ); attributesEmitted = true; } } // if (format.verticalAlignment() != defaultCharFormat.verticalAlignment()) { //TODO // NOTE the above line replaced with the bottom line to use default charFormat, which can be set from outside. if ( charFormat.verticalAlignment() != mDefaultCharFormat.verticalAlignment() ) { //TODO if ( ! attributesEmitted ) { html += styleTag; } html += QLatin1String( " vertical-align:" ); QTextCharFormat::VerticalAlignment valign = charFormat.verticalAlignment(); if ( valign == QTextCharFormat::AlignSubScript ) { html += QLatin1String( "sub" ); } else if ( valign == QTextCharFormat::AlignSuperScript ) { html += QLatin1String( "super" ); } html += QLatin1Char( ';' ); attributesEmitted = true; } //Append close span Tag if ( attributesEmitted ) { html += QLatin1String( "\">" ); tags.prepend( span ); } // kDebug() << "html=>" << html << tags; return tags; }
QItemSelection FlatProxyModel::mapSelectionFromSource(const QItemSelection& sourceSelection) const { QList<_RangeRect> newRanges; QHash<QModelIndex, SourceItem*> itemLookup; // basics steps of the loop: // 1. convert each source ItemSelectionRange to a mapped Range (internal one for easier post processing) // 2. insert it into the list of previously mapped Ranges sorted by top location for (int i = 0; i < sourceSelection.count(); i++) { const QItemSelectionRange& currentRange = sourceSelection[i]; QModelIndex currentParent = currentRange.topLeft().parent(); Q_ASSERT(currentParent == currentRange.bottomRight().parent()); SourceItem* parentItem = nullptr; if (!itemLookup.contains(currentParent)) { parentItem = sourceToInternal(currentParent); itemLookup[currentParent] = parentItem; } else { parentItem = itemLookup[currentParent]; } _RangeRect newRange = {currentRange.topLeft().column(), currentRange.bottomRight().column(), currentRange.topLeft().row(), currentRange.bottomRight().row(), parentItem->child(currentRange.topLeft().row()), parentItem->child(currentRange.bottomRight().row())}; if (newRanges.isEmpty()) { newRanges << newRange; continue; } _RangeRect& first = newRanges[0]; if (newRange < first) { newRanges.prepend(newRange); continue; } bool inserted = false; for (int j = 0; j < newRanges.count() - 1; j++) { _RangeRect& a = newRanges[j]; _RangeRect& b = newRanges[j + 1]; if (a < newRange && newRange < b) { newRanges[j + 1] = newRange; inserted = true; break; } } if (inserted) continue; _RangeRect& last = newRanges[newRanges.count() - 1]; if (last < newRange) { newRanges.append(newRange); continue; } Q_ASSERT(false); } // we've got a sorted list of ranges now. so we can easily check if there is a possibility to merge for (int i = newRanges.count() - 1; i > 0; i--) { _RangeRect& a = newRanges[i - 1]; _RangeRect& b = newRanges[i]; if (a.left != b.left || a.right != b.right) continue; if (a.bottom < b.top - 1) { continue; } // all merge checks passed! if (b.bottom > a.bottom) { a.bottom = b.bottom; a.bottomItem = b.bottomItem; } // otherwise b is totally enclosed in a -> nothing to do but drop b. newRanges.removeAt(i); } QItemSelection proxySelection; for (int i = 0; i < newRanges.count(); i++) { _RangeRect& r = newRanges[i]; proxySelection << QItemSelectionRange(createIndex(r.top, r.left, r.topItem), createIndex(r.bottom, r.right, r.bottomItem)); } return proxySelection; }
QQmlInfo::~QQmlInfo() { if (0 == --d->ref) { QList<QQmlError> errors = d->errors; QQmlEngine *engine = 0; if (!d->buffer.isEmpty()) { QQmlError error; QObject *object = const_cast<QObject *>(d->object); if (object) { engine = qmlEngine(d->object); QString typeName; QQmlType *type = QQmlMetaType::qmlType(object->metaObject()); if (type) { typeName = type->qmlTypeName(); int lastSlash = typeName.lastIndexOf(QLatin1Char('/')); if (lastSlash != -1) typeName = typeName.mid(lastSlash+1); } else { typeName = QString::fromUtf8(object->metaObject()->className()); int marker = typeName.indexOf(QLatin1String("_QMLTYPE_")); if (marker != -1) typeName = typeName.left(marker); marker = typeName.indexOf(QLatin1String("_QML_")); if (marker != -1) { typeName = typeName.left(marker); typeName += QLatin1Char('*'); type = QQmlMetaType::qmlType(QMetaType::type(typeName.toLatin1())); if (type) { typeName = type->qmlTypeName(); int lastSlash = typeName.lastIndexOf(QLatin1Char('/')); if (lastSlash != -1) typeName = typeName.mid(lastSlash+1); } } } d->buffer.prepend(QLatin1String("QML ") + typeName + QLatin1String(": ")); QQmlData *ddata = QQmlData::get(object, false); if (ddata && ddata->outerContext && !ddata->outerContext->url.isEmpty()) { error.setUrl(ddata->outerContext->url); error.setLine(ddata->lineNumber); error.setColumn(ddata->columnNumber); } } error.setDescription(d->buffer); errors.prepend(error); } QQmlEnginePrivate::warning(engine, errors); delete d; } }
void PlSqlParser::correctError(int *token, ParsingTableRow *row, ParsingTableAction **actionOnCurrentToken) { //qDebug("--------started error recovery--------------"); bool reservedWord = parsingTable->isReservedWord(scanner->getTokenLexeme()); if(*token!=PLS_SEMI){ *actionOnCurrentToken=row->actions->value(PLS_NOT_SEMI, 0); if(!reservedWord){ replaceKeywordWithIdentifier(*token, row, actionOnCurrentToken); } } if(*actionOnCurrentToken == 0 && !this->strict){ //try to recognize major constructs //read input until we encounter one of (first of) PLS_SEMI, END opt_identifier PLS_SEMI //while reading add all read tokens to token stack QList<TokenInfo*> reduceTokens; bool hasNonUsedReduceTokens = false; do{ if(!reservedWord || countOnLastPosition>maxStayCountOnSamePosition){ reduceTokens.prepend(createTokenInfo(*token)); hasNonUsedReduceTokens = true; } if(*token == PLS_SEMI || reservedWord){ int reducedConstruct = 0; QList<int> expectedTerminals = getExpectedTokens(row).first; //bool waitingForSemicolon = (expectedTerminals.size()==1 && expectedTerminals[0]==PLS_SEMI); bool waitingForSemicolon = expectedTerminals.contains(PLS_SEMI); if(reservedWord && countOnLastPosition<=maxStayCountOnSamePosition && !waitingForSemicolon){ //if current token is reserved word, try to reduce expression first int constuctsToCheck[] = {R_EXPRESSION, R_DECLARATION, R_STATEMENT}; reducedConstruct = reduceMajorConstruct(reduceTokens, constuctsToCheck, 3); }else{ //on semicolon try to reduce declaration or statement int constuctsToCheck[] = {R_DECLARATION, R_STATEMENT}; reducedConstruct = reduceMajorConstruct(reduceTokens, constuctsToCheck, 2); } if(reducedConstruct){ //read next token for parser to operate if(!reservedWord || countOnLastPosition>maxStayCountOnSamePosition){ *token = scanner->getNextToken(); if(*token == PLS_SEMI){ correctError(token, row, actionOnCurrentToken); } } ParsingTableRow *newRow=parsingTable->rows.at(stack.top()); //reduceMajorConstruct pushed new gotoState into stack *actionOnCurrentToken=(*newRow->actions).value(*token, 0); replaceKeywordWithIdentifier(*token, newRow, actionOnCurrentToken); }else{ qDeleteAll(reduceTokens); } hasNonUsedReduceTokens = false; break; } *token = scanner->getNextToken(); reservedWord = parsingTable->isReservedWord(scanner->getTokenLexeme()); }while(*token != PLS_E_O_F); if(hasNonUsedReduceTokens){ qDeleteAll(reduceTokens); } } if(scanner->getTokenStartPos() == lastErrorPosition){ ++countOnLastPosition; }else if(countOnLastPosition > 0){ countOnLastPosition = 0; } lastErrorPosition = scanner->getTokenStartPos(); //qDebug("--------completed error recovery--------------"); }
void MainWindow::change_graph(int i) { QDate simera; simera=QDate::currentDate(); QList <int> minut; QList <QString> label; QSqlQuery query(db1); switch(i) { case 0: { int dayno=simera.dayOfWeek(); for (int i=0;i<dayno;++i) { query.exec("select dayname(start_time),sum(TIMESTAMPDIFF(MINUTE,t.start_time,t.end_time)) from tasks t where date(start_time)='"+simera.addDays(-i).toString("yy/M/d")+"' group by dayname(start_time)"); if(query.next()) { minut.prepend(query.value(1).toInt()); label.prepend(query.value(0).toString()); } } //if(query.size()>=0) //{ //WeekGraph *drb=new WeekGraph(this); drb->set_list(minut,label); //drb->setFixedWidth(611); // drb->setFixedHeight(181); drb->repaint(); //} break; } case 1: { QVariant month,year; for (int i=1;i<=simera.month();++i) { month=i; year=simera.year(); query.exec("select monthname(start_time),sum(TIMESTAMPDIFF(MINUTE,t.start_time,t.end_time)) from tasks t where month(start_time)="+month.toString()+" and year(start_time)="+year.toString()+" group by monthname(start_time)"); if(query.next()) { minut.append(query.value(1).toInt()); label.append(query.value(0).toString()); } } if(query.size()>0) { drb->set_list(minut,label); drb->repaint(); } break; } case 2: { query.exec("select max(year(start_time))-2 from tasks"); query.next(); QVariant min_year=query.value(0); query.exec("select max(year(start_time)) from tasks"); query.next(); QVariant max_year=query.value(0); QVariant month,year; for (int i=min_year.toInt();i<=max_year.toInt();++i) { year=i; for (int j=1;j<=12;++j) { month=j; query.exec("select concat_ws('/',month(start_time),substr(year(start_time) from 3)),sum(TIMESTAMPDIFF(MINUTE,t.start_time,t.end_time)) from tasks t where month(start_time)="+month.toString()+" and year(start_time)="+year.toString()+" group by concat_ws('/',month(start_time),substr(year(start_time) from 3))"); if (query.next()) { minut.append(query.value(1).toInt()); label.append(query.value(0).toString()); } } drb->set_list(minut,label); drb->repaint(); } } } }
bool BiDirScheduler::schedule(ProcessModel &pm, Resources &rc, Schedule &schedule) { Debugger::info << "Building schedule using simple bidirectional approach." << ENDL; /** Algorithm: * * Lv - set of head scheduled operations; * Lr - set of tail scheduled operations; * Av - set of additionally head-schedulable operations; * Ar - set of additianally tail-schedulable operations; * * 1. Lv = Lr = 0; * Av = first available operations of the graph; * Ar = first available operations in the reverse graph. * * 2. While Av + Ar != 0 * * 2.a) select operation from Av according to some priority rule; * 2.b) schedule the selected operation as soon as possible; * 2.c) include the operation into Lv and exclude it from Av * 2.d) select next available operation(s) which are not in Ar + Lr and insert them into Av * * 2.e) select operation from Ar according to some priority rule; * 2.f) schedule the selected operation as late as possible before all of the operations from Lr; * 2.g) include the operation into Lr and exclude it from Ar; * 2.h) select next available operation(s) (in inverse graph) which are not in Av + Lv and insert them into Ar. * * 3. Shift left the start times of the operations from Lr so that they start immediately after latest from Lv finishes. * * */ QTextStream out(stdout); QList<ListDigraph::Node> Lv; QList<ListDigraph::Node> Lr; QList<ListDigraph::Node> Av; QList<ListDigraph::Node> Ar; QList<ListDigraph::Node> Avnext; QList<ListDigraph::Node> Lravail; // Currently available nodes from Lr QMap<ListDigraph::Node, Machine*> nodemachLr; // Assignments of the operations from Lr to the machines QHash<int, double> backmach; // Machines for backward operation scheduling <machine ID, time for operation finish> for (int i = 0; i < rc.machines().size(); i++) { backmach[rc.machines()[i]->ID] = 10000000; } ListDigraph::NodeMap<bool> nodesscheduled(pm.graph, false); // Scheduled nodes bool nodeavail; // Used for checking whether some node is available fro scheduling ListDigraph::Node curnode; Lv.clear(); Lr.clear(); Av.clear(); Ar.clear(); // Initialize the sets of operations Av for (ListDigraph::OutArcIt gait(pm.graph, pm.head); gait != INVALID; ++gait) { for (ListDigraph::OutArcIt lait(pm.graph, pm.graph.target(gait)); lait != INVALID; ++lait) { Av.append(pm.graph.target(lait)); } } //out << "Operations of Av:" << endl; //for (int i = 0; i < Av.size(); i++) { // out << Av[i] << endl; //} // Initialize the sets of operations Ar for (ListDigraph::InArcIt gait(pm.graph, pm.tail); gait != INVALID; ++gait) { for (ListDigraph::InArcIt lait(pm.graph, pm.graph.source(gait)); lait != INVALID; ++lait) { Ar.append(pm.graph.source(lait)); //Ar.append(pm.graph.source(gait)); } } //out << "Operations of Ar:" << endl; //for (int i = 0; i < Ar.size(); i++) { // out << *pm.ops[Ar[i]] << endl; //} //getchar(); NodeWeightComparatorGreater nwcg(&pm); // Run the loop while (Av.size() + Ar.size() > 0) { // Scheduling one operation from Av Avnext.clear(); //out << "Scheduling operations" << endl; //for (int i = 0; i < Av.size(); i++) { // out << pm.ops[Av[i]]->ID <<" "; //} //out<<endl; if (Av.size() > 0) { // Sort the nodes of Av qSort(Av.begin(), Av.end(), nwcg); curnode = Av[0]; // Schedule the first operation (as soon as possible) //Machine &m = rc(pm.ops[Av[0]]->toolID).nextAvailable(); // Select the fastest available machine from the corresponding tool group //Machine &m = rc(pm.ops[Av[0]]->toolID).fastestAvailable(pm.ops[Av[0]]->r(), pm.ops[Av[0]]->type); // Select the machine from the corresponding tool group to finish the operation the earliest Machine &m = rc(pm.ops[curnode]->toolID).earliestToFinish(pm.ops[curnode]); m << pm.ops[curnode]; nodesscheduled[curnode] = true; // Include the operation into Lv Lv.append(curnode); // Iterate through all child nodes of the current node for (ListDigraph::OutArcIt oait(pm.graph, curnode); oait != INVALID; ++oait) { if (!Lr.contains(pm.graph.target(oait)) && !Ar.contains(pm.graph.target(oait))) { // Check availability nodeavail = true; for (ListDigraph::InArcIt iait(pm.graph, pm.graph.target(oait)); iait != INVALID; ++iait) { nodeavail = nodeavail && nodesscheduled[pm.graph.source(iait)]; } if (nodeavail) { //out << "Now available : " << pm.graph.id(cursucc) << endl; // Update ready time of the newly enabled node pm.ops[pm.graph.target(oait)]->r(0.0); for (ListDigraph::InArcIt init(pm.graph, pm.graph.target(oait)); init != INVALID; ++init) { pm.ops[pm.graph.target(oait)]->r(Math::max(pm.ops[pm.graph.target(oait)]->r(), pm.ops[pm.graph.source(init)]->c())); } //if (!nodesscheduled[pm.graph.target(oait)]) { Av/*next*/.append(pm.graph.target(oait)); //} } } } // Exclude the operation from Av Av.removeAt(0); } //getchar(); //Av = Avnext; // Scheduling one operation from Ar if (Ar.size() > 0) { // Sort the nodes of Ar qSort(Ar.begin(), Ar.end(), nwcg); curnode = Ar.last(); // Schedule the operation with as late as possible before all operations from Lr // The operation with the smallest priority is selected //Machine &m = rc(pm.ops[curnode]->toolID).nextAvailable(); // Select the fastest available machine from the corresponding tool group //Machine &m = rc(pm.ops[curnode]->toolID).fastestAvailable(10000000, pm.ops[curnode]->type); // Select the random machine from the corresponding tool group //Machine &m = rc(pm.ops[curnode]->toolID).randomMachine(); // Find machine which could start this operation the latest Machine *m = NULL; double lateststarttime = 0.0; double curstarttime; // Iterate over all machines able to process the operation QList<Machine*> machines = rc(pm.ops[curnode]->toolID).machines(); for (int i = 0; i < machines.size(); i++) { curstarttime = backmach[machines[i]->ID] - machines[i]->procTime(pm.ops[curnode]); if (lateststarttime <= curstarttime) { lateststarttime = curstarttime; m = machines[i]; } } backmach[m->ID] = lateststarttime; // Select the machine from the corresponding tool group to finish the operation the earliest //Machine &m = rc(pm.ops[curnode]->toolID).earliestToFinish(pm.ops[curnode]); //m << pm.ops[curnode]; nodemachLr[curnode] = m; //nodesscheduled[curnode] = true; // Include the operation into Lr Lr.prepend(curnode); // Iterate through all parent nodes of the current node for (ListDigraph::InArcIt iait(pm.graph, curnode); iait != INVALID; ++iait) { if (!Lv.contains(pm.graph.source(iait)) && !Av.contains(pm.graph.source(iait))) { Ar.prepend(pm.graph.source(iait)); } } // Exclude the operation from Av Ar.removeLast(); } //out << "Av size = " << Av.size() << endl; } // Shift left all of the operations from Lr so that the earliest from them is started as soon as possible //out << "Operations in nodemachLr: " << endl; //for (int i = 0; i < nodemachLr.size(); i++) { // out << *pm.ops[nodemachLr[i].first] << endl; //} //getchar(); QList<ListDigraph::Node> keys; while (nodemachLr.size() > 0) { keys = nodemachLr.keys(); // Collect currently available (immediately schedulable) nodes from Lr Lravail.clear(); for (int i = 0; i < nodemachLr.size(); i++) { for (ListDigraph::InArcIt iait(pm.graph, keys[i]); iait != INVALID; ++iait) { if (Lv.contains(pm.graph.source(iait)) && nodesscheduled[pm.graph.source(iait)]) { Lravail.append(keys[i]); Lv.append(keys[i]); //Lr.removeOne(nodemachLr.keys()[i]); break; } } } // //Sort the nodes in Lravail qSort(Lravail.begin(), Lravail.end(), nwcg); //out << "Lravail operations before ready times update:" << endl; //for (int i = 0; i < Lravail.size(); i++) { // out << *pm.ops[Lravail[i]] << endl; //} //getchar(); // Update the ready time of the operations in Lravail and schedule them for (int i = 0; i < Lravail.size(); i++) { pm.ops[Lravail[i]]->r(0.0); for (ListDigraph::InArcIt iait(pm.graph, Lravail[i]); iait != INVALID; ++iait) { pm.ops[Lravail[i]]->r(Math::max(pm.ops[Lravail[i]]->r(), pm.ops[pm.graph.source(iait)]->c())); } // Schedule the available nodes *(nodemachLr.value(Lravail[i])) << pm.ops[Lravail[i]]; nodesscheduled[Lravail[i]] = true; nodemachLr.remove(Lravail[i]); } //out << "Lravail operations after ready times update:" << endl; //for (int i = 0; i < Lravail.size(); i++) { // out << *pm.ops[Lravail[i]] << endl; //} //getchar(); } //out << "Resources after scheduling" << endl; //out << rc << endl; // Iterate over all nodes directly preceding the tail and //Debugger::info << "Collecting schedule data ..." << ENDL; schedule.objective = 0.0; for (ListDigraph::ArcIt ait(pm.graph); ait != INVALID; ++ait) { if (pm.graph.target(ait) == pm.tail) { if (pm.ops[pm.graph.source(ait)]->ID < 0) { for (ListDigraph::InArcIt iait(pm.graph, pm.graph.source(ait)); iait != INVALID; ++iait) { schedule.objective += pm.ops[pm.graph.source(iait)]->wT(); } } else { schedule.objective += pm.ops[pm.graph.source(ait)]->wT(); } } } //Debugger::info << "Done collecting schedule data." << ENDL; return true; // Run BFS on the reverse graph to set due date for the operations Operation *so; Operation *to; ReverseDigraph<ListDigraph> rg(pm.graph); Bfs<ReverseDigraph<ListDigraph> > bfsr(rg); bfsr.init(); bfsr.addSource(pm.tail); //out << "Running BFS algorithm on the reverse graph ..." << endl; while (!bfsr.emptyQueue()) { curnode = bfsr.processNextNode(); if (pm.ops[curnode]->ID < 0) continue; //out << "Processing node with id= " << rg.id(curnode) << " " << *(pm.ops[curnode]) << endl; //out << "Next available nodes:" << endl; for (ReverseDigraph<ListDigraph>::OutArcIt it(rg, curnode); it != INVALID; ++it) { // Update the due dates of the reverse target nodes // Rev. target d == rev. source d. - rev. source longest processing time so = pm.ops[rg.source(it)]; to = pm.ops[rg.target(it)]; to->d(so->d() - rc(so->toolID).slowestMachine(so->type).procTime(so)); //out << "Node with id= " << rg.id(rg.target(it)) << " " << *(pm.ops[rg.target(it)]) << endl; } } so = to = NULL; //out << "Done running BFS algorithm on the reverse graph." << endl; return true; }
float Evaluate(const Mat &simmat, const Mat &mask, const QString &csv) { if (simmat.size() != mask.size()) qFatal("Similarity matrix (%ix%i) differs in size from mask matrix (%ix%i).", simmat.rows, simmat.cols, mask.rows, mask.cols); const int Max_Points = 500; float result = -1; // Make comparisons QList<Comparison> comparisons; comparisons.reserve(simmat.rows*simmat.cols); int genuineCount = 0, impostorCount = 0, numNaNs = 0; for (int i=0; i<simmat.rows; i++) { for (int j=0; j<simmat.cols; j++) { const BEE::Mask_t mask_val = mask.at<BEE::Mask_t>(i,j); const BEE::Simmat_t simmat_val = simmat.at<BEE::Simmat_t>(i,j); if (mask_val == BEE::DontCare) continue; if (simmat_val != simmat_val) { numNaNs++; continue; } comparisons.append(Comparison(simmat_val, j, i, mask_val == BEE::Match)); if (comparisons.last().genuine) genuineCount++; else impostorCount++; } } if (numNaNs > 0) qWarning("Encountered %d NaN scores!", numNaNs); if (genuineCount == 0) qFatal("No genuine scores!"); if (impostorCount == 0) qFatal("No impostor scores!"); // Sort comparisons by simmat_val (score) std::sort(comparisons.begin(), comparisons.end()); QList<OperatingPoint> operatingPoints; QList<float> genuines, impostors; QVector<int> firstGenuineReturns(simmat.rows, 0); int falsePositives = 0, previousFalsePositives = 0; int truePositives = 0, previousTruePositives = 0; int index = 0; float minGenuineScore = std::numeric_limits<float>::max(); float minImpostorScore = std::numeric_limits<float>::max(); while (index < comparisons.size()) { float thresh = comparisons[index].score; // Compute genuine and imposter statistics at a threshold while ((index < comparisons.size()) && (comparisons[index].score == thresh)) { const Comparison &comparison = comparisons[index]; if (comparison.genuine) { truePositives++; genuines.append(comparison.score); if (firstGenuineReturns[comparison.query] < 1) firstGenuineReturns[comparison.query] = abs(firstGenuineReturns[comparison.query]) + 1; if ((comparison.score != -std::numeric_limits<float>::max()) && (comparison.score < minGenuineScore)) minGenuineScore = comparison.score; } else { falsePositives++; impostors.append(comparison.score); if (firstGenuineReturns[comparison.query] < 1) firstGenuineReturns[comparison.query]--; if ((comparison.score != -std::numeric_limits<float>::max()) && (comparison.score < minImpostorScore)) minImpostorScore = comparison.score; } index++; } if ((falsePositives > previousFalsePositives) && (truePositives > previousTruePositives)) { // Restrict the extreme ends of the curve if ((falsePositives >= 10) && (falsePositives < impostorCount/2)) operatingPoints.append(OperatingPoint(thresh, float(falsePositives)/impostorCount, float(truePositives)/genuineCount)); previousFalsePositives = falsePositives; previousTruePositives = truePositives; } } if (operatingPoints.size() == 0) operatingPoints.append(OperatingPoint(1, 1, 1)); if (operatingPoints.size() == 1) operatingPoints.prepend(OperatingPoint(0, 0, 0)); if (operatingPoints.size() > 2) operatingPoints.takeLast(); // Remove point (1,1) // Write Metadata table QStringList lines; lines.append("Plot,X,Y"); lines.append("Metadata,"+QString::number(simmat.cols)+",Gallery"); lines.append("Metadata,"+QString::number(simmat.rows)+",Probe"); lines.append("Metadata,"+QString::number(genuineCount)+",Genuine"); lines.append("Metadata,"+QString::number(impostorCount)+",Impostor"); lines.append("Metadata,"+QString::number(simmat.cols*simmat.rows-(genuineCount+impostorCount))+",Ignored"); // Write Detection Error Tradeoff (DET), PRE, REC int points = qMin(operatingPoints.size(), Max_Points); for (int i=0; i<points; i++) { const OperatingPoint &operatingPoint = operatingPoints[double(i) / double(points-1) * double(operatingPoints.size()-1)]; lines.append(QString("DET,%1,%2").arg(QString::number(operatingPoint.FAR), QString::number(1-operatingPoint.TAR))); lines.append(QString("FAR,%1,%2").arg(QString::number(operatingPoint.score), QString::number(operatingPoint.FAR))); lines.append(QString("FRR,%1,%2").arg(QString::number(operatingPoint.score), QString::number(1-operatingPoint.TAR))); } // Write FAR/TAR Bar Chart (BC) lines.append(qPrintable(QString("BC,0.001,%1").arg(QString::number(getTAR(operatingPoints, 0.001), 'f', 3)))); lines.append(qPrintable(QString("BC,0.01,%1").arg(QString::number(result = getTAR(operatingPoints, 0.01), 'f', 3)))); // Write SD & KDE points = qMin(qMin(Max_Points, genuines.size()), impostors.size()); QList<double> sampledGenuineScores; sampledGenuineScores.reserve(points); QList<double> sampledImpostorScores; sampledImpostorScores.reserve(points); for (int i=0; i<points; i++) { float genuineScore = genuines[double(i) / double(points-1) * double(genuines.size()-1)]; float impostorScore = impostors[double(i) / double(points-1) * double(impostors.size()-1)]; if (genuineScore == -std::numeric_limits<float>::max()) genuineScore = minGenuineScore; if (impostorScore == -std::numeric_limits<float>::max()) impostorScore = minImpostorScore; lines.append(QString("SD,%1,Genuine").arg(QString::number(genuineScore))); lines.append(QString("SD,%1,Impostor").arg(QString::number(impostorScore))); sampledGenuineScores.append(genuineScore); sampledImpostorScores.append(impostorScore); } // Write Cumulative Match Characteristic (CMC) curve const int Max_Retrieval = 100; const int Report_Retrieval = 5; float reportRetrievalRate = -1; for (int i=1; i<=Max_Retrieval; i++) { int realizedReturns = 0, possibleReturns = 0; foreach (int firstGenuineReturn, firstGenuineReturns) { if (firstGenuineReturn > 0) { possibleReturns++; if (firstGenuineReturn <= i) realizedReturns++; } } const float retrievalRate = float(realizedReturns)/possibleReturns; lines.append(qPrintable(QString("CMC,%1,%2").arg(QString::number(i), QString::number(retrievalRate)))); if (i == Report_Retrieval) reportRetrievalRate = retrievalRate; } if (!csv.isEmpty()) QtUtils::writeFile(csv, lines); qDebug("TAR @ FAR = 0.01: %.3f\nRetrieval Rate @ Rank = %d: %.3f", result, Report_Retrieval, reportRetrievalRate); return result; }
void KJavaAppletServer::slotJavaRequest( const QByteArray& qb ) { // qb should be one command only without the length string, // we parse out the command and it's meaning here... QString cmd; QStringList args; int index = 0; const int qb_size = qb.size(); //get the command code const char cmd_code = qb[ index++ ]; ++index; //skip the next sep //get contextID QString contextID; while( qb[index] != 0 && index < qb_size ) { contextID += qb[ index++ ]; } bool ok; const int ID_num = contextID.toInt( &ok ); // context id or kio job id /*if (d->locked_context > -1 && ID_num != d->locked_context && (cmd_code == KJAS_JAVASCRIPT_EVENT || cmd_code == KJAS_APPLET_STATE || cmd_code == KJAS_APPLET_FAILED)) { / * Don't allow requests from other contexts if we're waiting * on a return value that can trigger JavaScript events * / d->java_requests.push_back(qb); return; }*/ ++index; //skip the sep if (cmd_code == KJAS_PUT_DATA) { // rest of the data is for kio put if (ok) { KIOJobMap::iterator it = d->kiojobs.find( ID_num ); if (ok && it != d->kiojobs.end()) { QByteArray qba; qba = QByteArray::fromRawData(qb.data() + index, qb.size() - index - 1); it.value()->data(qba); qba = QByteArray::fromRawData(qb.data() + index, qb.size() - index - 1); } kDebug(6100) << "PutData(" << ID_num << ") size=" << qb.size() - index; } else kError(6100) << "PutData error " << ok << endl; return; } //now parse out the arguments while( index < qb_size ) { int sep_pos = qb.indexOf( (char) 0, index ); if (sep_pos < 0) { kError(6100) << "Missing separation byte" << endl; sep_pos = qb_size; } //kDebug(6100) << "KJavaAppletServer::slotJavaRequest: "<< QString::fromLocal8Bit( qb.data() + index, sep_pos - index ); args.append( QString::fromLocal8Bit( qb.data() + index, sep_pos - index ) ); index = sep_pos + 1; //skip the sep } //here I should find the context and call the method directly //instead of emitting signals switch( cmd_code ) { case KJAS_SHOW_DOCUMENT: cmd = QLatin1String( "showdocument" ); break; case KJAS_SHOW_URLINFRAME: cmd = QLatin1String( "showurlinframe" ); break; case KJAS_SHOW_STATUS: cmd = QLatin1String( "showstatus" ); break; case KJAS_RESIZE_APPLET: cmd = QLatin1String( "resizeapplet" ); break; case KJAS_GET_URLDATA: if (ok && !args.empty() ) { d->kiojobs.insert(ID_num, new KJavaDownloader(ID_num, args.first())); kDebug(6100) << "GetURLData(" << ID_num << ") url=" << args.first(); } else kError(6100) << "GetURLData error " << ok << " args:" << args.size() << endl; return; case KJAS_PUT_URLDATA: if (ok && !args.empty()) { KJavaUploader* const job = new KJavaUploader(ID_num, args.first()); d->kiojobs.insert(ID_num, job); job->start(); kDebug(6100) << "PutURLData(" << ID_num << ") url=" << args.first(); } else kError(6100) << "PutURLData error " << ok << " args:" << args.size() << endl; return; case KJAS_DATA_COMMAND: if (ok && !args.empty()) { const int cmd = args.first().toInt( &ok ); KIOJobMap::iterator it = d->kiojobs.find( ID_num ); if (ok && it != d->kiojobs.end()) it.value()->jobCommand( cmd ); kDebug(6100) << "KIO Data command: " << ID_num << " " << args.first(); } else kError(6100) << "KIO Data command error " << ok << " args:" << args.size() << endl; return; case KJAS_JAVASCRIPT_EVENT: cmd = QLatin1String( "JS_Event" ); if(!args.empty()) { kDebug(6100) << "Javascript request: "<< contextID << " code: " << args[0] << endl; } else { kError(6100) << "Expected args not to be empty!" << endl; } break; case KJAS_GET_MEMBER: case KJAS_PUT_MEMBER: case KJAS_CALL_MEMBER: { if(!args.empty()) { const int ticket = args[0].toInt(); JSStack::iterator it = d->jsstack.find(ticket); if (it != d->jsstack.end()) { kDebug(6100) << "slotJavaRequest: " << ticket; args.pop_front(); it.value()->args.operator=(args); // just in case .. it.value()->ready = true; it.value()->exit = true; } else kDebug(6100) << "Error: Missed return member data"; } else { kError(6100) << "Expected args not to be empty!" << endl; } return; } case KJAS_AUDIOCLIP_PLAY: cmd = QLatin1String( "audioclip_play" ); if(!args.empty()) kDebug(6100) << "Audio Play: url=" << args[0]; else kError(6100) << "Expected args not to be empty!" << endl; break; case KJAS_AUDIOCLIP_LOOP: cmd = QLatin1String( "audioclip_loop" ); if(!args.empty()) kDebug(6100) << "Audio Loop: url=" << args[0]; else kError(6100) << "Expected args not to be empty!" << endl; break; case KJAS_AUDIOCLIP_STOP: cmd = QLatin1String( "audioclip_stop" ); if(!args.empty()) kDebug(6100) << "Audio Stop: url=" << args[0]; else kError(6100) << "Expected args not to be empty!" << endl; break; case KJAS_APPLET_STATE: if(args.size() > 1) kDebug(6100) << "Applet State Notification for Applet " << args[0] << ". New state=" << args[1]; else kError(6100) << "Expected args not to be empty!" << endl; cmd = QLatin1String( "AppletStateNotification" ); break; case KJAS_APPLET_FAILED: if(args.size() > 1) kDebug(6100) << "Applet " << args[0] << " Failed: " << args[1]; else kError(6100) << "Expected args not to be empty!" << endl; cmd = QLatin1String( "AppletFailed" ); break; case KJAS_SECURITY_CONFIRM: { if (KSSL::doesSSLWork() && !d->kssl) d->kssl = new KSSL; QStringList sl; QString answer( "invalid" ); if (!d->kssl) { answer = "nossl"; } else if (args.size() > 2) { const int certsnr = args[1].toInt(); Q_ASSERT(args.size() > certsnr + 1); QString text; QList<KSSLCertificate *> certs; for (int i = certsnr - 1; i >= 0; --i) { const QByteArray &arg = args[i + 2].toAscii(); KSSLCertificate * cert = KSSLCertificate::fromString(arg.constData()); if (cert) { certs.prepend(cert); if (cert->isSigner()) text += i18n("Signed by (validation: %1)", KSSLCertificate::verifyText(cert->validate())); else text += i18n("Certificate (validation: %1)", KSSLCertificate::verifyText(cert->validate())); text += "\n"; QString subject = cert->getSubject() + QChar('\n'); QRegExp reg(QString("/[A-Z]+=")); int pos = 0; while ((pos = subject.indexOf(reg, pos)) > -1) subject.replace(pos, 1, QString("\n ")); text += subject.mid(1); } } kDebug(6100) << "Security confirm " << args.first() << certs.count(); if ( !certs.isEmpty() ) { KSSLCertChain chain; chain.setChain( certs ); if ( chain.isValid() ) answer = PermissionDialog( qApp->activeWindow() ).exec( text, args[0] ); } qDeleteAll(certs); } sl.push_front( answer ); sl.push_front( QString::number(ID_num) ); process->send( KJAS_SECURITY_CONFIRM, sl ); return; } default: return; break; } if( !ok ) { kError(6100) << "could not parse out contextID to call command on" << endl; return; } KJavaAppletContext* const context = d->contexts[ ID_num ]; if( context ) context->processCmd( cmd, args ); else if (cmd != "AppletStateNotification") kError(6100) << "no context object for this id" << endl; }
void tst_ExceptionSafety::exceptionList() { { QList<FlexibleThrowerSmall> list; QList<FlexibleThrowerSmall> list2; QList<FlexibleThrowerSmall> list3; for( int i = 0; i<10; i++ ) list.append( FlexibleThrowerSmall(i) ); try { throwType = ThrowAtCopy; list.append( FlexibleThrowerSmall(10)); } catch (...) { } QCOMPARE( list.size(), 10 ); try { throwType = ThrowAtCopy; list.prepend( FlexibleThrowerSmall(10)); } catch (...) { } QCOMPARE( list.at(0).value(), 0 ); QCOMPARE( list.size(), 10 ); try { throwType = ThrowAtCopy; list.insert( 8, FlexibleThrowerSmall(10)); } catch (...) { } QCOMPARE( list.at(7).value(), 7 ); QCOMPARE( list.at(8).value(), 8 ); QCOMPARE( list.size(), 10 ); try { throwType = ThrowAtCopy; FlexibleThrowerSmall t = list.takeAt( 6 ); } catch (...) { } QCOMPARE( list.at(6).value(), 6 ); QCOMPARE( list.at(7).value(), 7 ); QCOMPARE( list.size(), 10 ); try { throwType = ThrowAtCopy; list3 = list; } catch (...) { } QCOMPARE( list.at(0).value(), 0 ); QCOMPARE( list.at(7).value(), 7 ); QCOMPARE( list.size(), 10 ); QCOMPARE( list3.at(0).value(), 0 ); QCOMPARE( list3.at(7).value(), 7 ); QCOMPARE( list3.size(), 10 ); try { throwType = ThrowAtCopy; list3.append( FlexibleThrowerSmall(11) ); } catch (...) { } QCOMPARE( list.at(0).value(), 0 ); QCOMPARE( list.at(7).value(), 7 ); QCOMPARE( list.size(), 10 ); QCOMPARE( list3.at(0).value(), 0 ); QCOMPARE( list3.at(7).value(), 7 ); QCOMPARE( list3.size(), 10 ); try { list2.clear(); list2.append( FlexibleThrowerSmall(11)); throwType = ThrowAtCopy; list3 = list+list2; } catch (...) { } QCOMPARE( list.at(0).value(), 0 ); QCOMPARE( list.at(7).value(), 7 ); QCOMPARE( list.size(), 10 ); // check that copy on write works atomar list2.clear(); list2.append( FlexibleThrowerSmall(11)); list3 = list+list2; try { throwType = ThrowAtCreate; list3[7]=FlexibleThrowerSmall(12); } catch (...) { } QCOMPARE( list.at(7).value(), 7 ); QCOMPARE( list.size(), 10 ); QCOMPARE( list3.at(7).value(), 7 ); QCOMPARE( list3.size(), 11 ); } QCOMPARE(objCounter, 0 ); // check that every object has been freed }
void CalligraphicMode::mouseReleaseEvent(QMouseEvent *m) { undoManager->setUndoEnabled(true); PageItem *currItem; m_MouseButtonPressed = false; m_canvas->resetRenderMode(); m->accept(); if (m_doc->appMode == modeDrawCalligraphicLine) { if (RecordP.size() > 1) { UndoTransaction createTransaction; if (UndoManager::undoEnabled()) createTransaction = UndoManager::instance()->beginTransaction(); uint z = m_doc->itemAdd(PageItem::Polygon, PageItem::Unspecified, Mxp, Myp, 1, 1, m_doc->itemToolPrefs().calligraphicPenLineWidth, m_doc->itemToolPrefs().calligraphicPenFillColor, m_doc->itemToolPrefs().calligraphicPenLineColor); currItem = m_doc->Items->at(z); currItem->PoLine.resize(0); QList<QPointF> clipU; QList<QPointF> clipL; double mx = sin(m_doc->itemToolPrefs().calligraphicPenAngle / 180.0 * M_PI) * (m_doc->itemToolPrefs().calligraphicPenWidth / 2.0); double my = cos(m_doc->itemToolPrefs().calligraphicPenAngle / 180.0 * M_PI) * (m_doc->itemToolPrefs().calligraphicPenWidth / 2.0); for (int px = 0; px < RecordP.size()-1; ++px) { FPoint clp = RecordP.point(px); clipU.append(QPointF(clp.x() - mx, clp.y() - my)); clipL.prepend(QPointF(clp.x() + mx, clp.y() + my)); } QPainterPath ppU = bezierFit(clipU, 5.0); QPainterPath ppL = bezierFit(clipL, 5.0); QPainterPath pp; pp.addPath(ppU); pp.connectPath(ppL); pp.closeSubpath(); currItem->PoLine.fromQPainterPath(pp); FPoint tp2(getMinClipF(&currItem->PoLine)); currItem->setXYPos(tp2.x(), tp2.y(), true); currItem->PoLine.translate(-tp2.x(), -tp2.y()); FPoint tp(getMaxClipF(&currItem->PoLine)); m_doc->sizeItem(tp.x(), tp.y(), currItem, false, false, false); m_doc->adjustItemSize(currItem); m_doc->m_Selection->clear(); m_doc->m_Selection->addItem(currItem); currItem->ClipEdited = true; currItem->FrameType = 3; currItem->OwnPage = m_doc->OnPage(currItem); currItem->PLineArt = Qt::PenStyle(m_doc->itemToolPrefs().calligraphicPenStyle); currItem->setFillShade(m_doc->itemToolPrefs().calligraphicPenFillColorShade); currItem->setLineShade(m_doc->itemToolPrefs().calligraphicPenLineColorShade); currItem->setFillEvenOdd(true); m_view->resetMousePressed(); currItem->checkChanges(); QString targetName = Um::ScratchSpace; if (currItem->OwnPage > -1) targetName = m_doc->Pages->at(currItem->OwnPage)->getUName(); if (createTransaction) createTransaction.commit(targetName, currItem->getUPixmap(), Um::Create + " " + currItem->getUName(), "", Um::ICreate); //FIXME m_canvas->m_viewMode.operItemResizing = false; m_doc->changed(); } if (!PrefsManager::instance()->appPrefs.uiPrefs.stickyTools) { m_view->requestMode(modeNormal); } else m_view->requestMode(m_doc->appMode); return; } m_canvas->setRenderModeUseBuffer(false); m_doc->DragP = false; m_doc->leaveDrag = false; m_view->MidButt = false; if (m_view->groupTransactionStarted()) { for (int i = 0; i < m_doc->m_Selection->count(); ++i) m_doc->m_Selection->itemAt(i)->checkChanges(true); m_view->endGroupTransaction(); } for (int i = 0; i < m_doc->m_Selection->count(); ++i) m_doc->m_Selection->itemAt(i)->checkChanges(true); //Commit drag created items to undo manager. if (m_doc->m_Selection->itemAt(0)!=NULL) { m_doc->itemAddCommit(m_doc->m_Selection->itemAt(0)); } //Make sure the Zoom spinbox and page selector don't have focus if we click on the canvas m_view->m_ScMW->zoomSpinBox->clearFocus(); m_view->m_ScMW->pageSelector->clearFocus(); if (m_doc->m_Selection->itemAt(0) != 0) // is there the old clip stored for the undo action { currItem = m_doc->m_Selection->itemAt(0); m_doc->nodeEdit.finishTransaction(currItem); } }