Exemplo n.º 1
0
void GraphUtils::minCut(QList<ConnectorItem *> & connectorItems, QList<SketchWidget *> & foreignSketchWidgets, ConnectorItem * source, ConnectorItem * sink, QList<ConnectorEdge *> & minCut) 
{
	// this helped:  http://boost.2283326.n4.nabble.com/graph-edmund-karp-max-flow-vs-kolmogorov-max-flow-color-map-td2565611.html
	
	using namespace boost;

	typedef adjacency_list_traits < vecS, vecS, directedS > Traits;
    typedef property < vertex_color_t, boost::default_color_type > COLOR;
	typedef property < vertex_index_t, long, COLOR > VERTEX;
    typedef property < edge_reverse_t, Traits::edge_descriptor > REVERSE;
    typedef property < edge_residual_capacity_t, long, REVERSE > RESIDUAL;
	typedef property < edge_capacity_t, long, RESIDUAL > EDGE;
	typedef adjacency_list < listS, vecS, directedS, VERTEX, EDGE > Graph;

	Graph g;

	property_map < Graph, edge_capacity_t >::type capacity = get(edge_capacity, g);
	property_map < Graph, edge_residual_capacity_t >::type residual_capacity = get(edge_residual_capacity, g);
	property_map < Graph, edge_reverse_t >::type reverse = get(edge_reverse, g);

	property_map < Graph, vertex_color_t >::type color = get(vertex_color, g);
	property_map < Graph, vertex_index_t >::type index = get(vertex_index, g);

	Traits::vertex_descriptor s, t;

	QList<Wire *> visitedWires;
	QList<int> indexes;
	QHash<ConnectorItem *, int> vertices;
	QList<ConnectorEdge *> edges;
	QVector<Traits::vertex_descriptor> verts;

	vertices.insert(source, 0);
	vertices.insert(sink, 1);
	verts.append(s = add_vertex(g));
	verts.append(t = add_vertex(g));

	foreach (ConnectorItem * connectorItem, connectorItems) {
		//connectorItem->debugInfo("input");
		if (connectorItem->attachedToItemType() == ModelPart::Wire) {
			Wire * wire = qobject_cast<Wire *>(connectorItem->attachedTo());
			if (visitedWires.contains(wire)) continue;

			QList<Wire *> wires;
			QList<ConnectorItem *> ends;
			wire->collectChained(wires, ends);
			visitedWires.append(wires);
			if (ends.count() < 2) continue;

			foreach (ConnectorItem * end, ends) {
				appendVertIf(end, vertices, verts);
			}

			for (int i = 0; i < ends.count(); i++) {
				ConnectorItem * end = ends[i];
				for (int j = i + 1; j < ends.count(); j++) {
					ConnectorEdge * connectorEdge = makeConnectorEdge(edges, end, ends[j], 1000, wire);
					connectorEdge->setHeadTail(vertices.value(connectorEdge->c0), vertices.value(connectorEdge->c1));
				}
			}
			continue;
		}
void UmlBaseUseCaseDiagramDefinition::read_()
{
    QHash<void*,UmlUseCaseReference*> ucrefs;
    unsigned n;
    unsigned rank;

    n = UmlCom::read_unsigned();
    _fragments.resize(n);

    for (rank = 0; rank != n; rank += 1) {
        UmlFragment * f = new UmlFragment();

        _fragments.insert(rank, f);
        f->read_();
    }

    //_fragments.setAutoDelete(TRUE);
    UmlBaseFragment::compute_container_(_fragments);

    n = UmlCom::read_unsigned();
    _subjects.resize(n);

    for (rank = 0; rank != n; rank += 1) {
        UmlSubject * sb = new UmlSubject();

        _subjects.insert(rank, sb);
        sb->read_();
    }

    //_subjects.setAutoDelete(TRUE);

    n = UmlCom::read_unsigned();
    _use_cases.resize(n);

    for (rank = 0; rank != n; rank += 1) {
        UmlUseCaseReference * uc = new UmlUseCaseReference();

        _use_cases.insert(rank, uc);
        ucrefs.insert((void *) UmlCom::read_unsigned(), uc);
        uc->read_(_fragments, _subjects);
    }

    //_use_cases.setAutoDelete(TRUE);

    n = UmlCom::read_unsigned();
    _actors.resize(n);

    for (rank = 0; rank != n; rank += 1)
        _actors.insert(rank, (UmlClass *) UmlBaseItem::read_());

    n = UmlCom::read_unsigned();
    _rels.resize(n);

    for (rank = 0; rank != n; rank += 1) {
        UmlUseCaseAssociation * r = new UmlUseCaseAssociation();

        _rels.insert(rank, r);
        r->read_(ucrefs);
    }

   // _rels.setAutoDelete(TRUE);
}
QHash<int, QByteArray> NodeListModel::roleNames() const
{
    QHash<int, QByteArray> roles = QAbstractListModel::roleNames();
    roles.insert(INDEX_ROLE, QByteArray("index"));

    roles.insert(FILE_TYPE_VOLUME_ROLE, QByteArray("isVolume"));
    roles.insert(FILE_TYPE_FILE_ROLE, QByteArray("isFile"));
    roles.insert(FILE_TYPE_DIRECTORY_ROLE, QByteArray("isDirectory"));

    roles.insert(FILE_STATUS_DOWNLOADED_ROLE, QByteArray("downloadedStatus"));
    roles.insert(FILE_STATUS_DOWNLOADING_ROLE, QByteArray("downloadingStatus"));

    roles.insert(FILE_PATH_ROLE, QByteArray("filePath"));
    roles.insert(FILE_NAME_ROLE, QByteArray("fileName"));
    roles.insert(IS_PUBLIC_ROLE, QByteArray("isPublic"));
    roles.insert(PUBLIC_URL_ROLE, QByteArray("publicUrl"));
    roles.insert(FILE_SIZE_ROLE, QByteArray("fileSize"));
    roles.insert(LAST_MODIFIED_ROLE, QByteArray("lastModified"));
    roles.insert(FILE_ICON_ROLE, QByteArray("icon"));
    roles.insert(FILE_DOWNLOAD_PROGRESS_ROLE, QByteArray("downloadProgress"));

    return roles;
}
QVariant::Type Soprano::LiteralValue::typeFromDataTypeUri( const QUrl& dataTypeUri )
{
    static QHash<QUrl, QVariant::Type> s_xsdTypes;
    if( s_xsdTypes.isEmpty() ) {
        s_xsdTypes.insert( Vocabulary::XMLSchema::xsdInt(), QVariant::Int );
        s_xsdTypes.insert( Vocabulary::XMLSchema::integer(), QVariant::Int );
        s_xsdTypes.insert( Vocabulary::XMLSchema::negativeInteger(), QVariant::Int );
        s_xsdTypes.insert( Vocabulary::XMLSchema::nonNegativeInteger(), QVariant::UInt );
        s_xsdTypes.insert( Vocabulary::XMLSchema::decimal(), QVariant::Int );
        s_xsdTypes.insert( Vocabulary::XMLSchema::xsdShort(), QVariant::Int );
        s_xsdTypes.insert( Vocabulary::XMLSchema::xsdLong(), QVariant::LongLong );
        s_xsdTypes.insert( Vocabulary::XMLSchema::unsignedInt(), QVariant::UInt );
        s_xsdTypes.insert( Vocabulary::XMLSchema::unsignedShort(), QVariant::UInt );
        s_xsdTypes.insert( Vocabulary::XMLSchema::unsignedLong(), QVariant::ULongLong );
        s_xsdTypes.insert( Vocabulary::XMLSchema::boolean(), QVariant::Bool );
        s_xsdTypes.insert( Vocabulary::XMLSchema::xsdDouble(), QVariant::Double );
        s_xsdTypes.insert( Vocabulary::XMLSchema::xsdFloat(), QVariant::Double );
        s_xsdTypes.insert( Vocabulary::XMLSchema::string(), QVariant::String );
        s_xsdTypes.insert( Vocabulary::XMLSchema::date(), QVariant::Date );
        s_xsdTypes.insert( Vocabulary::XMLSchema::time(), QVariant::Time );
        s_xsdTypes.insert( Vocabulary::XMLSchema::dateTime(), QVariant::DateTime );
        s_xsdTypes.insert( Vocabulary::XMLSchema::base64Binary(), QVariant::ByteArray );
        s_xsdTypes.insert( Vocabulary::RDF::XMLLiteral(), QVariant::String );
    }

    QHash<QUrl, QVariant::Type>::const_iterator it = s_xsdTypes.constFind( dataTypeUri );
    if ( it != s_xsdTypes.constEnd() ) {
        return it.value();
    }
    else {
//        qDebug() << "(Soprano::LiteralValue) unknown literal type uri:" << dataTypeUri;
        return QVariant::Invalid;
    }
}
Exemplo n.º 5
0
QStringList QCSP::containers( SslCertificate::KeyUsage usage )
{
	qWarning() << "Start enumerationg providers";
	QHash<QString,QPair<QString,QString> > certs;
	HCRYPTPROV h = 0;
	DWORD index = 0, type = 0, size = 0;
	while( CryptEnumProvidersW( index, 0, 0, &type, 0, &size ) )
	{
		QString provider( size / sizeof(wchar_t) - 1, 0 );
		if( !CryptEnumProvidersW( index++, 0, 0, &type, LPWSTR(provider.data()), &size ) )
			continue;

		qWarning() << "Found provider" << provider << "type" << type;
		if( type != PROV_RSA_FULL )
			continue;

		// its broken and does not play well with pkcs11
		if( provider.toLower().contains( "esteid" ) )
			continue;

		qWarning() << "Acquiring provider" << provider << "context";
		if( h )
			CryptReleaseContext( h, 0 );
		h = 0;
		if( !CryptAcquireContextW( &h, 0, LPCWSTR(provider.utf16()), type, CRYPT_SILENT ) )
			continue;

		qWarning() << "Checking if provider" << provider << "is HW";
		QByteArray imptype = QCSPPrivate::provParam( h, PP_IMPTYPE );
		if( imptype.isEmpty() || !(imptype[0] & CRYPT_IMPL_HARDWARE) )
			continue;

		qWarning() << "Enumerating provider " << provider << "containers";
		QStringList containers;
		QByteArray container = QCSPPrivate::provParam( h, PP_ENUMCONTAINERS, CRYPT_FIRST );
		while( !container.isEmpty() )
		{
			containers << container;
			container = QCSPPrivate::provParam( h, PP_ENUMCONTAINERS, CRYPT_NEXT );
		}
		qWarning() << "Provider" << provider << "containers" << containers;

		Q_FOREACH( const QString &container, containers )
		{
			if( h )
				CryptReleaseContext( h, 0 );
			h = 0;
			qWarning() << "Acquiring provider" << provider << "container" << container << "context";
			if( !CryptAcquireContextW( &h, LPCWSTR(container.utf16()), LPCWSTR(provider.utf16()), type, CRYPT_SILENT ) )
				continue;

			qWarning() << "Geting provider" << provider << "container" << container << "key";
			HCRYPTKEY key = 0;
			if( !CryptGetUserKey( h, usage == SslCertificate::NonRepudiation ? AT_SIGNATURE : AT_KEYEXCHANGE, &key ) )
				continue;

			qWarning() << "Reading provider" << provider << "container" << container << "cert";
			SslCertificate cert( QCSPPrivate::keyParam( key, KP_CERTIFICATE, 0 ), QSsl::Der );
			CryptDestroyKey( key );

			if( cert.isNull() )
				continue;

			qWarning() << "Adding provider" << provider << "container" << container << "list";
			certs.insert( cert.subjectInfo( QSslCertificate::CommonName ), QPair<QString,QString>( provider, container ) );
		}
	}
	if( h )
		CryptReleaseContext( h, 0 );
	qWarning() << "End enumerationg providers";

	d->certs = certs;
	return d->certs.keys();
}
Exemplo n.º 6
0
// Get all resources for a note
void ResourceTable::getAllResources(QList<Resource> &list, qint32 noteLid, bool fullLoad, bool withBinary) {
    //NoteTable ntable(db);
    //QString noteGuid = ntable.getGuid(noteLid);
    NSqlQuery query(*db);
    QHash<qint32, Resource*> lidMap;
    if (fullLoad){
        query.prepare("Select key, data, lid from datastore where lid in (select lid from datastore where key=:key2 and data=:notelid) order by lid");
        query.bindValue(":key2", RESOURCE_NOTE_LID);
        query.bindValue(":noteLid", noteLid);
    } else {
        query.prepare("Select key, data, lid from datastore where key=:key and lid in (select lid from datastore where key=:key2 and data=:notelid) order by lid");
        query.bindValue(":key", RESOURCE_GUID);
        query.bindValue(":key2", RESOURCE_NOTE_LID);
        query.bindValue(":noteLid", noteLid);
    }
    Resource *r = NULL;
    query.exec();
    while (query.next()) {
        qint32 lid = query.value(2).toInt();
        if (!lidMap.contains(lid)) {
            r = new Resource();
            lidMap.insert(lid, r);
        } else {
            r = lidMap[lid];
        }
        mapResource(query, *r);
    }
    query.finish();

    // if we need binary data, read it in.  Then add to the list
    QHash<qint32, Resource*>::iterator i;
    list.clear();
    for (i=lidMap.begin(); i!=lidMap.end(); ++i) {
        if (withBinary && fullLoad) {
            Resource *r = i.value();
            qint32 lid = i.key();
            QString mimetype = r->mime;
            MimeReference ref;
            QString filename;
            ResourceAttributes attributes;
            if (r->attributes.isSet())
                attributes = r->attributes;
            if (attributes.fileName.isSet())
                filename = attributes.fileName;
            QString fileExt = ref.getExtensionFromMime(mimetype, filename);
            QFile tfile(global.fileManager.getDbDirPath("/dba/"+QString::number(lid)) +fileExt );
            if (!tfile.open(QIODevice::ReadOnly)) {
                QDir dir(global.fileManager.getDbaDirPath());
                QStringList filterList;
                filterList.append(QString::number(lid)+".*");
                QStringList list= dir.entryList(filterList, QDir::Files);
                if (list.size() > 0) {
                    tfile.setFileName(global.fileManager.getDbaDirPath()+list[0]);
                    tfile.open(QIODevice::ReadOnly);
                }
            }
            QByteArray b = tfile.readAll();
            Data d;
            if (r->data.isSet())
                d = r->data;
            d.body = b;
            r->data = d;
            tfile.close();
        }
        list.append(*i.value());
    }
}
Exemplo n.º 7
0
void  QQuickTextNodeEngine::addToSceneGraph(QQuickTextNode *parentNode,
        QQuickText::TextStyle style,
        const QColor &styleColor)
{
    if (m_currentLine.isValid())
        processCurrentLine();


    for (int i=0; i<m_backgrounds.size(); ++i) {
        const QRectF &rect = m_backgrounds.at(i).first;
        const QColor &color = m_backgrounds.at(i).second;

        parentNode->appendChildNode(new QSGSimpleRectNode(rect, color));
    }

    // First, prepend all selection rectangles to the tree
    for (int i=0; i<m_selectionRects.size(); ++i) {
        const QRectF &rect = m_selectionRects.at(i);

        parentNode->appendChildNode(new QSGSimpleRectNode(rect, m_selectionColor));
    }

    // Finally, add decorations for each node to the tree.
    for (int i=0; i<m_lines.size(); ++i) {
        const TextDecoration &textDecoration = m_lines.at(i);

        QColor color = textDecoration.selectionState == Selected
                       ? m_selectedTextColor
                       : textDecoration.color;

        parentNode->appendChildNode(new QSGSimpleRectNode(textDecoration.rect, color));
    }

    // Then, go through all the nodes for all lines and combine all QGlyphRuns with a common
    // font, selection state and clip node.
    typedef QPair<QFontEngine *, QPair<QQuickDefaultClipNode *, QPair<QRgb, int> > > KeyType;
    QHash<KeyType, BinaryTreeNode *> map;
    QList<BinaryTreeNode *> nodes;
    for (int i = 0; i < m_processedNodes.size(); ++i) {
        BinaryTreeNode *node = m_processedNodes.data() + i;

        if (node->image.isNull()) {
            QGlyphRun glyphRun = node->glyphRun;
            QRawFont rawFont = glyphRun.rawFont();
            QRawFontPrivate *rawFontD = QRawFontPrivate::get(rawFont);

            QFontEngine *fontEngine = rawFontD->fontEngine;

            KeyType key(qMakePair(fontEngine,
                                  qMakePair(node->clipNode,
                                            qMakePair(node->color.rgba(), int(node->selectionState)))));

            BinaryTreeNode *otherNode = map.value(key, 0);
            if (otherNode != 0) {
                QGlyphRun &otherGlyphRun = otherNode->glyphRun;

                QVector<quint32> otherGlyphIndexes = otherGlyphRun.glyphIndexes();
                QVector<QPointF> otherGlyphPositions = otherGlyphRun.positions();

                otherGlyphIndexes += glyphRun.glyphIndexes();

                QVector<QPointF> glyphPositions = glyphRun.positions();
                otherGlyphPositions.reserve(otherGlyphPositions.size() + glyphPositions.size());
                for (int j = 0; j < glyphPositions.size(); ++j) {
                    otherGlyphPositions += glyphPositions.at(j) + (node->position - otherNode->position);
                }

                otherGlyphRun.setGlyphIndexes(otherGlyphIndexes);
                otherGlyphRun.setPositions(otherGlyphPositions);

            } else {
                map.insert(key, node);
                nodes.append(node);
            }
        } else {
            parentNode->addImage(node->boundingRect, node->image);
            if (node->selectionState == Selected) {
                QColor color = m_selectionColor;
                color.setAlpha(128);
                parentNode->appendChildNode(new QSGSimpleRectNode(node->boundingRect, color));
            }
        }
    }

    foreach (const BinaryTreeNode *node, nodes) {

        QQuickDefaultClipNode *clipNode = node->clipNode;
        if (clipNode != 0 && clipNode->parent() == 0 )
            parentNode->appendChildNode(clipNode);

        QColor color = node->selectionState == Selected
                       ? m_selectedTextColor
                       : node->color;

        parentNode->addGlyphs(node->position, node->glyphRun, color, style, styleColor, clipNode);
    }
Exemplo n.º 8
0
bool UPNPSubscription::ProcessRequest(HttpWorkerThread *pThread,
                                      HTTPRequest *pRequest)
{
    (void)pThread;
    if (!pRequest)
        return false;

    if (pRequest->m_sBaseUrl != "/Subscriptions")
        return false;
    if (pRequest->m_sMethod != "event")
        return false;

    LOG(VB_UPNP, LOG_DEBUG, QString("%1\n%2")
        .arg(pRequest->m_sRawRequest).arg(pRequest->m_sPayload));

    if (pRequest->m_sPayload.isEmpty())
        return true;

    pRequest->m_eResponseType = ResponseTypeHTML;

    QString nt  = pRequest->m_mapHeaders["nt"];
    QString nts = pRequest->m_mapHeaders["nts"];
    bool    no  = pRequest->m_sRawRequest.startsWith("NOTIFY");

    if (nt.isEmpty() || nts.isEmpty() || !no)
    {
        pRequest->m_nResponseStatus = 400;
        return true;
    }

    pRequest->m_nResponseStatus = 412;
    if (nt != "upnp:event" || nts != "upnp:propchange")
        return true;

    QString usn = pRequest->m_mapParams["usn"];
    QString sid = pRequest->m_mapHeaders["sid"];
    if (usn.isEmpty() || sid.isEmpty())
        return true;

    // N.B. Validating the usn and uuid here might mean blocking for some time
    // while waiting for a subscription to complete. While this operates in a
    // worker thread, worker threads are a limited resource which we could
    // rapidly overload if a number of events arrive. Instead let the
    // subscribing objects validate the usn - the uuid should be superfluous.

    QString seq = pRequest->m_mapHeaders["seq"];

    // mediatomb sends some extra character(s) at the end of the payload
    // which throw Qt, so try and trim them off
    int loc = pRequest->m_sPayload.lastIndexOf("propertyset>");
    QString payload = (loc > -1) ? pRequest->m_sPayload.left(loc + 12) :
                                   pRequest->m_sPayload;

    LOG(VB_UPNP, LOG_DEBUG, QString("Payload:\n%1").arg(payload));

    pRequest->m_nResponseStatus = 400;
    QDomDocument body;
    QString error;
    int errorCol = 0;
    int errorLine = 0;
    if (!body.setContent(payload, true, &error, &errorLine, &errorCol))
    {
        LOG(VB_GENERAL, LOG_ERR,
            QString("Failed to parse event: Line: %1 Col: %2 Error: '%3'")
            .arg(errorLine).arg(errorCol).arg(error));
        return true;
    }

    VERBOSE(VB_UPNP|VB_EXTRA, "/n/n" + body.toString(4) + "/n/n");

    QDomNodeList properties = body.elementsByTagName("property");
    QHash<QString,QString> results;

    // this deals with both one argument per property (compliant) and mutliple
    // arguments per property as sent by mediatomb
    for (int i = 0; i < properties.size(); i++)
    {
        QDomNodeList arguments = properties.at(i).childNodes();
        for (int j = 0; j < arguments.size(); j++)
        {
            QDomElement e = arguments.at(j).toElement();
            if (!e.isNull() && !e.text().isEmpty() && !e.tagName().isEmpty())
                results.insert(e.tagName(), e.text());
        }
    }

    // using MythObservable allows multiple objects to subscribe to the same
    // service but is less efficient from an eventing perspective, especially
    // if multiple objects are subscribing
    if (!results.isEmpty())
    {
        pRequest->m_nResponseStatus = 200;
        results.insert("usn", usn);
        results.insert("seq", seq);
        MythInfoMapEvent me("UPNP_EVENT", results);
        dispatch(me);
    }

    return true;
}