Example #1
0
        public void GetDoubleMark_ShouldReturnValidResults_WithVisitorWinResult(int homeScore, int visitorScore)
        {
            var finalResult = new FinalResult(this.mockedMatch, homeScore, visitorScore);
            var results     = finalResult.GetDoubleMark();

            Assert.AreEqual("X2", results[0]);
            Assert.AreEqual("_12", results[1]);
        }
Example #2
0
 public void DisplayResult(FinalResult result)
 {
     //TO DO
     foreach (var anim in result.unit)
     {
         Animate(anim);
         StartCoroutine(Wait());
     }
 }
Example #3
0
        private FinalResult GetResult()
        {
            var finalResult = new FinalResult();

            finalResult.FinalState = new FinalState(_positionState.X, _positionState.Y, _positionState.Facing.ToString());
            finalResult.Battery    = _positionState.LeftBattery;
            finalResult.Visited    = _instructionExecutor.GetVisited();
            finalResult.Cleaned    = _instructionExecutor.GetCleaned();
            return(finalResult);
        }
Example #4
0
        public void CalculateFinalResult()
        {
            FinalResult newResult = new FinalResult();

            newResult.InterArrivalTime = interArrivalTiemInputed;
            foreach (var finalResult in getAllFinalTableInfo())
            {
                newResult.ArrivalTime = finalResult.ArrivalTime + newResult.InterArrivalTime;
            }
            newResult.ServiceTime = serviceTimeInputed;
            int previousServiceEndTiem = 0;

            foreach (var finalResult in getAllFinalTableInfo())
            {
                previousServiceEndTiem = finalResult.ServiceEndTime;
            }

            if (previousServiceEndTiem <= newResult.ArrivalTime)
            {
                newResult.ServiceStartTime = newResult.ArrivalTime;
            }
            else
            {
                newResult.ServiceStartTime = previousServiceEndTiem;
            }

            newResult.ServiceEndTime = newResult.ServiceStartTime + newResult.ServiceTime;

            int initialQueue = 0;

            if (newResult.ServiceStartTime > newResult.ArrivalTime)
            {
                newResult.Queue = newResult.ServiceStartTime - newResult.ArrivalTime;
            }
            else
            {
                newResult.Queue = initialQueue;
            }

            newResult.TimeSpends = newResult.ServiceEndTime - newResult.ArrivalTime;

            int initialIdleTime = 0;

            if (previousServiceEndTiem < newResult.ArrivalTime)
            {
                newResult.IdleTime = newResult.ArrivalTime - previousServiceEndTiem;
            }
            else
            {
                newResult.IdleTime = initialIdleTime;
            }


            SaveFinalTableData(newResult);
        }
Example #5
0
        public void SaveFinalTableData(FinalResult finalResult)
        {
            string     query   = "Insert into tbl_TotalSimulation values(" + arrivalRD + "," + finalResult.InterArrivalTime + "," + finalResult.ArrivalTime + "," + serviceRD + "," + finalResult.ServiceTime + "," + finalResult.ServiceStartTime + "," + finalResult.ServiceEndTime + "," + finalResult.Queue + "," + finalResult.TimeSpends + "," + finalResult.IdleTime + ")";
            SqlCommand command = new SqlCommand();

            command.Connection  = connection;
            command.CommandText = query;
            connection.Open();
            command.ExecuteNonQuery();
            connection.Close();
        }
