Esempio n. 1
0
        void BindResults(IAsyncResult ar)
        {
            CalcResult result = null;
            string     opcode = (string)ar.AsyncState;

            // Harvest the results
            switch (opcode)
            {
            case "+":
                result = client.EndAdd(ar);
                break;

            case "-":
                result = client.EndSubtract(ar);
                break;

            case "*":
                result = client.EndMultiply(ar);
                break;

            case "/":
                result = client.EndDivide(ar);
                break;
            }

            // Put the results into the data context, causing the
            // bound data to be updated in the TextBlock controls
            this.DataContext = result;
        }
        private CalcResult ExecuteRequest(CalcRequest request)
        {
            CalcResult res = CalcResult.From(double.NaN);

            var sw = Stopwatch.StartNew();

            try
            {
                var client       = new TcpClient(HostIP, Port);
                var clientStream = client.GetStream();
                var bytes        = request.GetBytes();
                clientStream.Write(bytes, 0, bytes.Length);

                var buffer = new byte[client.ReceiveBufferSize];
                clientStream.Read(buffer, 0, client.ReceiveBufferSize);
                res = CalcResult.FromBytes(buffer);
                client.Close();
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Failed to execute request");
            }
            sw.Stop();
            _logger.Info($"Request to {HostIP}:{Port} executed in {sw.ElapsedMilliseconds} ms");

            return(res);
        }
Esempio n. 3
0
        void _equalsButton_Click(object sender, RoutedEventArgs e)
        {
            double operand1 = double.Parse(_operand1.Text);
            double operand2 = double.Parse(_operand2.Text);
            string opcode   = ((TextBlock)_op.SelectedValue).Text;

            // Start the call to the web service asynchronously, calling CalcComplete
            // when each calculation is complete and passing the calc opcode via
            // IAsyncResult.AsyncState so we can know which proxy End method to call
            switch (opcode)
            {
            case "+":
                client.BeginAdd(operand1, operand2, CalcComplete, opcode);
                break;

            case "-":
                client.BeginSubtract(operand1, operand2, CalcComplete, opcode);
                break;

            case "*":
                client.BeginMultiply(operand1, operand2, CalcComplete, opcode);
                break;

            case "/":
                client.BeginDivide(operand1, operand2, CalcComplete, opcode);
                break;
            }

            // Let the user know by creating a phony calc result object
            // (which the GUI knows how to bind to) and setting the words
            CalcResult progress = new CalcResult();

            progress.Words   = "(getting results)";
            this.DataContext = progress;
        }
Esempio n. 4
0
        public CalcResult <Phonecall, decimal> Calculate(List <ConsumedInfo <Phonecall, decimal> > items)
        {
            var result  = new CalcResult <Phonecall, decimal>();
            var chuncks = items.Chunker(3);

            foreach (var chunck in chuncks)
            {
                var prices = chunck.Select(x => priceCalculator.Calculate(new List <ConsumedInfo <Phonecall, decimal> >()
                {
                    x
                })).ToList();
                if (prices.Count == 3)
                {
                    var  min = prices.Min();
                    bool hasGivenDiscount = false;
                    foreach (var price in prices)
                    {
                        result.Billed.Add(new BillRecord <decimal>()
                        {
                        });
                    }
                }
            }

            return(result);
        }
Esempio n. 5
0
        public static void Operators_Test(ArithmeticOpetation op, int a, int b)
        {
            //arrange
            int expected = a;
            var result   = new CalcResult <int>(a);

            //act
            if (op == ArithmeticOpetation.Add)
            {
                result   += b;
                expected += b;
            }

            if (op == ArithmeticOpetation.Subtract)
            {
                result   -= b;
                expected -= b;
            }

            if (op == ArithmeticOpetation.Multiply)
            {
                result   *= b;
                expected *= b;
            }

            if (op == ArithmeticOpetation.Divide)
            {
                result   /= b;
                expected /= b;
            }

            //assert
            Assert.Equal(expected, result.Value);
        }
