public void EqualsSameObjectTest() { var token = new OperationToken(Operations.Multiplication); Assert.True(token.Equals(token)); Assert.Equal(token, token); }
public void EqualsNullTest() { var token = new OperationToken(Operations.Multiplication); Assert.False(token.Equals(null)); Assert.NotNull(token); }
public void EqualsDiffTypeTest() { var token = new OperationToken(Operations.Multiplication); Assert.False(token.Equals(1)); Assert.NotEqual((object)1, token); }
private static bool CanPushOperationTokenToStack(OperationToken operationToken, Stack <IToken> operatorStack) { var precedence = GetOperationPrecedence(operationToken, operatorStack.Peek()); var canPush = precedence > 0 || precedence == 0 && operationToken.Associativity == OperationAssociativity.Right; return(canPush); }
public void EqualsDiffOperationTest() { var token1 = new OperationToken(Operations.Multiplication); var token2 = new OperationToken(Operations.Subtraction); Assert.False(token1.Equals(token2)); Assert.NotEqual(token1, token2); }
public override decimal Evaluate(string expression) { List <Token> tokens = ConvertToTokens(expression); List <Token> outputTokens = new List <Token>(); Stack <Token> stack = new Stack <Token>(); foreach (Token token in tokens) { if (token is OperationToken) { OperationToken operationToken = token as OperationToken; while (stack.Count > 0 && stack.Peek() is OperationToken) { OperationToken peek = stack.Peek() as OperationToken; int i = operationToken.GetPrecedence() - peek.GetPrecedence(); if (i <= 0) { outputTokens.Add(stack.Pop()); } else { break; } } stack.Push(operationToken); } else if (token is BracketToken) { if ((token as BracketToken).BracketType == BracketType.Left) { stack.Push(token); } else { while (stack.Count > 0) { Token top = stack.Pop(); if (!(top is BracketToken) || (top as BracketToken).BracketType != BracketType.Left) { outputTokens.Add(top); } } } } else { outputTokens.Add(token); } } foreach (var operatorToken in stack) { outputTokens.Add(operatorToken); } return(CalculateTokens(outputTokens)); }
/// <summary> /// Returns: /// <list type="bullet"> /// <item> /// <term>positive number</term> /// <description>if <paramref name="operation"/> has greater precedence than <paramref name="compareTo"/></description> /// </item> /// <item> /// <term>0</term> /// <description>if <paramref name="operation"/> has the same precedence as <paramref name="compareTo"/></description> /// </item> /// <item> /// <term>negative number</term> /// <description>if <paramref name="operation"/> has smaller precedence than <paramref name="compareTo"/></description> /// </item> /// </list> /// </summary> /// <returns></returns> private static int GetOperationPrecedence(OperationToken operation, IToken compareTo) { if (compareTo is StringToken) { return(-1); } var compareToOperation = compareTo as OperationToken; if (compareToOperation == null) { return(1); } return(operation.Precedence - compareToOperation.Precedence); }
private decimal CalculateTokens(List <Token> outputTokens) { while (outputTokens.Count > 1) { int operatorIndex = outputTokens.FindIndex(token => token is OperationToken); OperationToken operationToken = outputTokens[operatorIndex] as OperationToken; ValueToken leftValueToken = outputTokens[operatorIndex - 2] as ValueToken; ValueToken rightValueToken = outputTokens[operatorIndex - 1] as ValueToken; outputTokens.RemoveAt(operatorIndex); outputTokens.RemoveAt(operatorIndex - 1); decimal result = DoOperation(leftValueToken.Value, rightValueToken.Value, operationToken.Operation); leftValueToken.Value = result; } return((outputTokens[0] as ValueToken).Value); }
public static int OperationTokenPriority(OperationToken token) { switch (token) { case OperationToken.Minus: case OperationToken.Plus: return(0); case OperationToken.Multiply: case OperationToken.Divide: return(1); case OperationToken.Power: return(2); default: throw new ArgumentOutOfRangeException(); } }
private static SyntaxNode PlaceOperationToken(OperationToken token, SyntaxNode currentNode) { // Insertion of operation tokens is right-biased (will try to use the right "child" position of a node first), // except in the case where the new node's precendence is less than that of the node being examined. var newNode = new SyntaxNode(token); var currentOperationToken = (OperationToken)currentNode.Token; if (token.Precedence < currentOperationToken.Precedence) { var leftOperationToken = currentNode.Left?.Token as OperationToken; if (leftOperationToken != null) { newNode.Right = currentNode.Left; } else { newNode.Left = currentNode.Left; } currentNode.Left = newNode; return(currentNode); } if (currentNode.Right == null) { currentNode.Right = newNode; return(newNode); } var rightOperationToken = currentNode.Right.Token as OperationToken; if (rightOperationToken != null && token.Precedence < rightOperationToken.Precedence) { newNode.Left = currentNode.Left; currentNode.Left = newNode; return(currentNode); } return(currentNode); }
/// <summary> /// Parses a summation production, handling addition and subtraction. /// </summary> /// <param name="enumerator">An enumerator containing the current location in the Expression of the parser.</param> /// <returns>Returns a parse tree node representing this sub-expression in the order it should be evaluated.</returns> protected ParseTreeNode ParseSummation(ParserEnumerator enumerator) { ParseTreeNode currentNode = ParseProduction(enumerator); while (enumerator.Accept <OperationToken>(t => t.Operation == OperationToken.OperationType.Add || t.Operation == OperationToken.OperationType.Subtract)) { OperationToken current = enumerator.Current as OperationToken; if (current.Operation == OperationToken.OperationType.Add) { currentNode = new BinaryParseTreeNode(AddEvaluator, currentNode, ParseProduction(enumerator)); } else if (current.Operation == OperationToken.OperationType.Subtract) { currentNode = new BinaryParseTreeNode(SubtractEvaluator, currentNode, ParseProduction(enumerator)); } } return(currentNode); }
/// <summary> /// Parses a production production (I might have called it that on purpose.)<para/> /// Basically, this handles multiplication and division. /// </summary> /// <param name="enumerator">An enumerator containing the current location in the Expression of the parser.</param> /// <returns>Returns a parse tree node representing this sub-expression in the order it should be evaluated.</returns> protected ParseTreeNode ParseProduction(ParserEnumerator enumerator) { ParseTreeNode currentNode = ParseUnary(enumerator); while (enumerator.Accept <OperationToken>(t => t.Operation == OperationToken.OperationType.Multiply || t.Operation == OperationToken.OperationType.Divide)) { OperationToken current = enumerator.Current as OperationToken; if (current.Operation == OperationToken.OperationType.Multiply) { currentNode = new BinaryParseTreeNode(MultiplyEvaluator, currentNode, ParseUnary(enumerator)); } else if (current.Operation == OperationToken.OperationType.Divide) { currentNode = new BinaryParseTreeNode(DivideEvaluator, currentNode, ParseUnary(enumerator)); } } return(currentNode); }
string ParseOperationToken(OperationToken token) { switch (token.Value) { case Operation.Add: return("+"); case Operation.Divide: return("/"); case Operation.Equals: return("="); case Operation.Multiply: return("*"); case Operation.Remove: return("-"); default: throw new InvalidOperationException($"Unknown {nameof(Operation)} type: {token.Value}."); } }
/// <summary> /// Parses unary operators, such as anything prefixed with + and -.<para/> /// This correctly swallows any additional operators so as to avoid any huge unnecessary chains of unary negation. /// This means an expression like <c>y=--++--+--++--++++--x</c> will correctly reduce to <c>y=x</c>. /// </summary> /// <param name="enumerator">An enumerator containing the current location in the Expression of the parser.</param> /// <returns>Returns a parse tree node representing this sub-expression in the order it should be evaluated.</returns> protected ParseTreeNode ParseUnary(ParserEnumerator enumerator) { bool positive = true; while (enumerator.Accept <OperationToken>(t => t.Operation == OperationToken.OperationType.Add || t.Operation == OperationToken.OperationType.Subtract)) { OperationToken current = enumerator.Current as OperationToken; if (current.Operation == OperationToken.OperationType.Subtract) { positive = !positive; } // do nothing if the operation token is positive } if (positive) { return(ParseAtomic(enumerator)); } else { return(new UnaryParseTreeNode(NegationEvaluator, ParseAtomic(enumerator))); } }
/// <summary> /// Evaluate a string based expression. /// </summary> /// <param name="expression">The expression to evaluate</param> /// <param name="variableLookup">A delegate that should return the value of the variable specified.</param> /// <returns>An evaluated expression</returns> public static int Evaluate(string expression, LookupEvaluator variableLookup) { // Get all tokens then remap and strip all whitespace // var tokens = Regex.Split(expression, "(?<=[-+*/(),])(?=.)|(?<=.)(?=[-+*/(),])") .Select(element => Regex.Replace(element, "\\s+", "")) .Where(element => element != "") .ToArray(); var OperationStack = new Stack <OperationToken>(); var NumberStack = new Stack <double>(); // Will either be a 1 or -1 int?sign = null; for (int i = 0; i < tokens.Length; i++) { var token = tokens[i]; double?possibleNumber = getNumberOrNothing(token); var operation = new OperationToken { Operation = token[0] }; if (!operation.IsValid && !possibleNumber.HasValue) { // Is a variable // possibleNumber = variableLookup(token); } // Handle negatives and positives // if (sign.HasValue) { possibleNumber = possibleNumber * sign; sign = null; } if (possibleNumber.HasValue) { // Is number // if (!OperationStack.IsEmpty()) { var topOperation = OperationStack.Peek(); if (topOperation.IsDivision || topOperation.IsMultiplication) { if (NumberStack.Count < 1) { throw new ArgumentException("Invalid Syntax"); } OperationStack.Pop(); // Passed our test, remove from stack // var number = NumberStack.Pop(); NumberStack.Push(topOperation.Apply(number, possibleNumber.Value)); continue; } } NumberStack.Push(possibleNumber.Value); } else { if (operation.IsAddition || operation.IsSubtraction) { var previousIndex = i - 1; if (previousIndex < 0) { // The sign provided was the first sign, it must be a + or - signifying that its positive or negative // sign = operation.IsSubtraction ? -1 : 1; continue; } else { var previousOperation = new OperationToken() { Operation = tokens[previousIndex][0] }; // If the previous token was an operation then this token must mean positive or negative // // Also make sure its not the last operation either // if (previousOperation.IsOperation && i + 1 < tokens.Length) { sign = operation.IsSubtraction ? -1 : 1; continue; } else if (!OperationStack.IsEmpty()) { // There's a pending operation, let's do that instead // var topOperation = OperationStack.Peek(); if (topOperation.IsAddition || topOperation.IsSubtraction) { if (NumberStack.Count < 2) { throw new ArgumentException("Invalid Syntax"); } OperationStack.Pop(); var number1 = NumberStack.Pop(); var number2 = NumberStack.Pop(); NumberStack.Push(topOperation.Apply(number2, number1)); } } } OperationStack.Push(operation); } else if (operation.IsMultiplication || operation.IsDivision || operation.IsOpenBrace) { // Nothing complex, just push operation to stack // OperationStack.Push(operation); } else if (operation.IsClosingBrace) { if (!OperationStack.IsEmpty()) { // If there's already a pending operation. // var topOperation = OperationStack.Peek(); if (topOperation.IsAddition || topOperation.IsSubtraction) { if (NumberStack.Count < 2) { throw new ArgumentException("Invalid Syntax"); } OperationStack.Pop(); var number1 = NumberStack.Pop(); var number2 = NumberStack.Pop(); NumberStack.Push(topOperation.Apply(number2, number1)); } } // Check for ending parenthesis // if (OperationStack.IsEmpty() || !OperationStack.Pop().IsOpenBrace) { throw new ArgumentException("Expecting '('. Invalid syntax."); } // Operation size could have changed, we need to check again // if (!OperationStack.IsEmpty()) { var topOperation = OperationStack.Peek(); if (topOperation.IsDivision || topOperation.IsMultiplication) { if (NumberStack.Count < 1) { throw new ArgumentException("Invalid Syntax"); } OperationStack.Pop(); // Passed our test, remove from stack // var b = NumberStack.Pop(); if (!possibleNumber.HasValue) { possibleNumber = NumberStack.Pop(); } NumberStack.Push(topOperation.Apply(possibleNumber.Value, b)); } } } else { throw new ArgumentException("Invalid Syntax. Cannot handle given operation."); } } } if (OperationStack.Count >= 2) { throw new ArgumentException("Invalid Syntax. Cannot handle given operation."); } if (OperationStack.Count == 1) { var b = NumberStack.Pop(); var a = NumberStack.Pop(); return((int)OperationStack.Pop().Apply(a, b)); } else { return((int)NumberStack.Pop()); } }
/// <summary> /// Inserts a token to the left of the cursor, and moves the cursor accordingly. /// </summary> /// <param name="token">The token to insert.</param> public void Insert(Token token) { token.RecalculateDimensions(this); Expression.Insert(Index, token); Expression defaultExpression = token.DefaultChild; if (defaultExpression == null) // if the token has no default child expression... { Index += 1; // skip over the token } else // otherwise... { if (token is ICollectorToken) { ICollectorToken collectorToken = token as ICollectorToken; int newIndex = Index + 1, addedTokens = 0; for (int i = Index - 1; i >= 0; i--) { Token collectedToken = Expression[i]; if (collectedToken is OperationToken) { OperationToken opCollectedToken = collectedToken as OperationToken; if (opCollectedToken.Operation == OperationToken.OperationType.Add || opCollectedToken.Operation == OperationToken.OperationType.Subtract || collectorToken.CollectorType == CollectorTokenType.Weak) { break; } } if (collectedToken is SymbolicToken && (collectedToken as SymbolicToken).Type == SymbolicToken.SymbolicType.Equals) { break; } collectedToken.Parent = defaultExpression; defaultExpression.Insert(0, collectedToken); Expression.RemoveAt(i); newIndex--; addedTokens++; if (collectorToken.CollectorType == CollectorTokenType.Weak && collectedToken is IParsable) { break; // weak collection stops as soon as possible } } if (addedTokens > 0) { // if we automatically collect tokens into the new token, we don't want to then move // the expression cursor into the pre-filled child expression, so find the next empty // child expression after the default child expression and move to that instead if (defaultExpression.IndexInParent() != defaultExpression.Parent.Children.Length - 1) { Expression nextDefaultExpression = defaultExpression.Parent.Children[defaultExpression.IndexInParent() + 1]; if (nextDefaultExpression.Count == 0) { Expression = nextDefaultExpression; } else { Index = newIndex; } } else { Index = newIndex; } } else { Expression = defaultExpression; } } else { Expression = defaultExpression; } } OnMoved(); }
/// <summary> /// Creates an expression object from <see cref="OperationToken"/>. /// </summary> /// <param name="token">The operation token.</param> /// <returns>An expression.</returns> protected virtual IExpression CreateOperation(OperationToken token) { switch (token.Operation) { case Operations.Addition: return(new Add()); case Operations.Subtraction: return(new Sub()); case Operations.Multiplication: return(new Mul()); case Operations.Division: return(new Div()); case Operations.Exponentiation: return(new Pow()); case Operations.UnaryMinus: return(new UnaryMinus()); case Operations.Factorial: return(new Fact()); case Operations.Modulo: return(new Mod()); case Operations.Assign: return(new Define()); case Operations.ConditionalAnd: return(new Expressions.Programming.And()); case Operations.ConditionalOr: return(new Expressions.Programming.Or()); case Operations.Equal: return(new Equal()); case Operations.NotEqual: return(new NotEqual()); case Operations.LessThan: return(new LessThan()); case Operations.LessOrEqual: return(new LessOrEqual()); case Operations.GreaterThan: return(new GreaterThan()); case Operations.GreaterOrEqual: return(new GreaterOrEqual()); case Operations.AddAssign: return(new AddAssign()); case Operations.SubAssign: return(new SubAssign()); case Operations.MulAssign: return(new MulAssign()); case Operations.DivAssign: return(new DivAssign()); case Operations.Increment: return(new Inc()); case Operations.Decrement: return(new Dec()); case Operations.Not: return(new Not()); case Operations.And: return(new Expressions.LogicalAndBitwise.And()); case Operations.Or: return(new Expressions.LogicalAndBitwise.Or()); case Operations.XOr: return(new XOr()); case Operations.Implication: return(new Implication()); case Operations.Equality: return(new Equality()); case Operations.NOr: return(new NOr()); case Operations.NAnd: return(new NAnd()); default: return(null); } }
async public Task LoginImplementation(string username, string password) { if (!progressBar.IsOperationStarted) {//we should perform login showProgress(true); IsLogining = true; var btnLogin = (ApplicationBarIconButton)ApplicationBar.Buttons[0]; btnLogin.IsEnabled = true; ApplicationState.Current = null; progressBar.ShowProgress(true, ApplicationStrings.Login_ProgressAuthentication); try { currentOperation = new OperationToken(); var sessionData = await BAService.LoginAsync(txtUserName.Text, password.ToSHA1Hash()); if (sessionData == null) { Settings.UserName = null; Settings.Password = null; IsLogining = false; showProgress(false); BAMessageBox.ShowError(ApplicationStrings.ErrUserOrPasswordNotValid); return; } if (currentOperation != null && currentOperation.Cancelled) { IsLogining = false; return; } progressBar.ShowProgress(true, ApplicationStrings.Login_ProgressRetrieveProfile); btnLogin.IsEnabled = true; if (Settings.LiveTileEnabled && Settings.InitialAsk) { try { pushNotification.RegisterDevice(sessionData.Profile.GlobalId); } catch { } } var state = ApplicationState.LoadState(); if (state == null) { state = new ApplicationState(); } else if (state.TempUserName != username) { //if we log as a different user, we should't use cache ApplicationState.ClearOffline(); state = new ApplicationState(); } state.IsOffline = false; ApplicationState.Current = state; ApplicationState.Current.SessionData = sessionData; ApplicationState.Current.TempUserName = username; ApplicationState.Current.TempPassword = password.ToSHA1Hash(); ApplicationState.Current.SessionData.Token.Language = ApplicationState.CurrentServiceLanguage; Settings.UserName = username; Settings.Password = password; try { await getProfileInformation(); } catch (Exception) { showProgress(false); IsLogining = false; BAMessageBox.ShowError(ApplicationStrings.ErrCantRetrieveProfileInfo); } } //catch (NetworkException) //{ // IsLogining = false; // showProgress(false); // BAMessageBox.ShowError(ApplicationStrings.ErrNoNetwork); //} catch (DatabaseVersionException) { IsLogining = false; showProgress(false); BAMessageBox.ShowError(ApplicationStrings.ErrOldApplicationVersion); } catch (Exception ex) { showProgress(false); IsLogining = false; goToOffline(true); } } else { if (currentOperation != null) { currentOperation.Cancel(); currentOperation = null; } showProgress(false); } }
/// <summary> /// Evaluate a string based expression. /// </summary> /// <param name="tokenEnumeration">The expression to evaluate</param> /// <param name="variableLookup">A delegate that should return the value of the variable specified.</param> /// <returns>An evaluated expression</returns> public static double Evaluate(IEnumerable <string> tokenEnumeration, Func <string, double> variableLookup) { try { var tokens = tokenEnumeration.ToArray(); var operationStack = new Stack <OperationToken>(); var numberStack = new Stack <double>(); // Will either be a 1 or -1 int?sign = null; for (var i = 0; i < tokens.Length; i++) { var token = tokens[i]; var possibleNumber = GetNumberOrNothing(token); var operation = new OperationToken { Operation = token[0] }; if (!operation.IsValid && !possibleNumber.HasValue) { // Is a variable // possibleNumber = variableLookup(token); } // Handle negatives and positives // if (sign.HasValue) { possibleNumber = possibleNumber * sign; sign = null; } if (possibleNumber.HasValue) { // Is number // if (!operationStack.IsEmpty()) { var topOperation = operationStack.Peek(); if (topOperation.IsDivision || topOperation.IsMultiplication) { if (numberStack.Count < 1) { throw new ArgumentException("Invalid Syntax"); } operationStack.Pop(); // Passed our test, remove from stack // var number = numberStack.Pop(); numberStack.Push(topOperation.Apply(number, possibleNumber.Value)); continue; } } numberStack.Push(possibleNumber.Value); } else { if (operation.IsAddition || operation.IsSubtraction) { var previousIndex = i - 1; if (previousIndex < 0) { // The sign provided was the first sign, it must be a + or - signifying that its positive or negative // sign = operation.IsSubtraction ? -1 : 1; continue; } var previousOperation = new OperationToken() { Operation = tokens[previousIndex][0] }; // If the previous token was an operation then this token must mean positive or negative // // Also make sure its not the last operation either // if (previousOperation.IsOperation && i + 1 < tokens.Length) { sign = operation.IsSubtraction ? -1 : 1; continue; } if (!operationStack.IsEmpty()) { // There's a pending operation, let's do that instead // var topOperation = operationStack.Peek(); if (topOperation.IsAddition || topOperation.IsSubtraction) { if (numberStack.Count < 2) { throw new ArgumentException("Invalid Syntax"); } operationStack.Pop(); var number1 = numberStack.Pop(); var number2 = numberStack.Pop(); numberStack.Push(topOperation.Apply(number2, number1)); } } operationStack.Push(operation); } else if (operation.IsMultiplication || operation.IsDivision || operation.IsOpenBrace) { // Nothing complex, just push operation to stack // operationStack.Push(operation); } else if (operation.IsClosingBrace) { if (!operationStack.IsEmpty()) { // If there's already a pending operation. // var topOperation = operationStack.Peek(); if (topOperation.IsAddition || topOperation.IsSubtraction) { if (numberStack.Count < 2) { throw new ArgumentException("Invalid Syntax"); } operationStack.Pop(); var number1 = numberStack.Pop(); var number2 = numberStack.Pop(); numberStack.Push(topOperation.Apply(number2, number1)); } } // Check for ending parenthesis // if (operationStack.IsEmpty() || !operationStack.Pop().IsOpenBrace) { throw new ArgumentException("Expecting '('. Invalid syntax."); } // Operation size could have changed, we need to check again // if (!operationStack.IsEmpty()) { var topOperation = operationStack.Peek(); if (topOperation.IsDivision || topOperation.IsMultiplication) { if (numberStack.Count < 1) { throw new ArgumentException("Invalid Syntax"); } operationStack.Pop(); // Passed our test, remove from stack // var b = numberStack.Pop(); possibleNumber = numberStack.Pop(); numberStack.Push(topOperation.Apply(possibleNumber.Value, b)); } } } else { throw new ArgumentException("Invalid Syntax. Cannot handle given operation."); } } } if (operationStack.Count >= 2) { throw new ArgumentException("Invalid Syntax. Cannot handle given operation."); } if (operationStack.Count == 1) { var b = numberStack.Pop(); var a = numberStack.Pop(); return(operationStack.Pop().Apply(a, b)); } return(numberStack.Pop()); } catch (Exception e) { if (e is DivideByZeroException) { throw e; // Re-throw } throw new ArgumentException(e.Message); } }
protected void VisitOperation(BinaryExpression expression) { var operation = new OperationToken(expression, Mapper); Query.Append(operation.Value); }
async private Task getProfileInformation() { currentOperation = new OperationToken(); var profileInfo = await BAService.GetProfileInformationAsync(new GetProfileInformationCriteria()); if (currentOperation != null && currentOperation.Cancelled) { showProgress(false); IsLogining = false; return; } ApplicationState.Current.ProfileInfo = profileInfo; ApplicationState.Current.Cache.Reminders.EnsureReminders(); ApplicationState.Current.ProfileInfo.FavoriteUsers.Sort (delegate(UserSearchDTO u1, UserSearchDTO u2) { return(u1.UserName.CompareTo(u2.UserName)); }); ApplicationState.Current.ProfileInfo.Friends.Sort( delegate(UserSearchDTO u1, UserSearchDTO u2) { return(u1.UserName.CompareTo(u2.UserName)); }); if (ApplicationState.Current.MyDays == null) { ApplicationState.Current.MyDays = new Dictionary <CacheKey, TrainingDaysHolder>(); } ApplicationState.Current.Cache.ClearAfterLogin(); ApplicationState.Current.CurrentBrowsingTrainingDays = null; ApplicationState.Current.ClearTrainingDays(); showProgress(false, false); IsLogining = false; onLoggingChanged(); //var m = new ServiceManager<GetProfileInformationCompletedEventArgs>(delegate(BodyArchitectAccessServiceClient client1, EventHandler<GetProfileInformationCompletedEventArgs> operationCompleted) //{ // currentOperation = new OperationToken(); // client1.GetProfileInformationAsync(ApplicationState.Current.SessionData.Token, new GetProfileInformationCriteria()); // client1.GetProfileInformationCompleted -= operationCompleted; // client1.GetProfileInformationCompleted += operationCompleted; //}); //m.OperationCompleted += (s, a1) => //{ // if (a1.Error !=null) // { // showProgress(false); // IsLogining=false; // BAMessageBox.ShowError(ApplicationStrings.ErrCantRetrieveProfileInfo); // return; // } // OperationToken op1 =(OperationToken)a.UserState; // if (op1 !=null && op1.Cancelled) // { // showProgress(false); // IsLogining=false; // return; // } // else if (a1.Result != null) // { // //if (Settings.RefreshFrequencyDays == 0) // //{ // // //in trial/free mode we retrieve exercises and the rest stuff in every login // // ApplicationState.Current.Cache.Clear(); // //} // ApplicationState.Current.ProfileInfo = a1.Result.Result; // ApplicationState.Current.Cache.Reminders.EnsureReminders(); // ApplicationState.Current.ProfileInfo.FavoriteUsers.Sort // (delegate(UserSearchDTO u1, UserSearchDTO u2) // { // return u1.UserName.CompareTo(u2.UserName); // }); // ApplicationState.Current.ProfileInfo.Friends.Sort( // delegate(UserSearchDTO u1, UserSearchDTO u2) // { // return u1.UserName.CompareTo(u2.UserName); // }); // if (ApplicationState.Current.MyDays == null) // { // //ApplicationState.Current.MyDays=new TrainingDaysHolder(ApplicationState.Current.SessionData.Profile); // ApplicationState.Current.MyDays =new Dictionary<CacheKey, TrainingDaysHolder>(); // } // ApplicationState.Current.Cache.ClearAfterLogin(); // ApplicationState.Current.CurrentBrowsingTrainingDays = // null; // ApplicationState.Current.ClearTrainingDays(); // showProgress(false, false); // IsLogining = false; // onLoggingChanged(); // } //}; //if (!m.Run(true)) //{ // IsLogining = false; // showProgress(false); // if (ApplicationState.Current.IsOffline) // { // BAMessageBox.ShowError(ApplicationStrings.ErrOfflineMode); // } // else // { // BAMessageBox.ShowError(ApplicationStrings.ErrNoNetwork); // } //} }
public void ToStringTest() { var token = new OperationToken(Operations.Multiplication); Assert.Equal("Operation: Multiplication", token.ToString()); }
/// <summary> /// Creates an expression object from <see cref="OperationToken"/>. /// </summary> /// <param name="token">The operation token.</param> /// <param name="arguments">The list of arguments.</param> /// <returns>An expression.</returns> protected virtual IExpression CreateOperation(OperationToken token, IEnumerable <IExpression> arguments) { var args = arguments.ToList(); switch (token.Operation) { case Operations.Addition: return(new Add(GetSecondArgument(args), GetArgument(args))); case Operations.Subtraction: return(new Sub(GetSecondArgument(args), GetArgument(args))); case Operations.Multiplication: return(new Mul(GetSecondArgument(args), GetArgument(args))); case Operations.Division: return(new Div(GetSecondArgument(args), GetArgument(args))); case Operations.Exponentiation: return(new Pow(GetSecondArgument(args), GetArgument(args))); case Operations.UnaryMinus: return(new UnaryMinus(GetArgument(args))); case Operations.Factorial: return(new Fact(GetArgument(args))); case Operations.Modulo: return(new Mod(GetSecondArgument(args), GetArgument(args))); case Operations.Assign: return(new Define(GetSecondArgument(args), GetArgument(args))); case Operations.ConditionalAnd: return(new Expressions.Programming.And(GetSecondArgument(args), GetArgument(args))); case Operations.ConditionalOr: return(new Expressions.Programming.Or(GetSecondArgument(args), GetArgument(args))); case Operations.Equal: return(new Equal(GetSecondArgument(args), GetArgument(args))); case Operations.NotEqual: return(new NotEqual(GetSecondArgument(args), GetArgument(args))); case Operations.LessThan: return(new LessThan(GetSecondArgument(args), GetArgument(args))); case Operations.LessOrEqual: return(new LessOrEqual(GetSecondArgument(args), GetArgument(args))); case Operations.GreaterThan: return(new GreaterThan(GetSecondArgument(args), GetArgument(args))); case Operations.GreaterOrEqual: return(new GreaterOrEqual(GetSecondArgument(args), GetArgument(args))); case Operations.AddAssign: return(new AddAssign(GetSecondArgument(args), GetArgument(args))); case Operations.SubAssign: return(new SubAssign(GetSecondArgument(args), GetArgument(args))); case Operations.MulAssign: return(new MulAssign(GetSecondArgument(args), GetArgument(args))); case Operations.DivAssign: return(new DivAssign(GetSecondArgument(args), GetArgument(args))); case Operations.Increment: return(new Inc(GetArgument(args))); case Operations.Decrement: return(new Dec(GetArgument(args))); case Operations.Not: return(new Not(GetArgument(args))); case Operations.And: return(new Expressions.LogicalAndBitwise.And(GetSecondArgument(args), GetArgument(args))); case Operations.Or: return(new Expressions.LogicalAndBitwise.Or(GetSecondArgument(args), GetArgument(args))); case Operations.XOr: return(new XOr(GetSecondArgument(args), GetArgument(args))); case Operations.Implication: return(new Implication(GetSecondArgument(args), GetArgument(args))); case Operations.Equality: return(new Equality(GetSecondArgument(args), GetArgument(args))); case Operations.NOr: return(new NOr(GetSecondArgument(args), GetArgument(args))); case Operations.NAnd: return(new NAnd(GetSecondArgument(args), GetArgument(args))); default: return(null); } }
public static double Caclulate(IEnumerable <IToken> form, double x, double y, double p, double p2) { double res = 0; Stack <double> values = new Stack <double>(); double first = 0, second = 0; foreach (var token in form) { if (token is VariableToken) { using (VariableToken otoken = token as VariableToken) { switch (otoken.Var) { case "x": values.Push(x); break; case "y": values.Push(y); break; case "e": values.Push(Math.E); break; case "pi": values.Push(Math.PI); break; } } } else if (token is ValueToken) { values.Push((token as ValueToken).Number); } else if (token is OperationToken && values.Count > 1) { using (OperationToken otoken = token as OperationToken) { switch (otoken.Operation) { case Operations.Add: first = values.Pop(); second = values.Pop(); values.Push(first + second); break; case Operations.Mul: first = values.Pop(); second = values.Pop(); values.Push(first * second); break; case Operations.Sub: first = values.Pop(); second = values.Pop(); values.Push(first - second); break; case Operations.Div: first = values.Pop(); second = values.Pop(); values.Push(first / second); break; } } } else if (token is FunctionToken && values.Count > 0) { using (FunctionToken otoken = token as FunctionToken) { switch (otoken.Function) { case Functions.Sin: first = values.Pop(); values.Push(Math.Sin(first)); break; case Functions.Cos: first = values.Pop(); values.Push(Math.Cos(first)); break; case Functions.Asin: first = values.Pop(); values.Push(Math.Asin(first)); break; case Functions.Tg: first = values.Pop(); values.Push(Math.Tan(first)); break; case Functions.Sh: first = values.Pop(); values.Push(Math.Sinh(first)); break; case Functions.Ch: first = values.Pop(); values.Push(Math.Cosh(first)); break; case Functions.Sqrt: first = values.Pop(); values.Push(Math.Sqrt(first)); break; } } } } if (values.Count == 1) { return(values.Pop()); } return(0); }