本文整理汇总了C++中QMultiMap::constBegin方法的典型用法代码示例。如果您正苦于以下问题:C++ QMultiMap::constBegin方法的具体用法?C++ QMultiMap::constBegin怎么用?C++ QMultiMap::constBegin使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QMultiMap
的用法示例。
在下文中一共展示了QMultiMap::constBegin方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: expire
/*!
Cleans the cache so that its size is under the maximum cache size.
Returns the current size of the cache.
When the current size of the cache is greater than the maximumCacheSize()
older cache files are removed until the total size is less then 90% of
maximumCacheSize() starting with the oldest ones first using the file
creation date to determine how old a cache file is.
Subclasses can reimplement this function to change the order that cache
files are removed taking into account information in the application
knows about that QNetworkDiskCache does not, for example the number of times
a cache is accessed.
Note: cacheSize() calls expire if the current cache size is unknown.
\sa maximumCacheSize(), fileMetaData()
*/
qint64 QNetworkDiskCache::expire()
{
Q_D(QNetworkDiskCache);
if (d->currentCacheSize >= 0 && d->currentCacheSize < maximumCacheSize())
return d->currentCacheSize;
if (cacheDirectory().isEmpty()) {
qWarning() << "QNetworkDiskCache::expire() The cache directory is not set";
return 0;
}
// close file handle to prevent "in use" error when QFile::remove() is called
d->lastItem.reset();
QDir::Filters filters = QDir::AllDirs | QDir:: Files | QDir::NoDotAndDotDot;
QDirIterator it(cacheDirectory(), filters, QDirIterator::Subdirectories);
QMultiMap<QDateTime, QString> cacheItems;
qint64 totalSize = 0;
while (it.hasNext()) {
QString path = it.next();
QFileInfo info = it.fileInfo();
QString fileName = info.fileName();
if (fileName.endsWith(CACHE_POSTFIX)) {
cacheItems.insert(info.created(), path);
totalSize += info.size();
}
}
int removedFiles = 0;
qint64 goal = (maximumCacheSize() * 9) / 10;
QMultiMap<QDateTime, QString>::const_iterator i = cacheItems.constBegin();
while (i != cacheItems.constEnd()) {
if (totalSize < goal)
break;
QString name = i.value();
QFile file(name);
qint64 size = file.size();
file.remove();
totalSize -= size;
++removedFiles;
++i;
}
#if defined(QNETWORKDISKCACHE_DEBUG)
if (removedFiles > 0) {
qDebug() << "QNetworkDiskCache::expire()"
<< "Removed:" << removedFiles
<< "Kept:" << cacheItems.count() - removedFiles;
}
#endif
return totalSize;
}
示例2: makeXmppUri
QString XmppUriQueries::makeXmppUri(const Jid &AContactJid, const QString &AAction, const QMultiMap<QString, QString> &AParams) const
{
if (AContactJid.isValid() && !AAction.isEmpty())
{
QUrl url;
url.setQueryDelimiters('=',';');
url.setScheme(XMPP_URI_SCHEME);
url.setPath(AContactJid.full());
QList< QPair<QString, QString> > query;
query.append(qMakePair<QString,QString>(AAction,QString::null));
for(QMultiMap<QString, QString>::const_iterator it=AParams.constBegin(); it!=AParams.end(); ++it)
query.append(qMakePair<QString,QString>(it.key(),it.value()));
url.setQueryItems(query);
return url.toString().replace(QString("?%1=;").arg(AAction),QString("?%1;").arg(AAction));
}
return QString::null;
}
示例3: dissolve
bool QgsGeometryAnalyzer::dissolve( QgsVectorLayer* layer, const QString& shapefileName,
bool onlySelectedFeatures, int uniqueIdField, QProgressDialog* p )
{
if ( !layer )
{
return false;
}
QgsVectorDataProvider* dp = layer->dataProvider();
if ( !dp )
{
return false;
}
bool useField = false;
if ( uniqueIdField == -1 )
{
uniqueIdField = 0;
}
else
{
useField = true;
}
QgsWkbTypes::Type outputType = dp->wkbType();
QgsCoordinateReferenceSystem crs = layer->crs();
QgsVectorFileWriter vWriter( shapefileName, dp->encoding(), layer->fields(), outputType, crs );
QgsFeature currentFeature;
QMultiMap<QString, QgsFeatureId> map;
if ( onlySelectedFeatures )
{
//use QgsVectorLayer::featureAtId
const QgsFeatureIds selection = layer->selectedFeaturesIds();
QgsFeatureIds::const_iterator it = selection.constBegin();
for ( ; it != selection.constEnd(); ++it )
{
if ( !layer->getFeatures( QgsFeatureRequest().setFilterFid( *it ) ).nextFeature( currentFeature ) )
{
continue;
}
map.insert( currentFeature.attribute( uniqueIdField ).toString(), currentFeature.id() );
}
}
else
{
QgsFeatureIterator fit = layer->getFeatures();
while ( fit.nextFeature( currentFeature ) )
{
map.insert( currentFeature.attribute( uniqueIdField ).toString(), currentFeature.id() );
}
}
QgsGeometry dissolveGeometry; //dissolve geometry
QMultiMap<QString, QgsFeatureId>::const_iterator jt = map.constBegin();
QgsFeature outputFeature;
while ( jt != map.constEnd() )
{
QString currentKey = jt.key();
int processedFeatures = 0;
bool first = true;
//take only selection
if ( onlySelectedFeatures )
{
//use QgsVectorLayer::featureAtId
const QgsFeatureIds selection = layer->selectedFeaturesIds();
if ( p )
{
p->setMaximum( selection.size() );
}
while ( jt != map.constEnd() && ( jt.key() == currentKey || !useField ) )
{
if ( p && p->wasCanceled() )
{
break;
}
if ( selection.contains( jt.value() ) )
{
if ( p )
{
p->setValue( processedFeatures );
}
if ( !layer->getFeatures( QgsFeatureRequest().setFilterFid( jt.value() ) ).nextFeature( currentFeature ) )
{
continue;
}
if ( first )
{
outputFeature.setAttributes( currentFeature.attributes() );
first = false;
}
dissolveGeometry = dissolveFeature( currentFeature, dissolveGeometry );
++processedFeatures;
}
++jt;
}
}
//take all features
else
{
int featureCount = layer->featureCount();
//.........这里部分代码省略.........
示例4: convexHull
bool QgsGeometryAnalyzer::convexHull( QgsVectorLayer* layer, const QString& shapefileName,
bool onlySelectedFeatures, int uniqueIdField, QProgressDialog* p )
{
if ( !layer )
{
return false;
}
QgsVectorDataProvider* dp = layer->dataProvider();
if ( !dp )
{
return false;
}
bool useField = false;
if ( uniqueIdField == -1 )
{
uniqueIdField = 0;
}
else
{
useField = true;
}
QgsFields fields;
fields.append( QgsField( QStringLiteral( "UID" ), QVariant::String ) );
fields.append( QgsField( QStringLiteral( "AREA" ), QVariant::Double ) );
fields.append( QgsField( QStringLiteral( "PERIM" ), QVariant::Double ) );
QgsWkbTypes::Type outputType = QgsWkbTypes::Polygon;
QgsCoordinateReferenceSystem crs = layer->crs();
QgsVectorFileWriter vWriter( shapefileName, dp->encoding(), fields, outputType, crs );
QgsFeature currentFeature;
QgsGeometry dissolveGeometry; //dissolve geometry
QMultiMap<QString, QgsFeatureId> map;
if ( onlySelectedFeatures )
{
//use QgsVectorLayer::featureAtId
const QgsFeatureIds selection = layer->selectedFeaturesIds();
QgsFeatureIds::const_iterator it = selection.constBegin();
for ( ; it != selection.constEnd(); ++it )
{
#if 0
if ( p )
{
p->setValue( processedFeatures );
}
if ( p && p->wasCanceled() )
{
// break; // it may be better to do something else here?
return false;
}
#endif
if ( !layer->getFeatures( QgsFeatureRequest().setFilterFid( *it ) ).nextFeature( currentFeature ) )
{
continue;
}
map.insert( currentFeature.attribute( uniqueIdField ).toString(), currentFeature.id() );
}
}
else
{
QgsFeatureIterator fit = layer->getFeatures();
while ( fit.nextFeature( currentFeature ) )
{
#if 0
if ( p )
{
p->setValue( processedFeatures );
}
if ( p && p->wasCanceled() )
{
// break; // it may be better to do something else here?
return false;
}
#endif
map.insert( currentFeature.attribute( uniqueIdField ).toString(), currentFeature.id() );
}
}
QMultiMap<QString, QgsFeatureId>::const_iterator jt = map.constBegin();
while ( jt != map.constEnd() )
{
QString currentKey = jt.key();
int processedFeatures = 0;
//take only selection
if ( onlySelectedFeatures )
{
//use QgsVectorLayer::featureAtId
const QgsFeatureIds selection = layer->selectedFeaturesIds();
if ( p )
{
p->setMaximum( selection.size() );
}
processedFeatures = 0;
while ( jt != map.constEnd() && ( jt.key() == currentKey || !useField ) )
{
if ( p && p->wasCanceled() )
{
break;
}
//.........这里部分代码省略.........
示例5: run
void CalculateTaskScore::run()
{
qDebug() << "CalculateTaskScore: Starting new thread";
ConfigParser settings;
QDateTime started = QDateTime::currentDateTime();
ctemplate::TemplateDictionary dict("user_task_score");
db = MySQLHandler::getInstance();
QMultiMap<int, LCCode> users = UserDao::getUserNativeLCCodes(db);
QList<QSharedPointer<Task> > tasks = this->getTasks(); //Must use custom function to check message for task id
QMultiMap<int, LCCode> userSecondaryLanguages = UserDao::getUserLCCodes(db);
QMultiMap<int, int> userTags = UserDao::getUserTagIds(db);
QMultiMap<int, int> taskTags = TaskDao::getTaskTagIds(db);
if(users.count() > 0) {
for(QMultiMap<int, LCCode>::ConstIterator usersIter = users.constBegin(); usersIter != users.constEnd(); ++usersIter) {
if(tasks.length() > 0) {
const LCCode userNativeLCCode = users.value(usersIter.key());
QList<TaskScore> taskScores;
foreach(QSharedPointer<Task> task, tasks) {
int score = 0;
Locale taskSourceLocale = task->sourcelocale();
if(userNativeLCCode.first == taskSourceLocale.languagecode()) {
score += 750;
if(userNativeLCCode.second == taskSourceLocale.countrycode()) {
score += 75;
}
}
Locale taskTargetLocale = task->targetlocale();
if(userNativeLCCode.first == taskTargetLocale.languagecode()) {
score += 1000;
if(userNativeLCCode.second == taskTargetLocale.countrycode()) {
score += 100;
}
}
if(userSecondaryLanguages.contains(usersIter.key())) {
const QList<LCCode> lcCodes = userSecondaryLanguages.values(usersIter.key());
if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), LidMatch(taskSourceLocale.languagecode()))) {
score += 500;
if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), CidMatch(taskSourceLocale.countrycode())) ) {
score += 50;
}
}
if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), LidMatch(taskTargetLocale.languagecode()))) {
score += 500;
if(lcCodes.end() != std::find_if(lcCodes.begin(), lcCodes.end(), CidMatch(taskTargetLocale.countrycode())) ) {
score += 50;
}
}
}
if(userTags.contains(usersIter.key()) && taskTags.contains(task->id())) {
int increment_value = 250;
QList<int> userTagIds = userTags.values(usersIter.key());
QList<int> userTaskTagIds = taskTags.values(task->id());
foreach(int userTagId, userTagIds) {
if(userTaskTagIds.contains(userTagId)) {
score += increment_value;
increment_value *= 0.75;
}
}
}
QDateTime created_time = QDateTime::fromString(
QString::fromStdString(task->createdtime()), Qt::ISODate);
//increase score by one per day since created time
score += created_time.daysTo(QDateTime::currentDateTime());
taskScores.append(TaskScore(task->id(), score));
}
this->saveUserTaskScore(usersIter.key(),taskScores);
} else {
示例6: main
//.........这里部分代码省略.........
QgsEditorWidgetRegistry::initEditors();
while ( fcgi_accept() >= 0 )
{
QgsMapLayerRegistry::instance()->removeAllMapLayers();
qgsapp.processEvents();
if ( logLevel < 1 )
{
time.start();
printRequestInfos();
}
//Request handler
QScopedPointer<QgsRequestHandler> theRequestHandler( createRequestHandler() );
try
{
// TODO: split parse input into plain parse and processing from specific services
theRequestHandler->parseInput();
}
catch ( QgsMapServiceException& e )
{
QgsMessageLog::logMessage( "Parse input exception: " + e.message(), "Server", QgsMessageLog::CRITICAL );
theRequestHandler->setServiceException( e );
}
#ifdef HAVE_SERVER_PYTHON_PLUGINS
// Set the request handler into the interface for plugins to manipulate it
serverIface.setRequestHandler( theRequestHandler.data() );
// Iterate filters and call their requestReady() method
QgsServerFiltersMap::const_iterator filtersIterator;
for ( filtersIterator = pluginFilters.constBegin(); filtersIterator != pluginFilters.constEnd(); ++filtersIterator )
{
filtersIterator.value()->requestReady();
}
//Pass the filters to the requestHandler, this is needed for the following reasons:
// 1. allow core services to access plugin filters and implement thir own plugin hooks
// 2. allow requestHandler to call sendResponse plugin hook
//TODO: implement this in the requestHandler ctor (far easier if we will get rid of
// HAVE_SERVER_PYTHON_PLUGINS
theRequestHandler->setPluginFilters( pluginFilters );
#endif
// Copy the parameters map
QMap<QString, QString> parameterMap( theRequestHandler->parameterMap() );
printRequestParameters( parameterMap, logLevel );
QMap<QString, QString>::const_iterator paramIt;
//Config file path
QString configFilePath = configPath( defaultConfigFilePath, parameterMap );
//Service parameter
QString serviceString = theRequestHandler->parameter( "SERVICE" );
if ( serviceString.isEmpty() )
{
// SERVICE not mandatory for WMS 1.3.0 GetMap & GetFeatureInfo
QString requestString = theRequestHandler->parameter( "REQUEST" );
if ( requestString == "GetMap" || requestString == "GetFeatureInfo" )
{
serviceString = "WMS";
}
}
示例7: loader
/*!
\internal
Returns a lazily-initialized singleton. Ownership is granted to the
QPlatformPrinterSupportPlugin, which is never unloaded or destroyed until
application exit, i.e. you can expect this pointer to always be valid and
multiple calls to this function will always return the same pointer.
*/
QPlatformPrinterSupport *QPlatformPrinterSupportPlugin::get()
{
if (!printerSupport) {
const QMultiMap<int, QString> keyMap = loader()->keyMap();
if (!keyMap.isEmpty())
printerSupport = qLoadPlugin<QPlatformPrinterSupport, QPlatformPrinterSupportPlugin>(loader(), keyMap.constBegin().value());
if (printerSupport)
qAddPostRoutine(cleanupPrinterSupport);
}
return printerSupport;
}
示例8: text
void
FormMain::folderChanged( QTreeWidgetItem * current, QTreeWidgetItem * )
{
editInfo->clear();
if ( ! current )
return;
const int folder_id = current->data( 0, Qt::UserRole ).toInt();
QString text("Folder: ");
QSqlQuery q;
// self
q.prepare("SELECT "
"name, "
"path, "
"size "
"FROM "
"folders "
"WHERE "
"id = :id ");
q.bindValue(":id", folder_id );
if ( q.exec() ) {
if ( q.first() )
text += q.value( 0 ).toString() + "<BR>" +
"Path: " + q.value( 1 ).toString() + "<BR>" +
"Size: " + prettyPrint( q.value( 2 ).toLongLong() ) + "<BR>";
} else {
emit yell( q.lastError().text() );
return;
}
// count of folders
int folderCount = 0;
countFolders( folder_id, folderCount );
// count of types
int typeCount = 0;
QHash< QString, int > types;
countTypes( folder_id, types, typeCount );
// ordering
QMultiMap< int, QString > typesMap;
QHash< QString, int >::const_iterator h = types.constBegin();
while ( h != types.constEnd() ) {
typesMap.insert( h.value(), h.key() );
++h;
}
// percent of folders
text += tr("folders: %1 (%2%)<BR>")
.arg( folderCount )
.arg( folderCount / ( qreal )( folderCount + typeCount ) * 100., 0, 'f', 1 );
// percents of files
chart->clear();
if ( typesMap.count() > 0 ) {
QMultiMap< int, QString >::const_iterator mm = typesMap.constEnd();
do {
--mm;
const qreal percent = mm.key() / ( qreal )( folderCount + typeCount ) * 100;
text += tr("%1: %2 (%3%)<BR>")
.arg( mm.value() )
.arg( mm.key() )
.arg( percent, 0, 'f', 1 );
chart->addPiece( percent, mm.value() );
} while ( mm != typesMap.constBegin() );
}
text += QString( 50, '-' ) + "<BR>"; // horizontal line -------
// folders
text += "<BR><B>folders:</B><BR>";
q.prepare("SELECT "
"name, "
"size "
"FROM "
"folders "
"WHERE "
"parent_id = :id "
"ORDER BY "
"size DESC");
q.bindValue(":id", folder_id );
if ( q.exec() ) {
//.........这里部分代码省略.........
示例9: QWidget
NotifyKindOptionsWidget::NotifyKindOptionsWidget(INotifications *ANotifications, QWidget *AParent) : QWidget(AParent)
{
FNotifications = ANotifications;
tbwNotifies = new QTableWidget(this);
tbwNotifies->setWordWrap(true);
tbwNotifies->verticalHeader()->setVisible(false);
tbwNotifies->horizontalHeader()->setHighlightSections(false);
tbwNotifies->setSelectionMode(QTableWidget::NoSelection);
connect(tbwNotifies,SIGNAL(itemChanged(QTableWidgetItem *)),SIGNAL(modified()));
tbwNotifies->setColumnCount(NTC__COUNT);
tbwNotifies->setHorizontalHeaderLabels(QStringList() << tr("Event") << "" << "" << "" << "" );
tbwNotifies->horizontalHeader()->SETRESIZEMODE(NTC_TYPE,QHeaderView::Stretch);
tbwNotifies->horizontalHeader()->SETRESIZEMODE(NTC_SOUND,QHeaderView::ResizeToContents);
tbwNotifies->horizontalHeaderItem(NTC_SOUND)->setToolTip(tr("Play sound at the notification"));
tbwNotifies->horizontalHeaderItem(NTC_SOUND)->setIcon(IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_NOTIFICATIONS_SOUNDPLAY));
tbwNotifies->horizontalHeader()->SETRESIZEMODE(NTC_POPUP,QHeaderView::ResizeToContents);
tbwNotifies->horizontalHeaderItem(NTC_POPUP)->setToolTip(tr("Display a notification in popup window"));
tbwNotifies->horizontalHeaderItem(NTC_POPUP)->setIcon(IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_NOTIFICATIONS_PUPUPWINDOW));
tbwNotifies->horizontalHeader()->SETRESIZEMODE(NTC_MINIMIZED,QHeaderView::ResizeToContents);
tbwNotifies->horizontalHeaderItem(NTC_MINIMIZED)->setToolTip(tr("Show the corresponding window minimized in the taskbar"));
tbwNotifies->horizontalHeaderItem(NTC_MINIMIZED)->setIcon(IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_NOTIFICATIONS_SHOWMINIMIZED));
tbwNotifies->horizontalHeader()->SETRESIZEMODE(NTC_TRAY,QHeaderView::ResizeToContents);
tbwNotifies->horizontalHeaderItem(NTC_TRAY)->setToolTip(tr("Display a notification icon in the system tray"));
tbwNotifies->horizontalHeaderItem(NTC_TRAY)->setIcon(IconStorage::staticStorage(RSR_STORAGE_MENUICONS)->getIcon(MNI_NOTIFICATIONS_TRAYICON));
QVBoxLayout *vblLayout = new QVBoxLayout(this);
vblLayout->addWidget(tbwNotifies);
vblLayout->setMargin(0);
QMultiMap<int, NotificationType> orderedTypes;
ushort visibleKinds = INotification::PopupWindow|INotification::TrayNotify|INotification::SoundPlay|INotification::ShowMinimized;
foreach(const QString &typeId, FNotifications->notificationTypes())
{
NotificationType notifyType = FNotifications->notificationType(typeId);
if (!notifyType.title.isEmpty() && (notifyType.kindMask & visibleKinds)>0)
{
notifyType.typeId = typeId;
orderedTypes.insertMulti(notifyType.order,notifyType);
}
}
for (QMultiMap<int, NotificationType>::const_iterator it=orderedTypes.constBegin(); it!=orderedTypes.constEnd(); ++it)
{
int row = tbwNotifies->rowCount();
tbwNotifies->setRowCount(row+1);
QTableWidgetItem *type = new QTableWidgetItem(it->icon,it->title);
type->setData(NTR_TYPE, it->typeId);
type->setFlags(Qt::ItemIsEnabled);
tbwNotifies->setItem(row,NTC_TYPE,type);
QTableWidgetItem *sound = new QTableWidgetItem();
sound->setData(NTR_KIND, INotification::SoundPlay);
if (it->kindMask & INotification::SoundPlay)
sound->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
else
sound->setFlags(Qt::ItemIsUserCheckable);
sound->setCheckState(Qt::Unchecked);
tbwNotifies->setItem(row,NTC_SOUND,sound);
QTableWidgetItem *popup = new QTableWidgetItem();
popup->setData(NTR_KIND, INotification::PopupWindow);
if (it->kindMask & INotification::PopupWindow)
popup->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
else
popup->setFlags(Qt::ItemIsUserCheckable);
popup->setCheckState(Qt::Unchecked);
tbwNotifies->setItem(row,NTC_POPUP,popup);
QTableWidgetItem *minimized = new QTableWidgetItem();
minimized->setData(NTR_KIND, INotification::ShowMinimized);
if (it->kindMask & INotification::ShowMinimized)
minimized->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
else
minimized->setFlags(Qt::ItemIsUserCheckable);
minimized->setCheckState(Qt::Unchecked);
tbwNotifies->setItem(row,NTC_MINIMIZED,minimized);
tbwNotifies->verticalHeader()->SETRESIZEMODE(row,QHeaderView::ResizeToContents);
QTableWidgetItem *tray = new QTableWidgetItem();
tray->setData(NTR_KIND, INotification::TrayNotify);
if (it->kindMask & INotification::TrayNotify)
tray->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
else
tray->setFlags(Qt::ItemIsUserCheckable);
tray->setCheckState(Qt::Unchecked);
tbwNotifies->setItem(row,NTC_TRAY,tray);
tbwNotifies->verticalHeader()->SETRESIZEMODE(row,QHeaderView::ResizeToContents);
}
reset();
}
示例10: shuffleTracks
void Playlist::shuffleTracks(MusicPlayer::ShuffleMode shuffleMode)
{
m_shuffledSongs.clear();
switch (shuffleMode)
{
case MusicPlayer::SHUFFLE_RANDOM:
{
QMultiMap<int, MusicMetadata*> songMap;
SongList::const_iterator it = m_songs.begin();
for (; it != m_songs.end(); ++it)
{
songMap.insert(rand(), *it);
}
QMultiMap<int, MusicMetadata*>::const_iterator i = songMap.constBegin();
while (i != songMap.constEnd())
{
m_shuffledSongs.append(i.value());
++i;
}
break;
}
case MusicPlayer::SHUFFLE_INTELLIGENT:
{
int RatingWeight = 2;
int PlayCountWeight = 2;
int LastPlayWeight = 2;
int RandomWeight = 2;
m_parent->FillIntelliWeights(RatingWeight, PlayCountWeight,
LastPlayWeight, RandomWeight);
// compute max/min playcount,lastplay for this playlist
int playcountMin = 0;
int playcountMax = 0;
double lastplayMin = 0.0;
double lastplayMax = 0.0;
uint idx = 0;
SongList::const_iterator it = m_songs.begin();
for (; it != m_songs.end(); ++it, ++idx)
{
if (!(*it)->isCDTrack())
{
MusicMetadata *mdata = (*it);
if (0 == idx)
{
// first song
playcountMin = playcountMax = mdata->PlayCount();
lastplayMin = lastplayMax = mdata->LastPlay().toTime_t();
}
else
{
if (mdata->PlayCount() < playcountMin)
playcountMin = mdata->PlayCount();
else if (mdata->PlayCount() > playcountMax)
playcountMax = mdata->PlayCount();
if (mdata->LastPlay().toTime_t() < lastplayMin)
lastplayMin = mdata->LastPlay().toTime_t();
else if (mdata->LastPlay().toTime_t() > lastplayMax)
lastplayMax = mdata->LastPlay().toTime_t();
}
}
}
// next we compute all the weights
std::map<int,double> weights;
std::map<int,int> ratings;
std::map<int,int> ratingCounts;
int TotalWeight = RatingWeight + PlayCountWeight + LastPlayWeight;
for (int trackItI = 0; trackItI < m_songs.size(); ++trackItI)
{
MusicMetadata *mdata = m_songs[trackItI];
if (!mdata->isCDTrack())
{
int rating = mdata->Rating();
int playcount = mdata->PlayCount();
double lastplaydbl = mdata->LastPlay().toTime_t();
double ratingValue = (double)(rating) / 10;
double playcountValue, lastplayValue;
if (playcountMax == playcountMin)
playcountValue = 0;
else
playcountValue = ((playcountMin - (double)playcount) / (playcountMax - playcountMin) + 1);
if (lastplayMax == lastplayMin)
lastplayValue = 0;
else
lastplayValue = ((lastplayMin - lastplaydbl) / (lastplayMax - lastplayMin) + 1);
double weight = (RatingWeight * ratingValue +
PlayCountWeight * playcountValue +
LastPlayWeight * lastplayValue) / TotalWeight;
weights[mdata->ID()] = weight;
//.........这里部分代码省略.........
示例11: signRequest
QByteArray Token::signRequest(const QUrl& requestUrl, Token::AuthMethod authMethod, Token::HttpMethod method, const QMultiMap<QString, QString>& parameters) const
{
QString timestamp;
QString nonce;
if (d->consumerKey == "test_token") { // Set known values for unit-testing
timestamp = "1234567890"; //Feb 13, 2009, 23:31:30 GMT
nonce = "ABCDEF";
} else {
#if QT_VERSION >= 0x040700
timestamp = QString::number(QDateTime::currentDateTimeUtc().toTime_t());
#else
timestamp = QString::number(QDateTime::currentDateTime().toUTC().toTime_t());
#endif
nonce = QString::number(qrand());
}
if (!requestUrl.isValid()) {
qWarning() << "OAuth::Token: Invalid url. The request will probably be invalid";
}
// Step 1. Get all the oauth params for this request
QMultiMap<QString, QString> oauthParams;
oauthParams.insert("oauth_consumer_key", d->consumerKey);
if(d->serviceType == "dbox")
oauthParams.insert("oauth_signature_method", "PLAINTEXT");
else
oauthParams.insert("oauth_signature_method", "HMAC-SHA1");
oauthParams.insert("oauth_timestamp", timestamp);
oauthParams.insert("oauth_nonce", nonce);
oauthParams.insert("oauth_version", "1.0");
switch (d->tokenType) {
case Token::InvalidToken:
oauthParams.insert("oauth_callback", d->callbackUrl.toString());
break;
case Token::RequestToken:
oauthParams.insert("oauth_token", d->oauthToken);
oauthParams.insert("oauth_verifier", d->oauthVerifier);
break;
case Token::AccessToken:
oauthParams.insert("oauth_token", d->oauthToken);
break;
}
// Step 2. Take the parameters from the url, and add the oauth params to them
QMultiMap<QString, QString> allParams = oauthParams;
QList<QPair<QString, QString> > queryItems = requestUrl.queryItems();
for(int i = 0; i < queryItems.count(); ++i) {
allParams.insert(queryItems[i].first, queryItems[i].second);
}
allParams.unite(parameters);
// Step 3. Calculate the signature from those params, and append the signature to the oauth params
QString signature = generateSignature(requestUrl, allParams, method);
oauthParams.insert("oauth_signature", signature);
// Step 4. Concatenate all oauth params into one comma-separated string
QByteArray authHeader;
if (authMethod == Sasl) {
authHeader = "GET ";
authHeader.append(requestUrl.toString() + " ");
} else {
authHeader = "OAuth ";
}
QMultiMap<QString, QString>::const_iterator p = oauthParams.constBegin();
while (p != oauthParams.constEnd()) {
authHeader += QString("%1=\"%2\",").arg(p.key()).arg(encode(p.value()));
++p;
}
authHeader.chop(1); // remove the last character (the trailing ",")
return authHeader;
}