/** * @brief NewProject::on_btnCreateProject_clicked */ void NewProjectDialog::on_btnCreateProject_clicked() { QFileInfo path(ui->editProjectPath->text()); QString name = ui->editProjectName->text().simplified().replace(QChar::Space, "_"); if (!checkName(name) || !checkPath(path)) return; emit newProject(name, path.absoluteFilePath()); App::Settings::setLastNewProjectDir(path.absoluteFilePath()); clear(); accept(); }
/** * Ok button slot. */ void FileNameDialog::okPressed(){ QString err = checkName(); if(!err.isNull()){ QMessageBox msgBox; msgBox.setWindowTitle(tr("Filename")); msgBox.setText(tr("Invalid filename entered.")); msgBox.setInformativeText(err); msgBox.setIcon(QMessageBox::Critical); msgBox.exec(); return; } success = true; close(); }
bool PlayerRelationsManager::isGoodName(const std::string &name) const { const size_t size = name.size(); if (size < 3) return true; const std::map<std::string, PlayerRelation *>::const_iterator it = mRelations.find(name); if (it != mRelations.end()) return true; return checkName(name); }
void RtAcquisition::newInterface(const QString& name, const QString& type, uint addr) { static const char* InvalidTypeMsg = "Invalid interface type specification.\n" "Valid types are:\n" " \"RS232\", Standard serial communications\n" " \"TCPIP\", Standard Tcp/Ip communications\n" " \"NI-GPIB\", National Instr. GPIB card\n" " \"MODBUS-TCP\", Modbus over Tcp/Ip communications\n" " \"PCI6602\", National Instr. PCI-6602 counter card"; // check name if (!checkName(name)) return; // check the type int idx = -1; if (type=="RS232") idx=0; else if (type=="NI-GPIB") idx=1; else if (type=="TCPIP") idx=2; else if (type=="PCI6602") idx=3; else if (type=="MODBUS-TCP") idx=4; else { throwScriptError(InvalidTypeMsg); return; } RtInterface* dev = 0; switch (idx) { case 0: dev = new RtRS232(name,this,addr); break; case 1: dev = new RtNiGpib(name,this,addr); break; case 2: dev = new RtTcpip(name,this); break; case 4: dev = new RtModbusTcp(name,this); break; case 3: dev = new Rt6602(name,this,addr); break; } createScriptObject(dev); }
/** * @brief Extracts wiener processes * * This function extracts the declaration of wiener processes as their * definition does not contain an equal sign but only the names of the * individual proceses. */ void xppParser::extractWiener(void) { auto line = lines.begin(); while (line != lines.end()) { std::size_t pos1 = line->first.find("wiener"); std::size_t pos2 = line->first.find(" ", pos1); if (pos1 != std::string::npos) { while (pos2 != std::string::npos) { Wieners.Args.push_back(getNextWord(*line, pos1, pos2)); checkName(Wieners.Args.back(), *line, pos1); } lines.erase(line); } else { ++line; } } }
//Signal for add/edit button to be clicked void AddCS::on_button_cs_add_clicked(){ bool ok1 = false; //Name-check bool ok2 = true; //Gender-check bool ok3 = false; //Death-check QString name = ui->input_cs_name->text(); ok1 = checkName(name); QString gender = ui->input_cs_gender->currentText(); if(gender.isEmpty()){ ui->error_cs_gender->setText("<span style ='color: red'>Choose a gender!</span>"); ok2 = false; } else{ ui->error_cs_gender->setText(""); ok2 = true; } QString yob = QString::number(ui->input_cs_yob->value()); QString yod = QString::number(ui->input_cs_yod->value()); if(ui->input_cs_alive->isChecked()){ yod = "Alive"; ui->error_cs_yod->setText(""); ok3 = true; } else{ if(ui->input_cs_yob->value() > ui->input_cs_yod->value()){ ui->error_cs_yod->setText("<span style ='color: red'>Can't be dead before date of birth!</span>"); ok3 = false; } else{ ui->error_cs_yod->setText(""); ok3 = true; } } if(ok1 && ok2 && ok3){ if(id != 0){ scientist temp(id, name, gender, yob, yod); s.editScientist(temp); qDebug() << "Scientist edited!"; } else{ //Sets the value to -1 as a placeholder. Value is not used by addScientist scientist temp(-1, name, gender, yob, yod); s.addScientist(temp); qDebug() << "Scientist added!"; } this->hide(); } }
/** * @brief Extract a markov process from the parsed lines * * This function extracts the definition of markov processes as they constitute * one of the few multiline statements in an ode file. */ void xppParser::extractMarkov(void) { auto line = lines.begin(); while (line != lines.end()) { std::size_t pos1 = line->first.find("markov"); std::size_t pos2 = line->first.find(" ", pos1); if (pos1 != std::string::npos) { opts opt(line->second); opt.Name = getNextWord(*line, pos1, pos2); checkName(opt.Name, *line, pos1); /* Parse the number of states */ int nstates; try { nstates = std::stoi(getNextWord(*line, pos1, pos2)); } catch (std::invalid_argument) { throw xppParserException(EXPECTED_NUMBER, *line, pos1); } opt.Expr = nstates; /* Parse the transition probabilities */ opt.Args.reserve(nstates*nstates); for (int i=0; i < nstates; i++) { auto line2 = std::next(line); pos2 = 0; for (int j=0; j < nstates; j++) { pos1 = line2->first.find("{", pos2); pos2 = line2->first.find("}", pos1); if (pos1 == std::string::npos) { throw xppParserException(MISSING_MARKOV_ASSIGNMENT, *line2, pos2); } opt.Args.push_back(line2->first.substr(pos1+1, pos2-pos1-1)); } if (pos2 != line2->first.size()-1) { throw xppParserException(WRONG_MARKOV_ASSIGNMENT, *line2, line2->first.size()); } lines.erase(line2); } Markovs.push_back(opt); lines.erase(line); } else { ++line; } } }
/*Вход*/ void login(void *buf) { int checkNum; struct loginRequest_t *loginReq = (struct loginRequest_t *) buf; struct loginResponce_t *loginRes = malloc(sizeof(struct loginResponce_t)); bzero(loginRes, sizeof(struct loginResponce_t)); if (readFile() == -1) { /*Некоректное имя*/ loginRes->status = STATUS_BAD; strcpy(loginRes->errorBuf, "User not found"); send_message(CURRENT, 0, LOG_IN, sizeof(struct loginResponce_t), (void *)loginRes); free(loginRes); return; } if ((checkNum = checkName(loginReq->name)) == -1) { /*Пользаватель с таким именем уже есть*/ loginRes->status = STATUS_BAD; strcpy(loginRes->errorBuf, "User not found"); printf("[Logic]User input incorrectly name\n"); send_message(CURRENT, 0, LOG_IN, sizeof(struct loginResponce_t), (void *)loginRes); free(loginRes); return; } if (checkPasswd(checkNum, loginReq->pass) == -1 ) { /*Некоректный пароль*/ loginRes->status = STATUS_BAD; strcpy(loginRes->errorBuf, "Incorrectly password"); printf("[Logic]User input incorrectly name\n"); send_message(CURRENT, 0, LOG_IN, sizeof(struct loginResponce_t), (void *)loginRes); /*Некоректный пароль*/ free(loginRes); return; } else { loginRes->status = STATUS_OK; IdName[currentPlayer].id = ++playersID; strncpy(IdName[currentPlayer].name, loginReq->name, MAX_NAME_LENGTH); currentPlayer++; send_message(CURRENT, 0, LOG_IN, sizeof(struct loginResponce_t), (void *)loginRes); printf("[Logic]User %s log in\n", loginReq->name); free(loginRes); return; } }
bool ProjectInfoPage::checkLocation(const QString &text) { projectLocation = text; projectLocation.remove(QRegExp("^\\s*")); projectLocation.remove(QRegExp("\\s*$")); projectLocation.remove(QRegExp("/$")); projectPathLineEdit->setText(projectLocation + "/" + projectName); if (!checkLocation()) return false; if (!checkName()) return false; if (!checkPath()) return false; warningLabel->clear(); warningLineEdit->setText(tr("t")); return true; }
int main(void ) { ListName *names = NULL; ListYear *years = NULL; int choice = 0; int year; char name[512]; readFile(&years, &names); do { printf("Do you want to find a name or a year?\n1) Year 2)Name 0) Exit\nChoice : "); scanf("%d", &choice); switch( choice ) { case 1: printf("Insert the year that you will look for : "); scanf("%d", &year); printf(" The year %d %s\n", year, ( checkYear(years, year) == 1 ) ? "was found!" : "was not found!"); printYear(years); break; case 2: printf("Insert the name that you will look for : "); scanf("%s", name); printf(" The name %s %s\n", name, ( checkName(names, name) == 1 ) ? "was found!" : "was not found!"); break; case 0: printf("You are exiting...\n"); break; } }while ( choice != 0 ); getchar(); return EXIT_SUCCESS; }
void readName( char* name, int f_or_l, int length ) { if( f_or_l == 0 ) // Wish passing strings in C was easier. f_or_l stands for first or last as in name. 0 for first and 1 for last name. { printf( "Please enter your first name on the card.\n" ) ; } else { printf( "Please enter your last name on the card.\n" ) ; } printf( "Please note if your name may contain spaces, but cannot exceed %d characters including spaces.\n", length - 1 ) ; printf( "Please use only English characters, numbers or special characters cannot be accepted by the system.\n" ) ; getData( name, length ) ; while( !checkName( name ) || allSpaces( name ) ) // Keep checking till the user gets it right. { printf( "The system seems to get only spaces, numericals or special characters.\nPlease try again.\n" ) ; getData( name, length ) ; } }
int MFS_Unlink(int pinum, char *name){ if(!initialized) return -1; if(checkName(name) < 0) return -1; Net_Packet sentPacket; Net_Packet responsePacket; sentPacket.inum = pinum; sentPacket.message = PAK_UNLINK; strcpy(sentPacket.name, name); if(sendPacket(serverHostname, serverPort, &sentPacket, &responsePacket, 3) < 0) return -1; return responsePacket.inum; }
void VCompDialog::okButton( WWindow* ) { _eName->getText( *_fn ); // _fn->toLower(); if( _fn->isMask() ) { WMessageDialog::messagef( this, MsgError, MsgOk, _viperError, "'%s' cannot be a wildcard", (const char*)*_fn ); } else if( !_fn->legal() ) { WMessageDialog::messagef( this, MsgError, MsgOk, _viperError, "'%s' is not a legal filename", (const char*)*_fn ); } else if( !checkName() ) { //error issued by checkName() } else if( streq( _fn->ext(), ".tgt" ) ) { quit( TRUE ); } else if( !legalExt() ) { //error issued by legalExt() } else if( !findRule() ) { //this will work since extension has been verified } else { quit( TRUE ); } }
void IconServerSession::parseUrl(std::string urlString) { ssize_t p; for(p = urlString.size() - 1; p >= 0; p--) { const char c = urlString.at(p); if(c == '/' || c == '\\' || c == ':') break; } if(p + 1 >= (ssize_t) urlString.size()) { // attempt to get a directory getStream()->write(htmlNotFound, htmlNotFoundSize); } else { std::string filename = urlString.substr(p + 1, std::string::npos); if(checkName(filename.c_str(), filename.size())) { sendIcon(filename); } else { log(LL_Warning, "Request to a invalid filename: \"%s\"\n", filename.c_str()); getStream()->write(htmlNotFound, htmlNotFoundSize); } } }
int MFS_Lookup(int pinum, char *name){ if(!initialized) return -1; if(checkName(name) < 0) return -1; Net_Packet sentPacket; Net_Packet responsePacket; sentPacket.inum = pinum; sentPacket.message = PAK_LOOKUP; strcpy((char*)&(sentPacket.name), name); int rc = sendPacket(serverHostname, serverPort, &sentPacket, &responsePacket, 3); if(rc < 0) return -1; rc = responsePacket.inum; return rc; }
bool check(const php::Class& c) { assert(checkName(c.name)); for (DEBUG_ONLY auto& m : c.methods) assert(check(*m)); // Some invariants about Closure classes. auto const isClo = is_closure(c); if (c.closureContextCls) { assert(c.closureContextCls->unit == c.unit); assert(isClo); } if (isClo) { assert(c.methods.size() == 1); assert(c.methods[0]->name->isame(s_invoke.get())); assert(c.methods[0]->isClosureBody); } else { assert(!c.closureContextCls); } return true; }
TVariableIndex CVariablesBuilder::AddRight( const TVariableName name, const TVariableTypeTag type ) { const TVariableType variableType = checkTypeTag( type ); if( variableType != VT_None && checkName( name ) ) { const TVariableIndex variableIndex = variableNameToIndex[name]; if( variableIndex != InvalidVariableIndex ) { CVariableData& variable = variables[variableIndex]; if( variable.Type == variableType ) { variable.CountRight++; return variableIndex; } else { errorTypesNotMatched( name, variable.Type ); } } else { error( "variable `" + std::string( 1, static_cast<char>( name ) ) + "` wasn't defined in left part of rule" ); } } return InvalidVariableIndex; }
int MFS_Creat(int pinum, int type, char *name){ if(!initialized) return -1; if(checkName(name) < 0) return -1; Net_Packet sentPacket; Net_Packet responsePacket; sentPacket.inum = pinum; sentPacket.type = type; sentPacket.message = PAK_CREAT; strcpy(sentPacket.name, name); if(sendPacket(serverHostname, serverPort, &sentPacket, &responsePacket, 3) < 0) return -1; return responsePacket.inum; }
ClientEditor::ClientEditor( QWidget *parent ) : KDialog( parent ) { ui = new ClientEditorUI( this ); setMainWidget( ui ); setCaption( i18n("Client Editor") ); setButtons( KDialog::Ok|KDialog::Cancel ); setDefaultButton(KDialog::NoDefault); //disable default button (return Pressed) enableButton(KDialog::Ok, false); connect( ui->btnChangeClientPhoto , SIGNAL( clicked() ), this, SLOT( changePhoto() ) ); connect( ui->editClientName, SIGNAL(textEdited(const QString &)),this, SLOT( checkNameDelayed()) ); connect(ui->editClientCode, SIGNAL(returnPressed()),ui->editClientName, SLOT(setFocus()) ); connect(ui->editClientCode, SIGNAL(editingFinished()),this, SLOT( checkNameDelayed() )); //both returnPressed and lost focus fires this signal. But only fired if validator is accepted. QRegExp regexpC("[0-9]{1,13}"); QRegExpValidator * validator = new QRegExpValidator(regexpC, this); ui->editClientPoints->setValidator(validator); ui->editClientDiscount->setValidator((new QDoubleValidator(0.00, 100.000, 3,ui->editClientDiscount))); //code can contain letters (for ids with letters, like RFC in Mexico) QRegExp regexpName("[A-Za-z_0-9\\s\\\\/\\-]+");//any letter, number, both slashes, dash and lower dash. and any space QRegExpValidator *regexpAlpha = new QRegExpValidator(regexpName, this); ui->editClientCode->setValidator(regexpAlpha); //Set filter to the name. Do not allow .,&^% etc... ui->editClientName->setValidator(regexpAlpha); ui->editClientCode->setEmptyMessage(i18n("Enter a 6, 12, or 13 digits Bar Code.")); ui->editClientName->setEmptyMessage(i18n("Enter client full name")); ui->editClientPhone->setEmptyMessage(i18n("Phone number")); ui->editClientCell->setEmptyMessage(i18n("Cell phone number")); ui->editClientPoints->setEmptyMessage(i18n("Accumulated points")); ui->editClientDiscount->setEmptyMessage(i18n("Personal discount")); //since date picker ui->sinceDatePicker->setDate(QDate::currentDate()); QTimer::singleShot(750, this, SLOT(checkName())); ui->editClientCode->setFocus(); }
//Signal for add/edit button to be clicked void AddC::on_button_c_add_clicked(){ bool ok1 = false; //Name-check bool ok2 = true; //Type-check bool ok3 = false; //Built-check QString name = ui->input_c_name->text(); ok1 = checkName(name); QString year = QString::number(ui->input_c_year->value()); QString type = ui->input_c_type->currentText(); if(type.isEmpty()){ ui->error_c_type->setText("<span style ='color: red'>Choose a type!</span>"); ok2 = false; } else{ ui->error_c_type->setText(""); ok2 = true; } QString build = ui->input_c_build->currentText(); if(build.isEmpty()){ ui->error_c_build->setText("<span style ='color: red'>Choose a build status!</span>"); ok3 = false; } else{ ui->error_c_build->setText(""); ok3 = true; } if(ok1 && ok2 && ok3){ if(id != 0){ computer temp(id, name, year, type, build); s.editComputer(temp); qDebug() << "Computer edited!"; } else{ //Sets the value to -1 as a placeholder. Value is not used by addComputer computer temp(-1, name, year, type, build); s.addComputer(temp); qDebug() << "Computer added!"; } this->hide(); } }
/*Регистрация*/ void registration(void * buf) { struct loginRequest_t *loginReq = (struct loginRequest_t *)buf; struct loginResponce_t *loginRes = malloc(sizeof(struct loginResponce_t)); bzero(loginRes, sizeof(struct loginResponce_t)); readFile(); /*Проверяем имя*/ if (checkName(loginReq->name) == -1) { strncpy(data[countAllPlayers].name, loginReq->name, MAX_NAME_LENGTH); strncpy(data[countAllPlayers].pswd, loginReq->pass, MAX_PASS_LENGTH); saveFile(); loginRes->status = STATUS_OK; send_message(CURRENT, 0, REGISTRATION, sizeof(struct loginResponce_t), (void *)loginRes); printf("[Logic]User %s registration\n", loginReq->name); } else { loginRes->status = STATUS_BAD; strcpy(loginRes->errorBuf, "Bad name"); printf("[logic]User input bad name\n"); send_message(CURRENT, 0, REGISTRATION, sizeof(struct loginResponce_t), (void *)loginRes); } free(loginRes); }
bool PlayerRelationsManager::isGoodName(Being *const being) const { if (!being) return false; if (being->getGoodStatus() != -1) return (being->getGoodStatus() == 1); const std::string &name = being->getName(); const size_t size = name.size(); if (size < 3) return true; const std::map<std::string, PlayerRelation *>::const_iterator it = mRelations.find(name); if (it != mRelations.end()) return true; const bool status = checkName(name); being->setGoodStatus(status ? 1 : 0); return status; }
bool check(const php::Func& f) { assert(checkParams(f)); assert(checkName(f.name)); for (DEBUG_ONLY auto& block : f.blocks) assert(checkBlock(f, *block)); /* * Some of these relationships may change as async/await * implementation progresses. Asserting them now so they are * revisited here if they aren't true anymore. */ if (f.isClosureBody) assert(!f.top); if (f.isPairGenerator) assert(f.isGenerator); if (f.isClosureBody) { assert(f.cls && f.cls->parentName && f.cls->parentName->isame(s_Closure.get())); } assert(checkExnTree(f)); return true; }
// this function will return the node named "FACESET_Woman" // if there is no such node NullFC will be returned NodePtr checkName(NodePtr n){ UInt32 children = n->getNChildren(); //make sure a name existes if (getName(n)) //check if it is the name we are looking for if (getName(n)== std::string("FACESET_Woman")) // We got the node! return n; //check all children for (int i = 0; i < children; i++){ NodePtr r = checkName(n->getChild(i)); if (r != NullFC) // if it is not NullFC it is the node we are looking for // so just pass it through return r; } // no children's name matches or there are no more childs // so return NullFC, indicating that the node was not found yet return NullFC; }
Clock::Clock(const std::string& name , Clock* parentClock , float timeScale , double maxTimeStep) : m_name(name) , m_parent(parentClock) , m_timeScale(timeScale) , m_lastTimeStep(0.0) , m_pause(false) , m_maxDeltaTimeStep(maxTimeStep) , m_currentTimeSeconds(0.0) { if(!m_parent) { if(s_clockMap.size() == 0 && !s_rootClock) { s_rootClock = this; m_parent = nullptr; } else { m_parent = s_rootClock; m_parent->AppendChild(this); } } else { m_parent->AppendChild(this); } std::transform(m_name.begin(), m_name.end(), m_name.begin(), ::tolower); int nameIndex = 0; std::string checkName(m_name); while(s_clockMap[checkName]) { checkName = m_name + std::to_string((long double)nameIndex); ++nameIndex; } m_name = checkName; s_clockMap[m_name] = this; }
void AckFunctionDialog::onAddAck() { SimpleTypeBox box( ("New acknowledge function name?"), ""); std::string name = boost::trim_copy(box.run()); if (box.valid()) { if (checkName(name)) { setSensitiveAck(false); Gtk::TreeIter iter = m_model->append(); if (iter) { savePreviousAck(mAckNameEntry->get_text()); mAckNameEntry->set_text(name); Gtk::ListStore::Row row = *iter; row[m_viewscolumnrecord.name] = name; mHeaderAck->set_text("void " + name + "(const std::string&"\ "activityname,\n\t"\ "const ved::Activity& activity) {"); std::string generatedFunc = ""; mTextViewFunction->get_buffer()->set_text(generatedFunc); m_iter = iter; mTreeAckList->set_cursor(m_model->get_path(iter)); mAckName.push_back(name); setSensitiveAck(true); } } else { Gtk::MessageDialog errorDial ("Name error !", false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true); errorDial.set_title("Error !"); errorDial.run(); } } }
bool check(const php::Func& f) { assert(checkParams(f)); assert(checkName(f.name)); for (DEBUG_ONLY auto& block : f.blocks) assert(checkBlock(*block)); /* * Some of these relationships may change as async/await * implementation progresses. Asserting them now so they are * revisited here if they aren't true anymore. */ if (f.isClosureBody) assert(!f.top); if (f.isPairGenerator) assert(f.isGenerator); if (f.isClosureBody) { assert(f.cls && f.cls->parentName && f.cls->parentName->isame(s_Closure.get())); } DEBUG_ONLY Attr pcm = AttrParamCoerceModeNull | AttrParamCoerceModeFalse; assert((f.attrs & pcm) != pcm); // not both boost::dynamic_bitset<> seenId(f.blocks.size()); for (auto& block : f.blocks) { if (block->id == NoBlockId) continue; assert(checkBlock(*block)); // All blocks have unique ids in a given function; not necessarily // consecutive. assert(block->id < f.blocks.size()); assert(!seenId.test(block->id)); seenId.set(block->id); } assert(checkExnTree(f)); return true; }
//UI Buttons - Boot Environments void mainUI::on_tool_BEadd_clicked(){ //Check to see if we need to reset the GRUB defaults afterwards bool updateGRUB=false; if( ui->tree_BE->topLevelItemCount() == 1){updateGRUB=true;} //moving from 1 to 2 //Get the new name from the user bool ok; QString newname = QInputDialog::getText( this, tr("New BE name"), tr("Choose a name for the new boot environment"), QLineEdit::Normal, "", &ok,0, Qt::ImhLowercaseOnly | Qt::ImhUppercaseOnly | Qt::ImhDigitsOnly); if(ok && !newname.isEmpty()){ if( !validateInput(newname) ){ on_tool_BEadd_clicked(); //try again return; } if( checkName(newname) ){ if(updateGRUB && !G_showMenu){ G_showMenu=true; saveGRUBdefaults(G_themeFile, G_fontFile, G_timer, G_showMenu, G_defaultBE); } beadmCreate(newname); updateBEList(); updateGRUBdefaults(); } } }
/** * @brief Extract a table * * This function extracts a precomputed table either from a file or calculates * it from the definition. */ void xppParser::extractTable(void) { auto line = lines.begin(); while (line != lines.end()) { std::size_t pos1 = line->first.find("table"); std::size_t pos2 = line->first.find(" ", pos1); if (pos1 != std::string::npos) { opts opt(line->second); unsigned npoints; double xLow, xHigh; /* Initialize the parser */ mup::ParserX parser; /* Parse the name */ opt.Name = getNextWord(*line, pos1, pos2); checkName(opt.Name, *line, pos1); /* If the table has to be calculated there is a % sign instead of a * filename */ std::string fn = getNextWord(*line, pos1, pos2); if (fn == "%") { /* Get the number of points */ try { npoints = std::stoi(getNextWord(*line, pos1, pos2)); } catch (std::invalid_argument) { throw xppParserException(EXPECTED_NUMBER, *line, pos1); } /* Get the bounds */ parser.SetExpr(getNextWord(*line, pos1, pos2)); try { xLow = parser.Eval().GetFloat(); } catch (mup::ParserError) { throw xppParserException(EXPECTED_NUMBER, *line, pos1); } parser.SetExpr(getNextWord(*line, pos1, pos2)); try { xHigh = parser.Eval().GetFloat(); } catch (mup::ParserError) { throw xppParserException(EXPECTED_NUMBER, *line, pos1); } /* Parse the defining function */ mup::Value t; parser.DefineVar("t", mup::Variable(&t)); parser.SetExpr(getNextWord(*line, pos1, pos2)); /* Evaluate the table expression */ double dx = (xHigh - xLow)/(npoints-1); try { opt.Args.reserve(npoints); for(unsigned j = 0; j < npoints; j++) { t = (mup::float_type)(xLow + j * dx); opt.Args.push_back(parser.Eval().ToString()); } } catch (mup::ParserError) { throw xppParserException(WRONG_TABLE_ASSIGNMENT, *line, pos1); } } else { /* Open file for parsing */ std::ifstream fileStream(fn.c_str(), std::ios::in); if (fileStream.fail()) { throw std::runtime_error("Cannot open table file " + fn + "\n"); } lineNumber temp; temp.second = 1; /* Get the number of points */ try { getline(fileStream, temp.first); ++temp.second; npoints = std::stoi(temp.first); } catch (std::invalid_argument) { throw xppParserException(EXPECTED_NUMBER, temp, pos1); } /* Get the bounds */ getline(fileStream, temp.first); ++temp.second; parser.SetExpr(temp.first); try { xLow = parser.Eval().GetFloat(); } catch (mup::ParserError) { throw xppParserException(EXPECTED_NUMBER, temp, pos1); } getline(fileStream, temp.first); ++temp.second; parser.SetExpr(temp.first); try { xHigh = parser.Eval().GetFloat(); } catch (mup::ParserError) { throw xppParserException(EXPECTED_NUMBER, temp, pos1); } /* Parse the table values */ try { opt.Args.reserve(npoints); for(unsigned j = 0; j < npoints; j++) { if (getline(fileStream, temp.first)) { ++temp.second; parser.SetExpr(temp.first); opt.Args.push_back(parser.Eval().ToString()); } else { throw xppParserException(EXPECTED_TABLE_ASSIGNMENT, temp, pos1); } } } catch (mup::ParserError) { throw xppParserException(WRONG_TABLE_ASSIGNMENT, temp, pos1); } fileStream.close(); } Tables.push_back(opt); lines.erase(line); } else { ++line; } } }
/** * @brief Extract definitions from the ode file * * This extracts definitions that are given in the keyword list and are marked * by an equal sign. */ void xppParser::extractDefinition(void) { auto line = lines.begin(); while (line != lines.end()) { /* Search for the first keyword. In most cases it should be the first * consecutive string that precedes a whitespace or equal sign. */ std::size_t pos1 = 0, pos2 = 0; std::string key = getNextWord(*line, pos1, pos2); if (pos2 == std::string::npos) { throw xppParserException(UNKNOWN_ASSIGNMENT, *line, pos1+1); } /* Search for keywords */ auto res = keywordSearch(key, line->first.at(pos2)); while (pos2 != std::string::npos) { opts opt(line->second); switch (res.id) { case 0: /* !Name */ opt.Name = line->first.substr(pos1+1, pos2-pos1-1); break; case 1: /* Name(t+1) */ case 2: /* Name' */ case 4: /* Name(t) */ case 11: /* Name(0) */ opt.Name = line->first.substr(pos1, res.start); break; case 3: /* dName/dt */ opt.Name = line->first.substr(pos1+1, res.start-1); break; case 9: {/* Name(args...) */ size_t pos3 = line->first.find("(", pos1); opt.Name = line->first.substr(pos1, pos3-pos1); opt.Args = getList(line->first.substr(pos3, pos2-pos3), opt.Line, ")", ","); break; } case 12: break; case 13: /* 0=Expression */ opt.Name = "Initial Condition"; break; case 19: /* Name=Expression */ opt.Name = line->first.substr(pos1, pos2-pos1); break; default: /* keyword Name */ opt.Name = getNextWord(*line, pos1, pos2); break; } /* Check whether the name is already taken/reserved, except for * initial conditions, where we check for existence. Also check * whether a given option is valid. */ if (res.id != 10 && res.id != 17) { checkName(opt.Name, *line, pos1); } else if (res.id == 10) { if (usedNames.parseText(opt.Name).empty()) { throw xppParserException(UNKNOWN_VARIABLE, *line, pos1); } } else if (res.id == 17) { if (options.parseText(opt.Name).empty()) { throw xppParserException(UNKNOWN_OPTION, *line, pos1); } /* Turn the name to upper case to simplify further handling */ for (char &c : opt.Name) { c = std::toupper(c); } } /* Get the expression */ opt.Expr = getNextExpr(*line, pos1, pos2); /* Check numbers are indeed numeric expressions */ if (res.id == 8 || (res.id == 17 && opt.Name != "OUTPUT" && opt.Name != "LOGFILE" && opt.Name != "METH")) { if (!isNumeric(opt.Expr)) { throw xppParserException(EXPECTED_NUMBER, *line, pos1); } /* Check if all function arguments are used */ } else if (res.id == 9) { size_t pos3 = opt.Name.length()+1; for (std::string &str : opt.Args) { if (opt.Expr.find(str) == std::string::npos) { throw xppParserException(MISSING_ARGUMENT, *line, pos3); } pos3 += str.length()+1; } } /* Find the type of the keyword */ switch(res.id) { case 0: Constants.push_back(opt); break; case 1: case 2: case 3: Equations.push_back(opt); break; case 4: Volterra.push_back(opt); break; case 5: Constants.push_back(opt); break; case 6: Auxiliar.push_back(opt); break; case 7: Parameters.push_back(opt); break; case 8: Numbers.push_back(opt); break; case 9: Functions.push_back(opt); break; case 10: InitConds.push_back(opt); break; case 11: Volterra.push_back(opt); break; case 12: /* Boundary expressions do not have a name */ opt.Expr = opt.Name; opt.Name = ""; Boundaries.push_back(opt); break; case 13: Volterra.push_back(opt); break; case 14: Algebraic.push_back(opt); break; case 15: /* Extract the argument list */ pos1 = opt.Expr.find("("); opt.Args = getList(opt.Expr.substr(pos1), opt.Line, ")", ","); opt.Expr.resize(pos1); Special.push_back(opt); break; case 16: /* Sets are a comma separated list */ opt.Args = getList(opt.Expr, opt.Line, "}", ","); opt.Expr = ""; Sets.push_back(opt); break; case 17: Options.push_back(opt); break; case 18: Exports.push_back(opt); break; case 19: Temporaries.push_back(opt); break; default: throw xppParserException(UNKNOWN_ASSIGNMENT, *line, pos1+1); break; } } lines.erase(line); } }