Example #1
0
QVariant QDbfSqlModel::data(const QModelIndex &index, int role) const
{

    QVariant value = QSqlQueryModel::data(index, role);
    int i,j,k;

    QByteArray tempDateArray;
    QDate tempDate;
    QTime tempTime;
    quint32 l;
    qint32 l1;
    qint64 l2;
    double db;
    bool ok;
    QString currency;
    //QLocale clocale(QLocale::German);
    QLocale clocale(QLocale::C);
    quint8 r,g,b;
    QByteArray tempByteArray;

    //QList<int> charFields;
    for (i=0;i<charFields.count();i++)
        {
            if (index.column() == charFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignLeft | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(charFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> currencyFields;
    for (i=0;i<currencyFields.count();i++)
        {
            if (index.column() == currencyFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                tempDateArray = value.toByteArray();
                                tempDateArray = QByteArray::fromHex(tempDateArray);

                                l2 = *(qint64 *)tempDateArray.data();

                                db = l2;
                                currency.setNum(db/10000,'f',4);

                                value = clocale.toString(db/10000,'f',4);
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(currencyFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> numericFields;
    for (i=0;i<numericFields.count();i++)
        {
            if (index.column() == numericFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                currency=value.toString().simplified();
                                k=currency.count()-1;
                                j=0;
                                ok=false;
                                while (k>0)
                                    {
                                        if (currency.at(k) == '.')
                                            {
                                                ok = true;
                                                break;
                                            }
                                        k--;
                                        j++;
                                    }
                                if (!ok) j=0;
                                value = clocale.toString(currency.toDouble(&ok),'f',j);
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(numericFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> dateFields;
    for (i=0;i<dateFields.count();i++)
        {
            if (index.column() == dateFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                value = value.toDate().toString("dd.MM.yyyy");
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(dateFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> timeFields;
    for (i=0;i<timeFields.count();i++)
        {
            if (index.column() == timeFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                tempDateArray = value.toByteArray();
                                tempDateArray = QByteArray::fromHex(tempDateArray);

                                l = *(quint32 *)tempDateArray.data();

                                tempDate = QDate::fromJulianDay(l);

                                l = *(quint32 *)(tempDateArray.data()+4);

                                tempTime.setHMS(0,0,0);
                                tempTime = tempTime.addMSecs(l);

                                value = tempDate.toString("dd.MM.yyyy")+" "+tempTime.toString("hh:mm:ss.zzz");

                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:                                
                                tempByteArray.append(timeFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> doubleFields;
    for (i=0;i<doubleFields.count();i++)
        {
            if (index.column() == doubleFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                tempDateArray = value.toByteArray();
                                tempDateArray = QByteArray::fromHex(tempDateArray);

                                db = *(double *)tempDateArray.data();

                                value = db;
                                //value = clocale.toString(db,'f',4);
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(doubleFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> intFields;
    for (i=0;i<intFields.count();i++)
        {
            if (index.column() == intFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                tempDateArray = value.toByteArray();
                                tempDateArray = QByteArray::fromHex(tempDateArray);

                                l1 = *(quint32 *)tempDateArray.data();

                                value = l1;

                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(intFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> logicalFields;
    for (i=0;i<logicalFields.count();i++)
        {
            if (index.column() == logicalFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(logicalFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> memoFields;
    for (i=0;i<memoFields.count();i++)
        {
            if (index.column() == memoFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(memoFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> memo4Fields;
    for (i=0;i<memo4Fields.count();i++)
        {
            if (index.column() == memo4Fields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                tempDateArray = value.toByteArray();
                                tempDateArray = QByteArray::fromHex(tempDateArray);

                                l = *(quint32 *)tempDateArray.data();

                                value = l;

                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(memo4FieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> generalFields;
    for (i=0;i<generalFields.count();i++)
        {
            if (index.column() == generalFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(generalFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    return value;
}
Example #2
0
//------------------------------------------------------------------------------
void GeoWidgetVariogram::slot_nugget(QString d)
{
    cur_set_vario.nuget_c0 = d.toDouble();
    graph->set_function(cur_set_vario);
    graph->repaint();
}
Example #3
0
//------------------------------------------------------------------------------
void GeoWidgetVariogram::slot_range(QString d)
{
    cur_set_vario.range_a = d.toDouble();
    graph->set_function(cur_set_vario);
    graph->repaint();
}
Example #4
0
void QgsProjectFileTransform::convertRasterProperties( QDomDocument& doc, QDomNode& parentNode,
    QDomElement& rasterPropertiesElem, QgsRasterLayer* rlayer )
{
  //no data
  //TODO: We would need to set no data on all bands, but we don't know number of bands here
  QDomNode noDataNode = rasterPropertiesElem.namedItem( QStringLiteral( "mNoDataValue" ) );
  QDomElement noDataElement = noDataNode.toElement();
  if ( !noDataElement.text().isEmpty() )
  {
    QgsDebugMsg( "mNoDataValue = " + noDataElement.text() );
    QDomElement noDataElem = doc.createElement( QStringLiteral( "noData" ) );

    QDomElement noDataRangeList = doc.createElement( QStringLiteral( "noDataRangeList" ) );
    noDataRangeList.setAttribute( QStringLiteral( "bandNo" ), 1 );

    QDomElement noDataRange =  doc.createElement( QStringLiteral( "noDataRange" ) );
    noDataRange.setAttribute( QStringLiteral( "min" ), noDataElement.text() );
    noDataRange.setAttribute( QStringLiteral( "max" ), noDataElement.text() );
    noDataRangeList.appendChild( noDataRange );

    noDataElem.appendChild( noDataRangeList );

    parentNode.appendChild( noDataElem );
  }

  QDomElement rasterRendererElem = doc.createElement( QStringLiteral( "rasterrenderer" ) );
  //convert general properties

  //invert color
  rasterRendererElem.setAttribute( QStringLiteral( "invertColor" ), QStringLiteral( "0" ) );
  QDomElement  invertColorElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "mInvertColor" ) );
  if ( !invertColorElem.isNull() )
  {
    if ( invertColorElem.text() == QLatin1String( "true" ) )
    {
      rasterRendererElem.setAttribute( QStringLiteral( "invertColor" ), QStringLiteral( "1" ) );
    }
  }

  //opacity
  rasterRendererElem.setAttribute( QStringLiteral( "opacity" ), QStringLiteral( "1" ) );
  QDomElement transparencyElem = parentNode.firstChildElement( QStringLiteral( "transparencyLevelInt" ) );
  if ( !transparencyElem.isNull() )
  {
    double transparency = transparencyElem.text().toInt();
    rasterRendererElem.setAttribute( QStringLiteral( "opacity" ), QString::number( transparency / 255.0 ) );
  }

  //alphaBand was not saved until now (bug)
  rasterRendererElem.setAttribute( QStringLiteral( "alphaBand" ), -1 );

  //gray band is used for several renderers
  int grayBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mGrayBandName" ), rlayer );

  //convert renderer specific properties
  QString drawingStyle = rasterPropertiesElem.firstChildElement( QStringLiteral( "mDrawingStyle" ) ).text();

  // While PalettedColor should normally contain only integer values, usually
  // color palette 0-255, it may happen (Tim, issue #7023) that it contains
  // colormap classification with double values and text labels
  // (which should normally only appear in SingleBandPseudoColor drawingStyle)
  // => we have to check first the values and change drawingStyle if necessary
  if ( drawingStyle == QLatin1String( "PalettedColor" ) )
  {
    QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "customColorRamp" ) );
    QDomNodeList colorRampEntryList = customColorRampElem.elementsByTagName( QStringLiteral( "colorRampEntry" ) );

    for ( int i = 0; i < colorRampEntryList.size(); ++i )
    {
      QDomElement colorRampEntryElem = colorRampEntryList.at( i ).toElement();
      QString strValue = colorRampEntryElem.attribute( QStringLiteral( "value" ) );
      double value = strValue.toDouble();
      if ( value < 0 || value > 10000 || !qgsDoubleNear( value, static_cast< int >( value ) ) )
      {
        QgsDebugMsg( QString( "forcing SingleBandPseudoColor value = %1" ).arg( value ) );
        drawingStyle = QStringLiteral( "SingleBandPseudoColor" );
        break;
      }
    }
  }

  if ( drawingStyle == QLatin1String( "SingleBandGray" ) )
  {
    rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "singlebandgray" ) );
    rasterRendererElem.setAttribute( QStringLiteral( "grayBand" ), grayBand );
    transformContrastEnhancement( doc, rasterPropertiesElem, rasterRendererElem );
  }
  else if ( drawingStyle == QLatin1String( "SingleBandPseudoColor" ) )
  {
    rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "singlebandpseudocolor" ) );
    rasterRendererElem.setAttribute( QStringLiteral( "band" ), grayBand );
    QDomElement newRasterShaderElem = doc.createElement( QStringLiteral( "rastershader" ) );
    QDomElement newColorRampShaderElem = doc.createElement( QStringLiteral( "colorrampshader" ) );
    newRasterShaderElem.appendChild( newColorRampShaderElem );
    rasterRendererElem.appendChild( newRasterShaderElem );

    //switch depending on mColorShadingAlgorithm
    QString colorShadingAlgorithm = rasterPropertiesElem.firstChildElement( QStringLiteral( "mColorShadingAlgorithm" ) ).text();
    if ( colorShadingAlgorithm == QLatin1String( "PseudoColorShader" ) || colorShadingAlgorithm == QLatin1String( "FreakOutShader" ) )
    {
      newColorRampShaderElem.setAttribute( QStringLiteral( "colorRampType" ), QStringLiteral( "INTERPOLATED" ) );

      //get minmax from rasterlayer
      QgsRasterBandStats rasterBandStats = rlayer->dataProvider()->bandStatistics( grayBand );
      double minValue = rasterBandStats.minimumValue;
      double maxValue = rasterBandStats.maximumValue;
      double breakSize = ( maxValue - minValue ) / 3;

      QStringList colorList;
      if ( colorShadingAlgorithm == QLatin1String( "FreakOutShader" ) )
      {
        colorList << QStringLiteral( "#ff00ff" ) << QStringLiteral( "#00ffff" ) << QStringLiteral( "#ff0000" ) << QStringLiteral( "#00ff00" );
      }
      else //pseudocolor
      {
        colorList << QStringLiteral( "#0000ff" ) << QStringLiteral( "#00ffff" ) << QStringLiteral( "#ffff00" ) << QStringLiteral( "#ff0000" );
      }
      QStringList::const_iterator colorIt = colorList.constBegin();
      double boundValue = minValue;
      for ( ; colorIt != colorList.constEnd(); ++colorIt )
      {
        QDomElement newItemElem = doc.createElement( QStringLiteral( "item" ) );
        newItemElem.setAttribute( QStringLiteral( "value" ), QString::number( boundValue ) );
        newItemElem.setAttribute( QStringLiteral( "label" ), QString::number( boundValue ) );
        newItemElem.setAttribute( QStringLiteral( "color" ), *colorIt );
        newColorRampShaderElem.appendChild( newItemElem );
        boundValue += breakSize;
      }
    }
    else if ( colorShadingAlgorithm == QLatin1String( "ColorRampShader" ) )
    {
      QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "customColorRamp" ) );
      QString type = customColorRampElem.firstChildElement( QStringLiteral( "colorRampType" ) ).text();
      newColorRampShaderElem.setAttribute( QStringLiteral( "colorRampType" ), type );
      QDomNodeList colorNodeList = customColorRampElem.elementsByTagName( QStringLiteral( "colorRampEntry" ) );

      QString value, label;
      QColor newColor;
      int red, green, blue;
      QDomElement currentItemElem;
      for ( int i = 0; i < colorNodeList.size(); ++i )
      {
        currentItemElem = colorNodeList.at( i ).toElement();
        value = currentItemElem.attribute( QStringLiteral( "value" ) );
        label = currentItemElem.attribute( QStringLiteral( "label" ) );
        red = currentItemElem.attribute( QStringLiteral( "red" ) ).toInt();
        green = currentItemElem.attribute( QStringLiteral( "green" ) ).toInt();
        blue = currentItemElem.attribute( QStringLiteral( "blue" ) ).toInt();
        newColor = QColor( red, green, blue );
        QDomElement newItemElem = doc.createElement( QStringLiteral( "item" ) );
        newItemElem.setAttribute( QStringLiteral( "value" ), value );
        newItemElem.setAttribute( QStringLiteral( "label" ), label );
        newItemElem.setAttribute( QStringLiteral( "color" ), newColor.name() );
        newColorRampShaderElem.appendChild( newItemElem );
      }
    }
  }
  else if ( drawingStyle == QLatin1String( "PalettedColor" ) )
  {
    rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "paletted" ) );
    rasterRendererElem.setAttribute( QStringLiteral( "band" ), grayBand );
    QDomElement customColorRampElem = rasterPropertiesElem.firstChildElement( QStringLiteral( "customColorRamp" ) );
    QDomNodeList colorRampEntryList = customColorRampElem.elementsByTagName( QStringLiteral( "colorRampEntry" ) );
    QDomElement newColorPaletteElem = doc.createElement( QStringLiteral( "colorPalette" ) );

    int red = 0;
    int green = 0;
    int blue = 0;
    int value = 0;
    QDomElement colorRampEntryElem;
    for ( int i = 0; i < colorRampEntryList.size(); ++i )
    {
      colorRampEntryElem = colorRampEntryList.at( i ).toElement();
      QDomElement newPaletteElem = doc.createElement( QStringLiteral( "paletteEntry" ) );
      value = static_cast< int >( colorRampEntryElem.attribute( QStringLiteral( "value" ) ).toDouble() );
      newPaletteElem.setAttribute( QStringLiteral( "value" ), value );
      red = colorRampEntryElem.attribute( QStringLiteral( "red" ) ).toInt();
      green = colorRampEntryElem.attribute( QStringLiteral( "green" ) ).toInt();
      blue = colorRampEntryElem.attribute( QStringLiteral( "blue" ) ).toInt();
      newPaletteElem.setAttribute( QStringLiteral( "color" ), QColor( red, green, blue ).name() );
      QString label = colorRampEntryElem.attribute( QStringLiteral( "label" ) );
      if ( !label.isEmpty() )
      {
        newPaletteElem.setAttribute( QStringLiteral( "label" ), label );
      }
      newColorPaletteElem.appendChild( newPaletteElem );
    }
    rasterRendererElem.appendChild( newColorPaletteElem );
  }
  else if ( drawingStyle == QLatin1String( "MultiBandColor" ) )
  {
    rasterRendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "multibandcolor" ) );

    //red band, green band, blue band
    int redBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mRedBandName" ), rlayer );
    int greenBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mGreenBandName" ), rlayer );
    int blueBand = rasterBandNumber( rasterPropertiesElem, QStringLiteral( "mBlueBandName" ), rlayer );
    rasterRendererElem.setAttribute( QStringLiteral( "redBand" ), redBand );
    rasterRendererElem.setAttribute( QStringLiteral( "greenBand" ), greenBand );
    rasterRendererElem.setAttribute( QStringLiteral( "blueBand" ), blueBand );

    transformContrastEnhancement( doc, rasterPropertiesElem, rasterRendererElem );
  }
  else
  {
    return;
  }

  //replace rasterproperties element with rasterrenderer element
  if ( !parentNode.isNull() )
  {
    parentNode.replaceChild( rasterRendererElem, rasterPropertiesElem );
  }
}
Example #5
0
void Calculatrice::fonctionBoutonInt() {
	QString nbtxt = ligne->text();
	double nombre = nbtxt.toDouble();
	nombre = floor(nombre);
	ligne->setText(QString::number(nombre));
}
Example #6
0
unsigned int TokenBuilder::buildNumber(QString str)
{
	parserlval.number = str.toDouble();
	return NUMBER;
}
void AddIncomeExpenseDialog::setValue(const QString& v) {
	qDebug() << "AddIncomeExpenseDialog::setValue()";
	ui->doubleSpinBox_value->setValue(v.toDouble());
}
bool Commentaire::generateReplaceVBS(){

    QString filename = pathSyst+"replace.vbs";

    cmdDos("del \""+filename+"\"");

    QFile file(filename);
    //on a besoin de caster ces valeurs pour qu'elles correspondent au excel qui ne prend pas les doubles, mais les int.

    int prixNomAff = static_cast<int>(currentProduit->getPrixTotNomAffaire());
    int prixNomFG = static_cast<int>(currentProduit->getPrixTotNomFG());
    int prixVenteMarcheCast = static_cast<int>(currentProduit->getPrixVenteMarche());
    QString prixVenteMarche = (currentProduit->getCurrentMarche().getName() == "") ? // si on a un marché, on met dans la variable le prix de vente du marché,
                                                                                     //si on ne l'a pas, on met la chaine de caractére " "
                                                                                     " ":
                                                                                     QString::number(prixVenteMarcheCast)  ;

    //Et oui! QT a besoin de doubles avec des points pour faire ses opérations, mais excel, lui a besoin de virgules! C'est magnifique!!!^ ^
    QString fraisDSS = QString::number(database->getListFrais().value(0).getPourcentage()).
            replace(".",",");
    QString fraisFin = QString::number(database->getListFrais().value(1).getPourcentage()).
            replace(".",",");
    QString fraisDir = QString::number(database->getListFrais().value(2).getPourcentage()).
            replace(".",",");
    QString fraisGen = QString::number(database->getListFrais().value(3).getPourcentage()).
            replace(".",",");


    QString coutHCdp = QString::number(database->getListMdo().value(0).getCoutH()).
            replace(".",",");
    QString coutHTech = QString::number(database->getListMdo().value(1).getCoutH()).
            replace(".",",");
    QString coutHOuv = QString::number(database->getListMdo().value(2).getCoutH()).
            replace(".",",");


    if (file.open(QIODevice::ReadWrite)) {
        QTextStream stream(&file);

        stream << "strFilename=WScript.Arguments.Item(0)\n"<<
                  "strFilename1=WScript.Arguments.Item(1)\n"<<

                  /******************SHEET2**********************/



                  "Const FromValue0 = \"nomProduit\"\n"<<
                  "Const ToValue0 = \""+currentProduit->getName()+"\"\n"<<

                  "Const FromValue = \"qteProduit\"\n"<<
                  "Const ToValue = \""+QString::number(currentProduit->getQte())+"\"\n"<<

                  "Const FromValue1 = \"mdoTech\"\n"<<

                  "Const ToValue1 = \""+QString::number(currentProduit->getNbHTech()*currentProduit->getQte())
                  .replace(".",",")+ "\"\n"<<

                  //et oui, excel ne comprends pas les "." pour les chiffres, donc on est obligé de lui passer en string...

                  "Const FromValue2 = \"mdoCdp\"\n"<<
                  "Const ToValue2 = \""+QString::number(currentProduit->getNbHCdp()*currentProduit->getQte())
                  .replace(".",",")+ "\"\n"<<

                  "Const FromValue3 = \"mdoOuv\"\n"<<
                  "Const ToValue3 = \""+QString::number(currentProduit->getNbHOuv()*currentProduit->getQte())
                  .replace(".",",")+ "\"\n"<<

                  "Const FromValue31 = \"codeProduit\"\n"<<
                  "Const ToValue31 = \""+currentProduit->getTag()+"_"
                  +currentProduit->readCode()
                  + "\"\n"<<



                  /******************SHEET3**********************/


                  "Const FromValue5 = \"fournitureAffaire\"\n"<<
                  "Const ToValue5 = "+QString::number(prixNomAff*currentProduit->getQte())+ "\n"<<

                  "Const FromValue6 = \"fournitureFG\"\n"<<
                  "Const ToValue6 = "+QString::number(prixNomFG*currentProduit->getQte())+ "\n"<<

                  "Const FromValue7 = \"prixVente\"\n"<<
                  "Const ToValue7 = \""+QString::number(prixVenteMarche.toDouble(0)
                                                        *currentProduit->getQte())+"\"\n"<<

                  /******************SHEET4**********************/


                  "Const FromValue8 = \"fraisDSS\"\n"<<
                  "Const ToValue8 = \""+fraisDSS+ "\"\n"<<

                  "Const FromValue9 = \"fraisFin\"\n"<<
                  "Const ToValue9 = \""+fraisFin+ "\"\n"<<

                  "Const FromValue10 = \"fraisDir\"\n"<<
                  "Const ToValue10 = \""+fraisDir+"\"\n"<<

                  "Const FromValue100 = \"fraisGeneraux\"\n"<<
                  "Const ToValue100 = \""+fraisGen+"\"\n"<<

                  "Const FromValue101 = \"coutHCdp\"\n"<<
                  "Const ToValue101 = \""+coutHCdp+ "\"\n"<<

                  "Const FromValue102 = \"coutHTech\"\n"<<
                  "Const ToValue102 = \""+coutHTech+ "\"\n"<<

                  "Const FromValue103 = \"coutHOuv\"\n"<<
                  "Const ToValue103 = \""+coutHOuv+"\"\n"<<

                  /******************SHEET5**********************/

                  "Const FromValue11 = \"vProd\"\n"<<
                  "Const ToValue11 = \""+currentProduit->getVersionProduitXML()+ "\"\n"<<

                  "Const FromValue12 = \"vNom\"\n"<<
                  "Const ToValue12 = \""+currentProduit->getVersionNomenclatureXML()+ "\"\n"<<

                  "Const FromValue13 = \"vOp\"\n"<<
                  "Const ToValue13 = \""+currentProduit->getVersionOperationXML()+"\"\n"<<

                  "Const FromValue14 = \"vMarch\"\n"<<
                  "Const ToValue14 = \""+currentProduit->getVersionMarcheXML()+ "\"\n"<<

                  "Const FromValue15 = \"vConf\"\n"<<
                  "Const ToValue15 = \""+database->getVersionConfXML()+"\"\n"<<

                  /******************SHEET8**********************/

                  "Const FromValue16 = \"nomMarche\"\n"<<
                  "Const ToValue16 = \""+currentProduit->getCurrentMarche().getName()+ "\"\n"<<



                  /******************REPLACE**********************/

                  "Dim objXLApp, objXLWb\n"<<
                  "Set objXLApp = CreateObject(\"Excel.Application\")\n"<<

                  "objXLApp.Visible = False\n"<<

                  "Set objXLWb = objXLApp.Workbooks.Open(strFilename)\n"<<
                  "Dim objXLWs2 : Set objXLWs2 = objXLWb.Worksheets(2)\n"<<
                  "objXLWs2.Cells.Replace FromValue0, ToValue0\n"<<
                  "objXLWs2.Cells.Replace FromValue, ToValue\n"<<
                  "objXLWs2.Cells.Replace FromValue1, ToValue1\n"<<
                  "objXLWs2.Cells.Replace FromValue2, ToValue2\n"<<
                  "objXLWs2.Cells.Replace FromValue3, ToValue3\n"<<
                  "objXLWs2.Cells.Replace FromValue31, ToValue31\n"<<

                  "Dim objXLWs3 : Set objXLWs3 = objXLWb.Worksheets(3)\n"<<
                  "objXLWs3.Cells.Replace FromValue5, ToValue5\n"<<
                  "objXLWs3.Cells.Replace FromValue6, ToValue6\n"<<
                  "objXLWs3.Cells.Replace FromValue7, ToValue7\n"<<

                  "Dim objXLWs4 : Set objXLWs4 = objXLWb.Worksheets(4)\n"<<
                  "objXLWs4.Cells.Replace FromValue8, ToValue8\n"<<
                  "objXLWs4.Cells.Replace FromValue9, ToValue9\n"<<
                  "objXLWs4.Cells.Replace FromValue10, ToValue10\n"<<
                  "objXLWs4.Cells.Replace FromValue100, ToValue100\n"<<
                  "objXLWs4.Cells.Replace FromValue101, ToValue101\n"<<
                  "objXLWs4.Cells.Replace FromValue102, ToValue102\n"<<
                  "objXLWs4.Cells.Replace FromValue103, ToValue103\n"<<

                  "Dim objXLWs5 : Set objXLWs5 = objXLWb.Worksheets(5)\n"<<
                  "objXLWs5.Cells.Replace FromValue11, ToValue11\n"<<
                  "objXLWs5.Cells.Replace FromValue12, ToValue12\n"<<
                  "objXLWs5.Cells.Replace FromValue13, ToValue13\n"<<
                  "objXLWs5.Cells.Replace FromValue14, ToValue14\n"<<
                  "objXLWs5.Cells.Replace FromValue15, ToValue15\n"<<

                  "Dim objXLWs6 : Set objXLWs6 = objXLWb.Worksheets(6)\n"<<
                  generateFillNomenclatureFG()<<

                  "Dim objXLWs7 : Set objXLWs7 = objXLWb.Worksheets(7)\n"<<
                  generateFillNomenclatureAffaire()<<

                  "Dim objXLW8 : Set objXLWs8 = objXLWb.Worksheets(8)\n"<<
                  generateFillBordereau()<<
                  "objXLWs8.Cells.Replace FromValue16, ToValue16\n"<<

                  "objXLApp.DisplayAlerts = False\n"<<
                  "objXLWb.SaveAs strFilename1, 51\n"<<
                  "objXLApp.Quit"
               << endl;
    }

    if(!file.exists()){
        QMessageBox::critical(this,"Erreur génération replace.vbs",
                              "Impossible de générer replace.vbs");
        return false;
    }
    return true;
}
void CUcontent_Adjustments::setupAdjustmentsTable()
{
	bool enable = false;
	bool ok = false;
	unsigned char k = 0;
	QTableWidgetItem *tableItem = NULL;
	ModQDoubleSpinBox *spinBox = NULL;
	QComboBox *comboBox = NULL;
	QIdPushButton *saveButton = NULL;
	QPushButton *resetButton = NULL;
	QPixmap leftIcon, rightIcon;
	QPixmap mergedIcon(54, 22);
	QStringList selectableScaledValueStr;
	QString helpScaledValueStr = 0;
	double minScaledValue = 0;
	double maxScaledValue = 0;
	double defaultScaledValue = 0;
	double minSingleStepFromPrecision = 0;
	double minSingleStepFromRaw = 0;
	bool calcerror = false;

	// Create "Save"-icon:
	leftIcon.load( QString::fromUtf8(":/icons/oxygen/22x22/go-next.png") );
	rightIcon.load( QString::fromUtf8(":/icons/oxygen/22x22/drive-harddisk.png") );
	mergedIcon.fill(Qt::transparent);
	QPainter painter(&mergedIcon);
	painter.drawTiledPixmap( 0, 0, 22, 22, leftIcon );
	painter.drawTiledPixmap( 32, 0, 22, 22, rightIcon );
	QIcon saveButton_icon( mergedIcon );
	// Create "Reset"-icon:
	leftIcon.load( QString::fromUtf8(":/icons/oxygen/22x22/go-first.png") );
	mergedIcon.fill(Qt::transparent);
	painter.drawTiledPixmap( 0, 0, 22, 22, leftIcon );
	painter.drawTiledPixmap( 32, 0, 22, 22, rightIcon );
	QIcon resetButton_icon( mergedIcon );
	// Clear Table:
	adjustments_tableWidget->clearContents();
	// Enable/Disable GUI-elements:
	title_label->setEnabled( enable );
	adjustments_tableWidget->setEnabled( enable );
	nonPermanentInfo_label->setEnabled( enable );
	// Increase nr. of table rows if necessary:
	if (_supportedAdjustments.size() && (static_cast<unsigned int>(adjustments_tableWidget->rowCount()) < _supportedAdjustments.size()))
		adjustments_tableWidget->setRowCount( _supportedAdjustments.size() + 2 );
	// Fill Table:
	for (k=0; k<_supportedAdjustments.size(); k++)
	{
		// Title:
		tableItem = new QTableWidgetItem( _supportedAdjustments.at(k).title );
		adjustments_tableWidget->setItem(k, 0, tableItem);
		// Current Value:
		tableItem = new QTableWidgetItem( "???" );
		tableItem->setTextAlignment(Qt::AlignCenter);
		adjustments_tableWidget->setItem(k, 1, tableItem);
		// New Value:
		if (_newValueSelWidgetType.at(k))
		{
			// Get selectable scaled values:
			selectableScaledValueStr.clear();
			getSelectableScaledValueStrings(_supportedAdjustments.at(k).formula, &selectableScaledValueStr);
			// Setup and insert selection-Combobox:
			comboBox = new QComboBox();
			comboBox->addItems( selectableScaledValueStr );
			adjustments_tableWidget->setCellWidget ( k, 2, comboBox );
		}
		else
		{
			// Calculate and set min/max:
			ok = libFSSM::raw2scaled(_supportedAdjustments.at(k).rawMin, _supportedAdjustments.at(k).formula, _supportedAdjustments.at(k).precision, &helpScaledValueStr);
			if (ok)
				minScaledValue = helpScaledValueStr.toDouble(&ok);
			if (ok)
				ok = libFSSM::raw2scaled(_supportedAdjustments.at(k).rawMax, _supportedAdjustments.at(k).formula, _supportedAdjustments.at(k).precision, &helpScaledValueStr);
			if (ok)
				maxScaledValue = helpScaledValueStr.toDouble(&ok);
			if (ok)
				ok = libFSSM::raw2scaled(_supportedAdjustments.at(k).rawDefault, _supportedAdjustments.at(k).formula, _supportedAdjustments.at(k).precision, &helpScaledValueStr);
			if (ok)
				defaultScaledValue = helpScaledValueStr.toDouble(&ok);
			if (!ok)
			{
				calcerror = true;
				continue; // continue with next adjustment value
			}
			spinBox = new ModQDoubleSpinBox();
			// put spinbox into the table:
			adjustments_tableWidget->setCellWidget ( k, 2, spinBox );
			/* NOTE: we do this here, because some spinbox functions don't work as expected (Qt-bugs ?) if spinBox is not visible yet */
			// Set adjustable range:
			if (minScaledValue > maxScaledValue)
				spinBox->setRange(maxScaledValue, minScaledValue);
			else
				spinBox->setRange(minScaledValue, maxScaledValue);
			// Calculate and set step size:
			minSingleStepFromPrecision = pow(10, (-1*_supportedAdjustments.at(k).precision));
			minSingleStepFromRaw = (maxScaledValue - minScaledValue) / (_supportedAdjustments.at(k).rawMax - _supportedAdjustments.at(k).rawMin);
			/* NOTE: this only works for constant step size ! */
			if (minSingleStepFromRaw > minSingleStepFromPrecision)
				spinBox->setSingleStep( minSingleStepFromRaw );
			else
				spinBox->setSingleStep( minSingleStepFromPrecision );
			// Set base value for "discrete values mode":
			spinBox->setDiscreteValuesModeBaseValue(defaultScaledValue);
			// Enable "discrete values mode":
			spinBox->setDiscreteValuesModeEnabled(true);
			// Set decimals:
			spinBox->setDecimals(_supportedAdjustments.at(k).precision);
			// Set suffix (unit):
			spinBox->setSuffix(" " + _supportedAdjustments.at(k).unit);
			// Set alignement:
			spinBox->setAlignment(Qt::AlignCenter);
		}
		// "Save"-button:
		saveButton = new QIdPushButton("", k, adjustments_tableWidget);
		saveButton->setIcon(saveButton_icon);
		saveButton->setIconSize( QSize(54,22) );
		connect (saveButton, SIGNAL( released(unsigned int) ), this, SLOT( saveAdjustmentValue(unsigned int) ));
		adjustments_tableWidget->setCellWidget ( k, 3, saveButton );	
	}
	// Setup "Reset all"-elements:
	if (_supportedAdjustments.size() > 0)
	{
		// Title:
		tableItem = new QTableWidgetItem( tr("Reset all: ") );
		tableItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignRight);
		adjustments_tableWidget->setItem(_supportedAdjustments.size()+1, 2, tableItem);
		// "Reset all"-button:
		resetButton = new QPushButton(adjustments_tableWidget);
		resetButton->setIcon( resetButton_icon );
		resetButton->setIconSize( QSize(54, 22) );
		connect (resetButton, SIGNAL( released() ), this, SLOT( resetAllAdjustmentValues() ));
		adjustments_tableWidget->setCellWidget ( _supportedAdjustments.size()+1, 3, resetButton );	
	}
	// Check for calculation error(s):
	if (calcerror)
		calculationError(tr("One or more values will not be adjustable to prevent\nwrong data being written to the Control Unit."));
	// NOTE: using released() instead of pressed() for buttons as workaround for a Qt-Bug occuring under MS Windows
}
Example #10
0
bool GaussianFchk::readDensityMatrix(unsigned int n, int width)
{
  // This function reads in the lower triangular density matrix
  m_density.resize(m_numBasisFunctions, m_numBasisFunctions);
  unsigned int cnt = 0;
  unsigned int i = 0, j = 0;
  unsigned int f = 1;
  bool ok = false;
  while (cnt < n) {
    if (m_in->atEnd()) {
      qDebug() << "GaussianFchk::readDensityMatrix could not read all elements"
               << n << "expected" << cnt << "parsed.";
      return false;
    }
    QString line = m_in->readLine();
    if (line.isEmpty())
      return false;

    if (width == 0) { // we can split by spaces
      QStringList list = line.split(' ', QString::SkipEmptyParts);
      for (int k = 0; k < list.size(); ++k) {
        if (cnt >= n) {
          qDebug() << "Too many variables read in. File may be inconsistent."
                   << cnt << "of" << n;
          return false;
        }
        // Read in lower half matrix
        m_density(i, j) = list.at(k).toDouble(&ok);
        if (ok) { // Valid double converted, carry on
          ++j; ++cnt;
          if (j == f) {
            // We need to move down to the next row and increment f - lower tri
            j = 0;
            ++f;
            ++i;
          }
        }
        else { // Invalid conversion of a string to double
          qDebug() << "Warning: problem converting string to double:"
                   << list.at(k) << "\nIn GaussianFchk::readDensityMatrix.";
          return false;
        }
      }
    }
    else { // Q-Chem files use 16-character fields
      int maxColumns = 80 / width;
      for (int c = 0; c < maxColumns; ++c) {
        QString substring = line.mid(c * width, width);
        if (substring.length() != width)
          break;
        else if (cnt >= n) {
          qDebug() << "Too many variables read in. File may be inconsistent."
                   << cnt << "of" << n;
          return false;
        }
        // Read in lower half matrix
        m_density(i, j) = substring.toDouble(&ok);
        if (ok) { // Valid double converted, carry on
          ++j; ++cnt;
          if (j == f) {
            // We need to move down to the next row and increment f - lower tri
            j = 0;
            ++f;
            ++i;
          }
        }
        else { // Invalid conversion of a string to double
          qDebug() << "Warning: problem converting string to double:"
                   << substring << "\nIn GaussianFchk::readDensityMatrix.";
          return false;
        }
      }
    }
  }
  return true;
}
Example #11
0
void RecallImage::SLICSuperCompact(QString num)
{
	superCompact = num.toDouble();
}
Example #12
0
KisImageWSP KisKraLoader::loadXML(const KoXmlElement& element)
{
    QString attr;
    KisImageWSP image = 0;
    QString name;
    qint32 width;
    qint32 height;
    QString profileProductName;
    double xres;
    double yres;
    QString colorspacename;
    const KoColorSpace * cs;

    if ((attr = element.attribute(MIME)) == NATIVE_MIMETYPE) {

        if ((m_d->imageName = element.attribute(NAME)).isNull()) {
            m_d->errorMessages << i18n("Image does not have a name.");
            return KisImageWSP(0);
        }

        if ((attr = element.attribute(WIDTH)).isNull()) {
            m_d->errorMessages << i18n("Image does not specify a width.");
            return KisImageWSP(0);
        }
        width = attr.toInt();

        if ((attr = element.attribute(HEIGHT)).isNull()) {
            m_d->errorMessages << i18n("Image does not specify a height.");
            return KisImageWSP(0);
        }

        height = attr.toInt();

        m_d->imageComment = element.attribute(DESCRIPTION);

        xres = 100.0 / 72.0;
        if (!(attr = element.attribute(X_RESOLUTION)).isNull()) {
            if (attr.toDouble() > 1.0) {
                xres = attr.toDouble() / 72.0;
            }
        }

        yres = 100.0 / 72.0;
        if (!(attr = element.attribute(Y_RESOLUTION)).isNull()) {
            if (attr.toDouble() > 1.0) {
                yres = attr.toDouble() / 72.0;
            }
        }

        if ((colorspacename = element.attribute(COLORSPACE_NAME)).isNull()) {
            // An old file: take a reasonable default.
            // Krita didn't support anything else in those
            // days anyway.
            colorspacename = "RGBA";
        }

        profileProductName = element.attribute(PROFILE);
        // A hack for an old colorspacename
        convertColorSpaceNames(colorspacename, profileProductName);

        QString colorspaceModel = KoColorSpaceRegistry::instance()->colorSpaceColorModelId(colorspacename).id();
        QString colorspaceDepth = KoColorSpaceRegistry::instance()->colorSpaceColorDepthId(colorspacename).id();

        if (profileProductName.isNull()) {
            // no mention of profile so get default profile";
            cs = KoColorSpaceRegistry::instance()->colorSpace(colorspaceModel, colorspaceDepth, "");
        } else {
            cs = KoColorSpaceRegistry::instance()->colorSpace(colorspaceModel, colorspaceDepth, profileProductName);
        }

        if (cs == 0) {
            // try once more without the profile
            cs = KoColorSpaceRegistry::instance()->colorSpace(colorspaceModel, colorspaceDepth, "");
            if (cs == 0) {
                m_d->errorMessages << i18n("Image specifies an unsupported color model: %1.", colorspacename);
                return KisImageWSP(0);
            }
        }

        if (m_d->document) {
            image = new KisImage(m_d->document->createUndoStore(), width, height, cs, name);
        }
        else {
            image = new KisImage(0, width, height, cs, name);
        }
        image->setResolution(xres, yres);
        loadNodes(element, image, const_cast<KisGroupLayer*>(image->rootLayer().data()));

        KoXmlNode child;
        for (child = element.lastChild(); !child.isNull(); child = child.previousSibling()) {
            KoXmlElement e = child.toElement();
            if(e.tagName() == "ProjectionBackgroundColor") {
                if (e.hasAttribute("ColorData")) {
                    QByteArray colorData = QByteArray::fromBase64(e.attribute("ColorData").toLatin1());
                    KoColor color((const quint8*)colorData.data(), image->colorSpace());
                    image->setDefaultProjectionColor(color);
                }
            }

            if (e.tagName().toLower() == "animation") {
                loadAnimationMetadata(e, image);
            }
        }

        for (child = element.lastChild(); !child.isNull(); child = child.previousSibling()) {
            KoXmlElement e = child.toElement();
            if(e.tagName() == "compositions") {
                loadCompositions(e, image);
            }
        }
    }
    KoXmlNode child;
    for (child = element.lastChild(); !child.isNull(); child = child.previousSibling()) {
        KoXmlElement e = child.toElement();
        if (e.tagName() == "assistants") {
            loadAssistantsList(e);
        }
    }
    return image;
}
Example #13
0
bool qtSDLTreeModel::setData(const QModelIndex &index, const QVariant &value, int role) {
    if(role != Qt::EditRole || value.type() != QVariant::String || index.column() != 0)
        return false;
    QString* strVal = (QString*)value.data();
    SDLModelIndex myIndex = indices[index.internalId()];
    if(myIndex.type != kVal)
        return false;
    plSimpleStateVariable* var = (plSimpleStateVariable*)myIndex.ptr.sv;
    switch(var->getDescriptor()->getType()) {
    case plVarDescriptor::kBool:
        if(*strVal == "True")
            var->Bool(index.row()) = true;
        else if(*strVal == "False")
            var->Bool(index.row()) = false;
        else
            return false;
        break;
    case plVarDescriptor::kInt:
    {
        bool result;
        int value = strVal->toInt(&result);
        if(result)
            var->Int(index.row()) = value;
        else
            return false;
        break;
    }
    case plVarDescriptor::kByte:
    {
        bool result;
        int value = strVal->toInt(&result);
        if(result && value >= 0 && value < 256)
            var->Byte(index.row()) = (unsigned char)value;
        else
            return false;
        break;
    }
    case plVarDescriptor::kChar:
    {
        char* str = strVal->toLocal8Bit().data();
        if(strlen(str) == 1)
            var->Char(index.row()) = str[0];
        else
            return false;
        break;
     }
    case plVarDescriptor::kFloat:
    {
        bool result;
        float value = strVal->toFloat(&result);
        if(result)
            var->Float(index.row()) = value;
        else
            return false;
        break;
    }
    case plVarDescriptor::kDouble:
    {
        bool result;
        double value = strVal->toDouble(&result);
        if(result)
            var->Double(index.row()) = value;
        else
            return false;
        break;
    }
    case plVarDescriptor::kString:
        var->String(index.row()) = plString(strVal->toLocal8Bit().data());
        break;
    default:
        return false;
    }
    emit sdlChanged(sdl);
    return true;
}
void UpgradeMessage::saveHeaderData (DbPlugin &db, QString &k, QString &d, QString &sym, DBIndexItem &item)
{
  // is this a co key?
  bool ok = FALSE;
  double t = k.toDouble(&ok);
  if (ok)
  {
    if (t < 10000)
    {
      // its a chart object
      Setting t;
      t.parse(d);
      QString s = "Plugin";
      QString s2;
      t.getData(s,s2);
      if (s2.length())
      {
        t.remove(s);
        s = "Type";
        t.setData(s, s2);
      }

      s = "Plot";
      t.getData(s, s2);
      if (! s2.compare("Main Plot"))
      {
        s2 = "Bars";
        t.setData(s, s2);
      }
      else
        return;

      index.setChartObject(sym, k, t);
      return;
    }
  }

  if (! k.compare("Type"))
  {
    item.setType(d);
    return;
  }

  if (! k.compare("FuturesType"))
  {
    item.setFuturesType(d);
    return;
  }

  if (! k.compare("FuturesMonth"))
  {
    item.setFuturesMonth(d);
    return;
  }

  if (! k.compare("BarType"))
  {
    item.setBarType(d);
    return;
  }

  if (! k.compare("Fundamentals"))
  {
    index.setFundamentals(sym, d);
    return;
  }

  if (! k.compare("LocalIndicators"))
  {
    index.addIndicator(sym, d);
    return;
  }

  if (! k.compare("QuotePlugin"))
  {
    item.setQuotePlugin(d);
    return;
  }

  if (! k.compare("Symbol"))
  {
    item.setSymbol(d);
    return;
  }

  if (! k.compare("Title"))
  {
    item.setTitle(d);
    return;
  }

  if (! k.compare("Path"))
  {
    item.setPath(d);
    return;
  }

  if (! k.compare("SpreadFirstSymbol"))
  {
    int t = d.find("/data0/", 0, TRUE);
    d.replace(t + 5, 1, "1");
    QString ts = "FirstSymbol";
    db.setData(ts, d);
    return;
  }

  if (! k.compare("SpreadSecondSymbol"))
  {
    int t = d.find("/data0/", 0, TRUE);
    d.replace(t + 5, 1, "1");
    QString ts = "SecondSymbol";
    db.setData(ts, d);
    return;
  }

  if (! k.compare("IndexList"))
  {
    while (1)
    {
      int t = d.find("/data0/", 0, TRUE);
      if (t == -1)
        break;
      else
        d.replace(t + 5, 1, "1");
    }
    QString ts = "List";
    db.setData(ts, d);
    return;
  }

  if (! k.compare("CCAdjustment"))
  {
    QString ts = "Adjustment";
    db.setData(ts, d);
    return;
  }
}
void QgsDelimitedTextSourceSelect::updateFieldLists()
{
  // Update the x and y field dropdown boxes
  QgsDebugMsg( "Updating field lists" );

  disconnect( cmbXField, SIGNAL( currentIndexChanged( int ) ), this, SLOT( enableAccept() ) );
  disconnect( cmbYField, SIGNAL( currentIndexChanged( int ) ), this, SLOT( enableAccept() ) );
  disconnect( cmbWktField, SIGNAL( currentIndexChanged( int ) ), this, SLOT( enableAccept() ) );
  disconnect( geomTypeXY, SIGNAL( toggled( bool ) ), this, SLOT( enableAccept() ) );
  disconnect( geomTypeWKT, SIGNAL( toggled( bool ) ), this, SLOT( enableAccept() ) );
  disconnect( geomTypeNone, SIGNAL( toggled( bool ) ), this, SLOT( enableAccept() ) );

  QString columnX = cmbXField->currentText();
  QString columnY = cmbYField->currentText();
  QString columnWkt = cmbWktField->currentText();

  // clear the field lists
  cmbXField->clear();
  cmbYField->clear();
  cmbWktField->clear();

  // clear the sample text box
  tblSample->clear();
  tblSample->setColumnCount( 0 );
  tblSample->setRowCount( 0 );

  if ( ! loadDelimitedFileDefinition() )
    return;

  // Put a sample set of records into the sample box.  Also while scanning assess suitability of
  // fields for use as coordinate and WKT fields


  QList<bool> isValidCoordinate;
  QList<bool> isValidWkt;
  QList<bool> isEmpty;
  int counter = 0;
  mBadRowCount = 0;
  QStringList values;
  QRegExp wktre( "^\\s*(?:MULTI)?(?:POINT|LINESTRING|POLYGON)\\s*Z?\\s*M?\\(", Qt::CaseInsensitive );

  while ( counter < mExampleRowCount )
  {
    QgsDelimitedTextFile::Status status = mFile->nextRecord( values );
    if ( status == QgsDelimitedTextFile::RecordEOF ) break;
    if ( status != QgsDelimitedTextFile::RecordOk ) { mBadRowCount++; continue; }
    counter++;

    // Look at count of non-blank fields

    int nv = values.size();
    while ( nv > 0 && values[nv-1].isEmpty() ) nv--;

    if ( isEmpty.size() < nv )
    {
      while ( isEmpty.size() < nv )
      {
        isEmpty.append( true );
        isValidCoordinate.append( false );
        isValidWkt.append( false );
      }
      tblSample->setColumnCount( nv );
    }

    tblSample->setRowCount( counter );

    bool xyDms = cbxXyDms->isChecked();

    for ( int i = 0; i < tblSample->columnCount(); i++ )
    {
      QString value = i < nv ? values[i] : "";
      if ( value.length() > MAX_SAMPLE_LENGTH ) value = value.mid( 0, MAX_SAMPLE_LENGTH ) + "...";
      QTableWidgetItem *item = new QTableWidgetItem( value );
      tblSample->setItem( counter - 1, i, item );
      if ( ! value.isEmpty() )
      {
        if ( isEmpty[i] )
        {
          isEmpty[i] = false;
          isValidCoordinate[i] = true;
          isValidWkt[i] = true;
        }
        if ( isValidCoordinate[i] )
        {
          bool ok = true;
          if ( cbxPointIsComma->isChecked() )
          {
            value.replace( ",", "." );
          }
          if ( xyDms )
          {
            ok = QgsDelimitedTextProvider::CrdDmsRegexp.indexIn( value ) == 0;
          }
          else
          {
            value.toDouble( &ok );
          }
          isValidCoordinate[i] = ok;
        }
        if ( isValidWkt[i] )
        {
          value.remove( QgsDelimitedTextProvider::WktPrefixRegexp );
          isValidWkt[i] = value.contains( wktre );
        }
      }
    }
  }

  QStringList fieldList = mFile->fieldNames();

  if ( isEmpty.size() < fieldList.size() )
  {
    while ( isEmpty.size() < fieldList.size() )
    {
      isEmpty.append( true );
      isValidCoordinate.append( false );
      isValidWkt.append( false );
    }
    tblSample->setColumnCount( fieldList.size() );
  }

  tblSample->setHorizontalHeaderLabels( fieldList );
  tblSample->resizeColumnsToContents();
  tblSample->resizeRowsToContents();

  // We don't know anything about a text based field other
  // than its name. All fields are assumed to be text
  // As we ignore blank fields we need to map original index
  // of selected fields to index in combo box.

  int fieldNo = 0;
  for ( int i = 0; i < fieldList.size(); i++ )
  {
    QString field = fieldList[i];
    // skip empty field names
    if ( field.isEmpty() ) continue;
    cmbXField->addItem( field );
    cmbYField->addItem( field );
    cmbWktField->addItem( field );
    fieldNo++;
  }

  // Try resetting current values for column names

  cmbWktField->setCurrentIndex( cmbWktField->findText( columnWkt ) );
  cmbXField->setCurrentIndex( cmbXField->findText( columnX ) );
  cmbYField->setCurrentIndex( cmbYField->findText( columnY ) );

  // Now try setting optional X,Y fields - will only reset the fields if
  // not already set.

  trySetXYField( fieldList, isValidCoordinate, "longitude", "latitude" );
  trySetXYField( fieldList, isValidCoordinate, "lon", "lat" );
  trySetXYField( fieldList, isValidCoordinate, "east", "north" );
  trySetXYField( fieldList, isValidCoordinate, "x", "y" );
  trySetXYField( fieldList, isValidCoordinate, "e", "n" );

  // And also a WKT field if there is one

  if ( cmbWktField->currentIndex() < 0 )
  {
    for ( int i = 0; i < fieldList.size(); i++ )
    {
      if ( ! isValidWkt[i] ) continue;
      int index = cmbWktField->findText( fieldList[i] );
      if ( index >= 0 )
      {
        cmbWktField->setCurrentIndex( index );
        break;
      }
    }
  }

  bool haveFields = fieldNo > 0;

  bool isXY = cmbWktField->currentIndex() < 0 ||
              ( geomTypeXY->isChecked() &&
                ( cmbXField->currentIndex() >= 0 && cmbYField->currentIndex() >= 0 ) );
  geomTypeXY->setChecked( isXY );
  geomTypeWKT->setChecked( ! isXY );
  swGeomType->setCurrentIndex( bgGeomType->checkedId() );

  if ( haveFields )
  {
    connect( cmbXField, SIGNAL( currentIndexChanged( int ) ), this, SLOT( enableAccept() ) );
    connect( cmbYField, SIGNAL( currentIndexChanged( int ) ), this, SLOT( enableAccept() ) );
    connect( cmbWktField, SIGNAL( currentIndexChanged( int ) ), this, SLOT( enableAccept() ) );
    connect( geomTypeXY, SIGNAL( toggled( bool ) ), this, SLOT( enableAccept() ) );
    connect( geomTypeWKT, SIGNAL( toggled( bool ) ), this, SLOT( enableAccept() ) );
    connect( geomTypeNone, SIGNAL( toggled( bool ) ), this, SLOT( enableAccept() ) );
  }

}
Example #16
0
//click move button
void CStepDlg::MoveButton()
{	  
	//m_pList->setCurrentRow(m_pList->count()-1);

	QString strMove;
    strMove = m_pLineMove->text();//get the string of lineedit

    if(strMove == tr(""))
    {
        /*remind user to input number*/
        QMessageBox::warning(this,QString::fromLocal8Bit("Warning"),QString::fromLocal8Bit("Please input data before clicking the button"));
    }
    else
    {
        double numMove = strMove.toDouble();//change string to double

        int MoveInt = 0;
        char MoveCh;
        MoveInt = numMove*200;
        MoveCh = char(MoveInt);

        int RandNum;
        char RandCh;
        RandNum = rand()%128;
        RandCh = (char)RandNum;
        //char string[4],stringKey[4];
        char string[4],stringKey[4];
        if(numMove >= 0 && numMove <= 163.835)//input is +
        {	
	    string[0] = 0x37;
            string[1] = MoveCh/256;
            string[2] = 0x00;
            string[3] = MoveCh%256;
	    
            /*指令加密……*/
            stringKey[0] = string[0]^string[3];
            stringKey[1] = string[0]^string[1]^string[3];
            stringKey[2] = string[0]^string[2]^string[3];
            stringKey[3] = string[3];

            m_pList->addItem(QString::fromLocal8Bit("向前移动") + strMove + QString::fromLocal8Bit("微步(mm)\r\n"));/*show the message in mainwindow: 向前移动*/
            /*m_Comm.WriteToPort(stringKey,4)*/
    	    //SuperTerminal sp;
            sp.write_to_serial(stringKey,4);
			//sps.read_from_serial();
            //sps.call_handle();
        }
        else if(numMove >= -163.84 && numMove < 0)//input is +
        {
            int MoveInt2 = -MoveInt;
            //char MoveCh2 = (char)MoveInt2;
            short MoveCh3 = (int)MoveInt2;
            string[0] = 0x37;
            string[1] = MoveCh3/256;
            string[2] = 0x01;
            string[3] = MoveCh3%256;
            /*指令加密……*/
            stringKey[0] = string[0]^string[3];
            stringKey[1] = string[0]^string[1]^string[3];
            stringKey[2] = string[0]^string[2]^string[3];
            stringKey[3] = string[3];

            m_pList->addItem(QString::fromLocal8Bit("反向移动") + strMove + QString::fromLocal8Bit("微步(mm)\r\n"));/*show the message in mainwindow: 反向移动*/

            /*m_Comm.WriteToPort(stringKey,4)*/
			//SuperTerminal sp;
            sp.write_to_serial(stringKey,4);
        }

        else
        {
            QMessageBox::warning(this,QString::fromLocal8Bit("Warning"),QString::fromLocal8Bit("Please input data in correct range"));
            MoveInt = 0;//unuseful data to 0
        }

        MoveValueSum = MoveValueSum + MoveInt;
    }
}
Example #17
0
/**
 * @brief Tlacitko pro rovna se - provede se vypocet operaci o dvou operandech
 */
void MainWindow::rovno() {


    druhyNum = value.toDouble();
    switch (proces) {

    /* pouze cislo */

    case -1:
        total = QString::number(druhyNum);
        lcd -> display(total);
        break;

    case 0:
        total = QString::number(druhyNum);
        lcd -> display(total);
        break;

    /* scitani */
    case 1:
        total = QString::number(add_f( prvniNum, druhyNum), 'g');
        lcd -> display(total);

        break;

    /* odcitani */
    case 2:
        total = QString::number(sub_f( prvniNum, druhyNum), 'g');
        lcd -> display(total);

        break;

    /* nasobeni */
    case 3:
        total = QString::number(mul_f( prvniNum, druhyNum), 'g');
        lcd -> display(total);

        break;

    /* deleni */
    case 4:
        if(druhyNum != 0) {
            total = QString::number(div_f( prvniNum, druhyNum), 'g');
            lcd -> display(total);
        } else {
            total = "0";
            lcd -> display("Err04");
        }

        break;

    /* mocnina */
    case 5:
        if((druhyNum - int(druhyNum)) != 0) {
            total = "0";
            lcd -> display("Err05");
        } else {
            druhyNum_int = int(druhyNum);
            total = QString::number(pow_f( prvniNum, druhyNum_int), 'g');
            lcd -> display(total);

        }

        break;

    /* default = error */
    default:
        lcd -> display("Err42");


    }

    prvniNum = total.toDouble();
    if (total == "0")
        total = "";

    value = total;
    proces = -1;
    total = "";

}
/*---------------------------------------------------------------------------*/
bool CRQReplyHandler::startElement( const QString&, const QString&, 
  const QString& qName, const QXmlAttributes& attr)
{
	/* process begin tag */
    const QString &tag = qName;
    switch (type) {
        case UNKNOWN:
            if( tag == "Reply" )
            {
                replyObject = new CRReply; 
                // process attributes
                const QString status = attr.value( QString( "Status" ));
                if ( !status.isNull() )
                {
                    if( status == "Ok" )
                        replyObject->status = true;
                    else
                        replyObject->status = false;
                }
            } else if ( tag == "Parameters") {
                type = PARAMETERS;
                replyObject->parameters = new CRParameters();

                const QString cycleTime = attr.value( QString( "CycleTime" ));
                if( !cycleTime.isNull() )
                    replyObject->parameters->cycleTime = cycleTime.toUInt();

                const QString simTime = attr.value( QString( "SimTime" ));
                if( !simTime.isNull() )
                    replyObject->parameters->simTime = simTime.toUInt();

                const QString compassTime = attr.value (QString( "CompassTime" ));
                if( !compassTime.isNull() )
                    replyObject->parameters->compassTime = compassTime.toUInt();

                const QString obstacleNoise = attr.value(QString("ObstacleNoise"));
                if( !obstacleNoise.isNull() )
                    replyObject->parameters->obstacleNoise =
                      obstacleNoise.toDouble();

                const QString motorsNoise = attr.value (QString( "MotorsNoise" ));
                if( !motorsNoise.isNull() )
                    replyObject->parameters->motorsNoise = motorsNoise.toDouble();
            }
            else if ( tag == "Grid" )
            {
                type = GRID;    //Next time startElement will process one GRID
                replyObject->grid = new CRGrid();
            }
            else if (tag == "Lab") {
                type = LAB;
                replyObject->lab = new CRLab();
                // process attributes
                const QString name = attr.value(QString("Name"));
                if( !name.isNull() )
                    replyObject->lab->setName( name.toAscii() );

                const QString width = attr.value(QString("Width"));
                if( !width.isNull() )
                    replyObject->lab->setWidth( width.toFloat() );

                const QString height = attr.value(QString("Height"));
                if( !height.isNull() )
                    replyObject->lab->setHeight( height.toFloat() );
            } 
            else {
                return false;
            }
            break;
        case PARAMETERS:
            break;
        case GRID:
            if( tag == "Position" )
            {
                type = POSITION;
                gridElement = new CRGridElement();
                // Process attributs
                const QString x = attr.value(QString("X"));
                if (!x.isNull())
                    gridElement->position.setX( x.toFloat() );

                const QString y = attr.value(QString("Y"));
                if (!y.isNull())
                    gridElement->position.setY( y.toFloat() );

                const QString dir = attr.value(QString("Dir"));
                if (!dir.isNull())
                    gridElement->direction = dir.toFloat();

                replyObject->grid->addPosition( gridElement ); // Add one position to the grid
            } 
            else {
                return false;
            }
            break;
        case LAB:
            if (tag == "Wall")
            {
                type = WALL;
                wall = new CRWall;
                /* process attributes */
                const QString height = attr.value(QString("Height"));
                if (!height.isNull())
                    wall->setWallHeight( height.toFloat() );
            }
            else if (tag == "Beacon")
            {
                type = BEACON;
                vertice = new CRVertice;
                beacon = new CRBeacon( *vertice );
                /* process attributes */
                const QString x = attr.value(QString("X"));
                if (!x.isNull())
                    vertice->setX( x.toFloat() );

                const QString y = attr.value(QString("Y"));
                if (!y.isNull())
                    vertice->setY( y.toFloat() );

                const QString height = attr.value(QString("Height"));
                if (!height.isNull())
                    replyObject->lab->addBeacon( *vertice, height.toFloat() );
                else
                    replyObject->lab->addBeacon( *vertice );
            }

            else if (tag == "Target")
            {
                type = TARGET;
                target = new CRTarget;
                vertice = new CRVertice;
                /* process attributes */
                const QString x = attr.value(QString("X"));
                if (!x.isNull())
                    vertice->setX( x.toFloat() );

                const QString y = attr.value(QString("Y"));
                if (!y.isNull())
                    vertice->setY( y.toFloat() );

                const QString radius = attr.value(QString("Radius"));
                if (!radius.isNull())
                    replyObject->lab->addTarget( *vertice, radius.toFloat() );
                else
                    replyObject->lab->addTarget( *vertice );
            }
            else {
                return false;
            }
            break;
        case WALL:
            if (tag == "Corner") {
                type = CORNER;
                vertice = new CRVertice;
                // process attributes
                const QString x = attr.value(QString("X"));
                if (!x.isNull())
                    vertice->setX(x.toFloat());

                const QString y = attr.value(QString("Y"));
                if (!y.isNull())
                    vertice->setY(y.toFloat());
                wall->addCorner(*vertice);
            }
            else {
                return false;
            }
            break;
    }
    return true;
}
Example #19
0
void AddIncomeExpenseDialog::setQty(const QString& q) {
	qDebug() << "AddIncomeExpenseDialog::setQty()";
	ui->doubleSpinBox_qty->setValue(q.toDouble());
}
Example #20
0
GeoDataDocument *LogRunner::parseFile(const QString &fileName, DocumentRole role, QString &errorString)
{
    QFile file( fileName );
    if ( !file.exists() ) {
        errorString = QStringLiteral("File %1 does not exist").arg(fileName);
        mDebug() << errorString;
        return nullptr;
    }

    file.open( QIODevice::ReadOnly );
    QTextStream stream( &file );

    GeoDataLineString *const track = new GeoDataLineString;

    GeoDataPlacemark *const placemark = new GeoDataPlacemark;
    placemark->setGeometry( track );

    GeoDataDocument *document = new GeoDataDocument();
    document->setDocumentRole( role );
    document->append( placemark );

    int count = 0;
    bool error = false;
    while( !stream.atEnd() || error ){
        const QString line = stream.readLine();
        const QStringList list = line.split(QLatin1Char(','));

        if ( list.size() != 7 ) {
            mDebug() << Q_FUNC_INFO << "Aborting due to error in line" << count << ". Line was:" << line;
            error = true;
            break;
        }

        const QString strLat = list[0];
        const QString strLon = list[1];
        const QString strElevation = list[2];
        const QString strSpeed = list[3];
        const QString strCourse = list[4];
        const QString strHdop = list[5];
        const QString strTime = list[6];

        if ( strLat.isEmpty() || strLon.isEmpty() || strElevation.isEmpty() ) {
            continue;
        }

        bool okLat, okLon, okAlt = false;
        const qreal lat = strLat.toDouble( &okLat );
        const qreal lon = strLon.toDouble( &okLon );
        const qreal alt = strElevation.toDouble( &okAlt );

        if ( !okLat || !okLon || !okAlt ) {
            continue;
        }

        GeoDataCoordinates coord( lon, lat, alt, GeoDataCoordinates::Degree );
        track->append( coord );
    }

    file.close();
    if ( track->size() == 0 || error ) {
        delete document;
        document = 0;
        return nullptr;
    }

    document->setFileName( fileName );
    return document;
}
Example #21
0
// common function for wheel up/down and key up/down
// delta is in wheel units: a delta of 120 means to increment by 1
void
SpinBox::increment(int delta,
                   int shift) // shift = 1 means to increment * 10, shift = -1 means / 10
{
    bool ok;
    QString str = text();
    //qDebug() << "increment from " << str;
    const double oldVal = str.toDouble(&ok);

    if (!ok) {
        // Not a valid double value, don't do anything
        return;
    }

    bool useCursorPositionIncr = appPTR->getCurrentSettings()->useCursorPositionIncrements();

    // First, treat the standard case: use the Knob increment
    if (!useCursorPositionIncr) {
        double val = oldVal;
        _imp->currentDelta += delta;
        double inc = std::pow(10., shift) * _imp->currentDelta * _imp->increment / 120.;
        double maxiD = 0.;
        double miniD = 0.;
        switch (_imp->type) {
        case eSpinBoxTypeDouble: {
            maxiD = _imp->maxi.toDouble();
            miniD = _imp->mini.toDouble();
            val += inc;
            _imp->currentDelta = 0;
            break;
        }
        case eSpinBoxTypeInt: {
            maxiD = _imp->maxi.toInt();
            miniD = _imp->mini.toInt();
            val += (int)inc;         // round towards zero
            // Update the current delta, which contains the accumulated error
            _imp->currentDelta -= ( (int)inc ) * 120. / _imp->increment;
            assert(std::abs(_imp->currentDelta) < 120);
            break;
        }
        }
        val = std::max( miniD, std::min(val, maxiD) );
        if (val != oldVal) {
            setValue(val);
            Q_EMIT valueChanged(val);
        }

        return;
    }

    // From here on, we treat the positin-based increment.

    if ( (str.indexOf( QLatin1Char('e') ) != -1) || (str.indexOf( QLatin1Char('E') ) != -1) ) {
        // Sorry, we don't handle numbers with an exponent, although these are valid doubles
        return;
    }

    _imp->currentDelta += delta;
    int inc_int = _imp->currentDelta / 120; // the number of integert increments
    // Update the current delta, which contains the accumulated error
    _imp->currentDelta -= inc_int * 120;

    if (inc_int == 0) {
        // Nothing is changed, just return
        return;
    }

    // Within the value, we modify:
    // - if there is no selection, the first digit right after the cursor (or if it is an int and the cursor is at the end, the last digit)
    // - if there is a selection, the first digit after the start of the selection
    int len = str.size(); // used for chopping spurious characters
    if (len <= 0) {
        return; // should never happen
    }
    // The position in str of the digit to modify in str() (may be equal to str.size())
    int pos = ( hasSelectedText() ? selectionStart() : cursorPosition() );
    //if (pos == len) { // select the last character?
    //    pos = len - 1;
    //}
    // The position of the decimal dot
    int dot = str.indexOf( QLatin1Char('.') );
    if (dot == -1) {
        dot = str.size();
    }

    // Now, chop trailing and leading whitespace (and update len, pos and dot)

    // Leading whitespace
    while ( len > 0 && str[0].isSpace() ) {
        str.remove(0, 1);
        --len;
        if (pos > 0) {
            --pos;
        }
        --dot;
        assert(dot >= 0);
        assert(len > 0);
    }
    // Trailing whitespace
    while ( len > 0 && str[len - 1].isSpace() ) {
        str.remove(len - 1, 1);
        --len;
        if (pos > len) {
            --pos;
        }
        if (dot > len) {
            --dot;
        }
        assert(len > 0);
    }
    assert( oldVal == str.toDouble() ); // check that the value hasn't changed due to whitespace manipulation

    // On int types, there should not be any dot
    if ( (_imp->type == eSpinBoxTypeInt) && (len > dot) ) {
        // Remove anything after the dot, including the dot
        str.resize(dot);
        len = dot;
    }

    // Adjust pos so that it doesn't point to a dot or a sign
    assert( 0 <= pos && pos <= str.size() );
    while ( pos < str.size() &&
            ( pos == dot || str[pos] == QLatin1Char('+') || str[pos] == QLatin1Char('-') ) ) {
        ++pos;
    }
    assert(len >= pos);

    // Set the shift (may have to be done twice due to the dot)
    pos -= shift;
    if (pos == dot) {
        pos -= shift;
    }

    // Now, add leading and trailing zeroes so that pos is a valid digit position
    // (beware of the sign!)
    // Trailing zeroes:
    // (No trailing zeroes on int, of course)
    assert( len == str.size() );
    if ( (_imp->type == eSpinBoxTypeInt) && (pos >= len) ) {
        // If this is an int and we are beyond the last position, change the last digit
        pos = len - 1;
        // also reset the shift if it was negative
        if (shift < 0) {
            shift = 0;
        }
    }
    while ( pos >= str.size() ) {
        assert(_imp->type == eSpinBoxTypeDouble);
        // Add trailing zero, maybe preceded by a dot
        if (pos == dot) {
            str.append( QLatin1Char('.') );
            ++pos; // increment pos, because we just added a '.', and next iteration will add a '0'
            ++len;
        } else {
            assert(pos > dot);
            str.append( QLatin1Char('0') );
            ++len;
        }
        assert( pos >= (str.size() - 1) );
    }
    // Leading zeroes:
    bool hasSign = ( str[0] == QLatin1Char('-') || str[0] == QLatin1Char('+') );
    while ( pos < 0 || ( pos == 0 && ( str[0] == QLatin1Char('-') || str[0] == QLatin1Char('+') ) ) ) {
        // Add leading zero
        str.insert( hasSign ? 1 : 0, QLatin1Char('0') );
        ++pos;
        ++dot;
        ++len;
    }
    assert( len == str.size() );
    assert( 0 <= pos && pos < str.size() && str[pos].isDigit() );

    QString noDotStr = str;
    int noDotLen = len;
    if (dot != len) {
        // Remove the dot
        noDotStr.remove(dot, 1);
        --noDotLen;
    }
    assert( (_imp->type == eSpinBoxTypeInt && noDotLen == dot) || noDotLen >= dot );
    double val = oldVal; // The value, as a double
    if ( (noDotLen > 16) && (16 >= dot) ) {
        // don't handle more than 16 significant digits (this causes over/underflows in the following)
        assert( noDotLen == noDotStr.size() );
        noDotLen = 16;
        noDotStr.resize(noDotLen);
    }
    qlonglong llval = noDotStr.toLongLong(&ok); // The value, as a long long int
    if (!ok) {
        // Not a valid long long value, don't do anything
        return;
    }
    int llpowerOfTen = dot - noDotLen; // llval must be post-multiplied by this power of ten
    assert(llpowerOfTen <= 0);
    // check that val and llval*10^llPowerOfTen are close enough (relative error should be less than 1e-8)
    assert(std::abs(val * std::pow(10., -llpowerOfTen) - llval) / std::max( qlonglong(1), std::abs(llval) ) < 1e-8);


    // If pos is at the end
    if ( pos == str.size() ) {
        switch (_imp->type) {
        case eSpinBoxTypeDouble:
            if ( dot == str.size() ) {
                str += QString::fromUtf8(".0");
                len += 2;
                ++pos;
            } else {
                str += QLatin1Char('0');
                ++len;
            }
            break;
        case eSpinBoxTypeInt:
            // take the character before
            --pos;
            break;
        }
    }

    // Compute the full value of the increment
    assert( len == str.size() );
    assert(pos != dot);
    assert( 0 <= pos && pos < len && str[pos].isDigit() );

    int powerOfTen = dot - pos - (pos < dot); // the power of ten
    assert( (_imp->type == eSpinBoxTypeDouble) || ( powerOfTen >= 0 && dot == str.size() ) );

    if (powerOfTen - llpowerOfTen > 16) {
        // too many digits to handle, don't do anything

        // (may overflow when adjusting llval)
        return;
    }

    double inc = inc_int * std::pow(10., (double)powerOfTen);

    // Check that we are within the authorized range
    double maxiD, miniD;
    switch (_imp->type) {
    case eSpinBoxTypeInt:
        maxiD = _imp->maxi.toInt();
        miniD = _imp->mini.toInt();
        break;
    case eSpinBoxTypeDouble:
    default:
        maxiD = _imp->maxi.toDouble();
        miniD = _imp->mini.toDouble();
        break;
    }
    val += inc;
    if ( (val < miniD) || (maxiD < val) ) {
        // out of the authorized range, don't do anything
        return;
    }

    // Adjust llval so that the increment becomes an int, and avoid rounding errors
    if (powerOfTen >= llpowerOfTen) {
        llval += inc_int * std::pow(10., powerOfTen - llpowerOfTen);
    } else {
        llval *= std::pow(10., llpowerOfTen - powerOfTen);
        llpowerOfTen -= llpowerOfTen - powerOfTen;
        llval += inc_int;
    }
    // check that val and llval*10^llPowerOfTen are still close enough (relative error should be less than 1e-8)
    assert(std::abs(val * std::pow(10., -llpowerOfTen) - llval) / std::max( qlonglong(1), std::abs(llval) ) < 1e-8);

    QString newStr;
    newStr.setNum(llval);
    bool newStrHasSign = newStr[0] == QLatin1Char('+') || newStr[0] == QLatin1Char('-');
    // the position of the decimal dot
    int newDot = newStr.size() + llpowerOfTen;
    // add leading zeroes if newDot is not a valid position (beware of sign!)
    while ( newDot <= int(newStrHasSign) ) {
        newStr.insert( int(newStrHasSign), QLatin1Char('0') );
        ++newDot;
    }
    assert( 0 <= newDot && newDot <= newStr.size() );
    assert( newDot == newStr.size() || newStr[newDot].isDigit() );
    if ( newDot != newStr.size() ) {
        assert(_imp->type == eSpinBoxTypeDouble);
        newStr.insert( newDot, QLatin1Char('.') );
    }
    // Check that the backed string is close to the wanted value (relative error should be less than 1e-8)
    assert( (newStr.toDouble() - val) / std::max( 1e-8, std::abs(val) ) < 1e-8 );
    // The new cursor position
    int newPos = newDot + (pos - dot);
    // Remove the shift (may have to be done twice due to the dot)
    newPos += shift;
    if (newPos == newDot) {
        // adjust newPos
        newPos += shift;
    }

    assert( 0 <= newDot && newDot <= newStr.size() );

    // Now, add leading and trailing zeroes so that newPos is a valid digit position
    // (beware of the sign!)
    // Trailing zeroes:
    while ( newPos >= newStr.size() ) {
        assert(_imp->type == eSpinBoxTypeDouble);
        // Add trailing zero, maybe preceded by a dot
        if (newPos == newDot) {
            newStr.append( QLatin1Char('.') );
        } else {
            assert(newPos > newDot);
            newStr.append( QLatin1Char('0') );
        }
        assert( newPos >= (newStr.size() - 1) );
    }
    // Leading zeroes:
    bool newHasSign = ( newStr[0] == QLatin1Char('-') || newStr[0] == QLatin1Char('+') );
    while ( newPos < 0 || ( newPos == 0 && ( newStr[0] == QLatin1Char('-') || newStr[0] == QLatin1Char('+') ) ) ) {
        // add leading zero
        newStr.insert( newHasSign ? 1 : 0, QLatin1Char('0') );
        ++newPos;
        ++newDot;
    }
    assert( 0 <= newPos && newPos < newStr.size() && newStr[newPos].isDigit() );

    // Set the text and cursor position
    //qDebug() << "increment setting text to " << newStr;
    setText(newStr, newPos);
    // Set the selection
    assert( newPos + 1 <= newStr.size() );
    setSelection(newPos + 1, -1);
    Q_EMIT valueChanged( value() );
} // increment
Example #22
0
/*
 *  名称:on_front_size_currentIndexChanged(const QString &arg1)
 *  类型:槽函数
 *  功能:根据聊天面板字体选择大小,显示聊天框字体大小
*/
void Chat_Frame::on_font_size_currentIndexChanged(const QString &arg1)
{
    ui->display_box->setFontPointSize(arg1.toDouble());
    ui->dialog_box->setFontPointSize(arg1.toDouble());
    ui->dialog_box->setFocus();
}
Example #23
0
void MiningPage::readProcessOutput()
{
    QByteArray output;

    minerProcess->reset();

    output = minerProcess->readAll();

    QString outputString(output);

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

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

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

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

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

                threadSpeed[threadID] = speed;

                updateSpeed();
            }
        }
    }
}
QString UnitConversions::CtoF(QString celsius){
    return QString::number(CtoF(celsius.toDouble()), 'f', 1);
}
Example #25
0
//------------------------------------------------------------------------------
void GeoWidgetVariogram::slot_klasa(QString d)
{
    cur_set_vario.set_variogram.x = d.toDouble();
}
QString UnitConversions::meterToMile(QString meter){
    return QString::number(meterToMile(meter.toDouble()), 'f', 3);
}
Example #27
0
//------------------------------------------------------------------------------
void GeoWidgetVariogram::slot_sill(QString d)
{
    cur_set_vario.sill_c1 = d.toDouble();
    graph->set_function(cur_set_vario);
    graph->repaint();
}
QString UnitConversions::mpsFPM(QString mps){
    return QString::number(mpsFPM(mps.toDouble()), 'f', 1);
}
Example #29
0
void 
ViewFogGL3::setStart(const QString& s)
{
  __start = s.toDouble();
}
Example #30
0
bool MainWindow::loadFile(const QString &fileName)
{
    QFile systemsFile(fileName);
    if(!systemsFile.open(QFile::ReadOnly | QFile::Text))
    {
        qDebug () << "could not open file for reading";
        return false;
    }
    QTextStream in(&systemsFile);
    QVector<QStringList> linesListVector;
    while(!in.atEnd())
    {
        QString line = in.readLine();
        QStringList lineList = line.split(" ");
        linesListVector.push_back(lineList);
    }
    bool canContinue=true;
    for(int i=1;i<linesListVector.size();i++)
    {
        if(linesListVector[i].size() != linesListVector[i-1].size()) canContinue = false;
    }
    if (linesListVector.size() != linesListVector[0].size()-1) canContinue = false;
    if(canContinue)
    {
        for(int i=0;i<linesListVector.size();i++)
        {
            for(int j=0;j<linesListVector[i].size();j++)
            {
                if(j==linesListVector[i].size()-1)
                {
                    bool ok = true;
                    QString string = linesListVector[i][j];
                    double value = string.toDouble(&ok);
                    if(ok)
                    {
                        rightRow.push_back(value);
                        //qDebug()<<value;
                        stream <<" "<< value << endl;
                    }else
                    {
                        qDebug() << "Error";
                        stream.flush();
                        stream << "Error input, please, check txt file." ;
                        printf(outputString);
                        systemsFile.close();
                        return false;
                    }
                }else
                {
                    bool ok = true;
                    QString string = linesListVector[i][j];
                    double value = string.toDouble(&ok);
                    if(ok)
                    {
                        matrix.push_back(value);
                        //qDebug()<<value;
                        stream << value<<"  ";
                    }else
                    {
                        qDebug() << "Error";
                        stream.flush();
                        stream << "Error input" ;
                        printf(outputString);
                        systemsFile.close();
                        return false;
                    }
                 }
            }
        }
        printf(outputString);
    }else
    {
        qDebug() << "error input";
        stream.flush();
        stream << "Error input" ;
        printf(outputString);
        systemsFile.close();
        return false;
    }
    /*qDebug() << simpleIterations(matrix,rightRow);
    qDebug() << nevyazka(matrix,rightRow,simpleIterations(matrix,rightRow));*/
    systemsFile.close();
    return true;
}