Пример #1
0
def email_alert(df,low_bound,high_bound):

    ## check for a significant deviation within the last 5 days
    ## if so - send an email!!

    snapshot = df.tail(5)
    vals = snapshot['prob'].tolist()
    hi_val, low_val = max(vals), min(vals)
    if low_val < low_bound or hi_val > high_bound:
        ffmt = "{:,.4f}".format
        table = snapshot.to_html(float_format=ffmt)
        table = table.replace('<th>',HEADER_STYLE)
        table = table.replace('<td>',ROW_STYLE)

        mail_client.mail('*****@*****.**','SPY Deviation!!!',text=EMAIL_HEADER,html=table,attach='thanos_spy.png')
Пример #2
0
def send_alert(symbol,df,low_bound,high_bound):

    ## check for a significant deviation within the last 5 days
    ## if so - send an email!!


    snapshot = df.tail(5)
    current_stats = df.tail(1).iloc[0].apply(str).tolist()
    
    # initilaize log file if one does not exist 
    if not os.path.isfile(THANOS_LOG):
        with open(THANOS_LOG,'w') as f:
            header = df.columns.tolist() + ['symbol','ext']
            f.write(",".join(header)+"\n")


    vals = snapshot['prob'].tolist()
    hi_val, low_val = max(vals), min(vals)
    if low_val < low_bound or hi_val > high_bound:
        hi_idx = low_idx = -1 
        if hi_val > high_bound: hi_idx = vals.index(hi_val)
        if low_val < low_bound: low_idx = vals.index(low_val)
        side = 'BOTTOM' if low_idx > hi_idx else 'TOP'

        ffmt = "{:,.4f}".format
        table = snapshot.to_html(float_format=ffmt)
        table = table.replace('<th>',HEADER_STYLE)
        table = table.replace('<td>',ROW_STYLE)

        subj = f'{symbol} {side} Deviation!!!'
        chart_file = THANOS_CHARTS + f'thanos_{symbol}.png'
        mail_client.mail('*****@*****.**',subj,text=EMAIL_HEADER,html=table,attach=chart_file)
        #mail_client.mail('*****@*****.**',subj,text=EMAIL_HEADER,html=table)

        todays_prob = float(current_stats[-1])  
        if todays_prob < low_bound or todays_prob > high_bound:
            current_stats.append(symbol)

            # flag extension type
            side = 'BOTTOM'
            if todays_prob > high_bound:
                side = 'TOP' 
            current_stats.append(side)
                
            outs = ",".join(current_stats)
            with open(THANOS_LOG,'a') as f:
                f.write(outs + '\n')
Пример #3
0
def send_heartbeat(uni):

    def modification_date(filename):
        t = os.path.getmtime(filename)
        return dt.datetime.fromtimestamp(t)


    uni_list = "\nUniverse:\n" + "\n".join(uni)
    
    now = dt.datetime.now()

    try:
        most_recent = modification_date(THANOS_LOG)
        delta = (now - most_recent).days
        if delta > 0 and delta % 5 == 0:
            message = f'Most recent update = {most_recent} ({delta} days)\n' + uni_list 
            mail_client.mail('*****@*****.**','THANOS Heartbeat!',text=message)
    except:
        mail_client.mail('*****@*****.**','THANOS Heartbeat FAILURE! Check Process!',text=uni_list)