Example #6
0
 static void Main(string[] args)
 {
     //Check for arguments
     if (args != null && args.Length > 0 && !string.IsNullOrEmpty(args[0]))
     {
         var path = args[0];
         if (File.Exists(path))
         {
             try
             {
                 //read csv file into list
                 var           lines    = File.ReadAllLines(path).Skip(1);
                 List <Equity> equities = new List <Equity>();
                 Equity        equity;
                 foreach (var line in lines)
                 {
                     equity = new Equity();
                     string[] words = line.Split(',');
                     equity.InvestmentDate  = Convert.ToDateTime(words[0].Trim());
                     equity.SharesPurchased = Convert.ToInt32(words[1].Trim());
                     equity.CashPaid        = Convert.ToDouble(words[2].Trim());
                     equity.Investor        = words[3].Trim();
                     equities.Add(equity);
                 }
                 //Get data by investors
                 var ownership = equities.GroupBy(e => e.Investor).Select(equity => new
                 {
                     investor  = equity.Key,
                     shares    = equity.Sum(x => x.SharesPurchased),
                     cash_paid = equity.Sum(x => x.CashPaid),
                     ownership = String.Format("{0:0.00}", (double)equity.Sum(x => x.SharesPurchased) * 100 / equities.Sum(e => e.SharesPurchased))
                 });
                 var f = new FinalResult();
                 f.date                   = equities.OrderByDescending(e => e.InvestmentDate).First().InvestmentDate.ToString("MM/dd/yyyy");
                 f.cash_raised            = equities.Sum(e => e.CashPaid);
                 f.total_number_of_shares = equities.Sum(e => e.SharesPurchased);
                 f.ownership              = ownership;
                 Console.WriteLine(JsonConvert.SerializeObject(f));
             }
             catch (Exception ex)
             {
                 Console.WriteLine("Some error occured. Details:" + ex.Message);
             }
         }
         else
         {
             Console.WriteLine("File don't exist on given path.");
         }
     }
     else
     {
         Console.WriteLine("Please enter valid path.");
     }
 }
    public override void DisplayFinalResult(FinalResult toDisplay)
    {
        this.gameObject.SetActive(true);

        print(toDisplay.m_Name);
        print(toDisplay.m_Color);

        m_DisplayText.text = toDisplay.m_Name;
        m_CocktailGlassFillDisplay.color = new Color(toDisplay.m_Color.r, toDisplay.m_Color.g, toDisplay.m_Color.b, 0.5f);
        m_FoamDisplay.sprite             = toDisplay.m_Foam;
        m_FoamDisplay.color = toDisplay.m_FoamColor;
    }
Example #8
0
        public FinalResult GetMinimum(InitialData data)
        {
            _func           = data.Func;
            _iterationCount = 0;
            _result         = new FinalResult {
                Results = new List <IterationResult>()
            };

            if (_method == FibonacciMethod)
            {
                GenerateFibonacci((long)((data.To - data.From) / _error));
            }

            var segment = new Segment {
                From = data.From, To = data.To
            };

            _x          = _v = _w = segment.Mid;
            _d          = _e = segment.Length;
            _brantError = _error / 1000;

            _initialSegment = new Segment()
            {
                From = segment.From, To = segment.To
            };
            _lastIterationResult = new IterationResult {
                Segment = _initialSegment
            };

            _result.Results.Add(new IterationResult
            {
                Segment     = segment,
                From        = segment.From,
                To          = segment.To,
                LengthRatio = segment.Length / _initialSegment.Length,
                Res1        = _func(segment.From),
                Res2        = _func(segment.To)
            });

            while (segment.Length >= _error)
            {
                _iterationCount++;
                segment = _method(segment);

                _result.Results.Add(_lastIterationResult);
            }

            _result.IterationCount = _iterationCount;
            _result.Res            = Math.Min(_func(segment.From), _func(segment.To));

            return(_result);
        }
 private void UpdateCheckDirty(FinalResult r)
 {
     if (r.FinalStatus != r.RunningStatus)
     {
         ++_nbFinalDifferFromRunning;
     }
     else
     {
         --_nbFinalDifferFromRunning;
     }
     Debug.Assert(_nbFinalDifferFromRunning >= 0, "There can't be less than zero differences..");
     _runner.SetDirty(_nbFinalDifferFromRunning > 0);
 }
        internal void SetRunningError(IExecutionPlanResult error)
        {
            Debug.Assert(error.Status != ExecutionPlanResultStatus.Success && error.Culprit != null, "An error is necessarily associated to a plugin.");

            FinalResult r = _final.GetOrSet(error.Culprit.PluginId, g => new FinalResult());
            bool        hasErrorAlready = r.RunningError != null;

            r.RunningError = error;
            if (!hasErrorAlready)
            {
                Update(error.Culprit.PluginId, r);
            }
        }
