void QgsWFSSourceSelect::buildQuery( const QModelIndex &index )
{
  if ( !index.isValid() )
  {
    return;
  }

  const QString typeName = index.sibling( index.row(), MODEL_IDX_NAME ).data().toString();

  //get available fields for wfs layer
  QgsWfsConnection connection( cmbConnections->currentText() );
  QgsWFSDataSourceURI uri( connection.uri().uri() );
  uri.setTypeName( typeName );

  QgsDataProvider::ProviderOptions providerOptions;
  QgsWFSProvider p( uri.uri(), providerOptions, mCaps );
  if ( !p.isValid() )
  {
    QMessageBox *box = new QMessageBox( QMessageBox::Critical, tr( "Server exception" ), tr( "DescribeFeatureType failed" ), QMessageBox::Ok, this );
    box->setAttribute( Qt::WA_DeleteOnClose );
    box->setModal( true );
    box->setObjectName( QStringLiteral( "WFSFeatureTypeErrorBox" ) );
    if ( !property( "hideDialogs" ).toBool() )
      box->open();

    return;
  }

  QModelIndex filterIndex = index.sibling( index.row(), MODEL_IDX_SQL );
  QString sql( filterIndex.data().toString() );
  QString displayedTypeName( typeName );
  if ( !mCaps.setAmbiguousUnprefixedTypename.contains( QgsWFSUtils::removeNamespacePrefix( typeName ) ) )
    displayedTypeName = QgsWFSUtils::removeNamespacePrefix( typeName );
  QString allSql( "SELECT * FROM " + QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ) );
  if ( sql.isEmpty() )
  {
    sql = allSql;
  }

  QgsSQLComposerDialog *d = new QgsSQLComposerDialog( this );

  QgsWFSValidatorCallback *validatorCbk = new QgsWFSValidatorCallback( d, uri, allSql, mCaps );
  d->setSQLValidatorCallback( validatorCbk );

  QgsWFSTableSelectedCallback *tableSelectedCbk = new QgsWFSTableSelectedCallback( d, uri, mCaps );
  d->setTableSelectedCallback( tableSelectedCbk );

  const bool bSupportJoins = mCaps.featureTypes.size() > 1 && mCaps.supportsJoins;
  d->setSupportMultipleTables( bSupportJoins, QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ) );

  QMap< QString, QString > mapTypenameToTitle;
  Q_FOREACH ( const QgsWfsCapabilities::FeatureType f, mCaps.featureTypes )
    mapTypenameToTitle[f.name] = f.title;

  QList< QgsSQLComposerDialog::PairNameTitle > tablenames;
  tablenames << QgsSQLComposerDialog::PairNameTitle(
               QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ), mapTypenameToTitle[typeName] );
  if ( bSupportJoins )
  {
    for ( int i = 0; i < mModel->rowCount(); i++ )
    {
      const QString iterTypename = mModel->index( i, MODEL_IDX_NAME ).data().toString();
      if ( iterTypename != typeName )
      {
        QString displayedIterTypename( iterTypename );
        QString unprefixedIterTypename( QgsWFSUtils::removeNamespacePrefix( iterTypename ) );
        if ( !mCaps.setAmbiguousUnprefixedTypename.contains( unprefixedIterTypename ) )
          displayedIterTypename = unprefixedIterTypename;

        tablenames << QgsSQLComposerDialog::PairNameTitle(
                     QgsSQLStatement::quotedIdentifierIfNeeded( displayedIterTypename ), mapTypenameToTitle[iterTypename] );
      }
    }
  }
  d->addTableNames( tablenames );

  QList< QgsSQLComposerDialog::Function> functionList;
  Q_FOREACH ( const QgsWfsCapabilities::Function &f, mCaps.functionList )
  {
    QgsSQLComposerDialog::Function dialogF;
    dialogF.name = f.name;
    dialogF.returnType = f.returnType;
    dialogF.minArgs = f.minArgs;
    dialogF.maxArgs = f.maxArgs;
    Q_FOREACH ( const QgsWfsCapabilities::Argument &arg, f.argumentList )
    {
      dialogF.argumentList << QgsSQLComposerDialog::Argument( arg.name, arg.type );
    }
    functionList << dialogF;
  }
  d->addFunctions( functionList );

  QList< QgsSQLComposerDialog::Function> spatialPredicateList;
  Q_FOREACH ( const QgsWfsCapabilities::Function &f, mCaps.spatialPredicatesList )
  {
    QgsSQLComposerDialog::Function dialogF;
    dialogF.name = f.name;
    dialogF.returnType = f.returnType;
    dialogF.minArgs = f.minArgs;
    dialogF.maxArgs = f.maxArgs;
    Q_FOREACH ( const QgsWfsCapabilities::Argument &arg, f.argumentList )
    {
      dialogF.argumentList << QgsSQLComposerDialog::Argument( arg.name, arg.type );
    }
    spatialPredicateList << dialogF;
  }
  d->addSpatialPredicates( spatialPredicateList );

  QList< QgsSQLComposerDialog::PairNameType> fieldList;
  QString fieldNamePrefix;
  if ( bSupportJoins )
  {
    fieldNamePrefix = QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ) + ".";
  }
  Q_FOREACH ( const QgsField &field, p.fields().toList() )
  {
    QString fieldName( fieldNamePrefix + QgsSQLStatement::quotedIdentifierIfNeeded( field.name() ) );
    fieldList << QgsSQLComposerDialog::PairNameType( fieldName, field.typeName() );
  }
  if ( !p.geometryAttribute().isEmpty() )
  {
    QString fieldName( fieldNamePrefix + QgsSQLStatement::quotedIdentifierIfNeeded( p.geometryAttribute() ) );
    fieldList << QgsSQLComposerDialog::PairNameType( fieldName, QStringLiteral( "geometry" ) );
  }
  fieldList << QgsSQLComposerDialog::PairNameType( fieldNamePrefix + "*", QString() );

  d->addColumnNames( fieldList, QgsSQLStatement::quotedIdentifierIfNeeded( displayedTypeName ) );

  d->setSql( sql );

  mSQLIndex = index;
  mSQLComposerDialog = d;
  // For testability, do not use exec()
  if ( property( "hideDialogs" ).toBool() )
  {
    d->setAttribute( Qt::WA_DeleteOnClose );
    d->setModal( true );
    d->open();
    connect( d, &QDialog::accepted, this, &QgsWFSSourceSelect::updateSql );
  }
  else
  {
    // But we need to use exec() for real GUI, otherwise it does not look
    // right on Mac
    if ( d->exec() )
    {
      updateSql();
    }
    delete d;
  }
}
/**
 * Saves model to xml file.
 */
bool DatasetTestMdlParser::save(DatasetTestModel* mdl) const{
	bool succ = true;

	QDir dir(mdl->projectPath());
	if(!dir.exists(mdl->folder()))
		succ = dir.mkdir(mdl->folder());

	if(!succ){
		QMessageBox msgBox;
        msgBox.setWindowTitle(tr("Save testing scenario"));
        msgBox.setText(tr("Testing scenario folder can't be created !!!"));
        msgBox.setInformativeText(tr("Check if given path exists or program have permission to read and write."));
		msgBox.setIcon(QMessageBox::Critical);
		msgBox.exec();
		return false;
	}

	QFile file(mdl->pathName());
	succ = file.open(QIODevice::WriteOnly);

	if(!succ){
		QMessageBox msgBox;
        msgBox.setWindowTitle(tr("Save testing scenario"));
        msgBox.setText(tr("Testing scenario file can't be created !!!"));
        msgBox.setInformativeText(tr("Check if given path exists or program have permission to read and write."));
		msgBox.setIcon(QMessageBox::Critical);
		msgBox.exec();
		return false;
	}

	QXmlStreamWriter wr(&file);
	wr.setAutoFormatting(true);
	wr.writeStartDocument();
	wr.writeStartElement("datasetTest");

	wr.writeStartElement("header");
	wr.writeTextElement("name", mdl->name());
	wr.writeTextElement("dataset", mdl->selectedDatasetName());
	wr.writeTextElement("network", mdl->selectedNetworkName());
	wr.writeEndElement();

	wr.writeEndElement();
	file.close();
	return true;
}
//------------------------------------------------------------------------------
// Create a message window
//------------------------------------------------------------------------------
void SaleCategories::message(QString text)
{
    QMessageBox msgBox;
    msgBox.setText(text);
    msgBox.exec();
}
Exemple #4
0
void MainWindow::updateDiskNameList()
{
    QMessageBox* testBox = new QMessageBox();
    testBox->exec();

}
void TelaPrincipal::sobre() {
    QMessageBox sobre;
    sobre.setText("UNOESC - Universidade do Oeste de Santa Catarina \nAluno: Luan Tavares \nDisciplina: Compiladores \nProfessor: Cristiano Azevedo");
    sobre.exec();
}
Exemple #6
0
int main(int argv, char **args)
{
    QApplication app(argv, args);
    QWidget *button;

  {
//![0]
    QStateMachine machine;
    machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties);

    QState *s1 = new QState();
    s1->assignProperty(object, "fooBar", 1.0);
    machine.addState(s1);
    machine.setInitialState(s1);

    QState *s2 = new QState();
    machine.addState(s2);
//![0]
  }

  {

//![2]
    QStateMachine machine;
    machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties);

    QState *s1 = new QState();
    s1->assignProperty(object, "fooBar", 1.0);
    machine.addState(s1);
    machine.setInitialState(s1);

    QState *s2 = new QState(s1);
    s2->assignProperty(object, "fooBar", 2.0);
    s1->setInitialState(s2);

    QState *s3 = new QState(s1);