Esempio n. 6
0
        public static void ArithmeticOperation_Test2(ArithmeticOpetation op, int a, int b)
        {
            //arrange
            int expected = a;
            var result   = new CalcResult <int>(a);
            var _b       = new CalcResult <int>(b);

            //act
            if (op == ArithmeticOpetation.Add)
            {
                result.Add(_b);
                expected += b;
            }

            if (op == ArithmeticOpetation.Subtract)
            {
                result.Subtract(_b);
                expected -= b;
            }

            if (op == ArithmeticOpetation.Multiply)
            {
                result.Multiply(_b);
                expected *= b;
            }

            if (op == ArithmeticOpetation.Divide)
            {
                result.Divide(_b);
                expected /= b;
            }

            //assert
            Assert.Equal(expected, result.Value);
        }
Esempio n. 7
0
        public static CalcResult ElementCalc(string[] fluid, double[] composition, double dh, double l, double Aa_fin, double Aa_tube, double A_r_cs, double Ar, double tai,
                                             double tri, double pri, double hri, double mr, double g, double ma, double ha,
                                             double eta_surface, double zh, double zdp, int hexType, double thickness, double conductivity, double Pwater)
        {
            double     r_metal = thickness / conductivity / Ar;
            double     gg      = 9.8;
            CalcResult res     = new CalcResult();

            Refrigerant.TPFLSHResult r = new Refrigerant.TPFLSHResult();
            r = Refrigerant.TPFLSH(fluid, composition, tri + 273.15, fluid[0] == "Water" ? Pwater : pri);
            double wm    = Refrigerant.WM(fluid, composition).Wm;
            double mu_r  = Refrigerant.TRNPRP(fluid, composition, tri + 273.15, r.D).Viscosity / Math.Pow(10, 6);
            double k_r   = Refrigerant.TRNPRP(fluid, composition, tri + 273.15, r.D).ThermalConductivity;
            double rho_r = r.D * wm;
            double cp_r  = r.cp / wm * 1000;
            double Pr_r  = cp_r * mu_r / k_r;

            res.Vel_r = g / rho_r;
            double Re_r    = rho_r * res.Vel_r * dh / mu_r;
            double fh      = RefrigerantSPHTC.ff_CHURCHILL(Re_r);
            double Nusselt = RefrigerantSPHTC.NU_GNIELINSKI(Re_r, Pr_r, fh);

            res.href = Nusselt * k_r / dh * zh;
            double cp_a = 1.0;

            cp_a = (hexType == 0 ? 1.027 : 1.02);

            double C_r = mr * cp_r / 1000;
            double C_a = ma * cp_a;

            res.R_1a = 1 / ((eta_surface * Aa_fin + Aa_tube) * ha);
            res.R_1r = 1 / (res.href * Ar);
            res.R_1  = res.R_1a + res.R_1r + r_metal;
            double UA      = 1 / res.R_1;
            double C_min   = Math.Min(C_a, C_r);
            double C_max   = Math.Max(C_a, C_r);
            double C_ratio = C_min / C_max;
            double NTU     = UA / (C_min * 1000);
            double epsilon = 1 - Math.Exp(Math.Pow(C_ratio, -1.0) * Math.Pow(NTU, 0.22)
                                          * (Math.Exp(-C_ratio * Math.Pow(NTU, 0.78)) - 1));

            res.Q = epsilon * C_min * Math.Abs(tri - tai);
            if (C_r < C_a)
            { // hexType=0 :evap, 1:cond
                res.Tro = tri + Math.Pow(-1, hexType) * epsilon * Math.Abs(tai - tri);
                res.Tao = tai + Math.Pow(-1, (hexType + 1)) * C_r * (Math.Abs(res.Tro - tri) / C_a);
            }
            else
            {
                res.Tao = tai + Math.Pow(-1, (hexType + 1)) * epsilon * Math.Abs(tai - tri);
                res.Tro = tri + Math.Pow(-1, hexType) * C_a * (Math.Abs(tai - res.Tao) / C_r);
            }
            double f_sp = RefrigerantSPDP.ff_Friction(Re_r);

            res.DP  = zdp * f_sp * l / dh * Math.Pow(g, 2.0) / rho_r / 2000;
            res.Pro = fluid[0] == "Water" ? pri : pri - res.DP;
            res.hro = hri + Math.Pow(-1, hexType) * res.Q / mr;

            return(res);
        }
