advent-of-code-data 2.0.1__tar.gz → 2.0.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/PKG-INFO +11 -4
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/README.rst +2 -2
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/advent_of_code_data.egg-info/PKG-INFO +11 -4
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/advent_of_code_data.egg-info/SOURCES.txt +2 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/aocd/__init__.py +24 -1
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/aocd/_ipykernel.py +2 -1
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/aocd/cli.py +1 -1
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/aocd/cookies.py +16 -5
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/aocd/examples.py +19 -12
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/aocd/get.py +14 -5
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/aocd/models.py +88 -57
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/aocd/post.py +17 -3
- advent_of_code_data-2.0.2/aocd/py.typed +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/aocd/runner.py +34 -17
- advent_of_code_data-2.0.2/aocd/types.py +35 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/aocd/utils.py +49 -13
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/pyproject.toml +21 -1
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/tests/test_models.py +46 -1
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/tests/test_submit.py +1 -1
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/LICENSE +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/advent_of_code_data.egg-info/dependency_links.txt +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/advent_of_code_data.egg-info/entry_points.txt +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/advent_of_code_data.egg-info/requires.txt +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/advent_of_code_data.egg-info/top_level.txt +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/aocd/exceptions.py +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/setup.cfg +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/tests/test_aocd.py +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/tests/test_auth.py +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/tests/test_cli.py +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/tests/test_cookies.py +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/tests/test_date_finding.py +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/tests/test_date_introspection.py +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/tests/test_example_parser.py +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/tests/test_get_data.py +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/tests/test_runner.py +0 -0
- {advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/tests/test_utils.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: advent-of-code-data
|
|
3
|
-
Version: 2.0.
|
|
3
|
+
Version: 2.0.2
|
|
4
4
|
Summary: Get your puzzle data with a single import
|
|
5
5
|
Author-email: Wim Glenn <hey@wimglenn.com>
|
|
6
6
|
License: MIT
|
|
@@ -12,8 +12,15 @@ Classifier: Topic :: Software Development :: Libraries
|
|
|
12
12
|
Classifier: Topic :: Games/Entertainment :: Puzzle Games
|
|
13
13
|
Requires-Python: >=3.9
|
|
14
14
|
Description-Content-Type: text/x-rst
|
|
15
|
-
Provides-Extra: nb
|
|
16
15
|
License-File: LICENSE
|
|
16
|
+
Requires-Dist: beautifulsoup4
|
|
17
|
+
Requires-Dist: pebble
|
|
18
|
+
Requires-Dist: urllib3
|
|
19
|
+
Requires-Dist: tzdata; platform_system == "Windows"
|
|
20
|
+
Requires-Dist: aocd-example-parser>=2023.2
|
|
21
|
+
Provides-Extra: nb
|
|
22
|
+
Requires-Dist: IPython; extra == "nb"
|
|
23
|
+
Requires-Dist: jupyter-server; extra == "nb"
|
|
17
24
|
|
|
18
25
|
Advent of Code data
|
|
19
26
|
===================
|
|
@@ -118,8 +125,8 @@ variable to some existing directory if you wish to use another location to store
|
|
|
118
125
|
|
|
119
126
|
*New in version 0.9.0.* There's a utility script ``aocd-token`` which attempts to
|
|
120
127
|
find session tokens from your browser's cookie storage. This feature is experimental
|
|
121
|
-
and requires you to additionally install the package ``browser-cookie3``. Only Chrome
|
|
122
|
-
and
|
|
128
|
+
and requires you to additionally install the package ``browser-cookie3``. Only Chrome,
|
|
129
|
+
Firefox, and Edge browsers are currently supported. On macOS, you may get an authentication
|
|
123
130
|
dialog requesting permission, since Python is attempting to read browser storage files.
|
|
124
131
|
This is expected, the script *is* actually scraping those private files to access AoC
|
|
125
132
|
session token(s).
|
|
@@ -101,8 +101,8 @@ variable to some existing directory if you wish to use another location to store
|
|
|
101
101
|
|
|
102
102
|
*New in version 0.9.0.* There's a utility script ``aocd-token`` which attempts to
|
|
103
103
|
find session tokens from your browser's cookie storage. This feature is experimental
|
|
104
|
-
and requires you to additionally install the package ``browser-cookie3``. Only Chrome
|
|
105
|
-
and
|
|
104
|
+
and requires you to additionally install the package ``browser-cookie3``. Only Chrome,
|
|
105
|
+
Firefox, and Edge browsers are currently supported. On macOS, you may get an authentication
|
|
106
106
|
dialog requesting permission, since Python is attempting to read browser storage files.
|
|
107
107
|
This is expected, the script *is* actually scraping those private files to access AoC
|
|
108
108
|
session token(s).
|
{advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/advent_of_code_data.egg-info/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: advent-of-code-data
|
|
3
|
-
Version: 2.0.
|
|
3
|
+
Version: 2.0.2
|
|
4
4
|
Summary: Get your puzzle data with a single import
|
|
5
5
|
Author-email: Wim Glenn <hey@wimglenn.com>
|
|
6
6
|
License: MIT
|
|
@@ -12,8 +12,15 @@ Classifier: Topic :: Software Development :: Libraries
|
|
|
12
12
|
Classifier: Topic :: Games/Entertainment :: Puzzle Games
|
|
13
13
|
Requires-Python: >=3.9
|
|
14
14
|
Description-Content-Type: text/x-rst
|
|
15
|
-
Provides-Extra: nb
|
|
16
15
|
License-File: LICENSE
|
|
16
|
+
Requires-Dist: beautifulsoup4
|
|
17
|
+
Requires-Dist: pebble
|
|
18
|
+
Requires-Dist: urllib3
|
|
19
|
+
Requires-Dist: tzdata; platform_system == "Windows"
|
|
20
|
+
Requires-Dist: aocd-example-parser>=2023.2
|
|
21
|
+
Provides-Extra: nb
|
|
22
|
+
Requires-Dist: IPython; extra == "nb"
|
|
23
|
+
Requires-Dist: jupyter-server; extra == "nb"
|
|
17
24
|
|
|
18
25
|
Advent of Code data
|
|
19
26
|
===================
|
|
@@ -118,8 +125,8 @@ variable to some existing directory if you wish to use another location to store
|
|
|
118
125
|
|
|
119
126
|
*New in version 0.9.0.* There's a utility script ``aocd-token`` which attempts to
|
|
120
127
|
find session tokens from your browser's cookie storage. This feature is experimental
|
|
121
|
-
and requires you to additionally install the package ``browser-cookie3``. Only Chrome
|
|
122
|
-
and
|
|
128
|
+
and requires you to additionally install the package ``browser-cookie3``. Only Chrome,
|
|
129
|
+
Firefox, and Edge browsers are currently supported. On macOS, you may get an authentication
|
|
123
130
|
dialog requesting permission, since Python is attempting to read browser storage files.
|
|
124
131
|
This is expected, the script *is* actually scraping those private files to access AoC
|
|
125
132
|
session token(s).
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import sys
|
|
2
|
+
import typing as t
|
|
2
3
|
from functools import partial
|
|
3
4
|
|
|
4
5
|
from . import _ipykernel
|
|
@@ -10,14 +11,36 @@ from . import get
|
|
|
10
11
|
from . import models
|
|
11
12
|
from . import post
|
|
12
13
|
from . import runner
|
|
14
|
+
from . import types
|
|
13
15
|
from . import utils
|
|
14
16
|
from .exceptions import AocdError
|
|
15
17
|
from .get import get_data
|
|
16
18
|
from .get import get_day_and_year
|
|
17
19
|
from .post import submit as _impartial_submit
|
|
18
20
|
|
|
21
|
+
__all__ = [
|
|
22
|
+
"AocdError",
|
|
23
|
+
"cli",
|
|
24
|
+
"cookies",
|
|
25
|
+
"data",
|
|
26
|
+
"examples",
|
|
27
|
+
"exceptions",
|
|
28
|
+
"get",
|
|
29
|
+
"get_data",
|
|
30
|
+
"models",
|
|
31
|
+
"post",
|
|
32
|
+
"runner",
|
|
33
|
+
"submit",
|
|
34
|
+
"types",
|
|
35
|
+
"utils",
|
|
36
|
+
]
|
|
19
37
|
|
|
20
|
-
|
|
38
|
+
if t.TYPE_CHECKING:
|
|
39
|
+
data: str
|
|
40
|
+
submit = _impartial_submit
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def __getattr__(name: str) -> t.Any:
|
|
21
44
|
if name == "data":
|
|
22
45
|
day, year = get_day_and_year()
|
|
23
46
|
return get_data(day=day, year=year)
|
|
@@ -17,7 +17,8 @@ def get_ipynb_path():
|
|
|
17
17
|
for serv in serverapp.list_running_servers():
|
|
18
18
|
url = url_path_join(serv["url"], "api/sessions")
|
|
19
19
|
resp = http.request("GET", url, fields={"token": serv["token"]})
|
|
20
|
-
resp.
|
|
20
|
+
if resp.status >= 400:
|
|
21
|
+
raise urllib3.exceptions.ResponseError(f"HTTP {resp.status}")
|
|
21
22
|
for sess in resp.json():
|
|
22
23
|
if kernel_id == sess["kernel"]["id"]:
|
|
23
24
|
path = serv["root_dir"]
|
|
@@ -12,10 +12,10 @@ from .utils import colored
|
|
|
12
12
|
from .utils import get_owner
|
|
13
13
|
|
|
14
14
|
|
|
15
|
-
log = logging.getLogger(__name__)
|
|
15
|
+
log: logging.Logger = logging.getLogger(__name__)
|
|
16
16
|
|
|
17
17
|
|
|
18
|
-
def get_working_tokens():
|
|
18
|
+
def get_working_tokens() -> dict[str, str]:
|
|
19
19
|
"""Check browser cookie storage for session tokens from .adventofcode.com domain."""
|
|
20
20
|
log.debug("checking for installation of browser-cookie3 package")
|
|
21
21
|
try:
|
|
@@ -48,9 +48,20 @@ def get_working_tokens():
|
|
|
48
48
|
firefox = [c for c in firefox if c.name == "session"]
|
|
49
49
|
log.info("%d candidates from firefox", len(firefox))
|
|
50
50
|
|
|
51
|
+
log.info("checking edge cookie jar...")
|
|
52
|
+
try:
|
|
53
|
+
edge = bc3.edge(domain_name=".adventofcode.com")
|
|
54
|
+
except Exception as err:
|
|
55
|
+
log.debug("Couldn't scrape edge - %s: %s", type(err), err)
|
|
56
|
+
edge = []
|
|
57
|
+
else:
|
|
58
|
+
edge = [c for c in edge if c.name == "session"]
|
|
59
|
+
log.info("%d candidates from edge", len(edge))
|
|
60
|
+
|
|
61
|
+
cookies = chrome + firefox + edge
|
|
51
62
|
# order preserving de-dupe
|
|
52
|
-
tokens = list({}.fromkeys([c.value for c in
|
|
53
|
-
removed = len(
|
|
63
|
+
tokens = list({}.fromkeys([c.value for c in cookies if c.value is not None]))
|
|
64
|
+
removed = len(cookies) - len(tokens)
|
|
54
65
|
if removed:
|
|
55
66
|
log.info("Removed %d duplicate%s", removed, "s"[: removed - 1])
|
|
56
67
|
|
|
@@ -66,7 +77,7 @@ def get_working_tokens():
|
|
|
66
77
|
return result
|
|
67
78
|
|
|
68
79
|
|
|
69
|
-
def scrape_session_tokens():
|
|
80
|
+
def scrape_session_tokens() -> None:
|
|
70
81
|
"""Scrape AoC session tokens from your browser's cookie storage."""
|
|
71
82
|
aocd_token_path = AOCD_CONFIG_DIR / "token"
|
|
72
83
|
aocd_tokens_path = AOCD_CONFIG_DIR / "tokens.json"
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
1
3
|
import argparse
|
|
2
4
|
import logging
|
|
3
5
|
import re
|
|
4
6
|
import sys
|
|
7
|
+
import typing as t
|
|
5
8
|
from dataclasses import dataclass
|
|
6
9
|
from datetime import datetime
|
|
7
10
|
from itertools import zip_longest
|
|
@@ -16,7 +19,11 @@ from aocd.utils import AOC_TZ
|
|
|
16
19
|
from aocd.utils import get_plugins
|
|
17
20
|
|
|
18
21
|
|
|
19
|
-
log = logging.getLogger(__name__)
|
|
22
|
+
log: logging.Logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
_AnswerElem = t.Literal[
|
|
25
|
+
"a_code", "a_li", "a_pre", "a_em", "b_code", "b_li", "b_pre", "b_em"
|
|
26
|
+
]
|
|
20
27
|
|
|
21
28
|
|
|
22
29
|
@dataclass
|
|
@@ -34,17 +41,17 @@ class Page:
|
|
|
34
41
|
soup: bs4.BeautifulSoup # The raw_html string parsed into a bs4.BeautifulSoup instance
|
|
35
42
|
year: int # AoC puzzle year (2015+) parsed from html title
|
|
36
43
|
day: int # AoC puzzle day (1-25) parsed from html title
|
|
37
|
-
article_a: bs4.
|
|
38
|
-
article_b: bs4.
|
|
44
|
+
article_a: bs4.Tag # The bs4 tag for the first <article> in the page, i.e. part a
|
|
45
|
+
article_b: bs4.Tag | None # The bs4 tag for the second <article> in the page, i.e. part b. It will be `None` if part b locked
|
|
39
46
|
a_raw: str # The first <article> html as a string
|
|
40
|
-
b_raw: str # The second <article> html as a string. Will be `None` if part b locked
|
|
47
|
+
b_raw: str | None # The second <article> html as a string. Will be `None` if part b locked
|
|
41
48
|
|
|
42
|
-
def __repr__(self):
|
|
49
|
+
def __repr__(self) -> str:
|
|
43
50
|
part_a_only = "*" if self.article_b is None else ""
|
|
44
51
|
return f"<Page({self.year}, {self.day}){part_a_only} at {hex(id(self))}>"
|
|
45
52
|
|
|
46
53
|
@classmethod
|
|
47
|
-
def from_raw(cls, html):
|
|
54
|
+
def from_raw(cls, html: str) -> Page:
|
|
48
55
|
soup = _get_soup(html)
|
|
49
56
|
title_pat = r"^Day (\d{1,2}) - Advent of Code (\d{4})$"
|
|
50
57
|
title_text = soup.title.text
|
|
@@ -77,7 +84,7 @@ class Page:
|
|
|
77
84
|
)
|
|
78
85
|
return page
|
|
79
86
|
|
|
80
|
-
def __getattr__(self, name):
|
|
87
|
+
def __getattr__(self, name: _AnswerElem) -> t.Sequence[str]:
|
|
81
88
|
if not name.startswith(("a_", "b_")):
|
|
82
89
|
raise AttributeError(name)
|
|
83
90
|
part, sep, tag = name.partition("_")
|
|
@@ -118,12 +125,12 @@ class Example(NamedTuple):
|
|
|
118
125
|
"""
|
|
119
126
|
|
|
120
127
|
input_data: str
|
|
121
|
-
answer_a: str = None
|
|
122
|
-
answer_b: str = None
|
|
123
|
-
extra: str = None
|
|
128
|
+
answer_a: str | None = None
|
|
129
|
+
answer_b: str | None = None
|
|
130
|
+
extra: str | None = None
|
|
124
131
|
|
|
125
132
|
@property
|
|
126
|
-
def answers(self):
|
|
133
|
+
def answers(self) -> tuple[str | None, str | None]:
|
|
127
134
|
return self.answer_a, self.answer_b
|
|
128
135
|
|
|
129
136
|
|
|
@@ -144,7 +151,7 @@ def _get_unique_real_inputs(year, day):
|
|
|
144
151
|
return list({}.fromkeys(strs))
|
|
145
152
|
|
|
146
153
|
|
|
147
|
-
def main():
|
|
154
|
+
def main() -> None:
|
|
148
155
|
"""
|
|
149
156
|
Summarize an example parser's results with historical puzzles' prose, and
|
|
150
157
|
compare the performance against a reference implementation
|
|
@@ -1,8 +1,12 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
1
3
|
import datetime
|
|
2
4
|
import os
|
|
3
5
|
import re
|
|
4
6
|
import traceback
|
|
7
|
+
import typing as t
|
|
5
8
|
from logging import getLogger
|
|
9
|
+
from logging import Logger
|
|
6
10
|
|
|
7
11
|
from ._ipykernel import get_ipynb_path
|
|
8
12
|
from .exceptions import AocdError
|
|
@@ -14,10 +18,15 @@ from .utils import AOC_TZ
|
|
|
14
18
|
from .utils import blocker
|
|
15
19
|
|
|
16
20
|
|
|
17
|
-
log = getLogger(__name__)
|
|
21
|
+
log: Logger = getLogger(__name__)
|
|
18
22
|
|
|
19
23
|
|
|
20
|
-
def get_data(
|
|
24
|
+
def get_data(
|
|
25
|
+
session: str | None = None,
|
|
26
|
+
day: int | None = None,
|
|
27
|
+
year: int | None = None,
|
|
28
|
+
block: bool = False,
|
|
29
|
+
) -> str:
|
|
21
30
|
"""
|
|
22
31
|
Get data for day (1-25) and year (2015+).
|
|
23
32
|
User's session cookie (str) is needed - puzzle inputs differ by user.
|
|
@@ -45,7 +54,7 @@ def get_data(session=None, day=None, year=None, block=False):
|
|
|
45
54
|
return puzzle.input_data
|
|
46
55
|
|
|
47
56
|
|
|
48
|
-
def most_recent_year():
|
|
57
|
+
def most_recent_year() -> int:
|
|
49
58
|
"""
|
|
50
59
|
This year, if it's December.
|
|
51
60
|
The most recent year, otherwise.
|
|
@@ -60,7 +69,7 @@ def most_recent_year():
|
|
|
60
69
|
return year
|
|
61
70
|
|
|
62
71
|
|
|
63
|
-
def current_day():
|
|
72
|
+
def current_day() -> int:
|
|
64
73
|
"""
|
|
65
74
|
Most recent day, if it's during the Advent of Code. Happy Holidays!
|
|
66
75
|
Day 1 is assumed, otherwise.
|
|
@@ -73,7 +82,7 @@ def current_day():
|
|
|
73
82
|
return day
|
|
74
83
|
|
|
75
84
|
|
|
76
|
-
def get_day_and_year():
|
|
85
|
+
def get_day_and_year() -> tuple[int, int | None]:
|
|
77
86
|
"""
|
|
78
87
|
Returns tuple (day, year).
|
|
79
88
|
|
|
@@ -1,12 +1,18 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
1
4
|
import json
|
|
2
5
|
import logging
|
|
3
6
|
import os
|
|
4
7
|
import re
|
|
5
8
|
import sys
|
|
6
9
|
import time
|
|
10
|
+
import typing as t
|
|
7
11
|
import webbrowser
|
|
8
12
|
from datetime import datetime
|
|
9
13
|
from datetime import timedelta
|
|
14
|
+
from decimal import Decimal
|
|
15
|
+
from fractions import Fraction
|
|
10
16
|
from functools import cache
|
|
11
17
|
from functools import cached_property
|
|
12
18
|
from importlib.metadata import entry_points
|
|
@@ -15,12 +21,17 @@ from pathlib import Path
|
|
|
15
21
|
from textwrap import dedent
|
|
16
22
|
|
|
17
23
|
from . import examples
|
|
24
|
+
from .examples import Example
|
|
18
25
|
from .exceptions import AocdError
|
|
19
26
|
from .exceptions import DeadTokenError
|
|
20
27
|
from .exceptions import ExampleParserError
|
|
21
28
|
from .exceptions import PuzzleLockedError
|
|
22
29
|
from .exceptions import PuzzleUnsolvedError
|
|
23
30
|
from .exceptions import UnknownUserError
|
|
31
|
+
from .types import AnswerValue
|
|
32
|
+
from .types import PuzzlePart
|
|
33
|
+
from .types import PuzzleStats
|
|
34
|
+
from .types import Submission
|
|
24
35
|
from .utils import _ensure_intermediate_dirs
|
|
25
36
|
from .utils import _get_soup
|
|
26
37
|
from .utils import AOC_TZ
|
|
@@ -31,7 +42,7 @@ from .utils import get_plugins
|
|
|
31
42
|
from .utils import http
|
|
32
43
|
|
|
33
44
|
|
|
34
|
-
log = logging.getLogger(__name__)
|
|
45
|
+
log: logging.Logger = logging.getLogger(__name__)
|
|
35
46
|
|
|
36
47
|
|
|
37
48
|
AOCD_DATA_DIR = Path(os.environ.get("AOCD_DIR", Path("~", ".config", "aocd")))
|
|
@@ -43,12 +54,12 @@ URL = "https://adventofcode.com/{year}/day/{day}"
|
|
|
43
54
|
class User:
|
|
44
55
|
_token2id = None
|
|
45
56
|
|
|
46
|
-
def __init__(self, token):
|
|
57
|
+
def __init__(self, token: str) -> None:
|
|
47
58
|
self.token = token
|
|
48
59
|
self._owner = "unknown.unknown.0"
|
|
49
60
|
|
|
50
61
|
@classmethod
|
|
51
|
-
def from_id(cls, id):
|
|
62
|
+
def from_id(cls, id: str) -> User:
|
|
52
63
|
users = _load_users()
|
|
53
64
|
if id not in users:
|
|
54
65
|
raise UnknownUserError(f"User with id '{id}' is not known")
|
|
@@ -57,7 +68,7 @@ class User:
|
|
|
57
68
|
return user
|
|
58
69
|
|
|
59
70
|
@property
|
|
60
|
-
def id(self):
|
|
71
|
+
def id(self) -> str:
|
|
61
72
|
"""
|
|
62
73
|
User's token might change (they expire eventually) but the id found on AoC's
|
|
63
74
|
settings page for a logged-in user is as close as we can get to a primary key.
|
|
@@ -86,27 +97,33 @@ class User:
|
|
|
86
97
|
self._owner = owner
|
|
87
98
|
return owner
|
|
88
99
|
|
|
89
|
-
def __str__(self):
|
|
100
|
+
def __str__(self) -> str:
|
|
90
101
|
return f"<{type(self).__name__} {self._owner} (token=...{self.token[-4:]})>"
|
|
91
102
|
|
|
92
103
|
@property
|
|
93
|
-
def memo_dir(self):
|
|
104
|
+
def memo_dir(self) -> Path:
|
|
94
105
|
"""
|
|
95
106
|
Directory where this user's puzzle inputs, answers etc. are stored on filesystem.
|
|
96
107
|
"""
|
|
97
108
|
return AOCD_DATA_DIR / self.id
|
|
98
109
|
|
|
99
|
-
def get_stats(
|
|
110
|
+
def get_stats(
|
|
111
|
+
self, years: int | t.Iterable[int] | None = None
|
|
112
|
+
) -> dict[str, dict[PuzzlePart, PuzzleStats]]:
|
|
100
113
|
"""
|
|
101
114
|
Parsed version of your personal stats (rank, solve time, score).
|
|
102
115
|
See https://adventofcode.com/<year>/leaderboard/self when logged in.
|
|
103
116
|
"""
|
|
104
117
|
aoc_now = datetime.now(tz=AOC_TZ)
|
|
105
118
|
all_years = range(2015, aoc_now.year + int(aoc_now.month == 12))
|
|
106
|
-
if isinstance(years, int)
|
|
119
|
+
if isinstance(years, int):
|
|
107
120
|
years = (years,)
|
|
108
121
|
if years is None:
|
|
109
122
|
years = all_years
|
|
123
|
+
invalid_years = sorted([y for y in years if y not in all_years])
|
|
124
|
+
if invalid_years:
|
|
125
|
+
bad = ', '.join(map(str, invalid_years))
|
|
126
|
+
raise ValueError(f"Invalid years: {bad}")
|
|
110
127
|
days = {str(i) for i in range(1, 26)}
|
|
111
128
|
results = {}
|
|
112
129
|
ur_broke = "You haven't collected any stars"
|
|
@@ -144,7 +161,7 @@ class User:
|
|
|
144
161
|
return results
|
|
145
162
|
|
|
146
163
|
|
|
147
|
-
def default_user():
|
|
164
|
+
def default_user() -> User:
|
|
148
165
|
"""
|
|
149
166
|
Discover user's token from the environment or file, and exit with a diagnostic
|
|
150
167
|
message if none can be found. This default user is used whenever a token or user id
|
|
@@ -178,30 +195,30 @@ def default_user():
|
|
|
178
195
|
|
|
179
196
|
|
|
180
197
|
class Puzzle:
|
|
181
|
-
def __init__(self, year, day, user=None):
|
|
198
|
+
def __init__(self, year: int, day: int, user: User | None = None) -> None:
|
|
182
199
|
self.year = year
|
|
183
200
|
self.day = day
|
|
184
201
|
if user is None:
|
|
185
202
|
user = default_user()
|
|
186
203
|
self._user = user
|
|
187
|
-
self.input_data_url = self.url + "/input"
|
|
188
|
-
self.submit_url = self.url + "/answer"
|
|
204
|
+
self.input_data_url: str = self.url + "/input"
|
|
205
|
+
self.submit_url: str = self.url + "/answer"
|
|
189
206
|
pre = self.user.memo_dir / f"{self.year}_{self.day:02d}"
|
|
190
|
-
self.input_data_path = pre.with_name(pre.name + "_input.txt")
|
|
191
|
-
self.answer_a_path = pre.with_name(pre.name + "a_answer.txt")
|
|
192
|
-
self.answer_b_path = pre.with_name(pre.name + "b_answer.txt")
|
|
193
|
-
self.submit_results_path = pre.with_name(pre.name + "_post.json")
|
|
194
|
-
self.prose0_path = AOCD_DATA_DIR / "prose" / (pre.name + "_prose.0.html")
|
|
195
|
-
self.prose1_path = pre.with_name(pre.name + "_prose.1.html") # part a solved
|
|
196
|
-
self.prose2_path = pre.with_name(pre.name + "_prose.2.html") # part b solved
|
|
207
|
+
self.input_data_path: Path = pre.with_name(pre.name + "_input.txt")
|
|
208
|
+
self.answer_a_path: Path = pre.with_name(pre.name + "a_answer.txt")
|
|
209
|
+
self.answer_b_path: Path = pre.with_name(pre.name + "b_answer.txt")
|
|
210
|
+
self.submit_results_path: Path = pre.with_name(pre.name + "_post.json")
|
|
211
|
+
self.prose0_path: Path = AOCD_DATA_DIR / "prose" / (pre.name + "_prose.0.html")
|
|
212
|
+
self.prose1_path: Path = pre.with_name(pre.name + "_prose.1.html") # part a solved
|
|
213
|
+
self.prose2_path: Path = pre.with_name(pre.name + "_prose.2.html") # part b solved
|
|
197
214
|
|
|
198
215
|
@property
|
|
199
|
-
def user(self):
|
|
216
|
+
def user(self) -> User:
|
|
200
217
|
# this is a property to make it clear that it's read-only
|
|
201
218
|
return self._user
|
|
202
219
|
|
|
203
220
|
@property
|
|
204
|
-
def input_data(self):
|
|
221
|
+
def input_data(self) -> str:
|
|
205
222
|
"""
|
|
206
223
|
This puzzle's input data, specific to puzzle.user. It will usually be retrieved
|
|
207
224
|
from caches, but if this is the first time it was accessed it will be requested
|
|
@@ -231,14 +248,14 @@ class Puzzle:
|
|
|
231
248
|
return data.rstrip("\r\n")
|
|
232
249
|
|
|
233
250
|
@property
|
|
234
|
-
def examples(self):
|
|
251
|
+
def examples(self) -> list[Example]:
|
|
235
252
|
"""
|
|
236
253
|
Sample data and answers associated with this puzzle, as a list of
|
|
237
254
|
`aocd.examples.Example` instances. These are extracted from the puzzle prose
|
|
238
255
|
html, and they're the same for every user id. This list might be empty (not
|
|
239
256
|
every puzzle has usable examples), or it might have several examples, but it
|
|
240
257
|
will usually have one element. The list, and the examples themselves, may be
|
|
241
|
-
different
|
|
258
|
+
different regardless of whether part b of the puzzle prose has been
|
|
242
259
|
unlocked (i.e. part a has already been solved correctly).
|
|
243
260
|
"""
|
|
244
261
|
return self._get_examples()
|
|
@@ -262,7 +279,7 @@ class Puzzle:
|
|
|
262
279
|
return result
|
|
263
280
|
|
|
264
281
|
@cached_property
|
|
265
|
-
def title(self):
|
|
282
|
+
def title(self) -> str:
|
|
266
283
|
"""
|
|
267
284
|
Title of the puzzle, used in the pretty repr (IPython etc) and also displayed
|
|
268
285
|
by aocd.runner.
|
|
@@ -291,35 +308,49 @@ class Puzzle:
|
|
|
291
308
|
# but it's convenient to be able to submit numbers, since many of the answers
|
|
292
309
|
# are numeric strings. coerce the values to string safely.
|
|
293
310
|
orig_val = val
|
|
294
|
-
orig_type = type(val)
|
|
295
311
|
coerced = False
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
#
|
|
302
|
-
if
|
|
312
|
+
# A user can't be submitting a numpy type if numpy is not installed, so skip
|
|
313
|
+
# handling of those types
|
|
314
|
+
with contextlib.suppress(ImportError):
|
|
315
|
+
import numpy as np
|
|
316
|
+
|
|
317
|
+
# "unwrap" arrays that contain a single element
|
|
318
|
+
if isinstance(val, np.ndarray) and val.size == 1:
|
|
319
|
+
coerced = True
|
|
320
|
+
val = val.item()
|
|
321
|
+
if isinstance(val, (np.integer, np.floating, np.complexfloating)) and val.imag == 0 and val.real.is_integer():
|
|
303
322
|
coerced = True
|
|
304
|
-
val = int(
|
|
305
|
-
elif orig_type.__name__.startswith(("float", "complex")):
|
|
306
|
-
if val.imag == 0.0 and float(val.real).is_integer():
|
|
307
|
-
coerced = True
|
|
308
|
-
val = int(val.real)
|
|
323
|
+
val = str(int(val.real))
|
|
309
324
|
if isinstance(val, int):
|
|
310
325
|
val = str(val)
|
|
326
|
+
elif isinstance(val, (float, complex)) and val.imag == 0 and val.real.is_integer():
|
|
327
|
+
coerced = True
|
|
328
|
+
val = str(int(val.real))
|
|
329
|
+
elif isinstance(val, bytes):
|
|
330
|
+
coerced = True
|
|
331
|
+
val = val.decode()
|
|
332
|
+
elif isinstance(val, (Decimal, Fraction)):
|
|
333
|
+
# if val can be represented as an integer ratio where the denominator is 1
|
|
334
|
+
# val is an integer and val == numerator
|
|
335
|
+
numerator, denominator = val.as_integer_ratio()
|
|
336
|
+
if denominator == 1:
|
|
337
|
+
coerced = True
|
|
338
|
+
val = str(numerator)
|
|
339
|
+
if not isinstance(val, str):
|
|
340
|
+
raise AocdError(f"Failed to coerce {type(orig_val).__name__} value {orig_val!r} for {self.year}/{self.day:02}.")
|
|
311
341
|
if coerced:
|
|
312
342
|
log.warning(
|
|
313
|
-
"coerced %s value %r for %d/%02d",
|
|
314
|
-
|
|
343
|
+
"coerced %s value %r for %d/%02d to %r",
|
|
344
|
+
type(orig_val).__name__,
|
|
315
345
|
orig_val,
|
|
316
346
|
self.year,
|
|
317
347
|
self.day,
|
|
348
|
+
val,
|
|
318
349
|
)
|
|
319
350
|
return val
|
|
320
351
|
|
|
321
352
|
@property
|
|
322
|
-
def answer_a(self):
|
|
353
|
+
def answer_a(self) -> str:
|
|
323
354
|
"""
|
|
324
355
|
The correct answer for the first part of the puzzle. This attribute hides
|
|
325
356
|
itself if the first part has not yet been solved.
|
|
@@ -330,7 +361,7 @@ class Puzzle:
|
|
|
330
361
|
raise AttributeError("answer_a")
|
|
331
362
|
|
|
332
363
|
@answer_a.setter
|
|
333
|
-
def answer_a(self, val):
|
|
364
|
+
def answer_a(self, val: AnswerValue) -> None:
|
|
334
365
|
"""
|
|
335
366
|
You can submit your answer to adventofcode.com by setting the answer attribute
|
|
336
367
|
on a puzzle instance, e.g.
|
|
@@ -346,12 +377,12 @@ class Puzzle:
|
|
|
346
377
|
self._submit(value=val, part="a")
|
|
347
378
|
|
|
348
379
|
@property
|
|
349
|
-
def answered_a(self):
|
|
380
|
+
def answered_a(self) -> bool:
|
|
350
381
|
"""Has the first part of this puzzle been solved correctly yet?"""
|
|
351
382
|
return bool(getattr(self, "answer_a", None))
|
|
352
383
|
|
|
353
384
|
@property
|
|
354
|
-
def answer_b(self):
|
|
385
|
+
def answer_b(self) -> str:
|
|
355
386
|
"""
|
|
356
387
|
The correct answer for the second part of the puzzle. This attribute hides
|
|
357
388
|
itself if the second part has not yet been solved.
|
|
@@ -362,7 +393,7 @@ class Puzzle:
|
|
|
362
393
|
raise AttributeError("answer_b")
|
|
363
394
|
|
|
364
395
|
@answer_b.setter
|
|
365
|
-
def answer_b(self, val):
|
|
396
|
+
def answer_b(self, val: AnswerValue) -> None:
|
|
366
397
|
"""
|
|
367
398
|
You can submit your answer to adventofcode.com by setting the answer attribute
|
|
368
399
|
on a puzzle instance, e.g.
|
|
@@ -378,11 +409,11 @@ class Puzzle:
|
|
|
378
409
|
self._submit(value=val, part="b")
|
|
379
410
|
|
|
380
411
|
@property
|
|
381
|
-
def answered_b(self):
|
|
412
|
+
def answered_b(self) -> bool:
|
|
382
413
|
"""Has the second part of this puzzle been solved correctly yet?"""
|
|
383
414
|
return bool(getattr(self, "answer_b", None))
|
|
384
415
|
|
|
385
|
-
def answered(self, part):
|
|
416
|
+
def answered(self, part: PuzzlePart) -> bool:
|
|
386
417
|
"""Has the specified part of this puzzle been solved correctly yet?"""
|
|
387
418
|
if part == "a":
|
|
388
419
|
return bool(getattr(self, "answer_a", None))
|
|
@@ -391,7 +422,7 @@ class Puzzle:
|
|
|
391
422
|
raise AocdError('part must be "a" or "b"')
|
|
392
423
|
|
|
393
424
|
@property
|
|
394
|
-
def answers(self):
|
|
425
|
+
def answers(self) -> tuple[str, str]:
|
|
395
426
|
"""
|
|
396
427
|
Returns a tuple of the correct answers for this puzzle. Will raise an
|
|
397
428
|
AttributeError if either part is yet to be solved by the associated user.
|
|
@@ -399,7 +430,7 @@ class Puzzle:
|
|
|
399
430
|
return self.answer_a, self.answer_b
|
|
400
431
|
|
|
401
432
|
@answers.setter
|
|
402
|
-
def answers(self, val):
|
|
433
|
+
def answers(self, val: tuple[AnswerValue, AnswerValue]) -> None:
|
|
403
434
|
"""
|
|
404
435
|
Submit both answers at once. Pretty much impossible in practice, unless you've
|
|
405
436
|
seen the puzzle before.
|
|
@@ -407,7 +438,7 @@ class Puzzle:
|
|
|
407
438
|
self.answer_a, self.answer_b = val
|
|
408
439
|
|
|
409
440
|
@property
|
|
410
|
-
def submit_results(self):
|
|
441
|
+
def submit_results(self) -> list[Submission]:
|
|
411
442
|
"""
|
|
412
443
|
Record of all previous submissions to adventofcode.com for this user/puzzle.
|
|
413
444
|
Submissions made by typing answers directly into the website will not be
|
|
@@ -653,7 +684,7 @@ class Puzzle:
|
|
|
653
684
|
msg = f"Answer {self.year}-{self.day}{part} is not available"
|
|
654
685
|
raise PuzzleUnsolvedError(msg)
|
|
655
686
|
|
|
656
|
-
def solve(self):
|
|
687
|
+
def solve(self) -> tuple[AnswerValue, AnswerValue]:
|
|
657
688
|
"""
|
|
658
689
|
If there is a unique entry-point in the "adventofcode.user" group, load it and
|
|
659
690
|
invoke it using this puzzle's input data. It is expected to return a tuple of
|
|
@@ -668,7 +699,7 @@ class Puzzle:
|
|
|
668
699
|
f = ep.load()
|
|
669
700
|
return f(year=self.year, day=self.day, data=self.input_data)
|
|
670
701
|
|
|
671
|
-
def solve_for(self, plugin):
|
|
702
|
+
def solve_for(self, plugin: str) -> tuple[AnswerValue, AnswerValue]:
|
|
672
703
|
"""
|
|
673
704
|
Load the entry-point from the "adventofcode.user" plugin group with the
|
|
674
705
|
specified name, and invoke it using this puzzle's input data. The entry-point
|
|
@@ -685,16 +716,16 @@ class Puzzle:
|
|
|
685
716
|
return f(year=self.year, day=self.day, data=self.input_data)
|
|
686
717
|
|
|
687
718
|
@property
|
|
688
|
-
def url(self):
|
|
719
|
+
def url(self) -> str:
|
|
689
720
|
"""A link to the puzzle's description page on adventofcode.com."""
|
|
690
721
|
return URL.format(year=self.year, day=self.day)
|
|
691
722
|
|
|
692
|
-
def view(self):
|
|
723
|
+
def view(self) -> None:
|
|
693
724
|
"""Open this puzzle's description page in a new browser tab"""
|
|
694
725
|
webbrowser.open(self.url)
|
|
695
726
|
|
|
696
727
|
@property
|
|
697
|
-
def my_stats(self):
|
|
728
|
+
def my_stats(self) -> dict[PuzzlePart, PuzzleStats]:
|
|
698
729
|
"""
|
|
699
730
|
Your personal stats (rank, solve time, score) for this particular puzzle.
|
|
700
731
|
Raises `PuzzleUnsolvedError` if you haven't actually solved it yet.
|
|
@@ -766,7 +797,7 @@ class Puzzle:
|
|
|
766
797
|
raise AocdError(f"Could not get prose for {self.year}/{self.day:02d}")
|
|
767
798
|
|
|
768
799
|
@property
|
|
769
|
-
def easter_eggs(self):
|
|
800
|
+
def easter_eggs(self) -> list[str]:
|
|
770
801
|
"""
|
|
771
802
|
Return a list of Easter eggs in the puzzle's description page. When you've
|
|
772
803
|
completed all 25 days, adventofcode.com will reveal the Easter eggs directly in
|
|
@@ -779,7 +810,7 @@ class Puzzle:
|
|
|
779
810
|
eggs = soup.find_all(["span", "em", "code"], class_=None, attrs={"title": bool})
|
|
780
811
|
return eggs
|
|
781
812
|
|
|
782
|
-
def unlock_time(self, local=True):
|
|
813
|
+
def unlock_time(self, local: bool = True) -> datetime:
|
|
783
814
|
"""
|
|
784
815
|
The time this puzzle unlocked. Might be in the future.
|
|
785
816
|
If local is True (default), returns a datetime in your local zone.
|
|
@@ -792,7 +823,7 @@ class Puzzle:
|
|
|
792
823
|
return result
|
|
793
824
|
|
|
794
825
|
@staticmethod
|
|
795
|
-
def all(user=None):
|
|
826
|
+
def all(user: User | None = None) -> t.Iterator[Puzzle]:
|
|
796
827
|
"""
|
|
797
828
|
Return an iterator over all known puzzles that are currently playable.
|
|
798
829
|
"""
|
|
@@ -1,18 +1,32 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
1
3
|
import logging
|
|
4
|
+
import typing as t
|
|
2
5
|
|
|
3
6
|
from .get import current_day
|
|
4
7
|
from .get import most_recent_year
|
|
5
8
|
from .models import default_user
|
|
6
9
|
from .models import Puzzle
|
|
7
10
|
from .models import User
|
|
11
|
+
from .types import AnswerValue
|
|
12
|
+
from .types import PuzzlePart
|
|
13
|
+
|
|
14
|
+
if t.TYPE_CHECKING:
|
|
15
|
+
from urllib3 import BaseHTTPResponse
|
|
8
16
|
|
|
9
17
|
|
|
10
|
-
log = logging.getLogger(__name__)
|
|
18
|
+
log: logging.Logger = logging.getLogger(__name__)
|
|
11
19
|
|
|
12
20
|
|
|
13
21
|
def submit(
|
|
14
|
-
answer
|
|
15
|
-
|
|
22
|
+
answer: AnswerValue,
|
|
23
|
+
part: PuzzlePart | None = None,
|
|
24
|
+
day: int | None = None,
|
|
25
|
+
year: int | None = None,
|
|
26
|
+
session: str | None = None,
|
|
27
|
+
reopen: bool = True,
|
|
28
|
+
quiet: bool = False,
|
|
29
|
+
) -> BaseHTTPResponse | None:
|
|
16
30
|
"""
|
|
17
31
|
Submit your answer to adventofcode.com, and print the response to the terminal.
|
|
18
32
|
The only required argument is `answer`, all others can usually be introspected
|
|
File without changes
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
1
3
|
import contextlib
|
|
2
4
|
import itertools
|
|
3
5
|
import logging
|
|
@@ -5,9 +7,11 @@ import os
|
|
|
5
7
|
import sys
|
|
6
8
|
import tempfile
|
|
7
9
|
import time
|
|
10
|
+
import typing as t
|
|
8
11
|
from argparse import ArgumentParser
|
|
9
12
|
from datetime import datetime
|
|
10
13
|
from functools import partial
|
|
14
|
+
from importlib.metadata import EntryPoint
|
|
11
15
|
from pathlib import Path
|
|
12
16
|
|
|
13
17
|
import pebble.concurrent
|
|
@@ -27,10 +31,10 @@ from .utils import get_plugins
|
|
|
27
31
|
|
|
28
32
|
|
|
29
33
|
DEFAULT_TIMEOUT = 60
|
|
30
|
-
log = logging.getLogger(__name__)
|
|
34
|
+
log: logging.Logger = logging.getLogger(__name__)
|
|
31
35
|
|
|
32
36
|
|
|
33
|
-
def main():
|
|
37
|
+
def main() -> t.NoReturn:
|
|
34
38
|
"""
|
|
35
39
|
Run user solver(s) against their inputs and render the results. Can use multiple
|
|
36
40
|
tokens to validate your code against multiple input datas.
|
|
@@ -199,7 +203,14 @@ def _process_wrapper(f, capture=False, **kwargs):
|
|
|
199
203
|
return f(**kwargs)
|
|
200
204
|
|
|
201
205
|
|
|
202
|
-
def run_with_timeout(
|
|
206
|
+
def run_with_timeout(
|
|
207
|
+
entry_point: EntryPoint,
|
|
208
|
+
timeout: float,
|
|
209
|
+
progress: str | None,
|
|
210
|
+
dt: float = 0.1,
|
|
211
|
+
capture: bool = False,
|
|
212
|
+
**kwargs: t.Any,
|
|
213
|
+
) -> tuple[str, str, float, str]:
|
|
203
214
|
"""
|
|
204
215
|
Execute a user solve, and display a progress spinner as it's running. Kill it if
|
|
205
216
|
the runtime exceeds `timeout` seconds.
|
|
@@ -234,7 +245,7 @@ def run_with_timeout(entry_point, timeout, progress, dt=0.1, capture=False, **kw
|
|
|
234
245
|
return a, b, walltime, error
|
|
235
246
|
|
|
236
247
|
|
|
237
|
-
def format_time(t, timeout=DEFAULT_TIMEOUT):
|
|
248
|
+
def format_time(t: float, timeout: float = DEFAULT_TIMEOUT) -> str:
|
|
238
249
|
"""
|
|
239
250
|
Used for rendering the puzzle solve time in color:
|
|
240
251
|
- green, if you're under a quarter of the timeout (15s default)
|
|
@@ -252,8 +263,14 @@ def format_time(t, timeout=DEFAULT_TIMEOUT):
|
|
|
252
263
|
|
|
253
264
|
|
|
254
265
|
def run_one(
|
|
255
|
-
year
|
|
256
|
-
|
|
266
|
+
year: int,
|
|
267
|
+
day: int,
|
|
268
|
+
data: str,
|
|
269
|
+
entry_point: EntryPoint,
|
|
270
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
271
|
+
progress: str | None = None,
|
|
272
|
+
capture: bool = False,
|
|
273
|
+
) -> tuple[str, str, float, str]:
|
|
257
274
|
"""
|
|
258
275
|
Creates a temporary dir and change directory into it (restores cwd on exit).
|
|
259
276
|
Lays down puzzle input in a file called "input.txt" in this directory - user code
|
|
@@ -293,16 +310,16 @@ def run_one(
|
|
|
293
310
|
|
|
294
311
|
|
|
295
312
|
def run_for(
|
|
296
|
-
plugs,
|
|
297
|
-
years,
|
|
298
|
-
days,
|
|
299
|
-
datasets,
|
|
300
|
-
example=False,
|
|
301
|
-
timeout=DEFAULT_TIMEOUT,
|
|
302
|
-
autosubmit=True,
|
|
303
|
-
reopen=False,
|
|
304
|
-
capture=False,
|
|
305
|
-
):
|
|
313
|
+
plugs: t.Collection[str],
|
|
314
|
+
years: t.Iterable[int],
|
|
315
|
+
days: t.Iterable[int],
|
|
316
|
+
datasets: t.Mapping[str, str],
|
|
317
|
+
example: bool = False,
|
|
318
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
319
|
+
autosubmit: bool = True,
|
|
320
|
+
reopen: bool = False,
|
|
321
|
+
capture: bool = False,
|
|
322
|
+
) -> int:
|
|
306
323
|
"""
|
|
307
324
|
Run with multiple users, multiple datasets, multiple years/days, and render the results.
|
|
308
325
|
"""
|
|
@@ -356,7 +373,7 @@ def run_for(
|
|
|
356
373
|
else:
|
|
357
374
|
for answer, part in zip((a, b), "ab"):
|
|
358
375
|
if day == 25 and part == "b":
|
|
359
|
-
# there's no part b on
|
|
376
|
+
# there's no part b on Christmas day, skip
|
|
360
377
|
continue
|
|
361
378
|
expected = None
|
|
362
379
|
try:
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import timedelta
|
|
4
|
+
from numbers import Number
|
|
5
|
+
from typing import Literal
|
|
6
|
+
from typing import TypedDict
|
|
7
|
+
from typing import Union
|
|
8
|
+
|
|
9
|
+
AnswerValue = Union[str, Number]
|
|
10
|
+
"""The answer to a puzzle, either a string or a number. Numbers are coerced to a string"""
|
|
11
|
+
PuzzlePart = Literal["a", "b"]
|
|
12
|
+
"""The part of a given puzzle, a or b"""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PuzzleStats(TypedDict):
|
|
16
|
+
"""Your personal stats for a given puzzle
|
|
17
|
+
|
|
18
|
+
See https://adventofcode.com/<year>/leaderboard/self when logged in.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
time: timedelta
|
|
22
|
+
rank: int
|
|
23
|
+
score: int
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Submission(TypedDict):
|
|
27
|
+
"""Record of a previous submission made for a given puzzle
|
|
28
|
+
|
|
29
|
+
Only applies to answers submitted with aocd.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
part: PuzzlePart
|
|
33
|
+
value: str
|
|
34
|
+
when: str
|
|
35
|
+
message: str
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
1
3
|
import argparse
|
|
2
4
|
import logging
|
|
3
5
|
import os
|
|
@@ -5,12 +7,14 @@ import platform
|
|
|
5
7
|
import shutil
|
|
6
8
|
import sys
|
|
7
9
|
import time
|
|
10
|
+
import typing as t
|
|
8
11
|
from collections import deque
|
|
9
12
|
from datetime import datetime
|
|
10
13
|
from functools import cache
|
|
11
14
|
from importlib.metadata import entry_points
|
|
12
15
|
from importlib.metadata import version
|
|
13
16
|
from itertools import cycle
|
|
17
|
+
from pathlib import Path
|
|
14
18
|
from tempfile import NamedTemporaryFile
|
|
15
19
|
from zoneinfo import ZoneInfo
|
|
16
20
|
|
|
@@ -19,8 +23,16 @@ import urllib3
|
|
|
19
23
|
|
|
20
24
|
from .exceptions import DeadTokenError
|
|
21
25
|
|
|
26
|
+
if sys.version_info >= (3, 10):
|
|
27
|
+
# Python 3.10+
|
|
28
|
+
from importlib.metadata import EntryPoints as _EntryPointsType
|
|
29
|
+
else:
|
|
30
|
+
# Python 3.9
|
|
31
|
+
from importlib.metadata import EntryPoint
|
|
32
|
+
|
|
33
|
+
_EntryPointsType = list[EntryPoint]
|
|
22
34
|
|
|
23
|
-
log = logging.getLogger(__name__)
|
|
35
|
+
log: logging.Logger = logging.getLogger(__name__)
|
|
24
36
|
AOC_TZ = ZoneInfo("America/New_York")
|
|
25
37
|
_v = version("advent-of-code-data")
|
|
26
38
|
USER_AGENT = f"github.com/wimglenn/advent-of-code-data v{_v} by hey@wimglenn.com"
|
|
@@ -31,8 +43,15 @@ class HttpClient:
|
|
|
31
43
|
# so that we can put in user agent header, rate-limit, etc.
|
|
32
44
|
# aocd users should not need to use this class directly.
|
|
33
45
|
|
|
34
|
-
|
|
35
|
-
|
|
46
|
+
pool_manager: urllib3.PoolManager
|
|
47
|
+
req_count: dict[t.Literal["GET", "POST"], int]
|
|
48
|
+
|
|
49
|
+
def __init__(self) -> None:
|
|
50
|
+
proxy_url = os.environ.get('http_proxy') or os.environ.get('https_proxy')
|
|
51
|
+
if proxy_url:
|
|
52
|
+
self.pool_manager = urllib3.ProxyManager(proxy_url, headers={"User-Agent": USER_AGENT})
|
|
53
|
+
else:
|
|
54
|
+
self.pool_manager = urllib3.PoolManager(headers={"User-Agent": USER_AGENT})
|
|
36
55
|
self.req_count = {"GET": 0, "POST": 0}
|
|
37
56
|
self._max_t = 3.0
|
|
38
57
|
self._cooloff = 0.16
|
|
@@ -47,13 +66,20 @@ class HttpClient:
|
|
|
47
66
|
# increasing exponentially on subsequent occasions. implemented
|
|
48
67
|
# at the AoC author's request:
|
|
49
68
|
# https://github.com/wimglenn/advent-of-code-data/issues/59
|
|
50
|
-
msg =
|
|
69
|
+
msg = (
|
|
70
|
+
"you're being rate-limited - slow down on the requests! "
|
|
71
|
+
"see https://github.com/wimglenn/advent-of-code-data/issues/59 "
|
|
72
|
+
"(delay=%.02fs)"
|
|
73
|
+
)
|
|
51
74
|
log.warning(msg, self._cooloff)
|
|
52
75
|
time.sleep(self._cooloff)
|
|
53
76
|
self._cooloff *= 2 # double it for repeat offenders
|
|
77
|
+
self._cooloff = min(self._cooloff, 10)
|
|
54
78
|
self._history.append(now)
|
|
55
79
|
|
|
56
|
-
def get(
|
|
80
|
+
def get(
|
|
81
|
+
self, url: str, token: str | None = None, redirect: bool = True
|
|
82
|
+
) -> urllib3.BaseHTTPResponse:
|
|
57
83
|
# getting user inputs, puzzle prose, etc
|
|
58
84
|
if token is None:
|
|
59
85
|
headers = self.pool_manager.headers
|
|
@@ -64,7 +90,9 @@ class HttpClient:
|
|
|
64
90
|
self.req_count["GET"] += 1
|
|
65
91
|
return resp
|
|
66
92
|
|
|
67
|
-
def post(
|
|
93
|
+
def post(
|
|
94
|
+
self, url: str, token: str, fields: t.Mapping[str, str]
|
|
95
|
+
) -> urllib3.BaseHTTPResponse:
|
|
68
96
|
# submitting answers
|
|
69
97
|
headers = self.pool_manager.headers | {"Cookie": f"session={token}"}
|
|
70
98
|
self._limiter()
|
|
@@ -79,14 +107,19 @@ class HttpClient:
|
|
|
79
107
|
return resp
|
|
80
108
|
|
|
81
109
|
|
|
82
|
-
http = HttpClient()
|
|
110
|
+
http: HttpClient = HttpClient()
|
|
83
111
|
|
|
84
112
|
|
|
85
113
|
def _ensure_intermediate_dirs(path):
|
|
86
114
|
path.expanduser().parent.mkdir(parents=True, exist_ok=True)
|
|
87
115
|
|
|
88
116
|
|
|
89
|
-
def blocker(
|
|
117
|
+
def blocker(
|
|
118
|
+
quiet: bool = False,
|
|
119
|
+
dt: float = 0.1,
|
|
120
|
+
datefmt: str | None = None,
|
|
121
|
+
until: tuple[int, int] | None = None,
|
|
122
|
+
) -> None:
|
|
90
123
|
"""
|
|
91
124
|
This function just blocks until the next puzzle unlocks.
|
|
92
125
|
Pass `quiet=True` to disable the spinner etc.
|
|
@@ -133,7 +166,7 @@ def blocker(quiet=False, dt=0.1, datefmt=None, until=None):
|
|
|
133
166
|
sys.stdout.flush()
|
|
134
167
|
|
|
135
168
|
|
|
136
|
-
def get_owner(token):
|
|
169
|
+
def get_owner(token: str) -> str:
|
|
137
170
|
"""
|
|
138
171
|
Find owner of the token.
|
|
139
172
|
Raises `DeadTokenError` if the token is expired/invalid.
|
|
@@ -170,7 +203,7 @@ def get_owner(token):
|
|
|
170
203
|
return result
|
|
171
204
|
|
|
172
205
|
|
|
173
|
-
def atomic_write_file(path, contents_str):
|
|
206
|
+
def atomic_write_file(path: Path, contents_str: str) -> None:
|
|
174
207
|
"""
|
|
175
208
|
Atomically write a string to a file by writing it to a temporary file, and then
|
|
176
209
|
renaming it to the final destination name. This solves a race condition where existence
|
|
@@ -200,12 +233,15 @@ def _cli_guess(choice, choices):
|
|
|
200
233
|
return result
|
|
201
234
|
|
|
202
235
|
|
|
203
|
-
|
|
236
|
+
_ANSIColor = t.Literal[
|
|
237
|
+
"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white"
|
|
238
|
+
]
|
|
239
|
+
_ansi_colors = t.get_args(_ANSIColor)
|
|
204
240
|
if platform.system() == "Windows":
|
|
205
241
|
os.system("color") # hack - makes ANSI colors work in the windows cmd window
|
|
206
242
|
|
|
207
243
|
|
|
208
|
-
def colored(txt, color):
|
|
244
|
+
def colored(txt: str, color: _ANSIColor | None) -> str:
|
|
209
245
|
if color is None:
|
|
210
246
|
return txt
|
|
211
247
|
code = _ansi_colors.index(color.casefold())
|
|
@@ -213,7 +249,7 @@ def colored(txt, color):
|
|
|
213
249
|
return f"\x1b[{code + 30}m{txt}{reset}"
|
|
214
250
|
|
|
215
251
|
|
|
216
|
-
def get_plugins(group="adventofcode.user"):
|
|
252
|
+
def get_plugins(group: str = "adventofcode.user") -> _EntryPointsType:
|
|
217
253
|
"""
|
|
218
254
|
Currently installed plugins for user solves.
|
|
219
255
|
"""
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "advent-of-code-data"
|
|
7
|
-
version = "2.0.
|
|
7
|
+
version = "2.0.2"
|
|
8
8
|
description = "Get your puzzle data with a single import"
|
|
9
9
|
requires-python = ">=3.9"
|
|
10
10
|
classifiers = [
|
|
@@ -48,6 +48,26 @@ aoce = "aocd.examples:main"
|
|
|
48
48
|
[tool.setuptools]
|
|
49
49
|
packages = ["aocd"]
|
|
50
50
|
|
|
51
|
+
[tool.setuptools.package-data]
|
|
52
|
+
aocd = ["py.typed"]
|
|
53
|
+
|
|
54
|
+
|
|
51
55
|
[project.entry-points]
|
|
52
56
|
"adventofcode.user" = {} # for user solvers
|
|
53
57
|
"adventofcode.examples" = {} # for example-parser implementations
|
|
58
|
+
|
|
59
|
+
[tool.pytest.ini_options]
|
|
60
|
+
addopts = """
|
|
61
|
+
--strict-markers
|
|
62
|
+
--disable-socket
|
|
63
|
+
--allow-unix-socket
|
|
64
|
+
--cov-branch
|
|
65
|
+
--cov=aocd --cov=tests
|
|
66
|
+
--cov-report=html --cov-report=term-missing:skip-covered"""
|
|
67
|
+
xfail_strict = true
|
|
68
|
+
markers = "answer_not_cached"
|
|
69
|
+
|
|
70
|
+
[tool.coverage.report]
|
|
71
|
+
exclude_also = [
|
|
72
|
+
"if t\\.TYPE_CHECKING:"
|
|
73
|
+
]
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import decimal
|
|
2
|
+
import fractions
|
|
1
3
|
import logging
|
|
2
4
|
from datetime import datetime
|
|
3
5
|
from datetime import timedelta
|
|
4
|
-
from textwrap import dedent
|
|
5
6
|
|
|
6
7
|
import numpy as np
|
|
7
8
|
import pytest
|
|
@@ -445,6 +446,50 @@ def test_type_coercions(v_raw, v_expected, len_logs, caplog):
|
|
|
445
446
|
assert len(caplog.records) == len_logs
|
|
446
447
|
|
|
447
448
|
|
|
449
|
+
@pytest.mark.parametrize(
|
|
450
|
+
"v_raw, v_expected, len_logs",
|
|
451
|
+
[
|
|
452
|
+
("xxx", "xxx", 0), # str -> str
|
|
453
|
+
(b"123", "123", 1), # bytes -> str
|
|
454
|
+
(123, "123", 0), # int -> str
|
|
455
|
+
(123.0, "123", 1), # float -> str
|
|
456
|
+
(123.0 + 0.0j, "123", 1), # complex -> str
|
|
457
|
+
(np.int32(123), "123", 1), # np.int -> str
|
|
458
|
+
(np.uint32(123), "123", 1), # np.uint -> str
|
|
459
|
+
(np.double(123.0), "123", 1), # np.double -> str
|
|
460
|
+
(np.complex64(123.0 + 0.0j), "123", 1), # np.complex -> str
|
|
461
|
+
(np.array([123]), "123", 1), # 1D np.array of int -> str
|
|
462
|
+
(np.array([[123.0]]), "123", 1), # 2D np.array of float -> str
|
|
463
|
+
(np.array([[[[[[123.0 + 0j]]]]]]), "123", 1), # deep np.array of complex -> str
|
|
464
|
+
(fractions.Fraction(123 * 2, 2), "123", 1), # Fraction -> int
|
|
465
|
+
(decimal.Decimal("123"), "123", 1), # Decimal -> int
|
|
466
|
+
],
|
|
467
|
+
)
|
|
468
|
+
def test_type_coercions(v_raw, v_expected, len_logs, caplog):
|
|
469
|
+
p = Puzzle(2022, 1)
|
|
470
|
+
v_actual = p._coerce_val(v_raw)
|
|
471
|
+
assert v_actual == v_expected, f"{type(v_raw)} {v_raw})"
|
|
472
|
+
assert len(caplog.records) == len_logs
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
@pytest.mark.parametrize(
|
|
476
|
+
"val, error_msg",
|
|
477
|
+
[
|
|
478
|
+
(123.5, "Failed to coerce float value 123.5 for 2022/01."), # non-integer float
|
|
479
|
+
(123.0 + 123.0j, "Failed to coerce complex value (123+123j) for 2022/01."), # complex w/ imag
|
|
480
|
+
(np.complex64(123.0 + 0.5j), "Failed to coerce complex64 value np.complex64(123+0.5j) for 2022/01."), # np.complex w/ imag
|
|
481
|
+
(np.array([1, 2]), "Failed to coerce ndarray value array([1, 2]) for 2022/01."), # 1D np.array with size != 1
|
|
482
|
+
(np.array([[1], [2]]), "Failed to coerce ndarray value array([[1],\n [2]]) for 2022/01."), # 2D np.array with size != 1
|
|
483
|
+
(fractions.Fraction(123, 2), "Failed to coerce Fraction value Fraction(123, 2) for 2022/01."), # Fraction
|
|
484
|
+
(decimal.Decimal("123.5"), "Failed to coerce Decimal value Decimal('123.5') for 2022/01."), # Decimal
|
|
485
|
+
]
|
|
486
|
+
)
|
|
487
|
+
def test_type_coercions_fail(val, error_msg):
|
|
488
|
+
p = Puzzle(2022, 1)
|
|
489
|
+
with pytest.raises(AocdError(error_msg)):
|
|
490
|
+
p._coerce_val(val)
|
|
491
|
+
|
|
492
|
+
|
|
448
493
|
def test_get_prose_cache(aocd_data_dir):
|
|
449
494
|
cached = aocd_data_dir / "other-user-id" / "2022_01_prose.2.html"
|
|
450
495
|
cached.parent.mkdir()
|
|
@@ -280,5 +280,5 @@ def test_submit_float_warns(pook, capsys, caplog):
|
|
|
280
280
|
)
|
|
281
281
|
submit(1234.0, part="a", day=8, year=2022, session="whatever", reopen=False)
|
|
282
282
|
assert post.calls == 1
|
|
283
|
-
record = ("aocd.models", logging.WARNING, "coerced float value 1234.0 for 2022/08")
|
|
283
|
+
record = ("aocd.models", logging.WARNING, "coerced float value 1234.0 for 2022/08 to '1234'")
|
|
284
284
|
assert record in caplog.record_tuples
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/advent_of_code_data.egg-info/requires.txt
RENAMED
|
File without changes
|
{advent-of-code-data-2.0.1 → advent_of_code_data-2.0.2}/advent_of_code_data.egg-info/top_level.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|