//![2]

  }

  {
//![3]
    QState *s1 = new QState();
    QState *s2 = new QState();

    s1->assignProperty(button, "geometry", QRectF(0, 0, 50, 50));
    s2->assignProperty(button, "geometry", QRectF(0, 0, 100, 100));

    s1->addTransition(button, SIGNAL(clicked()), s2);
//![3]

  }

  {
//![4]
    QState *s1 = new QState();
    QState *s2 = new QState();

    s1->assignProperty(button, "geometry", QRectF(0, 0, 50, 50));
    s2->assignProperty(button, "geometry", QRectF(0, 0, 100, 100));

    QSignalTransition *transition = s1->addTransition(button, SIGNAL(clicked()), s2);
    transition->addAnimation(new QPropertyAnimation(button, "geometry"));
//![4]

  }

  {
    QMainWindow *mainWindow = 0;

//![5]
    QMessageBox *messageBox = new QMessageBox(mainWindow);
    messageBox->addButton(QMessageBox::Ok);
    messageBox->setText("Button geometry has been set!");
    messageBox->setIcon(QMessageBox::Information);

    QState *s1 = new QState();

    QState *s2 = new QState();
    s2->assignProperty(button, "geometry", QRectF(0, 0, 50, 50));
    connect(s2, SIGNAL(entered()), messageBox, SLOT(exec()));

    s1->addTransition(button, SIGNAL(clicked()), s2);
//![5]
  }

  {
    QMainWindow *mainWindow = 0;

//![6]
    QMessageBox *messageBox = new QMessageBox(mainWindow);
    messageBox->addButton(QMessageBox::Ok);
    messageBox->setText("Button geometry has been set!");
    messageBox->setIcon(QMessageBox::Information);

    QState *s1 = new QState();

    QState *s2 = new QState();
    s2->assignProperty(button, "geometry", QRectF(0, 0, 50, 50));

    QState *s3 = new QState();
    connect(s3, SIGNAL(entered()), messageBox, SLOT(exec()));

    s1->addTransition(button, SIGNAL(clicked()), s2);
    s2->addTransition(s2, SIGNAL(propertiesAssigned()), s3);
//![6]

  }

  {

//![7]
    QState *s1 = new QState();
    QState *s2 = new QState();

    s2->assignProperty(object, "fooBar", 2.0);
    s1->addTransition(s2);

    QStateMachine machine;
    machine.setInitialState(s1);
    machine.addDefaultAnimation(new QPropertyAnimation(object, "fooBar"));
//![7]

  }



    return app.exec();
}
Exemple #7
0
void MainWindow::showButtonTestMessage() {
    QMessageBox msgBox;
    msgBox.setText("Button test ...");
    msgBox.exec();
    close();
}
Exemple #8
0
void ExperimentDialog::ShowError(QString msg)
{
    QMessageBox msgBox;
    msgBox.setText(msg);
    msgBox.exec();
}
void RicercaUt::cerca() {
    if(!rUs->isChecked() && !rNmCg->isChecked()) {
        QMessageBox msg;
        msg.setText("E' necessario selezionare una modalità di ricerca!");
        msg.setIcon(QMessageBox::Warning);
        msg.exec();

    }
    else {
        QString us_nm= campo->text();
        output=new QLabel(areaRisultato);
        output->setAlignment(Qt::AlignTop);
        output->setMargin(5);

        if(!us_nm.isEmpty()) {
            if(rUs->isChecked()) {
                string dati = us_nm.toStdString();
                Utente* risultato=admin->ricercaUsername(dati);
                if(risultato) {
                    string profilo=risultato->mostraDatiAccesso()+risultato->mostraPrCompleto()+"\n";
                    QString pr=QString::fromStdString(profilo);
                    output->setText(pr);
                    output->setWordWrap(true);
                }
                else {
                    QMessageBox msg;
                    msg.setText("Ricerca fallita:l'utente cercato non è registrato in LinQedIn!");
                    msg.setIcon(QMessageBox::Warning);
                    msg.exec();
                    this->close();
                }
            }
            else { //rNmCg->isChecked()==true
                QString cogn= campo1->text();
                string nm = us_nm.toStdString();
                string cgnm=cogn.toStdString();
                list<Utente*> risultato=admin->ricercaNomeCognome(nm,cgnm);
                int numero=risultato.size();
                if(numero!=0){
                    string profili;
                    list<Utente*>::iterator it=risultato.begin();
                    for(;it!=risultato.end();++it) {
                        profili=profili+(*it)->mostraDatiAccesso()+(*it)->mostraPrCompleto()+"\n \n";
                    }
                    QString pr=QString::fromStdString(profili);
                    output->setText(pr);
                    output->setWordWrap(true);
                }
                else {
                    QMessageBox msg;
                    msg.setText("Ricerca fallita:l'utente cercato non è registrato in LinQedIn!");
                    msg.setIcon(QMessageBox::Warning);
                    msg.exec();
                    this->close();
                }
            }

            areaRisultato->setWidget(output);
            areaRisultato->ensureWidgetVisible(output);
            areaRisultato->setWidgetResizable(true);
            areaRisultato->show();
            this->close();
        }
        else {
            QMessageBox msg;
            msg.setText("Campo vuoto: immettere l'utente da cercare!");
            msg.setIcon(QMessageBox::Warning);
            msg.exec();
        }
    }
}
Exemple #10
0
int main(int argc, char *argv[])
{
    QCoreApplication::setApplicationName( "VideoLibrary" );

    for(int i=0;i<argc;i++){
        if(!strcmp(argv[i],"-v")){              //return version ID integer
            QString version(CURRENT_VERSION);
            QStringList n = version.split(".");
            int ID = n.at(0).toInt()*100*100 + n.at(1).toInt()*100 + n.at(2).toInt();
            qDebug() << QString("Version : ") + version + QString(" - ID : ") + QString::number(ID);
            return ID;
        }
        if(!strcmp(argv[i],"-n")){              //return 1 if CURRENT_VERSION > version
            QStringList currentVersion = QString(CURRENT_VERSION).split(".");
            QStringList version = QString(argv[i+1]).split(".");
            if(currentVersion.at(0)>version.at(0)) return 1;
            if(currentVersion.at(1)>version.at(1)) return 1;
            if(currentVersion.at(2)>version.at(2)) return 1;
            return 0;
        }
    }

    QApplication a(argc, argv);

    QString path = qApp->applicationFilePath();

    Window w;
    w.setExecutableFilename(path);

#if defined(__WIN32__)
    if(path.contains("-update.exe")){
        QString original_path = path;
        original_path = original_path.remove("-update");

        w.showNewFeatures();

        if(QFile::exists(original_path)){
            if(!QFile::remove(original_path)){
               QMessageBox mess;
               mess.setText(QString("Can't remove: %1\nPlease close the software then restart the update").arg(original_path));
               mess.setWindowTitle("Error");
               mess.setIcon(QMessageBox::Critical);
               mess.exec();
            }
        }

        QFile::copy(path,original_path);
        QProcess process;

#ifdef DEBUG_OUTPUT
        w.addLog(path,QString(CURRENT_VERSION),original_path,"Install update");
#endif

        process.startDetached("\""+original_path+"\"");
        exit(1);
    }else{
        QString update = path;
        update.remove(".exe");
        update += "-update.exe";

#ifdef DEBUG_OUTPUT
        w.addLog(path,QString(CURRENT_VERSION),update,"Update path");
#endif

        if(QFile::exists(update)){
            QProcess process;
            QStringList arg;
            arg << "-v";
            int version = process.execute("\""+update+"\"",arg);
            QString updateVersion = QString::number(version);
            QString currentVersion(CURRENT_VERSION);
            QStringList n = currentVersion.split(".");
            int ID = n.at(0).toInt()*100*100 + n.at(1).toInt()*100 + n.at(2).toInt();
            if(ID>=version){
                qDebug() << "Already up to date";
#ifdef DEBUG_OUTPUT
                w.addLog(path,QString(CURRENT_VERSION),"","Already up to date");
                QMessageBox mess;
                mess.setText(QString("Already up to date\n%1 wille be remove").arg(update));
                mess.setWindowTitle("Information");
                mess.setIcon(QMessageBox::Information);
                mess.setDetailedText("Current version: "+currentVersion+"\n\n"
                                     "Update version: "+updateVersion);
                mess.exec();
#endif
                QFile::remove(update);
            }else{
#ifdef DEBUG_OUTPUT
                w.addLog(path,QString(CURRENT_VERSION),QString::number(version),"Start Update");
                QMessageBox mess;
                mess.setText(QString("Start update"));
                mess.setWindowTitle("Information");
                mess.setIcon(QMessageBox::Information);
                mess.setDetailedText("Update path:\n"+update);
                mess.exec();
#endif
                process.startDetached("\""+update+"\"");
                exit(1);
            }
        }
    }
#endif

    w.show();
    if(w.initForm()!=0)
        return 0;

    return a.exec();
}
bool xTupleDesignerActions::sSave()
{
  QMessageBox save;
  save.setText("How do you want to save your changes?");
  QPushButton *cancel= save.addButton(QMessageBox::Cancel);
  QPushButton *db    = save.addButton(tr("Database only"),    QMessageBox::AcceptRole);
  QPushButton *file  = save.addButton(tr("File only"),        QMessageBox::AcceptRole);
  QPushButton *both  = save.addButton(tr("Database and File"),QMessageBox::AcceptRole);

  save.setDefaultButton(_designer->formwindow()->fileName().isEmpty() ? db : both);
  save.setEscapeButton((QAbstractButton*)cancel);

  save.exec();
  if (save.clickedButton() == (QAbstractButton*)db)
    return sSaveToDB();
  else if (save.clickedButton() == (QAbstractButton*)file)
    return sSaveFile();
  else if (save.clickedButton() == (QAbstractButton*)both)
    return sSaveFile() && sSaveToDB();
  else if (save.clickedButton() == (QAbstractButton*)cancel)
    return false;
  else
  {
    qWarning("xTupleDesignerActions::sSave() bug - unknown button clicked");
    return false;
  }
}
ObjectEditorWidget::ObjectEditorWidget()
{
	this->setLayout( new QHBoxLayout() );

	QWidget * objectListContainer = new QWidget;
	objectListContainer->setLayout( new QVBoxLayout );

	objectListContainer->layout()->addWidget( new QLabel( "Objects" ) );

	objectList = new ObjectListWidget();
	objectList->refreshList();

	connect( objectList->selectionModel(), &QItemSelectionModel::selectionChanged, [this](){ this->changingSelection(); } );


	objectListContainer->setFixedWidth( 150 );

	objectListContainer->layout()->addWidget( objectList );

	QPushButton * newObjButt = new QPushButton( "New" );
	connect( newObjButt, &QPushButton::clicked, [this](){
		bool ok;
		QString s = QInputDialog::getText(this, tr("New Object"), tr("Name:"), QLineEdit::Normal, tr( "NewObject" ), &ok);
		if (ok && !s.isEmpty())
		{
			StructureObject obj;
			obj.name = s.toStdString();
			display( obj );
			saveCurrent();
			objectList->refreshList();
			hasChanged = false;
			objectList->seekObject( s );
		}
	} );
	objectListContainer->layout()->addWidget( newObjButt );

	QPushButton * deleteObjButt = new QPushButton( "Delete" );
	connect( deleteObjButt, &QPushButton::clicked, [this](){
		if( objectList->currentRow() != -1 )
		{
			QMessageBox msgBox;
			msgBox.setWindowTitle("Deleting Object");
			msgBox.setText("Are you sure you want to delete the object \"" + objectList->item( objectList->currentRow() )->text() + "\"?");
			msgBox.setStandardButtons(QMessageBox::Yes|QMessageBox::No);
			msgBox.setDefaultButton(QMessageBox::No);
			int result = msgBox.exec();
			if( result == QMessageBox::Yes )
			{
				remove( ( "Assets/objs/" + ( objectList->item( objectList->currentRow() )->text() + ".rpobj" ).toStdString() ).c_str() );
				editingIndex = -1;
				objectList->selectionModel()->reset();
				objectList->refreshList();				
				hide();
			}
		}
	} );
	objectListContainer->layout()->addWidget( deleteObjButt );

	this->layout()->addWidget( objectListContainer ); //Existing objects widget

	noObjectSelected = new QWidget();
	noObjectSelected->setLayout( new QVBoxLayout() );
	noObjectSelected->layout()->setAlignment( Qt::AlignHCenter );
	noObjectSelected->layout()->addWidget( new QLabel( "No object has been selected for editing" ) );
	QFont nf("Tahoma");
	nf.setPixelSize( 24 );
	noObjectSelected->setFont( nf );
	this->layout()->addWidget( noObjectSelected );

	currentObjectContainer = new QSplitter( Qt::Vertical );
	//currentObjectContainer->setLayout( new QVBoxLayout );

	QWidget * currentObjectEditorContainer = new QWidget;
	currentObjectEditorContainer->setLayout( new QVBoxLayout );

	nameEditor = new QLineEdit;
	QFont lf("Tahoma");
	lf.setPixelSize( 24 );
	nameEditor->setFont(lf);
	nameEditor->setMaximumWidth( 320 );
	connect( nameEditor, &QLineEdit::textEdited, [this](){ hasChanged = true; } );
	currentObjectEditorContainer->layout()->addWidget( nameEditor );

	codeEditTabs = new QTabWidget();

	const char * signatures[] = { "subsetRayMarch( x, y, z, out r, out g, out b ) : boolean", "distanceRayMarch( x, y, z, out r, out g, out b ) : number", "rayTrace( x, y, z, dx, dy, dy, out dist, out r, out g, out b ) : boolean" };

	for( int i = 0; i < 3; i++ )
	{
		QWidget * de = new QWidget;
		de->setLayout( new QVBoxLayout );

	
		QCheckBox * check = new QCheckBox;
		check->setChecked( false );
		check->setText( "Enabled" );
		de->layout()->addWidget( check );

	
		de->layout()->addWidget( new QLabel( signatures[i] ) );

		CodeEditWidget * edit = new CodeEditWidget();
		de->layout()->addWidget( edit );
		edit->setEnabled( false );
		connect( edit, &QTextEdit::textChanged, [this](){ hasChanged = true; } );

		connect( check, &QCheckBox::stateChanged, [edit, check](){ edit->setEnabled( check->isChecked() ); } );
		connect( check, &QCheckBox::clicked, [this](){ hasChanged = true; } );

		codeEditTabs->addTab( de, tr("Test"));
	}

	codeEditTabs->setTabText(0, "Subset Ray Marching" );
	codeEditTabs->setTabText(1, "Distance Estimated Ray Marching" );
	codeEditTabs->setTabText(2, "Absolute Ray Tracing" );

	//QObject::connect(
	//connect( check, SIGNAL( stateChanged( int ) ), [edit](int state){ edit->setEnabled( state == 0 ); } );


	currentObjectEditorContainer->layout()->addWidget( codeEditTabs ); 

	QSplitter * horizontalBottomBar = new QSplitter( Qt::Horizontal );
	//horizontalBottomBar->setLayout( new QHBoxLayout );

	currentObjectContainer->addWidget( currentObjectEditorContainer );

	
	horizontalBottomBar->setFixedHeight( 256 );

	QWidget * previewVerticalContainer = new QWidget;
	previewVerticalContainer->setLayout( new QVBoxLayout );

	QLabel * prevLabel = new QLabel( "Preview" );
	prevLabel->setFixedHeight( 24 );
	previewVerticalContainer->layout()->addWidget( prevLabel ); 
	NewRayMarchWidget * march = new NewRayMarchWidget( 256, 256 );
		NewRayMarchCL * under = new NewRayMarchCL();
		under->initialize();
		march->gpu = under;
	
	previewVerticalContainer->layout()->addWidget( march ); //preview
	march->init();

	//previewVerticalContainer->setFixedWidth( 256 );

	QWidget * previewButtonBar = new QWidget;
	previewButtonBar->setFixedHeight( 38 );
	previewButtonBar->setLayout( new QHBoxLayout );
	previewButtonBar->layout()->setAlignment( Qt::AlignHCenter );

	//Making the parser
	ScriptParser * parser = ScriptParser::makeRegular();

	QPushButton * compButt = new QPushButton( "Compile Selected" );
	connect( compButt, &QPushButton::clicked, [this,parser,march](){
		console->log( "Parsing started" );
		Block * script = parser->parse( this->codeEditTabs->currentWidget()->findChild<QTextEdit*>()->toPlainText().toStdString() );
		console->log( "Parsing ended" );
		console->log( "Compiling started" );

		std::string outlets = "";

		try
		{
			for( int i = 0; i < this->outlets->rowCount(); i++ )
			{
				outlets += ( "frac " + this->outlets->getName( i ) + " = " + std::to_string( this->outlets->getValue( i ) ).c_str() + ";" ).toStdString();
				script->variablesInScope[ this->outlets->getName( i ).toStdString() ] = VariablePacket( Value() );
			}

			if( ( this->codeEditTabs->currentIndex() ) == 0 )
			{
				script->variablesInScope[ "x" ] = VariablePacket( Value() );
				script->variablesInScope[ "y" ] = VariablePacket( Value() );
				script->variablesInScope[ "z" ] = VariablePacket( Value() );
				script->variablesInScope[ "r" ] = VariablePacket( Value(), true );
				script->variablesInScope[ "g" ] = VariablePacket( Value(), true );
				script->variablesInScope[ "b" ] = VariablePacket( Value(), true );

				std::ifstream if_a("Assets/clparts/clheader.cl", std::ios_base::binary);
				std::ifstream if_b("Assets/clparts/clfootergutsSUBSET.cl", std::ios_base::binary);
				std::ofstream of_c("Assets/temp/testAll.cl", std::ios_base::binary);

				std::string output = parser->textOf( script, 0, true );

				of_c << if_a.rdbuf() << "bool subsetFunction( frac x, frac y, frac z, frac * r, frac * g, frac * b ){ " << outlets << output << "}" << if_b.rdbuf();
				of_c.close();

				march->load( "Assets/temp/testAll.cl" );
			}
			else
			if( ( this->codeEditTabs->currentIndex() ) == 1 )
			{
				script->variablesInScope[ "x" ] = VariablePacket( Value() );
				script->variablesInScope[ "y" ] = VariablePacket( Value() );
				script->variablesInScope[ "z" ] = VariablePacket( Value() );
				script->variablesInScope[ "r" ] = VariablePacket( Value(), true );
				script->variablesInScope[ "g" ] = VariablePacket( Value(), true );
				script->variablesInScope[ "b" ] = VariablePacket( Value(), true );

				std::ifstream if_a("Assets/clparts/clheader.cl", std::ios_base::binary);
				std::ifstream if_b("Assets/clparts/clfooterguts.cl", std::ios_base::binary);
				std::ofstream of_c("Assets/temp/testAll.cl", std::ios_base::binary);

				std::string output = parser->textOf( script, 0, true );

				of_c << if_a.rdbuf() << "frac distanceFunction( frac x, frac y, frac z, frac * r, frac * g, frac * b, __global const float* sceneVarData ){ " << outlets << output << "}" << if_b.rdbuf();
				of_c.close();

				march->load( "Assets/temp/testAll.cl" );
			}
			else
			if( ( this->codeEditTabs->currentIndex() ) == 2 )
			{
				script->variablesInScope[ "x" ] = VariablePacket( Value() );
				script->variablesInScope[ "y" ] = VariablePacket( Value() );
				script->variablesInScope[ "z" ] = VariablePacket( Value() );
				script->variablesInScope[ "dx" ] = VariablePacket( Value() );
				script->variablesInScope[ "dy" ] = VariablePacket( Value() );
				script->variablesInScope[ "dz" ] = VariablePacket( Value() );
				script->variablesInScope[ "r" ] = VariablePacket( Value(), true );
				script->variablesInScope[ "g" ] = VariablePacket( Value(), true );
				script->variablesInScope[ "b" ] = VariablePacket( Value(), true );
				script->variablesInScope[ "dist" ] = VariablePacket( Value(), true );

				std::ifstream if_a("Assets/clparts/clheader.cl", std::ios_base::binary);
				std::ifstream if_b("Assets/clparts/clfootergutsTRACE.cl", std::ios_base::binary);
				std::ofstream of_c("Assets/temp/testAll.cl", std::ios_base::binary);

				std::string output = parser->textOf( script, 0, true );

				of_c << if_a.rdbuf() << "bool traceFunction( frac x, frac y, frac z, frac dx, frac dy, frac dz, frac * r, frac * g, frac * b, frac * dist ){ " << outlets << output << "}" << if_b.rdbuf();
				of_c.close();

				march->load( "Assets/temp/testAll.cl" );
			}
		}
		catch( char * error )
		{
			console->log( ( "UNEXPECTED COMPILATION ERROR: " + std::string( error ) ).c_str(), ConsoleWidget::MESSAGE_TYPE::MSG_DIREERROR );
		}
		console->log( "Compiling ended" );
	} );
	previewButtonBar->layout()->addWidget( compButt );
	QPushButton * viewButt = new QPushButton( "Reset View" );
	connect( viewButt, &QPushButton::clicked, [march](){ march->reset(); } );
	previewButtonBar->layout()->addWidget( viewButt );

	previewVerticalContainer->layout()->addWidget( previewButtonBar ); //preview

	horizontalBottomBar->addWidget( previewVerticalContainer );

	QWidget * consoleVerticalContainer = new QWidget;
	consoleVerticalContainer->setLayout( new QVBoxLayout );
	consoleVerticalContainer->setMinimumWidth( 256 );

	consoleVerticalContainer->layout()->addWidget( new QLabel( "Console" ) ); 

	console = new ConsoleWidget;

	consoleVerticalContainer->layout()->addWidget( console ); 

	horizontalBottomBar->addWidget( consoleVerticalContainer );

	currentObjectContainer->addWidget( horizontalBottomBar );

	
	this->layout()->addWidget( currentObjectContainer );//Script edit widget
	currentObjectContainer->setVisible( false );

	outletContainer = new QWidget;
	outletContainer->setLayout( new QVBoxLayout );

	outletContainer->layout()->addWidget( new QLabel( "Outlets" ) );

	outlets = new ValueTableWidget();

	outletContainer->setFixedWidth( 150 );

	outletContainer->layout()->addWidget( outlets );

	QPushButton * addButt = new QPushButton( "Add" );
	connect( addButt, &QPushButton::clicked, [this](){
		outlets->addFullRow();
		hasChanged = true;
	} );
	outletContainer->layout()->addWidget( addButt );

	QPushButton * deleteButt = new QPushButton( "Delete" );
	connect( deleteButt, &QPushButton::clicked, [this](){
		if( outlets->currentRow() != -1 )
		{
			QMessageBox msgBox;
			msgBox.setWindowTitle("Deleting outlet");
			msgBox.setText("Are you sure you want to delete the outlet \"" + outlets->getName( outlets->currentRow() ) + "\"?");
			msgBox.setStandardButtons(QMessageBox::Yes|QMessageBox::No);
			msgBox.setDefaultButton(QMessageBox::No);
			int result = msgBox.exec();
			if( result == QMessageBox::Yes )
			{
				outlets->removeRow( outlets->currentRow() );
				hasChanged = true;
			}
		}
	} );
	outletContainer->layout()->addWidget( deleteButt );

	this->layout()->addWidget( outletContainer ); //Outlet widget
	hasChanged = false;
	editingIndex = -1;
	hide();
}
Exemple #13
0
void Preview::mouseDoubleClickEvent(QMouseEvent *)
{
    QMessageBox mb;
    mb.setText("Double clicked");
    mb.exec();
}
/**
 * Loads model from xml file.
 */