Esempio n. 8
0
        void ShowResults(IAsyncResult ar)
        {
            CalcResult result = null;
            string     opcode = (string)ar.AsyncState;

            // Harvest the results
            switch (opcode)
            {
            case "+":
                result = client.EndAdd(ar);
                break;

            case "-":
                result = client.EndSubtract(ar);
                break;

            case "*":
                result = client.EndMultiply(ar);
                break;

            case "/":
                result = client.EndDivide(ar);
                break;
            }

            // Show the results
            _numberTextBlock.Text = result.Number.ToString();
            _wordsTextBlock.Text  = result.Words;
        }
Esempio n. 9
0
        private void 原始数据绘图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmSelectMItem frmSelectMItem = new FrmSelectMItem(this.User);

            frmSelectMItem.StartPosition = FormStartPosition.CenterScreen;
            if (frmSelectMItem.ShowDialog() == DialogResult.OK)
            {
                var dt          = frmSelectMItem.Result;
                var calcResults = new List <CalcResult>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    var id    = Convert.ToInt32(dt.Rows[i]["编号"]);
                    var title = dt.Rows[i]["观测单位"] + "-" + dt.Rows[i]["地名"] + "-" + dt.Rows[i]["方法名"] + "-" +
                                dt.Rows[i]["测项名"] + "-" + "原始数据";
                    var calcResult = new CalcResult();
                    calcResult.Title          = title;
                    calcResult.NumericalTable = DaoObject.GetRawData(id);
                    calcResults.Add(calcResult);
                }
                var frmDisplayCharts = GetChartForm();
                foreach (var calcResult in calcResults)
                {
                    frmDisplayCharts.AddChart(calcResult);
                }
            }
        }
Esempio n. 10
0
        private void FrmExportChartDemo_Load(object sender, EventArgs e)
        {
            var calcResult = new CalcResult();

            calcResult.NumericalTable = DaoObject.GetRawData(17);
            calcResult.Title          = "石景山区玉泉西街1号院";
            var chart = ChartHelper.BuildChart(calcResult);

            chart.Size = new Size(500, 260);
            chart.ChartAreas[0].AxisX.Title = "观测日期";
            chart.ChartAreas[0].AxisY.Title = "观测值";
//            chart.AntiAliasing = AntiAliasingStyles.All;
//            chart.TextAntiAliasingQuality = TextAntiAliasingQuality.High;
            this.Controls.Add(chart);

            var oldChartSize             = chart.Size;
            var oldTitleFont             = chart.Titles[0].Font;
            var oldAxisTitleFont         = chart.ChartAreas[0].AxisX.TitleFont;
            var oldAxisLabelFont         = chart.ChartAreas[0].AxisX.LabelStyle.Font;
            var oldAxisLineWidth         = chart.ChartAreas[0].AxisX.LineWidth;
            var oldAxisTickMarkLineWidth = chart.ChartAreas[0].AxisX.MajorTickMark.LineWidth;
            var oldAxisYIntervals        = chart.ChartAreas[0].AxisY.Interval;
            var oldAxisXIntervals        = chart.ChartAreas[0].AxisX.Interval;
            var oldSeriesBorderWidth     = chart.Series[0].BorderWidth;

            var times = 10;

            chart.Size           = new Size(chart.Width * times, chart.Height * times);
            chart.Titles[0].Font = new Font(oldTitleFont.Name, oldTitleFont.Size * times);
            chart.ChartAreas[0].AxisX.TitleFont               = new Font(oldAxisTitleFont.Name, oldAxisTitleFont.Size * times);
            chart.ChartAreas[0].AxisY.TitleFont               = new Font(oldAxisTitleFont.Name, oldAxisTitleFont.Size * times);
            chart.ChartAreas[0].AxisX.LabelStyle.Font         = new Font(oldAxisLabelFont.Name, oldAxisLabelFont.Size * times);
            chart.ChartAreas[0].AxisY.LabelStyle.Font         = new Font(oldAxisLabelFont.Name, oldAxisLabelFont.Size * times);
            chart.ChartAreas[0].AxisX.LineWidth               = oldAxisLineWidth * times;
            chart.ChartAreas[0].AxisY.LineWidth               = oldAxisLineWidth * times;
            chart.ChartAreas[0].AxisX.MajorTickMark.LineWidth = oldAxisTickMarkLineWidth * times;
            chart.ChartAreas[0].AxisY.MajorTickMark.LineWidth = oldAxisTickMarkLineWidth * times;
            //坐标轴上的Label间距先不调整了
            //chart.ChartAreas[0].AxisX.Interval = oldAxisXIntervals/Math.Round(times/3.0);
            //chart.ChartAreas[0].AxisY.Interval = oldAxisYIntervals/Math.Round(times/3.0);
            chart.Series[0].BorderWidth = oldSeriesBorderWidth * times;
            chart.Invalidate();
            chart.SaveImage(@"C:\1.png", ChartImageFormat.Png);

            chart.Size           = oldChartSize;
            chart.Titles[0].Font = oldTitleFont;
            chart.ChartAreas[0].AxisX.TitleFont               = oldTitleFont;
            chart.ChartAreas[0].AxisY.TitleFont               = oldTitleFont;
            chart.ChartAreas[0].AxisX.LabelStyle.Font         = oldAxisLabelFont;
            chart.ChartAreas[0].AxisY.LabelStyle.Font         = oldAxisLabelFont;
            chart.ChartAreas[0].AxisX.LineWidth               = oldAxisLineWidth;
            chart.ChartAreas[0].AxisY.LineWidth               = oldAxisLineWidth;
            chart.ChartAreas[0].AxisX.MajorTickMark.LineWidth = oldAxisTickMarkLineWidth;
            chart.ChartAreas[0].AxisY.MajorTickMark.LineWidth = oldAxisTickMarkLineWidth;
            chart.ChartAreas[0].AxisX.Interval = oldAxisXIntervals;
            chart.ChartAreas[0].AxisY.Interval = oldAxisYIntervals;
            chart.Series[0].BorderWidth        = oldSeriesBorderWidth;

            chart.Invalidate();
        }
