コード例 #1
0
        public static bool RunSimulation(string home, string away)
        {
            var context    = new AlgoTestContext();
            var leagueRepo = new LeagueRepository(context);

            var result   = PredictEngine.Predict(home, away);
            var FTResult = leagueRepo.GetFTResult(home, away);

            if (FTResult != null)
            {
                total = total + 1;
                if (FTResult == result.predictedValue)
                {
                    correct = correct + 1;
                    Console.WriteLine(result.predictedString + " - correct");
                }

                else
                {
                    Console.WriteLine(result.predictedString + " - wrong");
                }
                return(true);
            }
            return(false);
        }
コード例 #2
0
ファイル: LeagueCreate.cs プロジェクト: plubon/dotNet
        private void saveButton_Click(object sender, EventArgs e)
        {
            if (validate())
            {

                    League newLeague = new League();
                    newLeague.Description = descriptionInput.Text;
                    newLeague.Name = nameInput.Text;
                    newLeague.Discipline = discipline;
                    newLeague.Matches = new List<Match>();
                    var repo = new LeagueRepository();
                    repo.SaveOrUpdate(newLeague);
                    DialogResult result = MetroMessageBox.Show(this, "League created!", "Success!", MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                    if (result == DialogResult.OK)
                    {

                    }

            }
            else
            {
                MetroMessageBox.Show(this, "Sorry, data is not valid.", "Validation error", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                System.Console.Write(discipline.Name);
            }
        }
コード例 #3
0
        public void AddLeagues()
        {
            // Arrange
            var repository = new LeagueRepository();

            var dbContext = A.Fake <ProFootballEntities>();
            var leagues   = new List <League>();

            for (int i = 1; i <= 3; i++)
            {
                var league = new League
                {
                    Name = "League " + i
                };
                leagues.Add(league);
            }
            A.CallTo(() => dbContext.Leagues.AddRange(A <IEnumerable <League> > .Ignored)).Returns(leagues);

            // Act
            var result = repository.AddEntities(dbContext, leagues);

            // Assert
            A.CallTo(() => dbContext.Leagues.AddRange(leagues)).MustHaveHappenedOnceExactly();
            Assert.AreSame(leagues, result);
        }
コード例 #4
0
        public async Task <IPagingModelResponse <LeagueListItemDto> > GetLeaguesAsync(int pageSize = 0, int pageNumber = 0)
        {
            Logger?.LogInformation($"{nameof(GetLeaguesAsync)} has been invoked");

            var response = new PagingModelResponse <LeagueListItemDto>();

            try
            {
                response.PageSize   = pageSize;
                response.PageNumber = pageNumber;

                var query = LeagueRepository.GetItems()
                            .OrderByDescending(entity => entity.CreationDateTime)
                            .AsNoTracking();

                response.ItemCount = await query.CountAsync();

                query = query.Paging(pageSize, pageNumber);

                response.Model = await query.ProjectTo <LeagueListItemDto>().ToListAsync();
            }
            catch (Exception ex)
            {
                response.SetError(ex, Logger);
            }

            return(response);
        }
コード例 #5
0
ファイル: DataLayerTests.cs プロジェクト: plubon/dotNet
        public void AllLeaguesFromApi()
        {
            var repo   = new LeagueRepository();
            var result = repo.GetByDiscipline("Football");

            Assert.IsTrue(result.Count > 0);
        }
コード例 #6
0
        public async Task <ISingleModelResponse <LeagueDto> > GetLeagueAsync(int id)
        {
            Logger?.LogInformation($"{nameof(GetLeagueAsync)} has been invoked");

            var response = new SingleModelResponse <LeagueDto>();

            try
            {
                var item = await LeagueRepository.GetItemByIdAsync(id);

                if (ShouldIncludeAuditData())
                {
                    response.Model = Mapper.Map <LeagueAuditDto>(item);
                }
                else
                {
                    response.Model = Mapper.Map <LeagueDto>(item);
                }
            }
            catch (Exception ex)
            {
                response.SetError(ex, Logger);
            }

            return(response);
        }
コード例 #7
0
        private void PopulateEventComboBox()
        {
            SqlCeConnection Connection = DataBaseConnection.Instance.Connection;


            EventViewComboBox.Items.Clear();
            SqlCeCommand cmd = Connection.CreateCommand();

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT * FROM Event";
            cmd.ExecuteNonQuery();
            DataTable        dt = new DataTable();
            SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);

            da.Fill(dt);

            foreach (DataRow dr in dt.Rows)
            {
                int team1  = Int16.Parse(dr["Team_Id"].ToString());
                int team2  = Int16.Parse(dr["Team_Id1"].ToString());
                int game1  = Int16.Parse(dr["Game_type_Id"].ToString());
                int sport1 = Int16.Parse(dr["Sport_Id"].ToString());
                int leage1 = Int16.Parse(dr["League_Id"].ToString());

                string team11   = TeamRepository.GetTeamNameById(team1);
                string team22   = TeamRepository.GetTeamNameById(team2);
                string game11   = GameTypeRepository.GetGameTypeMarkById(game1);
                string sport11  = SportRepository.GetSportNameById(sport1);
                string league11 = LeagueRepository.GetLeagueNameById(leage1);

                EventViewComboBox.Items.Add(sport11 + " - " + league11 + " - " + team11 + " - " + team22 + " - " + dr["Time"].ToString() + " - " + game11 + " - " + dr["Quota"].ToString() + "KM ");
            }
            EventViewComboBox.SelectedIndex = 0;
        }
コード例 #8
0
ファイル: TeamService.cs プロジェクト: ubongessien007/FLM
        public async Task <IListModelResponse <LeagueDto> > GetTeamLeaguesAsync(int teamId)
        {
            Logger?.LogInformation($"{nameof(GetTeamLeaguesAsync)} has been invoked");

            var response = new ListModelResponse <LeagueDto>();

            try
            {
                var team = await TeamRepository.GetItemByIdAsync(teamId);

                if (team == null)
                {
                    throw new FlmException($"Team with id={teamId} doesn't exist");
                }

                var query = LeagueRepository.GetTeamLeagueAssignments()
                            .Where(assignment => assignment.TeamId == teamId)
                            .Select(assignment => assignment.League);

                response.Model = await query.ProjectTo <LeagueDto>().ToListAsync();
            }
            catch (Exception ex)
            {
                response.SetError(ex, Logger);
            }

            return(response);
        }
コード例 #9
0
ファイル: MatchesController.cs プロジェクト: plubon/dotNet
 public IEnumerable<Match> GetMatchesOfLeague(int id)
 {
     LeagueRepository tmp = new LeagueRepository();
     var league = tmp.GetById(id);
     var qres = _repository.GetAllMatchesOfLeague(league);
     return qres.Select(o => new APIMatch(o)).ToList();
 }
コード例 #10
0
        private void GenerateTourResults()
        {
            int?leagueId = League?.Id;

            if (Tour != null)
            {
                GamesInTour.GenerateResults();
                using (var repository = new GameRepository(DatabaseSourceDefinitor.ConnectionString))
                {
                    repository.UpdateGames(GamesInTour);
                }
                using (var repository = new LeagueRepository(DatabaseSourceDefinitor.ConnectionString))
                {
                    Leagues = repository.GetLeagues();
                }
                League = Leagues.FirstOrDefault(t => t.Id == leagueId);
                Tour   = League.Tours.FirstOrDefault(t => t.Id == Tour.Id);
                using (var repository = new GameRepository(DatabaseSourceDefinitor.ConnectionString))
                {
                    GamesInTour = repository.GetGamesInTour(Tour.Id);
                }
                League.Calculate();
                TeamsStat = League.TeamStats;
            }
        }
コード例 #11
0
        public IEnumerable <Match> GetMatchesOfLeague(int id)
        {
            LeagueRepository tmp = new LeagueRepository();
            var league           = tmp.GetById(id);
            var qres             = _repository.GetAllMatchesOfLeague(league);

            return(qres.Select(o => new APIMatch(o)).ToList());
        }
コード例 #12
0
ファイル: DataLayerTests.cs プロジェクト: plubon/dotNet
 public void GetLeagueById()
 {
     var repo = new LeagueRepository();
     var result = repo.GetByDiscipline("Football");
     int id = 1;
     var x = repo.GetById(1);
     Assert.IsTrue(x.Matches.Count > 0);
 }
コード例 #13
0
        //[TestCase]
        public void TestCase1()
        {
            // Arrange
            var repository = new LeagueRepository();

            // Act

            // Assert
        }
コード例 #14
0
        public async Task <ActionResult> Login(string leagueKey, string hashedPassword)
        {
            //get the league, if not exist return notfound
            var league = await LeagueRepository.GetAsync(leagueKey);

            if (league == null)
            {
                return(new BadRequestObjectResult("failed"));
            }

            //check hashed password matches if not return error
            if (league.HashPassword != hashedPassword)
            {
                return(new BadRequestObjectResult("failed"));
            }

            //generate login key, insert into db
            var token = Guid.NewGuid().ToString();

            var login = new Login();

            login.LeagueId       = league.LeagueId;
            login.LoginTimestamp = DateTime.Now;
            login.Expiry         = DateTime.Now.AddHours(1);
            login.LoginKey       = token;


            if (await LoginExistsForLeague(league.LeagueId))
            {
                try
                {
                    var oldLogin = await this.LoginRepository.GetAsync(league.LeagueId);

                    oldLogin.LoginTimestamp = DateTime.Now;
                    oldLogin.Expiry         = DateTime.Now.AddHours(1);
                    oldLogin.LoginKey       = token;

                    await this.LoginRepository.UpdateAsync(oldLogin);
                }
                catch (Exception ex)
                {
                    // handle somehow
                }
            }
            else
            {
                await this.LoginRepository.AddAsync(login);
            }
            // return login key
            LoginObject loginSuccess = new LoginObject(login);

            loginSuccess.LeagueId   = league.LeagueId;
            loginSuccess.LeagueName = league.LeagueName;
            loginSuccess.LeagueKey  = league.LeagueKey;
            loginSuccess.Logo       = league.Logo;
            return(new OkObjectResult(loginSuccess));
        }
コード例 #15
0
ファイル: DataLayerTests.cs プロジェクト: plubon/dotNet
        public void GetLeagueById()
        {
            var repo   = new LeagueRepository();
            var result = repo.GetByDiscipline("Football");
            int id     = 1;
            var x      = repo.GetById(1);

            Assert.IsTrue(x.Matches.Count > 0);
        }
コード例 #16
0
        public async Task <string> GetLeagueId(string leagueKey)
        {
            var LeagueRepository = new LeagueRepository(this.ConnectionString);
            var league           = await LeagueRepository.GetAsync(leagueKey);

            if (league == null)
            {
                return(null);
            }
            return(league.LeagueId.ToString());
        }
コード例 #17
0
 public UnitOfWork(AppDbContext dbContext, IDistributedCache cache)
 {
     _dbContext = dbContext;
     // Regular implementations inject the context into repositories.
     // However, by doing that the repository would have more control
     // over the context than it would be required.
     // For instance, calling SaveChangesAsync() is not allowed within
     // repositories
     JobRepository    = new CachedJobRepository(new JobRepository(dbContext.Jobs), cache);
     LeagueRepository = new LeagueRepository(dbContext.Leagues);
     TeamRepository   = new TeamRepository(dbContext.Teams);
 }
コード例 #18
0
 public UnitOfWork()
 {
     TeamRepo         = new TeamRepository();
     EventRepo        = new EventRepository();
     EventMessageRepo = new EventMessageRepository();
     MatchRepo        = new MatchRepository();
     PlayerRepo       = new PlayerRepository();
     StadiumRepo      = new StadiumRepository();
     StatiscticRepo   = new StatisticRepository();
     LeagueRepo       = new LeagueRepository();
     RefereeRepo      = new RefereeRepository();
 }
コード例 #19
0
        public void GetLeagues_HappyPath()
        {
            // Arrange
            var dbContext  = A.Fake <ProFootballEntities>();
            var repository = new LeagueRepository(dbContext);

            // Act
            var result = repository.GetEntities();

            // Assert
            Assert.IsInstanceOf <IEnumerable <League> >(result);
        }
コード例 #20
0
ファイル: LeagueModel.cs プロジェクト: manukartofanu/manuger
 private League CreateLeague(int seasonNumber, Country country)
 {
     using (ILeagueRepository repository = new LeagueRepository(DatabaseSourceDefinitor.ConnectionString))
     {
         var league = new League {
             CountryId = country.Id, Season = seasonNumber
         };
         league.Id = (int)repository.InsertLeague(league);
         repository.InsertTeamsIntoLeague(league.Id, GetTeamsOfCountry(country.Id));
         return(league);
     }
 }
コード例 #21
0
        private void SaveButton_Click(object sender, EventArgs e)
        {
            if (NameLeagueTextBox.Text == "")
            {
                MessageBox.Show("Unesite vrstu lige!");
            }

            else
            {
                string text = NameLeagueTextBox.Text;
                LeagueRepository.AddLeague(text);
            }
        }
コード例 #22
0
        public void EditLeague_ExceptionCaught_LogsAndRethrowsException()
        {
            // Arrange
            var dbContext  = A.Fake <ProFootballEntities>();
            var repository = new LeagueRepository(dbContext);

            var league = new League();

            A.CallTo(() => dbContext.SetModified(A <League> .Ignored)).Throws <Exception>();

            // Act & Assert
            Assert.Throws <Exception>(() => repository.EditEntity(league));
        }
コード例 #23
0
        private void SaveButton_Click(object sender, EventArgs e)
        {
            SqlCeConnection Connection = DataBaseConnection.Instance.Connection;

            try
            {
                if (QuotaTextBox.Text == "")
                {
                    MessageBox.Show("Uneste iznos kvote!");
                }
                else if (EventDateTimePicker.Text == "")
                {
                    MessageBox.Show("Unesite vrijeme dogadjaja!");
                }

                else
                {
                    int SportID    = SportRepository.GetIdByNameSport(SportIDComboBox.Text);
                    int TeamID     = TeamRepository.GetIdByNameTeam(TeamIDComboBox.Text);
                    int LeagueID   = LeagueRepository.GetIdByNameLeague(LeagueIDComboBox.Text);
                    int GameTypeID = GameTypeRepository.GetIdByNameGameType(GameTypeIDComboBox.Text);
                    int TeamID1    = TeamRepository.GetIdByNameTeam(TeamID1ComboBox.Text);


                    SqlCeCommand command1 = new SqlCeCommand("INSERT INTO Event (Sport_Id, Team_Id, Time, League_Id, Game_type_Id, Quota, Team_Id1) VALUES" + " ('" + SportID + "', '" + TeamID + "', '" + EventDateTimePicker.Value.Date.ToString("yyyy-MM-dd") + "', '" + LeagueID + "', '" + GameTypeID + "',  '" + QuotaTextBox.Text + "',  '" + TeamID1 + "'); ", Connection);


                    /*SqlCeCommand command1 = new SqlCeCommand(@"INSERT INTO Event (Sport_Id, Team_Id, Time, League_Id, Game_type_Id, Quota, Team_Id1) VALUES (@sportId, @teamId, @time, @leagueId, @gameTypeId, @quota, @teamId1)", Connection);
                     * command1.Parameters.AddWithValue("@sportId", SportID);
                     * command1.Parameters.AddWithValue("@teamId", TeamID);
                     * command1.Parameters.AddWithValue("@time", DateTime.Now.Date.ToString());
                     * command1.Parameters.AddWithValue("@leagueId", LeagueID);
                     * command1.Parameters.AddWithValue("@gameTypeId", GameTypeID);
                     * command1.Parameters.AddWithValue("@quota", QuotaTextBox.Text);
                     * command1.Parameters.AddWithValue("@teamId1", TeamID1);*/


                    command1.ExecuteNonQuery();
                    MessageBox.Show("Unos je uspio!");
                    QuotaTextBox.Clear();
                    QuotaTextBox.Focus();
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("Unos nije uspio! \r Greska: " + ex.Message);
                return;
            }
        }
コード例 #24
0
        public void EditLeague_HappyPath()
        {
            // Arrange
            var dbContext  = A.Fake <ProFootballEntities>();
            var repository = new LeagueRepository(dbContext);

            var league = new League();

            // Act
            repository.EditEntity(league);

            // Assert
            A.CallTo(() => dbContext.SetModified(league)).MustHaveHappenedOnceExactly();
        }
コード例 #25
0
        public async Task GetLeaguesAsync()
        {
            // Arrange
            var repository = new LeagueRepository();

            var dbContext = A.Fake <ProFootballEntities>();

            dbContext.SetUpFakeLeaguesAsync();

            // Act
            var result = await repository.GetEntitiesAsync(dbContext);

            // Assert
            Assert.IsInstanceOf <IEnumerable <League> >(result);
        }
コード例 #26
0
        public UnitOfWork()
        {
            Platform     = DBManager.GetPlatform();
            DatabasePath = DBManager.GetDatabasePath();

            TeamRepo         = new TeamRepository(Platform, DatabasePath, ImageManager);
            EventRepo        = new EventRepository(Platform, DatabasePath);
            EventMessageRepo = new EventMessageRepository(Platform, DatabasePath);
            MatchRepo        = new MatchRepository(Platform, DatabasePath);
            PlayerRepo       = new PlayerRepository(Platform, DatabasePath);
            StadiumRepo      = new StadiumRepository(Platform, DatabasePath);
            StatiscticRepo   = new StatisticRepository(Platform, DatabasePath);
            LeagueRepo       = new LeagueRepository(Platform, DatabasePath);
            RefereeRepo      = new RefereeRepository(Platform, DatabasePath);
        }
コード例 #27
0
        public void CreateLeague_HappyPath()
        {
            // Arrange
            var dbContext  = A.Fake <ProFootballEntities>();
            var repository = new LeagueRepository(dbContext);

            A.CallTo(() => dbContext.Leagues.Create()).Returns(new League());

            // Act
            var result = repository.CreateEntity();

            // Assert
            A.CallTo(() => dbContext.Leagues.Create()).MustHaveHappenedOnceExactly();
            Assert.IsInstanceOf <League>(result);
        }
コード例 #28
0
        public void CreateLeague_ExceptionCaught_LogsAndRethrowsException()
        {
            // Arrange
            var dbContext  = A.Fake <ProFootballEntities>();
            var repository = new LeagueRepository(dbContext);

            A.CallTo(() => dbContext.Leagues.Create()).Throws <Exception>();

            // Act
            League result = null;

            Assert.Throws <Exception>(() => result = repository.CreateEntity());

            // Assert
            Assert.IsNull(result);
        }
コード例 #29
0
        public void GetLeagues_ExceptionCaught_LogsAndRethrowsException()
        {
            // Arrange
            var dbContext  = A.Fake <ProFootballEntities>();
            var repository = new LeagueRepository(dbContext);

            A.CallTo(() => dbContext.Leagues).Throws <Exception>();

            // Act
            IEnumerable <League> result = null;

            Assert.Throws <Exception>(() => result = repository.GetEntities());

            // Assert
            Assert.IsNull(result);
        }
コード例 #30
0
        //[TestCase]
        public void TestCase1()
        {
            // Arrange
            var dbContext  = A.Fake <ProFootballEntities>();
            var repository = new LeagueRepository(dbContext);

            // TODO: Define argument variables of method under test.

            // TODO: Set up needed infrastructure of class under test.

            // Act
            // TODO: Call method under test.

            // Assert
            // TODO: Assert results of call to method under test.
        }
コード例 #31
0
        private async Task <League> GetAndValidateItem(int leagueId, byte?roundNum = null)
        {
            var league = await LeagueRepository.GetItemByIdAsync(leagueId);

            if (league == null)
            {
                throw new FlmException($"League with id={leagueId} doesn't exist");
            }

            if (roundNum.HasValue && league.RoundsCount < roundNum)
            {
                throw new FlmException($"League {league.GetDisplayName()} has only {league.RoundsCount} rounds");
            }

            return(league);
        }
コード例 #32
0
        public void RemoveLeague_HappyPath()
        {
            // Arrange
            var dbContext  = A.Fake <ProFootballEntities>();
            var repository = new LeagueRepository(dbContext);

            var league = new League();

            A.CallTo(() => dbContext.Leagues.Remove(A <League> .Ignored)).Returns(league);

            // Act
            var result = repository.RemoveEntity(league);

            // Assert
            A.CallTo(() => dbContext.Leagues.Remove(league)).MustHaveHappenedOnceExactly();
            Assert.AreSame(league, result);
        }
コード例 #33
0
        public void AddLeagues_HappyPath()
        {
            // Arrange
            var dbContext  = A.Fake <ProFootballEntities>();
            var repository = new LeagueRepository(dbContext);

            var leagues = new List <League>();

            A.CallTo(() => dbContext.Leagues.AddRange(A <IEnumerable <League> > .Ignored)).Returns(leagues);

            // Act
            var result = repository.AddEntities(leagues);

            // Assert
            A.CallTo(() => dbContext.Leagues.AddRange(leagues)).MustHaveHappenedOnceExactly();
            Assert.AreSame(leagues, result);
        }
コード例 #34
0
ファイル: Program.cs プロジェクト: CallumVass/AlgoTest
        public static bool RunSimulation(string home, string away)
        {
            var context = new AlgoTestContext();
            var leagueRepo = new LeagueRepository(context);

            var result = PredictEngine.Predict(home, away);
            var FTResult = leagueRepo.GetFTResult(home, away);
            if (FTResult != null)
            {
                total = total + 1;
                if (FTResult == result.predictedValue)
                {
                    correct = correct + 1;
                    Console.WriteLine(result.predictedString + " - correct");
                }

                else
                {
                    Console.WriteLine(result.predictedString + " - wrong");
                }
                return true;
            }
            return false;
        }
コード例 #35
0
ファイル: DataLayerTests.cs プロジェクト: plubon/dotNet
 public void AllLeaguesFromApi()
 {
     var repo = new LeagueRepository();
     var result = repo.GetByDiscipline("Football");
     Assert.IsTrue(result.Count>0);
 }
コード例 #36
0
ファイル: PredictEngine.cs プロジェクト: CallumVass/AlgoTest
        public static predictObject Predict(string home, string away)
        {
            var context = new AlgoTestContext();
            var leagueRepo = new LeagueRepository(context);

            var overallForm = "";
            var homeForm = "";
            var awayForm = "";

            var overallHome = leagueRepo.LoadTeam(home);
            var overallAway = leagueRepo.LoadTeam(away);
            var hometeam = leagueRepo.LoadHomeTeam(home);
            var awayteam = leagueRepo.LoadAwayTeam(away);
            var h2h = leagueRepo.H2H(home, away);

            var league = overallHome[0].League;
            var shotStatsHome = Program.homeShots;
            var shotStatsAway = Program.awayShots;

            var homeShotStatsListO = shotStatsHome.OrderBy(x => x.OffensiveRatio).ToList();
            var homeShotStatsListD = shotStatsHome.OrderByDescending(x => x.DefensiveRatio).ToList();
            var awayShotStatsListO = shotStatsAway.OrderBy(x => x.OffensiveRatio).ToList();
            var awayShotStatsListD = shotStatsAway.OrderByDescending(x => x.DefensiveRatio).ToList();

            //var homeShotStats = homeShotStatsList.FirstOrDefault(x => x.Team.ToLower().Contains(home.ToLower()));
            //var awayShotStats = awayShotStatsList.FirstOrDefault(x => x.Team.ToLower().Contains(away.ToLower()));

            #region Home Team (Home Form)

            foreach (var stats in hometeam)
            {
                var r = "";

                switch (stats.FTResult)
                {
                    case "H":
                        r = "W";
                        break;
                    case "A":
                        r = "L";
                        break;
                    default:
                        r = "D";
                        break;
                }

                homeForm = homeForm + r;
            }

            var homeValues = homeForm.ToCharArray();
            var homeTeamFormValue = 0;

            foreach (var val in homeValues)
            {
                if (val.ToString() == "W")
                {
                    homeTeamFormValue = homeTeamFormValue + 3;
                }
                if (val.ToString() == "D")
                {
                    homeTeamFormValue = homeTeamFormValue + 1;
                }
            }

            #endregion

            #region Away Team (Away Form)

            foreach (var stats in awayteam)
            {
                var r = "";
                switch (stats.FTResult)
                {
                    case "A":
                        r = "W";
                        break;
                    case "H":
                        r = "L";
                        break;
                    default:
                        r = "D";
                        break;
                }
                awayForm = awayForm + r;
            }

            var awayValues = awayForm.ToCharArray();
            var awayTeamFormValue = 0;

            foreach (var val in awayValues)
            {
                if (val.ToString() == "W")
                {
                    awayTeamFormValue = awayTeamFormValue + 3;
                }
                if (val.ToString() == "D")
                {
                    awayTeamFormValue = awayTeamFormValue + 1;
                }
            }

            #endregion

            #region Home Team (Overall Form)

            foreach (var stats in overallHome)
            {
                var r = "D";

                if (stats.Location == "H")
                {
                    if (stats.FTResult == "H")
                    {
                        r = "W";
                    }
                    if (stats.FTResult == "A")
                    {
                        r = "L";
                    }
                }
                if (stats.Location == "A")
                {
                    if (stats.FTResult == "H")
                    {
                        r = "L";
                    }
                    if (stats.FTResult == "A")
                    {
                        r = "W";
                    }
                }

                overallForm = overallForm + r;
            }

            var homeOverallValues = overallForm.ToCharArray();
            var homeTeamOverallFormValue = 0;

            foreach (var val in homeOverallValues)
            {
                if (val.ToString() == "W")
                {
                    homeTeamOverallFormValue = homeTeamOverallFormValue + 3;
                }
                if (val.ToString() == "D")
                {
                    homeTeamOverallFormValue = homeTeamOverallFormValue + 1;
                }
            }

            #endregion

            #region Away Team (Overall Form)

            overallForm = "";
            foreach (var stats in overallAway)
            {
                var r = "D";

                if (stats.Location == "H")
                {
                    if (stats.FTResult == "H")
                    {
                        r = "W";
                    }
                    if (stats.FTResult == "A")
                    {
                        r = "L";
                    }
                }
                if (stats.Location == "A")
                {
                    if (stats.FTResult == "H")
                    {
                        r = "L";
                    }
                    if (stats.FTResult == "A")
                    {
                        r = "W";
                    }
                }

                overallForm = overallForm + r;
            }

            var awayOverallValues = overallForm.ToCharArray();
            var awayTeamOverallFormValue = 0;

            foreach (var val in awayOverallValues)
            {
                if (val.ToString() == "W")
                {
                    awayTeamOverallFormValue = awayTeamOverallFormValue + 3;
                }
                if (val.ToString() == "D")
                {
                    awayTeamOverallFormValue = awayTeamOverallFormValue + 1;
                }
            }

            #endregion

            #region HeadToHead

            var homeh2hTotal = 0.0;
            var awayh2hTotal = 0.0;

            foreach (var val in h2h)
            {
                if (val.GoalsFor > val.GoalsAgainst)
                {
                    homeh2hTotal = homeh2hTotal + 3;
                }
                else if (val.GoalsFor == val.GoalsAgainst)
                {
                    homeh2hTotal = homeh2hTotal + 1;
                    awayh2hTotal = awayh2hTotal + 1;
                }
                else
                {
                    awayh2hTotal = awayh2hTotal + 3;
                }
            }

            #endregion

            #region HomeTeam (Goals Scored/Conceded)

            var homeGoalsFor = overallHome.Sum(x => x.GoalsFor);
            var homeGoalsAgainst = overallHome.Sum(x => x.GoalsAgainst);

            #endregion

            #region AwayTeam (Goals Scored/Conceded)

            var awayGoalsFor = overallAway.Sum(x => x.GoalsFor);
            var awayGoalsAgainst = overallAway.Sum(x => x.GoalsAgainst);

            #endregion

            #region Shot stats and conversion rates (Home)

            var offensiveRankH = 0;
            var defensiveRankH = 0;
            var normalisedOffensiveHome = 10;
            var normalisedDefensiveHome = 10;

            for (int i = 0; i < homeShotStatsListO.Count(); i++)
            {
                if (homeShotStatsListO[i].Team.ToLower().Contains(home.ToLower()))
                {
                    offensiveRankH = normalisedOffensiveHome;
                }
                if ((i + 1) % 2 == 0)
                {
                    normalisedOffensiveHome = normalisedOffensiveHome - 1;
                }
            }

            for (int i = 0; i < homeShotStatsListD.Count(); i++)
            {
                if (homeShotStatsListD[i].Team.ToLower().Contains(home.ToLower()))
                {
                    defensiveRankH = normalisedDefensiveHome;
                }
                if ((i + 1) % 2 == 0)
                {
                    normalisedDefensiveHome = normalisedDefensiveHome - 1;
                }
            }

            #endregion

            #region Shot stats and conversion rates (Away)

            var offensiveRankA = 0;
            var defensiveRankA = 0;
            var normalisedOffensiveAway = 10;
            var normalisedDefensiveAway = 10;

            for (int i = 0; i < awayShotStatsListO.Count(); i++)
            {
                if (awayShotStatsListO[i].Team.ToLower().Contains(away.ToLower()))
                {
                    offensiveRankA = normalisedOffensiveAway;
                }
                if ((i + 1) % 2 == 0)
                {
                    normalisedOffensiveAway = normalisedOffensiveAway - 1;
                }
            }

            for (int i = 0; i < awayShotStatsListD.Count(); i++)
            {
                if (awayShotStatsListD[i].Team.ToLower().Contains(away.ToLower()))
                {
                    defensiveRankA = normalisedDefensiveAway;
                }
                if ((i + 1) % 2 == 0)
                {
                    normalisedDefensiveAway = normalisedDefensiveAway - 1;
                }
            }

            #endregion

            #region Calculations

            var homeTotal = 0.0;
            var awayTotal = 0.0;
            var homePct = 0.0;
            var awayPct = 0.0;
            var homeGoalValue = 0.0;
            var awayGoalValue = 0.0;
            var resultString = "";

            if (homeGoalsFor > awayGoalsFor)
            {
                homeGoalValue = homeGoalValue + 2;
            }
            else if (homeGoalsFor == awayGoalsFor)
            {
                homeGoalValue = homeGoalValue + 1;
                awayGoalValue = awayGoalValue + 1;
            }
            else
            {
                awayGoalValue = awayGoalValue + 2;
            }

            if (homeGoalsFor > homeGoalsAgainst)
            {
                homeGoalValue = homeGoalValue + 1;
            }

            if (awayGoalsFor > awayGoalsAgainst)
            {
                awayGoalValue = awayGoalValue + 1;
            }

            var h2hMax = (h2h.Count * 3);
            if (h2h.Count > 0)
            {
                homeh2hTotal = (homeh2hTotal / h2hMax) * 10;
                awayh2hTotal = (awayh2hTotal / h2hMax) * 10;
            }
            else
            {
                homeh2hTotal = 0;
                awayh2hTotal = 0;
            }

            var homeTeamStatScore = (Convert.ToDouble(offensiveRankH + defensiveRankH)) / 2;
            var awayTeamStatScore = (Convert.ToDouble(offensiveRankA + defensiveRankA)) / 2;

            homeTotal = (Convert.ToDouble(homeTeamFormValue + homeTeamOverallFormValue) / 3) + (homeGoalValue * 2) + (homeh2hTotal * 0.75) + (homeTeamStatScore * 0.20);
            awayTotal = (Convert.ToDouble(awayTeamFormValue + awayTeamOverallFormValue) / 3) + (awayGoalValue * 2) + (awayh2hTotal * 0.75) + (awayTeamStatScore * 0.20);

            homePct = (homeTotal / (homeTotal + awayTotal)) * 100;
            awayPct = (awayTotal / (homeTotal + awayTotal)) * 100;

            if (homePct >= 54.5)
            {
                resultString = "Home Win";
            }
            else if (awayPct >= 54.5)
            {
                resultString = "Away Win";
            }
            else
            {
                resultString = "Draw";
            }

            #endregion

            var result = string.Format("{0} ({1}%) vs {2} ({3}%): {4}", home, Math.Round(homePct, 2), away, Math.Round(awayPct, 2), resultString);

            var returnObject = new predictObject
            {
                predictedString = result,
                predictedValue = resultString[0].ToString()
            };

            return returnObject;
        }
コード例 #37
0
ファイル: Program.cs プロジェクト: CallumVass/AlgoTest
        static void Main(string[] args)
        {
            const string directory = @"C:\Users\dean.mcgarrigle\Dropbox\public\FootballData";
            const string fixtures = @"C:\Users\dean.mcgarrigle\Dropbox\public\FootballData\fixturelist.csv";

            Console.WriteLine("Which league do you want to simulate?");
            var division = Console.ReadLine();
            var context = new AlgoTestContext();
            var leagueRepo = new LeagueRepository(context);
            var csvHandler = new CsvHandler<LeagueData, LeagueDataMap>();

            homeShots = leagueRepo.LeagueShotStatsHome().Where(x => x.League == division.ToUpper()).ToList();
            awayShots = leagueRepo.LeagueShotStatsAway().Where(x => x.League == division.ToUpper()).ToList();

            var input = Options();
            if (input == "download")
            {
                Console.WriteLine("Please select a season to download (1516 etc): ");
                var season = Console.ReadLine();
                var leagues = new[] { "E0", "E1", "E2", "E3", "EC" };
                var fileUrl = string.Format("http://www.football-data.co.uk/mmz4281/{0}", season);
                foreach (var league in leagues)
                {
                    var results = csvHandler.DownloadFile(string.Format("{0}/{1}.csv", fileUrl, league)).Result;
                    foreach (var result in results)
                    {
                        leagueRepo.AddFixture(result);
                        Console.WriteLine("Adding Fixture: " + result.HomeTeam + " v " + result.AwayTeam);
                    }
                }

                context.SaveChanges();
                Console.WriteLine("Added fixtures");
                Options();

            }

            if (input == "2")
            {
                string[] teams = File.ReadAllLines(fixtures);
                var query = from line in teams
                            let data = line.Split(',')
                            select new HeadToHead()
                            {
                                Home = data[0],
                                Away = data[1],
                            };
                foreach (var a in query.Take(130).Reverse().Take(100).Reverse())
                {
                    if (!RunSimulation(a.Home, a.Away)) break;
                }
                accuracy = Convert.ToDouble(correct)/Convert.ToDouble(total)*100;
                Console.WriteLine("Simulation was "+ accuracy + "% accurate");
                Options();

            }

            if (input == "1")
            {
                Run();
            }

            if (input == "4")
            {
                RunSimulation("Watford", "Man United");
                Options();
            }
        }