DatasetTestModel* DatasetTestMdlParser::load(QString path) const{
	DatasetTestModel* mdl = new DatasetTestModel();

	QFile file(path);
	bool succ = file.open(QIODevice::ReadOnly);

	if(!succ){
		QMessageBox msgBox;
        msgBox.setWindowTitle(tr("Open dataset test"));
        msgBox.setText(tr("Dataset test file can't be opened !!!"));
        msgBox.setInformativeText(tr("Check if file exists or program have permission to read it."));
		msgBox.setIcon(QMessageBox::Critical);
		msgBox.exec();
		delete mdl;
		return NULL;
	}

	QXmlStreamReader rd;
	rd.setDevice(&file);

	QString elemName;
	int state = 0;

	//reading
	while (!rd.atEnd()) {
		switch(rd.readNext()){
			case QXmlStreamReader::StartElement:
				elemName = rd.name().toString();
				if(rd.name() == "header"){
					state = 1;
				}
				break;

			case QXmlStreamReader::EndElement:
				elemName = "";
				if(rd.name() == "header"){
					state = 0;
				}
				break;

			case QXmlStreamReader::Characters:
				switch(state){
					case 1:
						if(elemName == "name") mdl->setName(rd.text().toString());
						if(elemName == "network") mdl->selectNetwork(rd.text().toString());
						if(elemName == "dataset") mdl->selectDataset(rd.text().toString());
						break;
				}
				break;

			default:
				break;
		}
	}

	//error handling
	if(rd.hasError()){
		QMessageBox msgBox;
        msgBox.setWindowTitle(tr("Open dataset test"));
        msgBox.setText(tr("Error parsing dataset test file !!!"));
		msgBox.setInformativeText(rd.errorString());
		msgBox.setIcon(QMessageBox::Critical);
		msgBox.exec();
		file.close();
		delete mdl;
		return NULL;
	}

	file.close();
	return mdl;
}
void ui_agregaraccesorios::on_pushButton_agregar_clicked()
{


    if(!verificarRestricciones())
        return;

    tuaccesorio.setCodigo(ui->lineEdit_codigo->text());
    tuaccesorio.setDescripcion(ui->lineEdit_descripcion->text());
    tuaccesorio.setPrecioCompra(ui->doubleSpinBox_precio_compra->text());
    tuaccesorio.setPrecioVenta(ui->doubleSpinBox_precio_venta->text());
    tuaccesorio.setPrecioDescuento(ui->doubleSpinBox_precio_descuento->text());
    tuaccesorio.setAccesorios(ui->lineEdit_accesorios->text());
    tuaccesorio.setStock(ui->spinBox_stock->text());
    tuaccesorio.setObservaciones(ui->lineEdit_observaciones->text());
    estado pEstado;pEstado.setNombre(ui->comboBox_estado->currentText());
    pEstado.setIdEstado(QString::number(ui->comboBox_estado->getId(ui->comboBox_estado->currentText())));
    m_marca pMarca;pMarca.setNombre(ui->comboBox_marca->currentText());
    pMarca.setIdMarca(QString::number(ui->comboBox_marca->getId(ui->comboBox_marca->currentText())));
    //colaborador
    color pColor;pColor.setNombre(ui->comboBox_color->currentText());
    pColor.setIdColor(QString::number(ui->comboBox_color->getId(ui->comboBox_color->currentText())));
    tamanio pTamanio;pTamanio.setNombre(ui->comboBox_tamanio->currentText());
    pTamanio.setIdTamanio(QString::number(ui->comboBox_tamanio->getId(ui->comboBox_tamanio->currentText())));
    calidad pCalidad;pCalidad.setNombre(ui->comboBox_calidad->currentText());
    pCalidad.setIdCalidad(QString::number(ui->comboBox_calidad->getId(ui->comboBox_calidad->currentText())));
    genero pGenero; pGenero.setNombre(ui->comboBox_genero->currentText());
    pGenero.setIdgenero(QString::number(ui->comboBox_genero->getId(ui->comboBox_genero->currentText())));

    tuaccesorio.setEstado(pEstado);
    tuaccesorio.setMarca(pMarca);
    //colaborador

    tuaccesorio.setColor(pColor);
    tuaccesorio.setTamanio(pTamanio);
    tuaccesorio.setCalidad(pCalidad);
    tuaccesorio.setGenero(pGenero);

    if(modo==0)
    {

        if(tuaccesorio.agregar())
        {

            emit guardado();
        }
        else
        {
            QMessageBox box;
            box.setIcon(QMessageBox::Critical);
            box.setWindowTitle("Error");
            box.setText("El producto no se pudo agregar!");
            box.setStandardButtons(QMessageBox::Ok);
            box.setDefaultButton(QMessageBox::Ok);
            box.exec();
        }
    }
    else//actualizo
    {
        if(tuaccesorio.actualizar())
        {
            emit guardado();
        }
        else
        {
            QMessageBox box;
            box.setIcon(QMessageBox::Critical);
            box.setWindowTitle("Error");
            box.setText("El producto no se pudo actualizar!");
            box.setStandardButtons(QMessageBox::Ok);
            box.setDefaultButton(QMessageBox::Ok);
            box.exec();
        }
    }
    this->close();

}
void NineMLLayout::load(QDomDocument *doc)
{
    QDomNode n = doc->documentElement().firstChild();
    while( !n.isNull() )
    {
        QDomElement e = n.toElement();
        if( e.tagName() == "LayoutClass" )
        {
            this->name = e.attribute("name","");
            // default to unsorted in no type found
            //this->type = e.attribute("type", "unsorted");
            QDomNode n2 = e.firstChild();
            while( !n2.isNull() )
            {
                QDomElement e2 = n2.toElement();
                if( e2.tagName() == "Parameter" )
                {
                    Parameter *tempPar = new Parameter;
                    tempPar->readIn(e2);
                    this->ParameterList.push_back(tempPar);
                }
                if( e2.tagName() == "Spatial" )
                {
                    QDomNode n3 = e2.firstChild();
                    while( !n3.isNull() )
                    {
                        QDomElement e3 = n3.toElement();
                        if( e3.tagName() == "Regime" )
                        {
                            RegimeSpace *tempRegime  = new RegimeSpace;
                            tempRegime->readIn(e3);
                            this->RegimeList.push_back(tempRegime);
                        }
                        if( e3.tagName() == "StateVariable" )
                        {
                            StateVariable *tempSV  = new StateVariable;
                            tempSV->readIn(e3);
                            this->StateVariableList.push_back(tempSV);
                        }
                        if( e3.tagName() == "Alias" )
                        {
                            Alias *tempAlias  = new Alias;
                            tempAlias->readIn(e3);
                            this->AliasList.push_back(tempAlias);
                        }

                        n3 = n3.nextSibling();
                    }
                }
                n2 = n2.nextSibling();
            }

        }
        n = n.nextSibling();
    }

    // validate this
    QStringList validated = validateComponent();
    if (validated.size() > 1) {
        QMessageBox msgBox;
        QString message;
        for (uint i = 0; i < (uint) validated.size(); ++i) {
            message += validated[i] + "\n";
        }
        msgBox.setText(message);
        msgBox.exec();
    }
}
bool ui_agregaraccesorios::verificarRestricciones()
{
    QRegExp noNumeros("[a-zA-Z]");
    QRegExp noAlfabeto("[0-9\.\,\@]");

    QMessageBox box;
    box.setIcon(QMessageBox::Warning);
    box.setWindowTitle("Error de Escritura");

    QString text=ui->lineEdit_codigo->text();
    if(text.size() == 0)
    {
        box.setText("El Codigo es obligatorio");
        box.exec();

        ui->lineEdit_codigo->setFocus();
        return false;
    }

    if(modo == false)
    {
        QSqlQuery query;
        query.prepare("SELECT codigo FROM Producto WHERE codigo=? AND idProducto !=?");
        query.bindValue(0,text);
        query.bindValue(1,tuaccesorio.getIdProducto());
        query.exec();
        if(query.next())
        {
            box.setText("El Codigo ya existe");
            box.exec();

            ui->lineEdit_codigo->setFocus();
            return false;
        }
    }

    if(!ui->comboBox_marca->selecciono())
    {
        box.setText("Seleccione alguna Marca");
        box.exec();
        ui->comboBox_marca->setFocus();
        return false;
    }
    if(!ui->comboBox_tamanio->selecciono())
    {
        box.setText("Seleccione algun Tamaño");
        box.exec();
        ui->comboBox_tamanio->setFocus();
        return false;
    }
    if(!ui->comboBox_calidad->selecciono())
    {
        box.setText("Seleccione alguna Calidad");
        box.exec();
        ui->comboBox_calidad->setFocus();
        return false;
    }
    if(!ui->comboBox_color->selecciono())
    {
        box.setText("Seleccione algun Color");
        box.exec();
        ui->comboBox_color->setFocus();
        return false;
    }
    if(modo==1)
        if(!ui->comboBox_estado->selecciono())
        {
            box.setText("Seleccione algun Estado");
            box.exec();
            ui->comboBox_estado->setFocus();
            return false;
        }
    if(!ui->comboBox_genero->selecciono())
    {
        box.setText("Seleccione algun Genero");
        box.exec();
        ui->comboBox_genero->setFocus();
        return false;
    }
    return true;
}
Exemple #18
0
void Settings::writeFreshClamConf(){

    QString dataCollect;
    QStringList freshclamList;

    if (groupBox_FcProxy->isChecked()) {

        dataCollect += "HTTPProxyServer " + lineEdit_FcProxyServer->text();
        dataCollect += " ||| ";
        dataCollect += "HTTPProxyPort " + lineEdit_FcProxyServerPort->text();
        dataCollect += " ||| ";
        dataCollect += "HTTPProxyUsername " + lineEdit_FcProxyServerUser->text();
        dataCollect += " ||| ";
        dataCollect += "HTTPProxyPassword " + lineEdit_FcProxyServerPassword->text();
        dataCollect += " ||| ";

    } else {

        dataCollect += "#HTTPProxyServer";
        dataCollect += " ||| ";
        dataCollect += "#HTTPProxyPort ";
        dataCollect += " ||| ";
        dataCollect += "#HTTPProxyUsername ";
        dataCollect += " ||| ";
        dataCollect += "#HTTPProxyPassword ";
        dataCollect += " ||| ";
    }

    if (comboBox_FcActivateLogFile->currentIndex() == 1){

        dataCollect += "UpdateLogFile " + comboBox_ConfigPath->currentText() + "freshclam.log";
        dataCollect += " ||| ";

        if (comboBox_FcVerboseLogging->currentIndex() == 1){
            dataCollect += "LogVerbose yes";
            dataCollect += " ||| ";
        } else {
            dataCollect += "LogVerbose no";
            dataCollect += " ||| ";
        }

        if (comboBox_FcTimeStamp->currentIndex() == 1){
            dataCollect += "LogTime yes";
            dataCollect += " ||| ";
        } else {
            dataCollect += "LogVerbose no";
            dataCollect += " ||| ";
        }

        if (comboBox_FcSystemLogging->currentIndex() == 1){
            dataCollect += "LogSyslog yes";
            dataCollect += " ||| ";
        } else {
            dataCollect += "LogVerbose no";
            dataCollect += " ||| ";
        }

        dataCollect += "LogFileMaxSize " + lineEdit_FcLogFileSize->text();
        dataCollect += " ||| ";
    } else {

        dataCollect += "#UpdateLogFile ";
        dataCollect += " ||| ";
        dataCollect += "#LogVerbose yes";
        dataCollect += " ||| ";
        dataCollect += "#LogTime yes";
        dataCollect += " ||| ";
        dataCollect += "#LogSyslog yes";
        dataCollect += " ||| ";
        dataCollect += "#LogFileMaxSize ";
        dataCollect += " ||| ";
    }

    dataCollect += "PidFile " + comboBox_ConfigPath->currentText() + "freshclam.pid";
    dataCollect += " ||| ";
    dataCollect += "MaxAttempts " + spinBox_FcAttempts->text();
    dataCollect += " ||| ";
    dataCollect += "DatabaseDirectory " + comboBox_ClamVDB->currentText();
    dataCollect += " ||| ";
    dataCollect += "DNSDatabaseInfo " + lineEdit_FcDNSverification->text();
    dataCollect += " ||| ";
    dataCollect += "DatabaseMirror " + lineEdit_FcMirror->text();
    dataCollect += " ||| ";
    dataCollect += "DatabaseMirror " + lineEdit_FcMirrorFallBack->text();

    freshclamList << dataCollect;

    FreshClamConf conf;
    if (!conf.writeFreshClamConf(freshclamList)) {

        QMessageBox message;
        message.setWindowTitle("Warnung!");
        message.setText(trUtf8("Die Datei <b>freshclam.conf</b> "
                               "konnte nicht nach <b>")
                               + comboBox_ConfigPath->currentText()
                               + trUtf8("</b> geschrieben werden."));
        message.setInformativeText(trUtf8("Bitte vergewissern Sie sich, dass Sie "
                                          "für das angegebene Verzeichnis auch die "
                                          "benötigten Schreibrechte besitzen."));
        message.setIcon(QMessageBox::Warning);
        message.setWindowIcon(QIcon::fromTheme("dialog-warning"));
        message.exec();
    }
}
Exemple #19
0
void MainWindow::showNoMasterMessage() {
	QMessageBox msgBox;
	msgBox.setText("Couldn't find the ros master.");
	msgBox.exec();
    close();
}
Exemple #20
0
void Settings::writeClamdConf(){

    QString dataCollect;
    QStringList clamdList;

    dataCollect += "DatabaseDirectory " + comboBox_ClamVDB->currentText();
    dataCollect += " ||| ";
    dataCollect += "LocalSocket " + comboBox_ConfigPath->currentText() + "clamd.socket";
    dataCollect += " ||| ";
    dataCollect += "FixStaleSocket yes ";
    dataCollect += " ||| ";
    dataCollect += "LocalSocketMode 660 ";
    dataCollect += " ||| ";
    dataCollect += "PidFile " + comboBox_ConfigPath->currentText() + "clamd.pid";
    dataCollect += " ||| ";
    dataCollect += "TemporaryDirectory " + comboBox_CdTempDir->currentText();
    dataCollect += " ||| ";

    if (comboBox_CdLeaveTemporaryFiles->currentIndex() == 1) {
        dataCollect += "LeaveTemporaryFiles yes";
        dataCollect += " ||| ";

    } else {
        dataCollect += "LeaveTemporaryFiles no";
        dataCollect += " ||| ";
    }

    if(comboBox_CdBytecode->currentIndex() == 1){
        dataCollect += "Bytecode yes";
        dataCollect += " ||| ";

    } else {
        dataCollect += "Bytecode no";
        dataCollect += " ||| ";
    }

    dataCollect += "BytecodeSecurity " + comboBox_CdTrustSign->currentText();
    dataCollect += " ||| ";

    dataCollect += "MaxDirectoryRecursion " + spinBox_CdMaxDirectoryRecursion->text();
    dataCollect += " ||| ";

    if (comboBox_CdFollowDirectorySymlinks->currentIndex() == 1) {
        dataCollect += "FollowDirectorySymlinks yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "FollowDirectorySymlinks no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdFollowFileSymlinks->currentIndex() == 1) {
        dataCollect += "FollowFileSymlinks yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "FollowFileSymlinks no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdCrossFilesystems->currentIndex() == 1) {
        dataCollect += "CrossFilesystems yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "CrossFilesystems no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdAlgorithmicDetection->currentIndex() == 1) {
        dataCollect += "AlgorithmicDetection yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "AlgorithmicDetection no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdForceToDisk->currentIndex() == 1) {
        dataCollect += "ForceToDisk yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "ForceToDisk no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdDisableCache->currentIndex() == 1) {
        dataCollect += "DisableCache yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "DisableCache no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdScanOLE2->currentIndex() == 1) {
        dataCollect += "ScanOLE2 yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "ScanOLE2 no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdOLE2BlockMacros->currentIndex() == 1) {
        dataCollect += "OLE2BlockMacros yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "OLE2BlockMacros no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdScanPDF->currentIndex() == 1) {
        dataCollect += "ScanPDF yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "ScanPDF no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdScanSWF->currentIndex() == 1) {
        dataCollect += "ScanSWF yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "ScanSWF no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdScanHTML->currentIndex() == 1) {
        dataCollect += "ScanHTML yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "ScanHTML no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdScanArchive->currentIndex() == 1) {
        dataCollect += "ScanArchive yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "ScanArchive no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdArchiveBlockEncrypted->currentIndex() == 1) {
        dataCollect += "ArchiveBlockEncrypted yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "ArchiveBlockEncrypted no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdDetectPUA->currentIndex() == 1) {
        dataCollect += "DetectPUA yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "DetectPUA no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdScanPE->currentIndex() == 1) {
        dataCollect += "ScanPE yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "ScanPE no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdDisableCertCheck->currentIndex() == 1) {
        dataCollect += "DisableCertCheck yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "DisableCertCheck no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdScanELF->currentIndex() == 1) {
        dataCollect += "ScanELF yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "ScanELF no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdDetectBrokenExecutables->currentIndex() == 1) {
        dataCollect += "DetectBrokenExecutables yes";
        dataCollect += " ||| ";
    } else {
        dataCollect += "DetectBrokenExecutables no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdScanMail->currentIndex() == 1) {
        dataCollect += "ScanMail yes";
        dataCollect += " ||| ";

        if (comboBox_CdScanPartialMessages->currentIndex() == 1) {
            dataCollect += "ScanPartialMessages yes";
            dataCollect += " ||| ";
        } else {
            dataCollect += "ScanPartialMessages no";
            dataCollect += " ||| ";
        }

        if (comboBox_CdPhishingSignatures->currentIndex() == 1) {
            dataCollect += "PhishingSignatures yes";
            dataCollect += " ||| ";
        } else {
            dataCollect += "PhishingSignatures no";
            dataCollect += " ||| ";
        }

        if (comboBox_CdPhishingScanURLs->currentIndex() == 1) {
            dataCollect += "PhishingScanURLs yes";
            dataCollect += " ||| ";
        } else {
            dataCollect += "PhishingScanURLs no";
            dataCollect += " ||| ";
        }

        if (comboBox_CdPhishingAlwaysBlockSSLMismatch->currentIndex() == 1) {
            dataCollect += "PhishingAlwaysBlockSSLMismatch yes";
            dataCollect += " ||| ";
        } else {
            dataCollect += "PhishingAlwaysBlockSSLMismatch no";
            dataCollect += " ||| ";
        }

        if (comboBox_CdPhishingAlwaysBlockCloak->currentIndex() == 1) {
            dataCollect += "PhishingAlwaysBlockCloak yes";
            dataCollect += " ||| ";
        } else {
            dataCollect += "PhishingAlwaysBlockCloak no";
            dataCollect += " ||| ";
        }

        if (comboBox_CdPartitionIntersection->currentIndex() == 1) {
            dataCollect += "PartitionIntersection yes";
            dataCollect += " ||| ";
        } else {
            dataCollect += "PartitionIntersection no";
            dataCollect += " ||| ";
        }

        if (comboBox_CdHeuristicScanPrecedence->currentIndex() == 1) {
            dataCollect += "HeuristicScanPrecedence yes";
            dataCollect += " ||| ";
        } else {
            dataCollect += "HeuristicScanPrecedence no";
            dataCollect += " ||| ";
        }
    } else {
        dataCollect += "ScanMail no";
        dataCollect += " ||| ";
        dataCollect += "ScanPartialMessages no";
        dataCollect += " ||| ";
        dataCollect += "PhishingSignatures no";
        dataCollect += " ||| ";
        dataCollect += "PhishingScanURLs no";
        dataCollect += " ||| ";
        dataCollect += "PhishingAlwaysBlockSSLMismatch no";
        dataCollect += " ||| ";
        dataCollect += "PhishingAlwaysBlockCloak no";
        dataCollect += " ||| ";
        dataCollect += "PartitionIntersection no";
        dataCollect += " ||| ";
        dataCollect += "HeuristicScanPrecedence no";
        dataCollect += " ||| ";
    }

    if (comboBox_CdActivateLogFile->currentIndex() == 1){

        dataCollect += "LogFile " + comboBox_ConfigPath->currentText() + "clamd.log";
        dataCollect += " ||| ";

        if (comboBox_CdVerboseLogging->currentIndex() == 1) {
            dataCollect += "LogVerbose yes";
            dataCollect += " ||| ";
        } else {
            dataCollect += "LogVerbose no";
            dataCollect += " ||| ";
        }

        if (comboBox_CdTimeStamp->currentIndex() == 1) {
            dataCollect += "LogTime yes";
            dataCollect += " ||| ";
        } else {
            dataCollect += "LogTime no";
            dataCollect += " ||| ";
        }

        if (comboBox_CdSystemLogging->currentIndex() == 1) {
            dataCollect += "LogSyslog yes";
            dataCollect += " ||| ";
        } else {
            dataCollect += "LogSyslog no";
            dataCollect += " ||| ";
        }

        if (comboBox_CdExtendedDetectionInfo->currentIndex() == 1) {
            dataCollect += "ExtendedDetectionInfo yes";
            dataCollect += " ||| ";
        } else {
            dataCollect += "ExtendedDetectionInfo no";
            dataCollect += " ||| ";
        }

        dataCollect += "LogFileMaxSize " + lineEdit_CdLogFileSize->text();
        dataCollect += " ||| ";
    } else {

        dataCollect += "#LogFile ";
        dataCollect += " ||| ";
        dataCollect += "#LogVerbose yes";
        dataCollect += " ||| ";
        dataCollect += "#LogTime yes";
        dataCollect += " ||| ";
        dataCollect += "#LogSyslog yes";
        dataCollect += " ||| ";
        dataCollect += "#ExtendedDetectionInfo yes";
        dataCollect += " ||| ";
        dataCollect += "#LogFileMaxSize ";
        dataCollect += " ||| ";
    }

    /*
     * Statistics
     */
    if (groupBox_Statistics->isChecked()) {

        dataCollect += "StatsEnabled yes";
        dataCollect += " ||| ";
        if (comboBox_StatsPEDisabled->currentIndex() == 0)
            dataCollect += "StatsPEDisabled no";
        else if (comboBox_StatsPEDisabled->currentIndex() == 1)
            dataCollect += "StatsPEDisabled yes";
        dataCollect += " ||| ";
        dataCollect += "StatsHostID " + lineEdit_StatsHostID->text();
        dataCollect += " ||| ";
        dataCollect += "StatsTimeout " + spinBox_StatsTimeout->text();
    } else if (!groupBox_Statistics->isChecked()) {

        dataCollect += "#StatsEnabled no";
        dataCollect += " ||| ";
        dataCollect += "#StatsPEDisabled yes";
        dataCollect += " ||| ";
        dataCollect += "#StatsHostID ";
        dataCollect += " ||| ";
        dataCollect += "#StatsTimeout ";
    }

    clamdList << dataCollect;

    ClamdConf conf;
    if (!conf.writeClamdConf(clamdList)) {

        QMessageBox message;
        message.setWindowTitle("Warnung!");
        message.setText(trUtf8("Die Datei <b>clamd.conf</b> "
                               "konnte nicht nach <b>")
                               + comboBox_ConfigPath->currentText()
                               + trUtf8("</b> geschrieben werden."));
        message.setInformativeText(trUtf8("Bitte vergewissern Sie sich, dass Sie "
                                          "für das angegebene Verzeichnis auch die "
                                          "benötigten Schreibrechte besitzen."));
        message.setIcon(QMessageBox::Warning);
        message.setWindowIcon(QIcon::fromTheme("dialog-warning"));
        message.exec();
    }
}
void QgsWFSSourceSelect::capabilitiesReplyFinished()
{
  QApplication::restoreOverrideCursor();
  btnConnect->setEnabled( true );

  if ( !mCapabilities )
    return;

  QgsWfsCapabilities::ErrorCode err = mCapabilities->errorCode();
  if ( err != QgsWfsCapabilities::NoError )
  {
    QString title;
    switch ( err )
    {
      case QgsWfsCapabilities::NetworkError:
        title = tr( "Network Error" );
        break;
      case QgsWfsCapabilities::XmlError:
        title = tr( "Capabilities document is not valid" );
        break;
      case QgsWfsCapabilities::ServerExceptionError:
        title = tr( "Server Exception" );
        break;
      default:
        title = tr( "Error" );
        break;
    }
    // handle errors
    QMessageBox *box = new QMessageBox( QMessageBox::Critical, title, mCapabilities->errorMessage(), QMessageBox::Ok, this );
    box->setAttribute( Qt::WA_DeleteOnClose );
    box->setModal( true );
    box->setObjectName( QStringLiteral( "WFSCapabilitiesErrorBox" ) );
    if ( !property( "hideDialogs" ).toBool() )
      box->open();

    emit enableButtons( false );
    return;
  }

  mCaps = mCapabilities->capabilities();

  mAvailableCRS.clear();
  Q_FOREACH ( const QgsWfsCapabilities::FeatureType &featureType, mCaps.featureTypes )
  {
    // insert the typenames, titles and abstracts into the tree view
    QStandardItem *titleItem = new QStandardItem( featureType.title );
    QStandardItem *nameItem = new QStandardItem( featureType.name );
    QStandardItem *abstractItem = new QStandardItem( featureType.abstract );
    abstractItem->setToolTip( "<font color=black>" + featureType.abstract  + "</font>" );
    abstractItem->setTextAlignment( Qt::AlignLeft | Qt::AlignTop );
    QStandardItem *filterItem = new QStandardItem();

    typedef QList< QStandardItem * > StandardItemList;
    mModel->appendRow( StandardItemList() << titleItem << nameItem << abstractItem << filterItem );

    // insert the available CRS into mAvailableCRS
    mAvailableCRS.insert( featureType.name, featureType.crslist );
  }

  if ( !mCaps.featureTypes.isEmpty() )
  {
    treeView->resizeColumnToContents( MODEL_IDX_TITLE );
    treeView->resizeColumnToContents( MODEL_IDX_NAME );
    treeView->resizeColumnToContents( MODEL_IDX_ABSTRACT );
    for ( int i = MODEL_IDX_TITLE; i < MODEL_IDX_ABSTRACT; i++ )
    {
      if ( treeView->columnWidth( i ) > 300 )
      {
        treeView->setColumnWidth( i, 300 );
      }
    }
    if ( treeView->columnWidth( MODEL_IDX_ABSTRACT ) > 150 )
    {
      treeView->setColumnWidth( MODEL_IDX_ABSTRACT, 150 );
    }
    btnChangeSpatialRefSys->setEnabled( true );
    treeView->selectionModel()->setCurrentIndex( mModelProxy->index( 0, 0 ), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows );
    treeView->setFocus();
  }
  else
  {
    QMessageBox::information( nullptr, tr( "No Layers" ), tr( "capabilities document contained no layers." ) );
    emit enableButtons( false );
    mBuildQueryButton->setEnabled( false );
  }
}
Exemple #22
0
void myWizard::on_pushButton_register_clicked()
{
    static int passwd = 0;
    if(passwd == 0){
        ui->lineEdit_pass_confirm->setHidden(false);
        ui->lineEdit_mail->setHidden(false);

        ui->pushButton_register->setText(tr("继续注册"));
        ui->pushButton_login->setDisabled(true);
        ui->comboBox_phone_brife->setHidden(false);
        ui->comboBox_phone_detail->setHidden(false);
        ui->lineEdit_other_phone->setHidden(false);


        QMessageBox info;
        info.addButton(QMessageBox::Ok);
        info.setText(tr("请重新输入密码、邮箱,选择对应的手机型号,如果找不到您的手机型号,请选择其他,并且你的其他中表示出的你的手机型号,功能加紧研发中,如果有特殊需求,请邮件联系[email protected]"));
        info.exec();
        passwd = 1;

    }
    else{
        if(ui->lineEdit_user->text() == tr("username")){
            QMessageBox info;
            info.addButton(QMessageBox::Ok);
            info.setText(tr("请输入有效用户名"));
            info.exec();
            return;
        }
        if(ui->lineEdit_pass->text() != ui->lineEdit_pass_confirm->text())
        {
            //wait and register
            qDebug()<<"user :"******"passwd :"<<ui->lineEdit_pass->text();
            //add register func
            QMessageBox info;
            info.addButton(QMessageBox::Ok);
            info.setText(tr("密码前后不一致"));
            info.exec();
            return;
        }
        if(ui->lineEdit_mail->text() == tr("*****@*****.**")){
            QMessageBox info;
            info.addButton(QMessageBox::Ok);
            info.setText(tr("请输入有效邮箱,这关系到今后你享受的服务质量"));
            info.exec();
            return;
        }
        //register func




    }
}
/*
 * Copyright (c) 2006 Sean C. Rhea ([email protected])
 * Copyright (c) 2014 Mark Liversedge ([email protected])
 *
 * [mostly cut and paste from Zones.cpp]
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <QMessageBox>
#include "PaceZones.h"
#include "Colors.h"
#include "Settings.h"
#include "TimeUtils.h"
#include "Units.h"
#include <QtGui>
#include <QtAlgorithms>
#include <qcolor.h>
#include <assert.h>
#include <cmath>


// the infinity endpoints are indicated with extreme date ranges
// but not zero dates so we can edit and compare them
static const QDate date_zero(1900, 01, 01);
static const QDate date_infinity(9999,12,31);

// initialize default static zone parameters
void PaceZones::initializeZoneParameters()
{
    int* initial_zone_default;
    int initial_nzones_default;

    // these default zones are based upon the Skiba run pace zones
    // but expressed as a percentage of Critical Velocity in km/h
    // rather than as a percentage of LT Pace in minutes/mile
    //
    // Name         %LT Pace         %CV
    // AR              > 125        0 - 80
    // Endurance    124 - 115      80 - 87
    // Tempo        114 - 105      88 - 95
    // Threshold    104 - 95       95 - 105
    // Vo2Max        94 - 84      105 - 119
    // Anaerobic       < 84         > 119
    //
    static int initial_zone_default_run[] = {
        0, 80, 87, 95, 105, 119
    };

    // these default zones are based upon the Skiba swim pace zones
    // but expressed as a percentage of Critical Velocity in km/h
    // rather than as a percentage of LT Pace in minutes/100yd
    //
    // Name         %LT Pace         %CV
    // AR              > 107        0 - 93
    // Endurance    107 - 103      93 - 97
    // Tempo        103 - 101      97 - 99
    // Threshold    101 - 98       99 - 102
    // Vo2Max        98 - 92      102 - 109
    // Anaerobic       < 92         > 109
    //
    static int initial_zone_default_swim[] = {
        0, 93, 97, 99, 102, 109
    };

    if (swim) {
        fileName_ = "swim-pace.zones";
        initial_zone_default = initial_zone_default_swim;
        initial_nzones_default =
            sizeof(initial_zone_default_swim) /
            sizeof(initial_zone_default_swim[0]);

    } else {
        fileName_ = "run-pace.zones";
        initial_zone_default = initial_zone_default_run;
        initial_nzones_default =
            sizeof(initial_zone_default_run) /
            sizeof(initial_zone_default_run[0]);
    }

    static const QString initial_zone_default_desc[] = {
        tr("Active Recovery"), tr("Endurance"), tr("Tempo"), tr("Threshold"),
        tr("VO2Max"), tr("Anaerobic")
    };
    static const char *initial_zone_default_name[] = {
        "Z1", "Z2", "Z3", "Z4", "Z5", "Z6"
    };

    scheme.zone_default.clear();
    scheme.zone_default_is_pct.clear();
    scheme.zone_default_desc.clear();
    scheme.zone_default_name.clear();
    scheme.nzones_default = 0;

    scheme.nzones_default = initial_nzones_default;

    for (int z = 0; z < scheme.nzones_default; z++) {
        scheme.zone_default.append(initial_zone_default[z]);
        scheme.zone_default_is_pct.append(true);
        scheme.zone_default_name.append(QString(initial_zone_default_name[z]));
        scheme.zone_default_desc.append(QString(initial_zone_default_desc[z]));
    }
}

// read zone file, allowing for zones with or without end dates
bool PaceZones::read(QFile &file)
{
    defaults_from_user = false;
    scheme.zone_default.clear();
    scheme.zone_default_is_pct.clear();
    scheme.zone_default_name.clear();
    scheme.zone_default_desc.clear();
    scheme.nzones_default = 0;
    ranges.clear();

    // set up possible warning dialog
    warning = QString();
    int warning_lines = 0;
    const int max_warning_lines = 100;

    // macro to append lines to the warning
    #define append_to_warning(s) \
    if (warning_lines < max_warning_lines) { \
        warning.append(s); }  \
    else if (warning_lines == max_warning_lines) { \
        warning.append("...\n"); } \
    warning_lines++;

    // read using text mode takes care of end-lines
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        err = tr("can't open file");
        return false;
    }
    QTextStream fileStream(&file);

    QRegExp commentrx("\\s*#.*$");
    QRegExp blankrx("^[ \t]*$");
    QRegExp rangerx[] = {
        QRegExp("^\\s*(?:from\\s+)?"                                 // optional "from"
                "((\\d\\d\\d\\d)[-/](\\d{1,2})[-/](\\d{1,2})|BEGIN)" // begin date
                "\\s*([,:]?\\s*(FTP|CV)\\s*=\\s*([\\d\\.]+))?"            // optional {CV/FTP = integer (optional %)}
                "\\s*:?\\s*$",                                       // optional :
                Qt::CaseInsensitive),
        QRegExp("^\\s*(?:from\\s+)?"                                 // optional "from"
                "((\\d\\d\\d\\d)[-/](\\d{1,2})[-/](\\d{1,2})|BEGIN)" // begin date
                "\\s+(?:until|to|-)\\s+"                             // until
                "((\\d\\d\\d\\d)[-/](\\d{1,2})[-/](\\d{1,2})|END)?"  // end date
                "\\s*:?,?\\s*((FTP|CV)\\s*=\\s*([\\d\\.]+))?"          // optional {CV/FTP = integer (optional %)}
                "\\s*:?\\s*$",                                       // optional :
                Qt::CaseInsensitive)
    };
    QRegExp zonerx("^\\s*([^ ,][^,]*),\\s*([^ ,][^,]*),\\s*"
                   "([\\d\\.]+)\\s*(%?)\\s*(?:,\\s*([\\d\\.]+|MAX)\\s*(%?)\\s*)?$",
                   Qt::CaseInsensitive);
    QRegExp zonedefaultsx("^\\s*(?:zone)?\\s*defaults?\\s*:?\\s*$",
                          Qt::CaseInsensitive);

    int lineno = 0;

    // the current range in the file
    // PaceZoneRange *range = NULL;
    bool in_range = false;
    QDate begin = date_zero, end = date_infinity;
    double cv=0;
    QList<PaceZoneInfo> zoneInfos;

    // true if zone defaults are found in the file (then we need to write them)
    bool zones_are_defaults = false;

    while (!fileStream.atEnd() ) {
        ++lineno;
        QString line = fileStream.readLine();
        int pos = commentrx.indexIn(line, 0);
        if (pos != -1)
            line = line.left(pos); if (blankrx.indexIn(line, 0) == 0)
            goto next_line;
        // check for default zone range definition (may be followed by zone definitions)
        if (zonedefaultsx.indexIn(line, 0) != -1) {
            zones_are_defaults = true;

            // defaults are allowed only at the beginning of the file
            if (ranges.size()) {
                err = tr("Zone defaults must be specified at head of %1 file").arg(fileName_);
                return false;
            }

            // only one set of defaults is allowed
            if (scheme.nzones_default) {
                err = tr("Only one set of zone defaults may be specified in %1 file").arg(fileName_);
                return false;
            }

            goto next_line;
        }

        // check for range specification (may be followed by zone definitions)
        for (int r=0; r<2; r++) {

            if (rangerx[r].indexIn(line, 0) != -1) {

                if (in_range) {

                    // if zones are empty, then generate them
                    PaceZoneRange range(begin, end, cv);
                    range.zones = zoneInfos;

                    if (range.zones.empty()) {

                        if (range.cv > 0) { 

                            setZonesFromCV(range); 

                        } else {

                            err = tr("line %1: read new range without reading "
                                     "any zones for previous one").arg(lineno);
                            file.close();
                            return false;
                        }

                    } else {

                        qSort(range.zones);

                    }
                    ranges.append(range);
                }

                in_range = true;
                zones_are_defaults = false;
                zoneInfos.clear();

                // process the beginning date
                if (rangerx[r].cap(1) == "BEGIN") {

                    begin = date_zero; 

                } else {

                    begin = QDate(rangerx[r].cap(2).toInt(),
                                  rangerx[r].cap(3).toInt(),
                                  rangerx[r].cap(4).toInt());
                }

                // process an end date, if any, else it is null
                if (rangerx[r].cap(5) == "END") {

                    end = date_infinity; 

                } else if (rangerx[r].cap(6).toInt() || rangerx[r].cap(7).toInt() || rangerx[r].cap(8).toInt()) {

                    end = QDate(rangerx[r].cap(6).toInt(),
                                rangerx[r].cap(7).toInt(),
                                rangerx[r].cap(8).toInt());

                } else {

                    end = QDate();
                }

                // set up the range, capturing CV if it's specified
                // range = new PaceZoneRange(begin, end);
                int nCV = (r ? 11 : 7);
                if (rangerx[r].captureCount() == (nCV)) cv = rangerx[r].cap(nCV).toDouble(); 
                else cv = 0;

                // bleck
                goto next_line;
            }
        }

        // check for zone definition
        if (zonerx.indexIn(line, 0) != -1) {

            if (!(in_range || zones_are_defaults)) {

                err = tr("line %1: read zone without "
                         "preceding date range").arg(lineno);
                file.close();
                return false;
            }

            double lo = zonerx.cap(3).toDouble();

            // allow for zone specified as % of CV
            bool lo_is_pct = false;
            if (zonerx.cap(4) == "%") {

                if (zones_are_defaults) {

                    lo_is_pct = true;

                } else if (cv > 0)  {

                    lo = double(lo * cv / 100.00f);

                } else {

                    err = tr("attempt to set zone based on % of "
                             "CV without setting CV in line number %1.\n").arg(lineno);
                    file.close();
                    return false;
                }
            }

            double hi;
            // if this is not a zone defaults specification, process possible hi end of zones
            if (zones_are_defaults || zonerx.cap(5).isEmpty()) {

                hi = -1;   // signal an undefined number

            } else if (zonerx.cap(5) == "MAX") {

                hi = INT_MAX;

            } else {

                hi = zonerx.cap(5).toDouble();

                // allow for zone specified as % of CV
                if (zonerx.cap(5) == "%") {

                    if (cv > 0) {

                        hi = double(hi * cv / 100.00f);

                    } else {

                        err = tr("attempt to set zone based on % of CV "
                                 "without setting CV in line number %1.\n").
                              arg(lineno);
                        file.close();
                        return false;

                    }
                }
            }

            if (zones_are_defaults) {

                scheme.nzones_default++;
                scheme.zone_default_is_pct.append(lo_is_pct);
                scheme.zone_default.append(lo);
                scheme.zone_default_name.append(zonerx.cap(1));
                scheme.zone_default_desc.append(zonerx.cap(2));
                defaults_from_user = true;

            } else {

                PaceZoneInfo zone(zonerx.cap(1), zonerx.cap(2), lo, hi);
                zoneInfos.append(zone);
            }
        }
next_line: {}
    }

    if (in_range) {

        PaceZoneRange range(begin, end, cv);
        range.zones = zoneInfos;

        if (range.zones.empty()) {

            if (range.cv > 0) {

                setZonesFromCV(range);

            } else {

                err = tr("file ended without reading any zones for last range");
                file.close();
                return false;
            }

        } else {

            qSort(range.zones);
        }

        ranges.append(range);
    }
    file.close();

    // sort the ranges
    qSort(ranges);

    // set the default zones if not in file
    if (!scheme.nzones_default)  {

        // do we have a zone which is explicitly set?
        for (int i=0; i<ranges.count(); i++) {

            if (ranges[i].zonesSetFromCV == false) {

                // set the defaults using this one!
                scheme.nzones_default = ranges[i].zones.count();
                for (int j=0; j<scheme.nzones_default; j++) {

                    scheme.zone_default.append(((double)ranges[i].zones[j].lo / (double)ranges[i].cv) * 100.00);
                    scheme.zone_default_is_pct.append(true);
                    scheme.zone_default_name.append(ranges[i].zones[j].name);
                    scheme.zone_default_desc.append(ranges[i].zones[j].desc);
                }
            }
        }

        // still not set then reset to defaults as usual
        if (!scheme.nzones_default) initializeZoneParameters();
    }

    // resolve undefined endpoints in ranges and zones
    for (int nr = 0; nr < ranges.size(); nr++) {

        // clean up gaps or overlaps in zone ranges
        if (ranges[nr].end.isNull()) {
            ranges[nr].end =
                (nr < ranges.size() - 1) ?
                ranges[nr + 1].begin :
                date_infinity;

        } else if ((nr < ranges.size() - 1) && (ranges[nr + 1].begin != ranges[nr].end)) {

            append_to_warning(tr("Setting end date of range %1 "
                                 "to start date of range %2.\n").
                              arg(nr + 1).
                              arg(nr + 2)
                              );

            ranges[nr].end = ranges[nr + 1].begin;

        } else if ((nr == ranges.size() - 1) && (ranges[nr].end < QDate::currentDate())) {

            append_to_warning(tr("Extending final range %1 to infinite "
                                 "to include present date.\n").arg(nr + 1));
            ranges[nr].end = date_infinity;
        }

        if (ranges[nr].cv <= 0) {

            err = tr("CV must be greater than zero in zone "
                     "range %1 of %2").arg(nr + 1).arg(fileName_);
            return false;
        }

        if (ranges[nr].zones.size()) {

            // check that the first zone starts with zero
            // ranges[nr].zones[0].lo = 0; // there is no reason we should enforce this

            // resolve zone end powers
            for (int nz = 0; nz < ranges[nr].zones.size(); nz++) {

                if (ranges[nr].zones[nz].hi == -1) {
                    ranges[nr].zones[nz].hi =
                        (nz < ranges[nr].zones.size() - 1) ?
                        ranges[nr].zones[nz + 1].lo :
                        INT_MAX;

                } else if ((nz < ranges[nr].zones.size() - 1) && (ranges[nr].zones[nz].hi != ranges[nr].zones[nz + 1].lo)) {

                    if (std::abs(ranges[nr].zones[nz].hi - ranges[nr].zones[nz + 1].lo) > 4.0) {

                        append_to_warning(tr("Range %1: matching top of zone %2 "
                                             "(%3) to bottom of zone %4 (%5).\n").
                                          arg(nr + 1).
                                          arg(ranges[nr].zones[nz].name).
                                          arg(ranges[nr].zones[nz].hi).
                                          arg(ranges[nr].zones[nz + 1].name).
                                          arg(ranges[nr].zones[nz + 1].lo)
                                          );

                    }
                    ranges[nr].zones[nz].hi = ranges[nr].zones[nz + 1].lo;

                } else if ((nz == ranges[nr].zones.size() - 1) && (ranges[nr].zones[nz].hi < INT_MAX)) {

                    append_to_warning(tr("Range %1: setting top of zone %2 from %3 to MAX.\n").
                                      arg(nr + 1).
                                      arg(ranges[nr].zones[nz].name).
                                      arg(ranges[nr].zones[nz].hi)
                                      );
                    ranges[nr].zones[nz].hi = INT_MAX;
                }
            }
        }
    }

    // mark zones as modified so pages which depend on zones can be updated
    modificationTime = QDateTime::currentDateTime();

    return true;
}

// note empty dates are treated as automatic matches for begin or
// end of range
int PaceZones::whichRange(const QDate &date) const
{
    for (int rnum = 0; rnum < ranges.size(); ++rnum) {

        const PaceZoneRange &range = ranges[rnum];
        if (((date >= range.begin) || (range.begin.isNull())) &&
            ((date < range.end) || (range.end.isNull())))
            return rnum;

    }
    return -1;
}

int PaceZones::numZones(int rnum) const
{
    assert(rnum < ranges.size());
    return ranges[rnum].zones.size();
}

int PaceZones::whichZone(int rnum, double value) const
{
    assert(rnum < ranges.size());
    const PaceZoneRange &range = ranges[rnum];

    for (int j = 0; j < range.zones.size(); ++j) {

        const PaceZoneInfo &info = range.zones[j];

        // note: the "end" of range is actually in the next zone
        if ((value >= info.lo) && (value < info.hi))
            return j;

    }

    // if we got here either it is negative, nan, inf or way high
    return -1;
}

void PaceZones::zoneInfo(int rnum, int znum, QString &name, QString &description, double &low, double &high) const
{
    assert(rnum < ranges.size());
    const PaceZoneRange &range = ranges[rnum];
    assert(znum < range.zones.size());
    const PaceZoneInfo &zone = range.zones[znum];
    name = zone.name;
    description = zone.desc;
    low = zone.lo;
    high = zone.hi;
}

double PaceZones::getCV(int rnum) const
{
    assert(rnum < ranges.size());
    return ranges[rnum].cv;
}

void PaceZones::setCV(int rnum, double cv)
{
    ranges[rnum].cv = cv;
    modificationTime = QDateTime::currentDateTime();
}

// generate a list of zones from CV
int PaceZones::lowsFromCV(QList <double> *lows, double cv) const {
    lows->clear();

    for (int z = 0; z < scheme.nzones_default; z++) {

        lows->append(scheme.zone_default_is_pct[z] ?  scheme.zone_default[z] * cv / 100.00f : scheme.zone_default[z]);

    }

    return scheme.nzones_default;
}

// access the zone name
QString PaceZones::getDefaultZoneName(int z) const {
    return scheme.zone_default_name[z];
}

// access the zone description
QString PaceZones::getDefaultZoneDesc(int z) const {
    return scheme.zone_default_desc[z];
}

// set the zones from the CV value (the cv variable)
void PaceZones::setZonesFromCV(PaceZoneRange &range)
{
    range.zones.clear();

    if (scheme.nzones_default == 0) initializeZoneParameters();

    for (int i = 0; i < scheme.nzones_default; i++) {

        double lo = scheme.zone_default_is_pct[i] ? scheme.zone_default[i] * range.cv / 100.00f : scheme.zone_default[i];
        double hi = lo;
        PaceZoneInfo zone(scheme.zone_default_name[i], scheme.zone_default_desc[i], lo, hi);
        range.zones.append(zone);
    }

    // sort the zones (some may be pct, others absolute, so zones need to be sorted,
    // rather than the defaults
    qSort(range.zones);

    // set zone end dates
    for (int i = 0; i < range.zones.size(); i++) {

        range.zones[i].hi =
            (i < scheme.nzones_default - 1) ?
            range.zones[i + 1].lo :
            INT_MAX;
    }

    // mark that the zones were set from CV, so if zones are subsequently
    // written, only CV is saved
    range.zonesSetFromCV = true;
}

void PaceZones::setZonesFromCV(int rnum)
{
    assert((rnum >= 0) && (rnum < ranges.size()));
    setZonesFromCV(ranges[rnum]);
}

// return the list of starting values of zones for a given range
QList <double> PaceZones::getZoneLows(int rnum) const
{
    if (rnum >= ranges.size()) return QList <double>();

    const PaceZoneRange &range = ranges[rnum];
    QList <double> return_values;

    for (int i = 0; i < range.zones.size(); i++) {
        return_values.append(ranges[rnum].zones[i].lo);
    }

    return return_values;
}

// return the list of ending values of zones for a given range
QList <double> PaceZones::getZoneHighs(int rnum) const
{

    if (rnum >= ranges.size()) return QList <double>();

    const PaceZoneRange &range = ranges[rnum];
    QList <double> return_values;

    for (int i = 0; i < range.zones.size(); i++) {
        return_values.append(ranges[rnum].zones[i].hi);
    }

    return return_values;
}

// return the list of zone names
QList <QString> PaceZones::getZoneNames(int rnum) const
{
    if (rnum >= ranges.size()) return QList <QString>(); 

    const PaceZoneRange &range = ranges[rnum];
    QList <QString> return_values;

    for (int i = 0; i < range.zones.size(); i++) {
        return_values.append(ranges[rnum].zones[i].name);
    }

    return return_values;
}

QString PaceZones::summarize(int rnum, QVector<double> &time_in_zone, QColor color) const
{

    assert(rnum < ranges.size());
    const PaceZoneRange &range = ranges[rnum];
    if (time_in_zone.size() != range.zones.size()) time_in_zone.resize(range.zones.size());

    // are we in metric or imperial ?
    bool metric = appsettings->value(this, GC_PACE, true).toBool();
    QString cvunit = metric ? "kph" : "mph";
    double cvfactor = metric ? 1.0f : KM_PER_MILE;
    QString paceunit = this->paceUnits(metric);

    QString summary;
    if(range.cv > 0) {
        summary += "<table align=\"center\" width=\"70%\" border=\"0\">";
        summary += "<tr><td align=\"center\">";
        summary += tr("Critical Velocity: %3%4 (%2%1)").arg(cvunit).arg(range.cv / cvfactor, 0, 'f', 2)
                                                        .arg(this->kphToPaceString(range.cv, metric))
                                                        .arg(paceunit);
        summary += "</td></tr></table>";
    }
    summary += "<table align=\"center\" width=\"70%\" ";
    summary += "border=\"0\">";
    summary += "<tr>";
    summary += tr("<td align=\"center\">Zone</td>");
    summary += tr("<td align=\"center\">Description</td>");
    summary += tr("<td align=\"center\">Low (%1)</td>").arg(paceunit);
    summary += tr("<td align=\"center\">High (%1)</td>").arg(paceunit);
    summary += tr("<td align=\"center\">Time</td>");
    summary += tr("<td align=\"center\">%</td>");
    summary += "</tr>";

    double duration = 0;
    foreach(double v, time_in_zone) {
        duration += v;
    }

    for (int zone = 0; zone < time_in_zone.size(); ++zone) {

        if (time_in_zone[zone] > 0.0) {
            QString name, desc;
            double lo, hi;
            zoneInfo(rnum, zone, name, desc, lo, hi);
            if (zone % 2 == 0)
                summary += "<tr bgcolor='" + color.name() + "'>"; else
                summary += "<tr>"; summary += QString("<td align=\"center\">%1</td>").arg(name);
            summary += QString("<td align=\"center\">%1</td>").arg(desc);
            summary += QString("<td align=\"center\">%1</td>").arg(this->kphToPaceString(lo, metric));
            if (hi == INT_MAX)
                summary += "<td align=\"center\">MAX</td>"; else
                summary += QString("<td align=\"center\">%1</td>").arg(this->kphToPaceString(hi, metric));
                summary += QString("<td align=\"center\">%1</td>").arg(time_to_string((unsigned) round(time_in_zone[zone])));
            summary += QString("<td align=\"center\">%1</td>")
                       .arg((double)time_in_zone[zone]/duration * 100, 0, 'f', 0);
            summary += "</tr>";
        }
    }
    summary += "</table>";
    return summary;
}

#define USE_SHORT_POWER_ZONES_FORMAT true   /* whether a less redundent format should be used */
void PaceZones::write(QDir home)
{
    QString strzones;

    // always write the defaults (config pane can adjust)
    strzones += QString("DEFAULTS:\n");

    for (int z = 0; z < scheme.nzones_default; z++) {

        strzones += QString("%1,%2,%3%4\n").
                    arg(scheme.zone_default_name[z]).
                    arg(scheme.zone_default_desc[z]).
                    arg(scheme.zone_default[z]).
                    arg(scheme.zone_default_is_pct[z] ? "%" : "");

    }
    strzones += QString("\n");

    for (int i = 0; i < ranges.size(); i++) {

        double cv = getCV(i);

        // print header for range
        // note this explicitly sets the first and last ranges such that all time is spanned

#if USE_SHORT_POWER_ZONES_FORMAT

        // note: BEGIN is not needed anymore
        //       since it becomes Jan 01 1900
        strzones += QString("%1: CV=%2").arg(getStartDate(i).toString("yyyy/MM/dd")).arg(cv);
        strzones += QString("\n");

        // step through and print the zones if they've been explicitly set
        if (!ranges[i].zonesSetFromCV) {
            for (int j = 0; j < ranges[i].zones.size(); j++) {
                const PaceZoneInfo &zi = ranges[i].zones[j];
                strzones += QString("%1,%2,%3\n").arg(zi.name).arg(zi.desc).arg(zi.lo);
            }
            strzones += QString("\n");
        }
#else
        if(ranges.size() <= 1) {

            strzones += QString("FROM BEGIN UNTIL END, CV=%1:").arg(cv);

        } else if (i == 0) {

            strzones += QString("FROM BEGIN UNTIL %1, CV=%2:").arg(getEndDate(i).toString("yyyy/MM/dd")).arg(cv);

        } else if (i == ranges.size() - 1) {

            strzones += QString("FROM %1 UNTIL END, CV=%2:").arg(getStartDate(i).toString("yyyy/MM/dd")).arg(cv);
        } else {
            strzones += QString("FROM %1 UNTIL %2, CV=%3:").arg(getStartDate(i).toString("yyyy/MM/dd")).arg(getEndDate(i).toString("yyyy/MM/dd")).arg(cv);
        }

        strzones += QString("\n");
        for (int j = 0; j < ranges[i].zones.size(); j++) {

            const PaceZoneInfo &zi = ranges[i].zones[j];

            if (ranges[i].zones[j].hi == INT_MAX) {
                strzones += QString("%1,%2,%3,MAX\n").arg(zi.name).arg(zi.desc).arg(zi.lo);

            } else {

                strzones += QString("%1,%2,%3,%4\n").arg(zi.name).arg(zi.desc).arg(zi.lo).arg(zi.hi);
            }
        }
        strzones += QString("\n");
#endif
    }

    QFile file(home.canonicalPath() + "/" + fileName_);
    if (file.open(QFile::WriteOnly)) {
        QTextStream stream(&file);
        stream << strzones;
        file.close();
    } else {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);
        msgBox.setText(tr("Problem Saving Pace Zones"));
        msgBox.setInformativeText(tr("File: %1 cannot be opened for 'Writing'. Please check file properties.").arg(home.canonicalPath() + "/" + fileName_));
        msgBox.exec();
        return;
    }
}
Exemple #24
0
void ui_agregarMontura::on_pushButton_agregar_clicked()
{
    if(!verificarRestricciones())
        return;
    pMontura.setCodigo(ui->lineEdit_codigo->text());
    pMontura.setDescripcion(ui->lineEdit_descripcion->text());
    pMontura.setPrecioCompra(ui->lineEdit_precioCompra->text());
    pMontura.setPrecioVenta(ui->lineEdit_precioVenta->text());
    pMontura.setPrecioDescuento(ui->lineEdit_precioDescuento->text());
    pMontura.setAccesorios(ui->lineEdit_accesorios->text());
    pMontura.setStock(ui->spinBox_stock->text());
    pMontura.setObservaciones(ui->lineEdit_observaciones->text());
    estado pEstado;pEstado.setNombre(ui->comboBox_estado->currentText());pEstado.completar();
    marca pMarca;pMarca.setNombre(ui->comboBox_marca->currentText());pMarca.completar();
    //colaborador
    forma pForma;pForma.setNombre(ui->comboBox_forma->currentText());pForma.completar();
    color pColor;pColor.setNombre(ui->comboBox_color->currentText());pColor.completar();
    tamanio pTamanio;pTamanio.setNombre(ui->comboBox_tamanio->currentText());pTamanio.completar();
    calidad pCalidad;pCalidad.setNombre(ui->comboBox_calidad->currentText());pCalidad.completar();
    pMontura.setEstado(pEstado);
    pMontura.setMarca(pMarca);
    //colaborador
    pMontura.setForma(pForma);
    pMontura.setColor(pColor);
    pMontura.setTamanio(pTamanio);
    pMontura.setCalidad(pCalidad);
    if(modo==0)//agrego
    {
        pEstado.setNombre("activo");pEstado.completar();
        pMontura.setEstado(pEstado);
        if(pMontura.agregar())
        {
            this->close();
            emit guardado();
        }
        else
        {
            QMessageBox box;
            box.setIcon(QMessageBox::Critical);
            box.setWindowTitle("Error");
            box.setText("El producto no se pudo agregar!");
            box.setStandardButtons(QMessageBox::Ok);
            box.setDefaultButton(QMessageBox::Ok);
            box.exec();
        }
    }
    else//actualizo
    {
        if(pMontura.actualizar())
        {
            this->close();
            emit guardado();
        }
        else
        {
            QMessageBox box;
            box.setIcon(QMessageBox::Critical);
            box.setWindowTitle("Error");
            box.setText("El producto no se pudo actualizar!");
            box.setStandardButtons(QMessageBox::Ok);
            box.setDefaultButton(QMessageBox::Ok);
            box.exec();
        }
    }
}
Exemple #25
0
void ConfigDialog::accept()
{
    bool needRestart=false;

//vst directory
    QString vstDir = ui->defaultVstPath->itemData( ui->defaultVstPath->currentIndex() ).toString();
    if(vstDir != "systemDefault" && vstDir != "fromLastSession") {
        vstDir = ui->defaultVstPath->currentText();
        QDir dir;
        if(vstDir.isEmpty() || !dir.exists(vstDir)) {
            QMessageBox msg(QMessageBox::Critical,
                            tr("Error"),
                            tr("Vst path is not a valid directory"),
                            QMessageBox::Ok,
                            this);
            msg.exec();
            ui->defaultVstPath->setFocus();
            return;
        }
    }

//bank directory
    QString bankDir = ui->defaultBankPath->itemData( ui->defaultBankPath->currentIndex() ).toString();
    if(bankDir != "fromLastSession") {
        bankDir = ui->defaultBankPath->currentText();
        QDir dir;
        if(bankDir.isEmpty() || !dir.exists(bankDir)) {
            QMessageBox msg(QMessageBox::Critical,
                            tr("Error"),
                            tr("Bank path is not a valid directory"),
                            QMessageBox::Ok,
                            this);
            msg.exec();
            ui->defaultBankPath->setFocus();
            return;
        }
    }

//setup file
    QString setupFile =  ui->defaultSetup->itemData( ui->defaultSetup->currentIndex() ).toString();
    if(setupFile != "empty" && setupFile != "fromLastSession") {
        setupFile = ui->defaultSetup->currentText();
        QFile file;
        if(!file.exists(setupFile) || !setupFile.endsWith(SETUP_FILE_EXTENSION)) {
            QMessageBox msg(QMessageBox::Critical,
                            tr("Error"),
                            tr("Setup file is not valid"),
                            QMessageBox::Ok,
                            this);
            msg.exec();
            ui->defaultSetup->setFocus();
            return;
        }
    }

//project file
    QString projectFile =  ui->defaultProject->itemData( ui->defaultProject->currentIndex() ).toString();
    if(projectFile != "empty" && projectFile != "fromLastSession") {
        projectFile = ui->defaultProject->currentText();
        QFile file;
        if(!file.exists(projectFile) || !projectFile.endsWith(PROJECT_FILE_EXTENSION)) {
            QMessageBox msg(QMessageBox::Critical,
                            tr("Error"),
                            tr("Project file is not valid"),
                            QMessageBox::Ok,
                            this);
            msg.exec();
            ui->defaultProject->setFocus();
            return;
        }
    }

//default files
    myHost->SetSetting("defaultVstPath", vstDir );
    myHost->SetSetting("defaultBankPath", bankDir );
    myHost->SetSetting("defaultSetupFile", setupFile );
    myHost->SetSetting("defaultProjectFile", projectFile );

    bool precision = ui->samplePrecision->itemData(ui->samplePrecision->currentIndex()).toBool();
    if(defaultDoublePrecision(myHost)!=precision)
        needRestart=true;
    myHost->SetSetting("doublePrecision",precision);

//on unsaved changes
    myHost->SetSetting("onUnsavedSetup", ui->onUnsavedSetup->itemData( ui->onUnsavedSetup->currentIndex() ).toInt() );
    myHost->SetSetting("onUnsavedProject", ui->onUnsavedProject->itemData( ui->onUnsavedProject->currentIndex() ).toInt() );

//engine
    int oldNbThreads = myHost->GetSetting("NbThreads",0).toInt();
    int newNbThreads = ui->nbThreads->value();
    if( newNbThreads != oldNbThreads ) {
        myHost->SetSetting("NbThreads", newNbThreads);
    }
//hide/close editors
    myHost->SetSetting("fastEditorsOpenClose", ui->fastEditorOpenClose->isChecked());

    QDialog::accept();

    if(needRestart) {
        QMessageBox msg;
        msg.setText(tr("You must restart VstBoard for the changes to take effect"));
        msg.setIcon(QMessageBox::Information);
        msg.exec();
    }
}
Exemple #26
0
bool ui_agregarMontura::verificarRestricciones()
{
    QRegExp noNumeros("[a-zA-Z]");
    QRegExp noAlfabeto("[0-9\.\,\@]");

    QMessageBox box;
    box.setIcon(QMessageBox::Warning);
    box.setWindowTitle("Error de Escritura");

    if(ui->lineEdit_codigo->text().size() == 0)
    {
        box.setText("El Codigo es obligatorio");
        box.exec();
        ui->lineEdit_codigo->setFocus();
        return false;
    }
    if(ui->lineEdit_precioCompra->text().contains(noNumeros))
    {
        box.setText("El Precio de Compra solo puede contener numeros");
        box.exec();
        ui->lineEdit_precioCompra->setFocus();
        return false;
    }
    if(ui->lineEdit_precioCompra->text().size() == 0)
    {
        box.setText("El Precio de Compra es obligatorio");
        box.exec();
        ui->lineEdit_precioCompra->setFocus();
        return false;
    }
    if(ui->lineEdit_precioVenta->text().contains(noNumeros))
    {
        box.setText("El Precio de Venta solo puede contener numeros");
        box.exec();
        ui->lineEdit_precioVenta->setFocus();
        return false;
    }
    if(ui->lineEdit_precioVenta->text().size() == 0)
    {
        box.setText("El Precio de Venta es obligatorio");
        box.exec();
        ui->lineEdit_precioVenta->setFocus();
        return false;
    }
    if(ui->lineEdit_precioDescuento->text().contains(noNumeros))
    {
        box.setText("El Precio de Descuento solo puede contener numeros");
        box.exec();
        ui->lineEdit_precioDescuento->setFocus();
        return false;
    }
    if(ui->lineEdit_precioDescuento->text().size() == 0)
    {
        box.setText("El Precio de Descuento es obligatorio");
        box.exec();
        ui->lineEdit_precioDescuento->setFocus();
        return false;
    }
    if(!ui->comboBox_marca->selecciono())
    {
        box.setText("Seleccione alguna Marca");
        box.exec();
        ui->comboBox_marca->setFocus();
        return false;
    }
    if(!ui->comboBox_tamanio->selecciono())
    {
        box.setText("Seleccione algun Tamaño");
        box.exec();
        ui->comboBox_tamanio->setFocus();
        return false;
    }
    if(!ui->comboBox_forma->selecciono())
    {
        box.setText("Seleccione alguna Forma");
        box.exec();
        ui->comboBox_forma->setFocus();
        return false;
    }
    if(!ui->comboBox_calidad->selecciono())
    {
        box.setText("Seleccione alguna Calidad");
        box.exec();
        ui->comboBox_calidad->setFocus();
        return false;
    }
    if(!ui->comboBox_color->selecciono())
    {
        box.setText("Seleccione algun Color");
        box.exec();
        ui->comboBox_color->setFocus();
        return false;
    }
    if(modo==1)
        if(!ui->comboBox_estado->selecciono())
        {
            box.setText("Seleccione algun Estado");
            box.exec();
            ui->comboBox_estado->setFocus();
            return false;
        }
    return true;
}
void AddEditCryptbitNode::on_okButton_clicked()
{
    if(ui->aliasLineEdit->text() == "")
    {
	QMessageBox msg;
        msg.setText("Please enter an alias.");
	msg.exec();
	return;
    }
    else if(ui->addressLineEdit->text() == "")
    {
	QMessageBox msg;
        msg.setText("Please enter an address.");
	msg.exec();
	return;
    }
    else
    {
	CCryptbitNodeConfig c;
        c.sAlias = ui->aliasLineEdit->text().toStdString();
	c.sAddress = ui->addressLineEdit->text().toStdString();
        CKey secret;
        secret.MakeNewKey(false);
        c.sMasternodePrivKey = CBitcoinSecret(secret).ToString();
	
        CWalletDB walletdb(pwalletMain->strWalletFile);
        CAccount account;
        walletdb.ReadAccount(c.sAlias, account);
        bool bKeyUsed = false;
	bool bForceNew = false;

        // Check if the current key has been used
        if (account.vchPubKey.IsValid())
        {
            CScript scriptPubKey;
            scriptPubKey.SetDestination(account.vchPubKey.GetID());
            for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
                 it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
                 ++it)
            {
                const CWalletTx& wtx = (*it).second;
                BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                    if (txout.scriptPubKey == scriptPubKey)
                        bKeyUsed = true;
            }
        }

        // Generate a new key
        if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
        {
            if (!pwalletMain->GetKeyFromPool(account.vchPubKey))
            {
		QMessageBox msg;
                msg.setText("Keypool ran out, please call keypoolrefill first.");
		msg.exec();
		return;
	    }
            pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), c.sAlias);
            walletdb.WriteAccount(c.sAlias, account);
        }

        c.sCollateralAddress = CBitcoinAddress(account.vchPubKey.GetID()).ToString();

        pwalletMain->mapMyCryptbitNodes.insert(make_pair(c.sAddress, c));
	walletdb.WriteCryptbitNodeConfig(c.sAddress, c);
        uiInterface.NotifyCryptbitNodeChanged(c);

        accept();
    }
