public async Task <IActionResult> PostPrediction([FromBody] PredictionRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }



            MatchEntity matchEntity = await _context.Matches.FindAsync(request.MatchId);

            if (matchEntity == null)
            {
                return(BadRequest("Este partido no existe."));
            }

            if (matchEntity.IsClosed)
            {
                return(BadRequest("Este partido está cerrado."));
            }

            UserEntity userEntity = await _userHelper.GetUserAsync(request.UserId);

            if (userEntity == null)
            {
                return(BadRequest("Este usuario no existe."));
            }

            if (matchEntity.Date <= DateTime.UtcNow)
            {
                return(BadRequest("Este partido ya empezó."));
            }

            PredictionEntity predictionEntity = await _context.Predictions
                                                .FirstOrDefaultAsync(p => p.User.Id == request.UserId.ToString() && p.Match.Id == request.MatchId);

            if (predictionEntity == null)
            {
                predictionEntity = new PredictionEntity
                {
                    GoalsLocal   = request.GoalsLocal,
                    GoalsVisitor = request.GoalsVisitor,
                    Match        = matchEntity,
                    User         = userEntity
                };

                _context.Predictions.Add(predictionEntity);
            }
            else
            {
                predictionEntity.GoalsLocal   = request.GoalsLocal;
                predictionEntity.GoalsVisitor = request.GoalsVisitor;
                _context.Predictions.Update(predictionEntity);
            }

            await _context.SaveChangesAsync();

            return(NoContent());
        }
Exemplo n.º 2
0
        public async Task <IActionResult> PostPrediction([FromBody] PredictionRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            CultureInfo cultureInfo = new CultureInfo(request.CultureInfo);

            Resource.Culture = cultureInfo;

            MatchEntity matchEntity = await _dataContext.Matches.FindAsync(request.MatchId);

            if (matchEntity == null)
            {
                return(BadRequest(Resource.MatchDoesntExists));
            }
            if (matchEntity.IsClosed)
            {
                return(BadRequest(Resource.MatchAlreadyClosed));
            }

            UserEntity userEntity = await _userHelper.GetUserAsync(request.UserId);

            if (userEntity == null)
            {
                return(BadRequest(Resource.UserDoesntExists));
            }
            if (matchEntity.Date <= DateTime.UtcNow)
            {
                return(BadRequest(Resource.MatchAlreadyStarts));
            }

            PredictionEntity predictionEntity = await _dataContext.Predictions
                                                .FirstOrDefaultAsync(p => p.User.Id == request.UserId.ToString() && p.Match.Id == request.MatchId);

            if (predictionEntity == null)
            {
                predictionEntity = new PredictionEntity
                {
                    GoalsLocal   = request.GoalsLocal,
                    GoalsVisitor = request.GoalsVisitor,
                    Match        = matchEntity,
                    User         = userEntity
                };

                _dataContext.Predictions.Add(predictionEntity);
            }
            else
            {
                predictionEntity.GoalsLocal   = request.GoalsLocal;
                predictionEntity.GoalsVisitor = request.GoalsVisitor;
                _dataContext.Predictions.Update(predictionEntity);
            }

            await _dataContext.SaveChangesAsync();

            return(NoContent());
        }
Exemplo n.º 3
0
 public PredictionResponse ToPredictionResponse(PredictionEntity predictionEntity)
 {
     return(new PredictionResponse
     {
         GoalsLocal = predictionEntity.GoalsLocal,
         GoalsVisitor = predictionEntity.GoalsVisitor,
         Id = predictionEntity.Id,
         Match = ToMatchResponse(predictionEntity.Match),
         Points = predictionEntity.Points
     });
 }
Exemplo n.º 4
0
        private int GetPoints(PredictionEntity predictionEntity)
        {
            int points = 0;

            if (predictionEntity.GoalsLocal == _matchEntity.GoalsLocal)
            {
                points += 2;
            }
            if (predictionEntity.GoalsVisitor == _matchEntity.GoalsVisitor)
            {
                points += 2;
            }
            if (_matchStatus == GetMatchStaus(predictionEntity.GoalsLocal.Value, predictionEntity.GoalsVisitor.Value))
            {
                points++;
            }
            return(points);
        }
