Skip to content

Commit d055d1e

Browse files
committed
Added option to view time used between p2 and p1 of each day.
1 parent ab8b967 commit d055d1e

File tree

3 files changed

+94
-38
lines changed

3 files changed

+94
-38
lines changed

Website/html/template.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
$.ajaxSetup({
5353
async: false
5454
});
55-
$.getJSON('/get_results/{{year}}', function(data){dataSet=data['data'], columns=data['columns'], last_refresh=data['ts'] ;});
55+
$.getJSON('/{{prefix}}{{year}}', function(data){dataSet=data['data'], columns=data['columns'], last_refresh=data['ts'] ;});
5656
/*$.each( dataSet[0], function( key, value ) {
5757
var my_item = {};
5858
my_item.data = key;

Website/main.py

Lines changed: 43 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55
@author: Gašper Rugelj
66
"""
77

8+
from collections import defaultdict as dd
89
from datetime import datetime
910
import json
11+
import logging
1012
from threading import Lock
1113

1214
import flask
@@ -18,42 +20,67 @@
1820
YEARS = ('2017', '2018', '2019', '2020')
1921

2022
@app.route('/get_results/<year>')
21-
def result_page(year, *args, **kwargs):
23+
def result_page(year, *args, duration=False, **kwargs):
2224
if lock.acquire(timeout=10):
23-
if (datetime.now() - cache[year]['ts']).seconds < LIMIT:
24-
response = cache[year]['data']
25-
print('Too soon, using cache')
25+
if (datetime.now() - cache[duration][year]['ts']).seconds < LIMIT:
26+
response = cache[duration][year]['data']
27+
logging.info('Refresh too soon, using cache')
2628
else:
27-
total = results.get_results(year=year, convert_ts=True)
29+
total = results.get_results(year=year,
30+
convert_ts=True,
31+
duration=duration)
32+
2833
if total is None: # something failed
29-
print('Failed retrieving data, using cache')
30-
response = cache[year]['data']
34+
logging.error('Failed retrieving data, using cache')
35+
response = cache[duration][year]['data']
36+
3137
else:
3238
data = total.to_dict(orient='records')
3339
columns = list(total.columns)
3440
ts = datetime.now()
3541
response = json.dumps(dict(data = data,
3642
columns=columns,
3743
ts=ts.strftime('%Y-%m-%d %H:%M')))
38-
response = response.replace('NaN', 'null').replace('NaT', '')
39-
cache[year]['data'] = response
40-
cache[year]['ts'] = ts
44+
response = response.replace('NaN', 'null')
45+
response = response.replace('NaT', '')
46+
cache[duration][year]['data'] = response
47+
cache[duration][year]['ts'] = ts
48+
4149
lock.release()
50+
4251
else:
43-
print("Can't acquire lock")
44-
response = cache[year]['data']
52+
logging.warning("Can't acquire lock, returning cached response")
53+
response = cache[duration][year]['data']
4554
return response
4655

56+
57+
@app.route('/get_duration/<year>')
58+
def duration(year, *args, **kwargs):
59+
return result_page(year, duration=True)
60+
61+
4762
@app.route('/')
4863
@app.route('/<year>')
49-
def index(year='2020'):
64+
def index(year='2020', duration=False):
5065
if str(year) not in YEARS:
5166
year = '2019'
5267
name = 'AoC {}'.format(year)
53-
ts = cache[year]['ts']
54-
return flask.render_template('template.html', name=name, year=year, ts=ts)
68+
ts = cache[duration][year]['ts']
69+
prefix = 'get_duration/' if duration else 'get_results/'
70+
return flask.render_template('template.html',
71+
name=name,
72+
year=year,
73+
ts=ts,
74+
prefix=prefix)
75+
76+
77+
@app.route('/duration')
78+
@app.route('/duration/<year>')
79+
def index_duration(year='2020'):
80+
return index(year, duration=True)
81+
5582

5683
if __name__ == '__main__':
5784
lock = Lock()
58-
cache = {year: dict(ts=datetime.min, data=None) for year in YEARS}
85+
cache = dd(lambda: dd(lambda: dict(ts=datetime.min, data=None)))
5986
app.run(port=5008, host='0.0.0.0', debug=True)

Website/results.py

Lines changed: 50 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,29 @@
55
@author: Gašper Rugelj
66
"""
77

8-
import json
9-
108
import pandas as pd
119
import requests
1210

13-
with open('cookie') as file:
14-
cookie = json.load(file)
11+
with open('../token.txt', 'r') as file:
12+
token = next(file)
13+
cookie= {'session':token}
1514
url = 'https://adventofcode.com/{year}/leaderboard/private/view/118799.json'
1615

17-
def get_results(convert_ts=False, year=2019):
16+
def _timezone(series):
17+
s = pd.to_datetime(series, unit='s')
18+
s = s.dt.tz_localize('UTC').dt.tz_convert('CET')
19+
s = s.dt.strftime('%#d.%m. %H:%M:%S')
20+
return s
21+
22+
23+
def formatter(i):
24+
if pd.isnull(i):
25+
return ''
26+
else:
27+
return '{:.0f}h {:02.0f}m {:02.0f}s'.format(i//3600, (i%3600)//60, (i%60))
28+
29+
30+
def get_results(convert_ts=False, year=2019, duration=False):
1831

1932
try:
2033
r = requests.get(url.format(year=year), cookies=cookie, timeout=5)
@@ -33,33 +46,49 @@ def get_results(convert_ts=False, year=2019):
3346
row = [member, name, score]
3447
for level in range(1, max_level+1):
3548
times = levels.get(str(level))
36-
if times is None:
37-
row += [None, None]
38-
else:
39-
for stage in ['1', '2']:
40-
t = times.get(stage)
41-
if t is not None:
42-
row.append(int(t.get('get_star_ts')))
43-
else:
49+
50+
if duration:
51+
if times is None:
52+
row.append(None)
53+
else:
54+
t1 = times.get('1')
55+
t2 = times.get('2')
56+
if t1 is None or t2 is None:
4457
row.append(None)
58+
else:
59+
t1_time = t1.get('get_star_ts')
60+
t2_time = t2.get('get_star_ts')
61+
row.append(int(t2_time)-int(t1_time))
62+
63+
else:
64+
if times is None:
65+
row += [None, None]
66+
else:
67+
for stage in ['1', '2']:
68+
t = times.get(stage)
69+
if t is not None:
70+
row.append(int(t.get('get_star_ts')))
71+
else:
72+
row.append(None)
4573
total.append(row)
4674

4775

4876
columns = ['ID', 'Name', 'Score']
4977
icol = 3 # first time col for conversion
78+
5079
for i in range(1, max_level+1):
51-
columns+='{0}a,{0}b'.format(i).split(',')
52-
80+
if duration:
81+
columns.append('{0}b-{0}a'.format(i))
82+
else:
83+
columns+='{0}a,{0}b'.format(i).split(',')
5384

54-
def timezone(series):
55-
s = pd.to_datetime(series, unit='s')
56-
s = s.dt.tz_localize('UTC').dt.tz_convert('CET')
57-
s = s.dt.strftime('%#d.%m. %H:%M:%S')
58-
return s
5985

6086
total = pd.DataFrame(total, columns=columns)
6187
if convert_ts:
62-
total.iloc[:, icol:] = total.iloc[:, icol:].apply(timezone)
88+
if duration:
89+
total.iloc[:, icol:] = total.iloc[:, icol:].applymap(formatter)
90+
else:
91+
total.iloc[:, icol:] = total.iloc[:, icol:].apply(_timezone)
6392
#total.iloc[:, icol:] = total.iloc[:, icol:].apply(pd.to_datetime, unit='s')
6493
total = total.sort_values('Score', ascending=False)
6594

0 commit comments

Comments
 (0)