QStringList* main_string_normalization(QString &temp){
    //пеержиток прошлой реализации
    QStringList *temp_string_list = new QStringList;
    //qDebug() >> "main_string_normalization()";
    //Literature::deleteExcessControlSymbols(temp);
    //    while (temp.indexOf("  ") + 1)
    //      temp.replace("  ", " ");
    //    for (int i = 0; i < temp.size(); ++i){
    //        if ((temp[i] == '\n' && temp[i-1] == ' ')
    //            || (temp[i] == '\n' && temp[i-1] == ','))
    //          {
    //            temp.remove(i, 1);
    //            i--;
    //          }
    //      }
    //    QRegExp multipleNewLines("\\n{2,}");
    //    QRegExp multipleSpaces("\\s{2,}");
    //    temp.replace(multipleNewLines, "\n");
    //    temp.replace(multipleSpaces, " ");
    //чтобы обрабатывать каждый экземпляр по отдельности
    //это нужно чтобы решить проблему со вставкой сшивателя
    //после фамилии первого автора, после которой идет запятая

    //QChar(0x2d) - дефис
    //QChar(0x2116) - №
    //  QChar(0x2010)	8208	HYPHEN	‐
    //  QChar(0x2011)	8209	NON-BREAKING HYPHEN	‑ дефис не переносящийся на следующую строку
    //  QChar(0x2012)	8210	FIGURE DASH	‒
    //  QChar(0x2013)	8211	EN DASH	–
    //  QChar(0x2014)	8212	EM DASH	—
    //  QChar(0x2015)	8213	HORIZONTAL BAR	―
    QString tire("[");
    tire.append(QChar(0x2d));
    tire.append(QChar(0x2010));
    tire.append(QChar(0x2011));
    tire.append(QChar(0x2012));
    //tire.append(QChar(0x2013));
    tire.append(QChar(0x2014));
    tire.append(QChar(0x2015));
    tire.append(QChar(']'));

    QString widetire(QChar(0x2013));
    QRegExp regTire(tire);
    temp = temp.replace(regTire,widetire);
    //TODO для оптимизации можно заменить манипуляции с памятью и стринг листом, чтобы функция вернула стринг лист,
    //но придется сделать temp_string_list объектом а не указателем (переписать моменты с temp_string_list где он используется как указатель)
    if (temp_string_list != nullptr)
        delete temp_string_list;
    temp_string_list = new QStringList;

    (*temp_string_list) = temp.split("\n", QString::SplitBehavior::SkipEmptyParts);

    for (int n = 0; n < (temp_string_list)->size(); ++n)
    {
        for (int i = 1; i < (*temp_string_list)[n].size(); ++i)
        {
            if ((*temp_string_list)[n][i] == '–'
                    || ((*temp_string_list)[n][i] == '/'
                        || (*temp_string_list)[n][i] == ':'
                        || (*temp_string_list)[n][i] == QChar(0x2013))
                    && (*temp_string_list)[n][i-1] == ' ')
                (*temp_string_list)[n][i-1] = QChar::Nbsp;
            //          else if ((*temp_string_list)[n][i] == QChar(0x2d)
            //                   && (*temp_string_list)[n][i-1].isNumber())
            //            (*temp_string_list)[n][i] = QChar(0x2011);
            else if ((*temp_string_list)[n][i] == QChar(0x2116)
                     && (*temp_string_list)[n][i+1] == ' ')
                (*temp_string_list)[n][i+1] = QChar::Nbsp;
            else if ((*temp_string_list)[n][i].isUpper()
                     && (i+3) < (*temp_string_list)[n].size()
                     && (*temp_string_list)[n][i+1] == '.'
                     && (*temp_string_list)[n][i+2].isUpper()
                     && ((*temp_string_list)[n][i+3].isSpace() || (*temp_string_list)[n][i+3] == '.')){
                (*temp_string_list)[n].insert(i+2, QChar::Nbsp);
                i++;
            }
            //СЛЕДУЮЩЕЕ УСЛОВИЕ не корректно тк срабатывает и в случаях, когда имя автора идет вначале, потом его инициалы, и сшивка
            else if ((*temp_string_list)[n][i].isUpper()
                     && (i+4) < (*temp_string_list)[n].size()
                     && (*temp_string_list)[n][i+1] == '.'
                     && (*temp_string_list)[n][i+2].isSpace()
                     && (*temp_string_list)[n][i+3].isUpper()) //это то из-за чего весь сыр бром
                // && ((*temp_string_list)[n][i+4].isSpace() || (*temp_string_list)[n][i+4] == '.'))
            {
                if (i > 20) //тут идет волшебное число, до 20 символов - начало
                    (*temp_string_list)[n][i+2] = QChar::Nbsp;
                else  (*temp_string_list)[n][i-1] = QChar::Nbsp;
            }
            else if (((*temp_string_list)[n][i] == QChar(0x2013) || (*temp_string_list)[n][i] == QChar(0x2116) || (*temp_string_list)[n][i] == QChar(0x2d))
                     && (*temp_string_list)[n][i-1].isNumber()
                     && (*temp_string_list)[n][i+1].isNumber()){
                (*temp_string_list)[n][i] = QChar(0x2011);
                //qDebug() >> (*temp_string_list)[n][i+1].isNumber() >> QString("=") >> (*temp_string_list)[n][i-1] >> QString(" ") >> (*temp_string_list)[n][i+1];
            }
            else if ((*temp_string_list)[n][i].isNumber()
                     && i+4 < (*temp_string_list)[n].size()
                     && ((*temp_string_list)[n][i+1] == ' ' || (*temp_string_list)[n][i+1] == QChar::Nbsp)
                     && (*temp_string_list)[n][i+2] == QChar(0x2013) /*|| (*temp_string_list)[n][i+2] == QChar(0x2116) || (*temp_string_list)[n][i+2] == QChar(0x2d)*/
                     && ((*temp_string_list)[n][i+3] == ' ' || (*temp_string_list)[n][i+3] == QChar::Nbsp)
                     && (*temp_string_list)[n][i+4].isNumber()){
                // осторожно, костыль %1
                (*temp_string_list)[n][i+1] = QChar(9792);
                (*temp_string_list)[n][i+2] = QChar(9792);
                (*temp_string_list)[n][i+3] = QChar(9792);
            }
            else if ((*temp_string_list)[n][i].isNumber()
                     && i+3 < (*temp_string_list)[n].size()
                     && ((*temp_string_list)[n][i+1] == ' ' || (*temp_string_list)[n][i+1] == QChar::Nbsp)
                     && (*temp_string_list)[n][i+2] == QChar(0x2013)
                     && (*temp_string_list)[n][i+3].isNumber()){

                // осторожно, костыль %1
                (*temp_string_list)[n][i+1] = QChar(9792);
                (*temp_string_list)[n][i+2] = QChar(9792);
                (*temp_string_list)[n].insert((i+3),QChar(9792));
            }
        }
        QString before = "♀♀♀"; // осторожно, костыль %1
        QString after = QChar(0x2011);
        (*temp_string_list)[n] = (*temp_string_list)[n].replace(before, after);
        (*temp_string_list)[n] = (*temp_string_list)[n].replace('\t', "");
    }
    //потеряный нон брейкабл дефис нужно восстановить (он может быть автоматически заменен на пробел или нонбрейкабл пробел
    QRegExp lostedHyphen("(\\d+[  ]\\d+)");
    for(int count = 0; count < temp_string_list->size(); ++count){
        if(temp_string_list->at(count).contains(lostedHyphen)){
            int pos = 0;
            //qDebug() >> pos >> "\t" >> temp_string_list->at(count);
            while((pos = lostedHyphen.indexIn(temp_string_list->at(count)), pos) != -1){
                for(; pos < temp_string_list->at(count).size(); ++pos){
                    if(temp_string_list->at(count).at(pos) == QChar::Space ||
                            temp_string_list->at(count).at(pos) == QChar::Nbsp){
                        (*temp_string_list)[count][pos] = QChar(0x2011);
                        break;
                    }
                }
                pos += lostedHyphen.matchedLength();
            }
        }
    }

    //нон брейкабл пробел перед страницами (P. || p. || C. || c.)

    QRegExp pagesProblem("[PCРС]. \\d+");
    QRegExp pagesProblemAtTheEnd("[pcрс]");
    for(int count = 0; count < temp_string_list->size(); ++count){
            int pos = pagesProblem.indexIn(temp_string_list->at(count));
            int pos2 = temp_string_list->at(count).size()-2;
            if(pos != -1 && pos+2 < temp_string_list->at(count).size()){
                if((*temp_string_list)[count][pos+2] == QChar::Space){
                    (*temp_string_list)[count][pos+2] = QChar::Nbsp;
                }
            }
            else if(pos2 > 0 &&
                    ((pos2 = pagesProblemAtTheEnd.indexIn(temp_string_list->at(count), pos2)) != -1)){
                //qDebug() << (*temp_string_list)[count][pos2-1] >> "\t" >> temp_string_list->at(count);
                    if((*temp_string_list)[count][pos2-1] == QChar::Space){
                        (*temp_string_list)[count][pos2-1] = QChar::Nbsp;
                    }
                }
            else {
               // qDebug() >> "ОШИБКА в : " >> temp_string_list->at(count);
                QMessageBox mess;
                QString messageText =  "ОШИБКА в : " + temp_string_list->at(count);
                mess.setText(messageText);
                mess.setStandardButtons(QMessageBox::Yes);
                if(mess.exec() == QMessageBox::Yes)
                    QApplication::quit();
            }

        }

        return temp_string_list;
    }
