Ejemplo n.º 1
0
        private void Culculate()
        {
            if (isShowResult)
            {
                SubTable.Text = Table.Text;
                return;
            }

            if (number1_ == null)
            {
                number1_      = double.Parse(Table.Text);
                SubTable.Text = number1_.ToString();
                Table.Text    = number1_.ToString();
                isShowResult  = true;
            }
            else if (number2_ == null)
            {
                number2_ = double.Parse(Table.Text);
                try
                {
                    number1_ = calculate_.Calculate(number1_.Value, number2_.Value);
                }
                catch (DivideByZeroException ex)
                {
                    MessageBox.Show("Делть на 0 нельзя!", "Ошбка!");

                    ButtonClearC_Click(null, null);
                    return;
                }
                SubTable.Text = number1_.ToString();
                Table.Text    = number1_.ToString();
                isShowResult  = true;
                number2_      = null;
            }
        }
Ejemplo n.º 2
0
        static void MainOLD()
        {
            Console.WriteLine("Enter first number");
            string input = Console.ReadLine();
            double number1, number2;
            bool   result = Double.TryParse(input, out number1);

            if (!result)
            {
                Console.WriteLine("Please enter a number");
                return;
            }

            Console.WriteLine("Enter second number");
            result = Double.TryParse(Console.ReadLine(), out number2);
            if (!result)
            {
                Console.WriteLine("Please enter a number");
                return;
            }

            Console.WriteLine("Enter add, subtract or divide bitch");
            CalculateFactory factory = new CalculateFactory();
            ICalculate       objectA = factory.GetCalculation(Console.ReadLine());

            // Divide objectA = new Divide();
            objectA.Calculate(number1, number2);
            MainOLD();
        }
Ejemplo n.º 3
0
        private decimal AddNewCellOrCalculateNewValue(ExpressionHandler.ExpressionType type,
                                                      decimal leftNum, decimal rightNum, string leftOperand)
        {
            var leftNumIsInList = leftNum != 0m;

            switch (type)
            {
            case ExpressionHandler.ExpressionType.AddExpression when leftNumIsInList:
                return(_calculateAdd.Calculate(leftNum, rightNum));

            case ExpressionHandler.ExpressionType.AddExpression:
                Register.Instance.MyRegister.Add(new Cell(leftOperand, rightNum));
                break;

            case ExpressionHandler.ExpressionType.SubExpression when leftNumIsInList:
                return(_calculateSub.Calculate(leftNum, rightNum));

            case ExpressionHandler.ExpressionType.SubExpression:
                Register.Instance.MyRegister.Add(new Cell(leftOperand, -rightNum));
                break;

            case ExpressionHandler.ExpressionType.MulExpression when leftNumIsInList:
                return(_calculateMul.Calculate(leftNum, rightNum));

            case ExpressionHandler.ExpressionType.MulExpression:
                Register.Instance.MyRegister.Add(new Cell(leftOperand, 0));
                break;
            }

            return(0m);
        }
Ejemplo n.º 4
0
        static void Main()
        {
            Console.WriteLine("Write a number");
            var input = Console.ReadLine();

            double num1, num2;
            var    result = Double.TryParse(input, out num1);

            if (!result)
            {
                Console.WriteLine("Error, write a number");
                return;
            }


            Console.WriteLine("Write another number");
            result = Double.TryParse(Console.ReadLine(), out num2);
            if (!result)
            {
                Console.WriteLine("error, write a number");
                return;
            }

            Console.WriteLine("Type +, / or -");
            CalculateFactory calculateFactory = new CalculateFactory();
            ICalculate       obj = calculateFactory.GetCalculation(Console.ReadLine());

            obj.Calculate(num1, num2);
            Main();
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the first number");
            string input = Console.ReadLine();

            Console.WriteLine("Enter the second number");
            string input1 = Console.ReadLine();
            double a, b;
            bool   result = Double.TryParse(input, out a);

            if (!result)
            {
                Console.WriteLine("Please enter the  number");
                input1 = Console.ReadLine();
                return;
            }
            bool result1 = Double.TryParse(input1, out b);

            if (!result1)
            {
                Console.WriteLine("Please Enter the number");
                return;
            }
            Console.WriteLine("Please Enter 1 for Addition 2 for Subtraction");
            CalculateFactory calculateFactory = new CalculateFactory();
            ICalculate       obj = calculateFactory.GetCalculations(Console.ReadLine());

            if (obj != null)
            {
                obj.Calculate(a, b);
            }
        }
