Example #1
0
void Extractor::extract(const QString &sourceFile, const QString &destination, const QString &root)
{
    ExtractInfo info = {
        archive_read_new(), // archiveHandle
        sourceFile, // filePath
        QFileInfo(sourceFile).size(), // totalBytes
        0 // extractedBytes
    };

    archive_read_support_filter_all(info.archiveHandle);
    archive_read_support_format_all(info.archiveHandle);

    int r = archive_read_open_filename(info.archiveHandle, qPrintable(sourceFile), 10240);
    if (r) {
        emit error(sourceFile, QString::fromLocal8Bit(archive_error_string(info.archiveHandle)));
        return;
    }

    QDir destinationDir(destination);
    if (!root.isEmpty()) {
        destinationDir = destinationDir.filePath(root);
    }

    // TODO: Do not strip root directory in archive if it equals to 'root'
    archive_entry *entry;
    while (archive_read_next_header(info.archiveHandle, &entry) == ARCHIVE_OK) {
#ifndef Q_OS_WIN32
        QString pathname = QString::fromUtf8(archive_entry_pathname(entry));
#else
        // TODO: Remove once https://github.com/libarchive/libarchive/issues/587 is resolved.
        QString pathname = QString::fromWCharArray(archive_entry_pathname_w(entry));
#endif

        if (!root.isEmpty()) {
            pathname.remove(0, pathname.indexOf(QLatin1String("/")) + 1);
        }

        const QString filePath = destinationDir.absoluteFilePath(pathname);

        const auto filetype = archive_entry_filetype(entry);
        if (filetype == S_IFDIR) {
            QDir().mkpath(QFileInfo(filePath).absolutePath());
            continue;
        }

        if (filetype != S_IFREG) {
            qWarning("Unsupported filetype %d for %s!", filetype, qPrintable(pathname));
            continue;
        }

        QScopedPointer<QFile> file(new QFile(filePath));
        if (!file->open(QIODevice::WriteOnly)) {
            qWarning("Cannot open file for writing: %s", qPrintable(pathname));
            continue;
        }

        const void *buffer;
        size_t size;
        std::int64_t offset;
        for (;;) {
            int rc = archive_read_data_block(info.archiveHandle, &buffer, &size, &offset);
            if (rc != ARCHIVE_OK) {
                if (rc == ARCHIVE_EOF) {
                    break;
                }

                qWarning("Cannot read from archive: %s", archive_error_string(info.archiveHandle));
                emit error(sourceFile,
                           QString::fromLocal8Bit(archive_error_string(info.archiveHandle)));
                return;
            }

            file->write(static_cast<const char *>(buffer), size);
        }

        emitProgress(info);
    }

    emit completed(sourceFile);
    archive_read_free(info.archiveHandle);
}
Example #2
0
/// \brief For add message info, this function is thread safe
void DebugEngine::addDebugInformation(const DebugLevel_custom &level,const QString& function,const QString& text,QString file,const int& ligne,const QString& location)
{
    if(DebugEngine::debugEngine==NULL)
    {
        qWarning() << "After close: " << function << file << ligne;
        return;
    }
    //Remove the compiler extra patch generated
    file=file.remove(QRegularExpression("\\.\\.?[/\\\\]([^/]+[/\\\\])?"));
    QString addDebugInformation_lignestring=QString::number(ligne);
    QString addDebugInformation_fileString=file;
    if(ligne!=-1)
        addDebugInformation_fileString+=":"+addDebugInformation_lignestring;
    //Load the time from start
    QString addDebugInformation_time = QString::number(startTime.elapsed());
    QString addDebugInformation_htmlFormat;
    bool important=true;
    switch(level)
    {
        case DebugLevel_custom_Information:
            addDebugInformation_htmlFormat="<tr class=\"Information\"><td class=\"time\">"+addDebugInformation_time+"</span></td><td>"+addDebugInformation_fileString+"</td><td class=\"function\">"+function+"()</td><td class=\"location\">"+location+"</td><td>"+htmlEntities(text)+"</td></tr>\n";
        break;
        case DebugLevel_custom_Critical:
            addDebugInformation_htmlFormat="<tr class=\"Critical\"><td class=\"time\">"+addDebugInformation_time+"</span></td><td>"+addDebugInformation_fileString+"</td><td class=\"function\">"+function+"()</td><td class=\"location\">"+location+"</td><td>"+htmlEntities(text)+"</td></tr>\n";
        break;
        case DebugLevel_custom_Warning:
            addDebugInformation_htmlFormat="<tr class=\"Warning\"><td class=\"time\">"+addDebugInformation_time+"</span></td><td>"+addDebugInformation_fileString+"</td><td class=\"function\">"+function+"()</td><td class=\"location\">"+location+"</td><td>"+htmlEntities(text)+"</td></tr>\n";
        break;
        case DebugLevel_custom_Notice:
        {
            addDebugInformation_htmlFormat="<tr class=\"Notice\"><td class=\"time\">"+addDebugInformation_time+"</span></td><td>"+addDebugInformation_fileString+"</td><td class=\"function\">"+function+"()</td><td class=\"location\">"+location+"</td><td>"+htmlEntities(text)+"</td></tr>\n";
            important=false;
        }
        break;
        case DebugLevel_custom_UserNote:
            addDebugInformation_htmlFormat="<tr class=\"Note\"><td class=\"time\">"+addDebugInformation_time+"</span></td><td>"+addDebugInformation_fileString+"</td><td class=\"function\">"+function+"()</td><td class=\"location\">"+location+"</td><td>"+htmlEntities(text)+"</td></tr>\n";
        break;
    }
    //To prevent access of string in multi-thread
    {
        //Show the text in console
        QString addDebugInformation_textFormat;
        addDebugInformation_textFormat = "("+addDebugInformation_time.rightJustified(8,' ')+") ";
        if(file!="" && ligne!=-1)
            addDebugInformation_textFormat += file+":"+addDebugInformation_lignestring+":";
        addDebugInformation_textFormat += function+"(), (location: "+location+"): "+text;
        QMutexLocker lock_mutex(&mutex);
        if(currentBackend==File)
        {
            if(logFile.size()<ULTRACOPIER_DEBUG_MAX_ALL_SIZE*1024*1024 || (important && logFile.size()<ULTRACOPIER_DEBUG_MAX_IMPORTANT_SIZE*1024*1024))
            {
                puts(qPrintable(addDebugInformation_textFormat));
                logFile.write(addDebugInformation_htmlFormat.toUtf8());
            }
        }
        else
        {
            if(debugHtmlContent.size()<ULTRACOPIER_DEBUG_MAX_ALL_SIZE*1024*1024 || (important && debugHtmlContent.size()<ULTRACOPIER_DEBUG_MAX_IMPORTANT_SIZE*1024*1024))
            {
                puts(qPrintable(addDebugInformation_textFormat));
                debugHtmlContent+=addDebugInformation_htmlFormat;
            }
        }
        //Send the new line
        if(addDebugInformationCallNumber<ULTRACOPIER_DEBUG_MAX_GUI_LINE)
        {
            addDebugInformationCallNumber++;
            DebugModel::debugModel->addDebugInformation(startTime.elapsed(),level,function,text,file,ligne,location);
        }
    }
}
/**
  Returns the best match for the given file url in the project directory.

  The method first checks whether the file inside the project directory exists.
  If not, the leading directory in the path is stripped, and the - now shorter - path is
  checked for existence, and so on. Second, it tries to locate the file in the sysroot
  folder specified. Third, we walk the list of project files, and search for a file name match
  there. If all fails, it returns the original path from the file url.
  */
QString FileInProjectFinder::findFile(const QUrl &fileUrl, bool *success) const
{
    if (debug)
        qDebug() << "FileInProjectFinder: trying to find file" << fileUrl.toString() << "...";

    QString originalPath = fileUrl.toLocalFile();
    if (originalPath.isEmpty()) // e.g. qrc://
        originalPath = fileUrl.path();

    if (originalPath.isEmpty()) {
        if (debug)
            qDebug() << "FileInProjectFinder: malformed url, returning";
        if (success)
            *success = false;
        return originalPath;
    }

    if (!m_projectDir.isEmpty()) {
        if (debug)
            qDebug() << "FileInProjectFinder: checking project directory ...";

        int prefixToIgnore = -1;
        const QChar separator = QLatin1Char('/');
        if (originalPath.startsWith(m_projectDir + separator)) {

#ifdef Q_OS_MAC
            // starting with the project path is not sufficient if the file was
            // copied in an insource build, e.g. into MyApp.app/Contents/Resources
            static const QString appResourcePath = QString::fromLatin1(".app/Contents/Resources");
            if (originalPath.contains(appResourcePath)) {
                // the path is inside the project, but most probably as a resource of an insource build
                // so ignore that path
                prefixToIgnore = originalPath.indexOf(appResourcePath) + appResourcePath.length();
            } else {
#endif
                if (debug)
                    qDebug() << "FileInProjectFinder: found" << originalPath << "in project directory";
                if (success)
                    *success = true;
                return originalPath;
#ifdef Q_OS_MAC
            }
#endif
        }

        if (m_cache.contains(originalPath)) {
            if (debug)
                qDebug() << "FileInProjectFinder: checking cache ...";
            // check if cached path is still there
            QString candidate = m_cache.value(originalPath);
            QFileInfo candidateInfo(candidate);
            if (candidateInfo.exists() && candidateInfo.isFile()) {
                if (success)
                    *success = true;
                if (debug)
                    qDebug() << "FileInProjectFinder: found" << candidate << "in the cache";
                return candidate;
            }
        }

        if (debug)
            qDebug() << "FileInProjectFinder: checking stripped paths in project directory ...";

        // Strip directories one by one from the beginning of the path,
        // and see if the new relative path exists in the build directory.
        if (prefixToIgnore < 0) {
            if (!QFileInfo(originalPath).isAbsolute()
                    && !originalPath.startsWith(separator)) {
                prefixToIgnore = 0;
            } else {
                prefixToIgnore = originalPath.indexOf(separator);
            }
        }
        while (prefixToIgnore != -1) {
            QString candidate = originalPath;
            candidate.remove(0, prefixToIgnore);
            candidate.prepend(m_projectDir);
            QFileInfo candidateInfo(candidate);
            if (candidateInfo.exists() && candidateInfo.isFile()) {
                if (success)
                    *success = true;

                if (debug)
                    qDebug() << "FileInProjectFinder: found" << candidate << "in project directory";

                m_cache.insert(originalPath, candidate);
                return candidate;
            }
            prefixToIgnore = originalPath.indexOf(separator, prefixToIgnore + 1);
        }
    }

    // find (solely by filename) in project files
    if (debug)
        qDebug() << "FileInProjectFinder: checking project files ...";

    const QString fileName = QFileInfo(originalPath).fileName();
    foreach (const QString &f, m_projectFiles) {
        if (QFileInfo(f).fileName() == fileName) {
            m_cache.insert(originalPath, f);
            if (success)
                *success = true;
            if (debug)
                qDebug() << "FileInProjectFinder: found" << f << "in project files";
            return f;
        }
    }

    if (debug)
        qDebug() << "FileInProjectFinder: checking absolute path in sysroot ...";

    // check if absolute path is found in sysroot
    if (!m_sysroot.isEmpty()) {
        const QString sysrootPath = m_sysroot + originalPath;
        if (QFileInfo(sysrootPath).exists() && QFileInfo(sysrootPath).isFile()) {
            if (success)
                *success = true;
            m_cache.insert(originalPath, sysrootPath);
            if (debug)
                qDebug() << "FileInProjectFinder: found" << sysrootPath << "in sysroot";
            return sysrootPath;
        }
    }

    if (success)
        *success = false;

    if (debug)
        qDebug() << "FileInProjectFinder: couldn't find file!";
    return originalPath;
}
	/**
	 *
	 * The neuronsWithActivationChange parameter can be used to collect all DoubelValues that correspond
	 * to activation values of neurons. These neurons have to be collected in each DymnamcisPlotter in
	 * variable DynamcisPlotter::mNeuronsWithActivationsToTransfer to be handled correctly, if the
	 * activation of a neuron should be varied during an analyzer run. Otherwise the varied activations
	 * are immediately overwritten by the newly calculated activations at the first network update.
	 *
	 * If this method is used to collect elements that will NOT be changed during analyzer runs,
	 * then the last parameter MUST be empty. Othewise activations of neurons collected in this way
	 * will be treated differently compared to the other neurons in the network. This may lead to
	 * unexpected and erroneous behavior.
	 *
	 * @param specifierLists a list of stringlists, containing the single specifications of DoubleValues.
	 * @param networkElements the list of objects that are considered to find the specified DoubleValue object.
	 * @param neuronsWithActivationChange (optional) list to collect all activation values that are going to be changed during a run.
	 */
	QList< QList<DoubleValue*> > DynamicsPlotterUtil::getElementValues(QList<QStringList> const &specifierLists,
																	   QList<NeuralNetworkElement*> const &networkElements,
																	   QList<Neuron*> *neuronsWithActivationChange)
	{
		QList< QList<DoubleValue*> > plotElements, emptyList;
		emptyList = QList< QList<DoubleValue*> >();

		for(int listNr = 0; listNr < specifierLists.size(); ++listNr) {
			QList<DoubleValue*> elementValues;

			QStringList specifierList = specifierLists.at(listNr);
			for(int specifierNr = 0; specifierNr < specifierList.size(); ++specifierNr) {

				QString specifier = specifierList.at(specifierNr);
				if(specifier.isEmpty()) {
					reportProblem("DynamicsPlotterUtil::getElementValues : Empty specifier!");
					return emptyList;
				}

				QStringList parameters = specifier.split(":");
				if(parameters.size() < 2 || parameters.size() > 3) {
					reportProblem("DynamicsPlotterUtil::getElementValues : Invalid specifier ["+specifier+"]!");
					return emptyList;
				}

				if(parameters.first() == "all") {
					QList<DoubleValue*> netValues;
					DoubleValue* elementValue;
					QString parameter = specifier.remove("all:");

					for(int elemNr = 0; elemNr < networkElements.size(); ++elemNr) {
						NeuralNetworkElement* networkElement = networkElements.at(elemNr);
						elementValue = getElementValue(parameter, networkElement, neuronsWithActivationChange);

						if(elementValue != 0) {
							netValues.append(elementValue);
						}
					}

					elementValues.append(netValues);

				} else {
					DoubleValue* elementValue;
					elementValue = getElementValue(specifier, networkElements, neuronsWithActivationChange);

					if(elementValue == 0) {
						reportProblem("DynamicsPlotterUtil::getElementValues : Could not find a value "
									  "for element specifier ["+specifier+"]!");
						return emptyList;
					}

					elementValues.append(elementValue);

				}
			}

			plotElements.append(elementValues);
		}

		return plotElements;
	}
