void CalcView::Evaluate() { BString expression = fExpressionTextView->Text(); if (expression.Length() == 0) { beep(); return; } _AudioFeedback(false); // evaluate expression BString value; try { ExpressionParser parser; parser.SetDegreeMode(fOptions->degree_mode); value = parser.Evaluate(expression.String()); } catch (ParseException e) { BString error(e.message.String()); error << " at " << (e.position + 1); fExpressionTextView->SetText(error.String()); return; } // render new result to display fExpressionTextView->SetValue(value.String()); }
int main(int argc, char* argv[]) { if (argc == 1) { // run GUI CalcApplication* app = new CalcApplication(); app->Run(); delete app; } else { // evaluate expression from command line BString expression; int32 i = 1; while (i < argc) { expression << argv[i]; i++; } try { ExpressionParser parser; BString result = parser.Evaluate(expression.String()); printf("%s\n", result.String()); } catch (ParseException e) { printf("%s at %" B_PRId32 "\n", e.message.String(), e.position + 1); return 1; } } return 0; }
/*static*/ status_t CalcView::_EvaluateThread(void* data) { CalcView* calcView = reinterpret_cast<CalcView*>(data); if (calcView == NULL) return B_BAD_TYPE; BMessenger messenger(calcView); if (!messenger.IsValid()) return B_BAD_VALUE; BString result; status_t status = acquire_sem(calcView->fEvaluateSemaphore); if (status == B_OK) { ExpressionParser parser; parser.SetDegreeMode(calcView->fOptions->degree_mode); BString expression(calcView->fExpressionTextView->Text()); try { result = parser.Evaluate(expression.String()); } catch (ParseException e) { result << e.message.String() << " at " << (e.position + 1); status = B_ERROR; } release_sem(calcView->fEvaluateSemaphore); } else result = strerror(status); BMessage message(kMsgDoneEvaluating); message.AddString(status == B_OK ? "value" : "error", result.String()); messenger.SendMessage(&message); return status; }
std::vector<std::string> Algo::getAnswer() { int i; int k; std::vector <std::string> answerSlots; // Print out all the permuations std::cout << TESTING_MESSAGE; for (i = 0; i < this -> numPermutations.size(); i++) { std::cout << numPermutations[i].num1 << ' ' << numPermutations[i].num2 << ' ' << numPermutations[i].num3 << ' ' << numPermutations[i].num4 << '\n'; } for (i = 0; i < this -> opPermutations.size(); i++) { std::cout << opPermutations[i] << '\n'; } for (i = 0; i < numPermutations.size(); i++) { for (k = 0; k < opPermutations.size(); k++) { std::string testy = to_string(numPermutations[i].num1) + opPermutations[k].at(0) + to_string(numPermutations[i].num2) + opPermutations[k].at(1) + to_string(numPermutations[i].num3) + opPermutations[k].at(2) + to_string(numPermutations[i].num4); std::cout << "Testing: " << testy; std::string firstJoint = to_string(numPermutations[i].num1) + opPermutations[k].at(0) + to_string(numPermutations[i].num2); std::string secondJoint = opPermutations[k].at(1) + to_string(numPermutations[i].num3); std::string thirdJoint = opPermutations[k].at(2) + to_string(numPermutations[i].num4); // Test the equation ExpressionParser <int> parser; int firstJointEval = parser.eval(firstJoint); int secondJointEval = parser.eval(to_string(firstJointEval) + secondJoint); int thirdJointEval = parser.eval(to_string(secondJointEval) + thirdJoint); if (thirdJointEval == this -> goal) { std::cout << SUCCESS_MESSAGE; answerSlots.push_back(testy); } else { std::cout << FAIL_MESSAGE; } } } return answerSlots; }
JoinOperator::JoinOperator(std::vector<std::string> expressionList, std::vector<Operator*> children): Operator(children){ this->type = "JOIN"; this->expressions = expressionList; Schema *lsch = children[0]->getSchema(), *rsch = children[1]->getSchema(); ExpressionParser parser; joinClause = parser.parse(expressions[0])[0]; updateExpression(joinClause, lsch->getColumnMap(), rsch->getColumnMap(), lsch->getTableName(), rsch->getTableName()); schema = mergeSchemas(lsch, rsch); }
int main(int c, char** v) { string line1, line2; ExpressionParser* parser = new ExpressionParser; Expression* expression = NULL; string input; cout << "this is a expression work demo, I accept expression like this:" << endl; cout << "$a + $b * 4" << endl; cout << "please input expression, (input exit to exit):" << endl; while(getline(cin, input) && input != "exit") { expression = parser->Parse(input); if(expression == NULL) { cout << "expression systax error, please go on inputing or exit." << endl; continue; } cout << "please input variables' value like this: a = 3, b = 5" << endl; getline(cin, input); map<string, float> operand; vector<string> splites; split(splites, input, is_any_of(","), token_compress_on); for(auto &s : splites) { size_t i = s.find("="); if(i == s.npos) continue; string v = s.substr(0, i); trim(v); string vv = s.substr(i + 1, s.size() - i - 1); trim(vv); operand[v] = lexical_cast<float>(vv); } float result = 0.0; if(!expression->Operate(operand, result)) { cout << "I think you maybe miss some variables' value, so I can't get result." << endl; delete expression; cout << "please input expression, (input exit to exit):" << endl; continue; } cout << "result = " << result << endl; cout << "please input expression, (input exit to exit):" << endl; delete expression; } delete parser; return 0; }
int main() { string input; std::getline(std::cin, input); ExpressionParser parser; stack<string> tokens = parser.getStackReversedPolishNotationOf(input); dottyPrint(nodeFromStack(tokens, parser.getOperatorsRegistry())); // queue<string> tokensq = parser.getQueueReversedPolishNotationOf(input); // dottyPrint(nodeFromQueue(tokensq, parser.getOperatorsRegistry())); return 0; }
ProjectionOperator::ProjectionOperator(std::vector<std::string> expressionList, std::vector<Operator*> children) : Operator(children){ this->type = "PROJECT"; this->expressions = expressionList; schema = children[0]->getSchema(); ExpressionParser parser; bool allFound = false; vector<string> attrs = schema->getAttributes(); for(int i = 0; i < expressions.size(); i++){ if(expressions[i] == "*"){ expressions.erase(expressions.begin()+i); if(!allFound) expressions.insert(expressions.begin()+i, attrs.begin(), attrs.end()); allFound = true; } } for(int i = 0; i < expressions.size(); i++){ std::vector<Expression*> exps = parser.parse(expressions[i]); projectionClauses.insert(projectionClauses.end(), exps.begin(), exps.end()); } }
void XYEquationCurvePrivate::recalculate() { //resize the vector if a new number of point to calculate was provided if (equationData.count != xVector->size()) { if (equationData.count >= 1) { xVector->resize(equationData.count); yVector->resize(equationData.count); } else { //invalid number of points provided xVector->clear(); yVector->clear(); emit (q->dataChanged()); return; } } else { if (equationData.count < 1) return; } ExpressionParser* parser = ExpressionParser::getInstance(); bool rc = false; if (equationData.type == XYEquationCurve::Cartesian) { rc = parser->evaluateCartesian( equationData.expression1, equationData.min, equationData.max, equationData.count, xVector, yVector ); } else if (equationData.type == XYEquationCurve::Polar) { rc = parser->evaluatePolar( equationData.expression1, equationData.min, equationData.max, equationData.count, xVector, yVector ); } else if (equationData.type == XYEquationCurve::Parametric) { rc = parser->evaluateParametric(equationData.expression1, equationData.expression2, equationData.min, equationData.max, equationData.count, xVector, yVector); } if (!rc) { xVector->clear(); yVector->clear(); } emit (q->dataChanged()); }
void ScriptingCompute::set_variables(ExpressionParser &p) { p.set_variable("A1", *_in_a1); p.set_variable("A2", *_in_a2); p.set_variable("A3", *_in_a3); p.set_variable("A4", *_in_a4); p.set_variable("B1", *_in_b1); p.set_variable("B2", *_in_b2); p.set_variable("B3", *_in_b3); p.set_variable("B4", *_in_b4); p.set_variable("C1", *_in_c1); p.set_variable("C2", *_in_c2); p.set_variable("C3", *_in_c3); p.set_variable("C4", *_in_c4); }
void InspectorWindow::MessageReceived(BMessage* msg) { switch (msg->what) { case MSG_INSPECT_ADDRESS: { target_addr_t address = 0; bool addressValid = false; if (msg->FindUInt64("address", &address) != B_OK) { ExpressionParser parser; parser.SetSupportHexInput(true); const char* addressExpression = fAddressInput->Text(); BString errorMessage; try { address = parser.EvaluateToInt64(addressExpression); } catch(ParseException parseError) { errorMessage.SetToFormat("Failed to parse address: %s", parseError.message.String()); } catch(...) { errorMessage.SetToFormat( "Unknown error while parsing address"); } if (errorMessage.Length() > 0) { BAlert* alert = new(std::nothrow) BAlert("Inspect Address", errorMessage.String(), "Close"); if (alert != NULL) alert->Go(); } else addressValid = true; } else { addressValid = true; } if (addressValid) { if (fCurrentBlock != NULL && !fCurrentBlock->Contains(address)) { fCurrentBlock->ReleaseReference(); fCurrentBlock = NULL; } if (fCurrentBlock == NULL) fListener->InspectRequested(address, this); else fMemoryView->SetTargetAddress(fCurrentBlock, address); fCurrentAddress = address; BString computedAddress; computedAddress.SetToFormat("0x%" B_PRIx64, address); fAddressInput->SetText(computedAddress.String()); } break; } case MSG_NAVIGATE_PREVIOUS_BLOCK: case MSG_NAVIGATE_NEXT_BLOCK: { if (fCurrentBlock != NULL) { target_addr_t address = fCurrentBlock->BaseAddress(); if (msg->what == MSG_NAVIGATE_PREVIOUS_BLOCK) address -= fCurrentBlock->Size(); else address += fCurrentBlock->Size(); BMessage setMessage(MSG_INSPECT_ADDRESS); setMessage.AddUInt64("address", address); PostMessage(&setMessage); } break; } default: { BWindow::MessageReceived(msg); break; } } }
RESULT // tests for ExpressionParser ExpressionParser* exp; CHECK(ExpressionParser()) exp = new ExpressionParser; RESULT CHECK(~ExpressionParser()) delete exp; RESULT ExpressionParser ep; CHECK(ExpressionParser(const ExpressionParser& parser)) ExpressionParser ep2(ep); RESULT CHECK(const SyntaxTree& getSyntaxTree() const throw(Exception::NullPointer)) ExpressionParser empty; TEST_EXCEPTION(Exception::NullPointer, empty.getSyntaxTree()) RESULT CHECK(void parse(const String& s) throw(Exception::ParseError)) ExpressionParser parser; parser.parse("test('(H2)') AND element(H)"); RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
void InspectorWindow::MessageReceived(BMessage* message) { switch (message->what) { case MSG_INSPECT_ADDRESS: { target_addr_t address = 0; bool addressValid = false; if (message->FindUInt64("address", &address) != B_OK) { ExpressionParser parser; parser.SetSupportHexInput(true); const char* addressExpression = fAddressInput->Text(); BString errorMessage; try { address = parser.EvaluateToInt64(addressExpression); } catch(ParseException parseError) { errorMessage.SetToFormat("Failed to parse address: %s", parseError.message.String()); } catch(...) { errorMessage.SetToFormat( "Unknown error while parsing address"); } if (errorMessage.Length() > 0) { BAlert* alert = new(std::nothrow) BAlert("Inspect Address", errorMessage.String(), "Close"); if (alert != NULL) alert->Go(); } else addressValid = true; } else { addressValid = true; } if (addressValid) { fCurrentAddress = address; if (fCurrentBlock == NULL || !fCurrentBlock->Contains(address)) { fListener->InspectRequested(address, this); } else fMemoryView->SetTargetAddress(fCurrentBlock, address); } break; } case MSG_NAVIGATE_PREVIOUS_BLOCK: case MSG_NAVIGATE_NEXT_BLOCK: { if (fCurrentBlock != NULL) { target_addr_t address = fCurrentBlock->BaseAddress(); if (message->what == MSG_NAVIGATE_PREVIOUS_BLOCK) address -= fCurrentBlock->Size(); else address += fCurrentBlock->Size(); BMessage setMessage(MSG_INSPECT_ADDRESS); setMessage.AddUInt64("address", address); PostMessage(&setMessage); } break; } case MSG_MEMORY_BLOCK_RETRIEVED: { TeamMemoryBlock* block = NULL; status_t result; if (message->FindPointer("block", reinterpret_cast<void **>(&block)) != B_OK || message->FindInt32("result", &result) != B_OK) { break; } { AutoLocker< ::Team> teamLocker(fTeam); block->RemoveListener(this); } if (result == B_OK) { if (fCurrentBlock != NULL) fCurrentBlock->ReleaseReference(); fCurrentBlock = block; fMemoryView->SetTargetAddress(block, fCurrentAddress); fPreviousBlockButton->SetEnabled(true); fNextBlockButton->SetEnabled(true); } else { BString errorMessage; errorMessage.SetToFormat("Unable to read address 0x%" B_PRIx64 ": %s", block->BaseAddress(), strerror(result)); BAlert* alert = new(std::nothrow) BAlert("Inspect address", errorMessage.String(), "Close"); if (alert == NULL) break; alert->Go(NULL); block->ReleaseReference(); } break; } default: { BWindow::MessageReceived(message); break; } } }
int main (int argc, char ** argv) { while (true) { break; double **a = new double *[2]; a[1] = new double [2]; a[0] = new double [2]; a[0][0] = a[0][1] = a[1][0] = a[1][1] = 1.5; Numeric *mat = new Matrix (2, 2, a); Expression *expr = new Expression ("a + 1"); ExpressionParser *parser = new ExpressionParser (expr); parser->SetVariable("a", mat); CalculationResult res = parser->ParseExpression (); cout << res.statusInformation << endl; delete[] a[0]; delete[] a[1]; delete[] a; delete mat; delete expr; delete parser; } while (true) { break; Expression *equation = new Expression ("x - 5"); ExpressionParser *parser = new ExpressionParser (equation); EquationSolver *solver = new EquationSolver (equation, parser, "x"); Expression *dEquation = new Expression ("1"); CalculationResult result = solver->SolveBySecant (0, 1); Double *re = static_cast <Double *> (result.numeric.get ()); cout <<re->GetValue () << endl; delete equation; delete parser; delete solver; delete dEquation; } while (true) { break; double a[4][4] = { {1, -1, 2, -1}, {2, -2, 3, -3}, {1, 1, 1, 0}, {1, -1, 4, 3} }; vector < double > *b = new vector < double > { -8, -20, -2, 4 }; double **eles = new double *[4]; for (int i = 0;i < 4;i++) eles[i] = new double [4]; for (int i = 0;i < 4;i++) for (int j = 0;j < 4;j++) eles[i][j] = a[i][j]; Matrix *mat = new Matrix (4, 4, eles); CalculationResult res = EquationSolver :: SolveByGauss (mat, b); Array < double > *ans = static_cast < Array < double > * > (res.numeric.get ()); vector < double > anss = ans->GetCopy (); for (int i = 0;i < anss.size ();i++) cout << anss[i] << ' '; cout << endl; for (int i = 0;i < 4;i++) delete[] eles[i]; delete[] eles; delete mat; delete b; } while (true) { double a[3][3] = { {25, 15, -5}, {15, 18, 0}, {-5, 0, 11} }; vector < double > *b = new vector < double > { 35, 33, 6 }; double **eles = new double *[3]; for (int i = 0;i < 3;i++) eles[i] = new double [3]; for (int i = 0;i < 3;i++) for (int j = 0;j < 3;j++) eles[i][j] = a[i][j]; Matrix *mat = new Matrix (3, 3, eles); CalculationResult res = EquationSolver :: SolveByCholesky (mat, b); Array < double > *ans = static_cast < Array < double > * > (res.numeric.get ()); vector < double > anss = ans->GetCopy (); for (int i = 0;i < anss.size ();i++) cout << anss[i] << ' '; cout << endl; for (int i = 0;i < 3;i++) delete[] eles[i]; delete[] eles; delete mat; delete b; } return 0; }
void CliDumpMemoryCommand::Execute(int argc, const char* const* argv, CliContext& context) { if (argc < 2) { PrintUsage(argv[0]); return; } target_addr_t address; ExpressionParser parser; parser.SetSupportHexInput(true); try { address = parser.EvaluateToInt64(argv[1]); } catch(...) { printf("Error parsing address/expression.\n"); return; } int32 itemSize = 0; int32 displayWidth = 0; // build the format string if (strcmp(argv[0], "db") == 0) { itemSize = 1; displayWidth = 16; } else if (strcmp(argv[0], "ds") == 0) { itemSize = 2; displayWidth = 8; } else if (strcmp(argv[0], "dw") == 0) { itemSize = 4; displayWidth = 4; } else if (strcmp(argv[0], "dl") == 0) { itemSize = 8; displayWidth = 2; } else if (strcmp(argv[0], "string") == 0) { itemSize = 1; displayWidth = -1; } else { printf("dump called in an invalid way!\n"); return; } int32 num = 0; if (argc == 3) { char *remainder; num = strtol(argv[2], &remainder, 0); if (*remainder != '\0') { printf("Error: invalid parameter \"%s\"\n", argv[2]); } } if (num <= 0) num = displayWidth; TeamMemoryBlock* block = context.CurrentBlock(); if (block == NULL || !block->Contains(address)) { context.GetUserInterfaceListener()->InspectRequested(address, &context); context.WaitForEvents(CliContext::EVENT_TEAM_MEMORY_BLOCK_RETRIEVED); if (context.IsTerminating()) return; block = context.CurrentBlock(); } if (!strcmp(argv[0], "string")) { printf("%p \"", (char*)address); target_addr_t offset = address; char c; while (block->Contains(offset)) { c = *(block->Data() + offset - block->BaseAddress()); if (c == '\0') break; if (c == '\n') printf("\\n"); else if (c == '\t') printf("\\t"); else { if (!isprint(c)) c = '.'; printf("%c", c); } ++offset; } printf("\"\n"); } else { BString output; UiUtils::DumpMemory(output, 0, block, address, itemSize, displayWidth, num); printf("%s\n", output.String()); } }
int main() { /** * Seeding part 1443936225 */ auto seed = time(NULL); std::cout << "Hello, no seed was defined, so the program will use the default time(NULL) seed." << std::endl << "Your seed is : " + std::to_string(seed) << std::endl; srand(seed); /** * File Opening and reading part */ std::string fileName = "/home/sergio/Copy/UFMG/Graduacao/2015_2/ComputacaoNatural/TP1/tests/SR_div.txt"; FileParser fileParser(fileName); fileParser.getNumberOfVariables(); std::vector<std::string> file = fileParser.getVectorOfTextFile(); for (int generation = 0 ; generation < ExecutionParameters::getInstance().getMaxNumberOfGenerations(); generation++) { /** * Individual creation */ std::vector<Individual> individualsList; for (int i = 0; i < ExecutionParameters::getInstance().getMaxNumberOfIndividuals(); i++) { Individual individual; individualsList.push_back(individual); } /** * Evaluation part */ ExpressionParser expressionParser; //expressionParser Individual bestIndividual, worstIndividual; bool noBestIndividual = true; std::vector<Individual> updatedIndividualList; for (Individual individual : individualsList) { //std::cout << individual.getGenotype().getMathematicalExpression() << std::endl; debug cout expressionParser.setExpression(individual.getGenotype().getMathematicalExpression()); for (auto line : file) { if (line == "") continue; double variableValues[ExecutionParameters::getInstance().getNumberOfVariables()]; double functionValue; /** * Transform into a function */ std::istringstream lineStream(line); for (int i = 0; i < ExecutionParameters::getInstance().getNumberOfVariables(); i++) { lineStream >> variableValues[i]; expressionParser.defineVars(variableValues[i]); } lineStream >> functionValue; /** * */ double resultForIndividual = expressionParser.parse(); double individualFitnessScore; //std::cout << "Results for A = " << variableValues[0] << " :\n\tind: " << resultForIndividual << "\nfun: " << functionValue << std::endl; debug cout if (!std::isnan(resultForIndividual)) //check whether it has a valid result { /** * The fitness score should be calculated here */ double differenceOfFunctionValueAndIndividual = std::fabs(resultForIndividual - functionValue); individualFitnessScore = individual.getFitnessScore() + differenceOfFunctionValueAndIndividual; individual.setFitnessScore(individualFitnessScore); } else { individualFitnessScore = std::nan(""); individual.setFitnessScore( individualFitnessScore); //Setting individuals with invalid score to NaN so they won't appear in the worst individuals //One case in which we don't want those individuals is for example the function x^x which can happen, and x can take negative values expressionParser.clearVars(); updatedIndividualList.push_back(individual); break; } expressionParser.clearVars(); } if (noBestIndividual && std::isfinite(individual.getFitnessScore())) { bestIndividual.Copy(individual); worstIndividual.Copy(individual); noBestIndividual = false; } if (bestIndividual.getFitnessScore() > individual.getFitnessScore() && std::isfinite(individual.getFitnessScore())) bestIndividual.Copy(individual); if (worstIndividual.getFitnessScore() < individual.getFitnessScore() && std::isfinite(individual.getFitnessScore())) worstIndividual.Copy(individual); updatedIndividualList.push_back(individual); } individualsList.clear(); individualsList = updatedIndividualList; IndividualsMetrics individualsMetrics(individualsList, 0.0); std::cout << "#################\n\tGeneration " << generation << std::endl; std::cout << "The best individual was : " << bestIndividual.getGenotype().getMathematicalExpression() << " with a fitness score of : " << bestIndividual.getFitnessScore() << std::endl; std::cout << "The worst individual was : " << worstIndividual.getGenotype().getMathematicalExpression() << " with a fitness score of : " << worstIndividual.getFitnessScore() << std::endl; std::cout << "The average fitness of this generation was : " << individualsMetrics.getAverageFitness() << std::endl; std::cout << "The number of repeated individuals on this generation was : " << individualsMetrics.getRepeatedIndividuals() << std::endl; std::cout << "There were " << individualsMetrics.getCrossoverIndividualsWithBetterFitnessThanParents() << " individuals generated by crossover better than parents" << std::endl; } return 0; }