Example #11
0
        public PlotData fromBacklogReport(FinalResult FINAL, int stepBacklogTime, DateTime startDate)
        {
            var backlogTimePlot = new PlotData();

            backlogTimePlot.DataName = "Перцентиль по backlogTime";
            backlogTimePlot.Periods  = new List <Period>();

            for (DateTime date = startDate; date < DateTime.Today; date = date.AddMonths(1))
            {
                if (date.AddMonths(stepBacklogTime) > DateTime.Today)
                {
                    break;
                }
                else
                {
                    var period = new Period();
                    period.items     = new List <ResultItem>();
                    period.startDate = date;
                    period.endDate   = date.AddMonths(stepBacklogTime);

                    List <ResultItem> backlogTimeList = new List <ResultItem>();

                    foreach (ResultItem i in FINAL.resultItems)
                    {
                        if (i.value[0].fields.ActivatedDate != null && DateTime.Parse(i.value[0].fields.ActivatedDate) < date.AddMonths(stepBacklogTime) && DateTime.Parse(i.value[0].fields.ActivatedDate) >= date)
                        {
                            //if (i.value[0].backlogTime != 0)
                            //{
                            period.items.Add(i);
                            // backlogTimeList.Add(i.value[0].backlogTime);
                            //}
                        }
                    }

                    period.items = period.items.OrderBy(o => o.value[0].backlogTime).ToList();

                    var percentil = Math.Round(period.items.Count * 0.8, 1);
                    if (percentil != 0 && percentil > 1)
                    {
                        var date1                 = date;
                        var date2                 = date.AddMonths(3);
                        var percentilFraction     = Math.Round(percentil - (int)percentil, 1);
                        var TaskDeltaForPercentil = period.items[(int)percentil].value[0].backlogTime - period.items[(int)percentil - 1].value[0].backlogTime;
                        var percentilResult       = period.items[(int)percentil - 1].value[0].backlogTime + (TaskDeltaForPercentil * percentilFraction); //значение по перцентилю, которое, помимо целой части, учитывает дробную часть перцентиля
                        period.percentilBacklogTime = (int)Math.Round(percentilResult);
                    }
                    backlogTimePlot.Periods.Add(period);
                }
            }
            return(backlogTimePlot);
        }
Example #12
0
        public ActionResult HotelsWebService()
        {
            // EXERCISE #2 CODE HERE
            //Rest of work done in above 3 methods, in XMLResult.cs File in Model, and in HotelWebService.cshtml in Views/Home
            int hotelId = 105304;

            FinalResult hotelResult = new FinalResult();

            hotelResult = InvokeRequest(hotelId);

            ViewData["HotelResult"] = hotelResult;

            return(View());
        }
Example #13
0
    public void DisplayFinalResult(FinalResult result, MedalRow.MedalType[] medalTypes)
    {
        var text = result.ToString().ToUpper();

        transform.Find("FinalResult").GetComponent <Text>().text = text;

        var medalRows = transform.GetComponentsInChildren <MedalRow>();
        var i         = 0;

        foreach (var medalType in medalTypes)
        {
            medalRows[i++].SetMedalType(medalType);
        }
    }
 void UpdateAll()
 {
     foreach (var e in _final)
     {
         FinalResult r = e.Value;
         if (e.Key is Guid)
         {
             Update((Guid)e.Key, r);
         }
         else
         {
             Update((string)e.Key, r);
         }
     }
 }
 /// <summary>
 /// Initialize the internal count of differences and set RunningConfiguration.IsDirty accordingly.
 /// </summary>
 internal void Initialize()
 {
     Debug.Assert(_nbFinalDifferFromRunning == 0);
     foreach (var c in _runner.ConfigManager.SolvedPluginConfiguration)
     {
         FinalResult r = new FinalResult();
         _final.Add(c.PluginId, r);
         Debug.Assert(r.FinalStatus == r.RunningStatus, "At creation time, they both are Optional.");
         if (r.UpdatePlugin(c.PluginId, _runnerDisabled, _runner.ConfigManager.SolvedPluginConfiguration, _layers, _runner.Discoverer))
         {
             Debug.Assert(r.FinalStatus != r.RunningStatus, "If FinalStatus changed, then it necessarily differs from RunningStatus.");
             ++_nbFinalDifferFromRunning;
         }
     }
     _runner.SetDirty(_nbFinalDifferFromRunning > 0);
 }
Example #16
0
        public HttpResponseMessage Post([FromBody] ListsToCompare listsToCompare)
        {
            FinalResult ComparisonResult = new FinalResult();

            try
            {
                ICommon common = new Common();
                ComparisonResult         = common.getCompareResult(listsToCompare);
                ComparisonResult.Message = "Result generated successfully";
            }
            catch (Exception ex)
            {
                ComparisonResult.Message = "Could not generate result, exception occured " + ex.InnerException;
            }
            return(Request.CreateResponse <FinalResult>(HttpStatusCode.OK, ComparisonResult));
        }
