Ejemplo n.º 1
0
bool QBluetoothServiceInfoPrivate::registerService(const QBluetoothAddress& localAdapter)
{
    Q_UNUSED(localAdapter); //QNX always uses default local adapter
    if (protocolDescriptor(QBluetoothUuid::Rfcomm).isEmpty()) {
        qCWarning(QT_BT_QNX) << Q_FUNC_INFO << "Only SPP services can be registered on QNX";
        return false;
    }

    if (serverChannel() == -1)
        return false;

    if (__fakeServerPorts.key(serverChannel()) != 0) {
        if (!ppsSendControlMessage("register_server", 0x1101, attributes.value(QBluetoothServiceInfo::ServiceId).value<QBluetoothUuid>(), QString(),
                                   attributes.value(QBluetoothServiceInfo::ServiceName).toString(),
                              __fakeServerPorts.key(serverChannel()), BT_SPP_SERVER_SUBTYPE))
            return false;
        //The server needs to know the service name for the socket mount point path
        __fakeServerPorts.key(serverChannel())->m_serviceName = attributes.value(QBluetoothServiceInfo::ServiceName).toString();
    } else {
        return false;
    }

    registered = true;
    return true;
}
bool QBluetoothServiceInfoPrivate::unregisterService()
{
    if (!registered)
        return false;
    if (serverChannel() == -1)
        return false;
    if ( __fakeServerPorts.key(serverChannel()) != 0) {
#ifdef QT_QNX_BT_BLUETOOTH
        QByteArray b_uuid = attributes.value(QBluetoothServiceInfo::ServiceId).
                value<QBluetoothUuid>().toByteArray();
        b_uuid = b_uuid.mid(1, b_uuid.length() - 2);
        if (bt_spp_close_server(b_uuid.data()) == -1)
            return false;
#else
        if (!ppsSendControlMessage("deregister_server", 0x1101, attributes.value(QBluetoothServiceInfo::ServiceId).value<QBluetoothUuid>(), QString(),
                                   attributes.value(QBluetoothServiceInfo::ServiceName).toString(),
                                   __fakeServerPorts.key(serverChannel()), BT_SPP_SERVER_SUBTYPE)) {
            return false;
        }
#endif
        else {
            __fakeServerPorts.remove(__fakeServerPorts.key(serverChannel()));
            registered = false;
            return true;
        }
    }
    else {
        return false;
    }
}
Ejemplo n.º 3
0
bool SalesModel::setProperty(int rowIndex, const QString &property, const QVariant &value)
{

    QVariantMap rowValues = getProperty(rowIndex);
    const char * UPDATE_STAMENT="UPDATE items_sales set price = :price WHERE prov = :prov and ref = :ref "
            "and size = :size and color = :color and sales_date = :sales_date;";
    m_updateQuery.prepare(UPDATE_STAMENT);
    m_updateQuery.bindValue(":ref",rowValues["ref"]);
    m_updateQuery.bindValue(":size",rowValues["size"]);
    m_updateQuery.bindValue(":color",rowValues["color"]);
    m_updateQuery.bindValue(":prov",rowValues["prov"]);
    m_updateQuery.bindValue(":sales_date",rowValues["date"]);
    m_updateQuery.bindValue(":price", value);
    if(!m_updateQuery.exec()){
        qWarning()<<"could no update sales "<<m_updateQuery.lastQuery();
        return false;

    }
    qDebug()<<"price updated "<<value;
    QHash<int, QByteArray> roles = roleNames();
    QModelIndex ind = index(rowIndex,roles.key("price"));
    QSqlQuery q = query();
    q.exec();
    setQuery(q);

    emit dataChanged(ind,ind);
    return true;

}
Ejemplo n.º 4
0
static void removeMenuAllActions(QMenu *pMenu)
{
	QList<QAction*> pActionsList=pMenu->actions();
	QList<QAction*> pActionsListDictValues=actionsDict.values();
	for(int i=0;i<pActionsList.count();i++)
	{
		int iIdx=pActionsListDictValues.indexOf(pActionsList.at(i));
		if (iIdx>=0) actionsDict.remove(actionsDict.key(pActionsList.at(i)));
	}
}
bool QBluetoothServiceInfoPrivate::registerService(const QBluetoothAddress& localAdapter)
{
    Q_UNUSED(localAdapter); //QNX always uses default local adapter
    if (protocolDescriptor(QBluetoothUuid::Rfcomm).isEmpty()) {
        qCWarning(QT_BT_QNX) << Q_FUNC_INFO << "Only SPP services can be registered on QNX";
        return false;
    }

    if (serverChannel() == -1)
        return false;

    if (__fakeServerPorts.key(serverChannel()) != 0) {
#ifdef QT_QNX_BT_BLUETOOTH
        QByteArray b_uuid = attributes.value(QBluetoothServiceInfo::ServiceId)
                .value<QBluetoothUuid>().toByteArray();
        b_uuid = b_uuid.mid(1, b_uuid.length() - 2);
        qCDebug(QT_BT_QNX) << "Registering server. " << b_uuid.data()
                           << attributes.value(QBluetoothServiceInfo::ServiceName)
                              .toString();
        if (bt_spp_open_server(attributes.value(QBluetoothServiceInfo::ServiceName)
                               .toString().toUtf8().data(),
                               b_uuid.data(), true, &QBluetoothServerPrivate::btCallback,
                               reinterpret_cast<long>(__fakeServerPorts.key(serverChannel()))) == -1) {
            qCDebug(QT_BT_QNX) << "Could not open the server. "
                               << qt_error_string(errno) << errno;
            bt_spp_close_server(b_uuid.data());
            return false;
        }
#else
        if (!ppsSendControlMessage("register_server", 0x1101, attributes.value(QBluetoothServiceInfo::ServiceId).value<QBluetoothUuid>(), QString(),
                                   attributes.value(QBluetoothServiceInfo::ServiceName).toString(),
                              __fakeServerPorts.key(serverChannel()), BT_SPP_SERVER_SUBTYPE))
            return false;
#endif
        //The server needs to know the service name for the socket mount point path
        __fakeServerPorts.key(serverChannel())->m_serviceName = attributes.value(QBluetoothServiceInfo::ServiceName).toString();
    } else {
        return false;
    }

    registered = true;
    return true;
}
bool QxtGlobalShortcutPrivate::nativeEventFilter(const QByteArray &, void *message, long *)
{
    EventRef event = (EventRef) message;
    if (GetEventClass(event) == kEventClassKeyboard && GetEventKind(event) == kEventHotKeyPressed)
    {
        EventHotKeyID keyID;
        GetEventParameter(event, kEventParamDirectObject, typeEventHotKeyID, nullptr, sizeof(keyID), nullptr, &keyID);
        Identifier id = keyIDs.key(keyID.id);
        activateShortcut(id.second, id.first);
    }
    return false;
}
Ejemplo n.º 7
0
OSStatus qxt_mac_handle_hot_key(EventHandlerCallRef nextHandler, EventRef event, void* data)
{
    Q_UNUSED(nextHandler);
    Q_UNUSED(data);
    if (GetEventClass(event) == kEventClassKeyboard && GetEventKind(event) == kEventHotKeyPressed)
    {
        EventHotKeyID keyID;
        GetEventParameter(event, kEventParamDirectObject, typeEventHotKeyID, NULL, sizeof(keyID), NULL, &keyID);
        Identifier id = keyIDs.key(keyID.id);
        QxtGlobalShortcutPrivate::activateShortcut(id.second, id.first);
    }
    return noErr;
}
Ejemplo n.º 8
0
bool QxtGlobalShortcutPrivate::eventFilter(void* message)
//bool QxtGlobalShortcutPrivate::macEventFilter(EventHandlerCallRef caller, EventRef event)
{
    EventRef event = (EventRef) message;
    if (GetEventClass(event) == kEventClassKeyboard && GetEventKind(event) == kEventHotKeyPressed)
    {
        EventHotKeyID keyID;
        GetEventParameter(event, kEventParamDirectObject, typeEventHotKeyID, NULL, sizeof(keyID), NULL, &keyID);
        Identifier id = keyIDs.key(keyID.id);
        activateShortcut(id.second, id.first);
    }
    return false;
}
Ejemplo n.º 9
0
const QHash<QString, QMPointer<QMJsonValue> >::iterator QMJsonObject::erase(const QHash<QString, QMPointer<QMJsonValue> >::iterator &iter)
{
    if (iter == mHash.end())
        return mHash.end();

    auto key = iter.key();
    auto value = iter.value();

    auto niter = mHash.erase(iter);
    emit itemRemoved(key, value);

    return niter;
}
Ejemplo n.º 10
0
int main()
{
    QString str;
    QTextStream in(stdin);

    QFile sout;
    sout.open(stdout, QIODevice::WriteOnly);
    QDataStream out(&sout);

    bool ok = true, ok2;
    QHash<quint32,quint8> data;
    QHash<qint8,QString> catalog;

    while ( ok )
    {
        QString line = in.readLine();
        ok =  !in.atEnd();

        if ( line.isEmpty() || line.startsWith('#') )
            continue;

        QRegExp rx(";");
        int split = rx.indexIn(line);

        QString catagoryString = line.right( line.size() - split - 1 ).simplified();

        qint8 catagory = catalog.key(catagoryString);
        if(!catagory)
        {
            catalog[ catagory = catalog.size()+1 ] = catagoryString;
        }

        QString codes = line.left( split ).simplified();
        QStringList codeList = codes.split ( ".." );

        quint32 start = codeList.at(0).toInt(&ok2, 16);
        quint32 end = (codeList.size() == 2) ? codeList.at(1).toInt(&ok2, 16) : start;
        for (quint32 code = start; code<=end; ++code)
        {
            data.insert( code, catagory );
            qDebug() << "[" << catagory << "] " << code;
        }
    }

    out << catalog << data;
}
Ejemplo n.º 11
0
void MainWindow::saveScreen()
{
    // create initial filepath
    QHash<QString, QString> formatsAvalible;

    formatsAvalible["png"] = tr("PNG Files");
    formatsAvalible["jpg"] = tr("JPEG Files");

    QString format = "png";
    _conf->getSaveFormat();

    Core* c = Core::instance();
    QString filePath = c->getSaveFilePath(format);

    // create file filters
    QString fileFilters;

    QString filterSelected;
    filterSelected = formatsAvalible[format];

    QHash<QString, QString>::const_iterator iter = formatsAvalible.constBegin();
    while (iter != formatsAvalible.constEnd())
    {
        fileFilters.append(iter.value() + " (*." + iter.key() + ");;");
        ++iter;
    }
    fileFilters.chop(2);

    QString fileName;
    fileName = QFileDialog::getSaveFileName(this, tr("Save As..."),  filePath, fileFilters, &filterSelected, QFileDialog::DontUseNativeDialog);

    QRegExp rx("\\(\\*\\.[a-z]{3,4}\\)");
    quint8 tmp = filterSelected.size() - rx.indexIn(filterSelected);

    filterSelected.chop(tmp + 1);
    format = formatsAvalible.key(filterSelected);

    // if user canceled saving
    if (fileName.isEmpty())
        return;

    c->writeScreen(fileName, format);
}
Ejemplo n.º 12
0
double AssetsIO::getRate(const QDate &date, double duration) {
    Q_UNUSED(date);
    double rate = 0.00;
    QHash<QString,QDate> hashRatesDates;
    QStringList listChosenOfRanges;
    AssetsRatesModel model(this);
    if (WarnDebugMessage)
        qDebug() << __FILE__ << QString::number(__LINE__) << " model.rowCount() =" << QString::number(model.rowCount()) ;
    for (int i = 0; i < model.rowCount(); i += 1) {
        QDate dateRequest = model.data(model.index(i,ASSETSRATES_DATE),Qt::DisplayRole).toDate();
        QString rangeReq = model.data(model.index(i,ASSETSRATES_YEARS),Qt::DisplayRole).toString();
        QString rate = model.data(model.index(i,ASSETSRATES_RATES),Qt::DisplayRole).toString();
        if (WarnDebugMessage)
            qDebug() << __FILE__ << QString::number(__LINE__) << " rangeReq and rate =" << rangeReq+" "+rate ;
        QStringList listOfRanges = rangeReq.split("_");
        if (int(duration) >= listOfRanges[0].toInt() && int(duration) <= listOfRanges[1].toInt()) {
            hashRatesDates.insertMulti(rate,dateRequest) ;
        }
    }
    QList<QDate> valuesOfDates = hashRatesDates.values();
    if (WarnDebugMessage)
        qDebug() << __FILE__ << QString::number(__LINE__) << " valuesOfDates size =" << QString::number(valuesOfDates.size()) ;
    if (hashRatesDates.size() < 1) {
        Utils::warningMessageBox(tkTr(Trans::Constants::ERROR),
                                 tr("You have to fill defaults for assets rates.\nGo "
                                    "in Configuration>Preferences to do so.\n"
                                    "Otherwise result will be wrong !"));
        return 1.00;
    }
    qSort(valuesOfDates.begin(),valuesOfDates.end());

    QDate nearestDate = valuesOfDates.last();
    QString nearestDateStr = nearestDate.toString("yyyy-MM-dd");
    QString rateStr = hashRatesDates.key(nearestDate);
    rate = rateStr.toDouble();
    qWarning() << __FILE__ << QString::number(__LINE__) << "rate = " << QString::number(rate) ;
    return rate;
}
Ejemplo n.º 13
0
int TwoDModelEngineApi::readColorFullSensor(QHash<uint, int> const &countsColor) const
{
	if (countsColor.isEmpty()) {
		return 0;
	}

	QList<int> const values = countsColor.values();
	int maxValue = INT_MIN;
	for (int value : values) {
		if (value > maxValue) {
			maxValue = value;
		}
	}

	const uint maxColor = countsColor.key(maxValue);
	switch (maxColor) {
	case (black):
		return 1;
	case (red):
		return 5;
	case (green):
		return 3;
	case (blue) :
		return 2;
	case (yellow):
		return 4;
	case (white):
		return 6;
	case (cyan):
		return 7;
	case (magenta):
		return 8;
	default:
		return 0;
	}
}
Ejemplo n.º 14
0
void ChatWindowStyle::readStyleFiles()
{
    // load style info
    QString infoPlistFile = d->baseHref + QLatin1String("../Info.plist");
    ChatStylePlistFileReader plistReader(infoPlistFile);
    d->defaultVariantName = plistReader.defaultVariant();
    if (d->defaultVariantName.isEmpty()) {
        // older themes use this
        d->defaultVariantName = plistReader.displayNameForNoVariant();
    }
    if (d->defaultVariantName.isEmpty()) {
        // If name is still empty we use "Normal"
        d->defaultVariantName = i18nc("Normal style variant menu item", "Normal");
    }
    qCDebug(KTP_TEXTUI_LIB) << "defaultVariantName = " << d->defaultVariantName;
    d->defaultFontFamily  = plistReader.defaultFontFamily().isEmpty() ? QFontDatabase::systemFont(QFontDatabase::GeneralFont).family()
                                                                      : plistReader.defaultFontFamily();

    // If the theme has no default font size, use the system font size, but since that is in points (pt), we need to convert
    // it to pixel size (and using pixelSize() does not work if the QFont was not set up using setPixelSize), so we use the
    // rough conversion ratio 4/3 and floor the number
    d->defaultFontSize    = plistReader.defaultFontSize() == 0 ? qFloor(QFontDatabase::systemFont(QFontDatabase::GeneralFont).pointSizeF() * (4.0/3.0))
                                                               : plistReader.defaultFontSize();
    d->disableCombineConsecutive = plistReader.disableCombineConsecutive();
    d->messageViewVersion = plistReader.messageViewVersion();

    // specify the files for the identifiers
    QHash<InternalIdentifier, QLatin1String> templateFiles;

    templateFiles.insert(Template, QLatin1String("Template.html"));

    templateFiles.insert(Header, QLatin1String("Header.html"));
    templateFiles.insert(Content, QLatin1String("Content.html"));
    templateFiles.insert(Footer, QLatin1String("Footer.html"));
    templateFiles.insert(Topic, QLatin1String("Topic.html"));

    templateFiles.insert(IncomingContent, QLatin1String("Incoming/Content.html"));
    templateFiles.insert(IncomingNextContent, QLatin1String("Incoming/NextContent.html"));
    templateFiles.insert(OutgoingContent, QLatin1String("Outgoing/Content.html"));
    templateFiles.insert(OutgoingNextContent, QLatin1String("Outgoing/NextContent.html"));
    templateFiles.insert(Status, QLatin1String("Status.html"));

    templateFiles.insert(IncomingHistory, QLatin1String("Incoming/Context.html"));
    templateFiles.insert(IncomingNextHistory, QLatin1String("Incoming/NextContext.html"));
    templateFiles.insert(OutgoingHistory, QLatin1String("Outgoing/Context.html"));
    templateFiles.insert(OutgoingNextHistory, QLatin1String("Outgoing/NextContext.html"));

    templateFiles.insert(ActionIncoming, QLatin1String("Incoming/Action.html"));
    templateFiles.insert(ActionOutgoing, QLatin1String("Outgoing/Action.html"));

    templateFiles.insert(FileTransferIncoming, QLatin1String("FileTransferRequest.html"));
    templateFiles.insert(VoiceClipIncoming, QLatin1String("voiceClipRequest.html"));

    templateFiles.insert(OutgoingStateUnknown, QLatin1String("Outgoing/StateUnknown.html"));
    templateFiles.insert(OutgoingStateSending, QLatin1String("Outgoing/StateSending.html"));
    templateFiles.insert(OutgoingStateSent, QLatin1String("Outgoing/StateSent.html"));
    templateFiles.insert(OutgoingStateError, QLatin1String("Outgoing/StateError.html"));


    // load all files
    QFile fileAccess;
    Q_FOREACH(const QLatin1String &fileName, templateFiles) {
        QString path = d->baseHref + fileName;
        // Load template file
        if (QFile::exists(path)) {
            fileAccess.setFileName(path);
            fileAccess.open(QIODevice::ReadOnly);
            QTextStream headerStream(&fileAccess);
            headerStream.setCodec(QTextCodec::codecForName("UTF-8"));
            QString data = headerStream.readAll();
            if(!data.isEmpty()) {
                //qCDebug(KTP_TEXTUI_LIB) << fileName << "was found!";
                setContent( templateFiles.key(fileName), data);
            } else {
                qCDebug(KTP_TEXTUI_LIB) << fileName << "was not found!";
            }
            //qCDebug(KTP_TEXTUI_LIB) << fileName << content(templateFiles.key(fileName));
            fileAccess.close();
        }
    }
Ejemplo n.º 15
0
void ChatWindowStyle::readStyleFiles()
{
    // load style info
    QString infoPlistFile = d->baseHref + QLatin1String("../Info.plist");
    ChatStylePlistFileReader plistReader(infoPlistFile);
    d->defaultVariantName = plistReader.defaultVariant();
    if (d->defaultVariantName.isEmpty()) {
        // older themes use this
        d->defaultVariantName = plistReader.displayNameForNoVariant();
    }
    if (d->defaultVariantName.isEmpty()) {
        // If name is still empty we use "Normal"
        d->defaultVariantName = i18nc("Normal style variant menu item", "Normal");
    }
    kDebug() << "defaultVariantName = " << d->defaultVariantName;
    d->defaultFontFamily  = plistReader.defaultFontFamily();
    d->defaultFontSize    = plistReader.defaultFontSize();
    d->disableCombineConsecutive = plistReader.disableCombineConsecutive();
    d->messageViewVersion = plistReader.messageViewVersion();

    // specify the files for the identifiers
    QHash<InternalIdentifier, QLatin1String> templateFiles;

    templateFiles.insert(Template, QLatin1String("Template.html"));

    templateFiles.insert(Header, QLatin1String("Header.html"));
    templateFiles.insert(Content, QLatin1String("Content.html"));
    templateFiles.insert(Footer, QLatin1String("Footer.html"));
    templateFiles.insert(Topic, QLatin1String("Topic.html"));

    templateFiles.insert(IncomingContent, QLatin1String("Incoming/Content.html"));
    templateFiles.insert(IncomingNextContent, QLatin1String("Incoming/NextContent.html"));
    templateFiles.insert(OutgoingContent, QLatin1String("Outgoing/Content.html"));
    templateFiles.insert(OutgoingNextContent, QLatin1String("Outgoing/NextContent.html"));
    templateFiles.insert(Status, QLatin1String("Status.html"));

    templateFiles.insert(IncomingHistory, QLatin1String("Incoming/Context.html"));
    templateFiles.insert(IncomingNextHistory, QLatin1String("Incoming/NextContext.html"));
    templateFiles.insert(OutgoingHistory, QLatin1String("Outgoing/Context.html"));
    templateFiles.insert(OutgoingNextHistory, QLatin1String("Outgoing/NextContext.html"));

    templateFiles.insert(ActionIncoming, QLatin1String("Incoming/Action.html"));
    templateFiles.insert(ActionOutgoing, QLatin1String("Outgoing/Action.html"));

    templateFiles.insert(FileTransferIncoming, QLatin1String("FileTransferRequest.html"));
    templateFiles.insert(VoiceClipIncoming, QLatin1String("voiceClipRequest.html"));

    templateFiles.insert(OutgoingStateUnknown, QLatin1String("Outgoing/StateUnknown.html"));
    templateFiles.insert(OutgoingStateSending, QLatin1String("Outgoing/StateSending.html"));
    templateFiles.insert(OutgoingStateSent, QLatin1String("Outgoing/StateSent.html"));
    templateFiles.insert(OutgoingStateError, QLatin1String("Outgoing/StateError.html"));


    // load all files
    QFile fileAccess;
    Q_FOREACH(const QLatin1String &fileName, templateFiles) {
        QString path = d->baseHref + fileName;
        // Load template file
        if (QFile::exists(path)) {
            fileAccess.setFileName(path);
            fileAccess.open(QIODevice::ReadOnly);
            QTextStream headerStream(&fileAccess);
            headerStream.setCodec(QTextCodec::codecForName("UTF-8"));
            QString data = headerStream.readAll();
            if(!data.isEmpty()) {
                //kDebug() << fileName << "was found!";
                setContent( templateFiles.key(fileName), data);
            } else {
                kDebug() << fileName << "was not found!";
            }
            //kDebug() << fileName << content(templateFiles.key(fileName));
            fileAccess.close();
        }
    }
Ejemplo n.º 16
0
NodeType_t NodeType::fromString(QString type) {
    return TYPE_NAME_HASH.key(type, NodeType::Unassigned);
}
Ejemplo n.º 17
0
void dumpColors(const QHash<QPair<QString, int>, QColor> &colors) {
    foreach (const QColor &color, colors.values()) {
        const QPair<QString, int> key = colors.key(color);
        qDebug() << key << color;
    }
}
Ejemplo n.º 18
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QTextStream  cout (stdout);
    
/*    for (int i=1; i<argc; i++)
    {
        cout<<argv[i];
        cout<<"\n";
    }  */
    /*leftthumb.txt out.txt 0.9 0.0001*/
    QString infileName (argv [1]);
    QString outfileName (argv [2]);

    double start;// = QString(argv[3]).toDouble();
    double step;// = QString(argv[4]).toDouble();


    cout<<"contendor version";
    cout<<infileName;
    cout <<"\n";
    cout<<outfileName;
    cout <<"\n";
    //cout<<start;
    cout <<"\n";
    //cout<<step;
    cout <<"\n";

    QList <double> thresholds;
    thresholds<<0.9 << 0.99 << 0.999 << 0.9999 << 1;

    makeFRRForAllFingers(infileName, thresholds).outTableToTextFile(outfileName);



//    TableContendor cnt (1,1);



//    cnt.readFileIntoContendor("tablein.txt");
  //  cnt.outTableToTextFile("tableout.txt");

    return 0;


    //return    onArrayOfThresholds (infileName, outfileName);







    QList <double> listOfValues; //список значений, читаемый из файла
    /*
        Временное решение проблемы - потом, наверное, считывать придётся в табличный контейнер или нечто типа того
    */

    QFile infile (infileName);

    if (!infile.open(QIODevice::ReadOnly | QIODevice::Text      ))
{
        cout<<"Error: infile cannot be opened";
        cout.flush();
        return -1;
    }
    QTextStream str (&infile);
    while(!str.atEnd())
    {
        listOfValues.append(str.readLine().toDouble());
    }
    QHash <int, int> counterValuesLowerThanThreshold;
    //сраный костыль, ибо qHash не может быть с ключом типа double, просто не может, трололо!!!!
//первое значение - ключ
    QHash <int, double> keytable;
//заполняем таблицу порогов
    int j=0;
    for (double i=start; i<=1; i+=step)
    {
        keytable.insert(j,i);
        counterValuesLowerThanThreshold.insert(j,0);
        j++;
    }
    //зерно алгоритма
    foreach (double val, listOfValues)
    {
               {

        for (double i=start; i<=1; i+=step)
            if (val<=i)
            {
    //сраные костыли во все поляяяя!!
                //тролли советуют написать-таки реализацию qHash()с double, вкупе с оператором ==()
                counterValuesLowerThanThreshold.insert(keytable.key(i),counterValuesLowerThanThreshold.value(keytable.key(i))+1  );
                //counterValuesLowerThanThreshold.insert(i,counterValuesLowerThanThreshold.value(i)+1);
            }
        }
    }
Ejemplo n.º 19
0
QUuid uuidOfIndex(int index)
{
    return (sCacheHash.key(index,QUuid()));
}
Ejemplo n.º 20
0
#include <Carbon/Carbon.h>

typedef QPair<uint, uint> Identifier;
static QMap<quint32, EventHotKeyRef> keyRefs;
static QHash<Identifier, quint32> keyIDs;
static quint32 hotKeySerial = 0;
static bool qxt_mac_handler_installed = false;

OSStatus qxt_mac_handle_hot_key(EventHandlerCallRef nextHandler, EventRef event, void *data)
{
    Q_UNUSED(nextHandler)
    Q_UNUSED(data)
    if (GetEventClass(event) == kEventClassKeyboard && GetEventKind(event) == kEventHotKeyPressed) {
        EventHotKeyID keyID;
        GetEventParameter(event, kEventParamDirectObject, typeEventHotKeyID, NULL, sizeof(keyID), NULL, &keyID);
        Identifier id = keyIDs.key(keyID.id);
        QxtGlobalShortcutPrivate::activateShortcut(id.second, id.first);
    }
    return noErr;
}

bool QxtGlobalShortcutPrivate::nativeEventFilter(const QByteArray & eventType,
                                                 void *message, long *result)
{
    Q_UNUSED(eventType)
    Q_UNUSED(message)
    Q_UNUSED(result)
    return false;
}

quint32 QxtGlobalShortcutPrivate::nativeModifiers(Qt::KeyboardModifiers modifiers)
Ejemplo n.º 21
0
QNetworkReply *Parse::query(QString endPoint, QUrlQuery extraParams)
{
    if (!isReady()) return NULL;

    if (extraParams.isEmpty())
        setEndPoint(endPoint);
    else setEndPoint( endPoint + "?" + extraParams.toString() ); //TODO improve me : not use endpoint to give url encoded params

    ensureEndPointHasPrefix("classes");

    m_conn = connect(this, &BaaS::replyFinished, [=](QJsonDocument json, QNetworkReply *reply){
        disconnect(m_conn);
        if (isLastRequestSuccessful()){
                //structure to return from parse
                QHash<int, QByteArray> roles = QHash<int, QByteArray>();
                QVector<QVariantMap> data = QVector<QVariantMap>();

                Q_ASSERT(json.isObject());
                QJsonObject obj = json.object();
                QJsonValue tmp = obj.value("results");

                if (tmp.isArray()){
                    QJsonArray res = tmp.toArray();
                    for ( QJsonValue elem: res){
                        if (elem.isObject()){
                            obj = elem.toObject();

                            //Update roles
                            QStringList keys = obj.keys();
                            for (QString roleName : keys )
                            {
                                if ( roles.key( roleName.toUtf8(), -1) == -1)
                                    roles[roles.size()] = roleName.toUtf8();
                            }
                            //Add values
                            data.push_back( obj.toVariantMap());


                        }
                    }

                    emit querySucceeded(roles, data, reply);
                }
                //else if (tmp.isObject()){
                    //obj = tmp.toObject();//Update roles
                else {
                    QStringList keys = obj.keys();
                    for (QString roleName : keys )
                    {
                        if ( roles.key( roleName.toUtf8(), -1) == -1)
                            roles[roles.size()] = roleName.toUtf8();
                    }
                    //Add values
                    data.push_back( obj.toVariantMap());
                    emit querySucceeded(roles, data, reply);
                }
        }
    } );

    initHeaders();
    return request( BaaS::GET);

}
Ejemplo n.º 22
0
void AnalysisDialog::showAnalysisResults() {

    lastCalcDateTime =
            QDateTime::currentDateTime().toString("dd-MM-yyyy_hh-mm-ss");

    const bool showImg = settings->val_showImgInReport();
    const bool createTmpImgFiles = settings->val_createTmpImg();
    const ptrdiff_t imgWidth = settings->val_imgWidth();

    createGraphics(graphics,
                   material1,
                   material2,
                   settings,
                   tempPath + QDir::separator() + lastCalcDateTime);

    if ( graphics.isEmpty() ) {

        freeMemory();
        QMessageBox::warning(this, "mixan", tr("Can not create graphics!"));

        return;
    }

    //

    report->moveCursor(QTextCursor::End);

    report->insertHtml(
                "<b>"
                + lastCalcDateTime
                + "</b><br><br>"
                + tr("Settings")
                + "<br>* "
                + tr("Type of analysis")
                + ": "
                + ui->comboBox_analysisType->currentText()
                + "<br>* "
                + tr("Power of the approximate polynom")
                + ": "
                + QString::number(settings->val_polyPwr())
                + "<br>* "
                + tr("Method of threshold color definition")
                + ": ");

    if ( settings->val_thrColDefMethod() == THRCOLDEFMETHOD_POLYAPPROX ) {

        report->insertHtml(
                    tr("Through polynomial approximation")
                    );
    }
    else {

        report->insertHtml(
                    tr("Through gravity centers")
                    );
    }

    report->insertHtml(
                + "<br>* "
                + tr("Accuracy of color threshold determining")
                + ": "
                + QString::number(settings->val_thrAccur())
                );

    if ( ui->comboBox_analysisType->currentIndex() == ANALTYPE_MIX ) {

        report->insertHtml(
                    "<br>* "
                    + tr("Ideal concentration")
                    + ": "
                    + QString::number(settings->val_idealConc())
                    );
    }
    else if ( ui->comboBox_analysisType->currentIndex() ==
              ANALTYPE_GRANULATION ) {

        report->insertHtml(
                    "<br>* "
                    + tr("Pixels per square millimeter")
                    + ": "
                    + QString::number(settings->val_pxpermm2())
                    );

        if ( settings->val_sievesCellDiameter().isEmpty() ) {

            report->insertHtml(
                        "<br>* "
                        + tr("Sieves cell diameter, mm")
                        + ": "
                        + tr("no values")
                        );
        }
        else {

            report->insertHtml(
                        "<br>* "
                        + tr("Sieves cell diameter, mm")
                        + ": "
                        + settings->val_sievesCellDiameter()
                        );
        }

        if ( settings->val_sievesCellDimension().isEmpty() ) {

            report->insertHtml(
                        "<br>* "
                        + tr("Sieves cell dimension, mm")
                        + ": "
                        + tr("no values")
                        );
        }
        else {

            report->insertHtml(
                        "<br>* "
                        + tr("Sieves cell dimension, mm")
                        + ": "
                        + settings->val_sievesCellDimension()
                        );
        }
    }

    if ( !thrmsg.isEmpty() ) {

        report->insertHtml("<br><br><b>" + thrmsg + "</b><br><hr><br>");
        report->moveCursor(QTextCursor::End);

        thrmsg.clear();
        freeMemory();

        return;
    }

    report->insertHtml(
                "<br><br>"
                + tr("First material image file")
                + ": "
                + ui->lineEdit_mat1FileName->text()
                );

    if ( showImg ) {

        report->insertHtml(
                    "<br><br>"
                    + tr("Image of the first material")
                    + ":<br>"
                    );

        if ( material1->originalImage().width() > imgWidth ) {

            report->textCursor().insertImage(
                        material1->
                        originalImage().scaledToWidth(imgWidth)
                        );
        }
        else {

            report->textCursor().insertImage(material1->originalImage());
        }
    }

    report->insertHtml(
                "<br><br>"
                + tr("Second material image file")
                + ": "
                + ui->lineEdit_mat2FileName->text());

    if ( showImg ) {

        report->insertHtml(
                    "<br><br>"
                    + tr("Image of the second material")
                    + ":<br>"
                    );

        if ( material2->originalImage().width() > imgWidth ) {

            report->textCursor().insertImage(
                        material2->
                        originalImage().scaledToWidth(imgWidth)
                        );
        }
        else {

            report->textCursor().insertImage(material2->originalImage());
        }
    }

    report->insertHtml(
                "<br><br>"
                + tr("Visualization of the calculated "
                     "gray color threshold. "
                     "Histograms (with polynoms) and threshold color.")
                + ":<br>"
                );
    report->textCursor().insertImage(graphics[0]);

    report->insertHtml("<br>");

    //

    if ( ui->comboBox_analysisType->currentIndex() == ANALTYPE_MIX &&
         probes.size() != 0 ) {

        QString imgname;

        double conc = 0;
        QVector<double> concs;

        for ( ptrdiff_t i=0; i<probes.size(); i++ ) {

            imgname = probes[i]->imageFileName();

            if ( imgname.isEmpty() ) {

                report->insertHtml(
                            "<br><b>"
                            + tr("Analysis of image")
                            + " "
                            + imgname
                            + " "
                            + tr("failed or canceled")
                            + ".</b>"
                            );

                continue;
            }

            conc = probes[i]->concentration();
            concs.push_back(conc);

            if ( showImg ) {

                report->insertHtml(
                            "<br>"
                            + tr("Mix image")
                            + ":<br>"
                            );

                if ( probes[i]->originalImage().width() > imgWidth ) {

                    report->textCursor().insertImage(
                                probes[i]->originalImage().
                                scaledToWidth(settings->val_imgWidth())
                                );
                }
                else {

                    report->textCursor().insertImage(
                                probes[i]->originalImage()
                                );
                }
            }

            report->insertHtml(
                        "<br>"
                        + tr("Mix image file")
                        + ": "
                        + imgname
                        + "<br>"
                        + tr("Concentration of the first component")
                        + " = <b>"
                        + QString::number(conc)
                        + "</b><br>"
                        );
        }

        if ( probes.size() < 2 ) {

            report->insertHtml("<hr><br>");
        }
        else {

            report->insertHtml(
                        "<br><b>Vc = " +
                        QString::number(Vc(concs, settings->val_idealConc())) +
                        "</b><br><hr><br>"
                        );
        }

        report->moveCursor(QTextCursor::End);
    }
    else if ( ui->comboBox_analysisType->currentIndex() ==
              ANALTYPE_GRANULATION &&
              granules.size() != 0 ) {

        double minArea = 0;
        double maxArea = 0;
        double meanArea = 0;
        double meanCompact = 0;

        createHistograms(histograms,
                         granules,
                         settings,
                         tempPath + QDir::separator() + lastCalcDateTime,
                         minArea,
                         maxArea,
                         meanArea,
                         meanCompact);

        if ( histograms.size() != 2 ) {

            QMessageBox::warning(this,
                                 "mixan",
                                 tr("Can not create histograms!"));
            freeMemory();

            return;
        }

        //

        QString imgname;
        ptrdiff_t totalParticlesNumber = 0;

        for ( ptrdiff_t i=0; i<granules.size(); i++ ) {

            totalParticlesNumber += granules[i]->partNumber();

            //

            imgname = granules[i]->imageFileName();

            if ( imgname.isEmpty() ) {

                report->insertHtml(
                            "<br><b>"
                            + tr("Analysis of image")
                            + " "
                            + imgname
                            + " "
                            + tr("failed or canceled")
                            + ".</b>"
                            );

                continue;
            }

            if ( showImg ) {

                report->insertHtml(
                            "<br>"
                            + tr("Granules image")
                            + ":<br>"
                            );

                if ( granules[i]->resImage().width() > imgWidth ) {

                    report->textCursor().insertImage(
                                granules[i]->resImage().
                                scaledToWidth(settings->val_imgWidth())
                                );
                }
                else {

                    report->textCursor().insertImage(
                                granules[i]->resImage()
                                );
                }
            }

            report->insertHtml(
                        "<br>"
                        + tr("Image file")
                        + " #"
                        + QString::number(i)
                        + ": "
                        + imgname
                        + "<br>"
                        );

            report->insertHtml(
                        tr("Particles found")
                        + ": <b>"
                        + QString::number(granules[i]->partNumber())
                        + "</b><br>"
                        );
        }

        report->insertHtml(
                    "<br>"
                    + tr("Total particles number (on all images)")
                    + ": <b>"
                    + QString::number(totalParticlesNumber)
                    + "</b><br>"
                    );

        report->insertHtml(
                    "<br>"
                    + tr("Total particle-size distribution")
                    + ":<br>"
                    );
        report->textCursor().insertImage(histograms[0]);

        report->insertHtml(
                    "<br><br>"
                    + tr("Size of particles")
                    + " ["
                    );

        if ( settings->val_sizeinmm() ) {
            report->insertHtml(tr("mm2"));
        }
        else {
            report->insertHtml(tr("px"));
        }

        report->insertHtml(
                    "]:<br>"
                    + tr("minimum_size")
                    + " = <b>"
                    + QString::number(minArea)
                    + "</b><br>"
                    + tr("maximum_size")
                    + " = <b>"
                    + QString::number(maxArea)
                    + "</b><br>"
                    + tr("mean_size")
                    + " = <b>"
                    + QString::number(meanArea)
                    + "</b>"
                    );

        report->insertHtml(
                    "<br><br>"
                    + tr("Total particle-circularity distribution")
                    + ":<br>"
                    );
        report->textCursor().insertImage(histograms[1]);

        report->insertHtml(
                    "<br><br>"
                    + tr("Mean compact particles")
                    + ": <b>"
                    + QString::number(meanCompact)
                    + "</b>"
                    );

        //

        if ( settings->val_sizeinmm() &&
             (!(settings->val_sievesCellDiameter().isEmpty()) ||
              !(settings->val_sievesCellDimension().isEmpty())) ) {

            QStringList diameters =
                    settings->val_sievesCellDiameter().
                    split(";", QString::SkipEmptyParts);
            QStringList dimensions =
                    settings->val_sievesCellDimension().
                    split(";", QString::SkipEmptyParts);

            QHash<QString, double> cells;
            QVector<double> sieveCells;

            if ( !diameters.isEmpty() ) {

                double diam = 0;

                for ( ptrdiff_t i=0; i<diameters.size(); i++ ) {

                    diam = diameters[i].toDouble();

                    cells.insert(diameters[i], diam);
                    sieveCells.push_back(diam);
                }
            }

            if ( !dimensions.isEmpty() ) {

                double reducedDim = 0;

                for ( ptrdiff_t i=0; i<dimensions.size(); i++ ) {

                    reducedDim = dimensions[i].toDouble() * CELLKOEFF;

                    cells.insert(dimensions[i], reducedDim);
                    sieveCells.push_back(reducedDim);
                }
            }

            QVector<double> partRemainders;
            QVector<double> totalRemainders;

            defRemainders(granules, sieveCells, partRemainders, totalRemainders);

            QString str = "<br><br>"
                    + tr("Remainders on sieves")
                    + "<table><tr><td align=\"right\" colspan=\"25\">"
                    + tr("Particular")
                    + "</td><td align=\"right\" colspan=\"11\">"
                    + tr("Total")
                    +"</td></tr>";

            ptrdiff_t i_fm = 0;

            for ( ptrdiff_t i=(sieveCells.size()-1); i>=0; i-- ) {

                if ( cells.key(sieveCells[i]) == "2.5" ) { i_fm = i; }

                str += "<tr><td colspan=\"5\">"
                        + tr("Sieve")
                        + "</td><td colspan=\"5\">#"
                        + QString::number(i)
                        + "</td><td>(</td><td align=\"right\">"
                        + cells.key(sieveCells[i])
                        + "<td>"
                        + tr("mm")
                        + "</td><td>)</td><td align=\"right\" colspan=\"10\">"
                        + QString::number(partRemainders[i]*100, 'f', 2)
                        + "</td><td>%</td>"
                        + "<td align=\"right\" colspan=\"10\">"
                        + QString::number(totalRemainders[i]*100, 'f', 2)
                        + "</td><td>%</td></tr>";
            }

            str += "</table>";

            report->insertHtml(str);

            //

            if ( cells.contains("2.5") &&
                 cells.contains("1.25") &&
                 cells.contains("0.63") &&
                 cells.contains("0.315") &&
                 (cells.contains("0.14") || cells.contains("0.16")) ) {

                double summFullRem = 0;

                for ( ptrdiff_t i=i_fm; i>(i_fm-5); i-- ) {

                    summFullRem += totalRemainders[i]*100;
                }

                report->insertHtml(
                            "<br><br>"
                            + tr("Fineness modulus")
                            + ": <b>"
                            + QString::number(summFullRem/100, 'f', 3)
                            + "</b>"
                            );
            }
        }

        //

        report->insertHtml("<br><hr><br>");
        report->moveCursor(QTextCursor::End);

        //

        if ( createTmpImgFiles ) {

            saveImages(granules,
                       tempPath
                       + QDir::separator()
                       + lastCalcDateTime
                       );
        }
    }
    else {

        report->insertHtml("<br><hr><br>");
        report->moveCursor(QTextCursor::End);
    }

    //

    freeMemory();
}