Example #5
0
File: dtd.cpp Project: KDE/quanta
bool DTD::parseDTD(const KURL &url)
{
    QString fileName = QString::null;
    if (!KIO::NetAccess::download(url, fileName))
    {
        KMessageBox::error(0, i18n("<qt>Cannot download the DTD from <b>%1</b>.</qt>").arg(url.prettyURL(0, KURL::StripFileProtocol)));
        return false;
    }
    QFile file(fileName);
    if (file.open(IO_ReadOnly))
    {
        QTextStream fileStream(&file);
        fileStream.setEncoding(QTextStream::UnicodeUTF8);
        QString entireDTD = fileStream.read();
        file.close();
        removeComments(entireDTD);

        QString line;
        QStringList lines = QStringList::split("\n",entireDTD);
        QStringList::Iterator it = lines.begin();
        while (it != lines.end()) {
            line = *it;

            if (line.startsWith("<")) {
                while (!line.endsWith(">") && it != lines.end()) {
                    ++it;
                    line += " \\end" + *it;
                }
            } else if (line.startsWith("%")) {
                while (!line.endsWith(";") && it != lines.end()) {
                    ++it;
                    line += *it;
                }
            }

            line = line.stripWhiteSpace();
            line = line.simplifyWhiteSpace();

            //kdDebug(24000) << "Parsed line is: " << line << endl;

            if ( line.startsWith("<!ENTITY") && line.endsWith(">"))
            {
                parseDTDEntity(line);
            }
            else if (line.startsWith("<!ELEMENT") && line.endsWith(">"))
            {
                parseDTDElement(line);
            }
            else if (line.startsWith("<!ATTLIST") && line.endsWith(">"))
            {
                parseDTDAttlist(line);
            }
            else if (line.startsWith("%") && line.endsWith(";"))
            {
                line.remove(0,1);
                line.truncate(line.length()-1);
                KURL entityURL = url;
                entityURL.setPath(url.directory()+ "/" + line + ".ent");
                parseDTD(entityURL);
            } else
            {
                kdDebug(24000) << QString("Unknown tag: [%1]").arg(line) << endl;
            }

            if (it != lines.end()) ++it;
        }
    }
}
/**
 * Executes an operation (or workflow) and generates output
 * @param parameters the input and output parameters that the user filled in
 */