Example #17
0
    public List <FinalResult> GetResult(string randomNumber, string userInput)
    {
        char[] splitRandomNumber = randomNumber.ToCharArray();
        char[] splitUserInput    = userInput.ToCharArray();

        List <FinalResult> results = new List <FinalResult>();

        for (int index = 0; index < randomNumber.Length; index++)
        {
            FinalResult result      = new FinalResult();
            var         isPlusMinus = false;
            if (splitRandomNumber[index] == splitUserInput[index])
            {
                result.Index  = index;
                result.Flag   = splitRandomNumber[index] == splitUserInput[index];
                result.Answer = "+";
                results.Add(result);
                isPlusMinus = true;
            }
            else
            {
                for (int j = 0; j < 4; j++)
                {
                    if (splitRandomNumber[index] == splitUserInput[j] && index != j)
                    {
                        result.Index  = index;
                        result.Flag   = false;
                        result.Answer = "-";
                        results.Add(result);
                        isPlusMinus = true;
                        break;
                    }
                }
            }
            // if nothing is matched printing empty string.
            if (!isPlusMinus)
            {
                result.Index  = index;
                result.Answer = " ";
                results.Add(result);
            }
        }

        return(results);
    }
        //Calculates the Total value of all boxes
        /// <summary>
        /// Calculates the Total value of all boxes
        /// </summary>
        /// <returns>
        /// Total calculated value
        /// </returns>
        public string GetCheckoutValue()
        {
            decimal FinalResult;

            //this if else statment is to prevent bugs with the + and - for the total value
            if (decimal.Parse(Allbalance.Text) < 0)
            {
                FinalResult = decimal.Parse(Allbalance.Text) + decimal.Parse(CountedCash.Text);

                return(CheckOut.Text = FinalResult.ToString());
            }
            else
            {
                FinalResult = decimal.Parse(Allbalance.Text) - decimal.Parse(CountedCash.Text);

                return(CheckOut.Text = FinalResult.ToString());
            }
        }
        public FinalizerEngine(string team1Name, string team2Name)
        {
            if (string.IsNullOrWhiteSpace(team1Name))
            {
                Logger.Error("FinalizerEngine team 1 name invalid.");
            }

            if (string.IsNullOrWhiteSpace(team2Name))
            {
                Logger.Error("FinalizerEngine team 2 name invalid.");
            }

            _finalResult = new FinalResult()
            {
                Team1 = team1Name,
                Team2 = team2Name
            };
        }
Example #20
0
        public ViewResult FinalResults()
        {
            if (IsLogged())
            {
                return(View("Redirect"));
            }

            if (Session["EventTypeSelected"] == null)
            {
                GetDataForIndex();
                return(View("Index", fashionFlavorRepository.GetAll()));
            }
            IList <FashionFlavor> flavors     = Session["FashionFlavorSelected"] as List <FashionFlavor>;
            IList <EventType>     eventTypes  = Session["EventTypeSelected"] as List <EventType>;
            FinalResult           finalResult = new FinalResult(flavors, eventTypes);

            return(View(finalResult));
        }
Example #21
0
    public override void OnEnterState(LogicManager logicManager)
    {
        base.OnEnterState(logicManager);

        m_FinalResultDisplay.gameObject.SetActive(true);

        string toPrint = logicManager.CurrentSessionInfo.ToString();

        print(toPrint);

        float finalR = 0.0f;
        float finalG = 0.0f;
        float finalB = 0.0f;

        string finalResultName = "";

        foreach (Ingredient i in logicManager.CurrentSessionInfo.IngredientsOfSession)
        {
            finalR += i.m_Color.r;
            finalG += i.m_Color.g;
            finalB += i.m_Color.b;

            finalResultName += i.m_Name.Substring(0, 3);
        }
        finalResultName += "-Cocktail";

        finalR /= logicManager.CurrentSessionInfo.IngredientsOfSession.Length;
        finalG /= logicManager.CurrentSessionInfo.IngredientsOfSession.Length;
        finalB /= logicManager.CurrentSessionInfo.IngredientsOfSession.Length;

        FinalResult finalResult = new FinalResult();

        finalResult.m_Color     = new Color(finalR, finalG, finalB);
        finalResult.m_Name      = finalResultName;
        finalResult.m_Foam      = logicManager.CurrentSessionInfo.MotionOfSession.m_FinalDisplaySprite;
        finalResult.m_FoamColor = logicManager.CurrentSessionInfo.MotionOfSession.m_FoamColor;
        m_FinalResultDisplay.DisplayFinalResult(finalResult);

        // Example of how to start the coroutine to leave the state after a set amount of seconds.
        StartCoroutine(LeaveAfterDisplayingResult());
    }