Пример #4
0
def email_me(new_user):

    rules = """
    <html>
    <head>
    </head>
    <body>
    <div class="rules_div">
    <div class="rule_header"><p>Rules of the Game:</p></div>
    <div class="rules">
    <ol>
    <li>Players must select one NFL team to win in the current week's NFL games.<br><br>
    During the period of picking a team to win each week, YOU CAN ONLY USE A EACH NFL TEAM ONCE</li><br>
    <li>If your selected team WINS in the current week - you SURVIVED the week's challenge and now advance to the next week of competition.</li><br>
    <li>If your selected team LOSES in the current week - you are ELIMINATED from competition. &nbsp;GAME OVER.<br><br> Only players that continue to successfully pick a winning team each week advance to the next round.</li><br>
    <li>THE MULLIGAN: &nbsp;Each player is permitted one second chance attempt ('A Mulligan') to remain in the pool upon thier inital losing pick.<br>If effect, each player is allowed to continue to play if they failed on ONE pick.  &nbsp;Once they lose again - they are completely eliminated.</li><br>
    <li>The last player to continue to advance each week WINS THE ENTIRE POOL.<br>In the case of mulitple winners (i.e. everyone left get's knocked out of the pool at the same time), the pool is divided equally among the last remaining participants.</li><br>
    <li>When the game ends - ppriority goes to winning players that DID NOT use their second chance entry ('Mulligan').<br> If winners have picked perfectly - WINNINGS ARE DIVIDED AMONG THOSE PLAYERS ONLY.<br><br>Otherwise, all ending survivors divide the total price.</li>
    </ol>
    </div>
    </div>
    </body>
    </html>
    """

    ## email me about the new user
    subject = 'KnockOut Pool: New Player: %s' % new_user['name']
    msg = "New Player\n-------------------------------------------\n"
    msg += "Name:     %s\n" % new_user['name']
    msg += "User_Id:  %s\n" % new_user['user_id']
    msg += "Email:    %s\n" % new_user['email']

    mail_client.mail("*****@*****.**", subject, msg)

    ## welcome the new user
    ## along with game rukes
    welcome = "Welcome %s (%s), to Mulligan's KnockOut Pool!\n" % (
        new_user['name'], new_user['user_id'])
    welcome += "\nGood Luck!\n"

    subject = "Welcome to Mulligan's KnockOut Pool"
    mail_client.mail(new_user['email'], subject, text=welcome, html=rules)
Пример #5
0
def stats_and_standings(send_to):
    global mulligans
    global COMMISSIONER

    players, _ = read_csv('players.csv')

    player_info = {}
    for row in players:
        player_info[row['user_id']] = row

    picks, picks_header = read_csv('picks.csv')
    teams_nfl, _ = read_csv('nfl_teams.csv')
    nfl_teams = {}
    for team_row in teams_nfl:
        nfl_teams[team_row['Code']] = team_row['Team']

    nfl_sched, _ = read_csv('nfl_sched.csv')
    scoreboard = parse_schedule(nfl_sched)
    report_week = len(scoreboard)
    freq = {}

    used_mulligan = 0
    survivors = []
    perfects = 0
    knocked_out = 0

    pick_map = {}
    for row in picks:
        player, teams = row['player'], row['picks']
        teams_played = []
        if len(teams) > 0:
            teams_played = [x.upper() for x in teams.split("|")]
            for i in range(report_week):
                if i < len(teams_played):
                    team = teams_played[i]
                    if team != 'XXX':
                        try:
                            freq[team] += 1
                        except KeyError:
                            freq[team] = 1

        vitals = parse_path(teams_played, scoreboard)
        vitals['user_id'] = player
        vitals['email'] = player_info[player]['email']
        pick_map[player] = dict(vitals)
        falls = vitals['falls']
        if falls <= mulligans:
            if falls == mulligans:
                used_mulligan += 1
            else:
                perfects += 1
            survivors.append(player)
        else:
            knocked_out += 1

    map_status(pick_map, survivors, perfects, len(scoreboard))

    players = len(picks)
    categories = [
        'Players', 'Eliminated (Dead)', 'Survivors (Alive)', '',
        'Used Mulligans', 'Perfects'
    ]
    cat_counts = [
        players, knocked_out, players - knocked_out, '', used_mulligan,
        perfects
    ]
    summary_info = zip(categories, cat_counts)

    ### ONLY email commisioner summary report
    if send_to == 'COMMISSIONER':
        subject = "Mulligan's KnockOut Pool  "
        subject += "Week %d Commissioner's Report" % report_week

        win_list = [(k, pick_map[k]['email']) for k in pick_map
                    if pick_map[k]['status'] == 'WINNER']
        win_table = """
            <br>
            <span style="font-family: Lucida Sans; font-size:18px; color:#000000;"><strong>WINNERS</strong></span> 
            <br> <br>
            <table width="400" border="1" cellpadding="6" cellspacing="0">
        """
        winner_row = """
              <tr>
                <td width="100" height="30" style="font-family: Lucida Sans; font-size: 16px; color: #000000;">
                    <strong>{user_id}</strong>
                </td>
                <td width="300" height="30" style="font-family:  Courier New; font-size: 16px; color: #000000;">
                    {email}
                </td>
              </tr>
        """
        for user_id, email in win_list:
            win_table += winner_row.format(user_id=user_id, email=email)
        win_table += '</table>'

        rpt_table = knockout_email.generate_commissioner_report(
            report_week, summary_info)
        if len(win_list) > 0: rpt_table = rpt_table + win_table

        mail_client.mail(COMMISSIONER, subject, text='', html=rpt_table)
        print("emailing COMMISSIONER: %s " % (COMMISSIONER))

    ## OTHERWISE email all individual reports
    if send_to == 'PLAYERS':
        ## report to all players active during the past pool week
        for user_id in pick_map:
            p = pick_map[user_id]

            if len(p['used_path']) >= report_week:
                subject = "Mulligan's KnockOut Pool  "
                subject += "Week %d Report" % report_week

                email_rpt = knockout_email.generate_player_report(
                    report_week=report_week,
                    players=players,
                    user_id=user_id,
                    scoreboard=scoreboard,
                    vitals=p,
                    summary_info=summary_info,
                    team_freqs=freq,
                    nfl_teams=nfl_teams)
                try:
                    mail_client.mail(p['email'],
                                     subject,
                                     text='',
                                     html=email_rpt)
                    print("emailing: %s %s" % (user_id, p['email']))
                except:
                    print("emailing: %s %s FAILED" % (user_id, p['email']))

    ## indiv email - used in demo executions
    if send_to.startswith("DEMO"):
        user_id = send_to.split()[1]  #'DEMO user_id'
        p = pick_map[user_id]

        subject = "Mulligan's KnockOut Pool  "
        subject += "Week %d Report (DEMO)" % report_week

        if len(p['used_path']) >= report_week:
            email_rpt = knockout_email.generate_player_report(
                report_week=report_week,
                players=players,
                user_id=user_id,
                scoreboard=scoreboard,
                vitals=p,
                summary_info=summary_info,
                team_freqs=freq,
                nfl_teams=nfl_teams)
            try:
                mail_client.mail(p['email'], subject, text='', html=email_rpt)
                print("DEMO emailing: %s %s" % (user_id, p['email']))
            except:
                print("DEMO emailing: %s %s FAILED" % (user_id, p['email']))