QString OperationCatalogModel::executeoperation(quint64 operationid, const QString& parameters) {
    if ( operationid == 0 || parameters == "")
        return sUNDEF;

    Resource operationresource = mastercatalog()->id2Resource(operationid);
    if ( !operationresource.isValid())
        return sUNDEF;

    em->clearList();

    QString expression;
    QStringList parms = parameters.split("|");
    bool hasInvalidParameters = false;

    for(int i = 0; i < parms.size(); ++ i){
        if (operationresource.ilwisType() & itWORKFLOW){
            int parm = i + 1;
            if (operationresource[QString("pout_%1_optional").arg(parm)] == "false" && i < operationresource["outparameters"].toInt()) {
                QString value = parms[i + operationresource["inparameters"].toInt()];

                QString output = value.split("@@")[0];
                if (output.size() == 0) {
                    em->addError(1, "Output parameter " + QString::number(i) + " is undefined with name " +  operationresource[QString("pout_%1_name").arg(parm)].toString());
                    hasInvalidParameters = true;
                } else {
                    for (const char& c : output.toStdString()) {
                        if (!isalnum(c) && c != ':' && c != '/' && c != '\\' && c != '.') {
                            em->addError(1, "Output parameter " + QString::number(i) + " is not a valid name");
                            hasInvalidParameters = true;
                            break;
                        }
                    }
                }
            }
            if (operationresource[QString("pin_%1_optional").arg(parm)] == "false" && i < operationresource["inparameters"].toInt() && parms[i].size() == 0) {
                em->addError(1, "Input parameter " + QString::number(i) + " is undefined with name " +  operationresource[QString("pin_%1_name").arg(parm)].toString());
                hasInvalidParameters = true;
            }
        }
        if(i < operationresource["inparameters"].toInt()){
            if ( expression.size() != 0)
                expression += ",";
            expression += parms[i];
        }
    }

    if (hasInvalidParameters) return sUNDEF;

    QString allOutputsString;

    bool duplicateFileNames = false;

    QStringList parts = operationresource["outparameters"].toString().split("|");
    int maxparms = parts.last().toInt();
    int count = 1;
    for(int i=(parms.size() - maxparms); i<parms.size(); ++i){
        QString output = parms[i];


        QString pout = QString("pout_%1_type").arg(count++);

        IlwisTypes outputtype = operationresource[pout].toULongLong();
        if ( output.indexOf("@@") != -1 ){
            QString format;
            QStringList parts = output.split("@@");
            output = parts[0];
            if ( output == "")
                continue;

            //Check if user didnt put the same output name in another output field
            int occurences = 0;
            for(int j=(parms.size() - maxparms); j<parms.size(); ++j){
                QString compareString = parms[j].split("@@")[0];
                if(output == compareString){
                    occurences++;
                }
            }

            //Add the duplicate name to the list of duplicate names
            if(occurences>1){
                duplicateFileNames = true;
                em->addError(1, "Workflow did not execute, multiple occurences of an output name");
            }

            QString formatName = parts[1];

            if ( operationresource.ilwisType() & itWORKFLOW) {
                QStringList existingFileNames;

                DIR *directory;

                //If not memory
                QString fileName;

                if(formatName == "Memory" ){
                    //Get all files in the internal catalog
                    QString dataLocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/internalcatalog";
                    directory = opendir(dataLocation.toStdString().c_str());
                }else {
                    //Get all files in the directory
                    QString dataLocation = output;
                    dataLocation.remove("file:///");

                    QStringList splitUrl = dataLocation.split("/");

                    fileName = splitUrl.last();

                    QString query = "name='" + formatName + "'";
                    std::multimap<QString, Ilwis::DataFormat>  formats = Ilwis::DataFormat::getSelectedBy(Ilwis::DataFormat::fpNAME, query);
                    if ( formats.size() == 1){
                        QString connector = (*formats.begin()).second.property(DataFormat::fpCONNECTOR).toString();
                        QString code = (*formats.begin()).second.property(DataFormat::fpCODE).toString();

                        QVariantList extensions = Ilwis::DataFormat::getFormatProperties(DataFormat::fpEXTENSION,outputtype, connector, code);

                        fileName += ".";
                        fileName += extensions[0].toString();
                    }

                    splitUrl.removeLast();

                    dataLocation = splitUrl.join("/");

                    directory = opendir(dataLocation.toStdString().c_str());
                }

                struct dirent *file;

                //Put the existing file names in a list for later use
                while ((file = readdir (directory)) != NULL) {
                    existingFileNames.push_back(file->d_name);
                }

                closedir(directory);

                //Check if a file with the same name already exist
                for(int j=0;j<existingFileNames.size();++j){
                    if(formatName == "Memory"){
                        if(existingFileNames[j] == output) {
                            duplicateFileNames = true;
                            em->addError(1, "Workflow did not execute duplicate name: " + output + ". Please change this name.");
                        }
                    }else{
                        if(existingFileNames[j] == fileName){
                            duplicateFileNames = true;
                            em->addError(1, "Workflow did not execute duplicate name: " + fileName + ". Please change this name.");
                        }
                    }
                }
            }

            if ( hasType(outputtype, itCOLUMN)){
                if ( formatName == "Memory"){
                    output = modifyTableOutputUrl(output, parms);
                }else
                    output = parms[0] + "[" + output + "]";
            }
            if ( formatName == "Keep original"){
                IIlwisObject obj;
                obj.prepare(parms[0], operationresource["pin_1_type"].toULongLong());
                if ( obj.isValid()){
                    IlwisTypes type = operationresource[pout].toULongLong();
                    QVariantList values = DataFormat::getFormatProperties(DataFormat::fpCODE,type,obj->provider());
                    if ( values.size() != 0){
                        format = "{format(" + obj->provider() + ",\"" + values[0].toString() + "\")}";
                    }else{
                        kernel()->issues()->log(QString("No valid conversion found for provider %1 and format %2").arg(obj->provider()).arg(IlwisObject::type2Name(type)));
                        return sUNDEF;
                    }
                }
            }
            //overrule the user if he wants to store things in the internalcatalog, then the format is by defintion stream
            if ( context()->workingCatalog()->source().url() == INTERNAL_OBJECT)
                formatName == "Memory";
            if ( formatName != "Memory"){ // special case
                if ( format == "") {
                    QString query = "name='" + formatName + "'";
                    std::multimap<QString, Ilwis::DataFormat>  formats = Ilwis::DataFormat::getSelectedBy(Ilwis::DataFormat::fpNAME, query);
                    if ( formats.size() == 1){
                        format = "{format(" + (*formats.begin()).second.property(DataFormat::fpCONNECTOR).toString() + ",\"" +
                                (*formats.begin()).second.property(DataFormat::fpCODE).toString() + "\")}";
                    }
                }
                // if there is no path we extend it with a path unless the output is a new column, output is than the "old" table so no new output object
                if ( output.indexOf("://") == -1 )
                    output = context()->workingCatalog()->source().url().toString() + "/" + output + format;
                else
                    output = output + format;
            }else{
                if ( hasType(outputtype,itRASTER)){
                    format = "{format(stream,\"rastercoverage\")}";
                }else if (hasType(outputtype, itFEATURE)){
                    format = "{format(stream,\"featurecoverage\")}";
                }else if (hasType(outputtype, itTABLE | itCOLUMN)){
                    format = "{format(stream,\"table\")}";
                }else if (hasType(outputtype, itCATALOG)){
                    format = "{format(stream,\"catalog\")}";
                }else if (hasType(outputtype, itDOMAIN)){
                    format = "{format(stream,\"domain\")}";
                }else if (hasType(outputtype, itCOORDSYSTEM)){
                    format = "{format(stream,\"coordinatesystem\")}";
                }else if (hasType(outputtype, itGEOREF)){
                    format = "{format(stream,\"georeference\")}";
                }

                output = output + format;
            }
        }

        if(!allOutputsString.isEmpty()){
            allOutputsString.append(",");
        }
        allOutputsString += output;
    }

    if(!duplicateFileNames){
        if ( allOutputsString == "")
            expression = QString("script %1(%2)").arg(operationresource.name()).arg(expression);
        else
            expression = QString("script %1=%2(%3)").arg(allOutputsString).arg(operationresource.name()).arg(expression);

        OperationExpression opExpr(expression);

        try {
            QThread* thread = new QThread;
            OperationWorker* worker = new OperationWorker(opExpr);
            worker->moveToThread(thread);
            thread->connect(thread, &QThread::started, worker, &OperationWorker::process);
            thread->connect(worker, &OperationWorker::finished, thread, &QThread::quit);
            thread->connect(worker, &OperationWorker::finished, worker, &OperationWorker::deleteLater);
            thread->connect(thread, &QThread::finished, thread, &QThread::deleteLater);
            thread->start();

            return "TODO";
        } catch (const ErrorObject& err){
            emit error(err.message());
        }
    }
    return sUNDEF;
}
void CKSocketClient::playMessage(const QString &message) {
	ostringstream os;
	os << message.toStdString() << endl;
	ColorKeeperModel::logMessage(os.str());
	if (message.compare(QString("GET_SCREEN_INFO")) == 0) {
		try {
			const DisplayDevice
					& currScreen =
							ColorKeeperModel::Instance().getDeviceInfo().getCalibrableDisplayDevice(
									_currentScreen);
			ColorKeeperModel::Instance().addCalibModelForScreen(_currentScreen);
			QString sendMessage("SCREEN_INFO_ [index]");

			sendMessage.append(currScreen.getOSIndex());
			sendMessage.append(";[uid]");
			sendMessage.append(currScreen.getFullSerialNumber().c_str());
			sendMessage.append(";[manufacturer]");
			sendMessage.append(currScreen.getManufacturerName().c_str());
			sendMessage.append(";[model]");
			sendMessage.append(currScreen.getModelName().c_str());
			sendMessage.append(";[type]");
			sendMessage.append(currScreen.getStringType().c_str());
			sendMessage.append(";[profil]");
			sendMessage.append(
					ColorKeeperModel::Instance().getScreenProfilName(
							currScreen.getOSIndex()).c_str());
			sendMessage.append("\n");
			writeSocket(sendMessage);

		} catch (std::string e) { //TODO exception
			QString sendMessage = "Error";
			writeSocket(sendMessage);
		}
	} else if (message.contains(QString("DISPLAY_LUM_PATT")) == true) {
		QString m = message;
		m.remove(QString("DISPLAY_LUM_PATT "));
		QChar sc = m[0];
		m.remove(sc);
		int screen = sc.digitValue();
		float gamma = m.toFloat();

		emit displayLumContPatt(gamma, screen, false);
	} else if (message.contains(QString("SET_LUT_ON")) == true) {
		QChar sc = message[11];
		int screen = sc.digitValue();
		ColorKeeperModel::Instance().setScreenShouldApplyCorrection(screen,
				true);
	} else if (message.contains(QString("SET_LUT_OFF")) == true) {
		QChar sc = message[12];
		int screen = sc.digitValue();
		ColorKeeperModel::Instance().setScreenShouldApplyCorrection(screen,
				false);

	} else if (message.contains(QString("UNSET_MOSAIC")) == true) {
		QChar sc = message[13];
		int screen = sc.digitValue();
		emit displayLumContPatt(-1, screen, false);
	} else if (message.contains(QString("SET_MOSAIC")) == true) {
		QChar sc = message[11];
		int screen = sc.digitValue();
		emit displayLumContPatt(-1, screen, true);
	} else if (message.contains(QString("SET_PATCH_COLOR")) == true) {
		QChar sc = message[16];
		int screen = sc.digitValue();
		QStringList list = message.split(QChar('-'));
		QStringList::Iterator it = list.begin() + 1;
		QString tmp = (*it);
		float r = tmp.toFloat() / 255.f;
		++it;
		tmp = (*it);
		float g = tmp.toFloat() / 255.f;
		++it;
		tmp = (*it);
		float b = tmp.toFloat() / 255.f;
		++it;
		tmp = (*it);
		QChar halo = tmp[0];
		bool drawHalo = false;
		if (halo == QChar('t')) {
			drawHalo = true;
		}

		emit displayPatch(screen, r, g, b, drawHalo);
		QString sendMessage("PATCH_OK\n");
		writeSocket(sendMessage);
	} else if (message.contains(QString("SET_REC_COLOR")) == true) {
		QChar sc = message[14];
		int screen = sc.digitValue();
		QStringList list = message.split(QChar('-'));
		QStringList::Iterator it = list.begin() + 1;
		QString tmp = (*it);
		float r = tmp.toFloat() / 255.f;
		++it;
		tmp = (*it);
		float g = tmp.toFloat() / 255.f;
		++it;
		tmp = (*it);
		float b = tmp.toFloat() / 255.f;
		++it;
		tmp = (*it);
		emit displayFullScreenRec(screen, r, g, b);
		QString sendMessage("REC_OK\n");
		writeSocket(sendMessage);
	} else if (message.contains(QString("SET_LUT_SIZE")) == true) {
		QChar sc = message[13];
		int screen = sc.digitValue();
		QStringList list = message.split(QChar('-'));
		QStringList::Iterator it = list.begin() + 1;
		QString tmp = (*it);
		unsigned int size = tmp.toInt();
		ColorKeeperModel::Instance().setCalibSizeForScreen(screen, size);
		QString sendMessage("SET_LUT_SIZE_OK\n");
		writeSocket(sendMessage);
	} else if (message.contains(QString("VALUE")) == true) {
		QChar sc = message[6];
		int screen = sc.digitValue();
		QStringList list = message.split(QChar('-'));
		QStringList::Iterator it = list.begin() + 1;
		QString tmp = (*it);
		unsigned short red = tmp.toInt();
		++it;
		tmp = (*it);
		unsigned short green = tmp.toInt();
		++it;
		tmp = (*it);
		unsigned short blue = tmp.toInt();
		ostringstream os;
		os << (int) red << (int) green << (int) blue << endl;
		ColorKeeperModel::logMessage(os.str());
		ColorKeeperModel::Instance().addCalibValueForScreen(screen, red, green,
				blue);
	} else if (message.contains(QString("SET_LUT_DONE")) == true) {
		//		QString sendMessage("SET_LUT_OK\n");
		//		writeSocket(sendMessage);
		QChar sc = message[13];
		int screen = sc.digitValue();
		ColorKeeperModel::Instance().setCalibDoneForScreen(screen);

	} else if (message.contains(QString("SHOULD_DISPLAY")) == true) {
		QChar sc = message[15];
		int screen = sc.digitValue();
		QChar va = message[17];
		bool tog = false;
		if (va == QChar('t')) {
			tog = true;
		}
		ColorKeeperModel::Instance().shoudDisplayCalibForScreen(screen, tog);
	} else if (message.contains(QString("UPDATE_CALIB_FILE")) == true) {
		QChar sc = message[18];
		int screen = sc.digitValue();
		QString infos = message;
		infos.remove(0, 19);
		infos.replace(QChar('#'), QChar('\n'));
		ColorKeeperModel::Instance().updateCorrection(screen, infos);
		QString sendMessage("UPDATE_OK\n");
		writeSocket(sendMessage);
	} else if (message.contains(QString("BUH_BYE")) == true) {
		QChar sc = message[8];
		int screen = sc.digitValue();
		ColorKeeperModel::Instance().endCalib(screen);
	}
}
void ImageWidget::restore(Graph *g, const QStringList& lst)
{
	int frameStyle = 0;
	QPen pen = QPen(Qt::black, 1, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin);
	double x = 0.0, y = 0.0, right = 0.0, bottom = 0.0;
	QStringList::const_iterator line;
	QString fn;
	bool save_xpm = false;
	ImageWidget *i = NULL;
	AttachPolicy attachTo = FrameWidget::Page;
	bool onTop = true;
	for (line = lst.begin(); line != lst.end(); line++){
        QString s = *line;
        if (s.contains("<Frame>"))
			frameStyle = s.remove("<Frame>").remove("</Frame>").toInt();
		else if (s.contains("<Color>"))
			pen.setColor(QColor(s.remove("<Color>").remove("</Color>")));
		else if (s.contains("<FrameWidth>"))
			pen.setWidth(s.remove("<FrameWidth>").remove("</FrameWidth>").toInt());
		else if (s.contains("<LineStyle>"))
			pen.setStyle(PenStyleBox::penStyle(s.remove("<LineStyle>").remove("</LineStyle>").toInt()));
		else if (s.contains("<x>"))
			x = s.remove("<x>").remove("</x>").toDouble();
		else if (s.contains("<y>"))
			y = s.remove("<y>").remove("</y>").toDouble();
		else if (s.contains("<right>"))
			right = s.remove("<right>").remove("</right>").toDouble();
		else if (s.contains("<bottom>"))
			bottom = s.remove("<bottom>").remove("</bottom>").toDouble();
		else if (s.contains("<attachTo>"))
			attachTo = (FrameWidget::AttachPolicy)s.remove("<attachTo>").remove("</attachTo>").toInt();
		else if (s.contains("<onTop>"))
			onTop = s.remove("<onTop>").remove("</onTop>").toInt();
		else if (s.contains("<path>"))
			i = g->addImage(s.remove("<path>").remove("</path>"));
		else if (s.contains("<xpm>")){
			save_xpm = true;
			if (!i){
				QString xpm;
				while ( s != "</xpm>" ){
					s = *(++line);
					xpm += s + "\n";
				}
				QImage image;
    			if (image.loadFromData(xpm.toAscii()))
					i = g->addImage(image);
			}
		}
	}

	if (i){
		i->setFrameStyle(frameStyle);
		i->setFramePen(pen);
		i->setCoordinates(x, y, right, bottom);
		i->setSaveInternally(save_xpm);
		i->setAttachPolicy(attachTo);
		i->setOnTop(onTop);
	}
}
Example #9
0
void CQFittingResult::slotSave(void)
{
  C_INT32 Answer = QMessageBox::No;
  QString fileName;

  while (Answer == QMessageBox::No)
    {
      fileName =
        CopasiFileDialog::getSaveFileName(this, "Save File Dialog",
                                          QString::null, "TEXT Files (*.txt);;All Files (*.*);;", "Save to");

      if (fileName.isEmpty()) return;

      if (!fileName.endsWith(".txt") &&
          !fileName.endsWith(".")) fileName += ".txt";

      fileName = fileName.remove(QRegExp("\\.$"));

      Answer = checkSelection(fileName);

      if (Answer == QMessageBox::Cancel) return;
    }

  std::ofstream file(utf8ToLocale(TO_UTF8(fileName)).c_str());

  if (file.fail()) return;

  unsigned C_INT32 i, imax;

  // The global result and statistics
  file << "Objective Value\tRoot Mean Square\tStandard Deviation" << std::endl;
  file << mpProblem->getSolutionValue() << "\t";
  file << mpProblem->getRMS() << "\t";
  file << mpProblem->getStdDeviation() << std::endl;

  file << "Function Evaluations\tCPU Time [s]\tEvaluations/second [1/s]" << std::endl;
  const unsigned C_INT32 & FunctionEvaluations = mpProblem->getFunctionEvaluations();
  const C_FLOAT64 & ExecutionTime = mpProblem->getExecutionTime();
  file << FunctionEvaluations << "\t";
  file << ExecutionTime << "\t";
  file << FunctionEvaluations / ExecutionTime << std::endl;

  // Set up the parameters table
  file << std::endl << "Parameters:" << std::endl;
  file << "Parameter\tValue\tStd. Deviation\tCoeff. of Variation [%]\tGradient" << std::endl;

  // Loop over the optimization items
  const std::vector< COptItem * > & Items = mpProblem->getOptItemList();
  const CVector< C_FLOAT64 > & Solutions = mpProblem->getSolutionVariables();
  const CVector< C_FLOAT64 > & StdDeviations = mpProblem->getVariableStdDeviations();
  const CVector< C_FLOAT64 > & Gradients = mpProblem->getVariableGradients();

  imax = Items.size();

  if (mpProblem->getFunctionEvaluations() == 0)
    imax = 0;

  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);

  for (i = 0; i != imax; i++)
    {
      const CCopasiObject *pObject =
        pDataModel->getObject(Items[i]->getObjectCN());

      if (pObject)
        {
          std::string Experiments =
            static_cast<CFitItem *>(Items[i])->getExperiments();

          if (Experiments != "")
            Experiments = "; {" + Experiments + "}";

          file << pObject->getObjectDisplayName() << Experiments << "\t";
        }
      else
        file << "Not Found\t";

      const C_FLOAT64 & Solution = Solutions[i];
      file << Solution << "\t";
      const C_FLOAT64 & StdDeviation = StdDeviations[i];
      file << StdDeviation << "\t";
      file << fabs(100.0 * StdDeviation / Solution) << "\t";
      file << Gradients[i] << std::endl;
    }

  // Set up the experiments table
  file << std::endl << "Experiments:" << std::endl;
  file << "Experiment\tObjective Value\tRoot Mean Square\tError Mean\tError Mean Std. Deviation" << std::endl;

  // Loop over the experiments
  const CExperimentSet & Experiments = mpProblem->getExperiementSet();

  imax = Experiments.getExperimentCount();

  if (mpProblem->getFunctionEvaluations() == 0)
    imax = 0;

  for (i = 0; i != imax; i++)
    {
      const CExperiment & Experiment = * Experiments.getExperiment(i);
      file << Experiment.getObjectName() << "\t";
      file << Experiment.getObjectiveValue() << "\t";
      file << Experiment.getRMS() << "\t";
      file << Experiment.getErrorMean() << "\t";
      file << Experiment.getErrorMeanSD() << std::endl;
    }

  // Set up the fitted values table
  file << std::endl << "Fitted Values:" << std::endl;
  file << "Fitted Value\tObjective Value\tRoot Mean Square\tError Mean\tError Mean Std. Deviation" << std::endl;

  // Loop over the fitted values objects
  imax = Experiments.getDependentObjects().size();

  if (mpProblem->getFunctionEvaluations() == 0)
    imax = 0;

  for (i = 0; i != imax; i++)
    {
      const CCopasiObject * pObject = Experiments.getDependentObjects()[i];

      if (pObject)
        file << pObject->getObjectDisplayName() << "\t";
      else
        file << "Not Found\t";

      file << Experiments.getDependentObjectiveValues()[i] << "\t";
      file << Experiments.getDependentRMS()[i] << "\t";
      file << Experiments.getDependentErrorMean()[i] << "\t";
      file << Experiments.getDependentErrorMeanSD()[i] << std::endl;
    }

  file << std::endl;

  // Save the parameter correlations
  file << mpProblem->getCorrelations() << std::endl;

  // Save the Fisher information
  file << mpProblem->getFisherInformation() << std::endl;

}
Example #10
0
/**
  Parses a snippet of an address template
  @param tsection   the template string to be parsed
  @param result     QString reference in which the result will be stored
  @return           true if at least one tag evaluated positively, else false
*/
static bool parseAddressTemplateSection( const QString &tsection, QString &result,
                                         const QString &realName, const QString &orgaName,
                                         const KABC::Address &address )
{
  // This method first parses and substitutes any bracketed sections and
  // after that replaces any tags with their values. If a bracketed section
  // or a tag evaluate to zero, they are not just removed but replaced
  // with a placeholder. This is because in the last step conditionals are
  // resolved which depend on information about zero-evaluations.
  result = tsection;
  int stpos = 0;
  bool ret = false;

  // first check for brackets that have to be evaluated first
  int fpos = result.indexOf( KABC_FMTTAG_purgeempty, stpos );
  while ( -1 != fpos ) {
    int bpos1 = fpos + KABC_FMTTAG_purgeempty.length();
    int bpos2;
    // expect opening bracket and find next balanced closing bracket. If
    // next char is no opening bracket, continue parsing (no valid tag)
    if ( QLatin1Char( '(' ) == result[bpos1] ) {
      bpos2 = findBalancedBracket( result, bpos1 );
      if ( -1 != bpos2 ) {
        // we have balanced brackets, recursively parse:
        QString rplstr;
        bool purge = !parseAddressTemplateSection( result.mid( bpos1+1,
                                                   bpos2-bpos1-1 ), rplstr,
                                                   realName, orgaName, address );
        if ( purge ) {
          // purge -> remove all
          // replace with !_P_!, so conditional tags work later
          result.replace( fpos, bpos2 - fpos + 1, QLatin1String( "!_P_!" ) );
          // leave stpos as it is
        } else {
          // no purge -> replace with recursively parsed string
          result.replace( fpos, bpos2 - fpos + 1, rplstr );
          ret = true;
          stpos = fpos + rplstr.length();
        }
      } else {
        // unbalanced brackets:  keep on parsing (should not happen
        // and will result in bad formatting)
        stpos = bpos1;
      }
    }
    fpos = result.indexOf( KABC_FMTTAG_purgeempty, stpos );
  }

  // after sorting out all purge tags, we just search'n'replace the rest,
  // keeping track of whether at least one tag evaluates to something.
  // The following macro needs QString for R_FIELD
  // It substitutes !_P_! for empty fields so conditional tags work later
#define REPLTAG(R_TAG,R_FIELD) \
  if ( result.indexOf( R_TAG, false ) != -1 ) { \
    QString rpl = R_FIELD.isEmpty() ? QLatin1String( "!_P_!" ) : R_FIELD; \
    result.replace( R_TAG, rpl ); \
    if ( !R_FIELD.isEmpty() ) { \
      ret = true; \
    } \
  }
  REPLTAG( KABC_FMTTAG_realname, realName );
  REPLTAG( KABC_FMTTAG_REALNAME, realName.toUpper() );
  REPLTAG( KABC_FMTTAG_company, orgaName );
  REPLTAG( KABC_FMTTAG_COMPANY, orgaName.toUpper() );
  REPLTAG( KABC_FMTTAG_pobox, address.postOfficeBox() );
  REPLTAG( KABC_FMTTAG_street, address.street() );
  REPLTAG( KABC_FMTTAG_STREET, address.street().toUpper() );
  REPLTAG( KABC_FMTTAG_zipcode, address.postalCode() );
  REPLTAG( KABC_FMTTAG_location, address.locality() );
  REPLTAG( KABC_FMTTAG_LOCATION, address.locality().toUpper() );
  REPLTAG( KABC_FMTTAG_region, address.region() );
  REPLTAG( KABC_FMTTAG_REGION, address.region().toUpper() );
  result.replace( KABC_FMTTAG_newline, QLatin1String( "\n" ) );
#undef REPLTAG

  // conditional comma
  fpos = result.indexOf( KABC_FMTTAG_condcomma, 0 );
  while ( -1 != fpos ) {
    const QString str1 = result.mid( fpos - 5, 5 );
    const QString str2 = result.mid( fpos + 2, 5 );
    if ( str1 != QLatin1String( "!_P_!" ) && str2 != QLatin1String( "!_P_!" ) ) {
      result.replace( fpos, 2, QLatin1String( ", " ) );
    } else {
      result.remove( fpos, 2 );
    }
    fpos = result.indexOf( KABC_FMTTAG_condcomma, fpos );
  }
  // conditional whitespace
  fpos = result.indexOf( KABC_FMTTAG_condwhite, 0 );
  while ( -1 != fpos ) {
    const QString str1 = result.mid( fpos - 5, 5 );
    const QString str2 = result.mid( fpos + 2, 5 );
    if ( str1 != QLatin1String( "!_P_!" ) && str2 != QLatin1String( "!_P_!" ) ) {
      result.replace( fpos, 2, QLatin1String( " " ) );
    } else {
      result.remove( fpos, 2 );
    }
    fpos = result.indexOf( KABC_FMTTAG_condwhite, fpos );
  }

  // remove purged:
  result.remove( QLatin1String( "!_P_!" ) );

  return ret;
}
Example #11
0
void StatusWidget::setStatusData( const Status &status )
{
    statusData = &status.entry;
    m_ui->favoriteReplyButton->disconnect();

    setDisplayMode( StatusModel::instance()->displayMode() );
    m_ui->userStatus->setHtml( statusData->text );
    m_ui->userImage->setPixmap( status.image );


    if ( statusData->type == Entry::Status ) {
        //adjust tooltip for reply/delete button
        if ( statusData->isOwn ) {
            m_ui->replyDeleteButton->setIcon( QIcon(":/icons/cross_16.png") );
            m_ui->replyDeleteButton->setToolTip( tr( "Delete status" ) );
        } else {
            m_ui->replyDeleteButton->setIcon( QIcon(":/icons/reply_16.png") );
            m_ui->replyDeleteButton->setToolTip( tr( "Reply to %1" ).arg( statusData->userInfo.screenName ) );
        }

        // favorite button
        if ( statusData->favorited ) {
            m_ui->favoriteReplyButton->setIcon( QIcon( ":/icons/star_on_16.png" ) );
            m_ui->favoriteReplyButton->setToolTip( tr( "Remove from Favorites" ) );
        } else {
            m_ui->favoriteReplyButton->setIcon( QIcon( ":/icons/star_off_16.png" ) );
            m_ui->favoriteReplyButton->setToolTip( tr( "Add to Favorites" ) );
        }
        connect( m_ui->favoriteReplyButton, SIGNAL(clicked()), this, SLOT(slotFavorite()) );

        // delete action
    } else {
        //adjust tooltip for reply/delete button and delete action
        m_ui->replyDeleteButton->setIcon( QIcon(":/icons/cross_16.png") );
        if ( currentServiceUrl == Account::NetworkUrlTwitter ) {
            m_ui->replyDeleteButton->setToolTip( tr( "Delete message" ) );
            m_ui->replyDeleteButton->setEnabled( true );
        } else {
            m_ui->replyDeleteButton->setToolTip( tr( "Deleting messages is not supported by StatusNet" ) );
            m_ui->replyDeleteButton->setEnabled( false );
        }

        // favorite button
        m_ui->favoriteReplyButton->setIcon( QIcon( ":/icons/reply_16.png" ) );
        m_ui->favoriteReplyButton->setToolTip( tr( "Reply to %1" ).arg( statusData->userInfo.screenName ) );
        connect( m_ui->favoriteReplyButton, SIGNAL(clicked()), this, SLOT(slotDM()) );

    }


    //display status's send time
    if( statusData->localTime.date() >= QDateTime::currentDateTime().date()) //today
        m_ui->timeStamp->setText( statusData->localTime.time().toString(Qt::SystemLocaleShortDate) );
    else  //yesterday or earlier
        m_ui->timeStamp->setText( statusData->localTime.toString(Qt::SystemLocaleShortDate) );

    //display in_reply_to link
    if( statusData->hasInReplyToStatusId ) {
        QString inReplyToUrl = currentServiceUrl;
        inReplyToUrl.remove( QRegExp("/api$", Qt::CaseInsensitive) );
        if ( currentServiceUrl == Account::NetworkUrlTwitter ) {
            inReplyToUrl.append( "/" + statusData->inReplyToScreenName + "/statuses/" + QString::number( statusData->inReplyToStatusId ) );
        }
        else {
            //for identica it works as is
            inReplyToUrl.append( "/notice/" + QString::number( statusData->inReplyToStatusId ) );
        }
        m_ui->timeStamp->setText( m_ui->timeStamp->text().append( " " )
                                  .append( tr( "in reply to %1" )
                                           .arg( QString( "<a style=\"color:rgb(255, 248, 140)\" href=%1>%2</a>" )
                                                 .arg( inReplyToUrl, statusData->inReplyToScreenName ) ) ) );
    }

    m_ui->infoButton->setData( &status );


    setState( status.state );
    setupMenu();
    adjustSize();
}
Example #12
0
QList<FileSystemInfo> FileServerHandler::QueryFileSystems(void)
{
    QStringList groups(StorageGroup::kSpecialGroups);
    groups.removeAll("LiveTV");
    QString specialGroups = groups.join("', '");

    MSqlQuery query(MSqlQuery::InitCon());
    query.prepare(QString("SELECT MIN(id),dirname "
                            "FROM storagegroup "
                           "WHERE hostname = :HOSTNAME "
                             "AND groupname NOT IN ( '%1' ) "
                           "GROUP BY dirname;").arg(specialGroups));
    query.bindValue(":HOSTNAME", gCoreContext->GetHostName());

    QList<FileSystemInfo> disks;
    if (query.exec() && query.isActive())
    {
        if (!query.size())
        {
            query.prepare("SELECT MIN(id),dirname "
                            "FROM storagegroup "
                           "WHERE groupname = :GROUP "
                           "GROUP BY dirname;");
            query.bindValue(":GROUP", "Default");
            if (!query.exec())
                MythDB::DBError("BackendQueryFileSystems", query);
        }

        QDir checkDir("");
        QString currentDir;
        FileSystemInfo disk;
        QMap <QString, bool>foundDirs;

        while (query.next())
        {
            disk.clear();
            disk.setHostname(gCoreContext->GetHostName());
            disk.setLocal();
            disk.setBlockSize(0);
            disk.setGroupID(query.value(0).toInt());

            /* The storagegroup.dirname column uses utf8_bin collation, so Qt
             * uses QString::fromAscii() for toString(). Explicitly convert the
             * value using QString::fromUtf8() to prevent corruption. */
            currentDir = QString::fromUtf8(query.value(1)
                                           .toByteArray().constData());
            disk.setPath(currentDir);

            if (currentDir.right(1) == "/")
                currentDir.remove(currentDir.length() - 1, 1);

            checkDir.setPath(currentDir);
            if (!foundDirs.contains(currentDir))
            {
                if (checkDir.exists())
                {
                    disk.PopulateDiskSpace();
                    disk.PopulateFSProp();
                    disks << disk;

                    foundDirs[currentDir] = true;
                }
                else
                    foundDirs[currentDir] = false;
            }
        }
    }

    return disks;
}
Example #13
0
void Yahoo::parseFundamental ()
{
  if (! data.length())
    return;

  if (data.contains("no data available"))
    return;

  QStringList l = QStringList::split("yfnc_tablehead1", data, FALSE);
  int loop;
  Setting fund;
  for (loop = 1; loop < (int) l.count(); loop++)
  {
    QString k = l[loop];
    int p = k.find(">", 0, TRUE);
    if (p == -1)
      continue;
    p++;
    k.remove(0, p);
    p = k.find("<", 0, TRUE);
    if (p == -1)
      continue;
    k.truncate(p);

    if (k.contains("&sup"))
      k.truncate(k.length() - 6);
    if (k.contains("&amp"))
      k.remove(k.find("&", 0, TRUE), 5);
    k = k.stripWhiteSpace();
    if (! k.length())
      continue;

    QString d = l[loop];
    p = d.find("yfnc_tabledata1", 0, TRUE);
    if (p == -1)
      continue;
    p = d.find(">", p, TRUE);
    if (p == -1)
      continue;
    p++;
    d.remove(0, p);
    p = d.find("<", 0, TRUE);
    if (p == -1)
      continue;
    d.truncate(p);
    d = d.stripWhiteSpace();
    if (! d.length())
      continue;

    fund.setData(k, d);
  }

  QString s = dataPath + "/";
  QString ts = "symbol";
  QString ts2;
  currentUrl->getData(ts, ts2);
  QFileInfo fi(ts2);
  if (fi.extension(FALSE).length())
    s.append(fi.extension(FALSE).upper());
  else
    s.append("US");
  s.append("/");
  s.append(ts2);

  if (plug.open(s, chartIndex))
  {
    QString ss(tr("Could not open db"));
    printStatusLogMessage(ss);
    return;
  }

  QString fn = ts2;

  // verify if this chart can be updated by this plugin
  DBIndexItem item;
  chartIndex->getIndexItem(fn, item);
  item.getSymbol(s);
  if (! s.length())
  {
    if(plug.createNewStock())
    {
      plug.close();
      return;
    }

    chartIndex->getIndexItem(fn, item);

    item.setQuotePlugin(pluginName);
    item.setSymbol(ts2);
    QString title = ts2;
    int p = data.find("yfnc_leftnav1", 0, TRUE);
    if (p != -1)
    {
      p = data.find("b>", p, TRUE);
      if (p != -1)
      {
        p = p + 2;
        int p2 = data.find("<", p, TRUE);
        if (p2 != -1)
	{
	  s = data.mid(p, p2 - p);
	  if (s.length())
            title = s;
	}
      }
    }
    item.setTitle(title);

    chartIndex->setIndexItem(fn, item);
  }
  else
  {
    QString s2;
    item.getTitle(s2);
    if (! s.compare(s2))
    {
      int p = data.find("yfnc_leftnav1", 0, TRUE);
      if (p != -1)
      {
        p = data.find("b>", p, TRUE);
        if (p != -1)
        {
          p = p + 2;
          int p2 = data.find("<", p, TRUE);
          if (p2 != -1)
	  {
            s = data.mid(p, p2 - p);
	    if (s.length())
            {
              item.setTitle(s);
              chartIndex->setIndexItem(fn, item);
            }
	  }
	}
      }
    }
  }

//  item.getQuotePlugin(s);
//  if (s.compare(pluginName))
//  {
//    s = ts2 + " - " + tr("skipping update. Source does not match destination");
//    printStatusLogMessage(s);
//    plug.close();
//    return;
//  }

  // include date of this update
  QDate dt = QDate::currentDate();
  ts = "updateDate";
  ts2 = dt.toString("yyyy-MM-dd");
  fund.setData(ts, ts2);
  fund.getString(ts2);
  ts = "Fundamentals";
  chartIndex->setFundamentals(fn, ts2);

  plug.close();

  emit signalWakeup();
}
Example #14
0
/**
 * Slot called when a column is clicked in the tree displaying the attribute data
 * @param theItem - The tree widget item click
 * @param theColumn - The column that was clicked
 */