Esempio n. 11
0
        private void CalcExpression_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                EvalArrayPosition = 0;
                eval.Expression   = CalcExpression.Text;
                CalcResult.Text  += "\r\n>> " + CalcExpression.Text;
                EvalArray.Add(CalcExpression.Text);
                CalcExpression.Text = "";
                string ResponsePrefix = "\r\n                ";
                switch (eval.Expression.ToLower())
                {
                case "clear":
                    //EvalArrayPosition = 0b1100;

                    CalcResult.Clear();
                    break;

                case "listvar":
                    foreach (System.Collections.DictionaryEntry a in eval.variables)
                    {
                        CalcResult.Text += (ResponsePrefix + a.Key + "=" + a.Value);
                    }
                    CalcResult.Text += (ResponsePrefix + eval.variables.Count + " variable(s)");
                    break;

                case "help":
                    CalcResult.Text += ResponsePrefix + EvalHelp;
                    break;

                case "longhelp":
                    CalcResult.Text += ResponsePrefix + EvalLongHelp;
                    break;

                case "exit":
                    Application.Exit();
                    break;

                default:
                    try
                    {
                        object result = eval.Evaluate();
                        CalcResult.Text += (ResponsePrefix + result);
                        try
                        {
                            double ans = Convert.ToDouble(result);
                            eval.variables.Remove("ans");
                            eval.variables.Add("ans", ans);
                        }
                        catch (Exception) {};
                    }
                    catch (Exception ex) { CalcResult.Text += (ResponsePrefix + ex.Message); }
                    break;
                }
                e.Handled = true;
            }
            return;
        }
Esempio n. 12
0
 private void PublicResult(CalcResult calcResult)
 {
     if (String.IsNullOrEmpty(calcResult.ErrorMessage))
     {
         TextBoxResult.Text = calcResult.Data.ToString();
     }
     else
     {
         TextBoxResult.Text = calcResult.ErrorMessage;
     }
 }