Exemple #29
0
void AddANewStudent::submited()
{
    QSqlQuery query;
    query.prepare( "insert into student (ticketnumber, studentnumber, direction, studentidentity, graduatelevel, name, picture, gender, address, emailaddress, birthday, telephoneday, telephonenight, mobile, graduateschool, graduatedepartment, companyname, currentposition, creditclass) values(:ticketnumber, :studentnumber, :direction, :studentidentity, :graduatelevel, :name, :picture, :gender, :address, :emailaddress, :birthday, :telephoneday, :telephonenight, :mobile, :graduateschool, :graduatedepartment, :companyname, :currentposition, :creditclass)" );
    QString mentionstring = "";
    if(ticketnumber->text().isEmpty()){
        msg.setWindowTitle("警告");
        msg.setIcon(QMessageBox::Critical);
        msg.setText("准考證號碼為必填項目");
        msg.exec();
        return;
    }else{
        QString ticket = ticketnumber->text().toUpper();
        QSqlQuery check("select * from student where ticketnumber = '"+ticket+"'");
        if(check.size()){
            msg.setWindowTitle("警告");
            msg.setIcon(QMessageBox::Critical);
            msg.setText("資料庫已有該准考證號碼");
            msg.exec();
            return;
        }
        query.bindValue(":ticketnumber",ticketnumber->text());
    }
    if(studentnumberedit->text().isEmpty()){
        msg.setWindowTitle("警告");
        msg.setIcon(QMessageBox::Critical);
        msg.setText("學號為必填項目");
        msg.exec();
        return;
    }
    else{
        QString studentnumber = studentnumberedit->text().toUpper();
        QSqlQuery check("select * from student where studentnumber = '"+studentnumber+"'");
        if(check.size()){
            msg.setWindowTitle("警告");
            msg.setIcon(QMessageBox::Critical);
            msg.setText("資料庫已有該學號");
            msg.exec();
            return;
        }
        if(studentnumber.left(2) != "R0"){
            msg.setWindowTitle("警告");
            msg.setIcon(QMessageBox::Critical);
            msg.setText("學號前兩碼必為R0");
            msg.exec();
            return;
        }
        if(studentnumber.left(5).right(3) != "000" && studentnumber.left(5).right(3).toInt() == 0){
            msg.setWindowTitle("警告");
            msg.setIcon(QMessageBox::Critical);
            msg.setText("無法從學號提取出畢業年度(三到五碼不是數字?)");
            msg.exec();
            return;
        }else{
            int graduate = studentnumber.left(5).right(3).toInt();
            graduate -= 597;
            if(graduate < 50){
                msg.setWindowTitle("警告");
                msg.setIcon(QMessageBox::Critical);
                msg.setText("從學號提取的畢業年度錯誤");
                msg.exec();
                return;
            }
            query.bindValue(":graduatelevel",graduate);
        }
        query.bindValue(":studentnumber",studentnumber);
    }
    if(nameedit->text().isEmpty()){
        if(!mentionstring.isEmpty())
            mentionstring += "\n";
        mentionstring += "姓名" ;
    }else{
        query.bindValue(":name",nameedit->text());
    }
    if(direction->text().isEmpty()){
        if(!mentionstring.isEmpty())
            mentionstring += "\n";
        mentionstring += "所在地區" ;
    }else{
        query.bindValue(":direction",direction->text());
    }
    if(address->text().isEmpty()){
        if(!mentionstring.isEmpty())
            mentionstring += "\n";
        mentionstring += "通訊地址" ;
    }else{
        query.bindValue(":address",address->text());
    }
    if(emailaddress->text().isEmpty()){
        if(!mentionstring.isEmpty())
            mentionstring += "\n";
        mentionstring += "電子郵件" ;
    }else{
        query.bindValue(":emailaddress",emailaddress->text());
    }
    if(telephoneday->text().isEmpty()){
        if(!mentionstring.isEmpty())
            mentionstring += "\n";
        mentionstring += "電話(日)" ;
    }else{
        query.bindValue(":telephoneday",telephoneday->text());
    }
    if(telephonenight->text().isEmpty()){
        if(!mentionstring.isEmpty())
            mentionstring += "\n";
        mentionstring += "電話(夜)" ;
    }else{
        query.bindValue(":telephonenight",telephonenight->text());
    }
    if(mobile->text().isEmpty()){
        if(!mentionstring.isEmpty())
            mentionstring += "\n";
        mentionstring += "手機電話" ;
    }else{
        query.bindValue(":mobile",mobile->text());
    }
    if(studentidentity->text().isEmpty()){
        if(!mentionstring.isEmpty())
            mentionstring += "\n";
        mentionstring += "報考身分" ;
    }else{
        query.bindValue(":studentidentity",studentidentity->text());
    }
    if(graduateschool->text().isEmpty()){
        if(!mentionstring.isEmpty())
            mentionstring += "\n";
        mentionstring += "畢業學校" ;
    }else{
        query.bindValue(":graduateschool",graduateschool->text());
    }
    if(graduatedepartment->text().isEmpty()){
        if(!mentionstring.isEmpty())
            mentionstring += "\n";
        mentionstring += "畢業科系" ;
    }else{
        query.bindValue(":graduatedepartment",graduatedepartment->text());
    }
    if(picturewidget->pictureinsert){
        QByteArray byteArray;
        QBuffer buffer(&byteArray);
        picturewidget->img.save(&buffer, "JPG"); // writes the image in PNG format inside the buffer
        query.bindValue(":picture",byteArray);
    }else{
        if(!mentionstring.isEmpty())
            mentionstring += "\n";
        mentionstring += "個人照片" ;
    }

    if(male->isChecked() || female->isChecked()){
        if(male->isChecked()){
            query.bindValue(":gender","男");
        }else{
            query.bindValue(":gender","女");
        }
    }else{
        if(!mentionstring.isEmpty())
            mentionstring += "\n";
        mentionstring += "性別" ;
    }
    if(creditclassbuttonyes->isChecked() || creditclassbuttonyes->isChecked()){
        if(creditclassbuttonyes->isChecked()){
            query.bindValue(":creditclass",1);
        }else{
            query.bindValue(":creditclass",0);
        }
    }else{
        if(!mentionstring.isEmpty())
            mentionstring += "\n";
        mentionstring += "學分班選擇" ;
    }
    query.bindValue(":birthday",dateinput->text());

    if(companyname->text().isEmpty()){
        if(!mentionstring.isEmpty())
            mentionstring += "\n";
        mentionstring += "公司名稱" ;
    }else{
        query.bindValue(":companyname",companyname->text());
    }
    if(companyposition->text().isEmpty()){
        if(!mentionstring.isEmpty())
            mentionstring += "\n";
        mentionstring += "公司電話" ;
    }else{
        query.bindValue(":currentposition",companyposition->text());
    }
    if(mentionstring.isEmpty()){
        if(query.exec()){
            QImage icon;
            icon.load("right.png");
            icon = icon.scaledToWidth(50);
            msg.setWindowTitle("完成");
            msg.setIconPixmap(QPixmap::fromImage(icon));
            msg.setText("資料已寫入");
            msg.exec();
        }else{
            QImage icon;
            icon.load("error.png");
            icon = icon.scaledToWidth(50);
            msg.setWindowTitle("錯誤");
            msg.setIconPixmap(QPixmap::fromImage(icon));
            msg.setText("資料寫入失敗");
            msg.exec();
        }
    }else{
        QMessageBox questmsg;
        questmsg.setWindowTitle("提示");
        questmsg.setText("以下為還沒填入的項目");
        questmsg.setInformativeText(mentionstring+"\n\n請問仍要輸入到資料庫嗎");
        questmsg.setIcon(QMessageBox::Warning);
        questmsg.layout()->setMargin(15);
        questmsg.layout()->setSpacing(10);
        QFont font;
        font.setPixelSize(15);
        font.setFamily("微軟正黑體");
        questmsg.setFont(font);
        questmsg.addButton(QMessageBox::Yes);
        questmsg.addButton(QMessageBox::No);
        if(questmsg.exec() == QMessageBox::Yes){
            if(query.exec()){
                QImage icon;
                icon.load("right.png");
                icon = icon.scaledToWidth(50);
                msg.setWindowTitle("完成");
                msg.setIconPixmap(QPixmap::fromImage(icon));
                msg.setText("資料已寫入");
                msg.exec();
            }else{
                QImage icon;
                icon.load("error.png");
                icon = icon.scaledToWidth(50);
                msg.setWindowTitle("錯誤");
                msg.setIconPixmap(QPixmap::fromImage(icon));
                msg.setText("資料寫入失敗");
                msg.exec();
            }
        }
    }
    /*QByteArray byteArray;
    QBuffer buffer(&byteArray);
    picturewidget->img.save(&buffer, "png"); // writes the image in PNG format inside the buffer
    QSqlQuery query;
    query.prepare( "insert into student(studentnumber,picture)values('bbbbbbb',:img)" );
    //query.bindValue(":img",byteArray);
    query.exec();*/
    /*QSqlQuery query;
    query.prepare( "select * from student where studentnumber = 'bbbbbbb'" );
    query.exec();
    query.next();
    QByteArray byteArray;
    byteArray = query.value(1).toByteArray();
    picturewidget->img.loadFromData(byteArray);
    picturewidget->setPixmap(QPixmap::fromImage(picturewidget->img));*/
}
Exemple #30
0
bool dh_solver::initialize()
{
	if (FreeLength < InstallLength)
	{
		QMessageBox msgbox;
		msgbox.setText(kor("장착길이 입력값이 자유장 길이를 초과합니다."));
		msgbox.setIcon(QMessageBox::Critical);
		msgbox.exec();
		return false;
	}
	
	cMinStiffness = 0.8;
	cMaxStiffness = 3;
	cMinStress = cMaxStress * 0.8;
	cWeight = 120;
	cMass = 50;
	PreComp = FreeLength - InstallLength;
	TotalComp = PreComp + Stroke;
	BHLimit = FreeLength - (TotalComp / DisBH);

	N_Lower = N + NLower;
	N_Upper = N + NUpper;
	D_Lower = D + DLower;
	D_Upper = D + DUpper;
	d_Lower = d + dLower;
	d_Upper = d + dUpper;
	Free_length_lower = FreeLength + FreeLengthLower;
	Free_length_upper = FreeLength + FreeLengthUpper;

	// Reference 스프링의 강성, 질량, 응력 등 계산
	k_ref = (shearModulus * pow(d, 4)) / (8 * N * pow(D, 3));
	Mass = density * (pow(M_PI, 2) * pow(d, 2) * D * (N + 1.6)) / 4;
	Mass_EB = density * (pow(M_PI, 2) * pow(d, 2) * D * 0.8) / 4;
	C = D / d;
	AR = FreeLength / D;
	B_Height = (N + 1.6) * d;
	P = k_ref * TotalComp;
	P_BH = k_ref * (FreeLength - B_Height);
	Kw = (4 * C - 1) / (4 * C - 4) + 0.615 / C;
	Sc = (8 * D * P * Kw) / (M_PI * pow(d, 3));
	Sc_BH = (8 * D * P_BH * Kw) / (M_PI * pow(d, 3));
	PE_full_ref = 0.5 * k_ref * 9.81 * 1000 * pow(TotalComp * 0.001, 2);
	PE_init_ref = 0.5 * k_ref * 9.81 * 1000 * pow(PreComp * 0.001, 2);
	PE_act_ref = PE_full_ref - PE_init_ref;

	//if ((FreeLength - TotalComp) <= B_Height){
	//	QMessageBox msgbox;
	//	msgbox.setText(kor("밀착고가));
	//	msgbox.setIcon(QMessageBox::Critical);
	//	msgbox.exec();
	//}

	v_ep = lumped(k_ref, Mass, Mass_EB, eq_mass, TotalComp, PreComp);

	transfer_energy_ref = 0.5 * eq_mass * pow(v_ep, 2);
	efficiency_ref = transfer_energy_ref / PE_act_ref;


	ref_result.N = N;
	ref_result.D = D;
	ref_result.d = d;
	ref_result.FreeLength = FreeLength;
	ref_result.k = k_ref;
	ref_result.Mass = Mass;
	ref_result.B_Height = B_Height;
	ref_result.P = P;
	ref_result.P_BH = P_BH;
	ref_result.Sc = Sc;
	ref_result.Sc_BH = Sc_BH;
	ref_result.PE_act = PE_act_ref;
	ref_result.Efficiency = efficiency_ref;
	ref_result.transferEnergy = transfer_energy_ref;
	ref_result.v_ep = v_ep;
	ref_result.C = C;
	ref_result.AR = AR;

	double dL = Free_length_upper - Free_length_lower;
	double dN = N_Upper - N_Lower;
	double dD = D_Upper - D_Lower;
	double dd = d_Upper - d_Lower;
	double prod = dL*dN*dD*dd;
	if (prod <= 0){
		QString str;
		if (dL <= 0) str = kor("자유장 설계변수");
		else if (dN <= 0) str = kor("유효권수 설계변수");
		else if (dD <= 0) str = kor("중심경 설계변수");
		else if (dd <= 0) str = kor("재질경 설계변수");
		QMessageBox msgbox;
		msgbox.setText(str + kor(" 입력에 잘못된 값이 있습니다."));
		msgbox.setIcon(QMessageBox::Critical);
		msgbox.exec();
		return false;
	}
	nL_iter = (unsigned int)floor((Free_length_upper - Free_length_lower) / deltaFreeLength) + 1;
	nN_iter = (unsigned int)floor((N_Upper - N_Lower) / deltaN) + 1;
	nD_iter = (unsigned int)floor((D_Upper - D_Lower) / deltaD) + 1;
	nd_iter = (unsigned int)floor((d_Upper - d_Lower) / deltad) + 1;
	total_iter = nL_iter * nN_iter * nD_iter * nd_iter;

	QFile file("autoSave.dat");
	if (file.open(QIODevice::WriteOnly)){
		file.write((char*)&N, sizeof(double) * 39);
	}
	file.close();
	return true;
}