public void LargerEqn3() { PostfixConverter converter = new PostfixConverter("12+3"); List <string> postfix = converter.ConvertAndReturn(); string result = ""; foreach (string c in postfix) { result += c; } Assert.AreEqual(result, "123+"); }
public void ComplexEqn3() { PostfixConverter converter = new PostfixConverter("(3+4)*2*3+6"); List <string> postfix = converter.ConvertAndReturn(); string result = ""; foreach (string c in postfix) { result += c; } Assert.AreEqual(result, "34+2*3*6+"); }
public void ComplexEqn1Inverse() { PostfixConverter converter = new PostfixConverter("2*3+1"); List <string> postfix = converter.ConvertAndReturn(); string result = ""; foreach (string c in postfix) { result += c; } Assert.AreEqual(result, "23*1+"); }
public void SimpleEquation() { PostfixConverter converter = new PostfixConverter("1+2"); List <string> postfix = converter.ConvertAndReturn(); string result = ""; foreach (string c in postfix) { result += c; } Assert.AreEqual(result, "12+"); }
public async Task MessageReceivedAsync(IDialogContext context, IAwaitable <Message> argument) { List <string> equation; string answer; var message = await argument; PostfixConverter pf = new PostfixConverter(message.Text); equation = pf.ConvertAndReturn(); PfCalculator pfc = new PfCalculator(); answer = pfc.CalculatePostfix(equation); await context.PostAsync($"The answer is: {answer}"); context.Wait(MessageReceivedAsync); }
/// <summary> /// event handler for autocorrecting the rule in the textbox /// </summary> private void ModificationTextBox_OnCtrlWPressed(object sender, KeyEventArgs keyEventArgs) { if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control && _cleanedRule != string.Empty) // Is Alt key pressed { if (Keyboard.IsKeyDown(Key.W)) { bool bestVariableEver = false; FlowDocument flow = ModificationTextBox.Document; while (!bestVariableEver) { var text = _cleanedRule; text = PostfixConverter.Tokenize(text); var ifMatches = Regex.Matches(text, @"(?<=(AKO))(.*)(?=(ONDA))|(?<=(ONDA))(.*)"); string test = ifMatches[0].Value.Trim(); string testFactor = ifMatches[1].Value.Trim(); Console.WriteLine("First part of the expression: " + test); Console.WriteLine("Second part of the expression: " + ifMatches[1].Value.Trim()); var tuple = ValidateExpression(test, testFactor); flow = tuple.Item1; bestVariableEver = tuple.Item2; } _cleanedRule = _cleanedRule.Trim(); WarningLabel.Content = "Enjoy!!!!"; var paragraph = new Paragraph(); paragraph.Inlines.Add(_cleanedRule); _cleanedRule = string.Empty; ModificationTextBox.Document = flow; } } }
/// <summary> /// Converts the expression and it's factor to their respective objects. /// If the conversion isn't successful, the invalid parts of the expression /// are colored red in the textbox as a warning to the user. /// </summary> /// <param name="expression"> /// expression that needs to be validated /// </param> /// <param name="factor"> /// factor part of the initial rule /// </param> /// <returns> /// flowDocument which contains the processed text, /// and a indicator whether the expression is valid /// </returns> private Tuple <FlowDocument, bool> ValidateExpression(string expression, string factor) { var expressionRegularized = true; _cleanedRule = string.Empty; // get all invalid character intervals in the expressions var errors = PostfixConverter.CheckInvalidCombinations(expression); int[] splitIndexes = new int[errors.Count * 2]; // split the expression string on the good/bad intervals // bad will appear as even splits for (int i = 0; i < errors.Count; i++) { splitIndexes[2 * i] = errors[i].Item1; splitIndexes[2 * i + 1] = errors[i].Item2 + 1; } Console.WriteLine("ALL ERRORS:"); foreach (var error in errors) { Console.WriteLine(error + expression.Substring(error.Item1, error.Item2 - error.Item1 + 1)); } var split = expression.SplitAt(splitIndexes); // wrapping each string to a decoreated Run object // and adding it to paragraph FlowDocument flow = new FlowDocument(); Paragraph para = new Paragraph(); var ifPart = "AKO "; var thenPart = " ONDA "; para.Inlines.Add(new Run(ifPart)); _cleanedRule += ifPart; // wrap the intervals in a run object and // add it to the paragraph for (int i = 0; i < split.Length; i++) { if (i % 2 != 0) { Brush brush = Brushes.Red; var run = new Run(split[i]) { Foreground = brush, FontSize = 20, FontWeight = FontWeights.Bold }; para.Inlines.Add(run); expressionRegularized = false; } else { para.Inlines.Add(new Run(split[i])); _cleanedRule += " " + split[i] + " "; } } para.Inlines.Add(new Run(thenPart)); para.Inlines.Add(new Run(factor)); // clean necessary multiple spacings _cleanedRule += " " + thenPart + " "; _cleanedRule = Regex.Replace(_cleanedRule, @"\s+", " "); _cleanedRule += factor; _cleanedRule = Regex.Replace(_cleanedRule, @"\s+", " "); // add the paragraph flow.Blocks.Add(para); Console.WriteLine( new TextRange(RuleRichTextBox.Document.ContentStart, RuleRichTextBox.Document.ContentEnd).Text); return(new Tuple <FlowDocument, bool>(flow, expressionRegularized)); }
/// <summary> /// parses the entered rule. if the rule is valid /// adds it to rules, if not displays the invalid text /// in the rule textbox as red, which can be autocorrected /// with CTRL + W command /// </summary> private void RuleRichTextBox_EnterClicked(object sender, KeyEventArgs e) { if (e.Key == Key.Return) { string pattern = @"\(\d([,.]\d+)?\)"; // this is how you get text from richtextbox string initialExpression = new TextRange(RuleRichTextBox.Document.ContentStart, RuleRichTextBox.Document.ContentEnd).Text; string expression = initialExpression.Replace("\n", string.Empty).Replace("\r", string.Empty); expression = Regex.Replace(expression, @"\s+", " "); // tokenize the expression expression = PostfixConverter.Tokenize(expression); // checking if the sentence begins with an IF var ifBeginMatch = Regex.Matches(expression, @"^(:?AKO\s)"); if (ifBeginMatch.Count == 0) { WarningLabel.Content = "Expression not beginning with IF, please reenter"; return; } //Grabbing expression & conclusion var ifMatches = Regex.Matches(expression, @"(?<=(AKO))(.*)(?=(ONDA))|(?<=(ONDA))(.*)"); if (ifMatches.Count == 0) { WarningLabel.Content = "Unallowed input, rewrite the rule"; return; } // trim the factor/expression part string test = ifMatches[0].Value.Trim(); string testFactor = ifMatches[1].Value.Trim(); Console.WriteLine("First part of the expression: " + test); Console.WriteLine("Second part of the expression: " + ifMatches[1].Value.Trim()); // Checks whether the conclusion is valid if (!Regex.IsMatch(ifMatches[1].Value, @"\s*\(\s*\d([,.]\d+)?\s*\)\s*")) { WarningLabel.Content = "Conclusion parsing failed, check after THEN"; return; } // Validate the expression var tuple = ValidateExpression(test, testFactor); // set the TextBox Document and regularized flag RuleRichTextBox.Document = tuple.Item1; var expressionRegularized = tuple.Item2; if (expressionRegularized) { // prepare the expression for the caching part var replacedExpression = expression .Replace(Regex.Match(expression, pattern).ToString(), string.Empty) .Replace("( ", "(") .Replace(" )", ")") .Replace(" ", " "); Rule modRule = MainWindow.GetCachedRule(replacedExpression); if (modRule == null) { try { AddRule(PostfixConverter.RuleConversion(expression)); } catch (ParsingException ex) { WarningLabel.Content = ex.Message; RuleRichTextBox.Document = new FlowDocument(); } } else { // regex for extracting the factor string match = Regex.Match(expression, @"[0-9]([.,][0-9]{1,3})?").ToString(); double factor = double.Parse(match); modRule.ObservedConclusionFactor = factor; } _factor = string.Empty; RuleRichTextBox.Document = new FlowDocument(); } else { WarningLabel.Content = "Potential sytax mistakes. Press Ctrl+W for autocorrect"; } e.Handled = true; } else if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control && _cleanedRule != string.Empty) { if (Keyboard.IsKeyDown(Key.W)) { bool bestVariableEver = false; FlowDocument flow = RuleRichTextBox.Document; // loop until all the mistakes are corrected while (!bestVariableEver) { var text = _cleanedRule; text = PostfixConverter.Tokenize(text); var ifMatches = Regex.Matches(text, @"(?<=(AKO))(.*)(?=(ONDA))|(?<=(ONDA))(.*)"); string test = ifMatches[0].Value.Trim(); string testFactor = ifMatches[1].Value.Trim(); Console.WriteLine("First part of the expression: " + test); Console.WriteLine("Second part of the expression: " + ifMatches[1].Value.Trim()); var tuple = ValidateExpression(test, testFactor); flow = tuple.Item1; bestVariableEver = tuple.Item2; } _cleanedRule = _cleanedRule.Trim(); WarningLabel.Content = "Enjoy!!!!"; var paragraph = new Paragraph(); paragraph.Inlines.Add(_cleanedRule); _cleanedRule = string.Empty; RuleRichTextBox.Document = flow; } } }
/// <summary> /// Converts the text from the textbox to a rule. /// If the conversion isn't possible, display /// invalid values colored red in the textbox as a warning, /// with an option of autocorrection on CTRL + W. /// If created rule is present in the system, do nothing. /// Else update the rules collection with the newly created rule. /// </summary> private void OkButton_Click(object sender, RoutedEventArgs e) { MainWindow mainWindow = this.Owner as MainWindow; string pattern = @"\(\s*\d([,.]\d+)?\s*\)"; var unmod = UnModifiedRule.Replace(Regex.Match(UnModifiedRule, pattern).ToString(), string.Empty); Rule unModRule = MainWindow.GetCachedRule(unmod); // this is how you get text from richtextbox string expression = new TextRange(ModificationTextBox.Document.ContentStart, ModificationTextBox.Document.ContentEnd).Text; expression = expression.Replace("\n", string.Empty).Replace("\r", string.Empty); expression = Regex.Replace(expression, @"\s+", " "); expression = PostfixConverter.Tokenize(expression); // checking if the sentence begins with an IF var ifBeginMatch = Regex.Matches(expression, @"^(:?AKO\s)"); if (ifBeginMatch.Count == 0) { WarningLabel.Content = "Expression not beginning with IF, please reenter"; return; } //Grabbing expression & conclusion var ifMatches = Regex.Matches(expression, @"(?<=(AKO))(.*)(?=(ONDA))|(?<=(ONDA))(.*)"); if (ifMatches.Count == 0) { WarningLabel.Content = "Unallowed input, rewrite the rule"; return; } // trim the match values string test = ifMatches[0].Value.Trim(); string testFactor = ifMatches[1].Value.Trim(); Console.WriteLine("First part of the expression: " + test); Console.WriteLine("Second part of the expression: " + ifMatches[1].Value.Trim()); if (!Regex.IsMatch(ifMatches[1].Value, @"\s*\(\s*\d([,.]\d+)?\s*\)\s*((\d|\w)+)$")) { WarningLabel.Content = "Conclusion parsing failed, check after THEN"; return; } // validate the expression var tuple = ValidateExpression(test, testFactor); ModificationTextBox.Document = tuple.Item1; var expressionRegularized = tuple.Item2; if (expressionRegularized) { // clean the expression var replacedExpression = expression .Replace(Regex.Match(expression, pattern).ToString(), string.Empty) .Replace("( ", "(") .Replace(" )", ")") .Replace(" ", " "); Rule modRule = MainWindow.GetCachedRule(replacedExpression); if (modRule == null) { MainWindow.ReplaceRule(unModRule, PostfixConverter.RuleConversion(expression)); } else { // regex for extracting the factor string match = Regex.Match(testFactor, @"[0-9]([.,][0-9]{1,3})?").ToString(); double factor = double.Parse(match); double TOLERANCE = 0.0001; if (Math.Abs(factor - unModRule.ObservedConclusionFactor) > TOLERANCE) { unModRule.ObservedConclusionFactor = factor; } } _factor = string.Empty; Close(); } else { WarningLabel.Content = "Potential sytax mistakes. Press Ctrl+W for autocorrect"; } }