Пример #6
0
def email_me(new_user):

    rules = """
    <html>
    <head>
    </head>
    <body>
    <div style="font-family: Verdana;">
    <br>
    <span style="font-size:18px; color:#000000;">Welcome <strong>{name} ['{user_id}']</strong>, to Mulligan's Knockout Pool!</span>
    <br>
    <br>
    <div class="rules" style="border: 2px solid; background-color: #f2f2f2;padding:10px;width:850px; font-family: Lucida Sans; font-size:14px; color:#000000;">
    <div class="rule_header" style="position:absolute; top:90px; left: 350px; font-size:18px; color:#000000;"><strong>Rules of the Game</strong></div>
    <ol>
    <br>
    <li>Players must select one NFL team to win in the current week's NFL games.<br>
    During the period of picking a team to win each week, YOU CAN ONLY USE A EACH NFL TEAM ONCE</li><br>
    <li>If your selected team WINS in the current week - you SURVIVED the week's challenge and now advance to the next week of competition.</li><br>
    <li>If your selected team LOSES in the current week - you are ELIMINATED from competition. &nbsp;GAME OVER.<br><br> Only players that continue to successfully pick a winning team each week advance to the next round.</li><br>
    <li>THE MULLIGAN: &nbsp;Each player is permitted one second chance attempt ('A Mulligan') to remain in the pool upon thier inital losing pick.<br>In effect, each player is allowed to continue to play if they failed on ONE pick.<br>Once they lose again - they are completely eliminated.</li><br>
    <li>The last player to continue to advance each week WINS THE ENTIRE POOL.<br>In the case of mulitple winners (i.e. everyone left get's knocked out of the pool at the same time), the pool is divided equally among the last remaining participants.</li><br>
    <li>When the game ends - priority goes to winning players that DID NOT use their second chance entry ('Mulligan').<br> If winners have picked perfectly - WINNINGS ARE DIVIDED AMONG THOSE PLAYERS ONLY.<br>Otherwise, all ending survivors divide the total prize.</li>
    </ol>
    </div>
    <br>
    <span style="font-size:18px; color:#000000;">Good Luck!</span>
    </div>
    </body>
    """

    ## email me about the new user
    subject = 'KnockOut Pool: New Player: %s' % new_user['name']
    player_table = """
    <br>
    <span style="font-family: Lucida Sans; font-size:18px; color:#000000;"><strong>NEW PLAYER</strong></span> 
    <br> <br>
    <table width="400" border="1" cellpadding="6" cellspacing="0">
      <tr>
        <td width="100" height="30" style="font-family: Lucida Sans; font-size: 16px; color: #000000;">
            <strong>Name</strong>
        </td>
        <td width="300" height="30" style="font-family:  Courier New; font-size: 16px; color: #000000;">
            {name}
        </td>
      </tr>
      <tr>
        <td width="100" height="30" style="font-family: Lucida Sans; font-size: 16px; color: #000000;">
            <strong>User_Id</strong>
        </td>
        <td width="300" height="30" style="font-family:  Courier New; font-size: 16px; color: #000000;">
            {user_id}
        </td>
      </tr>
      <tr>
        <td width="100" height="30" style="font-family: Lucida Sans; font-size: 16px; color: #000000;">
            <strong>Email</strong>
        </td>
        <td width="300" height="30" style="font-family:  Courier New; font-size: 16px; color: #000000;">
            {email}
        </td>
      </tr>
    """

    player_table = player_table.format(name=new_user['name'],
                                       user_id=new_user['user_id'],
                                       email=new_user['email'])
    rules = rules.format(name=new_user['name'], user_id=new_user['user_id'])
    mail_client.mail("*****@*****.**", subject, text='', html=player_table)

    subject = "Welcome to Mulligan's Knockout Pool"
    mail_client.mail(new_user['email'], subject, text='', html=rules)
