Example #1
0
static void LoadFielding(std::vector<FBBPlayer*> vecPlayers, const QString& file)
{
    // Open file
    QFile inputFile(":/data/2019-appearances.csv");
    inputFile.open(QIODevice::ReadOnly);
    QTextStream textStream(&inputFile);

    // Tokenize header data
    QStringList parsed = textStream.readLine().split(",");
    parsed.replaceInStrings("\"", "", Qt::CaseInsensitive);

    // Sort by ID so we can binary search
    std::sort(vecPlayers.begin(), vecPlayers.end(), [](const FBBPlayer* pLHS, const FBBPlayer* pRHS){
        return pLHS->id < pRHS->id;
    });

    enum
    {
        APPEARANCE_NAME,
        APPEARANCE_TEAM,
        APPEARANCE_POS,
        APPEARANCE_INN,
        APPEARANCE_RSZ,
        APPEARANCE_RCERA,
        APPEARANCE_RSB,
        APPEARANCE_RGDP,
        APPEARANCE_RARM,
        APPEARANCE_RGFP,
        APPEARANCE_RPM,
        APPEARANCE_RTS,
        APPEARANCE_DRS,
        APPEARANCE_BIZ,
        APPEARANCE_PLAYS,
        APPEARANCE_RZR,
        APPEARANCE_OOZ,
        APPEARANCE_FSR,
        APPEARANCE_FRM,
        APPEARANCE_ARM,
        APPEARANCE_DPR,
        APPEARANCE_RNGR,
        APPEARANCE_ERRR,
        APPEARANCE_UZR,
        APPEARANCE_UZRp150,
        APPEARANCE_DEF,
        APPEARANCE_PLAYERID,
    };

    // Loop rows
    while (!textStream.atEnd()) {

        // Tokenize this row
        QStringList parsed = textStream.readLine().split(",");
        parsed.replaceInStrings("\"", "", Qt::CaseInsensitive);

        QString id = parsed[APPEARANCE_PLAYERID];

        FBBPlayer* pPlayer = GetPlayerFromSortedById(vecPlayers, id);
        if (!pPlayer) {
            continue;
        }

        const QString pos = parsed[APPEARANCE_POS];
        const float count = parsed[APPEARANCE_INN].toFloat();

        static std::map<QString, FBBPlayer::Fielding> s_LUT = 
        {
            { "C", FBBPlayer::FIELDING_C},
            { "1B", FBBPlayer::FIELDING_1B},
            { "2B", FBBPlayer::FIELDING_2B},
            { "SS", FBBPlayer::FIELDING_SS},
            { "3B", FBBPlayer::FIELDING_3B},
            { "LF", FBBPlayer::FIELDING_LF},
            { "CF", FBBPlayer::FIELDING_CF},
            { "RF", FBBPlayer::FIELDING_RF},
        };

        auto itr = s_LUT.find(pos);
        if (itr == s_LUT.end()) {
            continue;
        }

        switch (itr->second)
        {
        case FBBPlayer::FIELDING_C:
            pPlayer->appearances.fielding.C += count;
            break;
        case FBBPlayer::FIELDING_1B:
            pPlayer->appearances.fielding._1B += count;
            break;
        case FBBPlayer::FIELDING_2B:
            pPlayer->appearances.fielding._2B += count;
            break;
        case FBBPlayer::FIELDING_SS:
            pPlayer->appearances.fielding.SS += count;
            break;
        case FBBPlayer::FIELDING_3B:
            pPlayer->appearances.fielding._3B += count;
            break;
        case FBBPlayer::FIELDING_LF:
            pPlayer->appearances.fielding.LF += count;
            break;
        case FBBPlayer::FIELDING_CF:
            pPlayer->appearances.fielding.CF += count;
            break;
        case FBBPlayer::FIELDING_RF:
            pPlayer->appearances.fielding.RF += count;
            break;
        default:
            break;
        }
    }
}
Example #2
0
void windowManager::saveAs(const QString projectFilename) {

  //const QString fileString = "test.xst";
  if (projectFilename.isNull()) {
    const QString fileString =
      QFileDialog::getSaveFileName(activeWindow(), tr("Save project"), ".", "Cstitch files (*.xst)\nAll files (*.*)");
    if (!fileString.isNull()) {
      projectFilename_ = fileString;
    }
    else {
      return;
    }
  }

  QDomDocument doc;
  QDomElement root = doc.createElement("cstitch");
  // version
  root.setAttribute("version", projectVersion_);
  doc.appendChild(root);
  ::appendTextElement(&doc, "warning",
                      tr("DIRE WARNING: DO NOT EDIT THIS FILE BY HAND! ! ! ! ! ! ! ! ! ! ! ! ! ! !"),
                      &root);
  // date
  ::appendTextElement(&doc, "date", QDateTime::currentDateTime().toString(),
                      &root);
  // image name
  ::appendTextElement(&doc, "image_name", originalImageName_, &root);
  // image color count
  ::appendTextElement(&doc, "color_count",
                      ::itoqs(getOriginalImageColorCount()), &root);
  // first write settings that are independent of any particular image
  QDomElement globals(doc.createElement("global_settings"));
  // a disabled window is one that doesn't have any images other than the
  // original (and is therefore not currently being displayed)
  if (colorChooserAction_->isEnabled() && colorChooser_.window()) {
    colorChooser_.window()->appendCurrentSettings(&doc, &globals);
  }
  if (colorCompareAction_->isEnabled() && colorCompareWindow_.window()) {
    colorCompareWindow_.window()->appendCurrentSettings(&doc, &globals);
  }
  if (squareWindowAction_->isEnabled() && squareWindow_.window()) {
    squareWindow_.window()->appendCurrentSettings(&doc, &globals);
  }
  if (patternWindowAction_->isEnabled() && patternWindow_.window()) {
    patternWindow_.window()->appendCurrentSettings(&doc, &globals);
  }

  root.appendChild(globals);
  //// colorCompare
  if (!colorCompareSavers_.empty()) {
    QDomElement colorCompareElement = doc.createElement("color_compare");
    root.appendChild(colorCompareElement);
    for (int i = 0, size = colorCompareSavers_.size(); i < size; ++i) {
      const colorCompareSaver thisColorCompareSaver = colorCompareSavers_[i];
      QDomElement thisColorCompareImage(thisColorCompareSaver.toXml(&doc));
      colorCompareElement.appendChild(thisColorCompareImage);
      if (thisColorCompareSaver.hasChildren()) {
        //// squareWindow
        squareWindow* squareWindowObject = squareWindow_.window();
        QDomElement squareWindowElement = doc.createElement("square_window");
        thisColorCompareImage.appendChild(squareWindowElement);
        const QList<int> colorCompareChildren =
          thisColorCompareSaver.children();
        for (int ii = 0, iiSize = colorCompareChildren.size();
             ii < iiSize; ++ii) {
          const int thisCompareChild = colorCompareChildren[ii];
          const squareWindowSaver thisSquareWindowSaver =
            getSaverFromIndex(squareWindowSavers_, thisCompareChild);
          QDomElement thisSquareXml = thisSquareWindowSaver.toXml(&doc);
          squareWindowElement.appendChild(thisSquareXml);
          if (!thisSquareWindowSaver.hidden()) {
            // append the current history for this child
            squareWindowObject->writeCurrentHistory(&doc, &thisSquareXml,
                                                    thisCompareChild);
          }
          if (thisSquareWindowSaver.hasChildren()) {
            //// patternWindow
            patternWindow* patternWindowObject = patternWindow_.window();
            QDomElement patternWindowElement =
              doc.createElement("pattern_window");
            thisSquareXml.appendChild(patternWindowElement);
            const QList<int> squareWindowChildren =
              thisSquareWindowSaver.children();
            for (int iii = 0, iiiSize = squareWindowChildren.size();
                 iii < iiiSize; ++iii) {
              const int thisSquareChild = squareWindowChildren[iii];
              const patternWindowSaver thisPatternWindowSaver =
                getSaverFromIndex(patternWindowSavers_, thisSquareChild);
              QDomElement thisPatternXml = thisPatternWindowSaver.toXml(&doc);
              patternWindowElement.appendChild(thisPatternXml);
              // append the history for this child
              patternWindowObject->writeCurrentHistory(&doc, &thisPatternXml,
                                                       thisSquareChild);
            }
          }
        }
      }
    }
  }
  QString xmlString = doc.toString(2);

  // write the xml portion as text
  QFile outFile(projectFilename_);
  outFile.open(QIODevice::WriteOnly);
  QTextStream textStream(&outFile);
  textStream << xmlString << endl;
  textStream.flush();
  outFile.close();

  // append the image as binary
  outFile.open(QIODevice::Append);
  QDataStream dataStream(&outFile);
  dataStream << originalImageData_;
  outFile.close();
  setWindowTitles(QFileInfo(projectFilename_).fileName());
  activeWindow()->showTemporaryStatusMessage(tr("Saved project to ") +
                                             projectFilename_);
}
Example #3
0
void FBBProjectionService::LoadPitchingProjections(std::vector<FBBPlayer*>& vecPlayers, const QString& file)
{
    // Open file
    QFile inputFile(file);
    inputFile.open(QIODevice::ReadOnly);
    QTextStream textStream(&inputFile);

    // Tokenize header data
    QStringList parsed = textStream.readLine().split(",");
    parsed.replaceInStrings("\"", "", Qt::CaseInsensitive);

    enum FanPitcher
    {
        FAN_PITCHER_NAME,
        FAN_PITCHER_TEAM,
        FAN_PITCHER_W,
        FAN_PITCHER_L,
        FAN_PITCHER_SV,
        FAN_PITCHER_HLD,
        FAN_PITCHER_ERA,
        FAN_PITCHER_GS,
        FAN_PITCHER_G,
        FAN_PITCHER_IP,
        FAN_PITCHER_H,
        FAN_PITCHER_ER,
        FAN_PITCHER_HR,
        FAN_PITCHER_SO,
        FAN_PITCHER_BB,
        FAN_PITCHER_WHIP,
        FAN_PITCHER_Kp9,
        FAN_PITCHER_BBp9,
        FAN_PITCHER_FIP,
        FAN_PITCHER_WAR,
        FAN_PITCHER_ADP,
        FAN_PITCHER_PLAYER_ID,
    };

    // Loop rows
    while (!textStream.atEnd()) {

        // Tokenize this row
        QStringList parsed = textStream.readLine().split(",");
        parsed.replaceInStrings("\"", "", Qt::CaseInsensitive);

        // Lazily get player
        FBBPlayer* pPlayer = new FBBPlayer(FBBPlayer::PLAYER_TYPE_PITCHER, parsed[FAN_PITCHER_PLAYER_ID], parsed[FAN_PITCHER_NAME], this);
        pPlayer->team = ToFBBTeam(parsed[FAN_PITCHER_TEAM]);
        
        // Load stats
        pPlayer->projection.pitching.W =  parsed[FAN_PITCHER_W].toUInt();
        pPlayer->projection.pitching.L =  parsed[FAN_PITCHER_L].toUInt();
        pPlayer->projection.pitching.GS = parsed[FAN_PITCHER_GS].toUInt();
        pPlayer->projection.pitching.G =  parsed[FAN_PITCHER_G].toUInt();
        pPlayer->projection.pitching.SV = parsed[FAN_PITCHER_SV].toUInt();
        pPlayer->projection.pitching.IP = parsed[FAN_PITCHER_IP].toFloat();
        pPlayer->projection.pitching.H =  parsed[FAN_PITCHER_H].toUInt();
        pPlayer->projection.pitching.ER = parsed[FAN_PITCHER_ER].toUInt();
        pPlayer->projection.pitching.HR = parsed[FAN_PITCHER_HR].toUInt();
        pPlayer->projection.pitching.SO = parsed[FAN_PITCHER_SO].toUInt();
        pPlayer->projection.pitching.BB = parsed[FAN_PITCHER_BB].toUInt();

        // Add player
        vecPlayers.push_back(pPlayer);
    }
}
Example #4
0
QString KicadModule2Svg::convert(const QString & filename, const QString & moduleName, bool allowPadsAndPins)
{
    m_nonConnectorNumber = 0;
    initLimits();

    QFile file(filename);
    if (!file.open(QFile::ReadOnly)) {
        throw QObject::tr("unable to open %1").arg(filename);
    }

    QString text;
    QTextStream textStream(&file);

    QString metadata = makeMetadata(filename, "module", moduleName);


    bool gotModule = false;
    while (true) {
        QString line = textStream.readLine();
        if (line.isNull()) {
            break;
        }

        if (line.contains("$MODULE") && line.contains(moduleName, Qt::CaseInsensitive)) {
            gotModule = true;
            break;
        }
    }

    if (!gotModule) {
        throw QObject::tr("footprint %1 not found in %2").arg(moduleName).arg(filename);
    }

    bool gotT0;
    QString line;
    while (true) {
        line = textStream.readLine();
        if (line.isNull()) {
            throw QObject::tr("unexpected end of file in footprint %1 in file %2").arg(moduleName).arg(filename);
        }

        if (line.startsWith("T0") || line.startsWith("DS") || line.startsWith("DA") || line.startsWith("DC")) {
            gotT0 = true;
            break;
        }
        else if (line.startsWith("Cd")) {
            metadata += m_comment.arg(TextUtils::stripNonValidXMLCharacters(TextUtils::escapeAnd(line.remove(0,3))));
        }
        else if (line.startsWith("Kw")) {
            QStringList keywords = line.split(" ");
            for (int i = 1; i < keywords.count(); i++) {
                metadata += m_attribute.arg("keyword").arg(TextUtils::stripNonValidXMLCharacters(TextUtils::escapeAnd(keywords[i])));
            }
        }
    }

    metadata += endMetadata();

    if (!gotT0) {
        throw QObject::tr("unexpected format (1) in %1 from %2").arg(moduleName).arg(filename);
    }

    while (line.startsWith("T")) {
        line = textStream.readLine();
        if (line.isNull()) {
            throw QObject::tr("unexpected end of file in footprint %1 in file %2").arg(moduleName).arg(filename);
        }
    }

    bool done = false;
    QString copper0;
    QString copper1;
    QString silkscreen0;
    QString silkscreen1;

    while (true) {
        if (line.startsWith("$PAD")) break;
        if (line.startsWith("$EndMODULE")) {
            done = true;
            break;
        }

        int layer = 0;
        QString svgElement;
        if (line.startsWith("DS")) {
            layer = drawDSegment(line, svgElement);
        }
        else if (line.startsWith("DA")) {
            layer = drawDArc(line, svgElement);
        }
        else if (line.startsWith("DC")) {
            layer = drawDCircle(line, svgElement);
        }
        switch (layer) {
        case KicadSilkscreenTop:
            silkscreen1 += svgElement;
            break;
        case KicadSilkscreenBottom:
            silkscreen0 += svgElement;
            break;
        default:
            break;
        }

        line = textStream.readLine();
        if (line.isNull()) {
            throw QObject::tr("unexpected end of file in footprint %1 in file %2").arg(moduleName).arg(filename);
        }
    }

    if (!done) {
        QList<int> numbers;
        for (int i = 0; i < 512; i++) {
            numbers << i;
        }
        int pads = 0;
        int pins = 0;
        while (!done) {
            try {
                QString pad;
                PadLayer padLayer = convertPad(textStream, pad, numbers);
                switch (padLayer) {
                case ToCopper0:
                    copper0 += pad;
                    pins++;
                    break;
                case ToCopper1:
                    copper1 += pad;
                    pads++;
                    break;
                default:
                    break;
                }
            }
            catch (const QString & msg) {
                DebugDialog::debug(QString("kicad pad %1 conversion failed in %2: %3").arg(moduleName).arg(filename).arg(msg));
            }

            while (true) {
                line = textStream.readLine();
                if (line.isNull()) {
                    throw QObject::tr("unexpected end of file in footprint %1 in file %2").arg(moduleName).arg(filename);
                }

                if (line.contains("$SHAPE3D")) {
                    done = true;
                    break;
                }
                if (line.contains("$EndMODULE")) {
                    done = true;
                    break;
                }
                if (line.contains("$PAD")) {
                    break;
                }
            }
        }

        if (!allowPadsAndPins && pins > 0 && pads > 0) {
            throw QObject::tr("Sorry, Fritzing can't yet handle both pins and pads together (in %1 in %2)").arg(moduleName).arg(filename);
        }

    }

    if (!copper0.isEmpty()) {
        copper0 = offsetMin("\n<g id='copper0'><g id='copper1'>" + copper0 + "</g></g>\n");
    }
    if (!copper1.isEmpty()) {
        copper1 = offsetMin("\n<g id='copper1'>" + copper1 + "</g>\n");
    }
    if (!silkscreen1.isEmpty()) {
        silkscreen1 = offsetMin("\n<g id='silkscreen'>" + silkscreen1 + "</g>\n");
    }
    if (!silkscreen0.isEmpty()) {
        silkscreen0 = offsetMin("\n<g id='silkscreen0'>" + silkscreen0 + "</g>\n");
    }

    QString svg = TextUtils::makeSVGHeader(10000, 10000, m_maxX - m_minX, m_maxY - m_minY)
                  + m_title + m_description + metadata + copper0 + copper1 + silkscreen0 + silkscreen1 + "</svg>";

    return svg;
}
/*!
    \internal
 */
