const unsigned char* QgsDistanceArea::measurePolygon( const unsigned char* feature, double* area, double* perimeter, bool hasZptr ) { if ( !feature ) { QgsDebugMsg( "no feature to measure" ); return 0; } // get number of rings in the polygon unsigned int numRings = *(( int* )( feature + 1 + sizeof( int ) ) ); if ( numRings == 0 ) { QgsDebugMsg( "no rings to measure" ); return 0; } // Set pointer to the first ring const unsigned char* ptr = feature + 1 + 2 * sizeof( int ); QList<QgsPoint> points; QgsPoint pnt; double x, y; if ( area ) *area = 0; if ( perimeter ) *perimeter = 0; try { for ( unsigned int idx = 0; idx < numRings; idx++ ) { int nPoints = *(( int* )ptr ); ptr += 4; // Extract the points from the WKB and store in a pair of // vectors. for ( int jdx = 0; jdx < nPoints; jdx++ ) { x = *(( double * ) ptr ); ptr += sizeof( double ); y = *(( double * ) ptr ); ptr += sizeof( double ); if ( hasZptr ) { // totally ignore Z value ptr += sizeof( double ); } pnt = QgsPoint( x, y ); if ( mEllipsoidalMode && ( mEllipsoid != GEO_NONE ) ) { pnt = mCoordTransform->transform( pnt ); } points.append( pnt ); } if ( points.size() > 2 ) { if ( area ) { double areaTmp = computePolygonArea( points ); if ( idx == 0 ) { // exterior ring *area += areaTmp; } else { *area -= areaTmp; // interior rings } } if ( perimeter ) { if ( idx == 0 ) { // exterior ring *perimeter += measureLine( points ); } } } points.clear(); } } catch ( QgsCsException &cse ) { Q_UNUSED( cse ); QgsMessageLog::logMessage( QObject::tr( "Caught a coordinate system exception while trying to transform a point. Unable to calculate polygon area or perimeter." ) ); } return ptr; }
void QgsDelimitedTextProvider::scanFile( bool buildIndexes ) { QStringList messages; // assume the layer is invalid until proven otherwise mLayerValid = false; mValid = false; mRescanRequired = false; clearInvalidLines(); // Initiallize indexes resetIndexes(); bool buildSpatialIndex = buildIndexes && nullptr != mSpatialIndex; // No point building a subset index if there is no geometry, as all // records will be included. bool buildSubsetIndex = buildIndexes && mBuildSubsetIndex && mGeomRep != GeomNone; if ( ! mFile->isValid() ) { // uri is invalid so the layer must be too... messages.append( tr( "File cannot be opened or delimiter parameters are not valid" ) ); reportErrors( messages ); QgsDebugMsg( "Delimited text source invalid - filename or delimiter parameters" ); return; } // Open the file and get number of rows, etc. We assume that the // file has a header row and process accordingly. Caller should make // sure that the delimited file is properly formed. if ( mGeomRep == GeomAsWkt ) { mWktFieldIndex = mFile->fieldIndex( mWktFieldName ); if ( mWktFieldIndex < 0 ) { messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( QStringLiteral( "Wkt" ), mWktFieldName ) ); } } else if ( mGeomRep == GeomAsXy ) { mXFieldIndex = mFile->fieldIndex( mXFieldName ); mYFieldIndex = mFile->fieldIndex( mYFieldName ); if ( mXFieldIndex < 0 ) { messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( QStringLiteral( "X" ), mWktFieldName ) ); } if ( mYFieldIndex < 0 ) { messages.append( tr( "%0 field %1 is not defined in delimited text file" ).arg( QStringLiteral( "Y" ), mWktFieldName ) ); } } if ( !messages.isEmpty() ) { reportErrors( messages ); QgsDebugMsg( "Delimited text source invalid - missing geometry fields" ); return; } // Scan the entire file to determine // 1) the number of fields (this is handled by QgsDelimitedTextFile mFile // 2) the number of valid features. Note that the selection of valid features // should match the code in QgsDelimitedTextFeatureIterator // 3) the geometric extents of the layer // 4) the type of each field // // Also build subset and spatial indexes. QStringList parts; long nEmptyRecords = 0; long nBadFormatRecords = 0; long nIncompatibleGeometry = 0; long nInvalidGeometry = 0; long nEmptyGeometry = 0; mNumberFeatures = 0; mExtent = QgsRectangle(); QList<bool> isEmpty; QList<bool> couldBeInt; QList<bool> couldBeLongLong; QList<bool> couldBeDouble; bool foundFirstGeometry = false; while ( true ) { QgsDelimitedTextFile::Status status = mFile->nextRecord( parts ); if ( status == QgsDelimitedTextFile::RecordEOF ) break; if ( status != QgsDelimitedTextFile::RecordOk ) { nBadFormatRecords++; recordInvalidLine( tr( "Invalid record format at line %1" ) ); continue; } // Skip over empty records if ( recordIsEmpty( parts ) ) { nEmptyRecords++; continue; } // Check geometries are valid bool geomValid = true; if ( mGeomRep == GeomAsWkt ) { if ( mWktFieldIndex >= parts.size() || parts[mWktFieldIndex].isEmpty() ) { nEmptyGeometry++; mNumberFeatures++; } else { // Get the wkt - confirm it is valid, get the type, and // if compatible with the rest of file, add to the extents QString sWkt = parts[mWktFieldIndex]; QgsGeometry geom; if ( !mWktHasPrefix && sWkt.indexOf( sWktPrefixRegexp ) >= 0 ) mWktHasPrefix = true; geom = geomFromWkt( sWkt, mWktHasPrefix ); if ( !geom.isNull() ) { QgsWkbTypes::Type type = geom.wkbType(); if ( type != QgsWkbTypes::NoGeometry ) { if ( mGeometryType == QgsWkbTypes::UnknownGeometry || geom.type() == mGeometryType ) { mGeometryType = geom.type(); if ( !foundFirstGeometry ) { mNumberFeatures++; mWkbType = type; mExtent = geom.boundingBox(); foundFirstGeometry = true; } else { mNumberFeatures++; if ( geom.isMultipart() ) mWkbType = type; QgsRectangle bbox( geom.boundingBox() ); mExtent.combineExtentWith( bbox ); } if ( buildSpatialIndex ) { QgsFeature f; f.setId( mFile->recordId() ); f.setGeometry( geom ); mSpatialIndex->insertFeature( f ); } } else { nIncompatibleGeometry++; geomValid = false; } } } else { geomValid = false; nInvalidGeometry++; recordInvalidLine( tr( "Invalid WKT at line %1" ) ); } } } else if ( mGeomRep == GeomAsXy ) { // Get the x and y values, first checking to make sure they // aren't null. QString sX = mXFieldIndex < parts.size() ? parts[mXFieldIndex] : QString(); QString sY = mYFieldIndex < parts.size() ? parts[mYFieldIndex] : QString(); if ( sX.isEmpty() && sY.isEmpty() ) { nEmptyGeometry++; mNumberFeatures++; } else { QgsPointXY pt; bool ok = pointFromXY( sX, sY, pt, mDecimalPoint, mXyDms ); if ( ok ) { if ( foundFirstGeometry ) { mExtent.combineExtentWith( pt.x(), pt.y() ); } else { // Extent for the first point is just the first point mExtent.set( pt.x(), pt.y(), pt.x(), pt.y() ); mWkbType = QgsWkbTypes::Point; mGeometryType = QgsWkbTypes::PointGeometry; foundFirstGeometry = true; } mNumberFeatures++; if ( buildSpatialIndex && std::isfinite( pt.x() ) && std::isfinite( pt.y() ) ) { QgsFeature f; f.setId( mFile->recordId() ); f.setGeometry( QgsGeometry::fromPointXY( pt ) ); mSpatialIndex->insertFeature( f ); } } else { geomValid = false; nInvalidGeometry++; recordInvalidLine( tr( "Invalid X or Y fields at line %1" ) ); } } } else { mWkbType = QgsWkbTypes::NoGeometry; mNumberFeatures++; } if ( !geomValid ) continue; if ( buildSubsetIndex ) mSubsetIndex.append( mFile->recordId() ); // If we are going to use this record, then assess the potential types of each column for ( int i = 0; i < parts.size(); i++ ) { QString &value = parts[i]; // Ignore empty fields - spreadsheet generated CSV files often // have random empty fields at the end of a row if ( value.isEmpty() ) continue; // Expand the columns to include this non empty field if necessary while ( couldBeInt.size() <= i ) { isEmpty.append( true ); couldBeInt.append( false ); couldBeLongLong.append( false ); couldBeDouble.append( false ); } // If this column has been empty so far then initiallize it // for possible types if ( isEmpty[i] ) { isEmpty[i] = false; couldBeInt[i] = true; couldBeLongLong[i] = true; couldBeDouble[i] = true; } if ( ! mDetectTypes ) { continue; } // Now test for still valid possible types for the field // Types are possible until first record which cannot be parsed if ( couldBeInt[i] ) { value.toInt( &couldBeInt[i] ); } if ( couldBeLongLong[i] && ! couldBeInt[i] ) { value.toLongLong( &couldBeLongLong[i] ); } if ( couldBeDouble[i] && ! couldBeLongLong[i] ) { if ( ! mDecimalPoint.isEmpty() ) { value.replace( mDecimalPoint, QLatin1String( "." ) ); } value.toDouble( &couldBeDouble[i] ); } } } // Now create the attribute fields. Field types are integer by preference, // failing that double, failing that text. QStringList fieldNames = mFile->fieldNames(); mFieldCount = fieldNames.size(); attributeColumns.clear(); attributeFields.clear(); QString csvtMessage; QStringList csvtTypes = readCsvtFieldTypes( mFile->fileName(), &csvtMessage ); for ( int i = 0; i < fieldNames.size(); i++ ) { // Skip over WKT field ... don't want to display in attribute table if ( i == mWktFieldIndex ) continue; // Add the field index lookup for the column attributeColumns.append( i ); QVariant::Type fieldType = QVariant::String; QString typeName = QStringLiteral( "text" ); if ( i < csvtTypes.size() ) { typeName = csvtTypes[i]; } else if ( mDetectTypes && i < couldBeInt.size() ) { if ( couldBeInt[i] ) { typeName = QStringLiteral( "integer" ); } else if ( couldBeLongLong[i] ) { typeName = QStringLiteral( "longlong" ); } else if ( couldBeDouble[i] ) { typeName = QStringLiteral( "double" ); } } if ( typeName == QStringLiteral( "integer" ) ) { fieldType = QVariant::Int; } else if ( typeName == QStringLiteral( "longlong" ) ) { fieldType = QVariant::LongLong; } else if ( typeName == QStringLiteral( "real" ) || typeName == QStringLiteral( "double" ) ) { typeName = QStringLiteral( "double" ); fieldType = QVariant::Double; } else { typeName = QStringLiteral( "text" ); } attributeFields.append( QgsField( fieldNames[i], fieldType, typeName ) ); } QgsDebugMsg( "Field count for the delimited text file is " + QString::number( attributeFields.size() ) ); QgsDebugMsg( "geometry type is: " + QString::number( mWkbType ) ); QgsDebugMsg( "feature count is: " + QString::number( mNumberFeatures ) ); QStringList warnings; if ( ! csvtMessage.isEmpty() ) warnings.append( csvtMessage ); if ( nBadFormatRecords > 0 ) warnings.append( tr( "%1 records discarded due to invalid format" ).arg( nBadFormatRecords ) ); if ( nEmptyGeometry > 0 ) warnings.append( tr( "%1 records have missing geometry definitions" ).arg( nEmptyGeometry ) ); if ( nInvalidGeometry > 0 ) warnings.append( tr( "%1 records discarded due to invalid geometry definitions" ).arg( nInvalidGeometry ) ); if ( nIncompatibleGeometry > 0 ) warnings.append( tr( "%1 records discarded due to incompatible geometry types" ).arg( nIncompatibleGeometry ) ); reportErrors( warnings ); // Decide whether to use subset ids to index records rather than simple iteration through all // If more than 10% of records are being skipped, then use index. (Not based on any experimentation, // could do with some analysis?) if ( buildSubsetIndex ) { long recordCount = mFile->recordCount(); recordCount -= recordCount / SUBSET_ID_THRESHOLD_FACTOR; mUseSubsetIndex = mSubsetIndex.size() < recordCount; if ( ! mUseSubsetIndex ) mSubsetIndex = QList<quintptr>(); } mUseSpatialIndex = buildSpatialIndex; mValid = mGeometryType != QgsWkbTypes::UnknownGeometry; mLayerValid = mValid; // If it is valid, then watch for changes to the file connect( mFile.get(), &QgsDelimitedTextFile::fileUpdated, this, &QgsDelimitedTextProvider::onFileUpdated ); }
void GDataPrivate::slotListRecentPosts( Syndication::Loader *loader, Syndication::FeedPtr feed, Syndication::ErrorCode status ) { kDebug(); Q_Q( GData ); if( !loader ) { kError() << "loader is a null pointer."; return; } if ( status != Syndication::Success ) { emit q->error( GData::Atom, i18n( "Could not get posts." ) ); return; } int number = 0; if ( mListRecentPostsMap.contains( loader ) ) { number = mListRecentPostsMap[ loader ]; } mListRecentPostsMap.remove( loader ); QList<KBlog::BlogPost> postList; QList<Syndication::ItemPtr> items = feed->items(); QList<Syndication::ItemPtr>::ConstIterator it = items.constBegin(); QList<Syndication::ItemPtr>::ConstIterator end = items.constEnd(); for ( ; it != end; ++it ) { BlogPost post; QRegExp rx( "post-(\\d+)" ); if ( rx.indexIn( ( *it )->id() ) == -1 ) { kError() << "QRegExp rx( 'post-(\\d+)' does not match"<< rx.cap(1); emit q->error( GData::Other, i18n( "Could not regexp the post id path." ) ); } else { post.setPostId( rx.cap(1) ); } kDebug() << "QRegExp rx( 'post-(\\d+)' matches" << rx.cap(1); post.setTitle( ( *it )->title() ); post.setContent( ( *it )->content() ); post.setLink( ( *it )->link() ); QStringList labels; int catCount = ( *it )->categories().count(); QList< Syndication::CategoryPtr > cats = ( *it )->categories(); for(int i=0; i < catCount; ++i) { if(cats[i].get()->label().isEmpty()){ labels.append(cats[i].get()->term()); } else { labels.append(cats[i].get()->label()); } } post.setTags(labels); // FIXME: assuming UTC for now post.setCreationDateTime( KDateTime( QDateTime::fromTime_t( ( *it )->datePublished() ), KDateTime::Spec::UTC() ).toLocalZone() ); post.setModificationDateTime( KDateTime( QDateTime::fromTime_t( ( *it )->dateUpdated() ), KDateTime::Spec::UTC() ).toLocalZone() ); post.setStatus( BlogPost::Fetched ); postList.append( post ); if ( number-- == 0 ) { break; } } kDebug() << "Emitting listedRecentPosts()"; emit q->listedRecentPosts( postList ); }
void SmugTalker::parseResponseListAlbums(const QByteArray& data) { int errCode = -1; QString errMsg; QDomDocument doc("albums.get"); if (!doc.setContent(data)) return; kDebug() << "Parse Albums response:" << endl << data; QList <SmugAlbum> albumsList; QDomElement e = doc.documentElement(); for (QDomNode node = e.firstChild(); !node.isNull(); node = node.nextSibling()) { if (!node.isElement()) continue; e = node.toElement(); if (e.tagName() == "Albums") { for (QDomNode nodeA = e.firstChild(); !nodeA.isNull(); nodeA = nodeA.nextSibling()) { if (!nodeA.isElement()) continue; e = nodeA.toElement(); if (e.tagName() == "Album") { SmugAlbum album; album.id = e.attribute("id").toInt(); album.key = e.attribute("Key"); album.title = htmlToText(e.attribute("Title")); album.description = htmlToText(e.attribute("Description")); album.keywords = htmlToText(e.attribute("Keywords")); album.isPublic = e.attribute("Public") == "1"; album.password = htmlToText(e.attribute("Password")); album.passwordHint = htmlToText(e.attribute("PasswordHint")); album.imageCount = e.attribute("ImageCount").toInt(); for (QDomNode nodeC = e.firstChild(); !nodeC.isNull(); nodeC = node.nextSibling()) { if (!nodeC.isElement()) continue; e = nodeC.toElement(); if (e.tagName() == "Category") { album.categoryID = e.attribute("id").toInt(); album.category = htmlToText(e.attribute("Name")); } else if (e.tagName() == "SubCategory") { album.subCategoryID = e.attribute("id").toInt(); album.subCategory = htmlToText(e.attribute("Name")); } } albumsList.append(album); } } errCode = 0; } else if (e.tagName() == "err") { errCode = e.attribute("code").toInt(); errMsg = e.attribute("msg"); kDebug() << "Error:" << errCode << errMsg; } } if (errCode == 15) // 15: empty list errCode = 0; emit signalBusy(false); emit signalListAlbumsDone(errCode, errorToText(errCode, errMsg), albumsList); }
/** * Act on mime data that is dropped in our model * * @param data The actual data that is dropped * @param action The action. This could mean drop/copy etc * @param row The row where it is dropper * @param column The column where it is dropper * @param parent The parent of where we have dropped it * * @return bool if we accest the drop */ bool PlaylistTableModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int /*column*/, const QModelIndex & /*parent*/) { if (action == Qt::IgnoreAction) { return true; } if (data->hasFormat("application/qtmpc_song_move_text")) { //Act on internal moves QByteArray encodedData = data->data("application/qtmpc_song_move_text"); QDataStream stream(&encodedData, QIODevice::ReadOnly); QList<quint32> items; int diff = row - lastClickedRow; if (diff == 0) { return true; } while (!stream.atEnd()) { QString text; stream >> text; //We only do real moves if (row < 0) { continue; } items.append(text.toUInt()); } QList<quint32>::iterator bound; //Sort playlist to make moves easier if (diff > 0) { qSort(items.begin(), items.end(), qGreater<quint32>()); diff -= 1; } else { qSort(items); } // Find if we have a playlist over or underflow for (QList<quint32>::iterator i = items.begin(); i != items.end(); i++) { if (diff > 0) { if ((qint32)(*i + diff) >= songs.size()-1) { bound = i+1; } } else { if ((qint32)(*i + diff) <= 0) { bound = i+1; } } } if (diff > 0) { qSort(items.begin(), bound); } else { qSort(items.begin(), bound, qGreater<quint32>()); } emit moveInPlaylist(items, diff, songs.size()-1); return true; } else if (data->hasFormat("application/qtmpc_songs_filename_text")) {
QVariant QMacPasteboard::retrieveData(const QString &format, QVariant::Type) const { if (!paste) return QVariant(); sync(); ItemCount cnt = 0; if(PasteboardGetItemCount(paste, &cnt) || !cnt) return QByteArray(); #ifdef DEBUG_PASTEBOARD qDebug("Pasteboard: retrieveData [%s]", qPrintable(format)); #endif const QList<QMacPasteboardMime *> mimes = QMacPasteboardMime::all(mime_type); for(int mime = 0; mime < mimes.size(); ++mime) { QMacPasteboardMime *c = mimes.at(mime); QString c_flavor = c->flavorFor(format); if(!c_flavor.isEmpty()) { // Handle text/plain a little differently. Try handling Unicode first. bool checkForUtf16 = (c_flavor == QLatin1String("com.apple.traditional-mac-plain-text") || c_flavor == QLatin1String("public.utf8-plain-text")); if (checkForUtf16 || c_flavor == QLatin1String("public.utf16-plain-text")) { // Try to get the NSStringPboardType from NSPasteboard, newlines are mapped // correctly (as '\n') in this data. The 'public.utf16-plain-text' type // usually maps newlines to '\r' instead. QString str = qt_mac_get_pasteboardString(paste); if (!str.isEmpty()) return str; } if (checkForUtf16 && hasFlavor(QLatin1String("public.utf16-plain-text"))) c_flavor = QLatin1String("public.utf16-plain-text"); QVariant ret; QList<QByteArray> retList; for(uint index = 1; index <= cnt; ++index) { PasteboardItemID id; if(PasteboardGetItemIdentifier(paste, index, &id) != noErr) continue; QCFType<CFArrayRef> types; if(PasteboardCopyItemFlavors(paste, id, &types ) != noErr) continue; const int type_count = CFArrayGetCount(types); for(int i = 0; i < type_count; ++i) { CFStringRef flavor = static_cast<CFStringRef>(CFArrayGetValueAtIndex(types, i)); if(c_flavor == QCFString::toQString(flavor)) { QCFType<CFDataRef> macBuffer; if(PasteboardCopyItemFlavorData(paste, id, flavor, &macBuffer) == noErr) { QByteArray buffer((const char *)CFDataGetBytePtr(macBuffer), CFDataGetLength(macBuffer)); if(!buffer.isEmpty()) { #ifdef DEBUG_PASTEBOARD qDebug(" - %s [%s] (%s)", qPrintable(format), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName())); #endif buffer.detach(); //detach since we release the macBuffer retList.append(buffer); break; //skip to next element } } } else { #ifdef DEBUG_PASTEBOARD qDebug(" - NoMatch %s [%s] (%s)", qPrintable(c_flavor), qPrintable(QCFString::toQString(flavor)), qPrintable(c->convertorName())); #endif } } } if (!retList.isEmpty()) { ret = c->convertToMime(format, retList, c_flavor); return ret; } } } return QVariant(); }
void OrderDownload::insertOrder2ERPByJson(const QJsonObject &json) { int orderId = json.value("OrderID").toInt(); // Kjt 系统订单号 int merchantSysNo = json.value("MerchantSysNo").toInt(); // QString merchantOrderID = json.value("MerchantOrderID").toString(); // 第三方商家订单号 /// 跨镜通将会把日期修改为 yyyy-MM-dd hh:mm:ss 形式。到时再修改此处 QDateTime orderDate = convertKjtTime(json.value("OrderDate").toString()); // 订单时间 /// 订单状态码规则 /// -4 系统作废 /// -1 作废 /// 0 待审核 /// 1 待出库 /// 4 已出库待申报 /// 41 已申报待通关 /// 45 已通关发往顾客 /// 5 订单完成 /// 6 申报失败订单作废 /// 65 通关失败订单作废 /// 7 订单拒收 int sOStatusCode = json.value("SOStatusCode").toInt(); // 订单当前状态代码 QString sOStatusDescription = json.value("SOStatusDescription").toString(); // 订单当前状态描述 int tradeType = json.value("TradeType").toInt(); // 贸易类型 0:直邮 1:自贸 int warehouseID = json.value("WarehouseID").toInt(); // 仓库编号 51 = 浦东机场自贸仓 52 = 洋山港自贸仓 53 = 外高桥自贸仓 QDateTime auditTime = convertKjtTime(json.value("AuditTime").toString()); // 审核时间 QDateTime sOOutStockTime = convertKjtTime(json.value("SOOutStockTime").toString()); // 出库时间 QDateTime sOOutCustomsTime = convertKjtTime(json.value("SOOutCustomsTime").toString()); // 出区时间 int saleChannelSysNo = json.value("SaleChannelSysNo").toInt(); // 分销渠道编号 QString saleChannelName = json.value("SaleChannelName").toString(); // 分销渠道名称 QJsonObject foreignExchangePurchasingInfoObject = json.value("ForeignExchangePurchasingInfo").toObject(); // 订单支付信息 /// 购汇状态代码 -3:购汇异常 0:未购汇 1:待购汇 2:购汇中 3:购汇完成 int statusCode = foreignExchangePurchasingInfoObject.value("StatusCode").toInt(); // 购汇状态代码 QString statusDescrption = foreignExchangePurchasingInfoObject.value("StatusDescrption").toString(); // 购汇状态描述 QString purchasingCurrencyCode = foreignExchangePurchasingInfoObject.value("PurchasingCurrencyCode").toString(); // 购汇币种代码,如 EUR, JPY, AUD 等 double purchasingAmt = foreignExchangePurchasingInfoObject.value("PurchasingAmt").toDouble(); // 购汇金额 QString purchasingException = foreignExchangePurchasingInfoObject.value("PurchasingException").toString(); // 购汇异常 QJsonObject payInfoObject = json.value("PayInfo").toObject(); // 订单支付信息 double productAmount = payInfoObject.value("ProductAmount").toDouble(); // 商品总金额,保留 2 位小数(如 120.50 或 100.00,无费用时为 0) double shippingAmount = payInfoObject.value("ShippingAmount").toDouble(); // 运费总金额,保留 2 位小数 double taxAmount = payInfoObject.value("TaxAmount").toDouble(); // 商品行邮税总金额,保留 2 位小数 double commissionAmount = payInfoObject.value("CommissionAmount").toDouble(); // 下单支付产生的手续费,保留 2 位小数 /// 支付方式编号 112: 支付宝 114: 财付通 117: 银联支付 118: 微信支付 int payTypeSysNo = payInfoObject.value("PayTypeSysNo").toInt(); // 支付方式编号 QString paySerialNumber = payInfoObject.value("PaySerialNumber").toString(); // 支付流水号,不能重复,订单申报必要信息 int payStatusCode = payInfoObject.value("PayStatusCode").toInt(); // 支付状态码 0:未支付 1:已支付未审核 2:已支付审核通过 QJsonObject shippingInfoObject = json.value("ShippingInfo").toObject(); // 订单配送信息 QString receiveName = shippingInfoObject.value("ReceiveName").toString(); // 收件人姓名 QString receivePhone = shippingInfoObject.value("ReceivePhone").toString(); // 收件人电话 QString receiveAddress = shippingInfoObject.value("ReceiveAddress").toString(); // 收件人收货地址,不包含省市区名称 /// 收货地区编号,至少需要到市级别(根据中华人民共和国国家统计局提供的《最新县及县以上行政区划代码(截止 2013 年 8月 31 日)》 /// http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201401/t20140116_501070.html QString receiveAreaCode = shippingInfoObject.value("ReceiveAreaCode").toString(); // 收货地区编号 QString receiveZip = shippingInfoObject.value("ReceiveZip").toString(); // 收件地邮政编码 QString shipTypeID = shippingInfoObject.value("ShipTypeID").toString(); // 订单物流运输公司编号,参见附录《跨境通自贸仓支持的配送方式列表》 QString senderName = shippingInfoObject.value("SenderName").toString(); // 发件人姓名 QString senderTel = shippingInfoObject.value("SenderTel").toString(); // 发件人电话 QString senderCompanyName = shippingInfoObject.value("SenderCompanyName").toString(); // 发件人公司 QString senderAddr = shippingInfoObject.value("SenderAddr").toString(); // 发件人地址 QString senderZip = shippingInfoObject.value("SenderZip").toString(); // 发件地邮编 QString senderCity = shippingInfoObject.value("SenderCity").toString(); // 发件地城市 QString senderProvince = shippingInfoObject.value("SenderProvince").toString(); // 发件地省 QString senderCountry = shippingInfoObject.value("SenderCountry").toString(); // 发件地国家,例如:USA(代表美国)CHN(代表中国) QString receiveAreaName = shippingInfoObject.value("ReceiveAreaName").toString(); // 收件省市区名称(省市区名称之间用半角逗号,隔开,如 上海,上海市,静安区) QString trackingNumber = shippingInfoObject.value("TrackingNumber").toString(); // 订单物流运单号 QJsonObject sOAuthenticationInfoObject = json.value("SOAuthenticationInfo").toObject(); // 下单用户实名认证信息 QString name = sOAuthenticationInfoObject.value("Name").toString(); // 下单用户真实姓名 int iDCardType = sOAuthenticationInfoObject.value("IDCardType").toInt(); // 下单用户证件类型(0 – 身份证) QString iDCardNumber = sOAuthenticationInfoObject.value("IDCardNumber").toString(); // 下单用户证件编号 QString phoneNumber = sOAuthenticationInfoObject.value("PhoneNumber").toString(); // 下单用户联系电话 QString email = sOAuthenticationInfoObject.value("Email").toString(); // 下单用户电子邮件 QString address = sOAuthenticationInfoObject.value("Address").toString(); // 下单用户联系地址 QJsonArray itemListObject = json.value("ItemList").toArray(); // 订单中购买商品列表 QList<SOItemInfo> sOItemInfoList; for (int i = 0; i < itemListObject.size(); i++) { QJsonObject sOItemInfoObject = itemListObject.at(i).toObject(); SOItemInfo sOitemInfo; sOitemInfo._productName = sOItemInfoObject.value("ProductName").toString(); // 商品名称 sOitemInfo._productId = sOItemInfoObject.value("ProductID").toString(); // KJT 商品 ID sOitemInfo._quantity = sOItemInfoObject.value("Quantity").toInt(); // sOitemInfo._productPrice = sOItemInfoObject.value("ProductPrice").toDouble(); sOitemInfo._taxPrice = sOItemInfoObject.value("TaxPrice").toDouble(); sOitemInfo._taxRate = sOItemInfoObject.value("TaxRate").toDouble(); sOitemInfo._sOItemSysNo = sOItemInfoObject.value("SOItemSysNo").toInt(); sOItemInfoList.append(sOitemInfo); } QJsonArray logsArray = json.value("Logs").toArray(); // 订单日志 QList<LogInfo> logInfoList; for (int i = 0; i < logsArray.size(); i++) { QJsonObject logObject = logsArray.at(i).toObject(); LogInfo logInfo; logInfo._optTime = convertKjtTime(logObject.value("OptTime").toString()); logInfo._optType = logObject.value("OptType").toInt(); logInfo._optNote = logObject.value("OptNote").toString(); logInfoList.append(logInfo); } qDebug() << orderId << merchantOrderID << "ReceiveAreaName: " << receiveAreaName; // if (10022053 != orderId) return; /// 如果“第三方商家订单号”这个字段不为空,则表示是其他平台上传的订单,此处不做下载处理 if (!merchantOrderID.isNull()) return; /// 仅下载付款后,待出库的订单 if (sOStatusCode != 5) return; QSqlQuery query; query.prepare(tr("select * from 订单 where 订单类型=:OrderType and 第三方订单号=:MerchantOrderID")); query.bindValue(":OrderType", "kjt"); query.bindValue(":MerchantOrderID", QString::number(orderId)); if (!query.exec()) { qInfo() << query.lastError().text(); _ohData._success = false; } /// 已存在此订单编号,直接返回 if (query.first()) { qInfo() << tr("此订单已存在。kjt系统订单号:") + QString::number(orderId); return; } query.prepare(tr("insert into 订单(" "订单号, 订单类型, 第三方订单号, 下单日期, 跨境通订单状态, " "贸易类型, 审核日期, 发货日期, 商品总金额, 配送费用, " "税金, 支付手续费, 支付方式, 支付流水号, 付款状态, " "收货人, 手机号码, 收货地址, 邮政编码, 发件人姓名, " "发件人电话, 发件人地址, 发件地邮编, 注册地址, 运单号, 个人姓名, " "纳税人识别号, 注册电话, 电子邮件, 获取时间 " ") values (" ":OrderID, :OrderType, :MerchantOrderID, :OrderDate, :SOStatusCode, " ":TradeType, :AuditTime, :SOOutStockTime, :ProductAmount, :ShippingAmount, " ":TaxAmount, :CommissionAmount, :PayTypeSysNo, :PaySerialNumber, :PayStatusCode, " ":ReceiveName, :ReceivePhone, :ReceiveAddress, :ReceiveZip, :SenderName, " ":SenderTel, :SenderAddr, :SenderZip, :ReceiveAreaName, :TrackingNumber, :Name, " ":IDCardNumber, :PhoneNumber, :Email, :GetTime " ")")); /// 订单号规则 /// 01(表示主订单) + 两位随机数 + 当前时间的日(两位) + 当前时间的月+70(两位) + 四位随机数 QString orderNumber = QString("%1%2%3%4%5") .arg("01") .arg(QString::number(qrand() % 100), 2, '0') .arg(QDate::currentDate().toString("dd")) .arg(QString::number(QDate::currentDate().month() + 70)) .arg(QString::number(qrand() % 10000), 4, '0'); query.bindValue(":OrderID", orderNumber); query.bindValue(":OrderType", "kjt"); // 固定为 kjt query.bindValue(":MerchantOrderID", orderId); query.bindValue(":OrderDate", orderDate); query.bindValue(":SOStatusCode", sOStatusCode); query.bindValue(":TradeType", tradeType); query.bindValue(":AuditTime", auditTime); query.bindValue(":SOOutStockTime", sOOutStockTime); query.bindValue(":ProductAmount", productAmount); query.bindValue(":ShippingAmount", shippingAmount); query.bindValue(":TaxAmount", taxAmount); query.bindValue(":CommissionAmount", commissionAmount); query.bindValue(":PayTypeSysNo", payTypeSysNo); query.bindValue(":PaySerialNumber", paySerialNumber.isNull() ? "" : paySerialNumber); query.bindValue(":PayStatusCode", payStatusCode); query.bindValue(":ReceiveName", receiveName); query.bindValue(":ReceivePhone", receivePhone.isNull() ? "" : receivePhone); query.bindValue(":ReceiveAddress", receiveAddress); query.bindValue(":ReceiveZip", receiveZip); query.bindValue(":ReceiveAreaName", receiveAreaName.isNull() ? "" : receiveAreaName); query.bindValue(":SenderName", senderName.isNull() ? "" : senderName); query.bindValue(":SenderTel", senderTel.isNull() ? "" : senderTel); query.bindValue(":SenderAddr", senderAddr.isNull() ? "" : senderAddr); query.bindValue(":SenderZip", senderZip.isNull() ? "" : senderZip); query.bindValue(":TrackingNumber", trackingNumber.isNull() ? "" : trackingNumber); query.bindValue(":Name", name); query.bindValue(":IDCardNumber", iDCardNumber); query.bindValue(":PhoneNumber", phoneNumber.isNull() ? "" : phoneNumber); query.bindValue(":Email", email); query.bindValue(":GetTime", QDateTime::currentDateTime()); // 同步时间为当前时间 if (!query.exec()) { // qFatal(query.lastError().text().toStdString().c_str()); qInfo() << query.lastError().text(); _ohData._success = false; } else { /// 插入订单商品数据 int parentId = query.lastInsertId().toInt(); // 订单id if (parentId > 0) { QSqlQuery queryItemInfo; foreach (SOItemInfo sOitemInfo, sOItemInfoList) { queryItemInfo.prepare(tr("insert into 订单商品 (" "订单id, 商品名称, 商品编号, 购买数量, 销售单价, " "税金 " ") values (" ":OrderId, :ProductName, :ProductID, :Quantity, :ProductPrice, " ":TaxPrice " ")")); queryItemInfo.bindValue(":OrderId", parentId); queryItemInfo.bindValue(":ProductName", sOitemInfo._productName.isNull() ? "" : sOitemInfo._productName); queryItemInfo.bindValue(":ProductID", sOitemInfo._productId.isNull() ? "" : sOitemInfo._productId); queryItemInfo.bindValue(":Quantity", sOitemInfo._quantity); queryItemInfo.bindValue(":ProductPrice", sOitemInfo._productPrice); queryItemInfo.bindValue(":TaxPrice", sOitemInfo._taxPrice); if (!queryItemInfo.exec()) { qInfo() << queryItemInfo.lastError().text(); _ohData._success = false; } } }
void Selection::doSelection(QList<Individual *> population2p, int matches, NormativeGrid *nGrid) { qDebug("Selection::doSelection"); selectedPopulation.clear(); outOfGridList.clear(); // lista de adversarios de tamano matches QList<Individual *> adversaryList; int randomIndex = 0; Individual * selectedIndividual; Individual * adversary; int i = 0; //for (int i=0; i<population2p; i++) while( i < population2p.count()) { // seleccionar individuo selectedIndividual = population2p.at(i); // escoger matches individuos aletorios y agregarlos a la lista de adversarios while( adversaryList.count() < matches) { // obtener un indice aleatorio de un individuo dentro de population2p randomIndex = getRandom(population2p.count()-1); // se selecciono el indice del mismo inviduo por lo tanto se escoge otro if (randomIndex == i) { continue; } adversary = population2p.at(randomIndex); adversaryList.append(adversary); } // ejecutar los torneos del individuo contra los adversarios makeTournaments(i, selectedIndividual, adversaryList, nGrid); // incrementar el valor de i i++; adversaryList.clear(); } // fin de los torneos // ordenar la poblacion2p con respecto al contador de encuentros ganados en torneo de menor a mayor qSort(population2p.begin(), population2p.end(), xLessThanWonMatchesCounter); // agregar los P individuos con mayores valores de victorias a la lista de la poblacion // seleccionada selectedPopulation // // evaluar cada individuo de la poblacion seleccionada o hacer fuera en la clase Simulation // TODO int halfPopulation = population2p.count()/2; for (int k=population2p.count()-1; k > (halfPopulation)-1; k--) { //qDebug("indice %d", indexToInsertInPopulation.at(k)); selectedPopulation.append(population2p.at(k)); } qDebug("TAMANO DE LA POBLACION SELECCIONADA DESPUES DE LOS TORNEOS: %d", selectedPopulation.count()); /* // contenedor auxiliar para realizar la seleccion de los P individuos con mas victorias QMultiMap<int, int> auxiliaryMap; QMapIterator<int, int> iterator1(tournamentsWinners); while (iterator1.hasNext()) { iterator1.next(); auxiliaryMap.insert(iterator1.value(), iterator1.key()); //swap value and key } // ---------------------------- // impresion de prueba /* QMap<int, int>::iterator it = tournamentsWinners.begin(); while (it != tournamentsWinners.end()) { qDebug(" index %d value %d", it.key(), it.value() ); ++it; } */ // ---------------------------- // ---------------------------- // impresion de prueba /* QMap<int, int>::iterator it3 = auxiliaryMap.begin(); while (it3 != auxiliaryMap.end()) { qDebug(" value %d index %d", it3.key(), it3.value() ); ++it3; } */ // ---------------------------- /* QList<int> indexToInsertInPopulation = auxiliaryMap.values(); for (int k=indexToInsertInPopulation.count()-1; k > (indexToInsertInPopulation.count()/2)-1; k--) { //qDebug("indice %d", indexToInsertInPopulation.at(k)); selectedPopulation.append(population2p.at(k)); } */ // evaluar cada individuo de la poblacion seleccionada o hacer fuera en la clase Simulation // TODO qDebug("Tamano de la lista de individuos que cayeron fuera de la rejilla: %d", outOfGridList.count()); }
void BookmarksManager::load() { if (m_loaded) return; m_loaded = true; QString dir = QDesktopServices::storageLocation(QDesktopServices::DataLocation); QString bookmarkFile = dir + QLatin1String("/bookmarks.xbel"); if (!QFile::exists(bookmarkFile)) bookmarkFile = QLatin1String(":defaultbookmarks.xbel"); XbelReader reader; m_bookmarkRootNode = reader.read(bookmarkFile); if (reader.error() != QXmlStreamReader::NoError) { QMessageBox::warning(0, QLatin1String("Loading Bookmark"), tr("Error when loading bookmarks on line %1, column %2:\n" "%3").arg(reader.lineNumber()).arg(reader.columnNumber()).arg(reader.errorString())); } BookmarkNode *toolbar = 0; BookmarkNode *menu = 0; QList<BookmarkNode*> others; for (int i = m_bookmarkRootNode->children().count() - 1; i >= 0; --i) { BookmarkNode *node = m_bookmarkRootNode->children().at(i); if (node->type() == BookmarkNode::Folder) { // Automatically convert if (node->title == tr("Toolbar Bookmarks") && !toolbar) { node->title = tr(BOOKMARKBAR); } if (node->title == tr(BOOKMARKBAR) && !toolbar) { toolbar = node; } // Automatically convert if (node->title == tr("Menu") && !menu) { node->title = tr(BOOKMARKMENU); } if (node->title == tr(BOOKMARKMENU) && !menu) { menu = node; } } else { others.append(node); } m_bookmarkRootNode->remove(node); } Q_ASSERT(m_bookmarkRootNode->children().count() == 0); if (!toolbar) { toolbar = new BookmarkNode(BookmarkNode::Folder, m_bookmarkRootNode); toolbar->title = tr(BOOKMARKBAR); } else { m_bookmarkRootNode->add(toolbar); } if (!menu) { menu = new BookmarkNode(BookmarkNode::Folder, m_bookmarkRootNode); menu->title = tr(BOOKMARKMENU); } else { m_bookmarkRootNode->add(menu); } for (int i = 0; i < others.count(); ++i) menu->add(others.at(i)); }
Spectr* AddSpectr::AddSpectrFromSpectralLib(QString filePath, HyperCube* cube) { QStringList possibleTitles; possibleTitles.append("Name:"); possibleTitles.append("Type:"); possibleTitles.append("Class:"); possibleTitles.append("Subclass:"); possibleTitles.append("Particle Size:"); possibleTitles.append("Sample No.:"); possibleTitles.append("Owner:"); possibleTitles.append("Wavelength Range:"); possibleTitles.append("Origin:"); possibleTitles.append("Description:"); possibleTitles.append("Geologic age:"); possibleTitles.append("Measurement:"); possibleTitles.append("First Column:"); possibleTitles.append("Second Column:"); possibleTitles.append("X Units:"); possibleTitles.append("Y Units:"); possibleTitles.append("First X Value:"); possibleTitles.append("Last X Value:"); possibleTitles.append("Number of X Values:"); possibleTitles.append("Additional Information:"); QFile fileIn(filePath); QTextStream* m_inStream = new QTextStream(&fileIn); m_inStream->setCodec(QTextCodec::codecForName("Windows-1251")); Spectr* spectr; QString err; try { if (!fileIn.open(QIODevice::ReadOnly)) { throw GenericExc("Невозможно открыть файл!"); } QList<QString> item; QVector<double> xUnits; QVector<double> yUnits; QString title, description; DescriptionSpectr descriptionItem; QList<DescriptionSpectr> spectrDescription; // Алгоритм предусматривает, что titles может идти не по порядку. Но нужно как-то разграничивать описание от данных // Поэтому смотрим по последнему элементу в possibleTitles; bool flagEndDescription = false; bool startData = false; // костыль, чтобы отличать класс от подкласса // bool classTitle = false; u::uint32 multiplier = 1; while (!m_inStream->atEnd()) { QString line = m_inStream->readLine(); if (line.compare("\r\n") == 0 || line.compare("") == 0 || line.compare(" ") == 0 || line.compare("\n") == 0){ if (flagEndDescription) { // Закидываем последний //m_attr->SetDescriptionItem(title, description); descriptionItem.title = title; descriptionItem.description = description; spectrDescription.push_back(descriptionItem); item.clear(); title.clear(); description.clear(); startData = true; flagEndDescription = false; } continue; } if (!startData) { bool contains = false; for (int i = 0; i < possibleTitles.size(); i++) { if (line.contains(possibleTitles.at(i), Qt::CaseInsensitive)) { if (line.contains("micrometers", Qt::CaseInsensitive) && line.contains("X Units",Qt::CaseInsensitive)) { multiplier = 1000; } if (line.at(0) != possibleTitles.at(i)[0]) { i++; } // закинуть предыдущие и начать новые if (i == possibleTitles.size()-1) { flagEndDescription = true; } if (!title.isEmpty()) { descriptionItem.title = title; descriptionItem.description = description; spectrDescription.push_back(descriptionItem); item.clear(); title.clear(); description.clear(); } item = line.split(possibleTitles.at(i), QString::KeepEmptyParts, Qt::CaseInsensitive ); title = possibleTitles.at(i); if (item.size() >= 2) { description = item.at(1); } else { description = ""; } contains = true; break; } } if (!contains) { description.append(" ").append(line); } } else { item = line.split("\t"); QList<QString> data; for (int i = 0; i < item.size(); i++) { QList<QString> it = item.at(i).split(" "); data.append(it); } for (int i = 0; i < data.size(); i++) { if (data.at(i) == "\t" || data.at(i) == "\n" || data.at(i) == " " || data.at(i) == "") { data.removeAt(i); i--; } } if (data.size() != 2) { throw GenericExc(QObject::tr("Неизвестный формат данных")); } else { double x = data.at(0).toDouble()*multiplier; double y = data.at(1).toDouble(); xUnits.push_back(x); yUnits.push_back(y); } } } fileIn.close(); // проверка на наличие данных if (xUnits.size() == 0) { throw GenericExc(QObject::tr("Неизвестный формат данных")); } else if (yUnits.size() == 0) { throw GenericExc(QObject::tr("Неизвестный формат данных")); } else if (xUnits.size() != yUnits.size()) { throw GenericExc(QObject::tr("Неизвестный формат данных")); } // в некоторых внешних библиотеках длины волн не сортированы по убыванию for (int i = 0; i < xUnits.size(); i++) { bool swapped = false; for (int j = 0; j < xUnits.size() -1; j++) { if (xUnits[j] > xUnits[j+1]) { double x = xUnits[j]; double y = yUnits[j]; xUnits[j] = xUnits[j+1]; yUnits[j] = yUnits[j+1]; xUnits[j+1] = x; yUnits[j+1] = y; swapped = true; } } } //QMessageBox::information(NULL, "Информация о спектре", toMessageBox); Measurements measurement = Unknown_measurement; for (int i = 0; i < spectrDescription.size(); i++) { if (spectrDescription.at(i).title.contains("Name", Qt::CaseInsensitive)) { title = spectrDescription.at(i).description; } else if (spectrDescription.at(i).title.contains("Y Units", Qt::CaseInsensitive)) { // пробуем определить в чем измеряются величины y if (spectrDescription.at(i).description.contains("Reflectance", Qt::CaseInsensitive)) { // определяем в % или в долях единиц if (spectrDescription.at(i).description.contains("percent", Qt::CaseInsensitive) ) { measurement = RFL_percent; } else { measurement = RFL_units; } } else if (spectrDescription.at(i).description.contains("Коэф. спектральной яркости", Qt::CaseInsensitive)) { measurement = RFL_units; } } } if (measurement == -1) { // неизвестный тип данных. Запрашиваем у пользователя // нужно сделать окно. } spectr = new Spectr(cube, xUnits, yUnits, title, measurement, spectrDescription); } catch (const GenericExc& exc) { err = exc.GetWhat(); } catch (...) { err = QObject::tr("Неизвестная ошибка"); } if (!err.isEmpty()) { return NULL; } return spectr; }
void MemoryMetaData::loadMetaDataFromFile(QString filestr) { qDebug() << "Loading config file from:" << filestr; QFile file(filestr); file.open(QIODevice::ReadOnly); QByteArray filebytes = file.readAll(); file.close(); QJson::Parser parser; QVariant top = parser.parse(filebytes); if (!top.isValid()) { QString errormsg = QString("Error parsing JSON from config file on line number: ") + QString::number(parser.errorLine()) + " error text: " + parser.errorString(); //QMessageBox::information(0,"Error",errormsg); qDebug() << "Error parsing JSON"; qDebug() << "Line number:" << parser.errorLine() << "error text:" << parser.errorString(); return; } QVariantMap topmap = top.toMap(); QVariantMap errormap = topmap["errormap"].toMap(); QVariantMap::iterator i = errormap.begin(); while (i != errormap.end()) { bool ok = false; m_errorMap[i.value().toString().mid(2).toInt(&ok,16)] = i.key(); i++; } QVariantMap ramvars = topmap["ramvars"].toMap(); i = ramvars.begin(); while (i != ramvars.end()) { bool ok = false; unsigned short locid = i.key().mid(2).toInt(&ok,16); m_readOnlyMetaDataMap[locid] = ReadOnlyRamBlock(); QVariantMap locidlist = i.value().toMap(); QString title = locidlist["title"].toString(); m_readOnlyMetaDataMap[locid].title = title; QVariantList locidmap = locidlist["vars"].toList(); int offset = 0; for (int j=0;j<locidmap.size();j++) { QVariantMap newlocidmap = locidmap[j].toMap(); ReadOnlyRamData rdata; rdata.dataTitle = newlocidmap["name"].toString(); rdata.dataDescription = newlocidmap["title"].toString(); rdata.locationId = locid; rdata.offset = offset; rdata.size = newlocidmap["size"].toInt(); offset += rdata.size; m_readOnlyMetaDataMap[locid].m_ramData.append(rdata); m_readOnlyMetaData.append(rdata); //m_readOnlyMetaDataMap[locid].append(rdata); } /*QVariantMap::iterator j = locidmap.begin(); while (j != locidmap.end()) { if (j.key() == "title") { QString title = j.value().toString(); qDebug() << "Location title:" << title; } else { qDebug() << j.key(); QVariantMap valuemap = j.value().toMap(); if (valuemap.contains("type")) { ConfigData cdata; cdata.configDescription = valuemap["title"].toString(); cdata.configTitle = j.key(); cdata.elementSize = valuemap["size"].toInt(); cdata.locationId = locid; cdata.offset = valuemap["offset"].toInt(); cdata.type = valuemap["type"].toString(); QVariantMap calcmap = valuemap["calc"].toMap(); QList<QPair<QString,double> > calclist; QVariantMap::iterator k = calcmap.begin(); while (k != calcmap.end()) { calclist.append(QPair<QString,double>(k.key(),k.value().toDouble())); k++; } cdata.elementCalc = calclist; if (valuemap["type"] == "value") { } else if (valuemap["type"] == "array") { cdata.arraySize = valuemap["arraysize"].toInt(); } m_configMetaData.append(cdata); } } j++; }*/ i++; } qDebug() << m_readOnlyMetaData.size() << "Ram entries found"; QVariantMap tables = topmap["tables"].toMap(); i = tables.begin(); while (i != tables.end()) { QVariantMap tabledata = i.value().toMap(); if (tabledata["type"] == "3D") { Table3DMetaData meta; QString id = tabledata["locationid"].toString(); QString xtitle = tabledata["xtitle"].toString(); QVariantList xcalc = tabledata["xcalc"].toList(); QString xdp = tabledata["xdp"].toString(); unsigned int size = tabledata["size"].toInt(); QString ytitle = tabledata["ytitle"].toString(); QVariantList ycalc = tabledata["ycalc"].toList(); QString ydp = tabledata["ydp"].toString(); QString ztitle = tabledata["ztitle"].toString(); QVariantList zcalc = tabledata["zcalc"].toList(); QString zdp = tabledata["zdp"].toString(); //QVariantMap::iterator calci = xcalc.begin(); QList<QPair<QString,double> > xcalclist; QList<QPair<QString,double> > ycalclist; QList<QPair<QString,double> > zcalclist; for (int j=0;j<xcalc.size();j++) { qDebug() << "XCalc:" << xcalc[j].toMap()["type"].toString() << xcalc[j].toMap()["value"].toDouble(); xcalclist.append(QPair<QString,double>(xcalc[j].toMap()["type"].toString(),xcalc[j].toMap()["value"].toDouble())); } for (int j=0;j<ycalc.size();j++) { ycalclist.append(QPair<QString,double>(ycalc[j].toMap()["type"].toString(),ycalc[j].toMap()["value"].toDouble())); } for (int j=0;j<zcalc.size();j++) { zcalclist.append(QPair<QString,double>(zcalc[j].toMap()["type"].toString(),zcalc[j].toMap()["value"].toDouble())); } bool ok = false; meta.locationId = id.mid(2).toInt(&ok,16); meta.tableTitle = i.key(); meta.xAxisCalc = xcalclist; meta.xAxisTitle = xtitle; meta.xDp = xdp.toInt(); meta.yAxisCalc = ycalclist; meta.yAxisTitle = ytitle; meta.yDp = ydp.toInt(); meta.zAxisCalc = zcalclist; meta.zAxisTitle = ztitle; meta.zDp = zdp.toInt(); meta.size = size; meta.valid = true; m_table3DMetaData.append(meta); } else if (tabledata["type"] == "2D") { Table2DMetaData meta; QString id = tabledata["locationid"].toString(); QString xtitle = tabledata["xtitle"].toString(); QVariantList xcalc = tabledata["xcalc"].toList(); QString xdp = tabledata["xdp"].toString(); QString ytitle = tabledata["ytitle"].toString(); QVariantList ycalc = tabledata["ycalc"].toList(); QString ydp = tabledata["ydp"].toString(); unsigned int size = tabledata["size"].toInt(); QList<QPair<QString,double> > xcalclist; QList<QPair<QString,double> > ycalclist; for (int j=0;j<xcalc.size();j++) { qDebug() << "XCalc:" << xcalc[j].toMap()["type"].toString() << xcalc[j].toMap()["value"].toDouble(); xcalclist.append(QPair<QString,double>(xcalc[j].toMap()["type"].toString(),xcalc[j].toMap()["value"].toDouble())); } for (int j=0;j<ycalc.size();j++) { ycalclist.append(QPair<QString,double>(ycalc[j].toMap()["type"].toString(),ycalc[j].toMap()["value"].toDouble())); } bool ok = false; meta.locationId = id.mid(2).toInt(&ok,16); meta.tableTitle = i.key(); meta.xAxisCalc = xcalclist; meta.xAxisTitle = xtitle; meta.xDp = xdp.toInt(); meta.yAxisCalc = ycalclist; meta.yAxisTitle = ytitle; meta.yDp = ydp.toInt(); meta.size = size; meta.valid = true; m_table2DMetaData.append(meta); } i++; } }
QList<MetaPaket> DB_QMDB_SQL::getTracksFromQuick(int y1, int y2, uint t, int p, bool br) { QList<MetaPaket> list; MetaPaket metaPaket; QDateTime dateTime = QDateTime::currentDateTime(); dateTime = dateTime.addMonths(-3); QString coverUrl; QString album; QString interpret; QString queryString ("SELECT pfad, title, tracknr, t_artist.name, t_album.name, t_year.name, " "wertung, gespielt, erfasst FROM t_title " "INNER JOIN t_artist ON t_title.artist = t_artist.id " "INNER JOIN t_album ON t_title.album = t_album.id " "INNER JOIN t_year ON t_title.year = t_year.id "); QString stringWhere = ""; QString stringAnd = ""; bool boolWhere = false; if(y1 && y2) { stringWhere = QString("WHERE t_year.name > '%1' ").arg(y1); boolWhere = true; stringAnd = QString("AND t_year.name < '%1' ").arg(y2); } if(t) { if(boolWhere) { stringAnd = stringAnd + QString("AND t_title.erfasst > " + QString("%1").arg(t) + " "); } else { stringWhere = QString("WHERE t_title.erfasst > " + QString("%1").arg(t) + " "); boolWhere = true; } } if(p) { if(boolWhere) { stringAnd = stringAnd + QString("AND t_title.wertung > " + QString("%1").arg(p) + " "); } else { stringWhere = QString("WHERE t_title.wertung > " + QString("%1").arg(p) + " "); boolWhere = true; } } if(br) { queryString = queryString + " WHERE t_title.gespielt < " + QString("%1").arg(dateTime.toTime_t()) + " ORDER BY RAND() LIMIT 50" ; } else { queryString = queryString + stringWhere + stringAnd; } qDebug() << queryString; QSqlQuery query(db); query.exec(queryString); while(query.next()) { metaPaket.isEmpty = false; metaPaket.url = query.value(0).toString(); metaPaket.title = query.value(1).toString(); metaPaket.interpret = query.value(3).toString(); metaPaket.album = query.value(4).toString(); metaPaket.coverUrl = getCoverPath(metaPaket.interpret, metaPaket.album); metaPaket.points = query.value(6).toInt(); metaPaket.lastPlayed = query.value(7).toUInt();; list.append(metaPaket); } return list; }
QList<BasicDrawObj*> Capella::readCapxDrawObjectArray(XmlReader& e) { QList<BasicDrawObj*> ol; while (e.readNextStartElement()) { if (e.name() == "drawObj") { BasicDrawObj* bdo = 0; while (e.readNextStartElement()) { const QStringRef& tag(e.name()); if (tag == "basic") { // note: the <basic> element always follows the DrawObject it applies to if (bdo) bdo->readCapx(e); else e.skipCurrentElement(); } else if (tag == "line") { qDebug("readCapxDrawObjectArray: found line (skipping)"); e.skipCurrentElement(); } else if (tag == "rectangle") { qDebug("readCapxDrawObjectArray: found rectangle (skipping)"); e.skipCurrentElement(); } else if (tag == "ellipse") { qDebug("readCapxDrawObjectArray: found ellipse (skipping)"); e.skipCurrentElement(); } else if (tag == "polygon") { qDebug("readCapxDrawObjectArray: found polygon (skipping)"); e.skipCurrentElement(); } else if (tag == "metafile") { qDebug("readCapxDrawObjectArray: found metafile (skipping)"); e.skipCurrentElement(); } else if (tag == "text") { SimpleTextObj* o = new SimpleTextObj(this); bdo = o; // save o to handle the "basic" tag (which sometimes follows) o->readCapx(e); ol.append(o); } else if (tag == "richText") { qDebug("readCapxDrawObjectArray: found richText (skipping)"); e.skipCurrentElement(); } else if (tag == "guitar") { qDebug("readCapxDrawObjectArray: found guitar (skipping)"); e.skipCurrentElement(); } else if (tag == "slur") { SlurObj* o = new SlurObj(this); bdo = o; // save o to handle the "basic" tag (which sometimes follows) o->readCapx(e); ol.append(o); } else if (tag == "wavyLine") { qDebug("readCapxDrawObjectArray: found wavyLine (skipping)"); e.skipCurrentElement(); } else if (tag == "bracket") { qDebug("readCapxDrawObjectArray: found bracket (skipping)"); e.skipCurrentElement(); } else if (tag == "wedge") { qDebug("readCapxDrawObjectArray: found wedge (skipping)"); e.skipCurrentElement(); } else if (tag == "notelines") { qDebug("readCapxDrawObjectArray: found notelines (skipping)"); e.skipCurrentElement(); } else if (tag == "volta") { VoltaObj* o = new VoltaObj(this); bdo = o; // save o to handle the "basic" tag (which sometimes follows) o->readCapx(e); ol.append(o); } else if (tag == "trill") { qDebug("readCapxDrawObjectArray: found trill (skipping)"); e.skipCurrentElement(); } else if (tag == "transposable") { qDebug("readCapxDrawObjectArray: found transposable (skipping)"); e.skipCurrentElement(); } else if (tag == "group") { qDebug("readCapxDrawObjectArray: found group (skipping)"); e.skipCurrentElement(); } else e.unknown(); } } else e.unknown(); } return ol; }
std::string InchiLineFormat::write(const chemkit::Molecule *molecule) { // check for valid molecule if(molecule->atomCount() > 1024){ setErrorString("InChI does not support molecules with more that 1024 atoms."); return std::string(); } // setup inchi input structure inchi_Input input; input.atom = new inchi_Atom[molecule->atomCount()]; input.stereo0D = 0; input.szOptions = 0; input.num_atoms = molecule->atomCount(); input.num_stereo0D = 0; inchi_Atom *inputAtom = &input.atom[0]; QList<const chemkit::Atom *> chiralAtoms; foreach(const chemkit::Atom *atom, molecule->atoms()){ // coordinates inputAtom->x = 0; inputAtom->y = 0; inputAtom->z = 0; // bonds and neighbors int neighborCount = 0; foreach(const chemkit::Bond *bond, atom->bonds()){ const chemkit::Atom *neighbor = bond->otherAtom(atom); if(neighbor->index() < atom->index()) continue; inputAtom->neighbor[neighborCount] = neighbor->index(); inputAtom->bond_type[neighborCount] = bond->order(); inputAtom->bond_stereo[neighborCount] = INCHI_BOND_STEREO_NONE; neighborCount++; } inputAtom->num_bonds = neighborCount; // element symbol strncpy(inputAtom->elname, atom->symbol().c_str(), ATOM_EL_LEN); // isotopic hydrogens inputAtom->num_iso_H[0] = -1; inputAtom->num_iso_H[1] = 0; inputAtom->num_iso_H[2] = 0; inputAtom->num_iso_H[3] = 0; // misc data inputAtom->isotopic_mass = 0; inputAtom->radical = 0; inputAtom->charge = 0; // chiral atoms if(atom->isChiral()){ chiralAtoms.append(atom); } // move pointer to the next position in the atom array inputAtom++; } // add stereochemistry if enabled bool stereochemistry = option("stereochemistry").toBool(); if(stereochemistry){ input.stereo0D = new inchi_Stereo0D[chiralAtoms.size()]; input.num_stereo0D = chiralAtoms.size(); int chiralIndex = 0; foreach(const chemkit::Atom *atom, chiralAtoms){ inchi_Stereo0D *stereo = &input.stereo0D[chiralIndex]; qMemSet(stereo, 0, sizeof(*stereo)); stereo->central_atom = atom->index(); int neighborIndex = 0; foreach(const chemkit::Atom *neighbor, atom->neighbors()){ stereo->neighbor[neighborIndex++] = neighbor->index(); } stereo->type = INCHI_StereoType_Tetrahedral; if(atom->chirality() == chemkit::Atom::R){ stereo->parity = INCHI_PARITY_EVEN; } else if(atom->chirality() == chemkit::Atom::S){ stereo->parity = INCHI_PARITY_ODD; } else if(atom->chirality() == chemkit::Atom::UnspecifiedChirality){ stereo->parity = INCHI_PARITY_UNDEFINED; } else{ stereo->parity = INCHI_PARITY_UNKNOWN; } chiralIndex++; } }
void SendCoinsDialog::on_sendButton_clicked() { if(!model || !model->getOptionsModel()) return; QList<SendCoinsRecipient> recipients; bool valid = true; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { // generate bold amount string QString amount = "<b>" + BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount); amount.append("</b>"); // generate monospace address string QString address = "<span style='font-family: monospace;'>" + rcp.address; address.append("</span>"); QString recipientElement; if (!rcp.paymentRequest.IsInitialized()) // normal payment { if(rcp.label.length() > 0) // label with address { recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.label)); recipientElement.append(QString(" (%1)").arg(address)); } else // just address { recipientElement = tr("%1 to %2").arg(amount, address); } } else if(!rcp.authenticatedMerchant.isEmpty()) // secure payment request { recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.authenticatedMerchant)); } else // insecure payment request { recipientElement = tr("%1 to %2").arg(amount, address); } formatted.append(recipientElement); }
QModelIndex ZealListModel::index(int row, int column, const QModelIndex &parent) const { if(!parent.isValid()) { if(row >= docsets->count() || row == -1) return QModelIndex(); if(column == 0) { return createIndex(row, column, (void*)getString(docsets->names().at(row))); } else if(column == 1) { QDir dir(docsets->dir(docsets->names().at(row))); if(QFile(dir.absoluteFilePath("index.html")).exists()) { return createIndex(row, column, (void*)getString(dir.absoluteFilePath("index.html"))); } else { // retrieve index file name from Info.plist for Dash docsets dir.cd("Contents"); QFile file(dir.absoluteFilePath("Info.plist")); QDomDocument infoplist("infoplist"); if(!file.open(QIODevice::ReadOnly)) { return createIndex(row, column, (void*)getString("")); } if(!infoplist.setContent(&file)) { file.close(); return createIndex(row, column, (void*)getString("")); } auto keys = infoplist.elementsByTagName("key"); for(int i = 0; i < keys.count(); ++i) { auto key = keys.at(i); if(key.firstChild().nodeValue() == "dashIndexFilePath") { auto path = key.nextSibling().firstChild().nodeValue().split("/"); auto filename = path.last(); path.removeLast(); dir.cd("Resources"); dir.cd("Documents"); for(auto directory : path) { if(!dir.cd(directory)) { return createIndex(row, column, (void*)getString("")); } } return createIndex(row, column, (void*)getString(dir.absoluteFilePath(filename))); } } // fallback to index.html dir.cd("Resources"); dir.cd("Documents"); return createIndex(row, column, (void*)getString(dir.absoluteFilePath("index.html"))); } } return QModelIndex(); } else { QString docsetName; for(auto name : docsets->names()) { if(i2s(parent)->startsWith(name+"/")) { docsetName = name; } } if(docsetName.isEmpty()) { // i2s(parent) == docsetName if(column == 0) { QList<QString> types; for(auto &pair : getModulesCounts().keys()) { if(pair.first == *i2s(parent)) { types.append(pair.second); } } qSort(types); return createIndex(row, column, (void*)getString(*i2s(parent)+"/"+pluralize(types[row]))); } } else { auto type = singularize(i2s(parent)->split('/')[1]); if(row >= getModulesCounts()[QPair<QString, QString>(docsetName, type)]) return QModelIndex(); if(column == 0) { return createIndex(row, column, (void*)getString(QString("%1/%2/%3").arg(docsetName, pluralize(type), getItem(*i2s(parent), row).first))); } else if(column == 1) { return createIndex(row, column, (void*)getString(getItem(*i2s(parent), row).second)); } } return QModelIndex(); } }
void GLSLTextEditorWidget::updateDocumentNow() { m_updateDocumentTimer->stop(); int variant = languageVariant(mimeType()); const QString contents = toPlainText(); // get the code from the editor const QByteArray preprocessedCode = contents.toLatin1(); // ### use the QtCreator C++ preprocessor. Document::Ptr doc(new Document()); GLSL::Engine *engine = new GLSL::Engine(); doc->_engine = new GLSL::Engine(); Parser parser(doc->_engine, preprocessedCode.constData(), preprocessedCode.size(), variant); TranslationUnitAST *ast = parser.parse(); if (ast != 0 || extraSelections(CodeWarningsSelection).isEmpty()) { GLSLEditorPlugin *plugin = GLSLEditorPlugin::instance(); Semantic sem; Scope *globalScope = engine->newNamespace(); doc->_globalScope = globalScope; sem.translationUnit(plugin->shaderInit(variant)->ast, globalScope, plugin->shaderInit(variant)->engine); if (variant & Lexer::Variant_VertexShader) sem.translationUnit(plugin->vertexShaderInit(variant)->ast, globalScope, plugin->vertexShaderInit(variant)->engine); if (variant & Lexer::Variant_FragmentShader) sem.translationUnit(plugin->fragmentShaderInit(variant)->ast, globalScope, plugin->fragmentShaderInit(variant)->engine); sem.translationUnit(ast, globalScope, engine); CreateRanges createRanges(document(), doc); createRanges(ast); QTextCharFormat errorFormat; errorFormat.setUnderlineStyle(QTextCharFormat::WaveUnderline); errorFormat.setUnderlineColor(Qt::red); QTextCharFormat warningFormat; warningFormat.setUnderlineStyle(QTextCharFormat::WaveUnderline); warningFormat.setUnderlineColor(Qt::darkYellow); QList<QTextEdit::ExtraSelection> sels; QSet<int> errors; foreach (const DiagnosticMessage &m, engine->diagnosticMessages()) { if (! m.line()) continue; else if (errors.contains(m.line())) continue; errors.insert(m.line()); QTextCursor cursor(document()->findBlockByNumber(m.line() - 1)); cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); QTextEdit::ExtraSelection sel; sel.cursor = cursor; sel.format = m.isError() ? errorFormat : warningFormat; sel.format.setToolTip(m.message()); sels.append(sel); } setExtraSelections(CodeWarningsSelection, sels); m_glslDocument = doc; }
/* * Decompose CWallet transaction to model transaction records. */ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx) { QList<TransactionRecord> parts; int64_t nTime = wtx.GetTxTime(); CAmount nCredit = wtx.GetCredit(ISMINE_ALL); CAmount nDebit = wtx.GetDebit(ISMINE_ALL); CAmount nNet = nCredit - nDebit; uint256 hash = wtx.GetHash(); std::map<std::string, std::string> mapValue = wtx.mapValue; uint32_t version = wtx.tx->nVersion; if (nNet > 0 || wtx.IsCoinBase()) { // // Credit // for(unsigned int i = 0; i < wtx.tx->vout.size(); i++) { const CTxOut& txout = wtx.tx->vout[i]; isminetype mine = wallet->IsMine(txout); if(mine) { TransactionRecord sub(hash, nTime); CTxDestination address; sub.idx = i; // vout index sub.credit = txout.nValue; sub.version = version; sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address)) { // Received by Bitcoin Address sub.type = TransactionRecord::RecvWithAddress; sub.address = CBitcoinAddress(address).ToString(); } else { // Received by IP connection (deprecated features), or a multisignature or other non-simple transaction sub.type = TransactionRecord::RecvFromOther; sub.address = mapValue["from"]; } if (wtx.IsCoinBase()) { // Generated sub.type = TransactionRecord::Generated; } parts.append(sub); } } } else { bool involvesWatchAddress = false; isminetype fAllFromMe = ISMINE_SPENDABLE; for (const CTxIn& txin : wtx.tx->vin) { isminetype mine = wallet->IsMine(txin); if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true; if(fAllFromMe > mine) fAllFromMe = mine; } isminetype fAllToMe = ISMINE_SPENDABLE; for (const CTxOut& txout : wtx.tx->vout) { isminetype mine = wallet->IsMine(txout); if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true; if(fAllToMe > mine) fAllToMe = mine; } if (fAllFromMe && fAllToMe) { // Payment to self CAmount nChange = wtx.GetChange(); parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, "", version, -(nDebit - nChange), nCredit - nChange)); parts.last().involvesWatchAddress = involvesWatchAddress; // maybe pass to TransactionRecord as constructor argument } else if (fAllFromMe) { // // Debit // CAmount nTxFee = nDebit - wtx.tx->GetValueOut(); for (unsigned int nOut = 0; nOut < wtx.tx->vout.size(); nOut++) { const CTxOut& txout = wtx.tx->vout[nOut]; TransactionRecord sub(hash, nTime); sub.idx = nOut; sub.involvesWatchAddress = involvesWatchAddress; sub.version = version; if(wallet->IsMine(txout)) { // Ignore parts sent to self, as this is usually the change // from a transaction sent back to our own address. continue; } CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address)) { // Sent to Bitcoin Address sub.type = TransactionRecord::SendToAddress; sub.address = CBitcoinAddress(address).ToString(); } else { // Sent to IP, or other non-address transaction like OP_EVAL sub.type = TransactionRecord::SendToOther; sub.address = mapValue["to"]; } CAmount nValue = txout.nValue; /* Add fee to first output */ if (nTxFee > 0) { nValue += nTxFee; nTxFee = 0; } sub.debit = -nValue; parts.append(sub); } } else { // // Mixed debit transaction, can't break down payees // parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0)); parts.last().involvesWatchAddress = involvesWatchAddress; } } return parts; }
QVariant PropertyConstraintListItem::value(const App::Property* prop) const { assert(prop && prop->getTypeId().isDerivedFrom(Sketcher::PropertyConstraintList::getClassTypeId())); PropertyConstraintListItem* self = const_cast<PropertyConstraintListItem*>(this); int id = 1; QList<Base::Quantity> quantities; QList<Base::Quantity> subquantities; bool onlyNamed = true; const std::vector< Sketcher::Constraint * > &vals = static_cast<const Sketcher::PropertyConstraintList*>(prop)->getValues(); for (std::vector< Sketcher::Constraint* >::const_iterator it = vals.begin();it != vals.end(); ++it, ++id) { if ((*it)->Type == Sketcher::Distance || // Datum constraint (*it)->Type == Sketcher::DistanceX || (*it)->Type == Sketcher::DistanceY || (*it)->Type == Sketcher::Radius || (*it)->Type == Sketcher::Angle ) { Base::Quantity quant; if ((*it)->Type == Sketcher::Angle ) { double datum = Base::toDegrees<double>((*it)->getValue()); quant.setUnit(Base::Unit::Angle); quant.setValue(datum); } else { quant.setUnit(Base::Unit::Length); quant.setValue((*it)->getValue()); } quantities.append(quant); // Use a 7-bit ASCII string for the internal name. // See also comment in PropertyConstraintListItem::initialize() QString internalName = QString::fromLatin1("Constraint%1").arg(id); PropertyConstraintListItem* self = const_cast<PropertyConstraintListItem*>(this); self->blockEvent = true; if ((*it)->Name.empty() && !onlyUnnamed) { onlyNamed = false; subquantities.append(quant); PropertyConstraintListItem* unnamednode = static_cast<PropertyConstraintListItem*>(self->child(self->childCount()-1)); unnamednode->blockEvent = true; unnamednode->setProperty(internalName.toLatin1(), QVariant::fromValue<Base::Quantity>(quant)); unnamednode->blockEvent = false; } else { self->setProperty(internalName.toLatin1(), QVariant::fromValue<Base::Quantity>(quant)); } self->blockEvent = false; } } // The quantities of unnamed constraints are only needed for display purposes inside toString() if (!onlyUnnamed && !onlyNamed) { self->blockEvent = true; self->setProperty("Unnamed", QVariant::fromValue< QList<Base::Quantity> >(subquantities)); self->blockEvent = false; } return QVariant::fromValue< QList<Base::Quantity> >(quantities); }
QList<CardItem *> GenericCardContainer::_createCards(QList<int> card_ids) { QList<CardItem *> result; foreach (int card_id, card_ids) { CardItem *item = _createCard(card_id); result.append(item); }
void OrderDownload::sReplyFinished(QNetworkReply *reply) { QByteArray replyData = reply->readAll(); QJsonObject json(QJsonDocument::fromJson(replyData).object()); QString code = json.value("Code").toString("-99"); QString desc = json.value("Desc").toString(); QString opt; switch (_optType) { case OTDownloadIdList: if (code == "0") { /// 读取订单id列表 QJsonObject data = json.value("Data").toObject(); _ohData._total = data.value("Total").toInt(); QJsonArray orderIdListArray = data.value("OrderIDList").toArray(); QList<int> orderIdList; for (int i = 0; i < orderIdListArray.size(); i++) orderIdList.append(orderIdListArray.at(i).toInt()); _ohData._orderIdList = orderIdList; _ohData._currentIndex = 0; qDebug() << "orderIdList:" << _ohData._orderIdList; _optType = OTOrderDownloading; _timer->start(1000); } else { _optType = OTOrderDownloadError; _msg = tr("下载区间订单ID列表错误:") + desc; _timer->start(1000); } break; case OTOrderDownloading: /// 解析数据,写入ERP数据库,并继续请求数据 if ("0" == code) { QJsonObject data = json.value("Data").toObject(); QJsonArray orderListArray = data.value("OrderList").toArray(); for (int i = 0; i < orderListArray.size(); i++) insertOrder2ERPByJson(orderListArray.at(i).toObject()); } _timer->start(1000); break; // case STOrderInfoBatchGet: // opt = tr("下载订单"); // /// 解析数据,写入ERP数据库,并继续请求数据 // if ("0" == code) // { // QJsonObject data = json.value("Data").toObject(); // QJsonArray orderListArray = data.value("OrderList").toArray(); // for (int i = 0; i < orderListArray.size(); i++) // insertOrder2ERPByJson(orderListArray.at(i).toObject()); // } // _timer->start(1000); // break; default: break; } qInfo() << opt << code << desc; }
static QList<double> _calcPrettyBreaks( double minimum, double maximum, int classes ) { // C++ implementation of R's pretty algorithm // Based on code for determining optimal tick placement for statistical graphics // from the R statistical programming language. // Code ported from R implementation from 'labeling' R package // // Computes a sequence of about 'classes' equally spaced round values // which cover the range of values from 'minimum' to 'maximum'. // The values are chosen so that they are 1, 2 or 5 times a power of 10. QList<double> breaks; if ( classes < 1 ) { breaks.append( maximum ); return breaks; } int minimumCount = ( int ) classes / 3; double shrink = 0.75; double highBias = 1.5; double adjustBias = 0.5 + 1.5 * highBias; int divisions = classes; double h = highBias; double cell; int U; bool small = false; double dx = maximum - minimum; if ( dx == 0 && maximum == 0 ) { cell = 1.0; small = true; U = 1; } else { cell = qMax( qAbs( minimum ), qAbs( maximum ) ); if ( adjustBias >= 1.5 * h + 0.5 ) { U = 1 + ( 1.0 / ( 1 + h ) ); } else { U = 1 + ( 1.5 / ( 1 + adjustBias ) ); } small = dx < ( cell * U * qMax( 1, divisions ) * 1e-07 * 3.0 ); } if ( small ) { if ( cell > 10 ) { cell = 9 + cell / 10; cell = cell * shrink; } if ( minimumCount > 1 ) { cell = cell / minimumCount; } } else { cell = dx; if ( divisions > 1 ) { cell = cell / divisions; } } if ( cell < 20 * 1e-07 ) { cell = 20 * 1e-07; } double base = pow( 10.0, floor( log10( cell ) ) ); double unit = base; if (( 2 * base ) - cell < h *( cell - unit ) ) { unit = 2.0 * base; if (( 5 * base ) - cell < adjustBias *( cell - unit ) ) { unit = 5.0 * base; if (( 10.0 * base ) - cell < h *( cell - unit ) ) { unit = 10.0 * base; } } } // Maybe used to correct for the epsilon here?? int start = floor( minimum / unit + 1e-07 ); int end = ceil( maximum / unit - 1e-07 ); // Extend the range out beyond the data. Does this ever happen?? while ( start * unit > minimum + ( 1e-07 * unit ) ) { start = start - 1; } while ( end * unit < maximum - ( 1e-07 * unit ) ) { end = end + 1; } QgsDebugMsg( QString( "pretty classes: %1" ).arg( end ) ); // If we don't have quite enough labels, extend the range out // to make more (these labels are beyond the data :( ) int k = floor( 0.5 + end - start ); if ( k < minimumCount ) { k = minimumCount - k; if ( start >= 0 ) { end = end + k / 2; start = start - k / 2 + k % 2; } else { start = start - k / 2; end = end + k / 2 + k % 2; } divisions = minimumCount; } else { divisions = k; } double minimumBreak = start * unit; //double maximumBreak = end * unit; int count = end - start; for ( int i = 1; i < count + 1; i++ ) { breaks.append( minimumBreak + i * unit ); } if ( breaks.isEmpty() ) return breaks; if ( breaks.first() < minimum ) { breaks[0] = minimum; } if ( breaks.last() > maximum ) { breaks[breaks.count()-1] = maximum; } return breaks; } // _calcPrettyBreaks
void SmugTalker::parseResponseListPhotos(const QByteArray& data) { int errCode = -1; QString errMsg; QDomDocument doc("images.get"); if (!doc.setContent(data)) return; kDebug() << "Parse Photos response:" << endl << data; QList <SmugPhoto> photosList; QDomElement e = doc.documentElement(); for (QDomNode node = e.firstChild(); !node.isNull(); node = node.nextSibling()) { if (!node.isElement()) continue; e = node.toElement(); if (e.tagName() == "Images") { for (QDomNode nodeP = e.firstChild(); !nodeP.isNull(); nodeP = nodeP.nextSibling()) { if (!nodeP.isElement()) continue; e = nodeP.toElement(); if (e.tagName() == "Image") { SmugPhoto photo; photo.id = e.attribute("id").toInt(); photo.key = e.attribute("Key"); photo.caption = htmlToText(e.attribute("Caption")); photo.keywords = htmlToText(e.attribute("Keywords")); photo.thumbURL = e.attribute("ThumbURL"); // try to get largest size available if (e.hasAttribute("Video1280URL")) photo.originalURL = e.attribute("Video1280URL"); else if (e.hasAttribute("Video960URL")) photo.originalURL = e.attribute("Video960URL"); else if (e.hasAttribute("Video640URL")) photo.originalURL = e.attribute("Video640URL"); else if (e.hasAttribute("Video320URL")) photo.originalURL = e.attribute("Video320URL"); else if (e.hasAttribute("OriginalURL")) photo.originalURL = e.attribute("OriginalURL"); else if (e.hasAttribute("X3LargeURL")) photo.originalURL = e.attribute("X3LargeURL"); else if (e.hasAttribute("X2LargeURL")) photo.originalURL = e.attribute("X2LargeURL"); else if (e.hasAttribute("XLargeURL")) photo.originalURL = e.attribute("XLargeURL"); else if (e.hasAttribute("LargeURL")) photo.originalURL = e.attribute("LargeURL"); else if (e.hasAttribute("MediumURL")) photo.originalURL = e.attribute("MediumURL"); else if (e.hasAttribute("SmallURL")) photo.originalURL = e.attribute("SmallURL"); photosList.append(photo); } } errCode = 0; } else if (e.tagName() == "err") { errCode = e.attribute("code").toInt(); errMsg = e.attribute("msg"); kDebug() << "Error:" << errCode << errMsg; } } if (errCode == 15) // 15: empty list errCode = 0; emit signalBusy(false); emit signalListPhotosDone(errCode, errorToText(errCode, errMsg), photosList); }
QgsGraduatedSymbolRendererV2* QgsGraduatedSymbolRendererV2::createRenderer( QgsVectorLayer* vlayer, QString attrName, int classes, Mode mode, QgsSymbolV2* symbol, QgsVectorColorRampV2* ramp ) { if ( classes < 1 ) return NULL; int attrNum = vlayer->fieldNameIndex( attrName ); double minimum = vlayer->minimumValue( attrNum ).toDouble(); double maximum = vlayer->maximumValue( attrNum ).toDouble(); QgsDebugMsg( QString( "min %1 // max %2" ).arg( minimum ).arg( maximum ) ); QList<double> breaks; QList<int> labels; if ( mode == EqualInterval ) { breaks = _calcEqualIntervalBreaks( minimum, maximum, classes ); } else if ( mode == Pretty ) { breaks = _calcPrettyBreaks( minimum, maximum, classes ); } else if ( mode == Quantile || mode == Jenks || mode == StdDev ) { // get values from layer QList<double> values; QgsFeature f; QgsAttributeList lst; lst.append( attrNum ); QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFlags( QgsFeatureRequest::NoGeometry ).setSubsetOfAttributes( lst ) ); // create list of non-null attribute values while ( fit.nextFeature( f ) ) if ( !f.attribute( attrNum ).isNull() ) values.append( f.attribute( attrNum ).toDouble() ); // calculate the breaks if ( mode == Quantile ) { breaks = _calcQuantileBreaks( values, classes ); } else if ( mode == Jenks ) { breaks = _calcJenksBreaks( values, classes, minimum, maximum ); } else if ( mode == StdDev ) { breaks = _calcStdDevBreaks( values, classes, labels ); } } else { Q_ASSERT( false ); } QgsRangeList ranges; double lower, upper = minimum; QString label; // "breaks" list contains all values at class breaks plus maximum as last break int i = 0; for ( QList<double>::iterator it = breaks.begin(); it != breaks.end(); ++it, ++i ) { lower = upper; // upper border from last interval upper = *it; if ( mode == StdDev ) { if ( i == 0 ) { label = "< " + QString::number( labels[i], 'i', 0 ) + " Std Dev"; } else if ( i == labels.count() - 1 ) { label = ">= " + QString::number( labels[i-1], 'i', 0 ) + " Std Dev"; } else { label = QString::number( labels[i-1], 'i', 0 ) + " Std Dev" + " - " + QString::number( labels[i], 'i', 0 ) + " Std Dev"; } } else { label = QString::number( lower, 'f', 4 ) + " - " + QString::number( upper, 'f', 4 ); } QgsSymbolV2* newSymbol = symbol->clone(); double colorValue = ( breaks.count() > 1 ? ( double ) i / ( breaks.count() - 1 ) : 0 ); newSymbol->setColor( ramp->color( colorValue ) ); // color from (0 / cl-1) to (cl-1 / cl-1) ranges.append( QgsRendererRangeV2( lower, upper, newSymbol, label ) ); } QgsGraduatedSymbolRendererV2* r = new QgsGraduatedSymbolRendererV2( attrName, ranges ); r->setSourceSymbol( symbol->clone() ); r->setSourceColorRamp( ramp->clone() ); r->setMode( mode ); return r; }
void ViNeuralNetworkWidget::setNeuralNetwork(ViNeuralNetwork *neuralNetwork) { mNeuralNetwork = neuralNetwork; if(mNeuralNetwork != NULL) { mNeuronWidgets.clear(); //Determine if there is a bias mHasBias = false; for(int i = 0; i < mNeuralNetwork->size(); ++i) { if(mNeuralNetwork->at(i)->hasBias()) { mHasBias = true; break; } } //Add neurons for(int i = 0; i < mNeuralNetwork->size(); ++i) { QList<ViNeuronWidget*> layer; for(int j = 0; j < mNeuralNetwork->at(i)->size(); ++j) { layer.append(new ViNeuronWidget(xNeuronOffset(i), yNeuronOffset(i, j, mHasBias), mNeuronSize, mNeuralNetwork->at(i)->at(j))); } //Add bias if(mNeuralNetwork->at(i)->hasBias()) { mBiasWidgets.append(new ViBiasWidget(xBiasOffset(i), yBiasOffset(), mNeuronSize, mNeuralNetwork->at(i)->bias())); } else { mBiasWidgets.append(NULL); } mNeuronWidgets.append(layer); } //Add synapses for(int i = 0; i < mNeuralNetwork->size() - 1; ++i) { ViNeuralLayer *inputLayer = mNeuralNetwork->at(i); for(int j = 0; j < inputLayer->size(); ++j) { ViNeuron *neuron = inputLayer->at(j); for(int n = 0; n < neuron->outputSize(); ++n) { ViNeuronWidget *inputWidget = neuronWidget(neuron); ViNeuronWidget *outputWidget = neuronWidget(neuron->outputAt(n)->output()); if(inputWidget != NULL && outputWidget != NULL) { mSynapseWidgets.append(new ViSynapseWidget(inputWidget, outputWidget, neuron->outputAt(n), this)); } } } //Add bias synapses if(inputLayer->hasBias()) { ViNeuron *neuron = inputLayer->bias(); for(int n = 0; n < neuron->outputSize(); ++n) { ViNeuronWidget *inputWidget = neuronWidget(neuron); ViNeuronWidget *outputWidget = neuronWidget(neuron->outputAt(n)->output()); if(inputWidget != NULL && outputWidget != NULL) { mSynapseWidgets.append(new ViSynapseWidget(inputWidget, outputWidget, neuron->outputAt(n), this)); } } } } //Add input lines for(int i = 0; i < mNeuronWidgets[0].size(); ++i) { mLineWidgets.append(new ViNeuronLineWidget(mNeuronWidgets[0][i], this)); } //Add output lines for(int i = 0; i < mNeuronWidgets[mNeuronWidgets.size() - 1].size(); ++i) { mLineWidgets.append(new ViNeuronLineWidget(mNeuronWidgets[mNeuronWidgets.size() - 1][i], this)); } //Make sure the neurons are drawn last for(int i = 0; i < mNeuronWidgets.size(); ++i) { for(int j = 0; j < mNeuronWidgets[i].size(); ++j) { mNeuronWidgets[i][j]->setParent(this); } } for(int i = 0; i < mBiasWidgets.size(); ++i) { if(mBiasWidgets[i] != NULL) { mBiasWidgets[i]->setParent(this); } } } }
void NewGameTab::removeImage() { QListWidgetItem* item = m_images->currentItem(); if (!item) { return; } QString current_image = item->data(ImageRole).toString(); QList<QString> games; QXmlStreamReader xml; QXmlStreamAttributes attributes; for (const QString& game : QDir(Path::saves(), "*.xml").entryList(QDir::Files)) { QFile file(Path::save(game)); if (!file.open(QIODevice::ReadOnly)) { continue; } xml.setDevice(&file); // Load details while (!xml.isStartElement()) { xml.readNext(); } attributes = xml.attributes(); if (xml.name() == QLatin1String("tetzle") && attributes.value("version").toString().toUInt() <= 5) { if (attributes.value("image").toString() == current_image) { games.append(game); } } } QString message; if (games.isEmpty()) { message = tr("Remove selected image?"); } else { message = tr("Remove selected image?\n\nThere are saved games using this image that will also be removed."); } if (QMessageBox::question(this, tr("Remove Image"), message, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) { QString image_id = current_image.section(".", 0, 0); QFile::remove(Path::image(current_image)); QDir dir(Path::thumbnails(), image_id + "*"); const QStringList thumbs = dir.entryList(); for (const QString& thumb : thumbs) { dir.remove(thumb); } for (const QString& game : games) { QFile::remove(Path::save(game)); } delete item; m_image_tags->removeImage(current_image); m_accept_button->setEnabled(m_images->count() > 0); if (!m_accept_button->isEnabled()) { m_slider->setMaximum(-1); m_count->clear(); QSettings settings; settings.remove("NewGame/Image"); settings.remove("NewGame/Pieces"); } } }
void LYGithubManager::onIssuesReturned(){ QList<QByteArray> headerList = getIssuesReply_->rawHeaderList(); for(int x = 0; x < headerList.count(); x++){ if(headerList.at(x) == "Link" && lastPageNumber_ == -1){ QString linkHeader = getIssuesReply_->rawHeader(headerList.at(x)); int lastPageNumber = -1; int nextPageNumber = -1; QStringList linkHeaderItems = linkHeader.split(','); for(int y = 0; y < linkHeaderItems.count(); y++){ if(linkHeaderItems.at(y).contains("; rel=\"last\"")) lastPageNumber = pageNumberFromURLString(linkHeaderItems.at(y)); if(linkHeaderItems.at(y).contains("; rel=\"next\"")) nextPageNumber = pageNumberFromURLString(linkHeaderItems.at(y)); } lastPageNumber_ = lastPageNumber; } } int currentPageNumber = -1; if(lastPageNumber_ != -1) currentPageNumber = pageNumberFromURLString(lastGetIssuesRequest_); QJson::Parser parser; QVariant githubFullReply = parser.parse(getIssuesReply_->readAll()); bool doEmit = false; QList<QVariantMap> localRetVal; QVariantMap oneIssue; if(githubFullReply.canConvert(QVariant::List)){ QVariantList githubListReply = githubFullReply.toList(); if(githubListReply.at(0).canConvert(QVariant::Map)){ if((lastPageNumber_ == -1) || (currentPageNumber == lastPageNumber_) ) doEmit = true; for(int x = 0; x < githubListReply.count(); x++){ oneIssue = githubListReply.at(x).toMap(); localRetVal.append(oneIssue); } } } fullIssuesReply_.append(localRetVal); disconnect(getIssuesReply_, 0); getIssuesReply_->deleteLater(); getIssuesReply_ = 0; if((lastPageNumber_ != -1) && (currentPageNumber != lastPageNumber_)){ QNetworkRequest request; QString currentPageNumberString = QString("&page=%1").arg(currentPageNumber); QString nextPageNumberString = QString("&page=%1").arg(currentPageNumber+1); lastGetIssuesRequest_.replace(currentPageNumberString, nextPageNumberString); request.setUrl(QUrl(lastGetIssuesRequest_)); QString userInfo = userName_+":"+password_; QByteArray userData = userInfo.toLocal8Bit().toBase64(); QString headerData = "Basic " + userData; request.setRawHeader("Authorization", headerData.toLocal8Bit()); LYGithubProductBacklogStatusLog::statusLog()->appendStatusMessage(QString("Processed page %1 of %2 for getIssues request").arg(currentPageNumber).arg(lastPageNumber_)); getIssuesReply_ = manager_->get(request); connect(getIssuesReply_, SIGNAL(readyRead()), this, SLOT(onIssuesReturned())); return; } if(doEmit){ LYGithubProductBacklogStatusLog::statusLog()->appendStatusMessage("Processed final getIssues request"); lastPageNumber_ = -1; emit issuesReturned(fullIssuesReply_); return; } LYGithubProductBacklogStatusLog::statusLog()->appendStatusMessage("Something went wrong in getIssues request"); }
void Mash::calcMashSchedule() { // Method to run through the mash table and calculate values if (!this->allowRecalcs) { return; } double strikeTemp = 0; double targetTemp = 0; double waterAddedQTS = 0; double waterEquiv = 0; double mr = mashRatio; double currentTemp = getGrainTemp(); double displTemp = 0; double tunLoss; // figure out a better way to do this, eg: themal mass double decoct = 0; int totalMashTime = 0; int totalSpargeTime = 0; double mashWaterQTS = 0; double mashVolQTS = 0; int numSparge = 0; double totalWeightLbs = 0; double totalCerealLbs = 0; // convert mash ratio to qts/lb if in l/kg if (mashRatioU.compare(L_PER_KG) == 0) { mr *= 0.479325; } // convert CurrentTemp to F if (tempUnits == "C") { currentTemp = BrewCalcs::cToF(currentTemp); tunLoss = tunLossF * 1.8; } else tunLoss = tunLossF; // perform calcs on first record if (steps.empty()) return; // sort the list //Collections.sort(steps); // add up the cereal mash lbs for (int i = 1; i < steps.size(); i++) { MashStep *stp = &steps[i]; if (stp->getMethod() == "cereal mash"){ totalCerealLbs += stp->getWeightLbs(); } } totalWeightLbs = maltWeightLbs - totalCerealLbs; // the first step is always an infusion MashStep *stp = &steps[0]; targetTemp = stp->getStartTemp(); strikeTemp = calcStrikeTemp(targetTemp, currentTemp, mr, tunLoss); waterAddedQTS = mr * totalWeightLbs; waterEquiv = totalWeightLbs * (0.192 + mr); mashVolQTS = calcMashVol(totalWeightLbs, mr); totalMashTime += stp->getMinutes(); mashWaterQTS += waterAddedQTS; stp->getInVol()->setUnits(CONVERTER_QT); stp->getInVol()->setAmount(waterAddedQTS); stp->setStrikeTemp(strikeTemp); stp->setMethod(INFUSION); stp->setWeightLbs(totalWeightLbs); qDebug() << "Subtracting cereal " << totalCerealLbs << " from " <<maltWeightLbs; totalWeightLbs = maltWeightLbs - totalCerealLbs; // subtract the water added from the Water Equiv so that they are correct when added in the next part of the loop waterEquiv -= waterAddedQTS; // Updated the water added if (tempUnits == "C") { strikeTemp = BrewCalcs::fToC(strikeTemp); } stp->setDirections("Mash in with " + SBStringUtils::format(stp->getInVol()->getValueAs(volUnits),1 ) + " " + volUnits + " of water at " + SBStringUtils::format(strikeTemp, 1) + " " + tempUnits); // set TargetTemp to the end temp targetTemp = stp->getEndTemp(); for (int i = 1; i < steps.size(); i++) { stp = &steps[i]; currentTemp = targetTemp; // switch targetTemp = stp->getStartTemp(); // if this is a former sparge step that's been changed, change // the method to infusion qDebug() << "Mash step Type: " << stp->getType() << " Method: " << stp->getMethod(); if (stp->getType() != SPARGE && ( stp->getMethod() == FLY || stp->getMethod() == BATCH)) stp->setMethod(INFUSION); // do calcs if (stp->getMethod() == INFUSION) { // calculate an infusion step decoct = 0; waterEquiv += waterAddedQTS; // add previous addition to get WE strikeTemp = boilTempF; // boiling water // Updated the water added waterAddedQTS = calcWaterAddition(targetTemp, currentTemp, waterEquiv, boilTempF); stp->getOutVol()->setAmount(0); stp->getInVol()->setUnits(CONVERTER_QT); stp->getInVol()->setAmount(waterAddedQTS); stp->setStrikeTemp(strikeTemp); stp->setWeightLbs(totalWeightLbs); if (tempUnits == "C") strikeTemp = 100; stp->setDirections("Add " + SBStringUtils::format(stp->getInVol()->getValueAs(volUnits), 1) + " " + volUnits + " of water at " + SBStringUtils::format(strikeTemp, 1) + " " + tempUnits); mashWaterQTS += waterAddedQTS; mashVolQTS += waterAddedQTS; } else if (stp->getMethod() == DECOCTION) { // calculate a decoction step waterEquiv += waterAddedQTS; // add previous addition to get WE waterAddedQTS = 0; strikeTemp = boilTempF; // boiling water double ratio=0.75; if (stp->getMethod() == DECOCTION_THICK) ratio = thickDecoctRatio; else if (stp->getMethod() == DECOCTION_THIN) ratio = thinDecoctRatio; // Calculate volume (qts) of mash to remove decoct = calcDecoction2(targetTemp, currentTemp, mashWaterQTS, ratio, totalWeightLbs); stp->getOutVol()->setUnits(CONVERTER_QT); stp->getOutVol()->setAmount(decoct); stp->getInVol()->setAmount(0); stp->setStrikeTemp(boilTempF); stp->setWeightLbs(totalWeightLbs); // Updated the decoction, convert to right units & make directions stp->setDirections("Remove " + SBStringUtils::format(stp->getOutVol()->getValueAs(volUnits), 1) + " " + volUnits + " of mash, boil, and return to mash."); } else if (stp->getMethod() == DIRECT) { // calculate a direct heat step decoct = 0; waterEquiv += waterAddedQTS; // add previous addition to get WE waterAddedQTS = 0; displTemp = stp->getStartTemp(); if (tempUnits == "C") displTemp = BrewCalcs::fToC(displTemp); stp->setDirections("Add direct heat until mash reaches " + QString::number(displTemp) + " " + tempUnits + "."); stp->getInVol()->setAmount(0); stp->getOutVol()->setAmount(0); stp->setStrikeTemp(0); stp->setWeightLbs(totalWeightLbs); } else if (stp->getMethod() == CEREAL_MASH) { // calculate a cereal mash step waterEquiv += waterAddedQTS; // add previous addition to get WE waterAddedQTS = 0; targetTemp = stp->getStartTemp(); double extraWaterQTS = 0; double cerealTemp = boilTempF; double cerealTargTemp = cerealMashTemp; QString addStr = ""; /* * 1. check the temp of the mash when you add the boiling cereal mash @ default ratio back * 2. if it's > than the step temp, adjust the step temp * 3. if it's < than the step temp, add extra water to increase the "heat equivalencey" of the cereal mash */ double cerealWaterEquiv = stp->getWeightLbs() * (0.192 + mr); waterAddedQTS = mr * stp->getWeightLbs(); strikeTemp = calcStrikeTemp(cerealMashTemp, grainTempF, mr, 0); double newTemp = ((waterEquiv * currentTemp) + (cerealWaterEquiv * cerealTemp)) / (waterEquiv + cerealWaterEquiv); if (newTemp > targetTemp){ stp->setStartTemp(newTemp); } if (newTemp < targetTemp){ double addQts = ((waterEquiv * (targetTemp - currentTemp)) / (cerealTemp - targetTemp)) - 0.192; extraWaterQTS = addQts - waterAddedQTS; addStr = " Add " + SBStringUtils::format(Quantity::convertUnit(CONVERTER_QT, volUnits, extraWaterQTS), 1) + " " + volUnits + " water to the cereal mash."; } // Calculate final temp of cereal mash // cerealTemp = (targetTemp * (waterEquiv + cerealWaterEquiv) - (waterEquiv * currentTemp)) / cerealWaterEquiv; totalMashTime += stp->getMinutes(); mashWaterQTS += waterAddedQTS + extraWaterQTS; stp->getInVol()->setUnits(CONVERTER_QT); stp->getInVol()->setAmount(waterAddedQTS); stp->getOutVol()->setAmount(0); stp->setStrikeTemp(strikeTemp); // make directions QString weightStr = SBStringUtils::format(Quantity::convertUnit(CONVERTER_LB, this->maltUnits, stp->getWeightLbs()), 1) + " " + this->maltUnits; QString volStr = SBStringUtils::format(Quantity::convertUnit(CONVERTER_QT, volUnits, waterAddedQTS), 1) + " " + volUnits; if (tempUnits == "C"){ strikeTemp = BrewCalcs::fToC(strikeTemp); cerealTemp = BrewCalcs::fToC(cerealTemp); targetTemp = BrewCalcs::fToC(targetTemp); cerealTargTemp = BrewCalcs::fToC(cerealTargTemp); } QString tempStr = SBStringUtils::format(strikeTemp, 1) + tempUnits; QString tempStr2 = SBStringUtils::format(cerealTemp, 1) + tempUnits; QString tempStr3 = SBStringUtils::format(targetTemp, 1) + tempUnits; QString tempStr4 = SBStringUtils::format(cerealTargTemp, 1) + tempUnits; QString newDirection = "Cereal mash: mash " + weightStr + " grain with " + volStr + " water at " + tempStr + " to hit " + tempStr4 + " and rest."; newDirection.append(addStr); newDirection.append(" Raise to " + tempStr2 + " and add to the main mash to reach " + tempStr3); stp->setDirections(newDirection); // add cereal mash to total weight totalWeightLbs += stp->getWeightLbs(); } else { qDebug() << "Unrecognised mash step: " << stp->getMethod(); } if (stp->getType() == SPARGE) numSparge++; else { totalMashTime += stp->getMinutes(); } // set target temp to end temp for next step targetTemp = stp->getEndTemp(); } // for steps.size() waterEquiv += waterAddedQTS; // add previous addition to get WE totalTime = totalMashTime; volQts = mashVolQTS; // water use stats: qDebug() << "Total Weight " << totalWeightLbs; absorbedQTS = totalWeightLbs * 0.52; // figure from HBD // spargeTotalQTS = (myRecipe.getPreBoilVol("qt")) - (mashWaterQTS - absorbedQTS); totalWaterQTS = mashWaterQTS; spargeQTS = this->preBoilQts - (mashWaterQTS - absorbedQTS - deadSpace.getValueAs(CONVERTER_QT)); qDebug() << "Sparge QTs: " << spargeQTS; // Now let's figure out the sparging: if (numSparge == 0) return; // Amount to collect per sparge double col = this->preBoilQts / numSparge; QList<double> charge = QList<double>(); QList<double> collect = QList<double>(); for (int i = 0; i < numSparge; i++) { charge.append(0.0); collect.append(0.0); } double totalCollectQts = this->preBoilQts; // do we need to add more water to charge up // is the amount we need to collect less than the initial mash volume - absorbption if (col <= (mashWaterQTS - absorbedQTS)) { charge[0] = 0; collect[0] = mashWaterQTS - absorbedQTS; // how much is left over from the mash totalCollectQts = totalCollectQts - collect[0]; } else { charge[0] = col - (mashWaterQTS - absorbedQTS); // add the additional water to get out the desired first collection amount PER sparge collect[0] = col; totalCollectQts = totalCollectQts - collect[0]; } // do we need any more steps? if(numSparge > 1) { /* batch_1_sparge_liters = (boil_size_l/<total number of steps> ) - mash_water_l + grain_wt_kg * 0.625) batch_2_liters = boil_size_l / <total number of steps> */ for (int i = 1; i < numSparge; i++) { charge[i] = col; collect[i] = col; } } int j=0; for (int i = 1; i < steps.size(); i++) { stp = &steps[i]; if (stp->getType() == SPARGE) { stp->getInVol()->setUnits(CONVERTER_QT); stp->getInVol()->setAmount(charge[j]); stp->getOutVol()->setUnits(CONVERTER_QT); stp->getOutVol()->setAmount(collect[j]); stp->setStrikeTemp(SPARGETMPF); totalSpargeTime += stp->getMinutes(); QString collectStr = SBStringUtils::format(Quantity::convertUnit(CONVERTER_QT, volUnits, collect[j]), 2) + " " + volUnits; QString tempStr = ""; if (tempUnits == "F"){ tempStr = "" + SBStringUtils::format(SPARGETMPF, 1) + "F"; } else { tempStr = SBStringUtils::format(BrewCalcs::fToC(SPARGETMPF), 1) + "C"; } if (numSparge > 1){ stp->setMethod(BATCH); QString add = SBStringUtils::format(Quantity::convertUnit(CONVERTER_QT, volUnits, charge[j]), 2) + " " + volUnits; stp->setDirections("Add " + add + " at " + tempStr + " to collect " + collectStr); } else { stp->getInVol()->setUnits(CONVERTER_QT); stp->getInVol()->setAmount(spargeQTS); stp->getOutVol()->setUnits(CONVERTER_QT); stp->getOutVol()->setAmount(collect[j]); stp->setMethod(FLY); stp->setDirections("Sparge with " + SBStringUtils::format(Quantity::convertUnit(CONVERTER_QT, volUnits, spargeQTS), 1) + " " + volUnits + " at " + tempStr + " to collect " + collectStr); } j++; } } }
void QgsGeometryCheckerSetupTab::runChecks() { // Get selected layer QList<QgsVectorLayer *> layers = getSelectedLayers(); if ( layers.isEmpty() ) return; if ( ui.radioButtonOutputNew->isChecked() ) { for ( QgsVectorLayer *layer : layers ) { if ( layer->dataProvider()->dataSourceUri().startsWith( ui.lineEditOutputDirectory->text() ) ) { QMessageBox::critical( this, tr( "Invalid Output Directory" ), tr( "The chosen output directory contains one or more input layers." ) ); return; } } } QgsVectorLayer *lineLayerCheckLayer = ui.comboLineLayerIntersection->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboLineLayerIntersection->currentData().toString() ) ) : nullptr; QgsVectorLayer *followBoundaryCheckLayer = ui.comboBoxFollowBoundaries->isEnabled() ? dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboBoxFollowBoundaries->currentData().toString() ) ) : nullptr; if ( layers.contains( lineLayerCheckLayer ) || layers.contains( followBoundaryCheckLayer ) ) { QMessageBox::critical( this, tr( "Error" ), tr( "The test layer set contains a layer selected for a topology check." ) ); return; } for ( QgsVectorLayer *layer : layers ) { if ( layer->isEditable() ) { QMessageBox::critical( this, tr( "Editable Input Layer" ), tr( "Input layer '%1' is not allowed to be in editing mode." ).arg( layer->name() ) ); return; } } bool selectedOnly = ui.checkBoxInputSelectedOnly->isChecked(); // Set window busy setCursor( Qt::WaitCursor ); mRunButton->setEnabled( false ); ui.labelStatus->setText( tr( "<b>Preparing output...</b>" ) ); ui.labelStatus->show(); QApplication::processEvents( QEventLoop::ExcludeUserInputEvents ); QList<QgsVectorLayer *> processLayers; if ( ui.radioButtonOutputNew->isChecked() ) { // Get output directory and file extension QDir outputDir = QDir( ui.lineEditOutputDirectory->text() ); QString outputDriverName = ui.comboBoxOutputFormat->currentData().toString(); QgsVectorFileWriter::MetaData metadata; if ( !QgsVectorFileWriter::driverMetadata( outputDriverName, metadata ) ) { QMessageBox::critical( this, tr( "Unknown Output Format" ), tr( "The specified output format cannot be recognized." ) ); mRunButton->setEnabled( true ); ui.labelStatus->hide(); unsetCursor(); return; } QString outputExtension = metadata.ext; // List over input layers, check which existing project layers need to be removed and create output layers QString filenamePrefix = ui.lineEditFilenamePrefix->text(); QSettings().setValue( "/geometry_checker/previous_values/filename_prefix", filenamePrefix ); QStringList toRemove; QStringList createErrors; for ( QgsVectorLayer *layer : layers ) { QString outputPath = outputDir.absoluteFilePath( filenamePrefix + layer->name() + "." + outputExtension ); // Remove existing layer with same uri from project for ( QgsVectorLayer *projectLayer : QgsProject::instance()->layers<QgsVectorLayer *>() ) { if ( projectLayer->dataProvider()->dataSourceUri().startsWith( outputPath ) ) { toRemove.append( projectLayer->id() ); } } // Create output layer QString errMsg; QgsVectorFileWriter::WriterError err = QgsVectorFileWriter::writeAsVectorFormat( layer, outputPath, layer->dataProvider()->encoding(), layer->crs(), outputDriverName, selectedOnly, &errMsg ); if ( err != QgsVectorFileWriter::NoError ) { createErrors.append( errMsg ); continue; } QgsVectorLayer *newlayer = new QgsVectorLayer( outputPath, QFileInfo( outputPath ).completeBaseName(), QStringLiteral( "ogr" ) ); if ( selectedOnly ) { QgsFeature feature; // Get features to select (only selected features were written up to this point) QgsFeatureIds selectedFeatures = newlayer->allFeatureIds(); // Write non-selected feature ids QgsFeatureList features; QgsFeatureIterator it = layer->getFeatures(); while ( it.nextFeature( feature ) ) { if ( !layer->selectedFeatureIds().contains( feature.id() ) ) { features.append( feature ); } } newlayer->dataProvider()->addFeatures( features ); // Set selected features newlayer->selectByIds( selectedFeatures ); } processLayers.append( newlayer ); } // Remove layers from project if ( !toRemove.isEmpty() ) { QgsProject::instance()->removeMapLayers( toRemove ); } // Error if an output layer could not be created if ( !createErrors.isEmpty() ) { QMessageBox::critical( this, tr( "Layer Creation Failed" ), tr( "Failed to create one or more output layers:\n%1" ).arg( createErrors.join( "\n" ) ) ); mRunButton->setEnabled( true ); ui.labelStatus->hide(); unsetCursor(); return; } } else { processLayers = layers; } // Check if output layers are editable QList<QgsVectorLayer *> nonEditableLayers; for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) ) { if ( ( layer->dataProvider()->capabilities() & QgsVectorDataProvider::ChangeGeometries ) == 0 ) { nonEditableLayers.append( layer ); } } if ( !nonEditableLayers.isEmpty() ) { QStringList nonEditableLayerNames; for ( QgsVectorLayer *layer : nonEditableLayers ) { nonEditableLayerNames.append( layer->name() ); } if ( QMessageBox::Yes != QMessageBox::question( this, tr( "Non-editable Output Layers" ), tr( "The following output layers are in a format that does not support editing features:\n%1\n\nThe geometry check can be performed, but it will not be possible to fix any errors. Do you want to continue?" ).arg( nonEditableLayerNames.join( "\n" ) ), QMessageBox::Yes, QMessageBox::No ) ) { if ( ui.radioButtonOutputNew->isChecked() ) { for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) ) { QString layerPath = layer->dataProvider()->dataSourceUri(); delete layer; if ( ui.comboBoxOutputFormat->currentText() == QLatin1String( "ESRI Shapefile" ) ) { QgsVectorFileWriter::deleteShapeFile( layerPath ); } else { QFile( layerPath ).remove(); } } mRunButton->setEnabled( true ); ui.labelStatus->hide(); unsetCursor(); } return; } } // Setup checker ui.labelStatus->setText( tr( "<b>Building spatial index...</b>" ) ); QApplication::processEvents( QEventLoop::ExcludeUserInputEvents ); QMap<QString, QgsFeaturePool *> featurePools; for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) ) { double layerToMapUntis = mIface->mapCanvas()->mapSettings().layerToMapUnits( layer ); QgsCoordinateTransform layerToMapTransform( layer->crs(), QgsProject::instance()->crs(), QgsProject::instance() ); featurePools.insert( layer->id(), new QgsFeaturePool( layer, layerToMapUntis, layerToMapTransform, selectedOnly ) ); } // LineLayerIntersection check is enabled, make sure there is also a feature pool for that layer if ( ui.checkLineLayerIntersection->isChecked() && !featurePools.keys().contains( ui.comboLineLayerIntersection->currentData().toString() ) ) { QgsVectorLayer *layer = dynamic_cast<QgsVectorLayer *>( QgsProject::instance()->mapLayer( ui.comboLineLayerIntersection->currentData().toString() ) ); Q_ASSERT( layer ); double layerToMapUntis = mIface->mapCanvas()->mapSettings().layerToMapUnits( layer ); QgsCoordinateTransform layerToMapTransform( layer->crs(), QgsProject::instance()->crs(), QgsProject::instance() ); featurePools.insert( layer->id(), new QgsFeaturePool( layer, layerToMapUntis, layerToMapTransform, selectedOnly ) ); } QgsGeometryCheckerContext *context = new QgsGeometryCheckerContext( ui.spinBoxTolerance->value(), QgsProject::instance()->crs(), featurePools ); QList<QgsGeometryCheck *> checks; for ( const QgsGeometryCheckFactory *factory : QgsGeometryCheckFactoryRegistry::getCheckFactories() ) { QgsGeometryCheck *check = factory->createInstance( context, ui ); if ( check ) { checks.append( check ); } } QgsGeometryChecker *checker = new QgsGeometryChecker( checks, context ); emit checkerStarted( checker ); if ( ui.radioButtonOutputNew->isChecked() ) { QList<QgsMapLayer *> addLayers; for ( QgsVectorLayer *layer : qgis::as_const( processLayers ) ) { addLayers.append( layer ); } QgsProject::instance()->addMapLayers( addLayers ); } // Run ui.buttonBox->addButton( mAbortButton, QDialogButtonBox::ActionRole ); mRunButton->hide(); ui.progressBar->setRange( 0, 0 ); ui.labelStatus->hide(); ui.progressBar->show(); ui.widgetInputs->setEnabled( false ); QEventLoop evLoop; QFutureWatcher<void> futureWatcher; connect( checker, &QgsGeometryChecker::progressValue, ui.progressBar, &QProgressBar::setValue ); connect( &futureWatcher, &QFutureWatcherBase::finished, &evLoop, &QEventLoop::quit ); connect( mAbortButton, &QAbstractButton::clicked, &futureWatcher, &QFutureWatcherBase::cancel ); connect( mAbortButton, &QAbstractButton::clicked, this, &QgsGeometryCheckerSetupTab::showCancelFeedback ); int maxSteps = 0; futureWatcher.setFuture( checker->execute( &maxSteps ) ); ui.progressBar->setRange( 0, maxSteps ); evLoop.exec(); // Restore window unsetCursor(); mAbortButton->setEnabled( true ); ui.buttonBox->removeButton( mAbortButton ); mRunButton->setEnabled( true ); mRunButton->show(); ui.progressBar->hide(); ui.labelStatus->hide(); ui.widgetInputs->setEnabled( true ); // Show result emit checkerFinished( !futureWatcher.isCanceled() ); }
QList<ProjectExplorer::ToolChain *> RvctToolChainFactory::autoDetect() { Utils::Environment env = Utils::Environment::systemEnvironment(); QMap<QString, QList<Utils::EnvironmentItem> > rvcts; QList<Utils::EnvironmentItem> globalItems; // Find all RVCT..x variables for (Utils::Environment::const_iterator i = env.constBegin(); i != env.constEnd(); ++i) { if (i.key() == QLatin1String(RVCT_LICENSE_KEY)) globalItems.append(Utils::EnvironmentItem(i.key(), i.value())); if (!i.key().startsWith(QLatin1String("RVCT"))) continue; const QString key = i.key().left(6); QList<Utils::EnvironmentItem> values = rvcts.value(key); values.append(Utils::EnvironmentItem(i.key(), i.value())); rvcts.insert(key, values); } // Set up toolchains for each RVCT.. set QList<ProjectExplorer::ToolChain *> result; for (QMap<QString, QList<Utils::EnvironmentItem> >::const_iterator i = rvcts.constBegin(); i != rvcts.constEnd(); ++i) { QList<Utils::EnvironmentItem> changes = i.value(); changes.append(globalItems); QString binary = QDir::fromNativeSeparators(valueOf(changes, QLatin1String("BIN"))); if (binary.isEmpty()) continue; binary = binary + QLatin1Char('/') + RVCT_BINARY; QFileInfo fi(binary); if (!fi.exists() || !fi.isExecutable()) continue; RvctToolChain::RvctVersion v = RvctToolChain::version(binary); if (v.majorVersion == 0 && v.minorVersion == 0 && v.build == 0) continue; // Failed to start. //: %1 arm version, %2 major version, %3 minor version, %4 build number const QString name = tr("RVCT (%1 %2.%3 Build %4)"); RvctToolChain *tc = new RvctToolChain(true); tc->setCompilerPath(binary); tc->setEnvironmentChanges(changes); tc->setDisplayName(name.arg(armVersionString(tc->armVersion())) .arg(v.majorVersion).arg(v.minorVersion).arg(v.build)); tc->setVersion(v); result.append(tc); tc = new RvctToolChain(true); tc->setCompilerPath(binary); tc->setEnvironmentChanges(changes); tc->setArmVersion(RvctToolChain::ARMv6); tc->setDisplayName(name.arg(armVersionString(tc->armVersion())) .arg(v.majorVersion).arg(v.minorVersion).arg(v.build)); tc->setVersion(v); result.append(tc); } return result; }