void eVisGenericEventBrowserGui::launchExternalApplication( QTreeWidgetItem * theItem, int theColumn )
{
  // At this point there is only attribute data with no children, ignore clicks on field name
  if ( 1 == theColumn )
  {
    int myIterator = 0;
    bool startsWithExtension = false;
    while ( myIterator < tableFileTypeAssociations->rowCount() )
    {
      if ( theItem->text( theColumn ).startsWith( tableFileTypeAssociations->item( myIterator, 0 )->text() + ':', Qt::CaseInsensitive ) )
      {
        startsWithExtension = true;
        break;
      }
      else if ( theItem->text( theColumn ).endsWith( tableFileTypeAssociations->item( myIterator, 0 )->text(), Qt::CaseInsensitive ) )
      {
        startsWithExtension = false;
        break;
      }
      else
        myIterator++;
    }

    if ( myIterator != tableFileTypeAssociations->rowCount() )
    {
      QProcess *myProcess = new QProcess();
      QString myApplication = tableFileTypeAssociations->item( myIterator, 1 )->text();
      QString myDocument = theItem->text( theColumn );
      if ( startsWithExtension )
      {
        myDocument = theItem->text( theColumn ).remove( tableFileTypeAssociations->item( myIterator, 0 )->text() + ':', Qt::CaseInsensitive );
      }

      if ( "" != myApplication )
      {
        if ( mConfiguration.isApplyPathRulesToDocsSet() )
        {
          int myDocumentNameMarker = 0;

          if ( myDocument.contains( '/' ) )
          {
            myDocumentNameMarker = myDocument.lastIndexOf( '/' );
          }
          else
          {
            myDocumentNameMarker = myDocument.lastIndexOf( '\\' );
          }

          QString myDocumentName = myDocument;
          myDocumentName.remove( 0, myDocumentNameMarker + 1 );
          if ( mConfiguration.isUseOnlyFilenameSet() )
          {
            myDocument = mConfiguration.basePath() + myDocumentName;
          }
          else
          {
            if ( mConfiguration.isEventImagePathRelative() )
            {
              myDocument = mConfiguration.basePath() + myDocument;
            }
          }
        }

        myProcess->start( myApplication, QStringList() << myDocument );
      }
    }
    else
    {
      QMessageBox::information( this, tr( "Attribute Contents" ), theItem->text( theColumn ) );
    }
  }
}
Example #15
0
void QJDMainWindow::creatNewLine(QString lineName)
{
    QString lowerCaseLineName;
    lowerCaseLineName=lineName.toLower();
    lowerCaseLineName.simplified();
    lowerCaseLineName.remove(" ");
    qDebug()<<"creatNewLine::"<<lineName<<lowerCaseLineName;  // 所有大写阿,带空格的之类的统一小写,并且去空格

    //1. 创建文件夹,需要获取当前area文件夹名称,通过当前的名称获取
    QDir newDir;
    newDir.setPath(areaWidget->getAbsolutePath());
    if(newDir.exists(lowerCaseLineName))
    {
        QMessageBox::warning(this,"Warning!","Do not creat the same LINE again!");
        return;
    }

    if(!newDir.mkdir(lowerCaseLineName))
        qDebug()<<"Creat New Line Dir failed";

    //2. 创建.Line Desc
    QFile newDesc;
    newDesc.setFileName(newDir.path()+"/"+lowerCaseLineName+"/DescName");
    if(!newDesc.open(QFile::WriteOnly))
    {
        qDebug()<<"creat new desc open failed";
    }
    QTextStream ts(&newDesc);
    ts<<lineName<<"\n";
    newDesc.close();

    // 3. 创建Data文件夹
    QDir dataDir;
    QString dataDirPath=areaWidget->getAbsolutePath()+"/"+lowerCaseLineName;
    dataDir.setPath(dataDirPath);
    if(dataDir.exists("Data"))
    {
        QMessageBox::warning(this,"Warning!","Can not creat the Data Dir for this LINE!");
        return;
    }

    if(!dataDir.mkdir("Data"))
        qDebug()<<"Creat Line Data Dir failed";

    QFile dataDesc;
    dataDesc.setFileName(dataDir.path()+"/Data/DescName");
    if(!dataDesc.open(QFile::WriteOnly))
    {
        qDebug()<<"creat data dir desc open failed";
    }
    QTextStream datats(&dataDesc);
    datats<<"Data\n";
    dataDesc.close();

    // 4. 创建各个类型文件的文件夹
    QStringList fileTypeList=settings.value("FileType").toStringList();
    for(int i=0; i<fileTypeList.size(); i++)
    {
        QDir typeDir;
        QString typeDirPath=dataDirPath+"/Data";
        typeDir.setPath(typeDirPath);
        if(typeDir.exists(fileTypeList.at(i)))
        {
            QMessageBox::warning(this,"Warning!","Can not creat the Same Type Dir for this LINE Data!");
            return;
        }

        if(!typeDir.mkdir(fileTypeList.at(i)))
            qDebug()<<"Creat Line Data Dir failed";
    }


    setHomeDir(getHomeDir());
    areaWidget->expandToDepth(1);
}
Example #16
0
bool QPEvents::handleEvent(const EventAction& ev)
{
  if (ev.type == EventAction::Internal)
  {
    if (ev.action == "email")
    {
       QString receiver = ev.arguments[0];
       TeamMember member;
       if (receiver == "teamleader")
         member = Project::ref()->teamLeader();
       else if (receiver.startsWith("subprojectleader-"))
       {
         QString s = receiver.remove("subprojectleader-");
         member = Project::ref()->subprojectLeader(s);
         SubProject subProject;
         QValueList<SubProject> *subprojects = Project::ref()->subprojects();
         for (uint i = 0 ; i < subprojects->count(); i++)
         {
           if ((*subprojects)[i].name == s)
           {
              subProject = (*subprojects)[i];
              break;
           }
         }
         if (!subProject.location.isEmpty() && !ev.arguments[2].startsWith(subProject.location))
         {
            kdDebug(24000) << ev.arguments[2] << " is not part of the " << subProject.name << "subproject \"" << subProject.location << "\". " << endl;
            return true;
         }
       }
       else if (receiver.startsWith("taskleader-"))
         member = Project::ref()->taskLeader(receiver.remove("taskleader-"));

       QString body;
       for (uint i = 2; i < ev.arguments.count(); i++)
          body += ev.arguments[i] + "\n";
       kapp->invokeMailer(member.name + "<" + member.email + ">", "", "", ev.arguments[1], body, "", QStringList(), "");

       return true;
    }
    if (ev.action == "log")
    {
      QString logFile = ev.arguments[0];
      KURL url = KURL::fromPathOrURL(logFile);
      if (url.isValid() && !url.isLocalFile())
      {
        KMessageBox::sorry(0L, i18n("Logging to remote files is not supported."));
        return false;
      }
      if (!logFile.startsWith("/"))
      {
        url = Project::ref()->projectBaseURL();
        url.addPath(logFile);
        if (!url.isLocalFile())
        {
          KMessageBox::sorry(0L, i18n("Logging to files inside a remote project is not supported."));
          return false;
        }
      }
      QFile file(url.path());
      bool result;
      if (ev.arguments[2] == "create_new")
        result = file.open(IO_WriteOnly);
      else
        result = file.open(IO_WriteOnly | IO_Append);
      if (result)
      {
        QTextStream stream(&file);
        stream.setEncoding(QTextStream::UnicodeUTF8);
        //Note: the log text should not be translated.
        QString s = QDateTime::currentDateTime().toString(Qt::ISODate) + ": ";
        s.append( "Event : " + m_eventName + " : ");
        s.append( "Action: " + ev.action + " : ");
        if (ev.arguments[1] == "full")
        {
          s.append( "Arguments: ");
          for (uint i = 1; i < ev.arguments.count(); i++)
            s.append(ev.arguments[i] + " | ");
        }
        s[s.length() - 1] = '\n';
        stream << s;
        file.close();
      }
      if (!result)
      {
        KMessageBox::sorry(0L, i18n("<qt>Logging failed. Check that you have write access to <i>%1</i>.").arg(url.path()));
        return false;
      }
    } else
      KMessageBox::sorry(0L, i18n("<qt>Unsupported internal event action : <b>%1</b>.</qt>").arg(ev.action));
  } else
  if (ev.type == EventAction::External)
  {
      //KMessageBox::sorry(0L, i18n("External event actions are not yet supported."));
      if (ev.action == "script" || ev.action =="action")
      {
          QString name = ev.arguments[0];
          KAction *action = quantaApp->actionCollection()->action(name);
          TagAction *tagAction = dynamic_cast<TagAction*>(action);
          if (tagAction)
          {
            bool blocking = (ev.arguments[1] == "yes");
            EventAction event = ev;
            event.arguments.remove(event.arguments.at(1));
            tagAction->addArguments(event.arguments);
            tagAction->execute(blocking);
          }
          else
          if (action)
          {
            action->activate();
          } else
            KMessageBox::sorry(0L, i18n("<qt>The <b>%1</b> script action was not found on your system.</qt>").arg(name), i18n("Action Execution Error"));
      }  else
      KMessageBox::sorry(0L, i18n("Unsupported external event action."));
  } else
      KMessageBox::sorry(0L, i18n("Unknown event type."));
  return false;
}
Example #17
0
void Bowtie2AlignTask::prepare() {
    {
        QStringList indexSuffixes;
        indexSuffixes << ".1.bt2" << ".2.bt2" << ".3.bt2" << ".4.bt2" << ".rev.1.bt2" << ".rev.2.bt2";

        if(settings.indexFileName.isEmpty()) {
            if(settings.prebuiltIndex) {
                QString indexName = QFileInfo(settings.refSeqUrl.getURLString()).fileName();
                for (int i = 0; i < indexSuffixes.size(); ++i) {
                    indexName.remove(indexSuffixes[i]);
                }
                settings.indexFileName = settings.refSeqUrl.dirPath() + "/" + indexName;
            } else {
                settings.indexFileName = settings.resultFileName.dirPath() + "/" + settings.resultFileName.baseFileName();
            }
        }
    }

    QStringList arguments;
    arguments.append(settings.getCustomValue(Bowtie2Task::OPTION_MODE, "--end-to-end").toString());

    arguments.append("-N");
    arguments.append(settings.getCustomValue(Bowtie2Task::OPTION_MISMATCHES, 0).toString());

    arguments.append(QString("-L"));
    arguments.append(settings.getCustomValue(Bowtie2Task::OPTION_SEED_LEN, 20).toString());

    arguments.append(QString("--dpad"));
    arguments.append(settings.getCustomValue(Bowtie2Task::OPTION_DPAD, 15).toString());

    arguments.append(QString("--gbar"));
    arguments.append(settings.getCustomValue(Bowtie2Task::OPTION_GBAR, 4).toString());

    {
        int seed = settings.getCustomValue(Bowtie2Task::OPTION_SEED, -1).toInt();
        if(-1 != seed) {
            arguments.append(QString("--seed"));
            arguments.append(QString::number(seed));
        }
    }

    {
        int threads = settings.getCustomValue(Bowtie2Task::OPTION_THREADS, 1).toInt();
        arguments.append(QString("--threads"));
        arguments.append(QString::number(threads));
    }

    if (settings.getCustomValue(Bowtie2Task::OPTION_NOMIXED, false).toBool()) {
        arguments.append("--no-mixed");
    }
    if (settings.getCustomValue(Bowtie2Task::OPTION_NODISCORDANT, false).toBool()) {
        arguments.append("--no-discordant");
    }
    if(settings.getCustomValue(Bowtie2Task::OPTION_NOFW, false).toBool()) {
        arguments.append("--nofw");
    }
    if(settings.getCustomValue(Bowtie2Task::OPTION_NORC, false).toBool()) {
        arguments.append("--norc");
    }
    if(settings.getCustomValue(Bowtie2Task::OPTION_NOOVERLAP, false).toBool()) {
        arguments.append("--no-overlap");
    }
    if(settings.getCustomValue(Bowtie2Task::OPTION_NOCONTAIN, false).toBool()) {
        arguments.append("--no-contain");
    }

    // We assume all datasets have the same format
    // QSEQ format is not supported
    if(!settings.shortReadSets.isEmpty())
    {
        QList<GUrl> shortReadUrls = settings.getShortReadUrls();
        QList<FormatDetectionResult> detectionResults = DocumentUtils::detectFormat(shortReadUrls.first());
        if(!detectionResults.isEmpty()) {
            if(detectionResults.first().format->getFormatId() == BaseDocumentFormats::FASTA) {
                arguments.append("-f");
            } else if(detectionResults.first().format->getFormatId() == BaseDocumentFormats::RAW_DNA_SEQUENCE) {
                arguments.append("-r");
            } else if (detectionResults.first().format->getFormatId() == BaseDocumentFormats::FASTQ) {
                arguments.append("-q");
            }else{
                setError(tr("Unknown short reads format %1").arg(detectionResults.first().format->getFormatId()));
            }
        }
    } else {
        setError("Short read list is empty!");
        return;
    }

    arguments.append(settings.indexFileName);
    {
        // we assume that all datasets have same library type
        ShortReadSet::LibraryType libType = settings.shortReadSets.at(0).type;
        int setCount = settings.shortReadSets.size();

        // unpaired reeds
        if (libType == ShortReadSet::SingleEndReads ) {
            QStringList readUrlsArgument;
            for(int index = 0;index < setCount;index++) {
                readUrlsArgument.append(settings.shortReadSets[index].url.getURLString());
            }
            arguments.append("-U");
            arguments.append(readUrlsArgument.join(","));
        } else {
            // paired reeds: mate 1s and 2s
            QStringList upstreamReads,downstreamReads;

            for ( int i = 0; i<setCount; ++i) {
                const ShortReadSet& set = settings.shortReadSets.at(i);
                if (set.order == ShortReadSet::UpstreamMate) {
                    upstreamReads.append(set.url.getURLString());
                } else {
                    downstreamReads.append(set.url.getURLString());
                }
            }

            if ( upstreamReads.count() != downstreamReads.count() ) {
                setError("Unequal number of upstream and downstream reads!");
                return;
            }

            arguments.append("-1");
            arguments.append(upstreamReads.join(","));
            arguments.append("-2");
            arguments.append(downstreamReads.join(","));
        }
    }
    arguments.append("-S");
    arguments.append(settings.resultFileName.getURLString());

    ExternalToolRunTask *task = new ExternalToolRunTask(ET_BOWTIE2_ALIGN, arguments, new ExternalToolLogParser());
    addSubTask(task);
}
void CTile_browser_dlg::on_batchLoadPushButton_clicked()
{
	QFileDialog::Options options;
	QString selectedFilter;
	QString fileName = QFileDialog::getOpenFileName(this, tr("Choose Bitmap"), QString(tileBankBrowser.getAbsPath().c_str()) , tr("Targa Bitmap (*.tga);;PNG Image (*.png);;All Files (*.*);;"), &selectedFilter, options);
	QFileInfo fi(fileName);
	QString baseName = fi.baseName() ;


	if (!fileName.isEmpty())
	{
		QRegExp rx("\\d{2}$");
		baseName = baseName.remove(rx);
	
		
		//TODO titegus: What's the point in asking for rotation if Texture != Alpha ???
		bool rotate = (QMessageBox::Yes == QMessageBox::question(this, tr("Import rotated tiles"), tr("Do you want to use rotation to reuse alpha tiles?"), QMessageBox::Yes | QMessageBox::No ));

		for (int i=0; i<CTileSet::count; i++)
		{
			if (tileTextureButtonGroup->checkedId() == Alpha)
			{
				// Current transition
				CTileSet::TTransition transition=(CTileSet::TTransition)i;



				// Transition to patch
				CTileSetTransition* trans=tileBankBrowser.getTileSet (tileSetIndex)->getTransition (transition);
				if (tileBankBrowser.getTile (trans->getTile())->getRelativeFileName (CTile::alpha)=="")
				{
					// Continue ?
					int ok;

					// Try to load transition with rotation
					for (int rot=0; rot<4; rot++)
					{
						// Try to load a tile with a file name like /tiletransition0.tga
						QString transitionNumber = QString::number(transition);
						QString batchNumber = transitionNumber.rightJustified(2, '0');
						QString nextBaseName = baseName + batchNumber;
						QString nextFileName = QDir::toNativeSeparators(fi.absolutePath()) + QDir::separator() + nextBaseName + QString(".") + fi.suffix();
						FILE *pFile=fopen (nextFileName.toStdString().c_str(), "rb");

						// Close the file and add the tile if opened
						if (pFile)
						{
							fclose (pFile);
							ok=browserModel.setTileTransitionAlpha (i, nextFileName.toStdString().c_str(), (4-rot)%4);

							// End
							break;
						}

						// Rotate the transition
						transition=CTileSet::rotateTransition (transition);

						if (!rotate)
							break;
					}
					if (!ok)
						break;
				}
			}
			else
			{

				//TODO titegus: Check that, Batch Load seems useless
				// Current transition
				CTileSet::TTransition transition=(CTileSet::TTransition)i;

				// Transition to patch
				//CTileSetTransition* trans=tileBankBrowser.getTileSet (tileSetIndex)->getTransition (transition);
				//if (tileBankBrowser.getTile (trans->getTile())->getRelativeFileName ((CTile::TBitmap)tileTextureButtonGroup->checkedId())=="")
				//{
				//	// Try to load a tile with a file name like /tiletransition0.tga
				//	char sName2[256];
				//	char sFinal[256];
				//	sprintf (sName2, "%s%02d", sName, (int)transition);
				//	_makepath (sFinal, sDrive, sPath, sName2, sExt);
				//	FILE *pFile=fopen (sFinal, "rb");

				//	// Close the file and add the tile if opened
				//	if (pFile)
				//	{
				//		fclose (pFile);
				//		if (!infoList.setTileTransition (i, sFinal, (CTile::TBitmap) tileTextureButtonGroup->checkedId()))
				//			break;
				//	}
				//}
			}
		}
		

		LoadInThread();

	}
}
Example #19
0
QString
findPartitionPathForMountPoint( const FstabEntryList& fstab,
                                const QString& mountPoint )
{
    if ( fstab.isEmpty() )
        return QString();

    for ( const FstabEntry& entry : fstab )
    {
        if ( entry.mountPoint == mountPoint )
        {
            QProcess readlink;
            QString partPath;

            if ( entry.partitionNode.startsWith( "/dev" ) ) // plain dev node
            {
                partPath = entry.partitionNode;
            }
            else if ( entry.partitionNode.startsWith( "LABEL=" ) )
            {
                partPath = entry.partitionNode.mid( 6 );
                partPath.remove( "\"" );
                partPath.replace( "\\040", "\\ " );
                partPath.prepend( "/dev/disk/by-label/" );
            }
            else if ( entry.partitionNode.startsWith( "UUID=" ) )
            {
                partPath = entry.partitionNode.mid( 5 );
                partPath.remove( "\"" );
                partPath = partPath.toLower();
                partPath.prepend( "/dev/disk/by-uuid/" );
            }
            else if ( entry.partitionNode.startsWith( "PARTLABEL=" ) )
            {
                partPath = entry.partitionNode.mid( 10 );
                partPath.remove( "\"" );
                partPath.replace( "\\040", "\\ " );
                partPath.prepend( "/dev/disk/by-partlabel/" );
            }
            else if ( entry.partitionNode.startsWith( "PARTUUID=" ) )
            {
                partPath = entry.partitionNode.mid( 9 );
                partPath.remove( "\"" );
                partPath = partPath.toLower();
                partPath.prepend( "/dev/disk/by-partuuid/" );
            }

            // At this point we either have /dev/sda1, or /dev/disk/by-something/...

            if ( partPath.startsWith( "/dev/disk/by-" ) ) // we got a fancy node
            {
                readlink.start( "readlink", { "-en", partPath });
                if ( !readlink.waitForStarted( 1000 ) )
                    return QString();
                if ( !readlink.waitForFinished( 1000 ) )
                    return QString();
                if ( readlink.exitCode() != 0 || readlink.exitStatus() != QProcess::NormalExit )
                    return QString();
                partPath = QString::fromLocal8Bit(
                               readlink.readAllStandardOutput() ).trimmed();
            }

            return partPath;
        }
    }

    return QString();
}
Example #20
0
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice,
    const QString &fname, QString currentPath, bool ignoreErrors)
{
    Q_ASSERT(m_errorDevice);
    const QChar slash = QLatin1Char('/');
    if (!currentPath.isEmpty() && !currentPath.endsWith(slash))
        currentPath += slash;

    QDomDocument document;
    {
        QString errorMsg;
        int errorLine = 0;
        int errorColumn = 0;
        if (!document.setContent(inputDevice, &errorMsg, &errorLine, &errorColumn)) {
            if (ignoreErrors)
                return true;
            const QString msg = QString::fromUtf8("RCC Parse Error: '%1' Line: %2 Column: %3 [%4]\n").arg(fname).arg(errorLine).arg(errorColumn).arg(errorMsg);
            m_errorDevice->write(msg.toUtf8());
            return false;
        }
    }

    QDomElement domRoot = document.firstChildElement(m_strings.TAG_RCC).toElement();
    if (!domRoot.isNull() && domRoot.tagName() == m_strings.TAG_RCC) {
        for (QDomNode node = domRoot.firstChild(); !node.isNull(); node = node.nextSibling()) {
            if (!node.isElement())
                continue;

            QDomElement child = node.toElement();
            if (!child.isNull() && child.tagName() == m_strings.TAG_RESOURCE) {
                QLocale::Language language = QLocale::c().language();
                QLocale::Country country = QLocale::c().country();

                if (child.hasAttribute(m_strings.ATTRIBUTE_LANG)) {
                    QString attribute = child.attribute(m_strings.ATTRIBUTE_LANG);
                    QLocale lang = QLocale(attribute);
                    language = lang.language();
                    if (2 == attribute.length()) {
                        // Language only
                        country = QLocale::AnyCountry;
                    } else {
                        country = lang.country();
                    }
                }

                QString prefix;
                if (child.hasAttribute(m_strings.ATTRIBUTE_PREFIX))
                    prefix = child.attribute(m_strings.ATTRIBUTE_PREFIX);
                if (!prefix.startsWith(slash))
                    prefix.prepend(slash);
                if (!prefix.endsWith(slash))
                    prefix += slash;

                for (QDomNode res = child.firstChild(); !res.isNull(); res = res.nextSibling()) {
                    if (res.isElement() && res.toElement().tagName() == m_strings.TAG_FILE) {

                        QString fileName(res.firstChild().toText().data());
                        if (fileName.isEmpty()) {
                            const QString msg = QString::fromUtf8("RCC: Warning: Null node in XML of '%1'\n").arg(fname);
                            m_errorDevice->write(msg.toUtf8());
                        }
                        QString alias;
                        if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_ALIAS))
                            alias = res.toElement().attribute(m_strings.ATTRIBUTE_ALIAS);
                        else
                            alias = fileName;

                        int compressLevel = m_compressLevel;
                        if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_COMPRESS))
                            compressLevel = res.toElement().attribute(m_strings.ATTRIBUTE_COMPRESS).toInt();
                        int compressThreshold = m_compressThreshold;
                        if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_THRESHOLD))
                            compressThreshold = res.toElement().attribute(m_strings.ATTRIBUTE_THRESHOLD).toInt();

                        // Special case for -no-compress. Overrides all other settings.
                        if (m_compressLevel == -2)
                            compressLevel = 0;

                        alias = QDir::cleanPath(alias);
                        while (alias.startsWith(QLatin1String("../")))
                            alias.remove(0, 3);
                        alias = QDir::cleanPath(m_resourceRoot) + prefix + alias;

                        QString absFileName = fileName;
                        if (QDir::isRelativePath(absFileName))
                            absFileName.prepend(currentPath);
                        QFileInfo file(absFileName);
                        if (!file.exists()) {
                            m_failedResources.push_back(absFileName);
                            const QString msg = QString::fromUtf8("RCC: Error in '%1': Cannot find file '%2'\n").arg(fname).arg(fileName);
                            m_errorDevice->write(msg.toUtf8());
                            if (ignoreErrors)
                                continue;
                            else
                                return false;
                        } else if (file.isFile()) {
                            const bool arc =
                                addFile(alias,
                                        RCCFileInfo(alias.section(slash, -1),
                                                    file,
                                                    language,
                                                    country,
                                                    RCCFileInfo::NoFlags,
                                                    compressLevel,
                                                    compressThreshold)
                                        );
                            if (!arc)
                                m_failedResources.push_back(absFileName);
                        } else {
                            QDir dir;
                            if (file.isDir()) {
                                dir.setPath(file.filePath());
                            } else {
                                dir.setPath(file.path());
                                dir.setNameFilters(QStringList(file.fileName()));
                                if (alias.endsWith(file.fileName()))
                                    alias = alias.left(alias.length()-file.fileName().length());
                            }
                            if (!alias.endsWith(slash))
                                alias += slash;
                            QDirIterator it(dir, QDirIterator::FollowSymlinks|QDirIterator::Subdirectories);
                            while (it.hasNext()) {
                                it.next();
                                QFileInfo child(it.fileInfo());
                                if (child.fileName() != QLatin1String(".") && child.fileName() != QLatin1String("..")) {
                                    const bool arc =
                                        addFile(alias + child.fileName(),
                                                RCCFileInfo(child.fileName(),
                                                            child,
                                                            language,
                                                            country,
                                                            RCCFileInfo::NoFlags,
                                                            compressLevel,
                                                            compressThreshold)
                                                );
                                    if (!arc)
                                        m_failedResources.push_back(child.fileName());
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if (m_root == 0) {
        const QString msg = QString::fromUtf8("RCC: Warning: No resources in '%1'.\n").arg(fname);
        m_errorDevice->write(msg.toUtf8());
        if (!ignoreErrors && m_format == Binary) {
            // create dummy entry, otherwise loading qith QResource will crash
            m_root = new RCCFileInfo(QString(), QFileInfo(),
                    QLocale::C, QLocale::AnyCountry, RCCFileInfo::Directory);
        }
    }

    return true;
}
Example #21
0
File: ct08.cpp Project: mtab3/qct08
void CT08::QGetData( int ch, int num, QVector<double> &data )
{
  int cnt = 0;
  data.clear();

  //  QString cmd = QString( "GSCRDX?%1%2%3%4%5" )
  int Num = num;
  if ( num > 9999 ) {
    Num = ceil( ((double)Num) / 1000. );
  } else {
    Num -= 1;     // データ個数は Num 個、なので読み出し番地指定は 0〜Num-1
  }
    
  QString cmd = QString( "GSCRDXH?%1%2%3%4%5" )
    .arg( ch,     2, 10, QChar( '0' ) )     // 指定チャンネル (ch) から
    .arg( ch,     2, 10, QChar( '0' ) )     // 指定チャンネル (ch) までの、要は ch だけの
    .arg( (int)1, 2, 10, QChar( '0' ) )     // タイマーも読み出して(0:w/o, 1:w timer)
    .arg( (int)0, 4, 10, QChar( '0' ) )     // 0 番目から
    .arg( Num,    4, 10, QChar( '0' ) );    // num 番目までのデータを読みだす
  if ( num > 9999 )
    cmd += "K";
  SendACmd( cmd );

  bool Finished = false;
  QTime eTime;
  eTime.start();  // measure total time to elapsed in the following loop 
  while(( cnt < num )&&( !Finished )) {
    qDebug() << "waitForReadyRead" << ss->bytesAvailable() << cnt << num;
    // ここでデータがなるべく多く受信バッファに溜るのを待つ。
    int oldLen = 0, newLen;
    if ( ! ss->waitForReadyRead( 50 ) ) {
      if ( eTime.elapsed() > 1000 )
	Finished = true;
    }
    while( ( newLen = ss->bytesAvailable() ) != oldLen ) {
      oldLen = newLen;
      ss->waitForReadyRead( 50 );
    }
    
    double time0 = 0;
    double time = 0;
    qDebug() << "in QGetData : num = " << num;
    while( ! ss->atEnd() ) {
      QString Rbuf = ss->readLine().simplified();
      if ( Rbuf == "EOF" ) {
	Finished = true;
	qDebug() << "normally break by EOF";
	break;
      }
      QStringList vals = Rbuf.remove( ' ' ).split( ',' );
      if ( vals.count() == 2 ) {
	time = (double)vals[1].toInt( NULL, 16 ) / 1e6;
	if ( cnt < num ) {   // The number of data is 'num'
	  if ( time != time0 ) {
	    data << (double)vals[0].toInt( NULL, 16 ) / ( time - time0 );
	    time0 = time;
	  }
	}
	cnt++;
      }
    }
    qDebug() << "in QGetData : data.count() = " << data.count();
  }
  qDebug() << "-----------------------";
}
Example #22
0
QString Serveur::parseCommande(QString comm,bool serveur)
{
    if(comm.startsWith("/"))
    {
        comm.remove(0,1);
        QString pref=comm.split(" ").first();
        QStringList args=comm.split(" ");
        args.removeFirst();
        QString destChan=tab->tabText(tab->currentIndex());
        QString msg=args.join(" ");

        if(pref=="me")
            return "PRIVMSG "+destChan+" ACTION " + msg + "";
        else if(pref=="join")
        {
            join(msg);
            return " ";
        }
        else if(pref=="quit")
        {
            if(msg == "")
                return "QUIT "+msgQuit;
            else
                return "QUIT "+msg;
        }
        else if(pref=="part")
        {
            tab->removeTab(tab->currentIndex());

            if(msg == "")
            {
                if(msg.startsWith("#"))
                    destChan=msg.split(" ").first();

                if(msgQuit=="")
                    return "PART "+destChan+" using IrcLightClient";
                else
                    return "PART "+destChan+" "+msgQuit;
            }
            else
                return "PART "+destChan+" "+msg;

            conversations.remove(destChan);
        }
        else if(pref=="kick")
        {
            QStringList tableau=msg.split(" ");
            QString c1,c2,c3;
            if(tableau.count() > 0) c1=" "+tableau.first();
            else c1="";
            if(tableau.count() > 1) c2=" "+tableau.at(1);
            else c2="";
            if(tableau.count() > 2) c3=" "+tableau.at(2);
            else c3="";

            if(c1.startsWith("#"))
                return "KICK"+c1+c2+c3;
            else
                return "KICK "+destChan+c1+c2;
        }
        else if(pref=="update")
        {
            updateUsers=true;
            return "WHO "+destChan;
        }
        else if(pref=="ns")
        {
            return "NICKSERV "+msg;
        }
        else if(pref=="nick")
        {
            emit pseudoChanged(msg);
                        ecrire("-> Nickname changed to "+msg);
            return "NICK "+msg;
        }
        else
            return pref+" "+msg;
    }
    else if(!serveur)
	{
        QString destChan=tab->tabText(tab->currentIndex());
                if(comm.endsWith("<br />"))
                    comm=comm.remove(QRegExp("<br />$"));
                ecrire("<b>&lt;"+pseudo+"&gt;</b> "+comm,destChan);

        if(comm.startsWith(":"))
            comm.insert(0,":");

        return "PRIVMSG "+destChan+" "+comm.replace(" ",".")+"";
    }
	else
	{
		return "";
	}
}
Example #23
0
void HttpConnection::respond() {
  if ((m_socket->peerAddress() != QHostAddress::LocalHost
      && m_socket->peerAddress() != QHostAddress::LocalHostIPv6)
     || m_httpserver->isLocalAuthEnabled()) {
    // Authentication
    const QString peer_ip = m_socket->peerAddress().toString();
    const int nb_fail = m_httpserver->NbFailedAttemptsForIp(peer_ip);
    if (nb_fail >= MAX_AUTH_FAILED_ATTEMPTS) {
      m_generator.setStatusLine(403, "Forbidden");
      m_generator.setMessage(tr("Your IP address has been banned after too many failed authentication attempts."));
      write();
      return;
    }
    QString auth = m_parser.header().value("Authorization");
    if (auth.isEmpty()) {
      // Return unauthorized header
      qDebug("Auth is Empty...");
      m_generator.setStatusLine(401, "Unauthorized");
      m_generator.setValue("WWW-Authenticate",  "Digest realm=\""+QString(QBT_REALM)+"\", nonce=\""+m_httpserver->generateNonce()+"\", opaque=\""+m_httpserver->generateNonce()+"\", stale=\"false\", algorithm=\"MD5\", qop=\"auth\"");
      write();
      return;
    }
    //qDebug("Auth: %s", qPrintable(auth.split(" ").first()));
    if (QString::compare(auth.split(" ").first(), "Digest", Qt::CaseInsensitive) != 0
        || !m_httpserver->isAuthorized(auth.toUtf8(), m_parser.header().method())) {
      // Update failed attempt counter
      m_httpserver->increaseNbFailedAttemptsForIp(peer_ip);
      qDebug("client IP: %s (%d failed attempts)", qPrintable(peer_ip), nb_fail);
      // Return unauthorized header
      m_generator.setStatusLine(401, "Unauthorized");
      m_generator.setValue("WWW-Authenticate",  "Digest realm=\""+QString(QBT_REALM)+"\", nonce=\""+m_httpserver->generateNonce()+"\", opaque=\""+m_httpserver->generateNonce()+"\", stale=\"false\", algorithm=\"MD5\", qop=\"auth\"");
      write();
      return;
    }
    // Client successfully authenticated, reset number of failed attempts
    m_httpserver->resetNbFailedAttemptsForIp(peer_ip);
  }
  QString url  = m_parser.url();
  // Favicon
  if (url.endsWith("favicon.ico")) {
    qDebug("Returning favicon");
    QFile favicon(":/Icons/skin/qbittorrent16.png");
    if (favicon.open(QIODevice::ReadOnly)) {
      const QByteArray data = favicon.readAll();
      favicon.close();
      m_generator.setStatusLine(200, "OK");
      m_generator.setContentTypeByExt("png");
      m_generator.setMessage(data);
      write();
    } else {
      respondNotFound();
    }
    return;
  }

  QStringList list = url.split('/', QString::SkipEmptyParts);
  if (list.contains(".") || list.contains("..")) {
    respondNotFound();
    return;
  }

  if (list.isEmpty())
    list.append("index.html");

  if (list.size() >= 2) {
    if (list[0] == "json") {
      if (list[1] == "torrents") {
        respondTorrentsJson();
        return;
      }
      if (list.size() > 2) {
        if (list[1] == "propertiesGeneral") {
          const QString& hash = list[2];
          respondGenPropertiesJson(hash);
          return;
        }
        if (list[1] == "propertiesTrackers") {
          const QString& hash = list[2];
          respondTrackersPropertiesJson(hash);
          return;
        }
        if (list[1] == "propertiesFiles") {
          const QString& hash = list[2];
          respondFilesPropertiesJson(hash);
          return;
        }
      } else {
        if (list[1] == "preferences") {
          respondPreferencesJson();
          return;
        } else {
          if (list[1] == "transferInfo") {
            respondGlobalTransferInfoJson();
            return;
          }
        }
      }
    }
    if (list[0] == "command") {
      const QString& command = list[1];
      if (command == "shutdown") {
        qDebug() << "Shutdown request from Web UI";
        // Special case handling for shutdown, we
        // need to reply to the Web UI before
        // actually shutting down.
        m_generator.setStatusLine(200, "OK");
        write();
        qApp->processEvents();
        // Exit application
        qApp->exit();
      } else {
        respondCommand(command);
        m_generator.setStatusLine(200, "OK");
        write();
      }
      return;
    }
  }

  // Icons from theme
  //qDebug() << "list[0]" << list[0];
  if (list[0] == "theme" && list.size() == 2) {
#ifdef DISABLE_GUI
    url = ":/Icons/oxygen/"+list[1]+".png";
#else
    url = IconProvider::instance()->getIconPath(list[1]);
#endif
    qDebug() << "There icon:" << url;
  } else {
    if (list[0] == "images") {
      list[0] = "Icons";
    } else {
      if (list.last().endsWith(".html"))
        list.prepend("html");
      list.prepend("webui");
    }
    url = ":/" + list.join("/");
  }
  QFile file(url);
  if (!file.open(QIODevice::ReadOnly)) {
    qDebug("File %s was not found!", qPrintable(url));
    respondNotFound();
    return;
  }
  QString ext = list.last();
  int index = ext.lastIndexOf('.') + 1;
  if (index > 0)
    ext.remove(0, index);
  else
    ext.clear();
  QByteArray data = file.readAll();
  file.close();

  // Translate the page
  if (ext == "html" || (ext == "js" && !list.last().startsWith("excanvas"))) {
    QString dataStr = QString::fromUtf8(data.constData());
    translateDocument(dataStr);
    if (url.endsWith("about.html")) {
      dataStr.replace("${VERSION}", VERSION);
    }
    data = dataStr.toUtf8();
  }
  m_generator.setStatusLine(200, "OK");
  m_generator.setContentTypeByExt(ext);
  m_generator.setMessage(data);
  write();
}
Example #24
0
void MiningPage::readProcessOutput()
{
    QByteArray output;

    minerProcess->reset();

    output = minerProcess->readAll();

    QString outputString(output);

    if (!outputString.isEmpty())
    {
        QStringList list = outputString.split("\n", QString::SkipEmptyParts);
        int i;
        for (i=0; i<list.size(); i++)
        {
            QString line = list.at(i);

            // Ignore protocol dump
            if (!line.startsWith("[") || line.contains("JSON protocol") || line.contains("HTTP hdr"))
                continue;

            if (ui->debugCheckBox->isChecked())
            {
                ui->list->addItem(line.trimmed());
                ui->list->scrollToBottom();
            }

            if (line.contains("(yay!!!)"))
                reportToList("Share accepted", SHARE_SUCCESS, getTime(line));
            else if (line.contains("(booooo)"))
                reportToList("Share rejected", SHARE_FAIL, getTime(line));
            else if (line.contains("LONGPOLL detected new block"))
                reportToList("LONGPOLL detected a new block", LONGPOLL, getTime(line));
            else if (line.contains("Supported options:"))
                reportToList("Miner didn't start properly. Try checking your settings.", ERROR, NULL);
            else if (line.contains("The requested URL returned error: 403"))
                reportToList("Couldn't connect. Please check your username and password.", ERROR, NULL);
            else if (line.contains("HTTP request failed"))
                reportToList("Couldn't connect. Please check pool server and port.", ERROR, NULL);
            else if (line.contains("JSON-RPC call failed"))
                reportToList("Couldn't communicate with server. Retrying in 30 seconds.", ERROR, NULL);
            else if (line.contains("thread ") && line.contains("khash/s"))
            {
                QString threadIDstr = line.at(line.indexOf("thread ")+7);
                int threadID = threadIDstr.toInt();

                int threadSpeedindx = line.indexOf(",");
                QString threadSpeedstr = line.mid(threadSpeedindx);
                threadSpeedstr.chop(8);
                threadSpeedstr.remove(", ");
                threadSpeedstr.remove(" ");
                threadSpeedstr.remove('\n');
                double speed=0;
                speed = threadSpeedstr.toDouble();

                threadSpeed[threadID] = speed;

                updateSpeed();
            }
        }
    }
}
Example #25
0
File: dtd.cpp Project: KDE/quanta
void DTD::parseTagAttributeValues(QString name, QString *value) {
    AttributeList *attributes = new AttributeList();

    QStringList attrLines = QStringList::split("\\end",*value);
    QStringList::Iterator lineIt = attrLines.begin();
    while (lineIt != attrLines.end()) //iterate through the attribute lines
    {
        //split the attribute line
        QStringList all = QStringList::split(" ", *lineIt);
        QStringList::Iterator it = all.begin();
        while(it != all.end())
        {
            Attribute *attr = new Attribute();
            attr->name = *it;
            //kdDebug() << "Inserting for tag " << name << ": " << *it << endl;
            ++it;

            QString values = *it;
            //list of possible values
            if ( values.startsWith("(") && values.endsWith(")") )
            {
                values.remove(0,1);
                values.remove(values.length()-1,1);
                attr->values = QStringList::split("|", values);
                QString s = (attr->values[0]+attr->values[1]).lower();
                stripSpaces(&s);
                if ((s == "truefalse") || (s == "falsetrue"))
                {
                    attr->type = "check";
                } else
                {
                    attr->type = "list";
                }
            } else
            {
                attr->values = values;
                attr->type = "input";
            }

            //kdDebug() << " --- values: " << *it << endl;
            if (it != all.end())
            {
                ++it;
                QString s=*it;
                if (s.startsWith("\"") && s.endsWith("\"") && it!=all.end())
                {
                    s.remove(0,1);
                    s.remove(s.length()-1,1);
                    attr->defaultValue = s;
                }
                if (s.startsWith("#") && it != all.end())
                {
                    s.remove(0,1);
                    attr->status = s.lower();
                }
                if (*it == "#FIXED" && it != all.end())
                {
                    ++it;
                    attr->values.append(*it);
                }
            }

            if (it != all.end())
            {
                ++it;
            }
            attributes->append(attr);
        }
        ++lineIt;
    }
    tagAttributes.insert(name, attributes);
}
QString CQuazaaSysInfo::osVersionToString()
{
	QString operatingSystemString = "";

#if defined(Q_OS_WIN)
	QString sVersion;
	QString sEdition;
	QString sServicePack;
	QString sMachine;

	switch(GetWindowsVersion())
	{
	case WindowsVersion::Windows:
		sVersion = "Windows";
		break;
	case WindowsVersion::Windows32s:
		sVersion = "Windows 32s";
		break;
	case WindowsVersion::Windows95:
		sVersion = "Windows 95";
		break;
	case WindowsVersion::Windows95OSR2:
		sVersion = "Windows 95 SR2";
		break;
	case WindowsVersion::Windows98:
		sVersion = "Windows 98";
		break;
	case WindowsVersion::Windows98SE:
		sVersion = "Windows 98 SE";
		break;
	case WindowsVersion::WindowsMillennium:
		sVersion = "Windows Me";
		break;
	case WindowsVersion::WindowsNT351:
		sVersion = "Windows NT 3.51";
		break;
	case WindowsVersion::WindowsNT40:
		sVersion = "Windows NT 4.0";
		break;
	case WindowsVersion::WindowsNT40Server:
		sVersion = "Windows NT 4.0 Server";
		break;
	case WindowsVersion::Windows2000:
		sVersion = "Windows 2000";
		break;
	case WindowsVersion::WindowsXP:
		sVersion = "Windows XP";
		break;
	case WindowsVersion::WindowsXPProfessionalx64:
		sVersion = "Windows XP Professional x64";
		break;
	case WindowsVersion::WindowsHomeServer:
		sVersion = "Windows Home Server";
		break;
	case WindowsVersion::WindowsServer2003:
		sVersion = "Windows Server 2003";
		break;
	case WindowsVersion::WindowsServer2003R2:
		sVersion = "Windows Server 2003 R2";
		break;
	case WindowsVersion::WindowsVista:
		sVersion = "Windows Vista";
		break;
	case WindowsVersion::WindowsServer2008:
		sVersion = "Windows Server 2008";
		break;
	case WindowsVersion::WindowsServer2008R2:
		sVersion = "Windows Server 2008 R2";
		break;
	case WindowsVersion::Windows7:
		sVersion = "Windows 7";
		break;
	case WindowsVersion::WindowsServer2012:
		sVersion = "Windows Server 2012";
		break;
	case WindowsVersion::Windows8:
		sVersion = "Windows 8";
		break;
	default:
		sVersion = "Unknown Windows Version";
		break;
	}

	switch(GetWindowsEdition())
	{
	case WindowsEdition::EditionUnknown:
		sEdition = "Unknown Edition";
		break;
	case WindowsEdition::Workstation:
		sEdition = "Workstation";
		break;
	case WindowsEdition::Server:
		sEdition = "Server";
		break;
	case WindowsEdition::AdvancedServer:
		sEdition = "Advanced Server";
		break;
	case WindowsEdition::Home:
		sEdition = "Home";
		break;
	case WindowsEdition::Ultimate:
		sEdition = "Ultimate";
		break;
	case WindowsEdition::HomeBasic:
		sEdition = "Home Basic";
		break;
	case WindowsEdition::HomePremium:
		sEdition = "Home Premium";
		break;
	case WindowsEdition::Enterprise:
		sEdition = "Enterprise";
		break;
	case WindowsEdition::HomeBasicN:
		sEdition = "Home Basic N";
		break;
	case WindowsEdition::Business:
		sEdition = "Business";
		break;
	case WindowsEdition::StandardServer:
		sEdition = "Server Standard";
		break;
	case WindowsEdition::DatacenterServer:
		sEdition = "Server Datacenter (full installation)";
		break;
	case WindowsEdition::SmallBusinessServer:
		sEdition = "Small Business Server";
		break;
	case WindowsEdition::EnterpriseServer:
		sEdition = "Server Enterprise (full installation)";
		break;
	case WindowsEdition::Starter:
		sEdition = "Starter";
		break;
	case WindowsEdition::DatacenterServerCore:
		sEdition = "Server Datacenter (core installation)";
		break;
	case WindowsEdition::StandardServerCore:
		sEdition = "Server Standard (core installation)";
		break;
	case WindowsEdition::EnterpriseServerCore:
		sEdition = "Server Enterprise (core installation)";
		break;
	case WindowsEdition::EnterpriseServerIA64:
		sEdition = "Server Enterprise for Itanium-based Systems";
		break;
	case WindowsEdition::BusinessN:
		sEdition = "Business N";
		break;
	case WindowsEdition::WebServer:
		sEdition = "Web Server (full installation)";
		break;
	case WindowsEdition::ClusterServer:
		sEdition = "High Performance Computing Edition";
		break;
	case WindowsEdition::HomeServer:
		sEdition = "Storage Server 2008 R2 Essentials";
		break;
	case WindowsEdition::StorageExpressServer:
		sEdition = "Storage Server Express";
		break;
	case WindowsEdition::StorageStandardServer:
		sEdition = "Storage Server Standard";
		break;
	case WindowsEdition::StorageWorkgroupServer:
		sEdition = "Storage Server Workgroup";
		break;
	case WindowsEdition::StorageEnterpriseServer:
		sEdition = "Storage Server Enterprise";
		break;
	case WindowsEdition::ServerForSmallBusiness:
		sEdition = "for Windows Essential Server Solutions";
		break;
	case WindowsEdition::SmallBusinessServerPremium:
		sEdition = "Small Business Server Premium";
		break;
	case WindowsEdition::HomePremiumN:
		sEdition = "Home Premium N";
		break;
	case WindowsEdition::EnterpriseN:
		sEdition = "Enterprise N";
		break;
	case WindowsEdition::UltimateN:
		sEdition = "Ultimate N";
		break;
	case WindowsEdition::WebServerCore:
		sEdition = "Web Server (core installation)";
		break;
	case WindowsEdition::MediumBusinessServerManagement:
		sEdition = "Essential Business Server Management Server";
		break;
	case WindowsEdition::MediumBusinessServerSecurity:
		sEdition = "Essential Business Server Security Server";
		break;
	case WindowsEdition::MediumBusinessServerMessaging:
		sEdition = "Essential Business Server Messaging Server";
		break;
	case WindowsEdition::ServerFoundation:
		sEdition = "Server Foundation";
		break;
	case WindowsEdition::HomePremiumServer:
		sEdition = "Home Server 2011";
		break;
	case WindowsEdition::ServerForSmallBusinessV:
		sEdition = "without Hyper-V for Windows Essential Server Solutions";
		break;
	case WindowsEdition::StandardServerV:
		sEdition = "Server Standard without Hyper-V";
		break;
	case WindowsEdition::DatacenterServerV:
		sEdition = "Server Datacenter without Hyper-V (full installation)";
		break;
	case WindowsEdition::EnterpriseServerV:
		sEdition = "Server Enterprise without Hyper-V (full installation)";
		break;
	case WindowsEdition::DatacenterServerCoreV:
		sEdition = "Server Datacenter without Hyper-V (core installation)";
		break;
	case WindowsEdition::StandardServerCoreV:
		sEdition = "Server Standard without Hyper-V (core installation)";
		break;
	case WindowsEdition::EnterpriseServerCoreV:
		sEdition = "Server Enterprise without Hyper-V (core installation) ";
		break;
	case WindowsEdition::HyperV:
		sEdition = "Hyper-V Server";
		break;
	case WindowsEdition::StorageExpressServerCore:
		sEdition = "Storage Express Server Core";
		break;
	case WindowsEdition::StorageStandardServerCore:
		sEdition = "Storage Standard Server Core";
		break;
	case WindowsEdition::StorageWorkgroupServerCore:
		sEdition = "Storage Workgroup Server Core";
		break;
	case WindowsEdition::StorageEnterpriseServerCore:
		sEdition = "Storage Enterprise Server Core";
		break;
	case WindowsEdition::StarterN:
		sEdition = "Starter N";
		break;
	case WindowsEdition::Professional:
		sEdition = "Professional";
		break;
	case WindowsEdition::ProfessionalN:
		sEdition = "Professional N";
		break;
	case WindowsEdition::SBSolutionServer:
		sEdition = "Windows Small Business Server 2011 Essentials";
		break;
	case WindowsEdition::ServerForSBSolutions:
		sEdition = "Server For Small Business Solutions";
		break;
	case WindowsEdition::StandardServerSolutions:
		sEdition = "Server Solutions Premium";
		break;
	case WindowsEdition::StandardServerSolutionsCore:
		sEdition = "Server Solutions Premium (core installation)";
		break;
	case WindowsEdition::SBSolutionServerEM:
		sEdition = "Server For Small Business Solutions EM";
		break;
	case WindowsEdition::ServerForSBSolutionsEM:
		sEdition = "Server For Small Business Solutions EM";
		break;
	case WindowsEdition::SolutionEmbeddedServer:
		sEdition = "MultiPoint Server";
		break;
	case WindowsEdition::SolutionEmbeddedServerCore:
		sEdition = "MultiPoint Server (core installation)";
		break;
	case WindowsEdition::EssentialBusinessServerMGMT:
		sEdition = "Essential Server Solution Management";
		break;
	case WindowsEdition::EssentialBusinessServerADDL:
		sEdition = "Essential Server Solution Additional";
		break;
	case WindowsEdition::EssentialBusinessServerMGMTSVC:
		sEdition = "Essential Server Solution Management Service";
		break;
	case WindowsEdition::EssentialBusinessServerADDLSVC:
		sEdition = "Essential Server Solution Additional Service";
		break;
	case WindowsEdition::SmallBusinessServerPremiumCore:
		sEdition = "Small Business Server Premium (core installation)";
		break;
	case WindowsEdition::ClusterServerV:
		sEdition = "Server Hyper Core V";
		break;
	case WindowsEdition::Embedded:
		sEdition = "Embedded Standard";
		break;
	case WindowsEdition::StarterE:
		sEdition = "Starter E";
		break;
	case WindowsEdition::HomeBasicE:
		sEdition = "Home Basic E";
		break;
	case WindowsEdition::HomePremiumE:
		sEdition = "Home Premium E";
		break;
	case WindowsEdition::ProfessionalE:
		sEdition = "Professional E";
		break;
	case WindowsEdition::EnterpriseE:
		sEdition = "Enterprise E";
		break;
	case WindowsEdition::UltimateE:
		sEdition = "Ultimate E";
		break;
	case WindowsEdition::EnterpriseEvaluation:
		sEdition = "Server Enterprise (evaluation installation)";
		break;
	case WindowsEdition::MultipointStandardServer:
		sEdition = "MultiPoint Server Standard (full installation)";
		break;
	case WindowsEdition::MultipointPremiumServer:
		sEdition = "MultiPoint Server Premium (full installation)";
		break;
	case WindowsEdition::StandardEvaluationServer:
		sEdition = "Server Standard (evaluation installation)";
		break;
	case WindowsEdition::DatacenterEvaluationServer:
		sEdition = "Server Datacenter (evaluation installation)";
		break;
	case WindowsEdition::EnterpriseNEvaluation:
		sEdition = "Enterprise N (evaluation installation)";
		break;
	case WindowsEdition::StorageWorkgroupEvaluationServer:
		sEdition = "Storage Server Workgroup (evaluation installation)";
		break;
	case WindowsEdition::StorageStandardEvaluationServer:
		sEdition = "Storage Server Standard (evaluation installation)";
		break;
	case WindowsEdition::CoreN:
		sEdition = "Core N";
		break;
	case WindowsEdition::CoreCountrySpecific:
		sEdition = "Core China";
		break;
	case WindowsEdition::CoreSingleLanguage:
		sEdition = "Core Single Language";
		break;
	case WindowsEdition::Core:
		sEdition = "Core";
		break;
	case WindowsEdition::ProfessionalWindowsMediaCenter:
		sEdition = "Professional Windows Media Center";
		break;
	default:
		sEdition = "Unknown Edition";
	}

	sServicePack = GetServicePackInfo();

	if(Is64bitPlatform())
		sMachine = "64-bit";
	else
		sMachine = "32-bit";

	operatingSystemString = QString(sVersion + " ");
	if(!sEdition.isEmpty())
		operatingSystemString.append(sEdition + " ");
	if(!sServicePack.isEmpty())
		operatingSystemString.append(tr("with %1 ").arg(sServicePack));
	operatingSystemString.append(sMachine);

#elif defined(Q_OS_MAC)
	switch ( QSysInfo::MacintoshVersion ) {
		case QSysInfo::MV_9 :
			operatingSystemString = "Mac OS 9 (unsupported)";
			break;
		case QSysInfo::MV_10_0 :
			operatingSystemString = "Mac OS X 10.0 Cheetah (unsupported)";
			break;
		case QSysInfo::MV_10_1 :
			operatingSystemString = "Mac OS X 10.1 Puma (unsupported)";
			break;
		case QSysInfo::MV_10_2 :
			operatingSystemString = "Mac OS X 10.2 Jaguar (unsupported)";
			break;
		case QSysInfo::MV_10_3 :
			operatingSystemString = "Mac OS X 10.3 Panther";
			break;
		case QSysInfo::MV_10_4 :
			operatingSystemString = "Mac OS X 10.4 Tiger";
			break;
		case QSysInfo::MV_10_5 :
			operatingSystemString = "Mac OS X 10.5 Leopard";
			break;
		case QSysInfo::MV_10_6 :
			operatingSystemString = "Mac OS X 10.6 Snow Leopard";
			break;
		case QSysInfo::MV_10_7 :
			operatingSystemString = "Mac OS X 10.7 Lion";
			break;
		case QSysInfo::MV_10_8 :
			operatingSystemString = "Mac OS X 10.8 Mountain Lion";
			break;
		case QSysInfo::MV_10_9 :
			operatingSystemString = "Mac OS X 10.9 Mavericks";
			break;
		case QSysInfo::MV_Unknown :
			operatingSystemString = "An unknown and currently unsupported Mac platform";
			break;
		default :
			operatingSystemString = "Unknown Mac operating system.";
			break;
	}
#else
	//TODO: Detect Unix, Linux etc. distro as described on http://www.novell.com/coolsolutions/feature/11251.html
	operatingSystemString = "Linux";
	QProcess process;
	process.start("uname -s");
	bool result = process.waitForFinished(1000);
	QString os = process.readAllStandardOutput().trimmed();

	process.start("uname -r");
	result = process.waitForFinished(1000);
	QString rev = process.readAllStandardOutput().trimmed();

	process.start("uname -m");
	result = process.waitForFinished(1000);
	QString mach = process.readAllStandardOutput().trimmed();

	if ( os == "SunOS" ) {
		os = "Solaris";

		process.start("uname -p");
		result = process.waitForFinished(1000);
		QString arch = process.readAllStandardOutput().trimmed();

		process.start("uname -v");
		result = process.waitForFinished(1000);
		QString timestamp = process.readAllStandardOutput().trimmed();

		operatingSystemString = os + " " + rev + " (" + arch + " " + timestamp + ")";
	}
	else if ( os == "AIX" ) {
		process.start("oslevel -r");
		result = process.waitForFinished(1000);
		QString oslevel = process.readAllStandardOutput().trimmed();

		operatingSystemString = os + "oslevel " + oslevel;
	}
	else if ( os == "Linux" ) {
		QString dist;
		QString pseudoname;
		QString kernel = rev;

		if ( QFile::exists("/etc/SUSE-release") ) {
			process.start("sh -c \"cat /etc/SUSE-release | tr '\\n' ' '| sed s/VERSION.*//\"");
			result = process.waitForFinished(1000);
			dist = process.readAllStandardOutput().trimmed();

			process.start("sh -c \"cat /etc/SUSE-release | tr '\\n' ' ' | sed s/.*=\\ //\"");
			result = process.waitForFinished(1000);
			rev = process.readAllStandardOutput().trimmed();
		}
		else if ( QFile::exists("/etc/mandrake-release") ) {
			dist = "Mandrake";

			process.start("sh -c \"cat /etc/mandrake-release | sed s/.*\\(// | sed s/\\)//\"");
			result = process.waitForFinished(1000);
			pseudoname = process.readAllStandardOutput().trimmed();

			process.start("sh -c \"cat /etc/mandrake-release | sed s/.*release\\ // | sed s/\\ .*//\"");
			result = process.waitForFinished(1000);
			rev = process.readAllStandardOutput().trimmed();
		}
		else if ( QFile::exists("/etc/lsb-release") ) {
			dist = "Ubuntu";

			QString processCall = "sh -c \"cat /etc/lsb-release | grep --max-count=1 DISTRIB_RELEASE=\"";
			process.start( processCall );
			result = process.waitForFinished(1000);
			rev = process.readAllStandardOutput().trimmed();
			qDebug() << "revision:" << rev;
			if(!rev.isEmpty())
			{
				rev.remove("DISTRIB_RELEASE=");
				rev.remove("\"");
			}
			QString errorStr = process.readAllStandardError();

			process.start("sh -c \"cat /etc/lsb-release | grep --max-count=1 DISTRIB_CODENAME=\"");
			result = process.waitForFinished(1000);
			pseudoname = process.readAllStandardOutput().trimmed();
			qDebug() << "pseudoname:" << pseudoname;
			if(!pseudoname.isEmpty())
			{
				pseudoname.remove("DISTRIB_CODENAME=");
				pseudoname.remove("\"");
			}
	   }
			else if ( QFile::exists("/etc/debian_version") ) {
			dist = "Debian";

			process.start("cat /etc/debian_version");
			result = process.waitForFinished(1000);
			dist += process.readAllStandardOutput().trimmed();

			rev = "";
		}

		if ( QFile::exists("/etc/UnitedLinux-release") ) {
			process.start("sh -c \"cat /etc/UnitedLinux-release | grep --max-count=1 \"VERSION = \"\"");
			result = process.waitForFinished(1000);
			dist += process.readAllStandardOutput().trimmed();
			if(!dist.isEmpty())
			{
				dist.remove("VERSION = ");
				dist.remove("\"");
			}
		}


		if ( QFile::exists("/etc/os-release") ) { //This file makes distribution identification much easier.
			process.start("sh -c \"cat /etc/os-release | grep --max-count=1 PRETTY_NAME=\"");
			result = process.waitForFinished(1000);
			QString distname = process.readAllStandardOutput().trimmed();
			if(!distname.isEmpty())
			{
				distname.remove("PRETTY_NAME=");
				distname.remove("\"");

				dist = distname;
				pseudoname = "";
			}
		}

		operatingSystemString = os;
		if(!dist.isEmpty())
			operatingSystemString.append(" " + dist);
		if(!rev.isEmpty())
			operatingSystemString.append(" " + rev);
		operatingSystemString.append(" (");
		if(!pseudoname.isEmpty())
			operatingSystemString.append(pseudoname + " ");
		if(!kernel.isEmpty())
			operatingSystemString.append(kernel + " ");
		operatingSystemString.append(mach + ")");
	}
#endif

	return operatingSystemString;
}
void QuantitySpinBox::fixup(QString &input) const
{
    input.remove(locale().groupSeparator());
}
Example #28
0
void SelectiveInstallWidget::installBootloader(void)
{
    if(ui.bootloaderCheckbox->isChecked()) {
        qDebug() << "[SelectiveInstallWidget] installing bootloader";

        QString platform = RbSettings::value(RbSettings::Platform).toString();
        QString backupDestination = "";

        // create installer
        BootloaderInstallBase *bl =
            BootloaderInstallHelper::createBootloaderInstaller(this,
                    SystemInfo::value(SystemInfo::CurBootloaderMethod).toString());
        if(bl == NULL) {
            m_logger->addItem(tr("No install method known."), LOGERROR);
            m_logger->setFinished();
            return;
        }

        // the bootloader install class does NOT use any GUI stuff.
        // All messages are passed via signals.
        connect(bl, SIGNAL(done(bool)), m_logger, SLOT(setFinished()));
        connect(bl, SIGNAL(done(bool)), this, SLOT(continueInstall(bool)));
        connect(bl, SIGNAL(logItem(QString, int)), m_logger, SLOT(addItem(QString, int)));
        connect(bl, SIGNAL(logProgress(int, int)), m_logger, SLOT(setProgress(int, int)));

        // set bootloader filename. Do this now as installed() needs it.
        QStringList blfile = SystemInfo::value(SystemInfo::CurBootloaderFile).toStringList();
        QStringList blfilepath;
        for(int a = 0; a < blfile.size(); a++) {
            blfilepath.append(RbSettings::value(RbSettings::Mountpoint).toString()
                    + blfile.at(a));
        }
        bl->setBlFile(blfilepath);
        QUrl url(SystemInfo::value(SystemInfo::BootloaderUrl).toString()
                + SystemInfo::value(SystemInfo::CurBootloaderName).toString());
        bl->setBlUrl(url);
        bl->setLogfile(RbSettings::value(RbSettings::Mountpoint).toString()
                + "/.rockbox/rbutil.log");

        if(bl->installed() == BootloaderInstallBase::BootloaderRockbox) {
            if(QMessageBox::question(this, tr("Bootloader detected"),
                        tr("Bootloader already installed. Do you want to reinstall the bootloader?"),
                        QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) {
                // keep m_logger open for auto installs.
                // don't consider abort as error in auto-mode.
                m_logger->addItem(tr("Bootloader installation skipped"), LOGINFO);
                delete bl;
                emit installSkipped(true);
                return;
            }
        }
        else if(bl->installed() == BootloaderInstallBase::BootloaderOther
                && bl->capabilities() & BootloaderInstallBase::Backup)
        {
            QString targetFolder = SystemInfo::value(SystemInfo::CurPlatformName).toString()
                + " Firmware Backup";
            // remove invalid character(s)
            targetFolder.remove(QRegExp("[:/]"));
            if(QMessageBox::question(this, tr("Create Bootloader backup"),
                        tr("You can create a backup of the original bootloader "
                            "file. Press \"Yes\" to select an output folder on your "
                            "computer to save the file to. The file will get placed "
                            "in a new folder \"%1\" created below the selected folder.\n"
                            "Press \"No\" to skip this step.").arg(targetFolder),
                        QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
                backupDestination = QFileDialog::getExistingDirectory(this,
                        tr("Browse backup folder"), QDir::homePath());
                if(!backupDestination.isEmpty())
                    backupDestination += "/" + targetFolder;

                qDebug() << "[RbUtil] backing up to" << backupDestination;
                // backup needs to be done after the m_logger has been set up.
            }
        }

        if(bl->capabilities() & BootloaderInstallBase::NeedsOf)
        {
            int ret;
            ret = QMessageBox::information(this, tr("Prerequisites"),
                    bl->ofHint(),QMessageBox::Ok | QMessageBox::Abort);
            if(ret != QMessageBox::Ok) {
                // consider aborting an error to close window / abort automatic
                // installation.
                m_logger->addItem(tr("Bootloader installation aborted"), LOGINFO);
                m_logger->setFinished();
                emit installSkipped(true);
                return;
            }
            // open dialog to browse to of file
            QString offile;
            QString filter
                = SystemInfo::value(SystemInfo::CurBootloaderFilter).toString();
            if(!filter.isEmpty()) {
                filter = tr("Bootloader files (%1)").arg(filter) + ";;";
            }
            filter += tr("All files (*)");
            offile = QFileDialog::getOpenFileName(this,
                    tr("Select firmware file"), QDir::homePath(), filter);
            if(!QFileInfo(offile).isReadable()) {
                m_logger->addItem(tr("Error opening firmware file"), LOGERROR);
                m_logger->setFinished();
                emit installSkipped(true);
                return;
            }
            if(!bl->setOfFile(offile, blfile)) {
                m_logger->addItem(tr("Error reading firmware file"), LOGERROR);
                m_logger->setFinished();
                emit installSkipped(true);
                return;
            }
        }

        // start install.
        if(!backupDestination.isEmpty()) {
            if(!bl->backup(backupDestination)) {
                if(QMessageBox::warning(this, tr("Backup error"),
                            tr("Could not create backup file. Continue?"),
                            QMessageBox::No | QMessageBox::Yes)
                        == QMessageBox::No) {
                    m_logger->setFinished();
                    return;
                }
            }
        }
        bl->install();

    }
Example #29
0
QString CardInfo::getCorrectedName() const
{
    QString result = name;
    // Fire // Ice, Circle of Protection: Red, "Ach! Hans, Run!", Who/What/When/Where/Why, Question Elemental?
    return result.remove(" // ").remove(':').remove('"').remove('?').replace('/', ' ');
}
Example #30
0
int main(int argc, char *argv[])
{
  Q_INIT_RESOURCE(resource_omedit);
  // read the second argument if specified by user.
  QString fileName = QString();
  // adding style sheet
  argc++;
  argv[(argc - 1)] = "-stylesheet=:/Resources/css/stylesheet.qss";

  QApplication a(argc, argv);
  QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
  QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
  QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
  a.setAttribute(Qt::AA_DontShowIconsInMenus, false);
  // Localization
  //*a.severin/ add localization
  const char *omhome = getenv("OPENMODELICAHOME");
#ifdef WIN32
  if (!omhome) {
    QMessageBox::critical(0, QString(Helper::applicationName).append(" - ").append(Helper::error),
                          GUIMessages::getMessage(GUIMessages::OPENMODELICAHOME_NOT_FOUND), Helper::ok);
    a.quit();
    exit(1);
  }
#else /* unix */
  omhome = omhome ? omhome : CONFIG_DEFAULT_OPENMODELICAHOME;
#endif
  QSettings settings(QSettings::IniFormat, QSettings::UserScope, "openmodelica", "omedit");
  QString language = settings.value("language").toString();
  QString translationDirectory = omhome + QString("/share/omedit/nls");
  QString locale = language.isEmpty() ? QLocale::system().name() : language;
  // install Qt's default translations
  QTranslator qtTranslator;
#ifdef Q_OS_WIN
  qtTranslator.load("qt_" + locale, translationDirectory);
#else
  qtTranslator.load("qt_" + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
#endif
  a.installTranslator(&qtTranslator);
  // install application translations
  QTranslator translator;
  translator.load("OMEdit_" + locale, translationDirectory);
  a.installTranslator(&translator);
  // Splash Screen
  QPixmap pixmap(":/Resources/icons/omeditor_splash.png");
  SplashScreen splashScreen(pixmap);
  splashScreen.setMessage();
  splashScreen.show();
  Helper::initHelperVariables();
  // MainWindow Initialization
  MainWindow mainwindow(&splashScreen);
  if (mainwindow.mExitApplication) {        // if there is some issue in running the application.
    a.quit();
    exit(1);
  }
  bool OMCLogger = false;
  // if user has requested to open the file by passing it in argument then,
  if (a.arguments().size() > 1)
  {
    for (int i = 1; i < a.arguments().size(); i++)
    {
      if (strncmp(a.arguments().at(i).toStdString().c_str(), "--OMCLogger=",12) == 0) {
        QString omcLoggerArg = a.arguments().at(i);
        omcLoggerArg.remove("--OMCLogger=");
        if (0 == strcmp("true", omcLoggerArg.toStdString().c_str()))
          OMCLogger = true;
        else if (0 == strcmp("false", omcLoggerArg.toStdString().c_str()))
          OMCLogger = false;
      }
      fileName = a.arguments().at(i);
      if (!fileName.isEmpty())
      {
        // if path is relative make it absolute
        QFileInfo file (fileName);
        if (file.isRelative())
        {
          fileName.prepend(QString(QDir::currentPath()).append("/"));
        }
        mainwindow.mpProjectTabs->openFile(fileName);
      }
    }
  }
  // hide OMCLogger send custom expression feature if OMCLogger is false
  mainwindow.mpOMCProxy->enableCustomExpression(OMCLogger);
  // finally show the main window
  mainwindow.show();
  // hide the splash screen
  splashScreen.finish(&mainwindow);
  return a.exec();
}