private object CalculateExpression(string s) { if (string.IsNullOrWhiteSpace(s)) { return(s); } NCalc.Expression exp = new NCalc.Expression(s); exp.EvaluateParameter += Exp_EvaluateParameter; PopulateVariables(exp); if (exp.HasErrors()) { return(s); } else { try { return(exp.Evaluate()); } catch (Exception ex) { /*if (_loggedExceptions.Where(x=>x.HResult == ex.HResult && x.Message == ex.Message).Count() == 0) * { * _logger.Error(ex, "Calculating expression failde"); * _loggedExceptions.Enqueue(ex); * if (_loggedExceptions.Count > 10) * _loggedExceptions.Dequeue(); * }*/ return(s); } } }
/// <summary> /// Gets the function result. /// </summary> /// <returns>The function result.</returns> /// <param name="function">The function.</param> /// <param name="input">The arguments values and expected results of the function.</param> public double GetFunctionResult(string function, InstinctualLearningInput input) { //var func = Parser<DoubleEvaluator>.Parse(function); //var ctx = new VariableContext<DoubleEvaluator>(); //var vars = "ABCDEFGH"; //for(int i = 0;i<input.Arguments.Count;i++) //{ // ctx.AddVariable(vars.Substring(i, 1), input.Arguments[i]); //} //var result = func.Eval(ctx); var expression = new NCalc.Expression(function); for (int i = 0; i < m_parameterNames.Length; i++) { expression.Parameters.Add(m_parameterNames[i], input.Arguments[i]); } var result = expression.Evaluate(); return((double)result); //return result.Result; // return 0.0; }
public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services) { await Task.Yield(); if (string.IsNullOrWhiteSpace(input)) { return(TypeReaderResult.FromError(CommandError.ParseFailed, "Input is empty.")); } var i = input.Trim().ToUpperInvariant(); i = i.Replace("K", "000"); //can't add m because it will conflict with max atm if (TryHandlePercentage(services, context, i, out var num)) { return(TypeReaderResult.FromSuccess(new ShmartNumber(num, i))); } try { var expr = new NCalc.Expression(i, NCalc.EvaluateOptions.IgnoreCase); expr.EvaluateParameter += (str, ev) => EvaluateParam(str, ev, context, services); var lon = (long)(decimal.Parse(expr.Evaluate().ToString())); return(TypeReaderResult.FromSuccess(new ShmartNumber(lon, input))); } catch (Exception) { return(TypeReaderResult.FromError(CommandError.ParseFailed, $"Invalid input: {input}")); } }
private object CalculateExpression(string s) { if (string.IsNullOrWhiteSpace(s)) { return(s); } NCalc.Expression exp = new NCalc.Expression(s); PopulateVariables(exp); if (exp.HasErrors()) { return(s); } else { try { return(exp.Evaluate()); } catch (Exception ex) { _logger.Error(ex, "Calculating expression failde"); return(s); } } }
object ExecExpression(string expression, Dictionary <string, object> data) { Dictionary <string, object> paramenters = new Dictionary <string, object>(); var key = 'a'; var newExp = regParam.Replace(expression, (Match x) => { paramenters.Add(key.ToString(), GetValue(x.Value, data)); return(key++.ToString()); }); var e = new NCalc.Expression(newExp); e.Parameters = paramenters; return(e.Evaluate()); // var list = expression.Split('+', '-', '*', '/', '%'); // if (list.Length > 1) // { // // return null; // } // else // { return(GetValue(expression, data)); // } }
public void Evaluate(string expression) { if (expression != null && expression.Length >= 0) { NCalc.Expression exp = new NCalc.Expression(expression); object eval = null; try { eval = exp.Evaluate(); } catch (ArgumentException) { this.AddList("Error in the expression."); return; } catch (EvaluateException e) { this.AddList("Error while evaluating expression, Error Message" + e.Message); return; } if (exp.HasErrors()) { this.AddList("Error while evaluating expression, Error Message" + exp.Error); } else { this.AddList(expression, eval); } } }
private void Calculation(string fullFormula) { NCalc.Expression e = new NCalc.Expression(fullFormula); var x = e.Evaluate(); OutputWindow.Text = x.ToString(); }
private void OnTextChanged(object sender, TextChangedEventArgs e) { RemoveRedundantChars(); try { var expression = new Expression(_ExpressionBox.Text); object resultObj = expression.Evaluate(); double result = Convert.ToDouble(resultObj); String str; if (result > 0 & result < 1) { str = result.ToString(); str += " (" + ((decimal)result).ToString("P") + ")"; } else { result = Math.Round(result, 2, MidpointRounding.AwayFromZero); str = result.ToString(); } _ResultBox.Text = str; } catch (Exception) { } }
public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services) { await Task.Yield(); if (string.IsNullOrWhiteSpace(input)) { return(TypeReaderResult.FromError(CommandError.ParseFailed, "Input is empty.")); } var i = input.Trim().ToLowerInvariant(); if (TryHandlePercentage(services, context, context.User.Id, i, out var num)) { return(TypeReaderResult.FromSuccess(new ShmartNumber(num, i))); } try { var expr = new NCalc.Expression(i, NCalc.EvaluateOptions.IgnoreCase); expr.EvaluateParameter += (str, ev) => EvaluateParam(str, ev, context, services); var lon = (long)(decimal.Parse(expr.Evaluate().ToString())); return(TypeReaderResult.FromSuccess(new ShmartNumber(lon, input))); } catch (Exception ex) { _log.Info(ex); return(TypeReaderResult.FromError(CommandError.ParseFailed, "Invalid input")); } }
private bool EvaluateExpression(String expression, out decimal result) { if (expression.Length <= 0) { result = 0; return(false); } bool success = true; NCalc.Expression.CacheEnabled = false; NCalc.Expression ex = new NCalc.Expression(expression); if (ex.HasErrors()) { success = false; result = 0; return(success); } try { result = Decimal.Parse(ex.Evaluate().ToString()); //result = Decimal.Parse(ex.Evaluate()); } catch (Exception e) { result = 0; success = false; } return(success); }
protected object EvaluateExpression(IColumnExpression expression, DataRow row) { if (expression.Language == LanguageType.NCalc) { var exp = new NCalc.Expression(expression.Value); var factory = new ColumnIdentifierFactory(); exp.EvaluateParameter += delegate(string name, NCalc.ParameterArgs args) { args.Result = GetValueFromRow(row, factory.Instantiate(name)); }; return(exp.Evaluate()); } else if (expression.Language == LanguageType.Native) { var parse = expression.Value.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); var variable = new ColumnIdentifierFactory().Instantiate(parse.ElementAt(0)); var value = GetValueFromRow(row, variable); foreach (var nativeFunction in parse.Skip(1)) { var factory = new NativeTransformationFactory(); var transformer = factory.Instantiate(nativeFunction); value = transformer.Evaluate(value); } return(value); } else { throw new ArgumentOutOfRangeException($"The language {expression.Language} is not supported during the evaluation of an expression."); } }
private void drawSolutionFunctionChart(Chart chart, Population population) { try { chart.Series.Clear(); Series mySeriesOfPoint = new Series("Series1"); mySeriesOfPoint.BorderWidth = 2; mySeriesOfPoint.ChartType = SeriesChartType.Line; mySeriesOfPoint.ChartArea = "ChartArea1"; for (double x = population.minValue; x <= population.maxValue; x += 0.01) { NExpression solutionFunction = population.solutionFunction; solutionFunction.Parameters["x"] = x; double sfr = Convert.ToDouble(solutionFunction.Evaluate()); mySeriesOfPoint.Points.AddXY(x, sfr); } //Добавляем созданный набор точек в Chart chart.Series.Add(mySeriesOfPoint); chart.ChartAreas[0].RecalculateAxesScale(); } catch { chart.Series.Clear(); return; } }
public void DictionaryApproach(Dictionary <string, object> dict, string formula) { var expression = new NCalc.Expression(formula); expression.Parameters = dict; expression.Evaluate(); }
public string Compute(SessionVariables variables, LogLine logLine) { if (_exp == null) { _exp = new NCalc.Expression(this.Expression); _exp.EvaluateParameter += delegate(string name, NCalc.ParameterArgs args) { Variable var = curLL.GetVariableByName(name); if (var != null) { args.Result = var.Value; } else { args.HasResult = false; } }; } object obj = "ERR"; if (!Error) { curLL = logLine; _exp.Parameters.Clear(); try { obj = _exp.Evaluate().ToString(); } catch { Error = true; } } return(obj.ToString()); }
private void DecodeRuleDetails(CustomList <SalaryRule> ruleDetails) { try { foreach (SalaryRule item in ruleDetails) { var pattern = new Regex(@"(\@.*?\@)", RegexOptions.IgnorePatternWhitespace); foreach (Match m in pattern.Matches(item.Formula2.ToUpper())) { string[] parts = m.Groups[1].Value.Split('@'); SalaryRule obj = ruleDetails.Find(f => f.HeadName.ToUpper().Trim() == parts[1].ToUpper().Trim()); item.Formula2 = item.Formula2.ToUpper().Replace(m.Groups[1].Value, obj.Formula2); } NCalc.Expression exp = new NCalc.Expression(item.Formula2); object ret = exp.Evaluate(); item.Formula2 = ret.ToString(); decimal val = 0M; EmployeeSalaryTemp eST = new EmployeeSalaryTemp(); eST.SalaryRuleCode = item.SalaryRuleCode; eST.SalaryHeadKey = item.SalaryHeadKey; eST.IsFixed = item.IsFixed; if (decimal.TryParse(item.Formula2, out val)) { eST.Amount = Math.Round(val, 2); } _EmpSalaryTempList.Add(eST); } } catch (Exception ex) { throw ex; } }
//----------------------------------------------------------------------- public static float Evaluate(this string expression) { var exp = new NCalc.Expression(expression); var obj = exp.Evaluate(); float value; if (obj is double) { value = (float)(double)obj; } else if (obj is int) { value = (float)(int)obj; } else if (obj is bool) { value = (bool)obj ? 1 : 0; } else { value = (float)obj; } return(value); }
/// <inheritdoc /> public string Eval(Evaluator evaluator) { var expression = new NCalc.Expression(NestedExpression.Eval(evaluator)); if (expression.HasErrors()) { return("[ERROR]"); } expression.EvaluateParameter += (name, args) => { Delegate func = null; try { func = evaluator.Context.GetDelegate(name); } catch { throw new InvalidOperationException("Invalid logical operation."); } if (func.GetMethodInfo().GetParameters().Length == 0) { args.HasResult = true; args.Result = func.DynamicInvoke(); } else { throw new InvalidOperationException("Invalid logical operation."); } }; return(expression.Evaluate().ToString()); }
public static IEnumerable <object> Project(ValueDescriptor descriptor, CultureInfo culture, IEnumerable <object> values, NCalc.Expression expression) { return(values.Select(x => { expression.Parameters[ExpressionEvaluator.IdentifierValue] = x; return expression.Evaluate(); })); }
private void ResultBtn_Click(object sender, RoutedEventArgs e) { if (nonOperation && !string.IsNullOrEmpty(ResultTb.Text)) { NCalc.Expression exp = new NCalc.Expression(ResultTb.Text); ResultTb.Text = exp.Evaluate().ToString(); } }
public int NCalcMethod(Dictionary <string, object> input, string inputString) { var e = new NCalc.Expression(inputString); e.Parameters = input; var result2 = e.Evaluate(); return(Convert.ToInt16(result2)); }
public void ReplaceApproachNoLambda(Dictionary <string, object> dict, string formula) { foreach (var item in dict) { formula = formula.Replace("[" + item.Key + "]", item.Value.ToString()); } var expression = new NCalc.Expression(formula); var output = expression.Evaluate(); }
static void Main(string[] args) { int m = 1000000; // <------------ Number of calculations done. Change for different results Stopwatch stopWatch = new Stopwatch(); var ran = new Random(); string se = "if(A>=17 && A<= 360, Pow(10,(1.016 * Log10( A ) - 1.71)), if(A<=17, 0.11, 7.7))"; //se = "if(A>=17, Min(Pow(10,(1.016 * Log10( A ) - 1.71)), 7.7), 0.11)"; // Alternate arrangement NCalc.Expression e = new NCalc.Expression(se); Console.WriteLine("Using equation for Cadmium (accute): " + se); Console.WriteLine("# of loops: " + m); if (e.HasErrors()) { Console.WriteLine("Errors detected!"); Console.ReadLine(); return; } double total = 0; stopWatch.Start(); for (int i = 0; i < m; i++) { e.Parameters["A"] = ran.Next(500); var x = e.Evaluate(); total += (double)x; //Console.WriteLine("A="+ e.Parameters["A"] + "; E = " + x); // Uncomment to see results from equation NOTE: lower the number of loops } stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; Console.WriteLine("DONE!"); Console.WriteLine("Average output: " + total / m); string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("RunTime " + elapsedTime); Console.WriteLine("Now executing same equation, iterating parameters inline..."); int[] r = new int[m]; for (int i = 0; i < m; i++) { r[i] = ran.Next(500); } stopWatch.Restart(); e = new NCalc.Expression(se, NCalc.EvaluateOptions.IterateParameters); e.Parameters["A"] = r; var y = (IList)e.Evaluate(); stopWatch.Stop(); total = 0; foreach (double i in y) { total += i; } ts = stopWatch.Elapsed; Console.WriteLine("DONE!"); Console.WriteLine("Average output: " + total / m); elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("RunTime " + elapsedTime); Console.ReadLine(); }
public int ParameterAccess1(string formula) { var expression = new NCalc.Expression(formula); expression.Parameters["Variable1"] = 4; expression.Parameters["Variable2"] = 9; var output = expression.Evaluate(); return(Convert.ToInt16(output)); }
public async Task Calculate([Remainder] string expression) { var expr = new NCalc.Expression(expression, NCalc.EvaluateOptions.IgnoreCase); expr.EvaluateParameter += Expr_EvaluateParameter; var result = expr.Evaluate(); if (expr.Error == null) await Context.Channel.SendConfirmAsync("⚙ " + GetText("result"), result.ToString()); else await Context.Channel.SendErrorAsync("⚙ " + GetText("error"), expr.Error); }
public override HandlerItem[] GetResultsFor(string search) { List<HandlerItem> ret = new List<HandlerItem>(); try { NCalc.Expression exp = new NCalc.Expression(search); ret.Add(new HandlerItem(exp.Evaluate() + " = " + exp.ParsedExpression.ToString(),this)); } catch { } return ret.ToArray(); }
private object EvaluateExpression(IColumnExpression expression, DataRow row) { var exp = new NCalc.Expression(expression.Value); exp.EvaluateParameter += delegate(string name, NCalc.ParameterArgs args) { args.Result = GetValueFromRow(row, name); }; return(exp.Evaluate()); }
public override HandlerItem[] GetResultsFor(string search) { List <HandlerItem> ret = new List <HandlerItem>(); try { NCalc.Expression exp = new NCalc.Expression(search); ret.Add(new HandlerItem(exp.Evaluate() + " = " + exp.ParsedExpression.ToString(), this)); } catch { } return(ret.ToArray()); }
protected object EvaluateExpression(IColumnExpression expression, DataRow row) { var exp = new NCalc.Expression(expression.Value); var factory = new ColumnIdentifierFactory(); exp.EvaluateParameter += delegate(string name, NCalc.ParameterArgs args) { args.Result = GetValueFromRow(row, factory.Instantiate(name)); }; return(exp.Evaluate()); }
public Object Evaluate(Dictionary <string, Object> variables) { if (!isParsed) { throw new InvalidOperationException("Before calling the Evaluate function, you must call the Parse function."); } var exp = new NCalc.Expression(Expression); exp.Parameters = variables; return(exp.Evaluate()); }
public double getValue(string func, double x) { string funcCopy = func; string result; funcCopy = funcCopy.Replace("x", x.ToString()); funcCopy = funcCopy.Replace("X", x.ToString()); NCalc.Expression e = new NCalc.Expression(funcCopy); result = e.Evaluate().ToString(); return(Double.Parse(result)); //return 20.0; }
/// <summary> /// Gets the function result. /// </summary> /// <returns>The function result.</returns> /// <param name="function">The function.</param> /// <param name="input">The arguments values and expected results of the function.</param> public double GetFunctionResult(string function, FunctionBuilderInput input) { var expression = new NCalc.Expression(function); for (int i = 0; i < m_parameterNames.Length; i++) { expression.Parameters.Add(m_parameterNames[i], input.Arguments[i]); } var result = expression.Evaluate(); return((double)result); }
private static string ProcessStandardCalCommand(string message) { try { var expression = new NCalc.Expression(message, NCalc.EvaluateOptions.IgnoreCase); if (!expression.HasErrors()) { return(Convert.ToString(expression.Evaluate())); } } catch (Exception) { } return(null); }
private double mu(double t) { exprMU = new NCalc.Expression(muText.Text); exprMU.Parameters["pi"] = Math.PI; exprMU.Parameters["e"] = Math.E; exprMU.Parameters["a"] = Convert.ToDouble(aText.Text); exprMU.Parameters["b"] = Convert.ToDouble(bText.Text); exprMU.Parameters["t"] = t; double r = Convert.ToDouble(exprMU.Evaluate()); return(r); }
public static async Task Calculate(IUserMessage msg, [Remainder] string expression) { try { var expr = new NCalc.Expression(expression, NCalc.EvaluateOptions.IgnoreCase); expr.EvaluateParameter += Expr_EvaluateParameter; var result = expr.Evaluate(); await msg.Reply(string.Format("⚙ `{0}`", expr.Error ?? result)); } catch (Exception e) { await msg.Reply($"Failed to evaluate: {e.Message} "); } }
private void Evaluate_Function_Button_Click(object sender, RoutedEventArgs e) { try { LogTextBox.Document.Blocks.Clear(); NCalc.Expression exp = new NCalc.Expression(FormulaTextBox.Text); if(!string.IsNullOrWhiteSpace(XValueTextBox.Text)) { Double xValue = 1.0; Double.TryParse(XValueTextBox.Text, out xValue); exp.Parameters["x"] = xValue; } String result = exp.Evaluate().ToString(); LogTextBox.AppendText(result); } catch(Exception ex) { System.Windows.MessageBox.Show(ex.ToString()); } scrollEl.ScrollToBottom(); }
public ISearchResult Search(string phrase) { phrase = Utils.PhraseWithoutPrefix(phrase, Prefix); var result = new TextSearchResult("Calculator"); if (!string.IsNullOrWhiteSpace(phrase)) { var ex = new NCalc.Expression(phrase); try { // TODO: allow sin, now only Sin works result.Text = string.Format("{0} = {1}", phrase, ex.Evaluate()); } catch { result.Text = null; } } result.SearchIcon = SearchIcon;// GetSearchIcon(); return result; }
private static double GetAndEvaluateExpression(string calculationName, IActor player) { var col = MongoUtils.MongoData.GetCollection<BsonDocument>("Calculations", "Combat"); var doc = MongoUtils.MongoData.RetrieveObjectAsync<BsonDocument>(col, c => c["_id"] == calculationName).Result; NCalc.Expression expression = new NCalc.Expression(ReplaceStringWithNumber(player, doc["Expression"].AsString)); double expressionResult = (double)expression.Evaluate(); //let's take into consideration some other factors. Visibility, stance, etc. //TODO: add that here. They only take away from chance to hit. But some of them can be negated. //if it's dark but player can see in the dark for example. return expressionResult; }
private void RunRules(String controlId, ControlCatalog catalog, IEnumerable<ControlRule> rules, DateTime now, Object[] answers) { var results = new List<RuleEvaluated>(); var validRules = rules.Where(r => r.ControlId == controlId); var parameters = ControlAnswers.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Values.First()); foreach (var rule in validRules) { var calc = new NCalc.Expression(rule.Rule.If); foreach (var answer in answers) { calc.Parameters.Clear(); calc.Parameters = parameters; calc.Parameters[controlId] = answer; try { var result = (Boolean)calc.Evaluate(); String message = null; if (result) { switch (rule.Rule.Then.GetType().Name) { case "NoActionOutcome": message = rule.Rule.Then.Message; break; case "FailedValidationOutcome": var outcome = (FailedValidationOutcome)rule.Rule.Then; message = $"{outcome.ValidatorName} failed for {outcome.ControlId} with message {outcome.Message}"; break; default: message = rule.Rule.Then.Message; break; } } else { switch (rule.Rule.Else.GetType().Name) { case "NoActionOutcome": message = rule.Rule.Else.Message; break; case "FailedValidationOutcome": var outcome = (FailedValidationOutcome)rule.Rule.Else; message = $"{outcome.ValidatorName} failed for {outcome.ControlId} with message {outcome.Message}"; break; default: message = rule.Rule.Else.Message; break; } } ApplyChange(new RuleEvaluated { ControlId = controlId, Date = now, FormId = rule.FormId, Id = Guid.NewGuid(), ReportingEntityInstanceId = ReportingEntityId, Result = message, RuleName = rule.Rule.Name, Values = answers, Version = Version }); } catch (Exception e) { Console.WriteLine($"Error in expression: {e.Message}"); } } } }
private static double GetAndEvaluateExpression(string calculationName, Character.Iactor player) { MongoCollection col = MongoUtils.MongoData.GetCollection("Calculations", "Combat"); IMongoQuery query = Query.EQ("_id", calculationName); BsonDocument doc = col.FindOneAs<BsonDocument>(query).AsBsonDocument; NCalc.Expression expression = new NCalc.Expression(ReplaceStringWithNumber(player, doc["Expression"].AsString)); double expressionResult = (double)expression.Evaluate(); //let's take into consideration some other factors. Visibility, stance, etc. //TODO: add that here. They only take away from chance to hit. But some of them can be negated. //if it's dark but player can see in the dark for example. return expressionResult; }
//Set the function to maximize/minimize public static bool setFunctionToOperate(string functionAsText) { bool canEvaluate = false; _exp = new NCalc.Expression(functionAsText); NCalc.Expression _expTest = new NCalc.Expression(functionAsText); _expTest.Parameters["x"] = 1; try { _expTest.Evaluate(); canEvaluate = true; } catch { canEvaluate = false; } return !_exp.HasErrors() && !_expTest.HasErrors() && canEvaluate; }
private int GetArraySize(string sFieldName) { int iLength = 1; int iStart = 0; if (sFieldName.Contains('[')) { while (sFieldName.IndexOf('[', iStart) > 0) { string sDimension; int iAStart = sFieldName.IndexOf('[', iStart); int iAEnd = sFieldName.IndexOf(']', iStart + 1); sDimension = sFieldName.Substring(iAStart + 1, iAEnd - iAStart - 1); sDimension=ReplaceDefines(sDimension); NCalc.Expression a = new NCalc.Expression(sDimension.Replace("eHashNumber", "32"));// TODO: make better int t = Convert.ToInt32(a.Evaluate()); iLength = iLength * t; iStart = iAEnd; } return iLength; } else { return 1; } }
//[TestMethod] public void TestMethod1() { var str = "(x*2)+5"; var list = new Dictionary<int, int>(); var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 2000; i++ ) { var exp = new NCalc.Expression(str); exp.Parameters["x"] = i; var result = exp.Evaluate(); list.Add(i, (int)result); break; } sw.Stop(); System.Diagnostics.Debug.WriteLine(sw.Elapsed.ToString()); sw.Reset(); list.Clear(); sw.Start(); for (int i = 0; i < 2000; i++) { var exp = new NCalc.Expression(str, NCalc.EvaluateOptions.NoCache); exp.Parameters["x"] = i; var result = exp.Evaluate(); list.Add(i, (int)result); } sw.Stop(); System.Diagnostics.Debug.WriteLine(sw.Elapsed.ToString()); sw.Reset(); list.Clear(); sw.Start(); var exp2 = new NCalc.Expression(str); for (int i = 0; i < 2000; i++) { exp2.Parameters["x"] = i; var result = exp2.Evaluate(); list.Add(i, (int)result); } sw.Stop(); System.Diagnostics.Debug.WriteLine(sw.Elapsed.ToString()); sw.Reset(); list.Clear(); sw.Start(); var exp1 = new NCalc.Expression(str, NCalc.EvaluateOptions.NoCache); for (int i = 0; i < 2000; i++) { exp1.Parameters["x"] = i; var result = exp1.Evaluate(); list.Add(i, (int)result); } sw.Stop(); System.Diagnostics.Debug.WriteLine(sw.Elapsed.ToString()); //System.Diagnostics.Debug.WriteLine(exp.Evaluate().ToString()); Assert.IsTrue(true); }
private void ReadStructures(string[] sFile) { bool bStartFound = false; bool bInHashIf = false; bool bInComment = false; bool bSkipUnionExtraLines = false; bool bFirstLineOfUnion = false; int iUnionRef = 0; int iOpenStructureCount = 0; stTableStructure stCurrentTable = new stTableStructure(); string sTestBuffer = ""; bStartFound = false; for (int i = 0; i < sFile.Count(); i++) { string sLine = sFile[i].Replace('\t', ' '); string sStructureName; if (sLine.Contains("/*")) { bInComment = true; } sTestBuffer += sLine + "\r\n"; if (bInComment == false) { if (sLine.Trim().ToUpper().StartsWith("union".ToUpper())) { // oh no bSkipUnionExtraLines = true; iUnionRef = iOpenStructureCount; bFirstLineOfUnion = true; } if (sLine.ToUpper().Contains("typedef struct".ToUpper()) || sLine.StartsWith ("struct")==true ) { bStartFound = true; bInHashIf = false; stCurrentTable = new stTableStructure(); stCurrentTable.sFields = new List<string>(); stCurrentTable.sFieldsType = new List<string>(); stCurrentTable.sDescription = new List<string>(); stCurrentTable.bBitField = false; if (sLine.Trim().EndsWith("{")) { iOpenStructureCount++; } if (sLine.StartsWith("struct") == true) { stCurrentTable.sStructureName = sLine.Replace("{", "").Trim(); } } if (bStartFound) { int iStartPos = sLine.IndexOf("sizeof("); int iEndPos = 0; if (sLine.Trim().StartsWith("{")) { iOpenStructureCount++; } if (sLine.Trim().StartsWith("}")) { iOpenStructureCount--; if (iOpenStructureCount == iUnionRef) { bSkipUnionExtraLines = false; } else { bFirstLineOfUnion = false; } if (iOpenStructureCount == 0) { iEndPos = sLine.Trim().IndexOf(";"); sStructureName = sLine.Trim().Substring(1, iEndPos - 1).Trim(); if (sStructureName.Length > 0) { stCurrentTable.sStructureName = sStructureName; } m_TableStructures.Add(stCurrentTable); bStartFound = false; sTestBuffer = ""; } } else { if (sLine.ToUpper().Contains("#if".ToUpper())) { string[] sTokens = sLine.Replace("\r", "").Split(' '); sTokens[1] = ReplaceDefines(sTokens[1]); sTokens[1] = ReplaceDefines(sTokens[1]); NCalc.Expression a = new NCalc.Expression(sTokens[1]);// TODO: make better int t; try { t = Convert.ToInt32(a.Evaluate()); } catch (Exception ex) { t = 1; } if (t == 0) { bInHashIf = true; } } // just ignore #else variable for now if (sLine.ToUpper().Contains("#else".ToUpper()) || sLine.ToUpper().Contains("#elif".ToUpper())) //#elif { bInHashIf = true; } if (sLine.ToUpper().Contains("#endif".ToUpper())) { bInHashIf = false; } if (sLine.Contains(";") && bInHashIf == false && sLine.Trim().Contains(" ") && sLine.Trim().StartsWith("//") == false && (bSkipUnionExtraLines == false || (bSkipUnionExtraLines == true && bFirstLineOfUnion == true))) { if (iOpenStructureCount == iUnionRef+1) { bFirstLineOfUnion = false; } // unsigned char hour; int iSemiColonPos = sLine.IndexOf(';'); int iSpacePos = sLine.LastIndexOf(' ', iSemiColonPos); int iCommandPos = sLine.LastIndexOf("//"); if (iCommandPos > 0) { stCurrentTable.sDescription.Add(sLine.Substring(iCommandPos + 2).Replace("\r", "")); } else { stCurrentTable.sDescription.Add(""); } string sFieldType = GetVaribleType(sLine); if (sLine.Substring(iSpacePos - 1, iSemiColonPos - iSpacePos).Trim().Contains(":")) { // contains bit field :( stCurrentTable.bBitField = true; stCurrentTable.sFields.Add(sLine); stCurrentTable.sFieldsType.Add(sLine); } else { stCurrentTable.sFields.Add(sLine.Substring(iSpacePos, iSemiColonPos - iSpacePos).Trim()); stCurrentTable.sFieldsType.Add(sLine.Substring(0, iSpacePos).Trim()); } } } } } if (sLine.Contains("*/")) { bInComment = false; } } }
private bool? evaluateExpressionString() { string newExpressionString = VariableEngine.substituteVariablesInString(_expressionString); NCalc.Expression ex = new NCalc.Expression(newExpressionString); _latestExpressionSubstitutionString = newExpressionString; Debug.Log(newExpressionString); bool result = false; try { result = (bool)ex.Evaluate(); } catch (Exception) { return null; } return result; }
/// <summary> /// Gets the function result. /// </summary> /// <returns>The function result.</returns> /// <param name="function">The function.</param> /// <param name="input">The arguments values and expected results of the function.</param> public double GetFunctionResult(string function, FunctionBuilderInput input) { var expression = new NCalc.Expression(function); for (int i = 0; i < m_parameterNames.Length; i++) { expression.Parameters.Add(m_parameterNames[i], input.Arguments[i]); } var result = expression.Evaluate(); return (double)result; }
public override bool Play(MappedItem control, Log log) { AppProcess process = AppManager.GetProcess(control); MappedItem window = AppManager.GetWindow(control); IUIItem uiItem = AppPlaybackService.GetControl(process, window, control, AppManager); Point clickPoint = new Point(X,Y); Point globalPoint = new Point((int)uiItem.Bounds.X + clickPoint.X, (int)uiItem.Bounds.Y + clickPoint.Y); Screenshot screenshot = CreateScreenshot(log); Cursor.LeftClick(globalPoint); string actualText = CopyText(); string expectedText = textParam.GetValue(); if (actualText == null) actualText = ""; if (expectedText == null) expectedText = ""; string originalExpectedText = expectedText; foreach (Variable v in this.TestItem.Test.Variables.OrderBy(v => v.Name.Length)) { expectedText = expectedText.Replace(v.Name, v.Value.ToString()); } Expression e = new Expression(expectedText); try { expectedText = e.Evaluate().ToString(); } catch (Exception ex) { //e.Evaluate() errored out. Probably not an expression expectedText = originalExpectedText; } if(!Equals(actualText, expectedText)) { string error = "Expected \"{0}\" but value was \"{1}\""; error = string.Format(error, expectedText, actualText); log.CreateLogItem(LogItemCategory.Error, error, screenshot); return false; } string description = "Validated that the text at ({0},{1}) on {2} is equal to \"{3}\""; description = string.Format(description, X, Y, control.Name, Text); log.CreateLogItem(LogItemCategory.Validation, description, screenshot); return true; }
public Object Evaluate(Dictionary<string, Object> variables) { if (!isParsed) throw new InvalidOperationException("Before calling the Evaluate function, you must call the Parse function."); var exp = new NCalc.Expression(Expression); exp.Parameters = variables; return exp.Evaluate(); }