Esempio n. 13
0
        /// <summary>
        /// Вычисление Total. И сборка данных для записи в файлы.
        /// </summary>
        private CalcResult CalculateTotal()
        {
            CalcResult calcResult = null; //набор для записи в файл

            if (_calculations.Items.Count > 0)
            {
                calcResult = new CalcResult();
                //Проходим по всем невыполненным действиям из Items. Выполняем их. После, переносим их в Items.
                for (int i = 0; i < _calculations.Items.Count; i++)
                {
                    if (_calculations.Items[i].Action == "+")
                    {
                        _calculations.Current.Total += _calculations.Items[i].Data;
                    }
                    else if (_calculations.Items[i].Action == "-")
                    {
                        _calculations.Current.Total -= _calculations.Items[i].Data;
                    }
                    else if (_calculations.Items[i].Action == "*")
                    {
                        _calculations.Current.Total *= _calculations.Items[i].Data;
                    }
                    else if (_calculations.Items[i].Action == "/")
                    {
                        if (_calculations.Items[i].Data != 0)
                        {
                            _calculations.Current.Total /= _calculations.Items[i].Data;
                        }
                        else //На ноль не делим :)
                        {
                            throw new DivideByZeroException();
                        }
                    }
                }
                //в Items, для файла, сразу добавим операцию из текущего Current
                if (!string.IsNullOrEmpty(_calculations.Current.Action))//(если это не пустая, самая первая операция)
                {
                    calcResult.Items.Add(new Action_Data()
                    {
                        Action = _calculations.Current.Action,
                        Data   = _calculations.Current.Data
                    });
                }
                // и добавим все новые операции, не включая последнюю :
                calcResult.Items.AddRange(_calculations.Items.GetRange(0, _calculations.Items.Count - 1));
                //Текущий Current заменим на последнюю новую операцию :
                _calculations.Current.Action = _calculations.Items[_calculations.Items.Count - 1].Action;
                _calculations.Current.Data   = _calculations.Items[_calculations.Items.Count - 1].Data;
                calcResult.Current           = _calculations.Current; //новый Current, для файла

                _calculations.Items.Clear();                          //очищаем Items в синглтоне _calculations.
            }
            return(calcResult);
        }