Exemplo n.º 5
0
        private int GetPoints(PredictionEntity predictionEntity)
        {
            int points = 0;

            if (predictionEntity.GoalsLocal == _matchEntity.GoalsLocal) //si son iguales
            {
                points += 2;                                            //suma dos puntos
            }

            if (predictionEntity.GoalsVisitor == _matchEntity.GoalsVisitor) //si son iguales
            {
                points += 2;                                                //suma dos puntos
            }

            if (_matchStatus == GetMatchStatus(predictionEntity.GoalsLocal.Value, predictionEntity.GoalsVisitor.Value)) //si es empate
            {
                points++;                                                                                               //suma un punto
            }

            return(points); //devuelve los puntos
        }
Exemplo n.º 6
0
 public PredictionResponse3 ToPredictionResponse3(PredictionEntity predictionEntity)
 {
     return(new PredictionResponse3
     {
         GoalsLocalPrediction = predictionEntity.GoalsLocal,
         GoalsVisitorPrediction = predictionEntity.GoalsVisitor,
         GoalsLocalReal = predictionEntity.Match.GoalsLocal,
         GoalsVisitorReal = predictionEntity.Match.GoalsVisitor,
         InitialsLocal = predictionEntity.Match.Local.Initials,
         InitialsVisitor = predictionEntity.Match.Visitor.Initials,
         LogoPathLocal = predictionEntity.Match.Local.LogoPath,
         LogoPathVisitor = predictionEntity.Match.Visitor.LogoPath,
         NameLocal = predictionEntity.Match.Local.Name,
         NameVisitor = predictionEntity.Match.Visitor.Name,
         MatchId = predictionEntity.Match.Id,
         MatchDate = predictionEntity.Match.DateLocal,
         PlayerId = predictionEntity.Player.Id,
         TournamentId = predictionEntity.Match.Group.Tournament.Id,
         Id = predictionEntity.Id,
         Points = predictionEntity.Points,
     });
 }
Exemplo n.º 7
0
        private void OnStartPredictionCommand(object args)
        {
            string prediction = "sushruta";

            if (this.hansanet != "Enable Hansanet")
            {
                prediction = "hansasushruta";
            }

            //System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            //dispatcherTimer.Tick += dispatcherTimer_Tick;
            //dispatcherTimer.Interval = TimeSpan.FromMilliseconds(1000 );
            //ProgressValue = 0;
            //dispatcherTimer.Start();

            //System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate
            //{

            this.IsEnabled        = false;
            this.IsProgressActive = true;
            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += (sender, e) =>
            {
                foreach (var item in PatientReport.OSPosteriorReportDatas)
                {
                    if (item.IsChecked)
                    {
                        string predictionResult = RestCalls.RestPredict(item.ImageUrl, prediction);

                        JavaScriptSerializer serializer = new JavaScriptSerializer();
                        PredictionEntity     obj        = JsonConvert.DeserializeObject <PredictionEntity>(predictionResult);
                        if (obj.result.StartsWith("Bad"))
                        {
                            item.Prediction = obj.result.Replace("(0)", "").Trim();
                            new Patient().UpdateReportData(item.Id, item.Prediction);
                        }
                        else
                        {
                            item.Prediction = obj.result.Replace(" (1). ", "").Replace(" (0). ", "").Trim();
                            new Patient().UpdateReportData(item.Id, item.Prediction);
                        }
                    }
                }
                foreach (var item in PatientReport.ODPosteriorReportDatas)
                {
                    if (item.IsChecked)
                    {
                        //try
                        //{
                        string predictionResult = RestCalls.RestPredict(item.ImageUrl, prediction);

                        JavaScriptSerializer serializer = new JavaScriptSerializer();
                        PredictionEntity     obj        = JsonConvert.DeserializeObject <PredictionEntity>(predictionResult);

                        //PredictionEntity obj = new PredictionEntity();
                        //  obj.result = "Bad Image";
                        if (obj.result.StartsWith("Bad"))
                        {
                            item.Prediction = obj.result.Replace("(0)", "").Trim();
                            new Patient().UpdateReportData(item.Id, item.Prediction);
                        }
                        else
                        {
                            item.Prediction = obj.result.Replace(" (1). ", "").Replace(" (0). ", "").Trim();
                            new Patient().UpdateReportData(item.Id, item.Prediction);
                        }
                        //}
                        //catch
                        //{
                        //    ModernDialog.ShowMessage("Prediction Internal Server Error.", "Prediction", MessageBoxButton.OK);
                        //}
                    }
                }
            };

            bw.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    ModernDialog.ShowMessage("Prediction Internal Server Error.", "Prediction", MessageBoxButton.OK);
                }
                this.IsEnabled        = true;
                this.IsProgressActive = false;
            };

            bw.RunWorkerAsync();



            //this.IsEnabled = true;
            //dispatcherTimer.Stop();
            //ProgressValue = 0;
            //});
        }