void QWebSocketServerPrivate::handshakeReceived()
{
    if (Q_UNLIKELY(!currentSender)) {
        qWarning() << QWebSocketServer::tr("Sender is NULL. This is a Qt bug.");
        return;
    }
    QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(currentSender->sender);
    if (Q_UNLIKELY(!pTcpSocket)) {
        qWarning() << QWebSocketServer::tr("Sender is not a QTcpSocket. This is a Qt bug!!!");
        return;
    }
    //When using Google Chrome the handshake in received in two parts.
    //Therefore, the readyRead signal is emitted twice.
    //This is a guard against the BEAST attack.
    //See: https://www.imperialviolet.org/2012/01/15/beastfollowup.html
    //For Safari, the handshake is delivered at once
    //FIXME: For FireFox, the readyRead signal is never emitted
    //This is a bug in FireFox (see https://bugzilla.mozilla.org/show_bug.cgi?id=594502)
    if (!pTcpSocket->canReadLine()) {
        return;
    }
    disconnect(pTcpSocket, &QTcpSocket::readyRead,
               this, &QWebSocketServerPrivate::handshakeReceived);
    Q_Q(QWebSocketServer);
    bool success = false;
    bool isSecure = false;

    if (m_pendingConnections.length() >= maxPendingConnections()) {
        pTcpSocket->close();
        pTcpSocket->deleteLater();
        qWarning() << QWebSocketServer::tr("Too many pending connections: " \
                                           "New WebSocket connection not accepted.");
        setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection,
                 QWebSocketServer::tr("Too many pending connections."));
        return;
    }

    QWebSocketHandshakeRequest request(pTcpSocket->peerPort(), isSecure);
    QTextStream textStream(pTcpSocket);
    request.readHandshake(textStream);

    if (request.isValid()) {
        QWebSocketCorsAuthenticator corsAuthenticator(request.origin());
        Q_EMIT q->originAuthenticationRequired(&corsAuthenticator);

        QWebSocketHandshakeResponse response(request,
                                             m_serverName,
                                             corsAuthenticator.allowed(),
                                             supportedVersions(),
                                             supportedProtocols(),
                                             supportedExtensions());

        if (response.isValid()) {
            QTextStream httpStream(pTcpSocket);
            httpStream << response;
            httpStream.flush();

            if (response.canUpgrade()) {
                QWebSocket *pWebSocket = QWebSocketPrivate::upgradeFrom(pTcpSocket,
                                                                        request,
                                                                        response);
                if (pWebSocket) {
                    addPendingConnection(pWebSocket);
                    Q_EMIT q->newConnection();
                    success = true;
                } else {
                    setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection,
                             QWebSocketServer::tr("Upgrade to WebSocket failed."));
                }
            }
            else {
                setError(response.error(), response.errorString());
            }
        } else {
            setError(QWebSocketProtocol::CloseCodeProtocolError,
                     QWebSocketServer::tr("Invalid response received."));
        }
    }
    if (!success) {
        qWarning() << QWebSocketServer::tr("Closing socket because of invalid or unsupported request.");
        pTcpSocket->close();
    }
}
Example #6
0
bool SkinSogou::loadSkin(const QString skinPath)
{
    init();
    QFile sogouSkinConfFile(skinPath + "skin.ini");

    if (!sogouSkinConfFile.exists())
        return false;

    if (!sogouSkinConfFile.open(QIODevice::ReadOnly))
        return false;


    QString line;
    QString key, value;

    /// parse ini file content
    bool general = false;
    bool display = false;
    bool scheme_h1 = false;
    bool scheme_v1 = false;
    bool statusbar = false;
    int h_pt, h_pb, h_pl, h_pr;
    int v_pt, v_pb, v_pl, v_pr;
    unsigned int pinyin_color, zhongwen_color, zhongwen_first_color, comphint_color;

    int fontPixelSize = 12;

    setAdjustWidth(10);
    setAdjustHeight(30);
    setHorizontalTileMode("Stretch");
    setVerticalTileMode("Stretch");
    setInputStringPosX(0);
    setInputStringPosY(0);
    setOutputCandPosX(0);
    setOutputCandPosY(0);

    QTextStream textStream(sogouSkinConfFile.readAll());
 
    do {

        line = textStream.readLine();

        if (line.isEmpty() || line.at(0) == '#')
            continue;

        if (line.at(0) == '[') {
            general = (line == "[General]");
            display = (line == "[Display]");
            scheme_h1 = (line == "[Scheme_H1]");
            scheme_v1 = (line == "[Scheme_V1]");
            statusbar = (line == "[StatusBar]");

            continue;
        }

        if (!line.contains('='))
            continue;

        key = line.split('=').at(0);
        value = line.split('=').at(1);

        if (value.isEmpty())
            continue;


        if (display) {
            if (key == "font_size")
                setFontSize(value.toInt());
            else if (key == "pinyin_color"){
                pinyin_color = value.toUInt(0, 0);
                setInputColor(QColor(qBlue(pinyin_color), qGreen(pinyin_color), qRed(pinyin_color)));
            } 
            else if (key == "zhongwen_color"){
                zhongwen_color = value.toUInt(0, 0);
                setOtherColor(QColor(qBlue(zhongwen_color), qGreen(zhongwen_color), qRed(zhongwen_color)));
            }
            else if (key == "zhongwen_first_color"){
                zhongwen_first_color = value.toUInt(0, 0);
                setFirstCandColor(QColor(qBlue(zhongwen_first_color), qGreen(zhongwen_first_color), qRed(zhongwen_first_color)));
            }
            else if (key == "comphint_color"){
                //FIXME
                //comphint_color = value.toUInt(0, 0);
            }
        }else if (scheme_h1) {
            if (key == "pic" && MainModel::self()->isHorizontal()) {
                setInputBackImg("file:/" + skinPath + value);
            }
            else if (key == "pinyin_marge") {
                QStringList list = value.split(',');
                h_pt = list.at(0).trimmed().toInt();
                h_pb = list.at(1).trimmed().toInt();
                h_pl = list.at(2).trimmed().toInt();
                h_pr = list.at(3).trimmed().toInt();

                if (MainModel::self()->isHorizontal()){
                    setMarginTop(h_pt);
                    setMarginBottom(h_pb);
                    setMarginLeft(h_pl);
                    setMarginRight(h_pr);
                }
            } 
            else if (key == "custom0_align") {
                //todo
            }
            else if (key == "custom0") {
                mCustomImgH1[0] = value;
                setCustomImg0 ("file:/" + skinPath + value);
            }
            else if (key == "custom1") {
                mCustomImgH1[1] = value;
                setCustomImg1 ("file:/" + skinPath + value);
            }
            else if (key == "custom_cnt") {
                mCustomCntH1 = value.toInt();
            }
        }else if (scheme_v1) {
            if (key == "pic" && !MainModel::self()->isHorizontal()) {
                setInputBackImg("file:/" + skinPath + value);
            }
            else if (key == "pinyin_marge") {
                QStringList list = value.split(',');
                v_pt = list.at(0).trimmed().toInt();
                v_pb = list.at(1).trimmed().toInt();
                v_pl = list.at(2).trimmed().toInt();
                v_pr = list.at(3).trimmed().toInt();

                if (!MainModel::self()->isHorizontal()){
                    setMarginTop(v_pt);
                    setMarginBottom(v_pb);
                    setMarginLeft(v_pl);
                    setMarginRight(v_pr);
                }
            }
            else if (key == "custom0") {
                mCustomImgV1[0] = value;
                //qDebug() << "cuystom0 " << value;
                //setCustomImg0(value);
            }
            else if (key == "custom1") {
                mCustomImgV1[1] = value;
                qDebug() << "cuystom1 " << value;
                //setCustomImg1(value);
            }
            else if (key == "custom_cnt") {
                mCustomCntV1 = value.toInt();
                //qDebug() << "cuystom_cnt " << mCustomCntV1;
            }
        } else if (statusbar) {
            if (key == "pic") {
                //FIXME
                //setTipsImg("file:/" + skinPath + value);
            }
        }


    } while (!line.isNull());

    sogouSkinConfFile.close();
    return true;
}
Example #7
0
Botuviettat::Botuviettat(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Botuviettat)
{
    ui->setupUi(this);

    setWindowTitle(QString::fromUtf8("Bộ từ viết tắt"));
    QFile file("tuviettat.txt");
    file.open(QIODevice ::ReadOnly);
    QString s,a,temp,xau;
    QTextStream textStream(&file);
    textStream.setCodec("UTF-8");
    s = textStream.readAll();
    QStringList mgiua,vietTat,vietChuan;
    mgiua = s.split(";",QString::SkipEmptyParts);

    for(int k=0;k<mgiua.size();k++)

    for(int i=0;i<mgiua.at(k).size();i++)
    {
        if(mgiua.at(k)[i]=='='){

            for(int j=0;j<i;j++)
                a.append(mgiua.at(k)[j]);
            vietTat<<a;//"d","dc"
            a="";temp=mgiua.at(k);
         temp.remove(0,i+1);
         vietChuan<<temp;

         temp="";
        }
    }for(int i=0;i<vietTat.size();i++)
    qDebug()<<vietTat.at(i)<<vietChuan.at(i);
//ui->textEdit->setText(s);
    int vitri;
    QStringList danhSachCot;


    danhSachCot.clear();
    vitri=s.indexOf(xau);
    qDebug()<<vitri;
    int k=0;
    ui->tableWidget->setColumnCount(2);
    danhSachCot<<QString::fromUtf8("Từ viết tắt")<<QString::fromUtf8("Từ viết chuẩn");
    ui->tableWidget->insertRow(ui->tableWidget->rowCount());
    ui->tableWidget->setHorizontalHeaderLabels(danhSachCot);
    for(int i=1;i<=vietTat.size();i++)
    {
        ui->tableWidget->insertRow(ui->tableWidget->rowCount());
        xau=vietTat.at(i-1);
        ui->tableWidget->setItem(i-1,0,new QTableWidgetItem(xau));
        k++;
}
    for(int i=1;i<=vietChuan.size();i++)
    {
        xau=vietChuan.at(i-1);
        ui->tableWidget->setItem(i-1,1,new QTableWidgetItem(xau));
        k++;
    }
    ui->tableWidget->setColumnWidth(0,300);
    ui->tableWidget->setColumnWidth(1,300);



//table gợi ý.
}
PreferencesDialog::PreferencesDialog(QWidget *parent,Profile * _profile) :
    QDialog(parent),
    ui(new Ui::PreferencesDialog),
    profile(_profile)
{
    ui->setupUi(this);
    ui->leakProfile->setRowCount(5);
    ui->leakProfile->setColumnCount(2);
    ui->leakProfile->horizontalHeader()->setStretchLastSection(true);
    ui->leakProfile->setColumnWidth(0,100);
    ui->maskTypeCombo->clear();

    //ui->customEventGroupbox->setEnabled(false);

    QString masktype=tr("Nasal Pillows");
    //masktype=PROFILEMaskType
    for (int i=0;i<num_masks;i++) {
        ui->maskTypeCombo->addItem(masks[i].name);

        /*if (masktype==masks[i].name) {
            ui->maskTypeCombo->setCurrentIndex(i);
            on_maskTypeCombo_activated(i);
        }*/
    }
    QLocale locale=QLocale::system();
    QString shortformat=locale.dateFormat(QLocale::ShortFormat);
    if (!shortformat.toLower().contains("yyyy")) {
        shortformat.replace("yy","yyyy");
    }
    ui->startedUsingMask->setDisplayFormat(shortformat);
    Qt::DayOfWeek dow=firstDayOfWeekFromLocale();

    ui->startedUsingMask->calendarWidget()->setFirstDayOfWeek(dow);

    ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->colourTab));

    // Stop both calendar drop downs highlighting weekends in red
    QTextCharFormat format = ui->startedUsingMask->calendarWidget()->weekdayTextFormat(Qt::Saturday);
    format.setForeground(QBrush(Qt::black, Qt::SolidPattern));
    ui->startedUsingMask->calendarWidget()->setWeekdayTextFormat(Qt::Saturday, format);
    ui->startedUsingMask->calendarWidget()->setWeekdayTextFormat(Qt::Sunday, format);

    //ui->leakProfile->setColumnWidth(1,ui->leakProfile->width()/2);

    {
        QString filename=PROFILE.Get("{DataFolder}/ImportLocations.txt");
        QFile file(filename);
        file.open(QFile::ReadOnly);
        QTextStream textStream(&file);
        while (1) {
            QString line = textStream.readLine();
             if (line.isNull())
                 break;
             else if (line.isEmpty())
                 continue;
             else {
                 importLocations.append(line);
             }
        };
        file.close();
    }
    importModel=new QStringListModel(importLocations,this);
    ui->importListWidget->setModel(importModel);
    //ui->tabWidget->removeTab(3);

    Q_ASSERT(profile!=NULL);
    ui->tabWidget->setCurrentIndex(0);

    //i=ui->timeZoneCombo->findText((*profile)["TimeZone"].toString());
    //ui->timeZoneCombo->setCurrentIndex(i);

    ui->spo2Drop->setValue(profile->oxi->spO2DropPercentage());
    ui->spo2DropTime->setValue(profile->oxi->spO2DropDuration());
    ui->pulseChange->setValue(profile->oxi->pulseChangeBPM());
    ui->pulseChangeTime->setValue(profile->oxi->pulseChangeDuration());
    ui->oxiDiscardThreshold->setValue(profile->oxi->oxiDiscardThreshold());
    ui->AddRERAtoAHI->setChecked(profile->general->calculateRDI());

    ui->timeEdit->setTime(profile->session->daySplitTime());
    int val=profile->session->combineCloseSessions();
    ui->combineSlider->setValue(val);
    if (val>0) {
        ui->combineLCD->display(val);
    } else ui->combineLCD->display(STR_GEN_Off);

    val=profile->session->ignoreShortSessions();
    ui->IgnoreSlider->setValue(val);
    if (val>0) {
        ui->IgnoreLCD->display(val);
    } else ui->IgnoreLCD->display(STR_GEN_Off);

    ui->applicationFont->setCurrentFont(QApplication::font());
    //ui->applicationFont->setFont(QApplication::font());
    ui->applicationFontSize->setValue(QApplication::font().pointSize());
    ui->applicationFontBold->setChecked(QApplication::font().weight()==QFont::Bold);
    ui->applicationFontItalic->setChecked(QApplication::font().italic());

    ui->graphFont->setCurrentFont(*defaultfont);
    //ui->graphFont->setFont(*defaultfont);
    ui->graphFontSize->setValue(defaultfont->pointSize());
    ui->graphFontBold->setChecked(defaultfont->weight()==QFont::Bold);
    ui->graphFontItalic->setChecked(defaultfont->italic());

    ui->titleFont->setCurrentFont(*mediumfont);
    //ui->titleFont->setFont(*mediumfont);
    ui->titleFontSize->setValue(mediumfont->pointSize());
    ui->titleFontBold->setChecked(mediumfont->weight()==QFont::Bold);
    ui->titleFontItalic->setChecked(mediumfont->italic());

    ui->bigFont->setCurrentFont(*bigfont);
    //ui->bigFont->setFont(*bigfont);
    ui->bigFontSize->setValue(bigfont->pointSize());
    ui->bigFontBold->setChecked(bigfont->weight()==QFont::Bold);
    ui->bigFontItalic->setChecked(bigfont->italic());

    ui->startedUsingMask->setDate(profile->cpap->maskStartDate());

    ui->leakModeCombo->setCurrentIndex(profile->cpap->leakMode());

    int mt=(int)profile->cpap->maskType();
    ui->maskTypeCombo->setCurrentIndex(mt);
    on_maskTypeCombo_activated(mt);


    ui->maskDescription->setText(profile->cpap->maskDescription());
    ui->useAntiAliasing->setChecked(profile->appearance->antiAliasing());
    ui->useSquareWavePlots->setChecked(profile->appearance->squareWavePlots());
    ui->enableGraphSnapshots->setChecked(profile->appearance->graphSnapshots());
    ui->skipLoginScreen->setChecked(PREF[STR_GEN_SkipLogin].toBool());
    ui->allowEarlyUpdates->setChecked(PREF[STR_PREF_AllowEarlyUpdates].toBool());

    ui->clockDrift->setValue(profile->cpap->clockDrift());

    ui->skipEmptyDays->setChecked(profile->general->skipEmptyDays());
    ui->enableMultithreading->setChecked(profile->session->multithreading());
    ui->cacheSessionData->setChecked(profile->session->cacheSessions());
    ui->animationsAndTransitionsCheckbox->setChecked(profile->appearance->animations());
    ui->complianceGroupbox->setChecked(profile->cpap->showComplianceInfo());
    ui->complianceHours->setValue(profile->cpap->complianceHours());

    ui->prefCalcMiddle->setCurrentIndex(profile->general->prefCalcMiddle());
    ui->prefCalcMax->setCurrentIndex(profile->general->prefCalcMax());
    float f=profile->general->prefCalcPercentile();
    ui->prefCalcPercentile->setValue(f);

    ui->tooltipTimeoutSlider->setValue(profile->general->tooltipTimeout());

    bool bcd=profile->session->backupCardData();
    ui->createSDBackups->setChecked(bcd);
    ui->compressSDBackups->setEnabled(bcd);
    ui->compressSDBackups->setChecked(profile->session->compressBackupData());
    ui->compressSessionData->setChecked(profile->session->compressSessionData());

    ui->graphHeight->setValue(profile->appearance->graphHeight());

    if (!PREF.contains(STR_GEN_UpdatesAutoCheck)) PREF[STR_GEN_UpdatesAutoCheck]=true;
    ui->automaticallyCheckUpdates->setChecked(PREF[STR_GEN_UpdatesAutoCheck].toBool());

    if (!PREF.contains(STR_GEN_UpdateCheckFrequency)) PREF[STR_GEN_UpdateCheckFrequency]=3;
    ui->updateCheckEvery->setValue(PREF[STR_GEN_UpdateCheckFrequency].toInt());
    if (PREF.contains(STR_GEN_UpdatesLastChecked)) {
        RefreshLastChecked();
    } else ui->updateLastChecked->setText("Never");


    ui->overlayFlagsCombo->setCurrentIndex(profile->appearance->overlayType());

    ui->oximetryGroupBox->setChecked(profile->oxi->oximetryEnabled());
    ui->oximetrySync->setChecked(profile->oxi->syncOximetry());
    int ot=ui->oximetryType->findText(profile->oxi->oximeterType(),Qt::MatchExactly);
    if (ot<0) ot=0;
    ui->oximetryType->setCurrentIndex(ot);

    ui->ahiGraphWindowSize->setEnabled(false);
    ui->ahiGraphWindowSize->setValue(profile->cpap->AHIWindow());
    ui->ahiGraphZeroReset->setChecked(profile->cpap->AHIReset());

    ui->customEventGroupbox->setChecked(profile->cpap->userEventFlagging());
    ui->apneaDuration->setValue(profile->cpap->userEventDuration());
    ui->apneaFlowRestriction->setValue(profile->cpap->userFlowRestriction());
    ui->userEventDuplicates->setChecked(profile->cpap->userEventDuplicates());
    ui->userEventDuplicates->setVisible(false);

    ui->eventTable->setColumnWidth(0,40);
    ui->eventTable->setColumnWidth(1,55);
    ui->eventTable->setColumnHidden(3,true);
    int row=0;
    QTableWidgetItem *item;
    QHash<QString, schema::Channel *>::iterator ci;
    for (ci=schema::channel.names.begin();ci!=schema::channel.names.end();ci++) {
        if (ci.value()->type()==schema::DATA) {
            ui->eventTable->insertRow(row);
            int id=ci.value()->id();
            ui->eventTable->setItem(row,3,new QTableWidgetItem(QString::number(id)));
            item=new QTableWidgetItem(ci.value()->description());
            ui->eventTable->setItem(row,2,item);
            QCheckBox *c=new QCheckBox(ui->eventTable);
            c->setChecked(true);
            QLabel *pb=new QLabel(ui->eventTable);
            pb->setText("foo");
            ui->eventTable->setCellWidget(row,0,c);
            ui->eventTable->setCellWidget(row,1,pb);


            QColor a=ci.value()->defaultColor();//(rand() % 255, rand() % 255, rand() % 255, 255);
            QPalette p(a,a,a,a,a,a,a);

            pb->setPalette(p);
            pb->setAutoFillBackground(true);
            pb->setBackgroundRole(QPalette::Background);
            row++;
        }
    }
