当前位置: 首页>>代码示例>>C++>>正文


C++ QMap::contains方法代码示例

本文整理汇总了C++中QMap::contains方法的典型用法代码示例。如果您正苦于以下问题:C++ QMap::contains方法的具体用法?C++ QMap::contains怎么用?C++ QMap::contains使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QMap的用法示例。


在下文中一共展示了QMap::contains方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: onCustomContextMenuRequested

void LibraryTreeWidget::onCustomContextMenuRequested(const QPoint& pos)
{
	QMenu menu(this);

	bool file = false;
	bool folder = false;
	bool project = false;

	int size = selectedItems().size();

	for (int i = 0; i < selectedItems().size(); ++i)
	{
		if (selectedItems()[i]->parent() == NULL)
		{
			project = true;
		}
		else
		{
			QString fileName = selectedItems()[i]->data(0, Qt::UserRole).toMap()["filename"].toString();

			if (fileName.isEmpty() == true)
				folder = true;
			else
				file = true;
		}
	}

	if (size == 1 && (folder || project))
	{
		menu.addAction(addNewFileAction_);
		menu.addAction(importToLibraryAction_);
		menu.addAction(newFolderAction_);
	}

	if (size > 0 && !project)
		menu.addAction(removeAction_);
	if (size == 1 && folder)
		menu.addAction(renameAction_);
	if (size == 1 && (folder || project))
		menu.addAction(sortAction_);

	if (size == 1 && file)
	{
		menu.addAction(insertIntoDocumentAction_);

		QMap<QString, QVariant> data = selectedItems()[0]->data(0, Qt::UserRole).toMap();

		QString fileName = data["filename"].toString();

		QFileInfo fileInfo(fileName);

		QString ext = fileInfo.suffix().toLower();

		if (ext == "lua")
        {
            menu.addAction(codeDependenciesAction_);
            bool excludeFromExecution = data.contains("excludeFromExecution") && data["excludeFromExecution"].toBool();
            excludeFromExecutionAction_->setChecked(excludeFromExecution);
            menu.addAction(excludeFromExecutionAction_);
        }

		if (ext == "png" || ext == "jpg" || ext == "jpeg")
		{
			bool downsizing = data.contains("downsizing") && data["downsizing"].toBool();
			automaticDownsizingAction_->setChecked(downsizing);
			menu.addAction(automaticDownsizingAction_);
		}
	}

	if (size == 1 && project)
		menu.addAction(projectPropertiesAction_);

	if (!menu.isEmpty())
		menu.exec(QCursor::pos());
}
开发者ID:dev-life,项目名称:gideros,代码行数:75,代码来源:librarytreewidget.cpp

示例2: note

void MsScWriter::note(const QString pitch, const QVector<Bww::BeamType> beamList,
                      const QString type, const int dots,
                      bool tieStart, bool /*TODO tieStop */,
                      StartStop triplet,
                      bool grace)
      {
      qDebug() << "MsScWriter::note()"
               << "type:" << type
               << "dots:" << dots
               << "grace" << grace
      ;

      if (!stepAlterOctMap.contains(pitch)
          || !typeMap.contains(type)) {
            // TODO: error message
            return;
            }
      StepAlterOct sao = stepAlterOctMap.value(pitch);

      int ticks = 4 * Ms::MScore::division / type.toInt();
      if (dots) ticks = 3 * ticks / 2;
      qDebug() << "ticks:" << ticks;
      Ms::TDuration durationType(Ms::TDuration::DurationType::V_INVALID);
      durationType.setVal(ticks);
      qDebug() << "duration:" << durationType.name();
      if (triplet != ST_NONE) ticks = 2 * ticks / 3;

      Ms::Beam::Mode bm  = (beamList.at(0) == Bww::BM_BEGIN) ? Ms::Beam::Mode::BEGIN : Ms::Beam::Mode::AUTO;
      Ms::Direction sd = Ms::Direction::AUTO;

      // create chord
      Ms::Chord* cr = new Ms::Chord(score);
      //ws cr->setTick(tick);
      cr->setBeamMode(bm);
      cr->setTrack(0);
      if (grace) {
            cr->setNoteType(Ms::NoteType::GRACE32);
            cr->setDurationType(Ms::TDuration::DurationType::V_32ND);
            sd = Ms::Direction::UP;
            }
      else {
            if (durationType.type() == Ms::TDuration::DurationType::V_INVALID)
                  durationType.setType(Ms::TDuration::DurationType::V_QUARTER);
            cr->setDurationType(durationType);
            sd = Ms::Direction::DOWN;
            }
      cr->setDuration(durationType.fraction());
      cr->setDots(dots);
      cr->setStemDirection(sd);
      // add note to chord
      Ms::Note* note = new Ms::Note(score);
      note->setTrack(0);
      xmlSetPitch(note, sao.s.toLatin1(), sao.a, sao.o);
      if (tieStart) {
            Ms::Tie* tie = new Ms::Tie(score);
            note->setTieFor(tie);
            tie->setStartNote(note);
            tie->setTrack(0);
            }
      cr->add(note);
      // add chord to measure
      if (!grace) {
            Ms::Segment* s = currentMeasure->getSegment(Ms::Segment::Type::ChordRest, tick);
            s->add(cr);
            if (!currentGraceNotes.isEmpty()) {
                  for (int i = currentGraceNotes.size() - 1; i >=0; i--)
                        cr->add(currentGraceNotes.at(i));
                  currentGraceNotes.clear();
                  }
            doTriplet(cr, triplet);
            int tickBefore = tick;
            tick += ticks;
            Ms::Fraction nl(Ms::Fraction::fromTicks(tick - currentMeasure->tick()));
            currentMeasure->setLen(nl);
            qDebug() << "MsScWriter::note()"
                     << "tickBefore:" << tickBefore
                     << "tick:" << tick
                     << "nl:" << nl.print()
            ;
            }
      else {
            currentGraceNotes.append(cr);
            }
      }
开发者ID:trig-ger,项目名称:MuseScore,代码行数:84,代码来源:importbww.cpp

示例3: pickedPolygon