Exemplo n.º 8
0
        private async void actionsUserControl_PredictButtonOnClick(object sender, EventArgs e)
        {
            if (!IsValidateForm())
            {
                return;
            }

            KeyValuePair <int, string> previousDataKeyValuePair = _previousData[previousDataComboBox.SelectedIndex];
            DateTime dateTime = predictDateDateTimePicker.Value;

            if (!_applicationService.IsAvailableEnoughtData(previousDataKeyValuePair.Key))
            {
                DialogResult dr = MessageBox.Show("Predictor method requires more data to work properly. Are you sure to continue anyway?", "Confrimation", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                if (dr == DialogResult.No)
                {
                    return;
                }
            }
            previousDataComboBox.Enabled        = false;
            predictDateDateTimePicker.Enabled   = false;
            actionsUserControl.IsEnabledButtons = false;

            PredictionEntity predictionEntity = await _applicationService.GetPredictionsAsync(previousDataKeyValuePair.Key, dateTime);

            actionsUserControl.ErrorMessageText = predictionEntity.WarningMessage;

            if (predictionEntity.IsPredicted)
            {
                balanceOnIntroLabel.Text = $"Balance on {dateTime.ToString("yyyy-MM-dd")}";
                balanceOnValueLabel.Text = predictionEntity.PredictBalanace.ToString("0.00");
                balanceOnTodayLabel.Text = predictionEntity.TodayBalanace.ToString("0.00");
                avgIncomeLabel.Text      = predictionEntity.AverageIncome.ToString("0.00");
                avgExpensesLabel.Text    = predictionEntity.AverageExpense.ToString("0.00");

                foreach (DailyBreakDownPredictionEntity dailyBreakDown in predictionEntity.DailyBreakDownPredictions)
                {
                    if (dailyBreakDown.DayOfWeek == DayOfWeek.Monday)
                    {
                        monInLabel.Text  = dailyBreakDown.AverageIncome.ToString("0.00");
                        monOutLabel.Text = dailyBreakDown.AverageExpense.ToString("0.00");
                    }
                    else if (dailyBreakDown.DayOfWeek == DayOfWeek.Tuesday)
                    {
                        tueInLabel.Text  = dailyBreakDown.AverageIncome.ToString("0.00");
                        tueOutLabel.Text = dailyBreakDown.AverageExpense.ToString("0.00");
                    }
                    else if (dailyBreakDown.DayOfWeek == DayOfWeek.Wednesday)
                    {
                        wedInLabel.Text  = dailyBreakDown.AverageIncome.ToString("0.00");
                        wedOutLabel.Text = dailyBreakDown.AverageExpense.ToString("0.00");
                    }
                    else if (dailyBreakDown.DayOfWeek == DayOfWeek.Thursday)
                    {
                        thuInLabel.Text  = dailyBreakDown.AverageIncome.ToString("0.00");
                        thuOutLabel.Text = dailyBreakDown.AverageExpense.ToString("0.00");
                    }
                    else if (dailyBreakDown.DayOfWeek == DayOfWeek.Friday)
                    {
                        friInLabel.Text  = dailyBreakDown.AverageIncome.ToString("0.00");
                        friOutLabel.Text = dailyBreakDown.AverageExpense.ToString("0.00");
                    }
                    else if (dailyBreakDown.DayOfWeek == DayOfWeek.Saturday)
                    {
                        satInLabel.Text  = dailyBreakDown.AverageIncome.ToString("0.00");
                        satOutLabel.Text = dailyBreakDown.AverageExpense.ToString("0.00");
                    }
                    else if (dailyBreakDown.DayOfWeek == DayOfWeek.Sunday)
                    {
                        sunInLabel.Text  = dailyBreakDown.AverageIncome.ToString("0.00");
                        sunOutLabel.Text = dailyBreakDown.AverageExpense.ToString("0.00");
                    }
                }
            }
            else
            {
                MessageBox.Show(predictionEntity.WarningMessage, "Prediction failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            resultGroup.Visible                 = predictionEntity.IsPredicted;
            previousDataComboBox.Enabled        = true;
            predictDateDateTimePicker.Enabled   = true;
            actionsUserControl.IsEnabledButtons = true;
        }
        public async Task <PredictionEntity> GetPredictionsAsync(int monthsBack, DateTime predictDate)
        {
            PredictionEntity predictionEntity = null;

            await Task.Run(() =>
            {
                predictionEntity = new PredictionEntity()
                {
                    WarningMessage = IsAvailableEnoughtData(monthsBack) ? "" : _warningMessage,
                    TodayBalanace  = CurrentUser.CurrentBalance
                };
                IList <DailyBreakDownPredictionEntity> dailyBreakDownPredictions = new List <DailyBreakDownPredictionEntity>();

                predictDate             = predictDate.Date;
                DateTime todayDate      = DateTime.Now;
                todayDate               = todayDate.Date;// Remove time
                DateTime monthsBackDate = todayDate.AddMonths(-1 * monthsBack);

                IEnumerable <TransactionEntity> orderedTransactions = Transactions.Where(t => t.TransactionDateTime >= monthsBackDate && t.IsActive).OrderBy(t => t.TransactionDateTime);

                if (orderedTransactions.Count() > 0)
                {
                    predictionEntity.IsPredicted = true;
                    int daysFromBackMonth        = (int)todayDate.Subtract(monthsBackDate.Date).TotalDays;

                    double totalInCome     = orderedTransactions.Where(ot => ot.IsIncome).Select(ot => ot.Amount).Sum();
                    double totalInExpenses = orderedTransactions.Where(ot => !ot.IsIncome).Select(ot => ot.Amount).Sum();

                    predictionEntity.AverageIncome  = totalInCome / daysFromBackMonth;
                    predictionEntity.AverageExpense = totalInExpenses / daysFromBackMonth;

                    int daysToPredictDate            = (int)predictDate.Subtract(todayDate).TotalDays;
                    predictionEntity.PredictBalanace = CurrentUser.CurrentBalance + ((totalInCome - totalInExpenses) / daysFromBackMonth) * daysToPredictDate;

                    // Day by day predictions
                    IEnumerable <DayOfWeek> daysOfWeek = Enum.GetValues(typeof(DayOfWeek)).Cast <DayOfWeek>();

                    foreach (DayOfWeek dayOfWeek in daysOfWeek)
                    {
                        DailyBreakDownPredictionEntity dailyBreakDown = new DailyBreakDownPredictionEntity()
                        {
                            DayOfWeek = dayOfWeek
                        };

                        IEnumerable <DateTime> dates = TimeConverterMethods.DatesDayOfWeekForDuration(monthsBackDate, todayDate, dayOfWeek);

                        if (dates.Count() > 0)
                        {
                            IEnumerable <TransactionEntity> dayOfWeekIncomeTransactions = orderedTransactions.Where(t => t.IsIncome && dates.Any(d => d.Date == t.TransactionDateTime.Date));
                            dailyBreakDown.AverageIncome = dayOfWeekIncomeTransactions.Select(x => x.Amount).Sum() / dates.Count();

                            IEnumerable <TransactionEntity> dayOfWeekExpensesTransactions = orderedTransactions.Where(t => !t.IsIncome && dates.Any(d => d.Date == t.TransactionDateTime.Date));
                            dailyBreakDown.AverageExpense = dayOfWeekExpensesTransactions.Select(x => x.Amount).Sum() / dates.Count();
                        }
                        else
                        {
                            dailyBreakDown.AverageIncome  = 0;
                            dailyBreakDown.AverageExpense = 0;
                        }

                        dailyBreakDownPredictions.Add(dailyBreakDown);
                    }

                    predictionEntity.DailyBreakDownPredictions = dailyBreakDownPredictions;
                }
                else
                {
                    predictionEntity.IsPredicted    = false;
                    predictionEntity.WarningMessage = "Error: No data found to do the predictions";
                }
            });

            return(predictionEntity);
        }