Ejemplo n.º 6
0
 private void Culculate()
 {
     if (_isShowResult)
     {
         return;
     }
     if (_number1 == null)
     {
         _number1      = double.Parse(Table.Text);
         Table.Text    = _number1.ToString();
         _isShowResult = true;
     }
     else if (_number2 == null)
     {
         _number2 = double.Parse(Table.Text);
         try
         {
             _number1 = _calculate.Calculate(_number1.Value, _number2.Value);
         }
         catch (DivideByZeroException ex)
         {
             MessageBox.Show("Делить на 0 нельзя!", "Ошибка!");
             ButtonClearC_Click(null, null);
             return;
         }
         Table.Text    = _number1.ToString();
         _isShowResult = true;
         _number2      = null;
     }
 }
Ejemplo n.º 7
0
    protected void When_CalculateBtn_Clicked(object sender, EventArgs e)
    {
        try
        {
            //get operands
            int operandX = Convert.ToInt32(Entry_OperandX.Text);
            int operandY = Convert.ToInt32(Entry_OperandY.Text);

            //get operator
            string oper = ComboBox_Operators.ActiveText;

            //produce suitable object depends on oper
            ICalculate cal = Factory.ProduceCalculateTool(oper);

            //calculate
            int result = cal.Calculate(operandX, operandY);

            //show result
            Label_Result.Text = string.Format("Result          : {0}", result.ToString());
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
        public List<Customer> GetRequiredCustomers(ICalculate calc,List<Customer> customers)
        {
            List<Customer> customersAround = new List<Customer> { };
            const double intercomLatitude = 53.3381985;
            const double intercomeLongitude = -6.2592576;
            // loop throught the customers list and return those are within 100km from the Intercom office
            for (int i = 0; i < customers.Count; i++)
            {
                if (calc.Calculate(customers[i].Latitude, customers[i].Longitude, intercomLatitude, intercomeLongitude) < 100 && calc.Calculate(customers[i].Latitude, customers[i].Longitude, intercomLatitude, intercomeLongitude) != 0.0)
                {
                    customersAround.Add(customers[i] as Customer);
                }
            }
            customersAround = customersAround.OrderBy(c => c.ID).ToList(); //order the list by ID

            return customersAround;
        }
Ejemplo n.º 9
0
        static void Main()
        {
            Console.WriteLine("Factory");
            //------------------------------Factory Pattern
            Console.WriteLine("Enter Add, subtract or divide");

            CalculateFactory factory = new CalculateFactory();
            ICalculate       obj     = factory.GetCalculation(Console.ReadLine());

            obj.Calculate(10, 10);

            Console.WriteLine("Singleton");
            //------------------------------Singleton
            Logger ob1 = Logger.Instance;

            Logger ob2 = Logger.Instance;

            Console.WriteLine(ob1.GetHashCode());
            Console.WriteLine(ob2.GetHashCode());

            Console.WriteLine("TemplateMethod");
            //------------------------------TemplateMethod
            ExcelFile objExcel = new ExcelFile();

            objExcel.ReadProcessAndSave();

            TextFile objText = new TextFile();

            objText.ReadProcessAndSave();

            Console.WriteLine("Adapter");
            //------------------------------Adapter
            Adaptee adaptee = new Adaptee();
            ITarget target  = new Adapter(adaptee);

            target.GetRequest();


            Console.WriteLine("Facade");
            //------------------------------Facade
            var searchEngineFacade = new SearchEngineFacade();
            var searchingResults   = searchEngineFacade.GetSearchResults("My query");

            Console.WriteLine(searchingResults);

            Console.WriteLine("StrategyPattern");
            //------------------------------Strategy

            StrategyContext context;

            context = new StrategyContext(new ConcreteStrategyA());
            context.ContextInterface();
            context = new StrategyContext(new ConcreteStrategyB());
            context.ContextInterface();
            context = new StrategyContext(new ConcreteStrategyC());
            context.ContextInterface();
        }
Ejemplo n.º 10
0
        private void Operations(object sender, EventArgs e)
        {
            double     first  = Convert.ToDouble(textBox1.Text);
            double     second = Convert.ToDouble(textBox2.Text);
            ICalculate Calc   = CalculatorFactory.CreateCalcuator(((Button)sender).Name);
            double     result = Calc.Calculate(first, second);

            textBox3.Text = result.ToString();
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            var(a, b) = GetNumbers();
            string operatorSymbol = GetOperatorSymbol();

            CalculateFactory calculateFactory = new CalculateFactory();
            ICalculate       calculate        = calculateFactory.GetCalculation(operatorSymbol);

            calculate.Calculate(a, b);
        }
Ejemplo n.º 12
0
 public override double Interpret(ICalculate <double> calculator)
 {
     if (calculator.CalculatedType == CalculatableTypes.OriginalGravity)
     {
         var originalValue = calculator.Calculate();
         return(((182.4601 * originalValue - 775.6821) * originalValue + 1262.7794) * originalValue - 669.5622);
     }
     else
     {
         throw new InvalidOperationException("Calculator must have CalculatedType of OriginalGravity to be valid!");
     }
 }
Ejemplo n.º 13
0
 public override double Interpret(ICalculate <double> calculator)
 {
     if (calculator.CalculatedType == CalculatableTypes.OriginalGravity)
     {
         var originalValue = calculator.Calculate();
         return((-1 * 616.868) + (1111.14 * originalValue) - (630.272 * (originalValue * originalValue)) + (135.997 * (originalValue * originalValue * originalValue)));
     }
     else
     {
         throw new InvalidOperationException("Calculator must have CalculatedType of OriginalGravity to be valid!");
     }
 }
Ejemplo n.º 14
0
        private static void DemoFactory()
        {
            CalculateFactory factory = new CalculateFactory();

            Console.WriteLine("Enter 2 numbers:");
            var a = Convert.ToDouble(Console.ReadLine());
            var b = Convert.ToDouble(Console.ReadLine());

            Console.WriteLine("Enter operation (add/subtract/devide):");
            ICalculate obj = factory.GetCalculate(Console.ReadLine());

            obj.Calculate(a, b);
        }
Ejemplo n.º 15
0
        public void TestMultiAdd()
        {
            // Arrange
            var           creator   = new CalculationFactory();
            ICalculate    calculate = creator.FactoryMethod(CalculationCreator.OperationType.BigSum);
            List <string> mylist    = new List <string>(new string[] { "121556550", "15589455452", "2254564555565552", "5554525455454554565" });

            // Act
            string multiResult = calculate.Calculate(mylist);

            // Assert
            Assert.AreEqual(multiResult, "5556780035721132119");
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter First Number");
            int first = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Enter Second Number");
            int second = Convert.ToInt32(Console.ReadLine());

            CalculateFactory calcfac = new CalculateFactory();
            ICalculate       obj     = calcfac.execute();

            obj.Calculate(first, second);
            Console.ReadLine();
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            Console.Write("Enter first number ==> ");
            double n1 = Convert.ToDouble(Console.ReadLine());

            Console.Write("Enter second number ==> ");
            double           n2      = Convert.ToDouble(Console.ReadLine());
            CalculateFactory factory = new CalculateFactory();

            Console.Write("Enter add subtract or divide ==> ");
            string     type      = Console.ReadLine();
            ICalculate calculate = factory.GetCalculation(type);

            Console.WriteLine(type + " is " + calculate.Calculate(n1, n2));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// The proxy implements the Calculate method by this strategy:
        /// 1) Given the Coordinate c, try to look up a result in the Cache,
        ///    by using the _cache instance field.
        /// 2) If a result was found in the cache, return it immediately to the caller.
        /// 3) If a result was NOT found in the cache, then
        ///    3a) Calculate the result, using the _calculator instance field.
        ///    3b) Store the returned result in the cache.
        ///    3c) Return the calculated result to the caller.
        /// </summary>
        public int Calculate(Coordinate c)
        {
            int cachedValue = _cache.Lookup(c);

            if (cachedValue != Cache.NoValue)
            {
                return(cachedValue);
            }
            else
            {
                int calculatedValue = _calculator.Calculate(c);
                _cache.Insert(c, calculatedValue);
                return(calculatedValue);
            }
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            //test
            Console.WriteLine("***BigNumberStrategy***");
            Console.WriteLine("Please input the count of your numbers");
            byte          countNum  = Convert.ToByte(Console.ReadLine());
            List <string> numHolder = new List <string>();

            for (int i = 0; i < countNum; i++)
            {
                Console.WriteLine($"Number {i}:");
                numHolder.Add(Console.ReadLine());
            }

            Console.WriteLine("Please Choose your operation:");
            Console.WriteLine("1: +\n2: *\n3:-");
            string opt = Console.ReadLine();

            // **** First method: using factory method: ****

            var creator = new CalculationFactory();

            ICalculate calculate = creator.FactoryMethod(CalculationCreator.OperationType.BigSum);

            string result = calculate.Calculate(numHolder);

            Console.WriteLine($"Result of Factory method is: {result}");

            // *********************************************

            // **** Second method: using Strategy method ****

            StandardKernel kernel = new StandardKernel();

            // Load Modules
            kernel.Load(Assembly.GetExecutingAssembly());

            // Gets a instance of the specified service.
            SumStrategy      objCalculate  = kernel.Get <SumStrategy>();      //"Sum"
            MultipleStrategy objCalculate2 = kernel.Get <MultipleStrategy>(); // "Multiple"

            // Inject
            CalculatorContext calculatorContext = new CalculatorContext(objCalculate, objCalculate2);

            // Call method of context
            Console.WriteLine($"Result of Strategy method is: {calculatorContext.Sum(numHolder)}");
            //Console.WriteLine(calculatorContext.Multiple(numHolder));
        }
        private void FactchResult(object sender, FetchResultEventArgs signpassed)
        {
            try
            {
                if (FetchResult != null)
                {
                    Regex re       = new Regex(@"(?:[0-9]+)");
                    var   SignList = re.Split(Expression);

                    var Values = Expression.Split('+', '-', '*', '/', '^', '\\', 'r', '%');
                    CalcultedValue = 0;
                    int i = 0;
                    CheckDetail.Clear();
                    CalcultedValue = CalcultedValue == 0 ? Convert.ToDouble(Values[i]) : CalcultedValue;
                    foreach (var item in Values)
                    {
                        double     ValueTwo   = Values.Length > 1 ? Convert.ToDouble(Values[i + 1]) : 0;
                        string     sign       = SignList.Length > 2 ? SignList[i + 1] : signpassed.ToString();
                        ICalculate Operation_ = CalCulationType.CalculationType.OperationType(sign);
                        CalcultedValue = Operation_.Calculate(CalcultedValue, Convert.ToDouble(ValueTwo));
                        //Thread.Sleep(1000);
                        args.OperationName   = Operation_.ToString();
                        args.OperationStatus = $" = {CalcultedValue}";
                        string s = OperationChanged(this, args);
                        //OperationChanged(this, args);

                        if (Values.Length == 2)
                        {
                            break;
                        }
                        i++;
                    }
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                if (!Expression.EndsWith("+") && !Expression.EndsWith("-") && !Expression.EndsWith("*") && !Expression.EndsWith("/") && signpassed.sign != "=")
                {
                    Expression += signpassed.sign;
                }
            }
        }
Ejemplo n.º 21
0
        private (long, long) ExecutionTimer(ICalculate calc, Dictionary <int, NativeArray <int> > map)
        {
            marker.Begin();

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            long elapsed = stopwatch.ElapsedTicks;

            long result = calc.Calculate(map);

            elapsed = stopwatch.ElapsedTicks - elapsed;
            stopwatch.Stop();

            marker.End();

            return(elapsed, result);
        }
Ejemplo n.º 22
0
 private void Calculate(object sender, EventArgs e)
 {
     try
     {
         string     firstValue  = textBox1.Text;
         string     secondValue = textBox2.Text;
         double     first       = Convert.ToDouble(firstValue);
         double     second      = Convert.ToDouble(secondValue);
         double     third;
         ICalculate calculate = Calculaterfactory.CreatCalculator(((Button)sender).Name);
         third    = calculate.Calculate(first, second);
         Rez.Text = third.ToString();
     }
     catch (Exception ex)
     {
         MessageBox.Show("произошла ошибка: " + ex.Message);
     }
 }
Ejemplo n.º 23
0
        public void Calculate()
        {
            Console.WriteLine("Enter num1");
            decimal num1, num2;
            bool    result;

            result = Decimal.TryParse(Console.ReadLine(), out num1);
            Console.WriteLine("Enter num2");
            result = Decimal.TryParse(Console.ReadLine(), out num2);

            CalculateFactory factory = new CalculateFactory();

            Console.WriteLine("Enter operation");
            ICalculate obj    = factory.GetCalculate(Console.ReadLine());
            decimal    output = obj.Calculate(num1, num2);

            Console.WriteLine(output);
        }
Ejemplo n.º 24
0
        static void Main()
        {
            var        provider   = MyContainer.Initialize();
            ICalculate calculator = provider.GetService <ICalculate>();

            while (true)
            {
                string input = Console.ReadLine();

                try
                {
                    Console.WriteLine(calculator.Calculate(input));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
Ejemplo n.º 25
0
        public List <Customer> GetRequiredCustomers(ICalculate calc, List <Customer> customers)
        {
            List <Customer> customersAround = new List <Customer> {
            };
            const double intercomLatitude   = 53.3381985;
            const double intercomeLongitude = -6.2592576;

            // loop throught the customers list and return those are within 100km from the Intercom office
            for (int i = 0; i < customers.Count; i++)
            {
                if (calc.Calculate(customers[i].Latitude, customers[i].Longitude, intercomLatitude, intercomeLongitude) < 100 && calc.Calculate(customers[i].Latitude, customers[i].Longitude, intercomLatitude, intercomeLongitude) != 0.0)
                {
                    customersAround.Add(customers[i] as Customer);
                }
            }
            customersAround = customersAround.OrderBy(c => c.ID).ToList(); //order the list by ID

            return(customersAround);
        }
Ejemplo n.º 26
0
        private static int Main(string[] args)
        { // Test if input arguments were supplied.
            if (args.Length == 0)
            {
                Console.WriteLine("Please provide Values Separated by Comma Below.");
                Console.WriteLine("Usage: 11,22,34534,6456");
                Console.ReadLine();
                return(1);
            }



            if (args.Length == 1)
            {
                _numbers = args[0].Split(separator: new char[] { ',' },
                                         options: StringSplitOptions.RemoveEmptyEntries)
                           .Where(val => int.TryParse(val, out _))
                           .Select(val => int.Parse(val))
                           .ToList();
            }


            Console.WriteLine("Sorted data:");
            _numbers.ForEach(n => Console.Write("{0}\t", n));

            var result  = _iCalculateAvg.Calculate(_numbers);
            var result2 = _iCalculateMax.Calculate(_numbers);

            var success   = 0;
            var failed    = 0;
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            _numbers.Sort();

            UpdateUI(success, failed, result, result2);
            Console.ReadLine();
            return(0);
        }
Ejemplo n.º 27
0
    void Update()
    {
        Stopwatch stopwatch = Stopwatch.StartNew();

        long sum = 0;

        marker3.Begin();

        markerCalculate.Begin();

        long elapsed = stopwatch.ElapsedTicks;

        sum     = calculateMethod1.Calculate(map);
        elapsed = stopwatch.ElapsedTicks - elapsed;

        markerCalculate.End();


        //Debug.Log($"{calculateMethod1.getDescription()} : Sum at Update = {sum}");



        marker3.End();
    }
Ejemplo n.º 28
0
        public void CalculateDefensiveScoring(ICalculate myCalculator, [Optional] bool doOpponent)
        {
            GameList = LoadGamesFrom(myCalculator.StartWeek.Season, myCalculator.StartWeek.Week, myCalculator.Offset);

             PtsFor = 0;
             PtsAgin = 0;
             decimal totFantasyPoints = 0;
             var totDefensiveScores = 0;
             decimal totTotSacks = 0;
             var totTotInterceptions = 0;
             var totGames = 0;
             var totPointsAgin = 0;

             foreach (NFLGame g in GameList)
             {
            #if DEBUG
            Utility.Announce(string.Format("  {0} Opponent in week {1} of {3} is {2}",
               TeamCode, g.Week, g.OpponentTeam(TeamCode).Name, g.Season));
            #endif
            var theTeam = (doOpponent ? g.OpponentTeam(TeamCode) : g.Team(TeamCode));

            myCalculator.Calculate(theTeam, g);

            totFantasyPoints += theTeam.FantasyPoints;
            totDefensiveScores += theTeam.DefensiveScores;
            totTotSacks += theTeam.TotSacks;
            totTotInterceptions += theTeam.TotInterceptions;
            totPointsAgin += theTeam.PtsAgin;
            totGames++;

            #if DEBUG
            if (doOpponent)
               Utility.Announce(
                  string.Format(
                     "    {5} defense against {4} racks up {0,3:##0} Fpts and {1} Defensive Scores {2} Sacks {3} intercepts, scoring {6} points",
                     theTeam.FantasyPoints,
                     theTeam.DefensiveScores,
                     theTeam.TotSacks,
                     theTeam.TotInterceptions,
                     TeamCode,
                     g.OpponentTeam(TeamCode).TeamCode,
                     theTeam.PtsAgin));
            else
               Utility.Announce(
                  string.Format(
                     "    {4} defense against {5} (score {7}) racks up {0,3:##0} Fpts and {1} Defensive Scores {2} Sacks {3} intercepts, allowing {6} points",
                     theTeam.FantasyPoints,
                     theTeam.DefensiveScores,
                     theTeam.TotSacks,
                     theTeam.TotInterceptions,
                     TeamCode,
                     g.OpponentTeam(TeamCode).TeamCode,
                     theTeam.PtsAgin,
                     g.ScoreOut(TeamCode)));
            #endif
             }

             PtsAgin = totPointsAgin;
             FantasyPoints = totFantasyPoints;
             DefensiveScores = totDefensiveScores;
             TotSacks = totTotSacks;
             TotInterceptions = totTotInterceptions;
             Games = totGames;

            #if DEBUG
             if (doOpponent)
            Utility.Announce(
               string.Format(
                  "{0} has allowed defenses to get {1,3:##0} Fpts on {2} Defensive Scores, {3} Sacks and {4} intercepts, scoring {5} points",
                   TeamCode, FantasyPoints, DefensiveScores, TotSacks, TotInterceptions, PtsAgin));
             else
            Utility.Announce(
               string.Format(
                  "{0} defense got {1,3:##0} Fpts on {2} Defensive Scores, {3} Sacks and {4} intercepts, allowing {5} points",
                   TeamCode, FantasyPoints, DefensiveScores, TotSacks, TotInterceptions, PtsAgin));
            #endif
        }