void
rce::gui::RImageMarkerScene::
mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
    if(mouseEvent->button() == Qt::LeftButton)
    {
        const QGraphicsView *eventView = NULL;
        if(mouseEvent->widget() != NULL)
        {
            eventView = dynamic_cast<const QGraphicsView*>(mouseEvent->widget()->parentWidget());
        }

        QTransform viewTransform;
        if(eventView != NULL)
        {
            viewTransform = eventView->transform();
        }

        itemEdited_ = false;
        switch(mode_)
        {
            case rce::gui::RImageMarkerScene::DrawPointMode:
                {
                    // check if there is handle under mouse
                    QList<QGraphicsItem *> itemsUnderMouse = items(rce::gui::getSceneRectAroundScreenPos(mouseEvent->screenPos(),
                                                                                                         mouseEvent->scenePos(),
                                                                                                         dynamic_cast<const QGraphicsView*>(mouseEvent->widget()->parentWidget())),
                                                                   Qt::IntersectsItemBoundingRect,
                                                                   Qt::DescendingOrder,
                                                                   viewTransform);
                    QGraphicsItem *handle = NULL;
                    for(int i = 0; i < itemsUnderMouse.size(); ++i)
                    {
                        if((itemsUnderMouse[i]->data(RCE_ITEM_TYPE_DATA_INDEX).toUInt() == HandleType)
                           && itemsUnderMouse[i]->boundingRect().contains(itemsUnderMouse[i]->mapFromScene(mouseEvent->scenePos())))
                        {
                            handle = itemsUnderMouse[i];
                            break;
                        }
                    }

                    if(handle != NULL)
                    { // there is handle, set is as active
                        activeHandleIdx_ = 0;
                    }
                    else
                    {
                        activeHandleIdx_ = -1;
                    }
                }
                break;
            case rce::gui::RImageMarkerScene::DrawPolygonMode:
            case rce::gui::RImageMarkerScene::DrawPolylineMode:
                {
                    // check if there is handle under mouse
                    QList<QGraphicsItem *> itemsUnderMouse = items(rce::gui::getSceneRectAroundScreenPos(mouseEvent->screenPos(),
                                                                                                         mouseEvent->scenePos(),
                                                                                                         dynamic_cast<const QGraphicsView*>(mouseEvent->widget()->parentWidget())),
                                                                   Qt::IntersectsItemBoundingRect,
                                                                   Qt::DescendingOrder,
                                                                   viewTransform);
                    QGraphicsItem *handle = NULL;
                    for(int i = 0; i < itemsUnderMouse.size(); ++i)
                    {
                        if((itemsUnderMouse[i]->data(RCE_ITEM_TYPE_DATA_INDEX).toUInt() == HandleType)
                           && itemsUnderMouse[i]->boundingRect().contains(itemsUnderMouse[i]->mapFromScene(mouseEvent->scenePos())))
                        {
                            handle = itemsUnderMouse[i];
                            break;
                        }
                    }

                    if(handle != NULL)
                    { // there is handle, set is as active
                        activeHandleIdx_ = handle->data(RCE_ITEM_ID_DATA_INDEX).toInt();
                    }
                    else
                    { // there is not handle - create new
                        addControlPoint(mouseEvent->scenePos());
                        itemEdited_ = true;
                        activeHandleIdx_ = handles_.size() - 1;
                    }
                }
                break;
            case rce::gui::RImageMarkerScene::PickPolygonMode:
            case rce::gui::RImageMarkerScene::PickPolylineMode:
            case rce::gui::RImageMarkerScene::PickPointMode:
            case rce::gui::RImageMarkerScene::PickAnyMode:
                {
                    QVector<quint32> polygons;
                    QVector<quint32> polylines;
                    QVector<quint32> points;

                    getItemsAtPosition(rce::gui::getSceneRectAroundScreenPos(mouseEvent->screenPos(),
                                                                             mouseEvent->scenePos(),
                                                                             dynamic_cast<const QGraphicsView*>(mouseEvent->widget()->parentWidget())),
                                       polygons,
                                       polylines,
                                       points,
                                       viewTransform);
//.........这里部分代码省略.........
开发者ID:Timie,项目名称:PositionEstimationAccuracy,代码行数:101,代码来源:RImageMarkerScene.cpp

示例4: contextMenuEvent

void FriendWidget::contextMenuEvent(QContextMenuEvent * event)
{
    QPoint pos = event->globalPos();
    QString id = Core::getInstance()->getFriendAddress(friendId);
    QString dir = Settings::getInstance().getAutoAcceptDir(id);
    QMenu menu;
    QMenu* inviteMenu = menu.addMenu(tr("Invite to group","Menu to invite a friend to a groupchat"));
    QAction* copyId = menu.addAction(tr("Copy friend ID","Menu to copy the Tox ID of that friend"));
    QMap<QAction*, Group*> groupActions;
    
    for (Group* group : GroupList::groupList)
    {
        QAction* groupAction = inviteMenu->addAction(group->widget->getName());
        groupActions[groupAction] =  group;
    }
    
    if (groupActions.isEmpty())
        inviteMenu->setEnabled(false);
    
    QAction* setAlias = menu.addAction(tr("Set alias..."));

    menu.addSeparator();
    QAction* autoAccept = menu.addAction(tr("Auto accept files from this friend", "context menu entry"));
    autoAccept->setCheckable(true);
    autoAccept->setChecked(!dir.isEmpty());
    menu.addSeparator();
    
    QAction* removeFriendAction = menu.addAction(tr("Remove friend", "Menu to remove the friend from our friendlist"));

    QAction* selectedItem = menu.exec(pos);
    if (selectedItem)
    {
        if (selectedItem == copyId)
        {
            emit copyFriendIdToClipboard(friendId);
            return;
        } else if (selectedItem == setAlias)
        {
            setFriendAlias();
        }
        else if (selectedItem == removeFriendAction)
        {
            hide();
            show(); //Toggle visibility to work around bug of repaintEvent() not being fired on parent widget when this is hidden
            hide();
            emit removeFriend(friendId);
            return;
        }
        else if (selectedItem == autoAccept)
        {
            if (!autoAccept->isChecked())
            {
                qDebug() << "not checked";
                dir = QDir::homePath();
                autoAccept->setChecked(false);
                Settings::getInstance().setAutoAcceptDir(id, "");
            }
            
            if (autoAccept->isChecked())
            {
                dir = QFileDialog::getExistingDirectory(0, tr("Choose an auto accept directory","popup title"), dir);
                autoAccept->setChecked(true);
                qDebug() << "FriendWidget: setting auto accept dir for" << friendId << "to" << dir;
                Settings::getInstance().setAutoAcceptDir(id, dir);
            }
        }
        else if (groupActions.contains(selectedItem))
        {
            Group* group = groupActions[selectedItem];
            Core::getInstance()->groupInviteFriend(friendId, group->groupId);
        }
    }
}
开发者ID:darkcoconuts,项目名称:qTox,代码行数:73,代码来源:friendwidget.cpp

示例5: init

GPGME_Error GPGME::init(const QString & gpgHomeDir)
{
    if (instancesStore.contains(gpgHomeDir)) {
        return GPG_ERR_NO_ERROR;
    }

    setlocale(LC_ALL, "");
    gpgme_check_version(NULL);
    gpgme_set_locale(NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL));
#ifdef LC_MESSAGES
    gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL));
#endif

    gpgme_error_t err;
    gpgme_ctx_t context;

    err = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
    if (err != GPG_ERR_NO_ERROR) {
        return err;
    }

    QString protocolName =  gpgme_get_protocol_name(GPGME_PROTOCOL_OpenPGP);
    qDebug() << "protocol: " << protocolName;

    gpgme_engine_info_t engineInfo;
    err = gpgme_get_engine_info(&engineInfo);
    if (err != GPG_ERR_NO_ERROR) {
        return err;
    }
    qDebug() << "Backend info";
    qDebug() << "filename: " << engineInfo->file_name << ", homedir: " << engineInfo->home_dir;

    err = gpgme_new(&context);
    if (err != GPG_ERR_NO_ERROR) {
        return err;
    }

    err = gpgme_set_protocol(context, GPGME_PROTOCOL_OpenPGP);
    if (err != GPG_ERR_NO_ERROR) {
        return err;
    }

    // we don't need to set gnupg home dir explicitly
    QString gnupgHome;
    if (gpgHomeDir.isEmpty()) {
        // i.e. use default gnupg directory or one from environment
        QString gnupgHomeEnv = QString::fromLatin1(qgetenv("GNUPGHOME"));
        if (!gnupgHomeEnv.isEmpty()) {
            gnupgHome = gnupgHomeEnv;
        } else {
            // use default path: "~/.gnupg"
            QDir gh = QDir::home();
            gh.cd(".gnupg");
            gnupgHome = gh.canonicalPath();
        }
    } else {
        QDir gh(gpgHomeDir);
        gnupgHome = gh.canonicalPath();
    }
    qDebug() << "GNUPGHOME" << gnupgHome;
    
    err = gpgme_ctx_set_engine_info(context, GPGME_PROTOCOL_OpenPGP, 
            engineInfo->file_name,
            gnupgHome.toLatin1().data()
            );
    if (err != GPG_ERR_NO_ERROR) {
        return err;
    }

    GPGME * inst = new GPGME(context, gnupgHome);
    instancesStore[gpgHomeDir] = inst;
    qDebug() << "gpgme initalized for the directory " << gnupgHome << "[store key: " << gpgHomeDir << "]";

    return GPG_ERR_NO_ERROR;
}
开发者ID:sigsergv,项目名称:guzum,代码行数:75,代码来源:gpgmewrapper.cpp