/*    QLocale locale=QLocale::system();
    QString shortformat=locale.dateFormat(QLocale::ShortFormat);
    if (!shortformat.toLower().contains("yyyy")) {
        shortformat.replace("yy","yyyy");
    }*/

    graphFilterModel=new MySortFilterProxyModel(this);
    graphModel=new QStandardItemModel(this);
    graphFilterModel->setSourceModel(graphModel);
    graphFilterModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
    graphFilterModel->setFilterKeyColumn(0);
    ui->graphView->setModel(graphFilterModel);

    resetGraphModel();
//    tree->sortByColumn(0,Qt::AscendingOrder);
}
Example #9
0
HY3131DMMLib::HY3131DMMLib(QObject *parent):QObject(parent){
	QPluginLoader loaderApp("libPTApplicationcardInterface.so", this);
	IAppCard = qobject_cast<IApplicationCardInterface*> (loaderApp.instance());
	IAppCard->setDeviceName(SLOT0);
	IAppCard->enumerateAPPCard();

	//BackPlaneInterfacePlugin
	QPluginLoader loader2("libBackPlaneInterface.so", this);
	IBackPlane = qobject_cast<IntefaceBackPlane*> (loader2.instance());
	IBackPlane->InitializeBpObject();

	selAppCard=false;

//	if(selAppCard)
//			IAppCard->writeRegister(0x20, DMM_CLK_DIV);//DMM SPI Clock Settings 1MHz
//	else
			IBackPlane->writeBackPlaneRegister(0x20,DMM_CLK_DIV_BP);

	D32Bit=0;
	reg0 = reg1 = reg2 = 0;
	ADCDigital = 0;
	RMSData=0;
	ReadData = RawData=0;
	minus=false;
	buzState=false;
	busyState=false;

	//Read Gain & Offset from file~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	bool ok=true;
	int index=0;
	//qDebug()<<"dp:26";
	QFile file("/home/HY3131/GainOffset.dat");
	if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
		return;
	while (!file.atEnd()) {

		QByteArray line = file.readLine();
		QList<QByteArray> data = line.split('\t');

		if (data[0].endsWith('\n'))
			data[0].chop(1);
		if (data[1].endsWith('\n'))
			data[1].chop(1);
		if (data[2].endsWith('\n'))
			data[2].chop(1);

		m_strRange[index]=data[0];
		m_nGain[index]=data[1].toDouble(&ok);
		m_nOffset[index]=data[2].toDouble(&ok);
		index++;
	}
	file.close();
	//qDebug()<<"dp:48";
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


	//Load No of Samples from File~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	m_nSampleCount=25;
	QStringList stringList;
	QFile textFile("/home/HY3131/Samples.dat");
	if (textFile.open(QIODevice::ReadOnly))
	{
		QTextStream textStream(&textFile);
		while (!textStream.atEnd())
		{
			stringList.append(textStream.readLine());
		}
		m_nSampleCount=stringList.value(0).toInt(&ok,10);
	}
        textFile.close();
	//qDebug()<<"samples:"<<m_nSampleCount;
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


}
Example #10
0
void Plotter::drawCurves(QPainter *painter)
{
	//~~~~~~~~Adjust X-y Axis ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    QStringList stringList;
    bool ok=true;
    QFile textFile("AdjustXYaxisVI.txt");
    if (textFile.open(QIODevice::ReadOnly))
    {
        QTextStream textStream(&textFile);
        while (!textStream.atEnd())
        {
            stringList.append(textStream.readLine());
        }
        adjustXaxis=stringList.value(0).toDouble(&ok) * m_nXZoomFactor;
        adjustYaxis=stringList.value(1).toDouble(&ok) * m_nYZoomFactor;
    }else{
        adjustXaxis=5.5;
        adjustYaxis=0;
    }
//    qDebug() << "Zoom Factor:" << m_nXZoomFactor << m_nYZoomFactor;
//    qDebug() << "Adjust Axis:" << adjustXaxis << adjustYaxis;
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    static const QColor colorForIds[8] = {Qt::red,Qt::green,Qt::cyan,Qt::magenta,Qt::yellow,Qt::white,Qt::gray,Qt::black};
    PlotSettings settings = zoomStack[curZoom];
    if( m_moveFlag == true)
    {
        settings.maxX = m_ZoomSettings->maxX;
        settings.maxY = m_ZoomSettings->maxY;
        settings.minX = m_ZoomSettings->minX;
        settings.minY = m_ZoomSettings->minY;
        settings.m_nOffset = m_ZoomSettings->m_nOffset;
        settings.numXTicks = m_ZoomSettings->numXTicks;
        settings.numYTicks = m_ZoomSettings->numYTicks;
    }
    QRect rect(Margin,Margin,width()-(2*Margin),height()-(2*Margin));
    if(m_bshowZoomRect == true)
    {
        painter->setPen(colorForIds[6]);
        painter->drawRect(rubberBandRect);
    }

    if(!rect.isValid())
        return;
    painter->setClipRect(rect.adjusted(+1,+1,-1,-1));
    QMapIterator<int, QVector<QPointF> > i(curveMap);
//    printf("Rect Left: %d\n",rect.left());
//    printf("Rect Height: %d\n",rect.height());
//    printf("Rect width: %d\n",rect.width());
//    printf("Rect Bottom: %d\n",rect.bottomLeft().y());
//    printf("Rect Top: %d\n",rect.top());
    double dx,dy;
    while(i.hasNext()){

        i.next();
        int id = i.key();
      //  qDebug() << "Curve ID" << id;
        QVector<QPointF> data = i.value();
        QPolygonF polyline(data.count());
        double y =0.0,x=0.0;
        int l_nCounter =0;
        //printf("MinY:%f\n",settings.minY);
        //printf("Offset:%f\n",m_nOffset);
        m_nOffset =0.0;
        for(int j=0; j< data.count();++j)
        {
             dx = data[j].x();
             dy = data[j].y();
             if(m_bUniPolar == true)
             {
                 float l_nDiv = (dy/2.0);
//                 printf("UniPolar %f->%f\n",l_nDiv,dy - l_nDiv);
             }
             if(( data[j].x()>=settings.minX && data[j].x()<=settings.maxX))
             {
                 //printf("X:%f Y:%f\n",dx,dy);
             }
            y =0.0,x=0.0;
            if(m_ZoomFlag == false)
            {
                if(m_bVIMode == true)
                    x = ((rect.width()/2)+adjustXaxis  + ((dx)*(((rect.width()-1)))/(settings.spanX())));
                else
                    x = (rect.left()+ ((dx)*(((rect.width()-1)))/(settings.spanX())));

                if( m_bUniPolar == true){
                    y = ((Margin+rect.bottom()) - (((dy/2.0)+settings.m_nOffset)*((rect.height()-1))/(settings.spanY())));
                    //y+=10;
//                    printf(" Coord-Y %f\n",dy/2.0);
                }
                else
                    y = (((Margin+rect.height()/2)+adjustYaxis) - ((dy+m_nOffset)*((rect.height()-1))/(settings.spanY())));//TO CHANGE THE Y AXIS IN THE GRAPH
               // printf(" Coord- X & Y %f %f\n",x,y);
            }
            else if(m_ZoomFlag == true)
            {
                x = (rect.left() + ((dx-settings.minX)*(((rect.width()-1)))/(settings.spanX())));
                y = ((Margin+rect.height()) - (((dy-settings.minY)+settings.m_nOffset)*((rect.height()-1))/(settings.spanY())));
            }
            if(( data[j].x()>=settings.minX && data[j].x()<=settings.maxX)&&(( data[j].y()>=settings.minY && data[j].y()<=settings.maxY)))
            {

            	polyline[j] = QPointF(x,y);
                l_nCounter++;
            }
        }
        QPolygonF zoomPolyline(l_nCounter);
        y =0.0,x=0.0;
        int l_nIndex1 =0;
        for(int l_nIndex=0;l_nIndex< data.count();l_nIndex++)
        {
            QPointF(x,y);
            x = polyline.at(l_nIndex).x();
            y = polyline.at(l_nIndex).y();
            //qDebug()<<x<<y;
            if(x!=0.0 || y!=0.0 )
            {
                zoomPolyline[l_nIndex1] = QPointF(x,y);
                l_nIndex1++;
            }
        }
//        if( m_nClearID == id)
//        	painter->setPen(Qt::black);
        //else
        	QPen pen;
        	painter->setPen(colorForIds[uint(id) %6]);
//        	pen.setColor(colorForIds[uint(id) %6]);
//            pen.setWidth(20);
//            painter->setPen(pen);


        if(m_ZoomFlag == false)
        {
        	painter->setPen(colorForIds[uint(id) %6]);
                painter->drawPolyline(polyline);
//            qDebug()<<"Band:"<<m_objPlotData->m_nEnvelopBand;
            //compareCurvePoints(polyline1);
        }
        else
            painter->drawPolyline(zoomPolyline);
        }
   // qDebug() << "Exit Draw Cruves.";
}
Example #11
0
void postGLTransactionsToExternal::sPost()
{
  if ( QMessageBox::critical( this, tr("Create New ICDIST File?"),
                              tr( "Creating a new Export File will delete the previous Export File.\n"
                                  "You should make sure that the previous Export Files have been imported into RW2000 before Proceeding.\n\n"
                                  "Are you sure that you want to Create a New Export File?" ),
                                  "&Yes", "&No", QString::null, 0, 1  ) != 0 )
    return;

  QFile distFile(_metrics->value("AccountingSystemExportPath") + "/ICDIST00.EXP");
  if (distFile.open(QIODevice::WriteOnly))
  {
    QString sql( "SELECT accnt_profit, accnt_number, accnt_sub,"
                 "       LPAD(SUBSTR(TEXT(gltrans_journalnumber), 1, 4), 4, '0') AS journalnumber,"
                 "       TO_CHAR(gltrans_date, 'YYYYMMDD') AS distdate,"
                 "       usr_initials,"
                 "       TRUNC((SUM(gltrans_amount) * 100), 0) AS amount "
                 "FROM accnt, usr, gltrans "
                 "WHERE ( (gltrans_accnt_id=accnt_id)"
                 " AND (NOT gltrans_exported)"
                 " AND (usr_username=CURRENT_USER)"
                 " AND (gltrans_date BETWEEN :startDate AND :endDate)" );

    if (_sourceModule->currentText() != tr("All"))
      sql += " AND (gltrans_source=:source)";

    sql += ") "
           "GROUP BY accnt_profit, accnt_number, accnt_sub, journalnumber,"
           "         distdate, usr_initials "
           "HAVING (SUM(gltrans_amount) <> 0);";

    q.prepare(sql);
    q.bindValue(":startDate", _dates->startDate());
    q.bindValue(":endDate", _dates->endDate());
    q.bindValue(":source", _sourceModule->currentText());
    q.exec();
    if (q.first())
    {
      QTextStream textStream(&distFile);
      QString     format;

      do
      {
        textStream << "8";                                                                                           //  IC-DIST-TYP (MISC-COSTS-APPLIED)
        if (_metrics->value("AccountingSystem") == "RealWorld91")
        {
          if (_metrics->value("GLProfitSize").toInt() == 0)
            textStream << "00000000";                                                                                //  IC-DIST-PFT-CTR-1
          else
          {
            format = "%0" + QString("%1").arg(_metrics->value("GLProfitSize").toInt()) + "d";
      
            textStream << QString().sprintf(format, q.value("accnt_profit").toInt());                               //  IC-DIST-PFT-CTR-1
            textStream << QString().fill('0', (8 - _metrics->value("GLProfitSize").toInt()));                        //  Filler '0's
          }

          textStream << "00000000";                                                                                  //  IC-DIST-PFT-CTR-2
        }

        format = "%0" + QString("%1").arg(_metrics->value("GLMainSize").toInt()) + "d";
        
        textStream << QString().sprintf(format, q.value("accnt_number").toInt());                                   //  IC-DIST-MAIN-ACCT-NO
        textStream << QString().fill('0', (8 - _metrics->value("GLMainSize").toInt()));                              //  Filler '0's

        if (_metrics->value("GLSubaccountSize").toInt() == 0)
          textStream << "00000000";                                                                                  //  IC-DIST-SUB-ACCT-NO
        else
        {
          format = "%0" + QString("%1").arg(_metrics->value("GLSubaccountSize").toInt()) + "d";
        
          textStream << QString().sprintf(format, q.value("accnt_sub").toInt());                                    //  IC-DIST-SUB-ACCT-NO
          textStream << QString().fill('0', (8 - _metrics->value("GLSubaccountSize").toInt()));                      //  Filler '0's
        }

        textStream << q.value("distdate").toString();                                                               //  IC-DIST-TRX-DAT
        textStream << "IC";                                                                                          //  Journal Code
        textStream << q.value("journalnumber").toString();                                                          //  IC-DIST-JRNL-NO

        if (q.value("usr_initials").toString().length())
          textStream << q.value("usr_initials").toString().leftJustify(3, ' ', TRUE);                               //  IC-DIST-USER-ID
        else
          textStream << "OMG";                                                                                       //  IC-DIST-USER-ID

        textStream << "N";                                                                                           //  IC-DIST-CORR-FLG

        if (q.value("amount").toInt() < 0)
          textStream << QString().sprintf("%014d+", abs(q.value("amount").toInt()));                                //  IC-DIST-AMT
        else
          textStream << QString().sprintf("%014d-", q.value("amount").toInt());                                     //  IC-DIST-AMT

        textStream << "N";                                                                                           //  IC-DIST-POST-TO-GL-FLG

        textStream << "\n";                                                                                          //  EOL
      }
      while (q.next());
    }

    distFile.close();
  }
  else
  {
    QMessageBox::critical( this, tr("Cannot Open Distribution File"),
                           tr( "The G/L Distribution Export file cannot be opened.  Please contact your Systems Adminstrator\n\n"
                               "G/L Transactions were NOT exported." ) );
    return;
  }

  if ( QMessageBox::information( this, tr("Mark Distributions as Posted"),
                                 tr( "A new ICDIST file has been generated in the RealWorld directory.\n"
                                     "You should now use the RealWorld icfu/icutil tool to import this file.\n"
                                     "After you have successfully imported the ICDIST file click the 'Post' button\n"
                                     "to mark these transactions as distributed.\n"
                                     "If, for any reason, you were unable to post the ICDIST file click on the\n"
                                     "'Do Not Post' button and re-export G/L Transactions to re-create the IDDIST file.\n" ),
                                     tr("&Post"), tr("Do &Not Post"), QString::null, 0, 1) == 0)
  {
    q.prepare( "UPDATE gltrans "
               "SET gltrans_exported=TRUE "
               "WHERE ( (NOT gltrans_exported)"
               " AND (gltrans_date BETWEEN :startDate AND :endDate) );" );
    q.bindValue(":startDate", _dates->startDate());
    q.bindValue(":endDate", _dates->endDate());
    q.exec();
  }

  accept();
}
bool SpriteState::exportSprite(const QString& filename, const QString& outputDir_,
                               const QString &postpScript, SpriteStateError* err) const
{
    setError(err, ErrNone);

    QFileInfo fileInfo(filename);

    QString outputDir;
    if (!outputDir_.isEmpty()) {
        outputDir = outputDir_;
    } else {
        outputDir = fileInfo.path();
    }

    QString binFileName  = outputDir + QDir::separator() + fileInfo.baseName() + ".lkob";
    QString textFileName = outputDir + QDir::separator() + fileInfo.baseName() + ".lkot";
    QString headerFileName = outputDir + QDir::separator() + "AnimNameDef_" + fileInfo.baseName() + ".h";

    QFile binOutput(binFileName);
    QFile textOutput(textFileName);
    QFile headerOutput(headerFileName);

    if (binOutput.exists()) {
        if (!binOutput.remove()) {
            qDebug() <<  "Error: SpriteState::exportSprite():"
                     << binOutput.fileName() << "already exists and cannot be removed";
            setError(err, ErrCantOpenReadWriteMode);
            return false;
        }
    }

    if (!binOutput.open(QFile::WriteOnly | QFile::Append)) {
        qDebug() <<  "Error: SpriteState::exportSprite(): could not open "
                 << binOutput.fileName() << " in WriteOnly mode";
        setError(err, ErrCantOpenReadWriteMode);
        return false;
    }

    if (!textOutput.open(QFile::WriteOnly | QFile::Text)) {
        qDebug() <<  "Error: SpriteState::exportSprite(): could not open "
                 << textOutput.fileName() << " in WriteOnly mode";
        setError(err, ErrCantOpenReadWriteMode);
        return false;
    }

    if (!headerOutput.open(QFile::WriteOnly | QFile::Text)) {
        qDebug() <<  "Error: SpriteState::exportSprite(): could not open "
                 << headerOutput.fileName() << " in WriteOnly mode";
        setError(err, ErrCantOpenReadWriteMode);
        return false;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // Export bin and text file

    QTextStream textStream(&textOutput);
    textStream << "### Exported LvkSprite ################################\n";
    textStream << "Exported LvkSprite version 0.1\n\n";

    textStream << "# Frame Pixmaps\n";
    textStream << "# format: frameId,offset(bytes),length(bytes)\n";
    textStream << "fpixmaps(\n";

    qint64 prevOffset = 0; /* previous offset */
    qint64 offset = 0;

    for (QMapIterator<Id, LvkFrame> it(_frames); it.hasNext();) {
        LvkFrame frame = it.next().value();

        // export only those frames that are used at least in one animation
        if (!isFrameUnused(frame.id)) {
            prevOffset = offset;
            writeImageWithPostprocessing(binOutput, frame, postpScript);
            offset = binOutput.size();
            textStream << "\t" <<  frame.id << "," <<  prevOffset << "," << (offset - prevOffset) << "\n";
        }
        else
        {
            qDebug() << "Omitting unused frame " << frame.id;
        }
    }
    textStream << ")\n\n";

    binOutput.close();

    textStream << "# Animations\n";
    textStream << "# format: animationId,name\n";
    textStream << "# Animation frames\n";
    textStream << "# format: aframeId,frameId,delay,ox,oy,sticky\n";
    textStream << "animations(\n";
    for (QMapIterator<Id, LvkAnimation> it(_animations); it.hasNext();) {
        it.next();
        textStream << "\t" << it.value().toString() << "\n";
        textStream << "\taframes(\n";
        for (QListIterator<LvkAframe> it2(it.value()._aframes); it2.hasNext();) {
            textStream << "\t\t" << it2.next().toString() << "\n";
        }
        textStream << "\t)\n\n";
    }
    textStream << ")\n\n";

    textStream << "### End Exported LvkSprite ############################\n";

    textOutput.close();

    /////////////////////////////////////////////////////////////////////////////////
    // Export header file

    QString headerFileMacroName = "__" + getMacroName(headerFileName) + "__";

    QTextStream headerStream(&headerOutput);
    headerStream << "// File autogenerated by " HEADER_LATEST "\n";
    headerStream << "// -- DO NOT EDIT OR MODIFY THIS FILE --\n\n";
    headerStream << "#ifndef " << headerFileMacroName << "\n";
    headerStream << "#define " << headerFileMacroName << "\n\n";

    for (QMapIterator<Id, LvkAnimation> it(_animations); it.hasNext();) {
        it.next();
        headerStream << "#define ANIM_" << getMacroName(it.value().name) << "\t\t\t\"" << it.value().name << "\"\n";
        headerStream << "#define ANIM_" << getMacroName(it.value().name) << "_FLAGS\t\t\t 0x" << QString::number(it.value().flags, 16) << "\n";
    }
    headerStream << "\n";

    if (!_customHeader.isEmpty()) {
        headerStream << "////////////////////////////////////////////////\n";
        headerStream << "// starting custom header data\n\n";
        headerStream << _customHeader << "\n";
        headerStream << "// end custom header data\n";
        headerStream << "////////////////////////////////////////////////\n";
        headerStream << "\n";
        headerStream << "\n";
    }

    headerStream << "#endif //" << headerFileMacroName << "\n";

    headerOutput.close();

    return true;
}
Example #13
0
void Statistic::onReport()
{
  ui.curOperationLabel->setText(trUtf8("Анализ отчета..."));
  setCursor(Qt::WaitCursor);
	CXSettings* settings = CXSettings::inst();

	settings->setValue(E_StartDate, QDateTime(ui.mStartDateEdit->date(), ui.mStartTimeEdit->time()));
	settings->setValue(E_EndDate, QDateTime(ui.mEndDateEdit->date(), ui.mEndTimeEdit->time()));

	QStringList xmlFiles;
#ifdef DEBUG_VER
  QString tmp = "D:/CNC_stat";
#else
  QString tmp = QApplication::applicationDirPath();
#endif
	QDir logsDir(tmp + "/" + LOG_PATH);
	//QDir logsDir(QApplication::applicationDirPath() + "/" + LOG_PATH);
	QString tempFileName;
	QStringList dirs = logsDir.entryList(QDir::Dirs);
	for (int i = 0; i < dirs.count(); ++i)
	{
		tempFileName = logsDir.path() + "/" + dirs.at(i) + "/report.xml";

		if (QFile::exists(tempFileName)) xmlFiles.append(tempFileName);
	}

	QList <SXReportError> errorList = Engine::generateReport(xmlFiles, settings->value(E_StartDate).toDateTime(), settings->value(E_EndDate).toDateTime());

//#ifndef QT_NO_DEBUG
//	ui.mErrorTree->clear();
//
//	QTreeWidgetItem* newItem = NULL;
//	QTreeWidgetItem* childItem = NULL;
//	QString lastFilename = "";
//
//	for (int i = 0; i < errorList.count(); ++i)
//	{
//		const SXReportError& curErrorData = errorList.at(i);
//
//		if ((newItem == NULL) || ((newItem != NULL) && (lastFilename != curErrorData.mFileName)))
//		{
//			newItem = new QTreeWidgetItem(ui.mErrorTree);
//			lastFilename = curErrorData.mFileName;
//			newItem->setText(0, lastFilename);
//		}
//
//		childItem = new QTreeWidgetItem(newItem);
//		childItem->setForeground(0, Qt::red);
//		childItem->setText(0, curErrorData.mError);
//
//		ui.mErrorTree->addTopLevelItem(newItem);
//	}
//#else
	QFile errorLog("errors.log");
	errorLog.open(QIODevice::WriteOnly);

	QTextStream textStream(&errorLog);
	textStream.setCodec(QTextCodec::codecForName("UTF-8"));

	for (int i = 0; i < errorList.count(); ++i)
	{
		const SXReportError& curErrorData = errorList.at(i);

		textStream << curErrorData.mFileName << "\t-\t";
		textStream << curErrorData.mError << "\n";
	}
//#endif

	ui.mReportView->setHtml(Engine::getReportText());
	ui.curOperationLabel->setText(trUtf8("Нет текущих операций"));
	setCursor(Qt::ArrowCursor);
}
//---------------------------------------------------------------------
// TODO factor code out of here and into its own class for loading and
//      saving PLY files (additional code in stereo/multiviewstereo.cpp)
//
void MainWindow::on_actionView_PLY_File_triggered() {
	QString initialDir = userSettings.contains("InitialPLYDir")
	                     ? userSettings.value("InitialPLYDir").toString()
	                     : QDir::homePath();

	// TODO sheets would be nice for Mac users :)
	QString fname = QFileDialog::getOpenFileName(this,
	                                             tr("Open File"),
	                                             initialDir,
	                                             "PLY Files (*.ply)");

	if(!fname.isNull()) {
		QFile file(fname);
		if(file.open(QFile::ReadOnly)) {
			userSettings.setValue("InitialPLYDir", QDir(fname).absolutePath());

			QTextStream textStream(&file);

			// For now we'll ignore the header and assume a certain format
			QString line;
			bool hasNormal = false;
			bool hasColor = false;
			bool isBinary = false;

			unsigned int numVertices = 0;
			unsigned int numFaces = 0;

			static QRegExp typeTest("n[xyz]");
			static QRegExp normalTest("n[xyz]");
			static QRegExp colorTest("diffuse_(red|blue|green)");
			static QRegExp elementTest("element (vertex|face) (\\d+)");

			while((line = textStream.readLine().trimmed()) != "end_header") {
				if(line.startsWith("property")) {
					if( line.contains(normalTest) )
						hasNormal = true;

					if( line.contains(colorTest) )
						hasColor = true;
				} else if(elementTest.indexIn(line) != -1) {
					if(elementTest.cap(1) == "face")
						numFaces = elementTest.cap(2).toUInt();
					else if(elementTest.cap(1) == "vertex")
						numVertices = elementTest.cap(2).toUInt();
				} else if(line.startsWith("format")) {
					isBinary = line.contains("binary");
				}
			}

			QDataStream dataStream;
			if(isBinary) {
				qint64 pos = textStream.pos();
				file.close();
				file.open(QFile::ReadOnly);
				dataStream.setDevice(&file);
				dataStream.skipRawData(pos);
			}

			//
			// Read in the verticies
			//
			GLfloat d[9] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
			std::vector<GLfloat> vertices(numVertices * 9);
			std::vector<GLfloat>::iterator vertexIter = vertices.begin();
			if(isBinary) {
				uint len = 12 + (hasNormal ? 12 : 0) + (hasColor ? 3 : 0);

				// TODO more efficient to read in larger chunk of data
				for(unsigned int vertex = 0; vertex < numVertices && !textStream.atEnd(); ++vertex) {
					dataStream.readRawData(reinterpret_cast<char *>(d), len);
					if(!hasNormal)
						d[3] = d[4] = d[5] = 0;

					if(!hasColor)
						d[6] = d[7] = d[8] = 1;

					if(dataStream.status() != QDataStream::ReadPastEnd)
						vertexIter = std::copy(d, d + 9, vertexIter);
				}
			} else {
				for(unsigned int vertex = 0; vertex < numVertices && !textStream.atEnd(); ++vertex) {
					textStream >> d[0] >> d[1] >> d[2];
					if(hasNormal)
						textStream >> d[3] >> d[4] >> d[5];
					else
						d[3] = d[4] = d[5] = 0.0f;

					if(hasColor) {
						textStream >> d[6] >> d[7] >> d[8];
						d[6] /= 255.0;
						d[7] /= 255.0;
						d[8] /= 255.0;
					} else {
						d[6] = d[7] = d[8] = 0.5f;
						//d[6] = qrand() / (1.0*RAND_MAX);
						//d[7] = qrand() / (1.0*RAND_MAX);
						//d[8] = qrand() / (1.0*RAND_MAX);
					}

					if(textStream.status() != QTextStream::ReadPastEnd)
						vertexIter = std::copy(d, d + 9, vertexIter);

					textStream.readLine();
				}
Example #15
0
void ShortLocater::Initializations(){

	IPsoc->resetRelays();
	IPsoc->srcImpedanceSelection(SRC_IMP_0E);
//	IPsoc->shLocatorDetection();
    m_nADCtimer = new QTimer(this);

    IBackPlane->writeBackPlaneRegister(0x0FFF,0x001E);//clear all interrupts
    IBackPlane->writeBackPlaneRegister(0x0000,0x0020);//disable all interrupts
    IBackPlane->writeBackPlaneRegister(0x0000,0x0024);//disable global interrupt
    IBackPlane->writeBackPlaneRegister(0x0100,0x0020);//enabling psoc INT0embedded key interrupt)

    IPTKeyEvent->InvokeGPIOEvent(this,"/dev/input/event2","pt_kpp",&m_nPTKeyCode);
    IGPIOEvent->InvokeGPIOEvent(this,"/dev/input/event7","gpioevent",&m_nGPIOCode);
    IBackPlane->writeBackPlaneRegister(0x0001,0x0024);

    //        IBackPlane->writeBackPlaneRegister();
    ohms=QChar(0x2126);
    micro=QChar(0x00B5);

    //~~~~~~~~~~~~~Reading Short Values from File~~~~~~~~~~~~~~~~~~~~~~
	QStringList stringList;
	bool ok=true;
	QFile textFile;
   	textFile.setFileName("shortValuesI.txt");

    if (textFile.open(QIODevice::ReadOnly))
    {
        QTextStream textStream(&textFile);
        while (!textStream.atEnd())
        {
            stringList.append(textStream.readLine());
        }
        r200EShortValue=stringList.value(0).toDouble(&ok);
        qDebug()<<"200E Short Value:"<<r200EShortValue;
        r2EShortValue=stringList.value(1).toDouble(&ok);
        qDebug()<<"2E Short Value:"<<r2EShortValue;
       	r200mEShortValue=stringList.value(2).toDouble(&ok);
        qDebug()<<"200mE Short Value:"<<r200mEShortValue;
    }else{
        r200EShortValue=r200mEShortValue=r2EShortValue=0.0;
    }
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //~~~~~~~~Check for debug panel~~~~~~~~~~~~~~~~~~~~~~~~
    QStringList debugPanel;
    QFile textFile2("debugPanel.txt");
    if (textFile2.open(QIODevice::ReadOnly))
    {
        QTextStream textStream(&textFile2);
        while (!textStream.atEnd())
        {
            debugPanel.append(textStream.readLine());
            if(debugPanel.value(0)=="1")
                ToolBox(true);
            else
                ToolBox(false);
        }
    }else{
        ToolBox(false);
    }
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    IDMMLib->ApplyDACOffset(false);

    dis->setValue("OL");
    IBackPlane->writeBackPlaneRegister(0x0,0x16);
    //	Beep(false);

    AutoFlag=false;
    on_Auto_clicked();

    OffsetFlag=false;
    BuzzerFlag=false;
    msgBoxLive=false;

    ui.progressBar_2->setValue(0);
    for(int i=0;i<100;i++)
        avgRetval[i]=0.0;

    retval=retval2=retval3=0.0;
    nullify=0.0;
    nullit=0.0;
    avg=0;

    noOFsamples=1;

    rangePrevValue=33;

    ui.uE->setText(micro+ohms);

    on_r200But_clicked();
    ui.holdCap->setVisible(false);
    runFlag=true;
    startStop();

	ui.openShortEnable->setChecked(true);

	m_nAvgCount=0;
	movingAverage=5;

	ui.splashWidget->setVisible(false);
		usleep(1000);

}
Example #16
0
void ShortLocater::on_Internal_clicked()
{

/*
            IPsoc->resetRelays();
            usleep(500);
            IPsoc->writeSerial(0x42);
            IPsoc->writeSerial(0x9);
            usleep(500);
            IPsoc->writeSerial(0x42);
            IPsoc->writeSerial(0x15);
            usleep(500);
            IPsoc->writeSerial(0x42);
            IPsoc->writeSerial(0x13);
*/			IPsoc->switchFly();

            ui.Internal->setVisible(false);
            ui.External->setVisible(true);
    		ui.ah1_inner->setVisible(false);
    		ui.ah1_outer->setStyleSheet("border:1px solid gray;border-radius:20px;image: url(:/fp_images/bnc.png);");
    		ui.ah1_outer->setGeometry(22,26,41,41);

    		ui.ah2_inner->setVisible(false);
    		ui.ah2_outer->setStyleSheet("border:1px solid gray;border-radius:20px;image: url(:/fp_images/bnc.png);");
    		ui.ah2_outer->setGeometry(96,26,41,41);

    		ui.ah3_inner->setVisible(false);
    		ui.ah3_outer->setStyleSheet("border:1px solid gray;border-radius:20px;image: url(:/fp_images/bnc.png);");
    		ui.ah3_outer->setGeometry(167,26,41,41);

    		ui.ah0_inner->setVisible(false);
    		ui.ah0_outer->setStyleSheet("border:1px solid gray;border-radius:20px;image: url(:/fp_images/bnc.png);");
    		ui.ah0_outer->setGeometry(237,26,41,41);

    		ui.fp_VI1_ICM_SL->setGeometry(24,20,41,41);
    		ui.fp_VI1_ICM_SL->setStyleSheet("border:1px solid gray;border-radius:20px;image: url(:/new/prefix1/Button-Blank-Gray-icon.png);");

    		ui.fp_VI2_EXT->setGeometry(110,20,41,41);
    		ui.fp_VI2_EXT->setStyleSheet("border:1px solid gray;border-radius:20px;image: url(:/new/prefix1/Button-Blank-Gray-icon.png);");

    		QStringList stringList;
    		bool ok=true;
    		QFile textFile;
    	    if(ui.External->isVisible())
    	    	textFile.setFileName("shortValuesE.txt");
    	    if(ui.Internal->isVisible())
    	    	textFile.setFileName("shortValuesI.txt");

    	    if (textFile.open(QIODevice::ReadOnly))
    	    {
    	        QTextStream textStream(&textFile);
    	        while (!textStream.atEnd())
    	        {
    	            stringList.append(textStream.readLine());
    	        }
    	        r200EShortValue=stringList.value(0).toDouble(&ok);
    	        qDebug()<<"200E Short Value:"<<r200EShortValue;
    	        r2EShortValue=stringList.value(1).toDouble(&ok);
    	        qDebug()<<"2E Short Value:"<<r2EShortValue;
    	       	r200mEShortValue=stringList.value(2).toDouble(&ok);
    	        qDebug()<<"200mE Short Value:"<<r200mEShortValue;
    	    }else{
    	        r200EShortValue=r200mEShortValue=r2EShortValue=0.0;
    	    }

}