Example #22
0
        public PlotData formTaskReport(FinalResult FINAL, DateTime startDate)
        {
            //DateTime startDate = new DateTime(2018, 3, 1);

            int step = 1;
            var plot = new PlotData();

            plot.DataName = "Сколько берется в работу";
            plot.Periods  = new List <Period>();

            for (DateTime date = startDate; date < DateTime.Today; date = date.AddMonths(step))
            {
                //создаём объект типа период, в который будем включать таски, попавшие в промежуток startDate/endDate
                var period = new Period();
                period.items     = new List <ResultItem>();
                period.startDate = date;
                period.endDate   = date.AddMonths(step);

                //Определяем сколько таск было создано/закрыто/взято в работу в текщий период
                foreach (ResultItem i in FINAL.resultItems)
                {
                    if (i.value[0].fields.ActivatedDate != null && DateTime.Parse(i.value[0].fields.ActivatedDate) < date.AddMonths(step) && DateTime.Parse(i.value[0].fields.ActivatedDate) > date)
                    {
                        period.items.Add(i);
                        period.activatedCount++;
                    }
                    if (i.value[0].fields.ClosedDate != null && DateTime.Parse(i.value[0].fields.ClosedDate) < date.AddMonths(step) && DateTime.Parse(i.value[0].fields.ClosedDate) > date)
                    {
                        period.items.Add(i);
                        period.closedCount++;
                    }
                    if (DateTime.Parse(i.value[0].fields.CreatedDate) < date.AddMonths(step) && DateTime.Parse(i.value[0].fields.CreatedDate) > date)
                    {
                        period.items.Add(i);
                        period.createdCount++;
                    }
                }
                plot.Periods.Add(period);
            }
            return(plot);
        }
Example #23
0
        public ActionResult result()
        {
            if (Session["id"] == null)
            {
                return(RedirectToAction("Login", "IPTSELogin"));
            }
            FinalResult    objResult    = new FinalResult();
            FinalResultBLL objGetResult = new FinalResultBLL();

            objResult = objGetResult.GetFinalResult(Convert.ToInt32(Session["id"]));
            if (objResult != null)
            {
                ViewBag.TotalQuestion   = objResult.TotalQuestion;
                ViewBag.MarksObtained   = objResult.MarksObtained;
                ViewBag.MarksPercentage = objResult.MarksPercentage;
                ViewBag.TotalMarks      = objResult.TotalMarks;
                ViewBag.msg             = "You have successfully completed the exam. Please find the exam details below.";
                return(View("result"));
            }
            return(View());
        }
Example #24
0
        public MatchController(HicoreSocket socket)
        {
            this._socket = socket;


            _socket.On(isMatchInProgressEvent, res => { OnIsMatchInProgressResult(new Result(res.Text)); });

            _socket.On(joinToMatchEvent, res => { OnJoinToMatchResult(new Result(res.Text)); });

            _socket.On(leaveMatchEvent, res => { OnLeaveMatch(new Result(res.Text)); });

            _socket.On(endOfMatchEvent, res =>
            {
                JSONNode jsonRes   = JSON.Parse(res.Text);
                FinalResult result = new FinalResult();

                result.Message = jsonRes["msg"].Value;
                result.Data    = jsonRes["data"];

                OnEnd(result);
            });
        }
Example #25
0
        public FinalResult getCompareResult(ListsToCompare compareList)
        {
            FinalResult ComparisonResult = new FinalResult();

            try
            {
                if (compareList != null && compareList.Current != null && compareList.Initial != null)
                {
                    List <BaseList> initial = new List <BaseList>();
                    List <BaseList> current = new List <BaseList>();

                    initial = compareList.Initial;
                    current = compareList.Current;

                    //new items to show with the newList list object
                    List <BaseList> newList = current.Where(n => !initial.Any(o => o.Key == n.Key)).ToList();

                    //updated items to show with the updatedList list object
                    List <BaseList> updatedList = current.Where(u => initial.Any(o => o.Key == u.Key && o.Value != u.Value)).ToList();

                    //deleted items to show with the deletedList list object
                    List <BaseList> deletedList = initial.Where(d => !current.Any(o => o.Key == d.Key)).ToList();

                    ComparisonResult.NewItems     = newList;
                    ComparisonResult.UpdatedItems = updatedList;
                    ComparisonResult.DeletedItems = deletedList;
                    ComparisonResult.Message      = "Success";
                }
                else
                {
                    ComparisonResult.Message = "Please provide valid input..";
                }
            }
            catch (Exception e)
            {
                ComparisonResult.Message = "Internal Error.";
            }
            return(ComparisonResult);  //Request.CreateResponse<SortedCompareList>(HttpStatusCode.OK, ComparisonResult);
        }