示例6: processGameCommandContainer

Response::ResponseCode Server_ProtocolHandler::processGameCommandContainer(const CommandContainer &cont, ResponseContainer &rc)
{
    static QList<GameCommand::GameCommandType> antifloodCommandsWhiteList = QList<GameCommand::GameCommandType>()
        // draw/undo card draw (example: drawing 10 cards one by one from the deck)
        << GameCommand::DRAW_CARDS
        << GameCommand::UNDO_DRAW
        // create, delete arrows (example: targeting with 10 cards during an attack)
        << GameCommand::CREATE_ARROW
        << GameCommand::DELETE_ARROW
        // set card attributes (example: tapping 10 cards at once)
        << GameCommand::SET_CARD_ATTR
        // increment / decrement counter (example: -10 life points one by one)
        << GameCommand::INC_COUNTER
        // mulling lots of hands in a row
        << GameCommand::MULLIGAN
        // allows a user to sideboard without receiving flooding message
        << GameCommand::MOVE_CARD;

    if (authState == NotLoggedIn)
        return Response::RespLoginNeeded;

    QMap<int, QPair<int, int> > gameMap = getGames();
    if (!gameMap.contains(cont.game_id()))
        return Response::RespNotInRoom;
    const QPair<int, int> roomIdAndPlayerId = gameMap.value(cont.game_id());

    QReadLocker roomsLocker(&server->roomsLock);
    Server_Room *room = server->getRooms().value(roomIdAndPlayerId.first);
    if (!room)
        return Response::RespNotInRoom;

    QReadLocker roomGamesLocker(&room->gamesLock);
    Server_Game *game = room->getGames().value(cont.game_id());
    if (!game) {
        if (room->getExternalGames().contains(cont.game_id())) {
            server->sendIsl_GameCommand(cont,
                                        room->getExternalGames().value(cont.game_id()).server_id(),
                                        userInfo->session_id(),
                                        roomIdAndPlayerId.first,
                                        roomIdAndPlayerId.second
                                        );
            return Response::RespNothing;
        }
        return Response::RespNotInRoom;
    }

    QMutexLocker gameLocker(&game->gameMutex);
    Server_Player *player = game->getPlayers().value(roomIdAndPlayerId.second);
    if (!player)
        return Response::RespNotInRoom;

    int commandCountingInterval = server->getCommandCountingInterval();
    int maxCommandCountPerInterval = server->getMaxCommandCountPerInterval();
    GameEventStorage ges;
    Response::ResponseCode finalResponseCode = Response::RespOk;
    for (int i = cont.game_command_size() - 1; i >= 0; --i) {
        const GameCommand &sc = cont.game_command(i);
        logDebugMessage(QString("game %1 player %2: ").arg(cont.game_id()).arg(roomIdAndPlayerId.second) + QString::fromStdString(sc.ShortDebugString()));

        if (commandCountingInterval > 0) {
            int totalCount = 0;
            if (commandCountOverTime.isEmpty())
                commandCountOverTime.prepend(0);

            if(!antifloodCommandsWhiteList.contains((GameCommand::GameCommandType) getPbExtension(sc)))
                ++commandCountOverTime[0];

            for (int i = 0; i < commandCountOverTime.size(); ++i)
                totalCount += commandCountOverTime[i];

            if (totalCount > maxCommandCountPerInterval)
                return Response::RespChatFlood;
        }

        Response::ResponseCode resp = player->processGameCommand(sc, rc, ges);

        if (resp != Response::RespOk)
            finalResponseCode = resp;
    }
    ges.sendToGame(game);

    return finalResponseCode;
}
开发者ID:MRH4287,项目名称:Cockatrice,代码行数:83,代码来源:server_protocolhandler.cpp

示例7: xmppStanzaIn

bool SASLAuthFeature::xmppStanzaIn(IXmppStream *AXmppStream, Stanza &AStanza, int AOrder)
{
	if (AXmppStream==FXmppStream && AOrder==XSHO_XMPP_FEATURE)
	{
		if (AStanza.kind() == "challenge")
		{
			QByteArray challengeData = QByteArray::fromBase64(AStanza.element().text().toLatin1());
			LOG_STRM_DEBUG(FXmppStream->streamJid(),QString("SASL auth challenge received: %1").arg(QString::fromUtf8(challengeData)));
			
			QMap<QByteArray, QByteArray> responseMap;
			QMap<QByteArray, QByteArray> challengeMap = parseChallenge(challengeData);
			if (challengeMap.value("qop") == "auth")
			{
				QByteArray randBytes(32,' ');
				for (int i=0; i<randBytes.size(); i++)
					randBytes[i] = (char) (256.0 * qrand() / (RAND_MAX + 1.0));

				responseMap["cnonce"] = randBytes.toHex();
				if (challengeMap.contains("realm"))
					responseMap["realm"] = challengeMap.value("realm");
				else
					responseMap["realm"] = FXmppStream->streamJid().pDomain().toUtf8();
				responseMap["username"] = FXmppStream->streamJid().pNode().toUtf8();
				responseMap["nonce"] = challengeMap.value("nonce");
				responseMap["nc"] = "00000001";
				responseMap["qop"] = "auth";
				responseMap["digest-uri"] = QString("xmpp/%1").arg(FXmppStream->streamJid().pDomain()).toUtf8();
				responseMap["charset"] = "utf-8";
				responseMap["response"] = getResponseValue(responseMap,FXmppStream->password());
			}
			QByteArray responseData = serializeResponse(responseMap);

			Stanza response("response",NS_FEATURE_SASL);
			response.element().appendChild(response.createTextNode(responseData.toBase64()));
			FXmppStream->sendStanza(response);

			LOG_STRM_DEBUG(FXmppStream->streamJid(),QString("SASL auth response sent: %1").arg(QString::fromUtf8(responseData)));
		}
		else
		{
			FXmppStream->removeXmppStanzaHandler(XSHO_XMPP_FEATURE,this);
			if (AStanza.kind() == "success")
			{
				LOG_STRM_INFO(FXmppStream->streamJid(),"Authorization successes");
				deleteLater();
				emit finished(true);
			}
			else if (AStanza.kind() == "failure")
			{
				XmppSaslError err(AStanza.element());
				LOG_STRM_WARNING(FXmppStream->streamJid(),QString("Authorization failed: %1").arg(err.condition()));
				emit error(err);
			}
			else
			{
				XmppError err(IERR_SASL_AUTH_INVALID_RESPONSE);
				LOG_STRM_WARNING(FXmppStream->streamJid(),QString("Authorization error: Invalid stanza kind=%1").arg(AStanza.kind()));
				emit error(err);
			}
		}
		return true;
	}
	return false;
}
开发者ID:ChALkeR,项目名称:vacuum-im,代码行数:64,代码来源:saslauthfeature.cpp

