예제 #1
0
bool CameraOutV4L2::sudo(const QString &command,
                         const QStringList &argumments,
                         const QString &password) const
{
    if (password.isEmpty())
        return false;

    QProcess echo;
    QProcess su;

    echo.setStandardOutputProcess(&su);

    switch (this->m_rootMethod) {
        case RootMethodSu: {
            QStringList args;

            for (QString arg: argumments)
                args << arg.replace(" ", "\\ ");

            echo.start("echo", {password});
            su.start("su", {"-c", command + " " + args.join(" ")});

            break;
        }
        case RootMethodSudo: {
            echo.start("echo", {password});
            su.start("sudo", QStringList{"-S", command} << argumments);

            break;
        }
    }

    su.setProcessChannelMode(QProcess::ForwardedChannels);
    echo.waitForStarted();

    if (!su.waitForFinished(this->m_passwordTimeout)) {
        su.kill();
        echo.waitForFinished();

        return false;
    }

    echo.waitForFinished();

    if (su.exitCode()) {
        QByteArray outMsg = su.readAllStandardOutput();

        if (!outMsg.isEmpty())
            qDebug() << outMsg.toStdString().c_str();

        QByteArray errorMsg = su.readAllStandardError();

        if (!errorMsg.isEmpty())
            qDebug() << errorMsg.toStdString().c_str();

        return false;
    }

    return true;
}
예제 #2
0
void ConnectionThread::run()
{
    if(stepByStep)
        sendNextCommand = false;
    else
        sendNextCommand = true;

    QSerialPort serial;
    serial.setPortName(portName);
    if (!serial.open(QIODevice::ReadWrite))
    {
        emit error(tr("Can't open %1, error code %2").arg(portName).arg(serial.error()));
        return;
    }

    while (!quit) {
        if(stepByStep)
        {
            while(!sendNextCommand);
            mutex.lock();
            sendNextCommand = false;
            mutex.unlock();
        }
        // Envoi microcommande
        serial.write(test->recupProchaineMicrocommande().c_str());
        if(!serial.waitForBytesWritten(waitTimeout))
        {
            emit timeout(tr("Wait write microcommande timeout %1").arg(QTime::currentTime().toString()));
        }
        //Accusé de reception
        if(serial.waitForReadyRead(waitTimeout))
        {
            QByteArray received = serial.readAll();
            if(received.toStdString().compare(COMMANDE_RECEIVED) != 0)
            {
                emit error("Not wanted response");
            }
        }
        else
        {
            emit timeout(tr("Wait read response timeout %1").arg(QTime::currentTime().toString()));
        }
        //Pret a recevoir prochaine commande
        if(serial.waitForReadyRead(waitTimeout))
        {
            QByteArray received = serial.readAll();
            if(received.toStdString().compare(READY_FOR_NEXT_COMMAND) != 0)
            {
                emit error("Not wanted response");
            }
        }
        else
        {
            emit timeout(tr("Wait read response timeout %1").arg(QTime::currentTime().toString()));
        }
    }
}
예제 #3
0
void TcpClient::slotReadyRead()
{
    while(m_pTcpSocket->bytesAvailable())
    {
        if (m_pTcpSocket->bytesAvailable() > headerMsgSize) {

            QByteArray buffer = m_pTcpSocket->read(headerMsgSize);
            QByteArray newarray;

            for (int i = 0; i < buffer.size(); i++) {
                if (buffer.at(i) == '\0')
                    continue;

                newarray.append(buffer.at(i));
            }

            int msgSize = QString(newarray.toStdString().c_str()).toInt();
            buffer.clear();
            newarray.clear();

            buffer = m_pTcpSocket->read(msgSize);
            while(buffer.size() < msgSize - headerMsgSize)
            {
                m_pTcpSocket->waitForReadyRead(3000);
                buffer.append(m_pTcpSocket->read(msgSize - buffer.size()));
            }

            for (int i = 0; i < buffer.size(); i++) {
                newarray.append(buffer.at(i));
            }

            if (msgSize != (newarray.length() + headerMsgSize)) {
                emit fileLoadingError("Данные были повреждены при скачивании. Попробуйте повторить процедуру сначала.");
                emit startFileDownloading();
                return;
            }

            QString fullMsg(newarray.toStdString().c_str());
            if (fullMsg.contains(newfileMsg) && fullMsg.contains(newentryMsg)) {
                processFileSaving(newarray);
            } else {
                processFileList(fullMsg);
            }
        } else {
            emit fileLoadingError("Сервер не содержит запрашиваемых файлов. Обратитесь за помощью скачивания файлов к преподавателю.");
            return;
        }
    }
}
예제 #4
0
ffmpegFileInfo Ffmpeg::getInfo() {
  QString ffmpegCachePath = getFfmpegCache().getQString();
  QString tempPath = ffmpegCachePath + "//" + cleanPathSymbols() + ".txt";
  if (QFile::exists(tempPath)) {
    QFile infoText(tempPath);
    infoText.open(QIODevice::ReadOnly);
    QByteArray ba = infoText.readAll();
    infoText.close();
    QString text = QString::fromStdString(ba.toStdString());
    m_lx         = text.split(" ")[0].toInt();
    m_ly         = text.split(" ")[1].toInt();
    m_frameRate  = text.split(" ")[2].toDouble();
    m_frameCount = text.split(" ")[3].toInt();
  } else {
    QFile infoText(tempPath);
    getSize();
    getFrameRate();
    getFrameCount();
    infoText.open(QIODevice::WriteOnly);
    std::string infoToWrite =
        std::to_string(m_lx) + " " + std::to_string(m_ly) + " " +
        std::to_string(m_frameRate) + " " + std::to_string(m_frameCount);
    int infoLength = infoToWrite.length();
    infoText.write(infoToWrite.c_str(), infoLength);
    infoText.close();
  }
  ffmpegFileInfo info;
  info.m_lx         = m_lx;
  info.m_ly         = m_ly;
  info.m_frameRate  = m_frameRate;
  info.m_frameCount = m_frameCount;
  return info;
}
예제 #5
0
// open by connecting and getting a basic list of folders available
bool
PolarFlow::open(QStringList &errors)
{
    printd("PolarFlow::open\n");

    // do we have a token
    QString token = getSetting(GC_POLARFLOW_TOKEN, "").toString();
    if (token == "") {
        errors << "You must authorise with PolarFlow first";
        return false;
    }

    // use the configed URL
    QString url = QString("%1/rest/users/delegates/users")
          .arg(getSetting(GC_POLARFLOW_URL, "https://whats.todaysplan.com.au").toString());

    printd("URL used: %s\n", url.toStdString().c_str());

    // request using the bearer token
    QNetworkRequest request(url);
    request.setRawHeader("Authorization", (QString("Bearer %1").arg(token)).toLatin1());

    QNetworkReply *reply = nam->get(request);

    // blocking request
    QEventLoop loop;
    connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    loop.exec();

    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "error" << reply->errorString();
        errors << tr("Network Problem reading PolarFlow data");
        return false;
    }
    // did we get a good response ?
    QByteArray r = reply->readAll();
    printd("response: %s\n", r.toStdString().c_str());

    QJsonParseError parseError;
    QJsonDocument document = QJsonDocument::fromJson(r, &parseError);

    // if path was returned all is good, lets set root
    if (parseError.error == QJsonParseError::NoError) {
        printd("NoError");

        // we have a root
        root_ = newCloudServiceEntry();

        // path name
        root_->name = "/";
        root_->isDir = true;
        root_->size = 0;
    } else {
        errors << tr("problem parsing PolarFlow data");
    }

    // ok so far ?
    if (errors.count()) return false;
    return true;
}
QByteArray Encryptor::encryptAsymmetricly(QByteArray &publicKey, QByteArray &data)
{
    Botan::DataSource_Memory key_pub(publicKey.toStdString());
    auto publicRsaKey = Botan::X509::load_key(key_pub);

    const uint DATA_SIZE = data.size();
    Botan::byte msgtoencrypt[DATA_SIZE];

    for (uint i = 0; i < DATA_SIZE; i++)
    {
        msgtoencrypt[i] = data[i];
    }

    Botan::PK_Encryptor_EME encryptor(*publicRsaKey, "EME1(SHA-256)");
    Botan::AutoSeeded_RNG rng;
    std::vector<Botan::byte> ciphertext = encryptor.encrypt(msgtoencrypt, DATA_SIZE, rng);

    QByteArray keyCipherData;
    keyCipherData.resize(ciphertext.size());

    for ( uint i = 0; i < ciphertext.size(); i++ ) {
        keyCipherData[i] = ciphertext.at(i);
    }

    return keyCipherData;
}
예제 #7
0
std::string BuyoutManager::Serialize(const QMap<QString, Buyout> &buyouts) {
    QJsonDocument doc;
    QJsonObject root;
    for (QString hash : buyouts.uniqueKeys()) {
        Buyout buyout = buyouts.value(hash);
        if (buyout.type != BUYOUT_TYPE_NO_PRICE && (buyout.currency == CURRENCY_NONE || buyout.type == BUYOUT_TYPE_NONE))
            continue;
        if (buyout.type >= BuyoutTypeAsTag.size() || buyout.currency >= CurrencyAsTag.size()) {
            QLOG_WARN() << "Ignoring invalid buyout, type:" << buyout.type
                << "currency:" << buyout.currency;
            continue;
        }
        QJsonObject value;
        value.insert("value", buyout.value);
        value.insert("set_by", buyout.set_by);

        if (!buyout.last_update.isNull()){
            value.insert("last_update", (int) buyout.last_update.toTime_t());
        } else {
            // If last_update is null, set as the actual time
            value.insert("last_update", (int) QDateTime::currentDateTime().toTime_t());
        }

        value.insert("type", QString::fromStdString(BuyoutTypeAsTag[buyout.type]));
        value.insert("currency", QString::fromStdString(CurrencyAsTag[buyout.currency]));

        root.insert(hash, value);
    }
    doc.setObject(root);
    QByteArray result = doc.toJson();
    return result.toStdString();
}
예제 #8
0
void elFlowPort::decodeMsg( const QByteArray& msg )
{
    elFlowAnswer answer = _protocol.interpretAnswer( msg.toStdString() );

    if( answer.type == elFlowAnswerType::elFlowError )
    {
        emit portError( "Invalid answer!" );
    }
    else if( answer.type == elFlowAnswerType::protocolError )
    {
        emit portError( "Protocol error!" );
    }
    else if( answer.type == elFlowAnswerType::elFlowStatus )
    {
        if( answer.text.find( "no error" ) == std::string::npos )
        {
            emit portError( QString::fromStdString( answer.text ) );
        }
    }
    else if( answer.type == elFlowAnswerType::elFlowValue )
    {
        showParameter( answer.paramNum, answer.value, answer.text );
    }
    else
    {
        emit portError( "Warning: unhandled answer type!" );
    }
}
예제 #9
0
void MainWindow::on_finished(QNetworkReply* reply)
{
    //qDebug("MainWindow::on_finished");

    QByteArray data = reply->readAll();

    std::string replyContent = data.toStdString();
    qDebug("MainWindow::on_finished reply: %s", replyContent.c_str());

    QJsonDocument doc = QJsonDocument::fromJson(data);
    QJsonObject json = doc.object();

    QString replyType = json["type"].toString();
    qDebug("MainWindow::on_finished type = %s", replyType.toStdString().c_str());

    if (replyType == "messageCount")
    {
        unsigned int currentMessagesCount = json["count"].toInt();
        qDebug("MainWindow::on_finished count: %d", currentMessagesCount);
        if (currentMessagesCount > m_messagesReceived)
        {
            m_getLastMessages(currentMessagesCount - m_messagesReceived);
        }
    }
    else if (replyType == "getLastMessages")
    {
        qDebug("on_finished type: %d", json["messages"].type());

        QJsonArray messages = json["messages"].toArray();
        m_updateMessages(messages);
    }


}
예제 #10
0
void YunClient::startRequest(QByteArray url)
{
#ifndef QREQUEST
    qDebug() << " request url : " << url;
    std::string std_url = url.toStdString(); // "http://121.40.218.177:8080/ml/rs/mediaReleaseVersions/1/10/null/null/90001";
    std::string readData;
    CurlUpload *curl = new CurlUpload();
    QString data = curl->getRequest(std_url, readData);
    delete curl;
    QJsonObject dataJson = getRequestData(QString(data));
    QJsonArray listJson = setPagingInfo(dataJson);
    setVersionList(listJson);
#else
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    manager = new QNetworkAccessManager(this);
    //发送GET请求
    reply = manager->get(request);
    //连接请求结束信号
    disconnect(reply);
    connect(reply, &QNetworkReply::finished,
            this, &YunClient::replyFinished);
    连接响应时返回数据信号
    connect(reply, &QNetworkReply::readyRead, this, &YunClient::readyRead);

    请求更新进度
    connect(reply, &QNetworkReply::downloadProgress,
            this,  &YunClient::updateDataReadProgress);
#endif
}
예제 #11
0
void Core::removeComa(QFile &file){


    QFile outfile(QString("/home/ethel/qwt-5.2/test-ethel/wireshark/resultats/report2.csv"));

    if (!outfile.open(QIODevice::ReadWrite | QIODevice::Text))
    {
        qDebug() << "Unable to open file";
        return;
    }

    if (!_reportFile.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Append))
    {
        qDebug() << "Unable to open file";
        return;
    }


    _reportFile.seek(0);
    while (!_reportFile.atEnd())
    {
        QByteArray line = _reportFile.readLine();

        std::string s=line.toStdString();
        std::replace( s.begin(), s.end(), '.', ',');
        QTextStream stream(&outfile);
        stream << QString::fromStdString(s);
    }

    file.close();

}
void CascadeClassifierNavigationPlayer::onEnter()
{
    if (m_classifier) {
        return;
    }

    QFile f(":/assets/lbpcascade_animeface.xml");
    if (!f.open(QIODevice::ReadOnly)) {
        qWarning("Fail to load cascade classifier");
        return;
    }

    QByteArray content = f.readAll();
    cv::FileStorage cvFile(content.toStdString(), cv::FileStorage::READ | cv::FileStorage::MEMORY);
    if (!cvFile.isOpened()) {
        qWarning("Fail to load cascade classifier as cv::FileStorage");
        return;
    }

    cv::CascadeClassifier *classifier = new cv::CascadeClassifier();
    if (!classifier->read(cvFile.getFirstTopLevelNode())) {
        qWarning("Fail to decode cascade classifer");
        delete classifier;
        return;
    }

    m_classifier = classifier;
}
예제 #13
0
void APIConnectionHandler::handleSetCommand(QLocalSocket *sock)
{
    odb::database *db = DB::getDB();
    Application connectedApp = getConnectedApp(sock);

    sock->waitForReadyRead();
    QByteArray username = sock->readLine().trimmed();

    sock->waitForReadyRead();
    string encryptedPassword = enc->encrypt(sock->readLine().trimmed().toStdString());

    bool allow = startMessageViewerAndGetResult("an application want's to set a password, allow or reject?");

    if ( allow )
    {
        vector<unsigned char> dbEncryptedPassword (encryptedPassword.begin(), encryptedPassword.end());

        ApplicationPassword appPass(&connectedApp, username.toStdString(), dbEncryptedPassword);

        int passwordId = db->persist(appPass);

        sock->write(QVariant(passwordId).toByteArray());
    } else {
        sock->write("-1");
    }

    sock->write("\n");
    sock->close();
}
예제 #14
0
std::string TripletStore :: toRdf() const
{
  QByteArray byteArray;
  QXmlStreamWriter xml(&byteArray);
  xml.setAutoFormatting(true);
  xml.writeStartDocument();
  xml.writeStartElement("rdf:RDF");
  xml.writeAttribute("xmlns:rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
  xml.writeAttribute("xmlns:soft", "http://www.sintef.no/rdf#");
  for (auto key: d->triplets.uniqueKeys()) {
    auto i = d->triplets.find(key);
    bool first = true;
    while (i != d->triplets.cend() && i.key() == key) {
      if (!i.value().first.startsWith("^")) {
  if (first) {
      xml.writeStartElement("rdf:Description");
      xml.writeAttribute("xmlns:about", key);
      first = !first;
  }
  xml.writeTextElement(i.value().first, i.value().second);
      }
      ++i;
    }
    if (!first)
      xml.writeEndElement();

  }
  xml.writeEndElement();
  xml.writeEndDocument();
  return byteArray.toStdString();
}
예제 #15
0
파일: motor.cpp 프로젝트: g7uvw/QtMonument
double Motor::GetPosition()
{
    stringstream cmd;
    QByteArray line;
    cmd.str("");
    cmd.clear();

    if (!TX_LOCKOUT)
    {
        //qDebug() << "Get Position";

        TALK_TO_MOTOR(cmd);
        cmd << "?96" << CRLF;
        line =  SendCommand(cmd);
        //qDebug() << line;
        line.clear();
        cmd.str("");
        cmd.clear();
        cmd << CRLF;
        line =  SendCommand(cmd);
        if (!line.isEmpty())
        {
            if (line.at(0) == 'P')
            {
                //qDebug()<< "I'll have a P please Bob";
                QByteArray tmp = line.mid(5);  // chomp the first 5 characters to leave just the number
                //qDebug() <<"Chomped first 5 chars " << tmp;
                std::string position = tmp.toStdString();
                int tpos = atoi (position.c_str());
                //qDebug()<< "converted to longs"  <<tpos;
                double pos = (m_circumference * tpos) / 50000;
                //qDebug()<<"converted to actual position" << pos;
                STOP_TALKING_TO_MOTOR(cmd);
                return pos;
            }

            else
            {
                STOP_TALKING_TO_MOTOR(cmd);
                return -1;
            }

        }

        else
        {
            STOP_TALKING_TO_MOTOR(cmd);
            return -1;
        }
    }
    else
    {
        STOP_TALKING_TO_MOTOR(cmd);
        return -1;
    }

}
예제 #16
0
bool SpellCheck::spell(const QString word)
{
    if(spellChecker == nullptr)
        return true;
    QByteArray w;
    if(codec != nullptr)
        w = codec->fromUnicode(word);
    else
        w = word.toLocal8Bit();
    return spellChecker->spell(w.toStdString());
}
예제 #17
0
파일: password.cpp 프로젝트: CMon/recipes
bool Password::checkPassword(const QString & password, const QByteArray & originalHash, const QString & usedCrypto)
{
	if (usedCrypto == "bcrypt") {
#ifdef WITH_BOTAN
		return Botan::check_bcrypt(password.toStdString(), originalHash.toStdString());
#else
		qCritical() << "The password was hashed with bcrypt, but this library was build without botan support, can not verify password";
		return false;
#endif
	}

	const QByteArray hash = QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Keccak_512).toHex();
	return  originalHash == hash;
}
예제 #18
0
/*!
  return all triples as a CSV formatted string
 */