Example #26
0
        private void AddData(FinalResult result)
        {
            const int precision = 10;
            int       rowNum    = 2;

            foreach (var iterationResult in result.Results)
            {
                var currentRow = _sheet.GetRow(rowNum);

                InsertCell(currentRow, _offset, Math.Round(iterationResult.LengthRatio, precision),
                           _percentageCellStyle, CellType.Numeric);
                InsertCell(currentRow, _offset + 1, Math.Round(iterationResult.From, precision),
                           _borderedCellStyle, CellType.Numeric);
                InsertCell(currentRow, _offset + 2, Math.Round(iterationResult.To, precision),
                           _borderedCellStyle, CellType.Numeric);
                InsertCell(currentRow, _offset + 3, Math.Round(iterationResult.Res1, precision),
                           _borderedCellStyle, CellType.Numeric);
                InsertCell(currentRow, _offset + 4, Math.Round(iterationResult.Res2, precision),
                           _borderedCellStyle, CellType.Numeric);

                rowNum++;
            }
        }
Example #27
0
        public List <ResultItem> getItemInfo(ResultItem finalResult, Report result, FinalResult FINAL)
        {
            for (int i = 0; i < result.workItems.Count; i++)
            {
                string myParameters = "?ids=" + result.workItems[i].Id + "&" +
                                      "fields=" + "System.Id,System.CreatedDate,System.IterationPath,System.WorkItemType,System.Title,System.AssignedTo,System.State,System.AreaPath,System.Tags,Microsoft.VSTS.Common.ActivatedDate,Microsoft.VSTS.Common.ClosedDate&" +
                                      "api-version=" + "3.0";

                string strReturn = null;
                try
                {
                    HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create("https://tfs.tele2.ru/tfs/Main/_apis/wit/workitems" + myParameters);
                    WebReq.Credentials = new NetworkCredential("service.crm.tfs", "$93aCZApFsW");

                    //Set method to post, otherwise postvars will not be used
                    WebReq.Method      = "GET";
                    WebReq.ContentType = "application/x-www-form-urlencoded";

                    //Get the response handle, we have no true response yet
                    HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
                    string          server  = WebResp.Server;
                    //read the response
                    Stream       WebResponse = WebResp.GetResponseStream();
                    StreamReader _response   = new StreamReader(WebResponse);
                    strReturn   = _response.ReadToEnd();
                    strReturn   = strReturn.Replace("System.", "");
                    strReturn   = strReturn.Replace("Microsoft.VSTS.Common.", "");
                    finalResult = JsonConvert.DeserializeObject <ResultItem>(strReturn);
                }
                catch (Exception ex)
                {
                    string MessageText = ex.Message;
                }
                FINAL.resultItems.Add(finalResult);
            }
            return(FINAL.resultItems);
        }
Example #28
0
        /// <summary>
        /// Computes the Results - orders by best lap time
        /// </summary>
        public void ComputeResults()
        {
            _logger.LogDebug("Computing results");

            if (_result == null)
            {
                _logger.LogWarning("ComputeResults: results object is null, cannot computer");
                StatusMessage = "Unable to compute results";
                return;
            }

            //var racers = _result.LeaderBoardLines.OrderBy(t => t.Timing.BestLap).ToList();
            var racers = _result.LeaderBoardLines;

            var racersLength = racers.Count;

            for (var i = 0; i < racersLength; i++)
            {
                var racer       = racers[i];
                var finalResult = new FinalResult
                {
                    Position   = i,
                    Name       = $"{racer.CurrentDriver.FirstName.Trim()} {racer.CurrentDriver.LastName.Trim()}",
                    RaceNumber = racer.Car.RaceNumber,
                    CarModel   = GetCarModel(racer.Car.CarModel),
                    LapCount   = racer.Timing.LapCount,
                    BestLap    = TimeSpan.FromMilliseconds(racer.Timing.BestLap).ToString(),
                    TotalTime  = racer.Timing.TotalTime
                };

                _logger.LogDebug($"ComputeResults: finalResult[{finalResult}]");
                _finalResults.Add(finalResult);
            }

            StatusMessage = "Successfully ordered";
        }