示例8: add

bool HsMenuClientPrivate::add(const QVariantMap &entryPreference)
{
    bool result = false;
    QMap<QString, QVariant> pref = entryPreference;
    
    CaIconDescription iconDesc;
    if(pref.contains(hsItemId))
        {
            QSharedPointer<CaEntry> update_entry = CaService::instance()->getEntry(pref.take(hsItemId).toInt());
            
            if(pref.contains(hsItemLocName))
                {
                update_entry->setText(pref.take(hsItemLocName).toString(),true);
                }
            else
                {
                update_entry->setText(pref.take(hsItemName).toString());   
                }
            
            if(pref.contains(hsItemLocDescription))
                {
                update_entry->setDescription(pref.take(hsItemLocDescription).toString(), true);
                }
            else
                {
                update_entry->setDescription(pref.take(hsItemDescription).toString());
                }                                             
            
            iconDesc.setFilename(pref.take(hsIconFileName).toString());
            iconDesc.setSkinId(pref.take(hsIconName).toString());
            iconDesc.setApplicationId(pref.take(hsIconApplicationId).toString());
            update_entry->setIconDescription(iconDesc);
            QMapIterator<QString, QVariant> k(pref);
            while (k.hasNext()) {
                k.next();
                update_entry->setAttribute(k.key(),k.value().toString());
            }
            
            result = CaService::instance()->updateEntry(*update_entry);
        }
    else if ((pref.contains(hsItemName) || pref.contains(hsItemLocName)) && pref.contains(hsitemLaunchUri) && pref.contains(hsitemPublisherId))
        {
            CaEntry add_entry(ItemEntryRole);
            add_entry.setEntryTypeName(Hs::templatedApplicationTypeName);
            // mandatory values
            if(pref.contains(hsItemLocName))
                {
                add_entry.setText(pref.take(hsItemLocName).toString(),true);
                }
            else
                {
                add_entry.setText(pref.take(hsItemName).toString());
                }
            
            iconDesc.setFilename(pref.take(hsIconFileName).toString());
            iconDesc.setSkinId(pref.take(hsIconName).toString());
            iconDesc.setApplicationId(pref.take(hsIconApplicationId).toString());            
            add_entry.setIconDescription(iconDesc);  
            
            if(pref.contains(hsItemLocDescription))
                {
                add_entry.setDescription(pref.take(hsItemLocDescription).toString(), true);
                }
            else
                {
                add_entry.setDescription(pref.take(hsItemDescription).toString());
                }  
            QMapIterator<QString, QVariant> k(pref);
            while (k.hasNext()) {
                k.next();
                add_entry.setAttribute(k.key(),k.value().toString());
            }

            add_entry.setFlags(add_entry.flags() & ~RemovableEntryFlag);
            
            QSharedPointer<CaEntry> entry = CaService::instance()->createEntry(add_entry);
            if (!entry.isNull()) {
                result = true;
            }      
        }
    else
        {
            return false;
        }
    return result;
    
  
}
开发者ID:cdaffara,项目名称:symbiandump-ossapps,代码行数:88,代码来源:hsmenuclient.cpp

示例9: updateContent

// This method will cause the class to rebuild its text representation.
// based on the parent classifier object.
// For any situation in which this is called, we are either building the code
// document up, or replacing/regenerating the existing auto-generated parts. As
// such, we will want to insert everything we resonablely will want
// during creation. We can set various parts of the document (esp. the
// comments) to appear or not, as needed.
void DClassifierCodeDocument::updateContent()
{
    // Gather info on the various fields and parent objects of this class...
    UMLClassifier * c = getParentClassifier();
    Q_ASSERT(c != 0);
    CodeGenerationPolicy * commonPolicy = UMLApp::app()->commonPolicy();
    CodeGenPolicyExt * pe = UMLApp::app()->policyExt();
    DCodeGenerationPolicy * policy = dynamic_cast<DCodeGenerationPolicy*>(pe);

    // first, set the global flag on whether or not to show classfield info
    // This depends on whether or not we have attribute/association classes
    const CodeClassFieldList * cfList = getCodeClassFieldList();
    CodeClassFieldList::const_iterator it = cfList->begin();
    CodeClassFieldList::const_iterator end = cfList->end();
    for (; it != end; ++it) {
        CodeClassField * field = *it;
        if (field->parentIsAttribute())
            field->setWriteOutMethods(policy->getAutoGenerateAttribAccessors());
        else
            field->setWriteOutMethods(policy->getAutoGenerateAssocAccessors());
    }

    // attribute-based ClassFields
    // we do it this way to have the static fields sorted out from regular ones
    CodeClassFieldList staticAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true);
    CodeClassFieldList attribClassFields = getSpecificClassFields (CodeClassField::Attribute, false);
    // association-based ClassFields
    // don't care if they are static or not..all are lumped together
    CodeClassFieldList plainAssocClassFields = getSpecificClassFields (CodeClassField::PlainAssociation);
    CodeClassFieldList aggregationClassFields = getSpecificClassFields (CodeClassField::Aggregation);
    CodeClassFieldList compositionClassFields = getSpecificClassFields (CodeClassField::Composition);

    bool isInterface = parentIsInterface();
    bool hasOperationMethods = false;

    UMLOperationList list = c->getOpList();
    hasOperationMethods = ! list.isEmpty();

    QString endLine = commonPolicy->getNewLineEndingChars(); // a shortcut..so we don't have to call this all the time

    //
    // START GENERATING CODE/TEXT BLOCKS and COMMENTS FOR THE DOCUMENT
    //

    //
    // PACKAGE CODE BLOCK
    //
    QString pkgs = getPackage();
    pkgs.replace(QRegExp(QLatin1String("::")), QLatin1String("."));
    QString packageText = getPackage().isEmpty() ? QString() : QString(QLatin1String("package ")+pkgs+QLatin1Char(';')+endLine);
    CodeBlockWithComments * pblock = addOrUpdateTaggedCodeBlockWithComments(QLatin1String("packages"), packageText, QString(), 0, false);
    if (packageText.isEmpty() && pblock->contentType() == CodeBlock::AutoGenerated)
        pblock->setWriteOutText(false);
    else
        pblock->setWriteOutText(true);

    // IMPORT CODEBLOCK
    //
    // Q: Why all utils? Aren't just List and Vector the only classes we are using?
    // A: doesn't matter at all; it is more readable to just include '*' and d compilers
    //    don't slow down or anything. (TZ)
    QString importStatement;
    if (hasObjectVectorClassFields())
        importStatement.append(QLatin1String("import d.util.*;"));

    //only import classes in a different package from this class
    UMLPackageList imports;
    QMap<UMLPackage*, QString> packageMap; // so we don't repeat packages

    CodeGenerator::findObjectsRelated(c, imports);
    for (UMLPackageListIt importsIt(imports); importsIt.hasNext();) {
        UMLPackage *con = importsIt.next();
        // NO (default) datatypes in the import statement.. use defined
        // ones whould be possible, but no idea how to do that...at least for now.
        // Dynamic casting is slow..not an optimal way to do this.
        if (!packageMap.contains(con) && !con->isUMLDatatype())
        {
            packageMap.insert(con, con->package());

            // now, we DON'T need to import classes that are already in our own package
            // (that is, IF a package is specified). Otherwise, we should have a declaration.
            if (con->package() != c->package() ||
                    (c->package().isEmpty() && con->package().isEmpty()))
            {
                importStatement.append(endLine+QLatin1String("import "));
                if (!con->package().isEmpty())
                    importStatement.append(con->package()+QLatin1Char('.'));
                importStatement.append(CodeGenerator::cleanName(con->name())+QLatin1Char(';'));
            }
        }
    }
    // now, add/update the imports codeblock
    CodeBlockWithComments * iblock = addOrUpdateTaggedCodeBlockWithComments(QLatin1String("imports"), importStatement, QString(), 0, false);