std::string TripletStore :: toCSV() const
{
  QByteArray byteArray;
  QTextStream stream(&byteArray, QIODevice::WriteOnly);
  for (auto key: d->triplets.uniqueKeys()) {
    auto i = d->triplets.find(key);
    while (i != d->triplets.cend() && i.key() == key) {
      if (!i.value().first.startsWith("^")) {
        stream << key << "," << i.value().first << "," << i.value().second << endl;
      }
      ++i;
    }
  }
  return byteArray.toStdString();
}
예제 #19
0
void TcpClient::processFileSaving(const QByteArray &fullMsg)
{
    QString msgStr(fullMsg.toStdString().c_str());

    int nameindx = msgStr.indexOf(newfileMsg);
    int entryindx = msgStr.indexOf(newentryMsg);

    QString filename = msgStr.mid(nameindx + newfileMsg.length(), entryindx - (nameindx + newfileMsg.length()));
    QFile file(QDir::currentPath() + QDir::separator() + filename);

    if (file.open(QIODevice::WriteOnly)) {
        QByteArray filedata = fullMsg.right(fullMsg.length() - (entryindx + newentryMsg.length()));
        file.write(filedata); //Stream work incorrectly in this case
        file.close();
        emit sendDownloadedFilePath(QDir::currentPath());
    }

    emit startFileDownloading();
}
QSharedPointer<WebSocketMessage> ProtobufWebSocketMessageFactory::createResponse(quint64 requestId,
                                                                                 quint32 status,
                                                                                 const QString &message,
                                                                                 const QByteArray &body)
{
    textsecure::WebSocketResponseMessage *tsResponseMessage = new textsecure::WebSocketResponseMessage;
    tsResponseMessage->set_id(requestId);
    tsResponseMessage->set_status(status);
    tsResponseMessage->set_message(message.toStdString());

    if (!body.isEmpty()) {
        tsResponseMessage->set_body(body.toStdString());
    }

    textsecure::WebSocketMessage *tsMessage = new textsecure::WebSocketMessage;
    tsMessage->set_type(textsecure::WebSocketMessage_Type_RESPONSE);
    tsMessage->set_allocated_response(tsResponseMessage);

    return QSharedPointer<WebSocketMessage>(new ProtoBufWebSocketMessage(tsMessage));
}
예제 #21
0
void            GUI::Registration::replyFinished(QNetworkReply *reply) {
    std::cout << "request registration ok" << std::endl;
    QByteArray bytes = reply->readAll();
    QJsonDocument doc(QJsonDocument::fromJson(bytes));
    QJsonObject json = doc.object();
    int status = json["status"].toObject().value("code").toInt();
    if (status == 200) {
        ui->warningText->setText("Account created !");
        ui->warningText->setStyleSheet("color: green; 	font: 9pt \"MS Shell Dlg 2\";font-weight: bold;");
    } else {
        std::cout << bytes.toStdString() << std::endl;
        QString message = json["status"].toObject().value("message").toString();
        ui->warningText->setText(message);
        ui->warningText->setStyleSheet("color : red; 	font: 9pt \"MS Shell Dlg 2\";font-weight: bold;");
    }
    if (_background != NULL) {
        _background->stop();
        delete _background;
        _background = NULL;
    }
}
예제 #22
0
void YunClient::requestVersionInfo(const int &row)
{
    QStringList rowValue = rowList.at(row);
    QString verId = rowValue.at(1);
    QString verName = rowValue.at(2);
    qDebug() << "version id :" << verId << "version name : " << verName;
    if(!verId.toInt()){
        qDebug() << "version id error!";
        return;
    }

    request_type = get_media_list;
    QByteArray url =  host.toLatin1() + "/ml/rs/mediaReleaseVersions/" + verId.toLatin1();

#ifndef QREQUEST
    std::string std_url = url.toStdString();
    std::string readData;
    CurlUpload *curl = new CurlUpload();
    QString data = curl->getRequest(std_url, readData);
#else
    startRequest(url);
#endif

    bool isUpdate = false;
    if (rowValue.last().compare("已更新") == 0)
        isUpdate = true;

    dialog = new YunDM();
    dialog->initSqlAndVersion(_sql, verId, verName, isUpdate);
    connect(this, &YunClient::sqlValue, dialog, &YunDM::setSqlValue);

#ifndef QREQUEST
    QJsonObject dataJson = getRequestData(data);
    setUpdateList(dataJson);
#else

#endif
    dialog->exec();
    getUpdateVersionList();
}
예제 #23
0
void Modification::Init(void){
	QDir basedir;
	basedir.setPath(Settings::JKFolder + "base/");
	QStringList modlist = basedir.entryList(QDir::Filter::Readable, QDir::SortFlag::Name);
	if (modlist.size() < 4){
		/* ERROR*/
	}/*assets0-3.pk3*/
	Q_FOREACH(QString name, modlist){
		if (name.contains(QRegExp("assets[0-4].pk3"))) continue;
		name.chop(3); //purge extension
		QFile *file = new QFile(Settings::JKFolder + "base" + name + ".json");
		QByteArray data = file->readAll();

		cJSON *root = cJSON_Parse(data.toStdString().c_str()), *temp;
		if (!root) continue; /* WARNING*/

		temp = cJSON_GetObjectItem(root, "id");
		Modification *mod = new Modification(cJSON_ToInteger(temp));

		temp = cJSON_GetObjectItem(root, "author");
		mod->author = cJSON_ToString(temp);

		temp = cJSON_GetObjectItem(root, "description");
		mod->description = cJSON_ToString(temp);

		temp = cJSON_GetObjectItem(root, "notcompatiblewith");
		QStringList list = QString(cJSON_ToString(temp)).split(QChar(','));
		Q_FOREACH(QString num, list){
			mod->notcompatiblewith.push_back(num.toInt());
		}

		temp = cJSON_GetObjectItem(root, "name");
		mod->name = cJSON_ToString(temp);

		temp = cJSON_GetObjectItem(root, "version");
		mod->version = cJSON_ToInteger(temp);

		cJSON_Delete(root);
		delete file;
	}
예제 #24
0
파일: main.cpp 프로젝트: t686/DSProject
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg){
	QByteArray localMsg = msg.toLocal8Bit();
	switch (type) {
	case QtDebugMsg:
		fprintf(stderr, "\n***\nDebug: %s (%s:%u, %s)\n***\n", localMsg.constData(), context.file, context.line, context.function);
		break;
	case QtInfoMsg:
		fprintf(stderr, "\n***\nInfo: %s (%s:%u, %s)\n***\n", localMsg.constData(), context.file, context.line, context.function);
		break;
	case QtWarningMsg:
		fprintf(stderr, "\n***\nWarning: %s (%s:%u, %s)\n***\n", localMsg.constData(), context.file, context.line, context.function);
		break;
	case QtCriticalMsg:
		//Filter out multiple protocol start... its a library bug
		if (!QString::fromStdString(localMsg.toStdString()).contains("Multiple proto"))
			fprintf(stderr, "\n***\nCritical: %s (%s:%u, %s)\n***\n", localMsg.constData(), context.file, context.line, context.function);
		break;
	case QtFatalMsg:
		fprintf(stderr, "\n***\nFatal: %s (%s:%u, %s)\n***\n", localMsg.constData(), context.file, context.line, context.function);
		abort();
	}
}
예제 #25
0
void CBilateralFilterSet::OnOpenImg()
{


	//QString path = QFileDialog::getOpenFileName(this, QStringLiteral("打开图片"), ".", QStringLiteral("Image Files(*.jpg *.png *.bmp)"));

 	QFileDialog openImg(this);
	openImg.setWindowTitle(QStringLiteral("打开图片"));
	openImg.setNameFilter(QStringLiteral("Image Files(*.jpg *.png *.bmp)"));
	if (openImg.exec() == Accepted)
	{
		QString path = openImg.selectedFiles()[0];
		QByteArray byteArray = path.toLocal8Bit();
		string strPath =  byteArray.toStdString();

		m_imgProcessed = imread(strPath.c_str(), IMREAD_UNCHANGED);
		//QImage qImg(path);
		
		BilateralFilterParamChanged(); //打开图片时需要进行一次滤波操作
		
	}

}
QSharedPointer<WebSocketMessage> ProtobufWebSocketMessageFactory::createRequest(quint64 requestId,
                                                                                const QString &verb,
                                                                                const QString &path,
                                                                                const QByteArray &body)
{
    textsecure::WebSocketRequestMessage *tsRequestMessage = new textsecure::WebSocketRequestMessage;
    tsRequestMessage->set_verb(verb.toStdString());
    tsRequestMessage->set_path(path.toStdString());

    if (requestId != 0) {
        tsRequestMessage->set_id(requestId);
    }

    if (!body.isEmpty()) {
        tsRequestMessage->set_body(body.toStdString());
    }

    textsecure::WebSocketMessage *tsMessage = new textsecure::WebSocketMessage;
    tsMessage->set_type(textsecure::WebSocketMessage_Type_REQUEST);
    tsMessage->set_allocated_request(tsRequestMessage);

    return QSharedPointer<WebSocketMessage>(new ProtoBufWebSocketMessage(tsMessage));
}
예제 #27
0
ShopSubmission* ShopSubmitter::ExtractResponse(QNetworkReply *reply) {
    QString threadId = reply->request().attribute((QNetworkRequest::Attribute) SHOP_DATA_THREAD).toString();
    QString error;
    ShopSubmission* submission = 0;

    if (threadId.isEmpty()) {
        error = "An empty shop was submitted.";
    }
    else {
        submission = submissions.value(threadId);

        if (reply->error() != QNetworkReply::NoError) {
            error = "A network error occurred: " + reply->errorString();
            if (reply->error() == QNetworkReply::OperationCanceledError) {
                error = "Timed out while submitting to the server.";
            }
        }
        else {
            QByteArray bytes = reply->readAll();
            switch (submission->state) {
            case SHOP_SUBMISSION_STARTED: {
                std::string hash = Util::GetCsrfToken(bytes.toStdString(), "forum_thread");
                if (hash.empty()) {
                    error = "Could not extract CSRF token.";
                    break;
                }

                std::string title = Util::FindTextBetween(bytes.toStdString(),
                                                          "<input type=\"text\" name=\"title\" id=\"title\" value=\"", "\" class=\"textInput\">");
                if (title.empty()) {
                    error = "Could not extract title from forum thread.";
                    break;
                }

                submission->data.insert("forum_thread", QString::fromStdString(hash));
                submission->data.insert("forum_title", QString::fromStdString(title));
            } break;
            case SHOP_SUBMISSION_BUMP_STARTED: {
                std::string hash = Util::GetCsrfToken(bytes.toStdString(), "forum_post");
                if (hash.empty()) {
                    error = "Could not extract CSRF token.";
                    break;
                }
                submission->data.insert("forum_post", QString::fromStdString(hash));
            } break;
            case SHOP_SUBMISSION_BUMPING:
            case SHOP_SUBMISSION_SUBMITTING: {
                std::string forumError = Util::FindTextBetween(bytes.toStdString(), "<ul class=\"errors\"><li>", "</li></ul>");
                if (!forumError.empty()) {
                    error = "The forum responded with an error: " + QString::fromStdString(forumError);
                    break;
                }
            } break;
            case SHOP_SUBMISSION_IDLE:
            case SHOP_SUBMISSION_FINISHED:
            default:
                error = "Internal error";
            }
        }

        if (submission->timerId != -1) {
            killTimer(submission->timerId);
            submission->timerId = -1;
        }
    }

    reply->disconnect();
    reply->deleteLater();

    if (!error.isEmpty()) {
        if (submission) RemoveSubmission(submission);
        emit ShopSubmissionError(threadId, error);
        return 0;
    }
    return submission;
}
bool LyricJson::loadLRC(const QString& path, const QString& musicPath)
{
	QFile infile(path);
	if (!infile.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		return false;
	}

	_song.Clear();
	auto settings = Settings::getInstance();
	_song.general.maxline = 2;	// always 2 ?

	while (!infile.atEnd())
	{
		QByteArray lineByte = infile.readLine();
		QString line = QString::fromStdString(lineByte.toStdString()).trimmed();
		if (!line.startsWith("["))
		{
			continue;
		}
		if (!line.contains("]"))
		{
			continue;
		}
		int indexOfClose = line.indexOf("]");
		QString controlPart = line.mid(1, indexOfClose - 1).trimmed();
		if (controlPart.startsWith("ti:"))
		{
			_song.info.title = controlPart.right(controlPart.length() - 3); // no trim
		}
		else if (controlPart.startsWith("au:"))
		{
			_song.info.author = controlPart.right(controlPart.length() - 3); // no trim
		}
		else if (controlPart.startsWith("ar:"))
		{
			_song.info.artist = controlPart.right(controlPart.length() - 3); // no trim
		}
		else if (controlPart.startsWith("al:"))
		{
			_song.info.album = controlPart.right(controlPart.length() - 3); // no trim
		}
		else if (controlPart.startsWith("by:"))
		{
			_song.info.by = controlPart.right(controlPart.length() - 3); // no trim
		}
		else if (controlPart.startsWith("offset:"))
		{
			_song.general.offset = controlPart.right(controlPart.length() - 7).toLongLong();
		}
		else if (controlPart.at(0).isDigit())
		{
			QTime beginTime = QTime::fromString(controlPart + "0", "mm:ss.zzz");
			qint64 begin = beginTime.msecsSinceStartOfDay();

			KJsonSentence sentence;
			KJsonWord word;
			word.begin = begin;
			word.end = begin + settings->maximumDuration(); //std::numeric_limits<qint64>::max();
			word.text = line.right(line.length() - indexOfClose - 1);

			if (word.text.isEmpty())
			{
				int thisIndex = _song.lyric.sentencelist.count();
				if (thisIndex % _song.general.maxline == 0)
				{
					// skip
					continue;
				}
				else
				{
					// move up
					// skip multiple whites
					if (_song.lyric.sentencelist.last().wordlist.last().begin < 0)
					{
						continue;
					}
					else
					{
						word.end = word.begin + settings->minimumDuration();
					}
				}
			}

			if (!_song.lyric.sentencelist.empty())
			{
				KJsonWord& lastword = _song.lyric.sentencelist.last().wordlist.last();
				if (lastword.end - lastword.begin> settings->minimumDuration())
				{
					lastword.end = begin;// - lastword.begin;
				}
			}
			sentence.wordlist.append(word);
			_song.lyric.sentencelist.append(sentence);
		}
	}

	KJsonSong songCopy = _song;

	// first generate weak version
	treatSentecesAsControl();
	QString jsonPath = Settings::getInstance()->makeJsonPath(path, false);
	exportToJson(jsonPath);

	_song = songCopy;

	lrcWordSeparate();

	exportToASS(Settings::getInstance()->makeASSPath(path), musicPath);

	return loadJson(jsonPath);
}
void URLRequestCustomJobDelegate::setReply(const QByteArray &contentType, QIODevice *device)
{
    m_job->setReplyMimeType(contentType.toStdString());
    m_job->setReplyDevice(device);
}
예제 #30
0
QByteArray HoedownMarkdownConverterPrivate::markdown2Html(const QByteArray &markdownText) const {

    int markdownLength = markdownText.size();

    if(markdownLength == 0) {
        return QByteArray("");
    }

    hoedown_buffer *ib, *ob;
    hoedown_renderer *renderer = NULL;
    hoedown_document *document;

    // malloc
    ob = hoedown_buffer_new(markdownLength);
    ib = hoedown_buffer_new(markdownLength);
    renderer = hoedown_html_renderer_new(HOEDOWN_HTML_USE_XHTML, 0);

/*
typedef enum hoedown_extensions {
    // block-level extensions
    HOEDOWN_EXT_TABLES = (1 << 0),
    HOEDOWN_EXT_FENCED_CODE = (1 << 1),
    HOEDOWN_EXT_FOOTNOTES = (1 << 2),

    // span-level extensions
    HOEDOWN_EXT_AUTOLINK = (1 << 3),
    HOEDOWN_EXT_STRIKETHROUGH = (1 << 4),
    HOEDOWN_EXT_UNDERLINE = (1 << 5),
    HOEDOWN_EXT_HIGHLIGHT = (1 << 6),
    HOEDOWN_EXT_QUOTE = (1 << 7),
    HOEDOWN_EXT_SUPERSCRIPT = (1 << 8),
    HOEDOWN_EXT_MATH = (1 << 9),

    // other flags
    HOEDOWN_EXT_NO_INTRA_EMPHASIS = (1 << 11),
    HOEDOWN_EXT_SPACE_HEADERS = (1 << 12),
    HOEDOWN_EXT_MATH_EXPLICIT = (1 << 13),

    // negative flags
    HOEDOWN_EXT_DISABLE_INDENTED_CODE = (1 << 14)
} hoedown_extensions;
*/
    // 尽可能的指定
    document = hoedown_document_new(renderer, HOEDOWN_EXT_TABLES, 16);

    // put data
    hoedown_buffer_put(ib, (const uint8_t *) markdownText.toStdString().c_str(), markdownText.size());

    // render markdown to html
    hoedown_document_render(document, ob, ib->data, ib->size);

    QByteArray html((const char*)ob->data, ob->size);

    // free
    hoedown_buffer_free(ib);
    hoedown_document_free(document);
    hoedown_html_renderer_free(renderer);
    hoedown_buffer_free(ob);

    return html;
}