Esempio n. 14
0
        public void Test_errors_double_conversion()
        {
            var input = "1+2.1.1";

            ParsedData parsedData = Parser.ConvertStringToData(input);

            CalcResult actual = Calculator.Calculate(parsedData);

            CalcResult expected = new CalcResult(Single.NaN, ErrorMessages.double_conversion);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 15
0
        public void Test_errors_parentheses()
        {
            var input = "1+3*(2+5";

            ParsedData parsedData = Parser.ConvertStringToData(input);

            CalcResult actual = Calculator.Calculate(parsedData);

            CalcResult expected = new CalcResult(Single.NaN, ErrorMessages.parentheses);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 16
0
        public void Test_multiplication()
        {
            var input = "1+2+3*3+5*6";

            ParsedData parsedData = Parser.ConvertStringToData(input);

            CalcResult actual = Calculator.Calculate(parsedData);

            CalcResult expected = new CalcResult(42, "");

            Assert.AreEqual(expected, actual);
        }
Esempio n. 17
0
        public void Test_parentheses()
        {
            var input = "1+2*(3+4/(1+1))+5*(6*7-36)";

            ParsedData parsedData = Parser.ConvertStringToData(input);

            CalcResult actual = Calculator.Calculate(parsedData);

            CalcResult expected = new CalcResult(41, "");

            Assert.AreEqual(expected, actual);
        }
Esempio n. 18
0
        public void Test_four_elements_add()
        {
            var input = "1+2+3+4";

            ParsedData parsedData = Parser.ConvertStringToData(input);

            CalcResult actual = Calculator.Calculate(parsedData);

            CalcResult expected = new CalcResult(10, "");

            Assert.AreEqual(expected, actual);
        }
Esempio n. 19
0
        public static CalcResult Calc(
            float bezierLengthRequired,
            Vector2 start,
            Vector2 end,
            BezierCalculatorControlPointDirection dir1,
            BezierCalculatorControlPointDirection dir2,
            Vector2 p1Adj = new Vector2(),
            Vector2 p2Adj = new Vector2(),
            int rangeMin  = 1,
            int rangeMax  = 200)
        {
            if (layoutOnly)
            {
                return(new CalcResult());
            }

            int        currentIterationValue  = ((rangeMax - rangeMin) / 2) + rangeMin;
            int        previousIterationValue = 0;
            CalcResult lengthFound            = new CalcResult();

            for (int i = 1; i < 51; i++)
            {
                lengthFound = CalcLength(start, end, dir1, dir2, p1Adj, p2Adj, currentIterationValue);

                if (Math.Abs(bezierLengthRequired - lengthFound.FoundLength) <= 0.3F)
                {
                    //System.Diagnostics.Debug.WriteLine(" BezierCalculator requiredLength=" + bezierLengthRequired + " foundLength=" + lengthFound.FoundLength + " i=" + i);
                    lengthFound.SolutionFound = true;
                    return(lengthFound);
                }

                if (lengthFound.FoundLength > bezierLengthRequired)
                {
                    rangeMax = currentIterationValue;
                }

                if (lengthFound.FoundLength < bezierLengthRequired)
                {
                    rangeMin = currentIterationValue;
                }

                currentIterationValue = ((rangeMax - rangeMin) / 2) + rangeMin;
                if (currentIterationValue == previousIterationValue)
                {
                    break;
                }
                previousIterationValue = currentIterationValue;
                //System.Diagnostics.Debug.WriteLine("currentIterationValue="+currentIterationValue);
            }
            //System.Diagnostics.Debug.WriteLine(description + " Warning - BezierCalculator, no soltion found after 50 iterations");
            lengthFound.SolutionFound = false;
            return(lengthFound);// new CalcResult();
        }
Esempio n. 20
0
        public void Test_errors_division_to_zero()
        {
            var input = "1/0";

            ParsedData parsedData = Parser.ConvertStringToData(input);

            CalcResult actual = Calculator.Calculate(parsedData);

            CalcResult expected = new CalcResult(Single.NaN, ErrorMessages.division_to_zero);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 21
0
        public void Test_empty_string()
        {
            var input = "";

            ParsedData parsedData = Parser.ConvertStringToData(input);

            CalcResult actual = Calculator.Calculate(parsedData);

            CalcResult expected = new CalcResult(Single.NaN, ErrorMessages.empty_input);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 22
0
        public void Test_errors_math_operators_absent()
        {
            var input = "123";

            ParsedData parsedData = Parser.ConvertStringToData(input);

            CalcResult actual = Calculator.Calculate(parsedData);

            CalcResult expected = new CalcResult(Single.NaN, ErrorMessages.mathOp_absent);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 23
0
        public static CalcResult Map(int nOne, int nTwo, string method, double res)
        {
            CalcResult result = new CalcResult
            {
                NumberOne = nOne,
                NumberTwo = nTwo,
                Method    = method,
                Result    = res
            };

            return(result);
        }
        public async static Task WriteDbContext(this CalcDbContext _db, int id, string message)
        {
            CalcResult calcResult = new CalcResult()
            {
                Insert_Date    = DateTimeOffset.UtcNow,
                Value          = message,
                CalcFunctionId = id
            };
            await _db.CalcResults.AddAsync(calcResult);

            await _db.SaveChangesAsync();
        }
Esempio n. 25
0
        protected void ButtonCalc_Click(object sender, EventArgs e)
        {
            TextBoxResult.Text = "";

            string math_sequence = GetMathSequence();

            ParsedData parsedData = Parser.ConvertStringToData(math_sequence);

            CalcResult calcResult = Calculator.Calculate(parsedData);

            PublicResult(calcResult);
        }
Esempio n. 26
0
        public void Test_decimal_division()
        {
            var input = "1.2+2,4+3/4";

            ParsedData parsedData = Parser.ConvertStringToData(input);

            CalcResult actual = Calculator.Calculate(parsedData);

            CalcResult expected = new CalcResult(4.35, "");

            Assert.AreEqual(expected, actual);
        }
Esempio n. 27
0
        public CalcResult <Phonecall, decimal> Calculate(List <ConsumedInfo <Phonecall, decimal> > items)
        {
            var result = new CalcResult <Phonecall, decimal>();

            foreach (var itme in items)
            {
                var am = itme.Origin.Duration.Seconds - itme.Consumed;
                result.Billed.Add(new BillRecord <decimal>()
                {
                    BillAmount = am, Consumed = am, Description = "a $ a second"
                });
            }

            return(result);
        }
Esempio n. 28
0
        CalcResult IOperatorOrFunction.Calc(params CalcResult[] parameters)
        {
            CalcResult a = parameters[0];
            CalcResult b = parameters[1];

            if (a.Precedence > Precedence)
            {
                a.AddParenthesis();
            }
            if (b.Precedence > Precedence || (b.Precedence == Precedence && IsSubOrDiv))
            {
                b.AddParenthesis();
            }
            return(new CalcResult(CalcCore(a.Value, b.Value), $"{a.Text}{Name}{b.Text}", Precedence));
        }
Esempio n. 29
0
File: Tube.cs Progetto: birdol/MCoil
        public static CalcResult TubeCalc(int Nelement, string[] fluid, double[] composition,
                                          double dh, double l, double Aa_fin, double Aa_tube, double A_r_cs, double Ar, double[] tai,
                                          double tri, double pri, double hri, double mr, double ma, double ha,
                                          double eta_surface, double zh, double zdp, int hexType, double thickness, double conductivity, double Pwater)
        {
            double g = mr / A_r_cs;

            CalcResult res_tube = new CalcResult();
            CalcResult r        = new CalcResult();

            for (int i = 0; i < Nelement; i++)
            {
                r = Element.ElementCal(fluid, composition, dh, l / Nelement, Aa_fin / Nelement, Aa_tube / Nelement, A_r_cs, Ar / Nelement,
                                       tai[i], tri, pri, hri, mr, g, ma, ha, eta_surface, zh, zdp, hexType, thickness, conductivity, Pwater);

                pri = r.Pro;
                hri = r.hro;
                tri = r.Tro;

                res_tube.Tao   = r.Tao;
                res_tube.DP   += r.DP;
                res_tube.Q    += r.Q;
                res_tube.M    += r.M;
                res_tube.Tro   = r.Tro;
                res_tube.Pro   = r.Pro;
                res_tube.hro   = r.hro;
                res_tube.x_o   = r.x_o;
                res_tube.Vel_r = r.Vel_r;
                res_tube.href += r.href;
                res_tube.R_1  += r.R_1;
                res_tube.R_1a += r.R_1a;
                res_tube.R_1r += r.R_1r;
            }
            //res_tube.Tao = res_tube.Tao / Nelement; //to be modified....
            res_tube.href = res_tube.href / Nelement;
            res_tube.R_1  = res_tube.R_1 / Nelement;
            res_tube.R_1a = res_tube.R_1a / Nelement;
            res_tube.R_1r = res_tube.R_1r / Nelement;

            return(res_tube);
        }
Esempio n. 30
0
        private static void RunServer(object state)
        {
            var server = (BlockingTcpServer)state;

            while (server.IsStarted)
            {
                var    client       = server._listener.AcceptTcpClient();
                var    clientStream = client.GetStream();
                byte[] buffer       = new byte[client.ReceiveBufferSize];
                clientStream.Read(buffer, 0, client.ReceiveBufferSize);

                var        request = CalcRequest.FromBytes(buffer);
                CalcResult res;
                switch (request.Operation)
                {
                case Operation.Sum:
                    res = CalcResult.From(server._calculator.Sum(request.Vector1, request.Vector2));
                    break;

                case Operation.Minus:
                    res = CalcResult.From(server._calculator.Minus(request.Vector1, request.Vector2));
                    break;

                case Operation.ScalarMultiply:
                    res = CalcResult.From(server._calculator.ScalarMultiply(request.Vector1, request.Vector2));
                    break;

                default:
                    continue;
                }

                Thread.Sleep(250);

                var resBytes = res.GetBytes();
                clientStream.Write(resBytes, 0, resBytes.Length);

                client.Close();
            }
        }