//.........这里部分代码省略.........
开发者ID:KDE,项目名称:umbrello,代码行数:101,代码来源:dclassifiercodedocument.cpp

示例10: trainClassifier

void ANNClassifier::trainClassifier( SuspectLibraryPtr suspectLibrary, QMap<QString,QVariant> trainingParameters )
{
    bool ok = true;

    /// @todo  add a fetch required parameters method to query which parameters are required for training

    /// @todo  Move the input and output width parameters down into the base class
    // Fetch the input width for this classifier
    SOMError::requireCondition( trainingParameters.contains( "inputWidth" ), "Missing required input width parameter" );
    inputWidth = trainingParameters[ "inputWidth" ].toInt( &ok );
    SOMError::requireCondition( ok, "Failed to convert input width parameter" );
    SOMError::requireCondition( inputWidth > 0, "Invalid input size" );

    // Fetch the output width for this classifier
    SOMError::requireCondition( trainingParameters.contains( "outputWidth" ), "Missing required output width parameter" );
    outputWidth = trainingParameters[ "outputWidth" ].toInt( &ok );
    SOMError::requireCondition( ok, "Failed to convert output width parameter" );
    SOMError::requireCondition( outputWidth > 0, "Invalid output size" );

    // Fetch the iterations parameter for this classifier
    int iterations = 0;
    if( trainingParameters.contains( "iterations" ) )
    {
        iterations = trainingParameters[ "iterations" ].toInt( &ok );
        SOMError::requireCondition( ok, "Failed to convert iterations parameter" );
        SOMError::requireCondition( iterations > 0, "Invalid iterations value" );
    }

    // Fetch the iterations parameter for this classifier
    double epsilon = 0.0;
    if( trainingParameters.contains( "epsilon" ) )
    {
        epsilon = trainingParameters[ "epsilon" ].toDouble( &ok );
        SOMError::requireCondition( ok, "Failed to convert epsilon parameter" );
        SOMError::requireCondition( epsilon > 0.0, "Invalid epsilon value" );
    }

    QVector< SuspectPtr > suspects = suspectLibrary->suspects();
    /* Make an input matrix for training the back-end MLPANN.
     * This is a matrix composed of vectors the length of the SOM's area ( width x height )
     */
    cv::Mat_<double>  input( suspects.size(), inputWidth, 0.0 );

    /* Make an output matrix for trainig the back-end MLPANN.
     * This is a matrix composed of vectors the length of the number of classification categories.
     */
    cv::Mat_<double> output( suspects.size(), outputWidth, 0.0 );

    for( int i=0; i<suspects.size(); i++ )
    {
        SuspectPtr suspect = suspects[i];
        HistogramPtr histogram = suspect->histogram();

        // Set the input for the training input matrix row to the histogram of the suspect
        for( int j=0; j<inputWidth; j++ )
            input( i, j ) = histogram->bin( j );

        // Set the output value for the real category of the suspect to 1.  All other values will already be 0
        output( i, suspect->realCategory() ) = 1.0;
    }

    cv::TermCriteria terminationCriteria;
    terminationCriteria.type = 0;
    if( iterations != 0 )
        terminationCriteria.type += cv::TermCriteria::MAX_ITER;
    if( epsilon != 0.0 )
        terminationCriteria.type += cv::TermCriteria::EPS;

    cv::ANN_MLP_TrainParams trainingParams( terminationCriteria, CvANN_MLP_TrainParams::RPROP, iterations, epsilon );

    int normFlag = 0;

    int tmp[4];

    // The input layer has one node for each element in the input histograms
    tmp[0] = inputWidth;

    // The first hidden layer is half the size of the input layer
    tmp[1] = inputWidth / 2;

    // The second input layer is one quarter the size of the input layer
    tmp[2] = inputWidth / 4;

    // The output layer has one node for each category
    tmp[3] = outputWidth;

    CvMat ls = cvMat( 4, 1, CV_32S, tmp );

    // If there is already an MPLANN attached to this HSOM, delete it to start over
    if( _ann != NULL )
        delete _ann;

    // Create a new MLPANN for the HSOM
    _ann = new CvANN_MLP( &ls, CvANN_MLP::SIGMOID_SYM );

    _ann->train( input, output, cv::Mat(), cv::Mat(), trainingParams, normFlag );
}
开发者ID:alex09x,项目名称:somtk,代码行数:97,代码来源:annclassifier.cpp