Пример #7
0
def stats_and_standings(send_to):
    global mulligans
    global COMMISSIONER

    players, _ = read_csv('players.csv')

    player_info = {}
    for row in players:
        player_info[row['user_id']] = row

    picks, picks_header = read_csv('picks.csv')
    teams_nfl, _ = read_csv('nfl_teams.csv')
    nfl_teams = {}
    for team_row in teams_nfl:
        nfl_teams[team_row['Code']] = team_row['Team']

    nfl_sched, _ = read_csv('nfl_sched.csv')
    scoreboard = parse_schedule(nfl_sched)
    report_week = len(scoreboard)
    freq = {}

    used_mulligan = 0
    survivors = []
    perfects = 0
    knocked_out = 0

    pick_map = {}
    for row in picks:
        player, teams = row['player'], row['picks']
        teams_played = []
        if len(teams) > 0:
            teams_played = [x.upper() for x in teams.split("|")]
            for i in range(report_week):
                if i < len(teams_played):
                    team = teams_played[i]
                    if team != 'XXX':
                        try:
                            freq[team] += 1
                        except KeyError:
                            freq[team] = 1

        vitals = parse_path(teams_played, scoreboard)
        vitals['user_id'] = player
        vitals['email'] = player_info[player]['email']
        pick_map[player] = dict(vitals)
        falls = vitals['falls']
        if falls <= mulligans:
            if falls == mulligans:
                used_mulligan += 1
            else:
                perfects += 1
            survivors.append(player)
        else:
            knocked_out += 1

    map_status(pick_map, survivors, perfects, len(scoreboard))

    players = len(picks)
    categories = [
        'Players', 'Eliminated (Dead)', 'Survivors (Alive)', '',
        'Used Mulligans', 'Perfects'
    ]
    cat_counts = [
        players, knocked_out, players - knocked_out, '', used_mulligan,
        perfects
    ]
    summary_info = zip(categories, cat_counts)

    ### ONLY email commisioner summary report
    if send_to == 'COMMISSIONER':
        subject = "Mulligan's KnockOut Pool  "
        subject += "Week %d Commissioner's Report" % report_week

        win_list = [
            "%s: %s" % (k, pick_map[k]['email']) for k in pick_map
            if pick_map[k]['status'] == 'WINNER'
        ]
        winners = "WINNERS:\n" + "\n".join(win_list)

        rpt_table = knockout_email.generate_commissioner_report(
            report_week, summary_info)
        mail_client.mail(COMMISSIONER, subject, text=winners, html=rpt_table)
        print("emailing COMMISSIONER: %s " % (COMMISSIONER))

    ## OTHERWISE email all individual reports
    if send_to == 'PLAYERS':
        rpt_generator = knockout_email.generate_player_report
        ## report to all players active during the past pool week

        for user_id in pick_map:
            p = pick_map[user_id]

            if len(p['used_path']) >= report_week:
                subject = "Mulligan's KnockOut Pool  "
                subject += "Week %d Report" % report_week

                email_rpt = rpt_generator(report_week=report_week,
                                          players=players,
                                          user_id=user_id,
                                          scoreboard=scoreboard,
                                          vitals=p,
                                          summary_info=summary_info,
                                          team_freqs=freq,
                                          nfl_teams=nfl_teams)

                mail_client.mail(p['email'], subject, text='', html=email_rpt)
                print("emailing: %s %s" % (user_id, p['email']))