Example #29
0
        public bool SaveData(FinalResult final)
        {
            try
            {
                DateTime  dt       = DateTime.Now;
                IWorkbook workbook = null;
                string    file     = excelPath + "\\" + dt.ToString("yyyy-MM-dd") + ".xls";
                if (!Directory.Exists(excelPath))
                {
                    Directory.CreateDirectory(excelPath);  //使用Directory类的CreateDirectory方法创建文件夹
                }
                if (!File.Exists(file))
                {
                    File.Copy(Application.StartupPath + "\\" + "DATA.xls", file);
                }
                string fileExt = Path.GetExtension(file).ToLower();

                using (FileStream fs = File.Open(file, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    if (fileExt == ".xlsx")
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    else
                    {
                        workbook = new HSSFWorkbook(fs);
                    }                                    //fileExt == ".xls"

                    ISheet sheet     = workbook.GetSheet("Sheet1");
                    IRow   row0      = sheet.GetRow(0);  //第一行
                    int    cellcount = row0.LastCellNum; //列数
                    int    rowcount  = sheet.LastRowNum; //行数 不包含标题行

                    IRow row = sheet.CreateRow(rowcount + 1);

                    ICell cell0 = row.CreateCell(0);
                    ICell cell1 = row.CreateCell(1);
                    ICell cell2 = row.CreateCell(2);
                    ICell cell3 = row.CreateCell(3);
                    ICell cell4 = row.CreateCell(4);
                    ICell cell5 = row.CreateCell(5);
                    ICell cell6 = row.CreateCell(6);
                    ICell cell7 = row.CreateCell(7);

                    cell0.SetCellValue(final.CodeIndex);
                    cell1.SetCellValue(final.TestMode);
                    cell2.SetCellValue(final.TestStatus);
                    cell3.SetCellValue(final.Alarm);
                    cell4.SetCellValue(final.PressureValue + final.PressureUnit);
                    cell5.SetCellValue(final.LeakValue + final.LeakUnit);
                    cell6.SetCellValue(final.Result);
                    cell7.SetCellValue(final.Product);
                }


                using (FileStream fs = File.OpenWrite(file))
                {
                    workbook.Write(fs);//向打开的这个xls文件中写入数据
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
            return(true);
        }
Example #30
0
        public PlotSet errorBercutWithOther(DateTime startDate, int stepBacklogTime, int stepLeadTime)
        {
            #region Запрос номеров таск из TFS, удовлетворяющих запросу
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://tfs.tele2.ru/tfs/Main/Tele2/_apis/wit/wiql?api-version=3.0");
            httpWebRequest.Method      = "POST";
            httpWebRequest.Credentials = new NetworkCredential("user", "password");
            httpWebRequest.ContentType = "application/json; charset=utf-8; api-version=3.0";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string ErrorBercutWithOther =
                    "{" + "\"query\":" + "\"" +
                    "select[System.Id], " +
                    "[System.CreatedDate], " +
                    "[Microsoft.VSTS.Common.ActivatedDate], " +
                    "[Microsoft.VSTS.Common.ClosedDate], " +
                    "[System.WorkItemType], " +
                    "[System.Title], " +
                    "[System.State], " +
                    "[System.AreaPath], " +
                    "[System.IterationPath], " +
                    "[System.Tags] from WorkItems where " +
                    "[System.TeamProject] = @project and " +
                    "([System.WorkItemType] = 'Ошибка' and " +
                    "[System.CreatedBy] in " +
                    @"('Гордеев Александр Валериевич <T2RU\\a.gordeev>', " +
                    @"'Муратов Михаил Александрович <T2RU\\mikhail.muratov>', " +
                    @"'Юренков Станислав Сергеевич <T2RU\\supp.Dynamics21>', " +
                    @"'Евланов Сергей Леонидович <T2RU\\sergey.evlanov>', " +
                    @"'Семенов Антон Юрьевич <T2RU\\anton.y.semenov>', " +
                    @"'Кораблёва Екатерина Викторовна <T2RU\\supp.Dynamics11>', " +
                    @"'Иванов Арсений Дмитриевич <T2RU\\Supp.Dynamics02>', " +
                    @"'Анисимов Максим Александрович <T2RU\\supp.Dynamics12>', " +
                    @"'Фокин Андрей Геннадьевич <T2RU\\supp.Dynamics19>', " +
                    @"'Свидэрский Николай Сергеевич <T2RU\\nikolay.svidersky>', " +
                    @"'Панфилова Наталья Геннадьевна <T2RU\\natalya.panfilova>', " +
                    @"'Смирнов Фёдор Леонидович <T2RU\\supp.Dynamics20>', " +
                    @"'Большакова Мария Владимировна <T2RU\\supp.Dynamics17>', " +
                    @"'Чубукина Татьяна Сергеевна <T2RU\\Supp.Dynamics10>', " +
                    @"'Нижников Виталий Сергеевич <T2RU\\vitaly.nizhnikov>', " +
                    @"'Недоступ Александр Николаевич <T2RU\\alexander.nedostup>', " +
                    @"'Курилюк Антон Викторович <T2RU\\anton.kurilyuk>', " +
                    @"'Бондарчук Евгений Маркович <T2RU\\Supp.Dynamics08>', " +
                    @"'Чистяков Максим Сергеевич <T2RU\\supp.Dynamics18>', " +
                    @"'Манукян Ашот Каренович <T2RU\\ashot.manukyan>', " +
                    @"'Моисеева Ольга Алексеевна <T2RU\\supp.DSuite29>', " +
                    @"'Струнников Артем Сергеевич <T2RU\\supp.bercut120>', " +
                    @"'Калашников Дмитрий Юрьевич <T2RU\\dmitry.y.kalashnikov>', " +
                    @"'Полях Виктор Васильевич <T2RU\\victor.polyakh>', " +
                    @"'Глушков Сергей Иванович <T2RU\\Supp.Dynamics05>', " +
                    @"'Остапенко Сергей Сергеевич <T2RU\\sergey.ostapenko>', " +
                    @"'Жиряков Дмитрий Владимирович <T2RU\\supp.Dynamics15>', " +
                    @"'Тришечкин Евгений Владимирович <T2RU\\Supp.Dynamics06>', " +
                    @"'Хромина Ольга Анатольевна <T2RU\\olga.khromina>', " +
                    @"'Арсеньева Юлия Андреевна <T2RU\\supp.Dynamics16>', " +
                    @"'Артюков Иван Алексеевич <T2RU\\Supp.Dynamics03>', " +
                    @"'Сибакова Евгения Александровна <T2RU\\evgenia.sibakova>', " +
                    @"'Хрупин Дмитрий Владимирович <T2RU\\dmitry.khrupin>', " +
                    @"'Сологуб Николай Сергеевич <T2RU\\Supp.Dynamics24>') and " +
                    @"[System.AreaPath] in ('Tele2\\Партнеры\\Беркут\\Product testing') and " +
                    "[System.Reason] <> 'Не является ошибкой' and " +
                    "[System.Reason] <> 'Отклонена' and " +
                    "not [System.Tags] contains 'Техническое' and " +
                    "[System.Tags] contains 'Other' or " +
                    "([System.WorkItemType] = 'Ошибка' and " +
                    @"[System.AreaPath] = 'Tele2\\CRM\\CRM Team Bercut' and " +
                    "[System.Reason] <> 'Отклонена' and " +
                    "[System.Reason] <> 'Не является ошибкой' and " +
                    "[System.Tags] contains 'Other' and " +
                    "not [System.Tags] contains 'Техническое')) " +
                    "order by[Microsoft.VSTS.Common.ClosedDate] " +
                    "\"" +
                    "}";

                streamWriter.Write(ErrorBercutWithOther);
                streamWriter.Flush();
                streamWriter.Close();
            }
            var     httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            dynamic resultOfQuery;
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                resultOfQuery = streamReader.ReadToEnd();
            }
            Report result = JsonConvert.DeserializeObject <Report>(resultOfQuery);
            #endregion

            FinalResult FINAL = new FinalResult();
            FINAL.resultItems = new List <ResultItem>();
            ResultItem finalResult = new ResultItem();

            ItemInfoHelper itemInfoHelper = new ItemInfoHelper();
            FINAL.resultItems = itemInfoHelper.getItemInfo(finalResult, result, FINAL);

            //Считаем LeadTime и BackLogTime для каждой таски
            foreach (ResultItem i in FINAL.resultItems)
            {
                if (i.value[0].fields.ActivatedDate != null && i.value[0].fields.CreatedDate != null)
                {
                    i.value[0].backlogTime = (int)(DateTime.Parse(i.value[0].fields.ActivatedDate) - DateTime.Parse(i.value[0].fields.CreatedDate)).TotalDays;
                }
                if (i.value[0].fields.ClosedDate != null && i.value[0].fields.ActivatedDate != null)
                {
                    i.value[0].leadTime = (int)(DateTime.Parse(i.value[0].fields.ClosedDate) - DateTime.Parse(i.value[0].fields.ActivatedDate)).TotalDays;
                }
            }

            TaskReportHelper    taskReportHelper    = new TaskReportHelper();
            BacklogReportHelper backlogReportHelper = new BacklogReportHelper();
            LeadReportHelper    leadReportHelper    = new LeadReportHelper();

            PlotSet plotResult = new PlotSet();
            plotResult.PlotList = new List <PlotData>();
            plotResult.PlotList.Add(taskReportHelper.formTaskReport(FINAL, startDate));
            plotResult.PlotList.Add(backlogReportHelper.fromBacklogReport(FINAL, stepBacklogTime, startDate));
            plotResult.PlotList.Add(leadReportHelper.formLeadReport(FINAL, stepLeadTime, startDate));
            return(plotResult);
        }