def sim_run(filename, teams=None): print(f"Running sim for {filename}...") tic = time.perf_counter() if teams is None: teams = DEFAULT_TEAMS team_records = dict() teams = [copy_team(team) for team in teams] league = League(teams) num_years = args.y league.run_years(num_years) for team in league.teams: team_records[team.name] = team.records with open(f"{filename}", "w") as outfile: json.dump({'teams': team_records}, outfile) print( f"Sim for {filename} complete in {time.perf_counter() - tic:0.3f} seconds" )
def __init__(self): logging.debug("In DDPL constructor") self.__standings = dict() self.__postseason = dict() League.__init__(self, 'DDPL') pc = Conference('Piler') pc.setColors('black', 'blue') fc = Conference('Fornicator') fc.setColors('black', 'red') self.addChild(pc) self.addChild(fc) pc.addChild(Team('Beaners', 'BE')) pc.addChild(Team('Brains', 'BR')) pc.addChild(Team('CM All-Stars', 'CM')) pc.addChild(Team('Cuban Prostitutes', 'CP')) pc.addChild(Team('Hairy Palms', 'HP')) pc.addChild(Team('Umbrellas', 'UM')) fc.addChild(Team('Charlies', 'CH')) fc.addChild(Team('Dictators', 'DI')) fc.addChild(Team('La Players', 'LP')) fc.addChild(Team('Raw Doggers', 'RD')) fc.addChild(Team('Rusty Trombones', 'RT')) fc.addChild(Team('Sausage Milkers', 'SM'))
def test_paired_points(self): eng_dao_16_17 = DAO(country="england", season="16-17", cols="sport_cols") eng_league = League(eng_dao_16_17) eng_league_anl = LeagueAnalysis(league=eng_league) n_round = 18 five_dates = [eng_league.date_by_round(round_n) for round_n in range(n_round - 4, n_round + 1)] date1 = five_dates[0] date2 = five_dates[-1] df1 = eng_league.table(to_date=date1) df2 = eng_league.table(to_date=date2) # Chelsea 34 46 Chelsea # Arsenal 31 40 Liverpool # Liverpool 30 39 Man City # Man City 30 37 Arsenal # Tottenham 27 36 Tottenham points1, points2 = eng_league_anl.paired_points(df1, df2, n_head=5) self.assertEqual(points1.tolist(), [34, 31, 30, 30, 27]) self.assertEqual(points2.tolist(), [46, 37, 40, 39, 36])
def setUp(self): #testing reference http://www.zerozero.pt/edition.php?jornada_in=19&id_edicao=86785&fase=81592 eng_dao_15_16 = DAO(country="england", season="15-16", cols="sport_cols") self.league = League(eng_dao_15_16) spa_dao_15_16 = DAO(country="spain", season="15-16", cols="sport_cols") self.league_spa = League(spa_dao_15_16)
def get_league(file_name): try: file = open(join("json", file_name)) json_data = json.load(file) file.close() return League.get_from_json(json_data) except FileNotFoundError: return League(settings.LEAGUE_NAME)
def __init__(self): # Creat league and do a draft league = League() league.doDraft() self.teams = league.final_teams # Initialize points with zeros self.teamScores = {} for team in self.teams: self.teamScores[team.name] = 0
def read_data(file_name, year): """ read_data -> reads league's informatin from file :param file_name: Name of file to read data from :param year: Year of the league :return: League Class Object """ teams = [] weeks_and_matches = [] # Open File in read mode with open(file_name, "r") as file_stream: for each_line in file_stream.readlines(): # Capture each line of file # Look for a line containing table word with ( : ) character following it if each_line.find("table") > -1 and each_line.find(":") > -1: # Look for the begining of table get_list_str = each_line[each_line.find("[") + 1:each_line.find("]")] # Retrieve Teams name for names in get_list_str.split(): names = names.strip(",") if names.find("'") > -1: # Append team object to teams list teams.append(Team(names.strip("'"))) elif names.find('"') > -1: # Append team object to teams list teams.append(Team(names.strip('"'))) # Look for lines containing week word with ( : ) character following it if each_line.find("week") > -1 and each_line.find(":") > -1: # Append Week matches and it's number to list weeks_and_matches.append([ # Number of week each_line[:each_line.find(":")].strip("week").split()[0], # Match of week each_line[each_line.find(":") + 1:].strip("\n"), ]) # Create week objects list_of_weeks = [] for i in range(int(len(teams) * (len(teams) - 1) / 2)): list_of_weeks.append(Weeks(i)) # Add matches to weeks for object in weeks_and_matches: list_of_weeks[int(object[0]) - 1].add_match(Match(object[1])) # Create League object league_object = League(teams, year) # Add weeks to League object for object_of_week in list_of_weeks: league_object.add_week(object_of_week) return league_object
class AllFeatures: def __init__(self): self.label_pickle = os.path.join(PICKLE_DIR, '{:d}_labels.pkl') self.feature_pickle = os.path.join(PICKLE_DIR, '{:d}_features.pkl') self._db = DataHandler() self.league = League() def build_features(self): for season in range(FIRST_SEASON, 2015): self.features_and_labels(season) def features_and_labels(self, season): feature_pickle = self.feature_pickle.format(season) label_pickle = self.label_pickle.format(season) if os.path.exists(feature_pickle) and os.path.exists(label_pickle): return pickle.load(open(feature_pickle)), pickle.load( open(label_pickle)) with self._db.connector() as cur: cur.execute( """SELECT daynum, wteam, lteam FROM regular_season_compact_results WHERE season = ?""", (season, )) features = [] labels = [] print(season) for j, row in enumerate(cur): print(j) wteam = self.league.data(row['wteam']) lteam = self.league.data(row['lteam']) game_features = team_features(wteam, lteam, season, row['daynum']) if game_features: w_pagerank = self.league.strength(wteam.id, season, row['daynum']) l_pagerank = self.league.strength(lteam.id, season, row['daynum']) line = self.league.pointspread(season, wteam.id, lteam.id, row['daynum']) features.append(game_features + [w_pagerank, l_pagerank, line]) labels.append(1) features.append( team_features(lteam, wteam, season, row['daynum']) + [l_pagerank, w_pagerank, -line]) labels.append(0) pickle.dump(features, open(feature_pickle, 'w')) pickle.dump(labels, open(label_pickle, 'w')) return features, labels @staticmethod def clean(): list(map(os.remove, glob.glob(os.path.join(PICKLE_DIR, "*"))))
def main(): league = League(players=[ agents.ProximityRandomPlayer(name='proximity'), agents.RandomPlayer(name='random'), ]) league.play_games(number_of_games=100000, turns_per_game=40) print(league) print(league.games) datagen = DataGenerator(league.games) datagen.generate(save_folder='data')
def __init__(self, token_file, dev=False): """ Not only does it represent a client connection to the discord server, but it also initializes the used api tokens and a representation of the League client by generating a League object. :param str token_file: location of the token file containing the api tokens :type token_file: str :param dev: allows the bot to start in a development environment with a separate discord bot token :type dev: bool :returns: GanjaClient -- the GanjaClient object acting as the discord client """ super(GanjaClient, self).__init__() with open(token_file) as f: data = json.load(f) self.server_token = data['token'] self.dev_token = data['dev_token'] self.wolfram = data['wolfram_token'] open_token = data['open_league_token'] riot_token = data['league_token'] self.database = '.databases/' self.http_header = {'User-Agent': 'Mozilla/5.0', 'Accept': 'text/html,application/json'} self.list_commands = {} self.voice = None self.player = None self.last_channel = None self.queue = Queue() self.queue_name = Queue() self.league = League(open_token, riot_token, self.http_header) for i in os.listdir('data'): with open('data/' + i) as f: lines = f.read().splitlines() self.list_commands[i] = lines if dev: self.token = self.dev_token else: self.token = self.server_token
def createLeague(): """Creates a league object and fills it with all the nfl teams""" league = League() for team in teams: league.teams.append(Team(team)) return league
def test_points_corr(self): eng_dao_16_17 = DAO(country="england", season="16-17", cols="sport_cols") eng_league = League(eng_dao_16_17) eng_league_anl = LeagueAnalysis(league=eng_league) n_round = 18 date1 = "2016-12-28" table_df1 = eng_league.table(to_date=date1) corr1 = eng_league_anl.points_corr(df_tables=[table_df1, table_df1], method="spearman", n_head=10) self.assertLess(0.98, corr1[0]) date2 = "2016-12-05" table_df2 = eng_league.table(to_date=date2) corr2 = eng_league_anl.points_corr(df_tables=[table_df1, table_df2], method="spearman", n_head=5) self.assertLess(0.665, corr2[0]) self.assertGreater(0.669, corr2[0])
def main(): stats = [] print("Starting MC Simulation...") for i in range(0, N): if i % 1000 == 0 and i > 0: print("Compeleted %i of %i iterations" % (i, N)) league = League() league.doDraft() leagueStats = LeagueStats(league) stats.append(leagueStats) print("Finished MC Simulation.") aggregateStats(stats)
def __init__(self, league_path, game_path): self.league = League(league_path) self.games = [] self.current_game = 0 with open(game_path, 'r') as f: for line in f: data = line.split(',') self.games.append( Game(data[0], data[1], data[2], int(data[3]), int(data[4])))
def makeLeague(self): fieldsFilled = False # Check to see if all the fields were filled out # Correct indices for incorrect label if(not self.creationBoo): if(not self.currentWidgets[6].get() == ""): if(not self.currentWidgets[8].get() == ""): fieldsFilled = True if(fieldsFilled): # Make the league object, save it, send the user to the viewLeague page, and set creationBoo to True league = League(self.currentWidgets[6].get(), self.currentWidgets[8].get()) dat.saveLeague(league) self.creationBoo = True self.currentObject = league self.objectView = True self.viewLeague() else: # Deny the user, and send them back to createTeam with the error message. self.creationBoo = False self.createLeague() else: if(not self.currentWidgets[5].get() == ""): if(not self.currentWidgets[7].get() == ""): fieldsFilled = True if(fieldsFilled): # Make the league object, save it, send the user to the viewLeague page, and set creationBoo to True self.creationBoo = True league = League(self.currentWidgets[5].get(), self.currentWidgets[7].get()) dat.saveLeague(league) self.currentObject = league self.objectView = True self.viewLeague() else: # Deny the user, and send them back to createTeam with the error message self.creationBoo = False self.createLeague()
def get_alts(file_name): alts = {} for line in get_lines(file_name): if line: # League.get_check_str removes punctuation and spaces / capitalizes names = [League.get_check_str(n) for n in line.split(" ")] for n in names[1:]: alts[n] = names[0] return alts
def test5_League(self): t51 = Team("Sevilla") t52 = Team("Valencia") t53 = Team("Barcelona") t54 = Team("Cadiz") m51 = Match(" Sevilla 3 - 1 Valencia ") m52 = Match(" Barcelona 0 - 1 Cadiz ") m53 = Match("Valencia 0 - 2 Barcelona ") m54 = Match(" Cadiz 4 - 3 Sevilla") w51 = Weeks(1) w51.add_match(m51) w51.add_match(m52) w52 = Weeks(2) w52.add_match(m53) w52.add_match(m54) l5 = League([t52, t53, t51, t54], 1395) l5.add_week(w51) l5.add_week(w52) self.assertEqual(l5.all_standing[1][3].gd, -2) self.assertEqual(l5.all_standing[2][2].pts, 3)
def league(self): """ Fetches the whole league, including each team's current lineup and yearly stats :return: League - the whole league """ stats = self.year_stats() teams = [] for team_id, lineup in stats.items(): t = Team(team_id, lineup, stats.get(team_id)) teams.append(t) return League(teams)
def main(): newTeam = Team("Colts") newLeague = League("NFL", "Football") anotherTeam = Team("Steelers") anotherLeague = League("MLS", "Soccer") #saveLeague(newLeague) #saveLeague(anotherLeague) #removeLeague(newLeague.name) newLeague.addTeam("Colts") #saveLeague(newLeague) #removeLeague(anotherLeague.name) anotherLeague.addTeam("LA Galaxy") #saveLeague(anotherLeague) print(newLeague.getTeamNames())
def getAllLeagues(self): query = "SELECT * FROM leagues;" if not self.connection: return False cur = self.connection.cursor() cur.execute(query) self.connection.commit() result = [] for record in cur.fetchall(): l = League.fromDB(record) result.append(l) cur.close() return result
def test_range_points_spread(self): spain_dao = DAO(country="spain", season="16-17", cols="sport_cols") league = League(spain_dao) league_anl = LeagueAnalysis(league=league) dates = ['2016/11/28', '2016/12/05', '2016/12/12', '2016/12/19', '2017/01/09', '2017/01/16', '2017/01/22'] # for date in dates: # print() # print(league.table(to_date=date)) range_points_spread = league_anl.range_points_spread(dates=dates, top_n_clubs=6) self.assertEqual([11, 11, 12, 9, 11, 9, 12], range_points_spread)
def fetch_league(self, instance): # 1086064 # TODO: What if league fetch fails if self.preauthenticated.text: _, username, password, league_id, swid, espn_s2 = login[ login['id'] == self.preauthenticated.text].values[0] self.league = League( league_id, year, username, password, swid, espn_s2) # Fetch league from input information else: # self.username.text: print(self.username.text) league_id = int(self.leagueId.text) username = self.username.text password = self.password.text self.league = League( league_id, year, username, password) # Fetch league from input information self.fetchLeagueButton.text = "League Fetched!" self.remove_widget( self.login) # Remove the login information from the screen self.remove_widget( self.fetchLeagueButton) # Remove the fetchLeagueButton # Create the league info and stats buttons widget self.infoAndStats = GridLayout() self.infoAndStats.cols = 1 leagueName = Label(text="League Name: " + self.league.settings['name']) self.infoAndStats.add_widget( leagueName ) # Add the league name as a label to the (now) top of the screen self.add_widget(self.infoAndStats) self.add_stats() return
def generate_league_object(self) -> League: """ Calls other methods of this class in order to build a League object that holds all of the necessary Game, Player, and Team objects needed to accurately hold data for all games played in the NBA provided by the JSON files. Returns ------- League The league object that holds all of the data for each NBA game. """ seasons_dict: Dict[str, List[Dict[Any, Any]]] = dict() for game in self.games: seasons_dict.setdefault(game.season, list()) seasons_dict[game.season].append(game) return League(seasons_dict)
def mlb_1989(): ab = 142821 hits = 36293 doubles = 6307 triples = 868 homeruns = 3083 singles = hits - (doubles + triples + homeruns) walks = 13528 pa = ab + walks return League(name='MLB1989', walk=walks / pa, single=singles / pa, double=doubles / pa, triple=triples / pa, homerun=homeruns / pa)
def mlb_2019(): ab = 166651 hits = 42039 doubles = 8531 triples = 785 homeruns = 6776 singles = hits - (doubles + triples + homeruns) walks = 15895 pa = ab + walks return League(name='MLB2019', walk=walks / pa, single=singles / pa, double=doubles / pa, triple=triples / pa, homerun=homeruns / pa)
def getLeagueLeadersForStatTotal(leagueName, season, stat): """ Get the league leaders for a given stat in a season ARGS: leagueName (str) - name of the league season (str) - seasons string to search stat (str) - stat name to get leaders for RETURNS: [(str, str, float),] - list of tuples sorted by value, in the form (playerName, teamName, statValue) """ leagueLeadersDict = {} league = League.fromLeagueName(leagueName) if league is not None: seasonMatchList = league._matches[season] for match in seasonMatchList: for team in match.players.keys(): for player in match.players[team]: if player.id in leagueLeadersDict: leagueLeadersDict[player.id][2] += player.getStat(stat) else: leagueLeadersDict[player.id] = [player.name, team, player.getStat(stat)] return sorted(leagueLeadersDict.values(), key=lambda tup: tup[2], reverse=True)
def get_match_list(self, player_list=None): matches = [] if player_list: player_list = [League.get_check_str(n) for n in player_list] for match in self.matches: # check names against alts winner_tag = self.get_tag_by_id(match["winner-id"]) loser_tag = self.get_tag_by_id(match["loser-id"]) # check data is complete include = winner_tag and loser_tag # True unless # Challonge data is incomplete # check names to include list if player_list: include = winner_tag in player_list and loser_tag in player_list # convert to league data if include: matches.append(self.get_match_object(match)) return matches
def testLeague(): l = League(1234, 'leagueOne', { '1819': [1, 2, 3, 4], '1718': [5, 6, 7, 8] }, False) checkResult("League - All Match ids", l.getMatchIds, [], [5, 6, 7, 8, 1, 2, 3, 4]) checkResult("League - Season Match ids", l.getMatchIds, ['1819'], [1, 2, 3, 4]) with Timer('League Load') as t: l = League('180659', 'Six Nations', initMatches=True) startDate = datetime.datetime(2018, 3, 16) endDate = datetime.datetime(2018, 3, 18) filteredLeagueMatches = l.getMatchesInDateRange(startDate, endDate) checkResult('League - Test date range', len, [filteredLeagueMatches], 3) l = League.fromLeagueName('Six Nations', initMatches=False) checkResult('League - Test fromLeagueName', cmp, [l.id, '180659'], 0)
"에버튼", "크리스탈팰리스", "뉴캐슬", "사우스햄튼", "브라이튼", "웨스트햄", "왓포드", "아스톤빌라", "본머스", "노르위치시티" ] numTeams = len(team_names) teams = [] list_profile = ["호날두", "FW", "포르투갈", 186, 75, 35] for i in range(numTeams): team = Team(team_names[i]) for j in range(Team.numPlayers): p = Player(list_profile) team.addPlayer(p) teams.append(team) epl = League(teams) epl.begin() # print(epl.getSchedule()) for i in range(epl.getTotalRound()): epl.nextRound() epl.showTable() # 가상의 선수 23명으로 팀을 만들어보았습니다. # 선수 한명에 관한 정보를 출력해봅시다 teamName = teams[4].getTeamName() print(f'{teamName}') for i, player in enumerate(teams[4].getPlayers()): print(i, player.getProfileObj().getProfile()["이름"], end='\t') print(player.getProfileObj().getProfile()["포지션"], end='\t') print(player.getAbilityObj().getTechnical()["드리블"], end='\t') print(player.getAbilityObj().getMental()["시야"], end='\t')
# print(s.get_number_dice()) #c = Character("Jeff") #c.add_skill("health", EDice.d8, 2) #health = c.get_health() #print(health.get_number_dice().name) # c.add_skill("Health", EDice.d6, 2) # health = c.get_health() # print(health.get_number_dice().name) # l = League("Buffalo") # try: # c = l.add_character("J", "Follower", "d6", "1d6", "1d6", "1d6", "1d6", "1d6") # if c is not None: # print(c.get_health().get_number_dice() + c.get_health().get_dice_type().name) # print(c.get_brawl().get_number_dice() + c.get_brawl().get_dice_type().name) # print(c.get_might().get_number_dice() + c.get_might().get_dice_type().name) # except TypeError as e: # print(e) l = League("Buffalo") c = l.add_character("J", char_type="Follower", health="d6", brawl="1d6", shoot="1d6", dodge="1d6", might="1d6", finesse="1d6", cunning="1d6") if c is not None: print("Health: " + c.get_health().get_number_dice() + c.get_health().get_dice_type().name) print("Brawl: " + c.get_brawl().get_number_dice() + c.get_brawl().get_dice_type().name) print("Might: " + c.get_might().get_number_dice() + c.get_might().get_dice_type().name) print ("League: " + c.get_my_league().get_name()) print(l)
from league import League from authorize import Authorize from team import Team from player import Player from utils.building_utils import getUrl import pandas as pd import requests from tabulate import tabulate as table # Define user and season year user_id = 'desi' year = 2020 # Get login credentials for leagues login = pd.read_csv( 'C:\\Users\\desid\\Documents\\Fantasy_Football\\espn-api-v3\\login.csv') _, username, password, league_id, swid, espn_s2 = login[login['id'] == user_id].values[0] # Generate cookies payload and API endpoint cookies = {'swid': swid, 'espn_s2': espn_s2} url = getUrl(year, league_id) league = League(league_id, year, username, password, swid, espn_s2) print(league)
class league_test(unittest.TestCase): def setUp(self): #testing reference http://www.zerozero.pt/edition.php?jornada_in=19&id_edicao=86785&fase=81592 eng_dao_15_16 = DAO(country="england", season="15-16", cols="sport_cols") self.league = League(eng_dao_15_16) spa_dao_15_16 = DAO(country="spain", season="15-16", cols="sport_cols") self.league_spa = League(spa_dao_15_16) def test_half_league_date(self): self.league.half_league_date() def test_table(self): half_league_date = self.league.date_by_round(19) league_table = self.league.table(to_date=half_league_date) self.assertEqual(19, min(league_table["Played"])) self.assertEqual(20, len(league_table)) self.assertEqual(20, len(self.league.table())) self.assertEqual("Leicester", self.league.table().loc[1]["Team"]) self.assertEqual("Arsenal", self.league.table().loc[2]["Team"]) self.assertEqual("Leicester", league_table.loc[2]["Team"]) self.assertEqual("Arsenal", league_table.loc[1]["Team"]) def test_played_matches(self): played_matches = self.league.played_matches() self.assertEqual(38, played_matches.iloc[0]) self.assertEqual(38, played_matches["Man United"]) self.assertEqual(38, min(played_matches)) self.assertEqual(38, min(played_matches)) half_league_date = self.league.half_league_date() played_matches_h1 = self.league.played_matches( to_date=half_league_date) self.assertEqual(19 * 20, sum(played_matches_h1)) half_league_date_next_day = next_day(half_league_date) played_matches_h2 = self.league.played_matches( to_date=half_league_date_next_day) self.assertEqual(19 * 20, sum(played_matches_h2)) firsts_5_rounds = self.league.played_matches(to_date="14/09/2015") self.assertEqual(5, (firsts_5_rounds.mean())) def test_points(self): full_league_points = self.league.points() leicester_full = full_league_points[full_league_points["Team"] == "Leicester"] self.assertEqual(81, leicester_full["Points"].item()) aston_villa_full = full_league_points[full_league_points["Team"] == "Aston Villa"] self.assertEqual(17, aston_villa_full["Points"].item()) chelsea_full = full_league_points[full_league_points["Team"] == "Chelsea"] self.assertEqual(50, chelsea_full["Points"].item()) firsts_5_rounds = self.league.points(to_date="14/09/2015") arsenal_5_rounds = firsts_5_rounds[firsts_5_rounds["Team"] == "Arsenal"] self.assertEqual(10, arsenal_5_rounds["Points"].item()) def test_remaining_matches(self): #remaining matches after league completion end_date = self.league.end_league_date() full_league_remaining_matches = self.league.remaining_matches( from_date=end_date) self.assertEqual(0, min(full_league_remaining_matches)) self.assertEqual(0, max(full_league_remaining_matches)) #print(full_league_remaining_matches) #print("\n\n\n\n") #remaining matches after half league half_league_date_previous_day = previous_day( self.league.half_league_date()) half_league_remaining_matches = self.league.remaining_matches( from_date=half_league_date_previous_day) #median because maybe sometimes a time could end the first half league with 1 more match # or a match less self.assertEqual(19, half_league_remaining_matches.median()) #print(half_league_remaining_matches) #print("\n\n\n\n") #remaining matches before league beginning start_league_date_previous_day = previous_day( self.league.start_league_date()) before_league_remaining_matches = self.league.remaining_matches( from_date=start_league_date_previous_day) self.assertEqual(38, min(before_league_remaining_matches)) self.assertEqual(38, max(before_league_remaining_matches)) #print(before_league_remaining_matches) #print("\n\n\n\n") remainig_after_25_10_2015 = self.league.remaining_matches( from_date="25/10/2015") #print(self.league.remaining_matches(from_date="25/10/2015")) #print("\n\n\n\n") self.assertEqual(28, remainig_after_25_10_2015["Tottenham"]) remainig_after_24_10_2015 = self.league.remaining_matches( from_date="24/10/2015") #print(self.league.remaining_matches(from_date="24/10/2015")) #print("\n\n\n\n") self.assertEqual(29, remainig_after_24_10_2015["Man United"]) def test_matches(self): matches = self.league.matches() self.assertEqual(20 * 19, len(matches)) self.assertEqual(19, len(matches[matches["HomeTeam"] == "Everton"])) self.assertEqual(19, len(matches[matches["AwayTeam"] == "Watford"])) self.assertEqual(to_datetime("2015-08-08"), min(matches["Date"])) self.assertEqual(to_datetime("2016-05-17"), max(matches["Date"])) match = matches[(matches["Date"] == to_datetime("2015-08-22")) & (matches["HomeTeam"] == "West Ham")] self.assertEqual(match["HomeTeam"].item(), "West Ham") self.assertEqual(match["AwayTeam"].item(), "Bournemouth") self.assertEqual(match["FTHG"].item(), 3) self.assertEqual(match["FTAG"].item(), 4) def test_home_away_matches(self): manutd_played_matches = self.league.home_away_matches( team="Man United") manutd_everton = manutd_played_matches[manutd_played_matches["Aiganst"] == "Everton"] self.assertEqual(0, manutd_everton["AigHG"].item()) self.assertEqual(3, manutd_everton["TeamAG"].item()) self.assertEqual(1, manutd_everton["TeamHG"].item()) self.assertEqual(0, manutd_everton["AigAG"].item()) livp_played_matches = self.league.home_away_matches(team="Liverpool") livp_norw = livp_played_matches[livp_played_matches["Aiganst"] == "Norwich"] self.assertEqual(4, livp_norw["AigHG"].item()) self.assertEqual(5, livp_norw["TeamAG"].item()) self.assertEqual(1, livp_norw["TeamHG"].item()) self.assertEqual(1, livp_norw["AigAG"].item()) def test_team_history_goals(self): self.league.team_history_goals(team="Leicester") #TODO def test_team_history_points(self): hp = self.league.team_history_points(team="Leicester", to_date="2016-05-08") self.assertEqual(37, len(hp)) self.assertEqual(3, hp.iloc[0]["Points"]) self.assertEqual(1, hp.iloc[3]["Points"]) self.assertEqual(0, hp.iloc[6]["Points"]) self.assertEqual(1, hp.iloc[8]["Points"]) self.assertEqual(1, hp.iloc[21]["Points"]) self.assertEqual(0, hp.iloc[25]["Points"]) def test_team_shots(self): team_shots = self.league_spa.team_shots(team="Real Madrid") home = team_shots["home"] away = team_shots["away"] # print() # print(home["shots"], home["shots_target"], home["goals"]) # print(float(home["goals"]) / home["shots_target"]) # print(away["shots"], away["shots_target"], away["goals"]) # print(float(away["goals"]) / away["shots_target"]) team_shots = self.league_spa.team_shots(team="Barcelona") home = team_shots["home"] away = team_shots["away"] # print() # print(home["shots"], home["shots_target"], home["goals"]) # print(float(home["goals"]) / home["shots_target"]) # print(away["shots"], away["shots_target"], away["goals"]) # print(float(away["goals"]) / away["shots_target"]) # print () def test_date_by_round(self): n_round = 20 self.assertEqual("2016-01-03 00:00:00", str(self.league.date_by_round(n_round)))
class GanjaClient(discord.Client): """ Extends the Client class in discord.py. """ def __init__(self, token_file, dev=False): """ Not only does it represent a client connection to the discord server, but it also initializes the used api tokens and a representation of the League client by generating a League object. :param str token_file: location of the token file containing the api tokens :type token_file: str :param dev: allows the bot to start in a development environment with a separate discord bot token :type dev: bool :returns: GanjaClient -- the GanjaClient object acting as the discord client """ super(GanjaClient, self).__init__() with open(token_file) as f: data = json.load(f) self.server_token = data['token'] self.dev_token = data['dev_token'] self.wolfram = data['wolfram_token'] open_token = data['open_league_token'] riot_token = data['league_token'] self.database = '.databases/' self.http_header = {'User-Agent': 'Mozilla/5.0', 'Accept': 'text/html,application/json'} self.list_commands = {} self.voice = None self.player = None self.last_channel = None self.queue = Queue() self.queue_name = Queue() self.league = League(open_token, riot_token, self.http_header) for i in os.listdir('data'): with open('data/' + i) as f: lines = f.read().splitlines() self.list_commands[i] = lines if dev: self.token = self.dev_token else: self.token = self.server_token def run(self): """ Starts the client so it actually starts listening to incoming connections. Will also start the thread that initializes the DJ portion of the bot in a later version. """ super(GanjaClient, self).run(self.token) td = PlayThread(self) td.start() def get_from_shelve(self, name, item): """ Al persistent data gets saved in a shelve file. This method will get a certain item from the shelf :param name: name of the shelve to get the item from :type name: str :param item: name of the item you want from the shelve :type item: str :returns: str, list, dict """ with shelve.open(self.database + name) as db: return db[item] def add_to_shelve(self, name, key, value): """ Adds an item to the persistent shelve file. :param name: name of the shelve to get the item from :type name: str :param key: the key representing the location in the shelve :type key: str :param value: the value to put in the shelve :type value: str, list, dict """ with shelve.open(self.database + name) as db: db[key] = value def get_command(self, key): """ Gets the response of a user added command from the shelve. :param key: command :type key: str :returns: str -- the response of the given command """ try: return self.get_from_shelve('commands', key) except: raise Exception('Entry not found.') def add_command(self, key, value): """ Adds a user-defined command, response pair to the shelve. :param key: command :type key: str :param value: response :type value: str """ self.add_to_shelve('commands', key, value) def remove_command(self, key): """ Removes a user-defined command from the shelve. :param key: command :type key: str :returns: str -- the response to be sent to the discord server """ try: with shelve.open(self.database + 'commands') as commands: del commands['!' + key] return 'Command: ' + key + ' was removed.' except KeyError: return 'Command: ' + key + ' could not be found.' def get_command_list(self): """ Request a list of user-defined commands from the shelve. :returns: list -- list of commands """ with shelve.open(self.database + 'commands') as db: ret = db return list(ret.keys()) def is_command(self, arg): """ Checks if a string is a user-defined command. :param arg: the string to test against :type arg: str :returns: bool -- whether the item is a user-defined command or not """ with shelve.open(self.database + 'commands') as db: return arg in db def get_quote(self, key): """ Gets a previously saved quote by a server member from the shelve. :param key: name of the quotee :type key: str :returns: list -- list of saved quotes made by the member """ try: return self.get_from_shelve('quotes', key) except: raise Exception('Entry not found.') def add_quote(self, quotee, mess): """ Adds a memorable quote by a server member to the shelf. :param quotee: name of the quotee :type quotee: str :param mess: the actual quote :type mess: str """ with shelve.open(self.database + 'quotes') as quotes: if quotee not in quotes: quotes[quotee] = [] tmp = quotes[quotee] tmp.append(mess) quotes[quotee] = tmp def get_user(self, quotee): """ Finds the string that can be used to mention a certain server member on the server. :param quotee: name of the person :type quotee: str :returns: str -- will show up as a mention to the member on the discord server. """ try: return self.get_from_shelve('users', quotee) except KeyError: return 'Entry not found.' def find_id(self, member): """ Finds the name of a server member used in the shelve from a mention string. :param member: discord server mention :type member: str :returns: str -- the plain string that represents the member in the database """ with shelve.open(self.database + 'users') as users: uid = -1 added = False for key in users: val = users[key] if val == member: uid = key if uid == -1: uid = len(list(users.keys())) users[str(uid)] = member added = True return str(uid), added @asyncio.coroutine def on_message_delete(self, message): if message.content == 'http://i.imgur.com/IZAl8yz.png': yield from self.send_file(message.channel, 'http://i.imgur.com/IZAl8yz.png') @asyncio.coroutine def on_message(self, message): """ Determines whether the command is a known message and handles + responds to it if it is. :param message: the message sent by the discord users on the :type message: discord.Message """ # if str(message) == 'INTERNAL': # mess = '!dj next' # else: mess = message.content self.last_channel = message.channel if not mess.startswith('!'): # Impossible to be a command, no need to handle. return if mess.startswith('!lol'): # Handles league commands. Decodes the message en sends the command to the League class. yield from self.send_typing(message.channel) args = mess.replace('!lol ', '').replace(' ', '-', 1).split('-') if len(args) == 1: args.append('None') if args[0] != 'counters': yield from self.send_message(message.channel, self.league.run_command(args[0], args[1])) else: resp = self.league.run_command('counters', args[1]) if resp.endswith('.png'): yield from self.send_file(message.channel, resp) else: yield from self.send_message(message.channel, resp) elif mess.startswith('!wolfram'): # Gets the response from a query to the wolfram alpha server. yield from self.send_typing(message.channel) wol = wolframalpha.Client(self.wolfram) res = wol.query('\'' + mess.replace('!wolfram ', '') + '\'') try: yield from self.send_message(message.channel, res.pods[1].img) except IndexError: yield from self.send_message(message.channel, mess.replace('!wolfram ', '') + ' was not found.') elif mess.replace('!', '').split()[0] in self.list_commands: # Checks if command refers to one of the list files defined in the 'data/' folder # and gets a random line from it. yield from self.send_typing(message.channel) ls = mess.replace('!', '').split()[0] yield from self.send_message(message.channel, random.choice(self.list_commands[ls])) elif mess.startswith('!cat bomb'): # Sends 'n' cute cat pictures to the server 1>=n>=10 yield from self.send_typing(message.channel) mess = mess.replace('!cat bomb ', '') try: count = int(mess) if count > 10: count = 10 except ValueError: count = 1 ans = '' for i in range(count): req = request.Request('http://random.cat/meow.php', headers=self.http_header) with request.urlopen(req) as f: response = f.read().decode('UTF-8') response_dict = json.JSONDecoder().decode(response) ans += response_dict['file'] + '\n' yield from self.send_message(message.channel, ans[:-1]) elif mess.startswith('!deletecommand'): # Removes a user-defined command. yield from self.send_typing(message.channel) command = mess.replace('!deletecommand ', '').replace('!', '').strip() yield from self.send_message(message.channel, self.remove_command(command)) elif mess.startswith('!decide'): # Randomly selects one of many options. yield from self.send_typing(message.channel) mess = mess.replace('!decide ', '') dec = mess.split('or') if len(dec) < 2: answer = 'Usage: !decide something **or** something...' else: answer = 'I\'d go with: **' + dec[random.randint(0, len(dec) - 1)] + '**' yield from self.send_message(message.channel, answer) elif mess.startswith('!gif'): # Gets a gif with the given parameters from the Giphy server. yield from self.send_typing(message.channel) mess = mess.replace('!gif ', '') g = giphypop.Giphy() results = [x for x in g.search(mess)] if not results: results.append('Gif could not be found for: ' + mess) result = results[random.randint(0, len(results) - 1)] yield from self.send_message(message.channel, result) elif mess.startswith('!add'): # Used to add commands or quotes. yield from self.send_typing(message.channel) mess = mess.replace('!add ', '') if mess.startswith('gif '): # Adds a user-defined command. mess = mess.replace('gif ', '').replace(' \"', '---\"') key_val = mess.split('---') if len(key_val) < 2: yield from self.send_message(message.channel, 'usage: !add gif \"command name\" \"site or text\"') else: key = key_val[0].replace('!', '').replace('\"', '') key = '!' + key value = key_val[1].replace('\"', '') self.add_command(key, value) yield from self.send_message(message.channel, key + ' was added.') elif mess.startswith('quote'): # Adds a memorable quote. mess = message.clean_content.replace('!add quote ', '') mess = re.sub(r'@\S+\s', '', mess) if len(message.mentions) != 1: yield from self.send_message(message.channel, 'usage: !add quote @person quote') else: quotee, added = self.find_id(message.mentions[0].mention) self.add_quote(quotee, mess) yield from self.send_message(message.channel, '' + self.get_user(quotee) + ' \"' + mess + '\" was added.') elif mess.startswith('!quote'): # Used to retrieve a memorable quote from a certain user. yield from self.send_typing(message.channel) if len(message.mentions) != 1: yield from self.send_message(message.channel, 'usage: !quote @person number (optional)') else: quotee, added = self.find_id(message.mentions[0].mention) if added: yield from self.send_message(message.channel, 'No quotes for ' + self.get_user(quotee) + ' :(') else: mess = message.content.replace('!quote ', '') mess = re.sub(r'@\S+\s', '', mess).strip().replace('<', '') quote_list = self.get_from_shelve('quotes', quotee) if mess == 'list': quote_line = '\r\n'.join(quote_list) response = '```' + quote_line + '```' yield from self.send_message(message.channel, '' + self.get_user(quotee)) yield from self.send_message(message.channel, response) else: try: index = int(mess) - 1 except ValueError: index = -1 if index == -1 or index >= len(quote_list): index = random.randint(0, len(quote_list) - 1) yield from self.send_message(message.channel, '' + self.get_user(quotee) + '\n' + str(index + 1) + ': ' + quote_list[ index]) elif mess.startswith('!help'): # Returns a list of client commands and their uses. yield from self.send_typing(message.channel) if mess.startswith('!help list'): response = ['List of user added commands:', '```'] for x in self.get_command_list(): response.append(x + '\n') response.append('```') yield from self.send_message(message.channel, ''.join(response)) else: cmds = '```' cmds += '!gif search term\r\n' cmds += '!decide something or something...\r\n' cmds += '!wolfram something\r\n' for command in self.list_commands.keys(): cmds = cmds + '!' + command + ' \r\n' cmds += '```' response = ['Ganjabot feels very attacked but wants to learn, you can add images or messages with:', '```!add gif \"command name\" \"site or text\"```', 'Ganjabot finds your quotes offensive, add quotes with:', '```!add quote @person what you want to quote```', 'View league commands with: ```!lol```', 'View quotes with:', '```!quote @person' '\r\n!quote @person number' '\r\n!quote @person list```', 'For a list of user added commands:', '```!help list```', 'Miscellaneous commands:', cmds ] query = '' for res in response: query += res + '\r\n' yield from self.send_message(message.channel, query) elif self.is_command(mess): # Handles a user-defined command. response = self.get_command(mess) yield from self.send_message(message.channel, response) elif mess.startswith('!chill'): # Music bot. WIP: autoplay doesn't work yet. mess = mess.replace('!dj ', '') if mess.startswith('join'): self.voice = yield from self.join_voice_channel(message.author.voice_channel) elif mess.startswith('play'): if self.voice: if self.player: if self.player.is_playing(): self.player.stop() self.voice = yield from self.join_voice_channel(message.author.voice_channel) self.player = yield from self.voice.create_ytdl_player(self.queue.get()) yield from self.send_message(message.channel, 'Now playing: **' + self.queue_name.get() + '**') self.player.volume = 0.05 self.player.start() elif mess.startswith('add'): url = mess.replace('add', '').replace(' ', '') + '&' search = re.search('([^&]*)&.*$', url) url = search.group(1) match = youtube_url_validation(url) if match: self.queue.put(url) title = get_vid_title(url) self.queue_name.put(title) yield from self.send_message(message.channel, '**' + title + '** was added.') yield from self.delete_message(message) elif mess.startswith('next'): if self.voice: try: self.player = yield from self.voice.create_ytdl_player(self.queue.get()) yield from self.send_message(message.channel, 'Now playing: **' + self.queue_name.get() + '**') self.player.volume = 0.5 self.player.start() except Empty: if self.last_channel: yield from self.send_message(self.last_channel, 'List empty, stopping') self.voice.disconnect() else: yield from self.send_message(message.channel, 'Not connected to voice_channel, please use !dj join or !dj play.') elif mess.startswith('stop'): if self.voice: if self.player: if self.player.is_playing(): self.player.stop() yield from self.voice.disconnect() elif mess.startswith('list'): ret = 'Current songs in queue:' i = 0 for elem in list(self.queue_name.queue): i += 1 ret += '\n**[' + str(i) + '] ' + elem + '**' yield from self.send_message(message.channel, ret) elif mess.startswith('volup'): if self.player: self.player.volume += 0.01 elif mess.startswith('voldown'): if self.player: self.player.volume -= 0.01 @asyncio.coroutine def on_voice_state_update(self, before, after): #vc = after.voice channel = after.voice_channel if channel: if channel.id == '218477677768736768': self.voice = yield from self.join_voice_channel(channel) url = "https://www.youtube.com/watch?v=QX4j_zHAlw8" search = re.search('([^&]*)&.*$', url) url = search.group(1) match = youtube_url_validation(url) if match: self.queue.put(url) title = get_vid_title(url) self.queue_name.put(title) if self.voice: if self.player: if self.player.is_playing(): self.player.stop() self.voice = yield from self.join_voice_channel(channel) self.voice.opus.load_opus() self.player = yield from self.voice.create_ytdl_player(self.queue.get()) self.player.volume = 0.05 self.player.start()
# West Bromwich Albion west_brom = Team("West Bromwich Albion") west_brom.add_identifier("PTF", "West Brom") west_brom.add_identifier("Oddschecker", "West Brom") # West Ham United west_ham = Team("West Ham United") west_ham.add_identifier("PTF", "West Ham") west_ham.add_identifier("Oddschecker", "West Ham") premier_league_teams = [bournemouth, burnley, arsenal, chelsea, crystal_palace, everton, hull, leicester_city, liverpool, man_city, man_united, middlesbrough, southampton, stoke, sunderland, swansea, tottenham, watford, west_brom, west_ham] premier_league = League("Premier League") premier_league.add_teams(premier_league_teams) premier_league.add_identifier("PTF", "English Premier League") premier_league.add_identifier("PTF url", "premierleague") premier_league.add_identifier("OC url", "english/premier-league") ####################### ## Greek Superleague ## ####################### # AEK Athens aek_athens = Team("AEK Athens") aek_athens.add_identifier("PTF", "AEK Athens") aek_athens.add_identifier("Oddschecker", "AEK Athens")
return bs(content, "html.parser") def __call__(self, url_): return self.readUrl(url_) if __name__ == "__main__": scraper = PageScraper() soup = scraper(LEAGUES_URL) LeagueTables = soup.find("table", class_="items").find("tbody") Leagues = LeagueTables.find_all( "a", href=re.compile("wettbewerb/([A-Z]{2}|L)1"), title=re.compile("\w")) Leagues = Leagues[:N_LEAGUES] LeagueUrlDic = { league.text: BASE_URL + league["href"] for league in Leagues } LeaguesData = [] for leagueName, leagueUrl in LeagueUrlDic.items(): LeaguesData.append(League(leagueName, leagueUrl, scraper)) # flattening all players information to pandas.DataFrame and exporting to csv PlayerProfiles = [ player.PlayerData for league in LeaguesData for team in league.TeamsData for player in team.PlayersData ] df = pd.DataFrame(PlayerProfiles) df.to_csv("../data/performance-new.csv", index=False)
def __init__(self): logging.debug("In NFL constructor") self.__standings = dict() self.__postseason = dict() League.__init__(self, 'NFL') afc = Conference('AFC') nfc = Conference('NFC') self.addChild(afc) self.addChild(nfc) afce = Division('East') afce.setColors('black', 'red') afcn = Division('North') afcn.setColors('yellow', 'blue') afcs = Division('South') afcs.setColors('black', 'white') afcw = Division('West') afcw.setColors('black', 'orange') afc.addChild(afce) afc.addChild(afcn) afc.addChild(afcs) afc.addChild(afcw) afce.addChild(Team('Buffalo Bills', 'BUF')) afce.addChild(Team('Miami Dolphins', 'MIA')) afce.addChild(Team('New England Patriots', 'NE')) afce.addChild(Team('New York Jets', 'NYJ')) afcn.addChild(Team('Baltimore Ravens', 'BAL')) afcn.addChild(Team('Cincinnati Bengals', 'CIN')) afcn.addChild(Team('Cleveland Browns', 'CLE')) afcn.addChild(Team('Pittsburgh Steelers', 'PIT')) afcs.addChild(Team('Houston Texans', 'HOU')) afcs.addChild(Team('Indianapolis Colts', 'IND')) afcs.addChild(Team('Jacksonville Jaguars', 'JAC')) afcs.addChild(Team('Tennessee Titans', 'TEN')) afcw.addChild(Team('Denver Broncos', 'DEN')) afcw.addChild(Team('Kansas City Chiefs', 'KC')) afcw.addChild(Team('Oakland Raiders', 'OAK')) afcw.addChild(Team('San Diego Chargers', 'SD')) nfce = Division('East') nfce.setColors('black', 'darkgreen') nfcc = Division('Central') nfcc.setColors('orange', 'black') nfcs = Division('South') nfcs.setColors('black', 'lightblue') nfcw = Division('West') nfcw.setColors('black', 'yellow') nfc.addChild(nfce) nfc.addChild(nfcc) nfc.addChild(nfcs) nfc.addChild(nfcw) nfce.addChild(Team('Dallas Cowboys', 'DAL')) nfce.addChild(Team('New York Giants', 'NYG')) nfce.addChild(Team('Philadelphia Eagles', 'PHI')) nfce.addChild(Team('Washington Redskins', 'WAS')) nfcc.addChild(Team('Chicago Bears', 'CHI')) nfcc.addChild(Team('Detroit Lions', 'DET')) nfcc.addChild(Team('Green Bay Packers', 'GB')) nfcc.addChild(Team('Minnesota Vikings', 'MIN')) nfcs.addChild(Team('Atlanta Falcons', 'ATL')) nfcs.addChild(Team('Carolina Panthers', 'CAR')) nfcs.addChild(Team('New Orleans Saints', 'NO')) nfcs.addChild(Team('Tampa Bay Buccaneers', 'TB')) nfcw.addChild(Team('Arizona Cardnials', 'ARI')) nfcw.addChild(Team('San Francisco 49ers', 'SF')) nfcw.addChild(Team('Seattle Seahawks', 'SEA')) nfcw.addChild(Team('St. Louis Rams', 'STL'))