Best Python code snippet using lemoncheesecake
runner.py
Source:runner.py  
...277    if setup_suite is None:278        return None279    fixtures_names = suite.get_hook_params("setup_suite")280    def wrapper():281        fixtures = scheduled_fixtures.get_fixture_results(fixtures_names)282        setup_suite(**fixtures)283    return wrapper284def build_suite_initialization_task(suite, scheduled_fixtures, dependencies, force_disabled):285    if not suite.has_enabled_tests() and not force_disabled:286        return None287    setup_teardown_funcs = []288    if not scheduled_fixtures.is_empty():289        setup_teardown_funcs.extend(scheduled_fixtures.get_setup_teardown_pairs())290    if suite.get_injected_fixture_names():291        setup_teardown_funcs.append((292            lambda: suite.inject_fixtures(scheduled_fixtures.get_fixture_results(suite.get_injected_fixture_names())),293            None294        ))295    if suite.has_hook("setup_suite") or suite.has_hook("teardown_suite"):296        setup_teardown_funcs.append([297            wrap_setup_suite(suite, scheduled_fixtures),298            suite.get_hook("teardown_suite")299        ])300    return SuiteInitializationTask(suite, setup_teardown_funcs, dependencies) if setup_teardown_funcs else None301class SuiteEndingTask(BaseTask):302    def __init__(self, suite, dependencies):303        BaseTask.__init__(self)304        self.suite = suite305        self._dependencies = dependencies306    def get_on_success_dependencies(self):...fpl_csv_converter.py
Source:fpl_csv_converter.py  
...80            'position': position81        }82        # Create CurrentSeasonStats Table83        CURR_SEASON_STATS[PLAYER_NAMES[i]] = curr_season_data84def get_fixture_results():85    """86    Use FPL API fixtures endpoint for eventual Result.csv87    88    :return: None89    """90    team_dictionary = {91        1: 'Arsenal', 2: 'Bournemouth', 3: 'Burnley',92        4: 'Chelsea', 5: 'Crystal Palace', 6: 'Everton',93        7: 'Hull City', 8: 'Leicester City', 9: 'Liverpool',94        10: 'Manchester City', 11: 'Manchester United', 12: 'Middlesborough',95        13: 'Southampton', 14: 'Stoke City', 15: 'Sunderland',96        16: 'Swansea City', 17: 'Tottenham Hotspur', 18: 'Watford',97        19: 'West Bromwich Albion', 20: 'West Ham United'98    }99    manager_dictionary = {100        1: 'Arsene Wenger', 2: 'Eddie Howe', 3: 'Sean Dyche', 4: 'Antonio Conte',101        5: 'Alan Pardew', 6: 'Ronald Koeman', 7: 'Mike Phelan', 8: 'Claudio Ranieri',102        9: 'Jurgen Klopp', 10: 'Pep Guardiola', 11: 'Jose Mourinho', 12: 'Aitor Karanka',103        13: 'Claude Puel', 14: 'Mark Hughes', 15: 'David Moyes', 16: 'Bob Bradley',104        17: 'Mauricio Pochettino', 18: 'Walter Mazzarri', 19: 'Tony Pullis', 20: 'Slaven Bilic'105    }106    r = requests.get('https://fantasy.premierleague.com/drf/fixtures')107    fixtures_data = r.json()108    for fixture in fixtures_data:109        home_team = team_dictionary[fixture['team_h']]110        away_team = team_dictionary[fixture['team_a']]111        RESULTS[home_team + ' VS. ' + away_team] = {112            'id': fixture['id'],113            'gameweek': fixture['event'],114            'home_score': fixture['team_h_score'],115            'away_score': fixture['team_a_score'],116            'home_team': home_team,117            'away_team': away_team,118            'home_mgr': manager_dictionary[fixture['team_h']],119            'away_mgr': manager_dictionary[fixture['team_a']]120        }121def get_past_seasons(pid, data, psc):122    """123    Return stats from previous seasons if player is a veteran.124    125    :param pid: Int - Player ID# 126    :param data: Dictionary - JSON127    :param psc: Int - Past Season Count128    :return: Dictionary - JSON129    """130    # Variable declarations for summed past statistic headers131    total_points, minutes, goals_scored, assists, clean_sheets = 0, 0, 0, 0, 0132    goals_conceded, own_goals, penalties_saved, penalties_missed = 0, 0, 0, 0133    yellow_cards, red_cards, saves, ea_index = 0, 0, 0, 0134    # For all previous PL seasons...135    for s in range(psc):136        total_points += data['history_past'][s]['total_points']137        minutes += data['history_past'][s]['minutes']138        goals_scored += data['history_past'][s]['goals_scored']139        assists += data['history_past'][s]['assists']140        clean_sheets += data['history_past'][s]['clean_sheets']141        goals_conceded += data['history_past'][s]['goals_conceded']142        own_goals += data['history_past'][s]['own_goals']143        penalties_saved += data['history_past'][s]['penalties_saved']144        penalties_missed += data['history_past'][s]['penalties_missed']145        yellow_cards += data['history_past'][s]['yellow_cards']146        red_cards += data['history_past'][s]['red_cards']147        saves += data['history_past'][s]['saves']148        ea_index += data['history_past'][s]['ea_index']149    # Create JSON of overall past season stats150    past_season_data = {151        'total_points': total_points,152        'mins_played': minutes,153        'goals_scored': goals_scored,154        'assists': assists,155        'clean_sheets': clean_sheets,156        'goals_conceded': goals_conceded,157        'own_goals': own_goals,158        'penalties_saved': penalties_saved,159        'penalties_missed': penalties_missed,160        'yellow_cards': yellow_cards,161        'red_cards': red_cards,162        'saves': saves,163        'ea_index': ea_index,164        'previous_pl_seasons': psc,165        'Player_pid': pid166    }167    return past_season_data168def get_history():169    """170    Use FPL API element-summary endpoint for eventual TotalPastStats.csv and PlayerResultStats.csv171    172    :return: None173    """174    misses = 0175    player_url = 'https://fantasy.premierleague.com/drf/element-summary/{}'176    for pid in range(1, NUM_PLAYERS + 1):177        player_name = PLAYER_NAMES[pid - 1]178        r = requests.get(player_url.format(pid))179        print('Grabbing ' + player_name)180        # Skip broken URLs181        if r.status_code != 200:182            misses += 1183            print('BROKEN URL @ PLAYER #: ' + str(pid) + '\n')184            print(player_name + ' should be here!\n')185            # More than one miss in a row - end of requests!186            if misses > 1:187                print('Two broken URLs in a row...')188                print('Something is wrong with your connection or the API.\n')189                sys.exit()190            continue191        # Reset 'missing' counter to continue loop through entire API endpoint.192        misses = 0193        player_data = r.json()194        # Number of seasons previously played in the PL195        past_season_count = len(player_data['history_past'])196        # If player has played in PL before...197        if past_season_count > 0:198            # Sum up past season statistics for overall past table199            TOTAL_PAST_STATS[player_name] = get_past_seasons(pid, player_data, past_season_count)200        # Get Player's stats for each game played so far201        games_played = player_data['history']202        for game in games_played:203            # key looks like this: 'Hector Bellerin Fixture 8: {stats}204            key = (player_name + ' Fixture ' + str(game['fixture']))205            PLAYER_RESULTS_STATS[key] = {206                'pmid': game['id'],207                'points': game['total_points'],208                'mins_played': game['minutes'],209                'goals_scored': game['goals_scored'],210                'assists': game['assists'],211                'clean_sheets': game['clean_sheets'],212                'goals_conceded': game['goals_conceded'],213                'own_goals': game['own_goals'],214                'penalties_saved': game['penalties_saved'],215                'penalties_missed': game['penalties_missed'],216                'yellow_cards': game['yellow_cards'],217                'red_cards': game['red_cards'],218                'saves': game['saves'],219                'influence': float(game['influence']),220                'creativity': float(game['creativity']),221                'threat': float(game['threat']),222                'ict_index': float(game['ict_index']),223                'Result_id': game['fixture'],224                'Player_pid': pid225            }226        # Next player...227        pid += 1228def dict_to_csv(json_data, filename, headers, tablename):229    """230    Export dictionary collection to CSV231    232    :param json_data: Dictionary - JSON233    :param filename: String - Name of .csv output234    :param headers: String - CSV column headers235    :param tablename: String - Related database table236    :return: None 237    """238    with open(filename, 'w') as csvfile:239        try:240            writer = csv.DictWriter(csvfile, fieldnames=headers)241            writer.writeheader()242            for i in json_data:243                writer.writerow(json_data[i])244        finally:245            print(tablename, ' written to CSV successfully.')246def sort_csv(csv_filename, sorting_key):247    """248    Use pandas to sort CSVs and delete unsorted arguments in .csv249    ** Author: Adam Obeng **250    - stackoverflow.com/questions/15559812/sorting-by-specific-column-data-using-csv-in-python251    252    :param csv_filename: String - Name of .csv output253    :param sorting_key: String - Refers to CSV column header254    :return: None255    """256    df = pd.read_csv(csv_filename)257    df = df.sort_values(by=sorting_key)258    os.remove(csv_filename)259    df.to_csv(csv_filename, index=False)260# Collection function for relevant exporting functions261# TODO: Implement OrderedDict instead of manually plugging in headers262def export_data():263    """264    Function to call all related export functions.265    266    :return: None267    """268    # Headers for CSV creation functions269    player_table_headers = ['pid', 'name', 'nationality', 'position']270    curr_table_headers = ['total_points', 'mins_played', 'goals_scored', 'assists', 'clean_sheets',271                          'goals_conceded', 'own_goals', 'penalties_saved', 'penalties_missed',272                          'yellow_cards', 'red_cards', 'saves', 'ea_index', 'influence',273                          'creativity', 'threat', 'ict_index', 'Player_pid']274    past_table_headers = ['total_points', 'mins_played', 'goals_scored', 'assists', 'clean_sheets',275                          'goals_conceded', 'own_goals', 'penalties_saved', 'penalties_missed',276                          'yellow_cards', 'red_cards', 'saves', 'ea_index', 'previous_pl_seasons',277                          'Player_pid']278    result_table_headers = ['id', 'gameweek', 'home_score', 'away_score', 'home_team', 'away_team',279                            'home_mgr', 'away_mgr']280    prs_table_headers = ['pid', 'points', 'mins_played', 'goals_scored', 'assists', 'clean_sheets',281                         'goals_conceded', 'own_goals', 'penalties_saved', 'penalties_missed',282                         'yellow_cards', 'red_cards', 'saves', 'influence', 'creativity', 'threat',283                         'ict_index', 'Result_id', 'Player_pid']284    dict_to_csv(PLAYERS, 'Player.csv', player_table_headers, 'PLAYERS')285    dict_to_csv(CURR_SEASON_STATS, 'CurrentSeasonStats.csv', curr_table_headers, 'CURRENT_SEASON_STATS')286    dict_to_csv(TOTAL_PAST_STATS, 'TotalPastStats.csv', past_table_headers, 'TOTAL_PAST_STATS')287    dict_to_csv(RESULTS, 'Result.csv', result_table_headers, 'RESULTS')288    dict_to_csv(PLAYER_RESULTS_STATS, 'PlayerResultStats.csv', prs_table_headers, 'PLAYER_RESULTS_STATS')289    print('...Sorting CSV Files...\n')290    time.sleep(1)291    sort_csv('Player.csv', 'pid')292    print('......\n')293    sort_csv('CurrentSeasonStats.csv', 'Player_pid')294    print('......\n')295    sort_csv('TotalPastStats.csv', 'Player_pid')296    print('......\n')297    sort_csv('Result.csv', 'id')298    print('......\n')299    sort_csv('PlayerResultStats.csv', 'pmid')300    print('DONE!')301if __name__ == '__main__':302    print('...Getting player names and current season stats...\n')303    get_curr_stats()304    print('...Getting players past season stats (if any)...\n')305    get_history()306    print('...Getting scorelines from games played thus far this season...\n')307    get_fixture_results()308    print('...Writing CSV Files...\n')...scoreboard.py
Source:scoreboard.py  
...175        self.owner_id = owner_id        176        self.group = ''177        self.owner = owner178        self.fixtures = []179        self.record = self.get_fixture_results()180        self.recordstr =  self.calc_record()181        self.pts = self.calc_pts()182        self.eliminated = self.is_eliminated()183    def get_fixture_results(self):184        results = {}185        with open('fixtures.json') as f:186            fixtures = json.load(f)187        for game in fixtures['response']:188            rnd = game['league']['round']189            group = ''190            if 'Qualifying' in rnd:191                rnd = 'Qualifying'192            elif 'Group' in rnd:193                group = game['league']['round']194                rnd = 'Group'195            if not results.get(rnd):196                results[rnd] = {'w': 0, 'l': 0, 'd': 0}197            for side, team in game['teams'].items():...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