示例11: setupFragmentShader

			void DisplayWidget::setupFragmentShader() {


			QMap<QString, bool> textureCacheUsed;

			if (shaderProgram) {
				shaderProgram->release();
			}
			delete(shaderProgram);
			shaderProgram = new QGLShaderProgram(this);

			// Vertex shader
			bool s = false;
			s = shaderProgram->addShaderFromSourceCode(QGLShader::Vertex,fragmentSource.vertexSource.join("\n"));
			if (fragmentSource.vertexSource.count() == 0) {
				WARNING("No vertex shader found!");
				s = false;
			}

			if (!s) WARNING("Could not create vertex shader: " + shaderProgram->log());
			if (!s) { delete(shaderProgram); shaderProgram = 0; return; }
			if (!shaderProgram->log().isEmpty()) INFO("Vertex shader compiled with warnings: " + shaderProgram->log());

			// Fragment shader
			s = shaderProgram->addShaderFromSourceCode(QGLShader::Fragment,
				fragmentSource.getText());
			if (!s) WARNING("Could not create fragment shader: " + shaderProgram->log());
			if (!s) { delete(shaderProgram); shaderProgram = 0; return; }
			if (!shaderProgram->log().isEmpty()) INFO("Fragment shader compiled with warnings: " + shaderProgram->log());

			s = shaderProgram->link();
			if (!s) WARNING("Could not link shaders: " + shaderProgram->log());
			if (!s) { delete(shaderProgram); shaderProgram = 0; return; }
			if (!shaderProgram->log().isEmpty()) INFO("Fragment shader compiled with warnings: " + shaderProgram->log());

			s = shaderProgram->bind();
			if (!s) WARNING("Could not bind shaders: " + shaderProgram->log());
			if (!s) { delete(shaderProgram); shaderProgram = 0; return; }

			// Setup textures.
			int u = 0;

			// Bind first texture to backbuffer
			int l = shaderProgram->uniformLocation("backbuffer");
			if (l != -1) {
				if (bufferType != None) {
					glActiveTexture(GL_TEXTURE0+u); // non-standard (>OpenGL 1.3) gl extension
					GLuint i = backBuffer->texture();
					glBindTexture(GL_TEXTURE_2D,i);
					if (fragmentSource.textureParams.contains("backbuffer")) {
						setGlTexParameter(fragmentSource.textureParams["backbuffer"]);

					}
					shaderProgram->setUniformValue(l, (GLuint)u);
					//INFO(QString("Binding back buffer (ID: %1) to active texture %2").arg(backBuffer->texture()).arg(u));
					//INFO(QString("Setting uniform backbuffer to active texture %2").arg(u));
					u++;
				} else {
					WARNING("Trying to use a backbuffer, but no bufferType set.");
					WARNING("Use the buffer define, e.g.: '#buffer RGBA8' ");
				}
			}


			for (QMap<QString, QString>::iterator it = fragmentSource.textures.begin(); it!=fragmentSource.textures.end(); it++) {
				QString textureName = it.key();
				QString texturePath = it.value();
				QImage im(texturePath);
				if (im.isNull() && !texturePath.endsWith(".hdr", Qt::CaseInsensitive)) {
					WARNING("Failed to load texture: " + QFileInfo(texturePath).absoluteFilePath());
				} else {
					int l = shaderProgram->uniformLocation(textureName);
					if (l != -1) {
						if (im.isNull()) {
													
							GLuint texture = 0;

							// set current texture
							glActiveTexture(GL_TEXTURE0+u); // non-standard (>OpenGL 1.3) gl extension
							
							// allocate a texture id

							if (TextureCache.contains(texturePath)) {
								textureCacheUsed[texturePath] = true;
								int textureID = TextureCache[texturePath];
								glBindTexture(GL_TEXTURE_2D, textureID );
								INFO(QString("Found texture in cache: %1 (id: %2)").arg(texturePath).arg(textureID));
							} else {
								glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	    
								glGenTextures(1, &texture );
								INFO(QString("Allocated texture ID: %1").arg(texture));

								glBindTexture(GL_TEXTURE_2D, texture );
								//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
								
								// TODO: If I don't keep this line, HDR images don't work.
								// It must be a symptom of some kind of error in the OpenGL setup.
								glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
								if (fragmentSource.textureParams.contains(textureName)) {
//.........这里部分代码省略.........
开发者ID:plule,项目名称:Fragmentarium,代码行数:101,代码来源:DisplayWidget.cpp

示例12: CalcParams

/** \fn AutoExpire::CalcParams()
 *   Calculates how much space needs to be cleared, and how often.
 */
void AutoExpire::CalcParams()
{
    VERBOSE(VB_FILE, LOC + "CalcParams()");

    vector<FileSystemInfo> fsInfos;
    if (mainServer)
        mainServer->GetFilesystemInfos(fsInfos);

    if (fsInfos.empty())
    {
        QString msg = "ERROR: Filesystem Info cache is empty, unable to "
                      "calculate necessary parameters.";
        VERBOSE(VB_IMPORTANT, LOC + msg);
        gCoreContext->LogEntry("mythbackend", LP_WARNING,
                           "Autoexpire CalcParams", msg);

        return;
    }

    size_t maxKBperMin = 0;
    size_t extraKB = gCoreContext->GetNumSetting("AutoExpireExtraSpace", 0) << 20;

    QMap<int, uint64_t> fsMap;
    QMap<int, vector<int> > fsEncoderMap;

    // we use this copying on purpose. The used_encoders map ensures
    // that every encoder writes only to one fs.
    // Copying the data minimizes the time the lock is held
    instance_lock.lock();
    QMap<int, int>::const_iterator ueit = used_encoders.begin();
    while (ueit != used_encoders.end())
    {
        fsEncoderMap[*ueit].push_back(ueit.key());
        ++ueit;
    }
    instance_lock.unlock();

    vector<FileSystemInfo>::iterator fsit;
    for (fsit = fsInfos.begin(); fsit != fsInfos.end(); ++fsit)
    {
        if (fsMap.contains(fsit->fsID))
            continue;

        fsMap[fsit->fsID] = 0;
        size_t thisKBperMin = 0;

        // append unknown recordings to all fsIDs
        vector<int>::iterator unknownfs_it = fsEncoderMap[-1].begin();
        for (; unknownfs_it != fsEncoderMap[-1].end(); ++unknownfs_it)
            fsEncoderMap[fsit->fsID].push_back(*unknownfs_it);

        if (fsEncoderMap.contains(fsit->fsID))
        {
            VERBOSE(VB_FILE, QString(
                "fsID #%1: Total: %2 GB   Used: %3 GB   Free: %4 GB")
                .arg(fsit->fsID)
                .arg(fsit->totalSpaceKB / 1024.0 / 1024.0, 7, 'f', 1)
                .arg(fsit->usedSpaceKB / 1024.0 / 1024.0, 7, 'f', 1)
                .arg(fsit->freeSpaceKB / 1024.0 / 1024.0, 7, 'f', 1));


            vector<int>::iterator encit = fsEncoderMap[fsit->fsID].begin();
            for (; encit != fsEncoderMap[fsit->fsID].end(); ++encit)
            {
                EncoderLink *enc = *(encoderList->find(*encit));

                if (!enc->IsConnected() || !enc->IsBusy())
                {
                    // remove the encoder since it can't write to any file system
                    VERBOSE(VB_FILE, LOC
                            + QString("Cardid %1: is not recoding, removing it "
                                      "from used list.").arg(*encit));
                    instance_lock.lock();
                    used_encoders.remove(*encit);
                    instance_lock.unlock();
                    continue;
                }

                long long maxBitrate = enc->GetMaxBitrate();
                if (maxBitrate<=0)
                    maxBitrate = 19500000LL;
                thisKBperMin += (((size_t)maxBitrate)*((size_t)15))>>11;
                VERBOSE(VB_FILE, QString("    Cardid %1: max bitrate "
                        "%2 Kb/sec, fsID %3 max is now %4 KB/min")
                        .arg(enc->GetCardID())
                        .arg(enc->GetMaxBitrate() >> 10)
                        .arg(fsit->fsID)
                        .arg(thisKBperMin));
            }
        }
        fsMap[fsit->fsID] = thisKBperMin;

        if (thisKBperMin > maxKBperMin)
        {
            VERBOSE(VB_FILE,
                    QString("  Max of %1 KB/min for fsID %2 is higher "
                    "than the existing Max of %3 so we'll use this Max instead")
//.........这里部分代码省略.........
开发者ID:microe,项目名称:mythtv,代码行数:101,代码来源:autoexpire.cpp

示例13: updateContent

// This method will cause the class to rebuild its text representation.
// based on the parent classifier object.
// For any situation in which this is called, we are either building the code
// document up, or replacing/regenerating the existing auto-generated parts. As
// such, we will want to insert everything we resonablely will want
// during creation. We can set various parts of the document (esp. the
// comments) to appear or not, as needed.
void CPPHeaderCodeDocument::updateContent( )
{
    // Gather info on the various fields and parent objects of this class...
    UMLClassifier * c = getParentClassifier();
    CodeGenPolicyExt *pe = UMLApp::app()->policyExt();
    CPPCodeGenerationPolicy * policy = dynamic_cast<CPPCodeGenerationPolicy*>(pe);

    // first, set the global flag on whether or not to show classfield info
    const CodeClassFieldList * cfList = getCodeClassFieldList();
    CodeClassFieldList::const_iterator it = cfList->begin();
    CodeClassFieldList::const_iterator end = cfList->end();
    for( ; it != end; ++it )
        (*it)->setWriteOutMethods(policy->getAutoGenerateAccessors());

    // attribute-based ClassFields
    // we do it this way to have the static fields sorted out from regular ones
    CodeClassFieldList staticPublicAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true, Uml::Visibility::Public );
    CodeClassFieldList publicAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, false, Uml::Visibility::Public );
    CodeClassFieldList staticProtectedAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true, Uml::Visibility::Protected );
    CodeClassFieldList protectedAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, false, Uml::Visibility::Protected );
    CodeClassFieldList staticPrivateAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true, Uml::Visibility::Private );
    CodeClassFieldList privateAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, false, Uml::Visibility::Private);

    // association-based ClassFields
    // don't care if they are static or not..all are lumped together
    CodeClassFieldList publicPlainAssocClassFields = getSpecificClassFields ( CodeClassField::PlainAssociation , Uml::Visibility::Public);
    CodeClassFieldList publicAggregationClassFields = getSpecificClassFields ( CodeClassField::Aggregation, Uml::Visibility::Public);
    CodeClassFieldList publicCompositionClassFields = getSpecificClassFields ( CodeClassField::Composition, Uml::Visibility::Public );

    CodeClassFieldList protPlainAssocClassFields = getSpecificClassFields ( CodeClassField::PlainAssociation , Uml::Visibility::Protected);
    CodeClassFieldList protAggregationClassFields = getSpecificClassFields ( CodeClassField::Aggregation, Uml::Visibility::Protected);
    CodeClassFieldList protCompositionClassFields = getSpecificClassFields ( CodeClassField::Composition, Uml::Visibility::Protected);

    CodeClassFieldList privPlainAssocClassFields = getSpecificClassFields ( CodeClassField::PlainAssociation , Uml::Visibility::Private);
    CodeClassFieldList privAggregationClassFields = getSpecificClassFields ( CodeClassField::Aggregation, Uml::Visibility::Private);
    CodeClassFieldList privCompositionClassFields = getSpecificClassFields ( CodeClassField::Composition, Uml::Visibility::Private);

    bool hasOperationMethods = false;
    Q_ASSERT(c != NULL);
    if (c) {
        UMLOperationList list = c->getOpList();
        hasOperationMethods = ! list.isEmpty();
    }
    bool hasNamespace = false;
    bool isEnumeration = false;
    bool isInterface = parentIsInterface();
    bool hasclassFields = hasClassFields();
    bool forcedoc = UMLApp::app()->commonPolicy()->getCodeVerboseDocumentComments();
    QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars();

    UMLClassifierList superclasses = c->findSuperClassConcepts();


    // START GENERATING CODE/TEXT BLOCKS and COMMENTS FOR THE DOCUMENT
    //

    // Write the hash define stuff to prevent multiple parsing/inclusion of header
    QString cppClassName = CodeGenerator::cleanName(c->name());
    QString hashDefine = CodeGenerator::cleanName(c->name().toUpper().simplified());
    QString defText = "#ifndef "+hashDefine + "_H"+ endLine + "#define "+ hashDefine + "_H";
    addOrUpdateTaggedCodeBlockWithComments("hashDefBlock", defText, "", 0, false);

    // INCLUDE CODEBLOCK
    //
    // Q: Why all utils? Isnt just List and Vector the only classes we are using?
    // A: doesn't matter at all; its more readable to just include '*' and cpp compilers
    //    don't slow down or anything. (TZ)
    QString includeStatement = "";
    bool stringGlobal = policy->stringIncludeIsGlobal();
    QString sStartBrak = stringGlobal ? "<" : "\"";
    QString sEndBrak = stringGlobal ? ">" : "\"";
    includeStatement.append("#include "+sStartBrak+policy->getStringClassNameInclude()+sEndBrak+endLine);
    if ( hasObjectVectorClassFields() )
    {
        bool vecGlobal = policy->vectorIncludeIsGlobal();
        QString vStartBrak = vecGlobal ? "<" : "\"";
        QString vEndBrak = vecGlobal ? ">" : "\"";
        QString value ="#include "+vStartBrak+policy->getVectorClassNameInclude()+vEndBrak;
        includeStatement.append(value+endLine);
    }

    //only include classes in a different package from this class
    UMLPackageList includes;
    QMap<UMLPackage *,QString> packageMap; // so we don't repeat packages

    CodeGenerator::findObjectsRelated(c,includes);
    foreach(UMLPackage* con, includes ) {
        if (con->baseType() != Uml::ot_Datatype && !packageMap.contains(con)) {
            packageMap.insert(con,con->package());
            if(con != getParentClassifier())
                includeStatement.append("#include \""+CodeGenerator::cleanName(con->name().toLower())+".h\""+endLine);
        }
    }
//.........这里部分代码省略.........
开发者ID:Elv13,项目名称:Umbrello-ng,代码行数:101,代码来源:cppheadercodedocument.cpp

示例14: getCompiledCode

CompiledPythonFragment * getCompiledCode( Table * table, int pkey, const QString & pCode, const QString & codeName )
{
	CompiledPythonFragment * ret = 0;
	ensurePythonInitialized();
	// Create the key for looking up the code fragment in the cache
	QPair<Table*,int> codeKey = qMakePair(table,pkey);

	// Return the cached code fragment, if the code still matches
	if( codeCache.contains( codeKey ) ) {
		CompiledPythonFragment * frag = &codeCache[codeKey];
		// This should actually be very fast because of QString's
		// implicit sharing, should usually just be a pointer comparison
		if( frag->codeString == pCode )
			return frag;

		// Remove from cache if the fragment is out of date
		// TODO: This should free any references and remove the module
		// this isn't a big deal though, since code fragments won't
		// change very often during program execution
		codeCache.remove( codeKey );
	}

	if( pCode.isEmpty() )
		return 0;

	// Compile the code
	CompiledPythonFragment frag;
	frag.codeString = pCode;
	SIP_BLOCK_THREADS
	frag.code = (PyCodeObject*)Py_CompileString( pCode.toLatin1(), codeName.toLatin1(), Py_file_input );
	SIP_UNBLOCK_THREADS
	if( !frag.code )
	{
		PyErr_Print();
		LOG_5( "PathTemplate:getCompiledCode: Error Compiling Python code for: " + table->schema()->tableName() + " " + QString::number( pkey ) + " " + codeName );
		return 0;
	}

	// Load the code into a module
	// This is the only way i could figure out how to make the globals work properly
	// before i was using PyEval_EvalCode, passing the __main__ dict as the globals
	// but this wasn't working properly when calling the functions later, because
	// the import statements were lost.
	// This method works great and takes less code.
	
	// Generate a unique module name
	QString moduleName = "__" + table->schema()->tableName() + "__" + QString::number(pkey) + "__";
	// Returns a NEW ref
	SIP_BLOCK_THREADS
	PyObject * module = PyImport_ExecCodeModule(moduleName.toLatin1().data(),(PyObject*)frag.code);
	if( !module ) {
		PyErr_Print();
		LOG_3( "Unable to execute code module" );
	}

	// Save the modules dict, so we can lookup the function later
	else {
		frag.locals = PyModule_GetDict(module);
		Py_INCREF(frag.locals);
		codeCache[codeKey] = frag;
		ret = &codeCache[codeKey];
	}
	SIP_UNBLOCK_THREADS

	return ret;
}
开发者ID:vgrant,项目名称:arsenalsuite,代码行数:66,代码来源:pyembed.cpp

示例15: message


//.........这里部分代码省略.........
    //---------------------------------------------------------------------------
    addMessage("XML", i18n("XML"));
    addMessage("GENERATE_XML", i18n("Generate XML"));
    addMessage("XML_OUTPUT", i18n("XML output directory"));
    addMessage("XML_SCHEMA", i18n("XML schema"));
    addMessage("XML_DTD", i18n("XML DTD file"));
    addMessage("XML_PROGRAMLISTING", i18n("Dump program listings to the XML output"));

    //---------------------------------------------------------------------------
    // configuration options for the AutoGen Definitions output
    //---------------------------------------------------------------------------
    addMessage("DEF", i18n("DEF"));
    addMessage("GENERATE_AUTOGEN_DEF", i18n("Generate Autogen DEF"));

    //---------------------------------------------------------------------------
    // configuration options related to the Perl module output
    //---------------------------------------------------------------------------
    addMessage("PerlMod", i18n("Perl"));
    addMessage("GENERATE_PERLMOD", i18n("Generate Perl module"));
    addMessage("PERLMOD_LATEX", i18n("Generate PDF and DVI using LaTeX"));
    addMessage("PERLMOD_PRETTY", i18n("Make the Perl module output human readable"));
    addMessage("PERLMOD_MAKEVAR_PREFIX", i18n("Perl module variable prefix in the makefiles"));

    //---------------------------------------------------------------------------
    // Configuration options related to the preprocessor
    //---------------------------------------------------------------------------
    addMessage("Preprocessor", i18n("Preprocessor"));
    addMessage("ENABLE_PREPROCESSING", i18n("Enable preprocessing"));
    addMessage("MACRO_EXPANSION", i18n("Expand macros"));
    addMessage("EXPAND_ONLY_PREDEF", i18n("Expand only predefined macros"));
    addMessage("SEARCH_INCLUDES", i18n("Search for includes"));
    addMessage("INCLUDE_PATH", i18n("Include path"));
    addMessage("INCLUDE_FILE_PATTERNS", i18n("Include file patterns"));
    addMessage("PREDEFINED", i18n("Predefined macros"));
    addMessage("EXPAND_AS_DEFINED", i18n("Expand as defined"));
    addMessage("SKIP_FUNCTION_MACROS", i18n("Skip function macros"));

    //---------------------------------------------------------------------------
    // Configuration::addtions related to external references
    //---------------------------------------------------------------------------
    addMessage("External", i18n("External"));
    addMessage("TAGFILES", i18n("Tagfiles"));
    addMessage("GENERATE_TAGFILE", i18n("Generate tagfile"));
    addMessage("ALLEXTERNALS", i18n("List all externals"));
    addMessage("EXTERNAL_GROUPS", i18n("External groups"));
    addMessage("PERL_PATH", i18n("Path to Perl"));

    //---------------------------------------------------------------------------
    // Configuration options related to the dot tool
    //---------------------------------------------------------------------------
    addMessage("Dot", i18n("Dot"));
    addMessage("CLASS_DIAGRAMS", i18n("Generate class diagrams"));
    addMessage("HIDE_UNDOC_RELATIONS", i18n("Hide undocumented relations"));
    addMessage("HAVE_DOT", i18n("Use dot"));
    addMessage("CALLER_GRAPH", i18n("Generate a caller dependency graph"));
    addMessage("CLASS_GRAPH", i18n("Generate class graphs"));
    addMessage("COLLABORATION_GRAPH", i18n("Generate collaboration graphs"));
    addMessage("GROUP_GRAPHS", i18n("Generate a graph showing the direct groups dependencies"));
    addMessage("UML_LOOK", i18n("Generate UML looking inheritance and colloboration diagrams"));
    addMessage("TEMPLATE_RELATIONS", i18n("Show relations between templates and their instances"));
    addMessage("INCLUDE_GRAPH", i18n("Generate include graphs"));
    addMessage("INCLUDED_BY_GRAPH", i18n("Generate included-by graphs"));
    addMessage("CALL_GRAPH", i18n("Generate a call dependency graph for every global function or class method"));
    addMessage("GRAPHICAL_HIERARCHY", i18n("Generate graphical hierarchy"));
    addMessage("DIRECTORY_GRAPH", i18n("Show the dependencies a directory has on other directories"));
    addMessage("DOT_IMAGE_FORMAT", i18n("Dot image format"));
    addMessage("DOT_PATH", i18n("Path to dot"));
    addMessage("DOTFILE_DIRS", i18n("Directories with extra dot files"));
    addMessage("MAX_DOT_GRAPH_WIDTH", i18n("Maximum graph width"));
    addMessage("MAX_DOT_GRAPH_HEIGHT", i18n("Maximum graph height"));
    addMessage("MAX_DOT_GRAPH_DEPTH", i18n("Maximum graph depth"));
    addMessage("DOT_TRANSPARENT", i18n("Generate images with a transparent background"));
    addMessage("DOT_MULTI_TARGETS", i18n("Generate multiple output files in one run"));
    addMessage("GENERATE_LEGEND", i18n("Generate legend"));
    addMessage("DOT_CLEANUP", i18n("Remove intermediate files"));
    addMessage("Search", i18n("Search"));

    //---------------------------------------------------------------------------
    // Configuration::addtions related to the search engine
    //---------------------------------------------------------------------------
    addMessage("SEARCHENGINE", i18n("Search engine"));
    addMessage("CGI_NAME", i18n("CGI name"));
    addMessage("CGI_URL", i18n("CGI URL"));
    addMessage("DOC_URL", i18n("Documentation URL"));
    addMessage("DOC_ABSPATH", i18n("Absolute path to documentation"));
    addMessage("BIN_ABSPATH", i18n("Absolute path to doxysearch binary"));
    addMessage("EXT_DOC_PATHS", i18n("Paths to external documentation"));

    initialized = true;
  }

  if (!sMessages.contains(key))
  {
    kdDebug() << "Unhandled message: " << key << endl;

    return key;
  }

  return sMessages[key];
}
开发者ID:serghei,项目名称:kde3-kdevelop,代码行数:101,代码来源:messages.cpp


注:本文中的QMap::contains方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。