From 9fa164d457a25c1abb936cf7fffae4579e01ecee Mon Sep 17 00:00:00 2001 From: ABDreos Date: Wed, 20 Mar 2024 14:25:09 +0000 Subject: [PATCH] Code formatted with Ruff --- 2022/ab_testing/with_tracking/feature.py | 1 - 2022/adapter/adapter/config_protocol.py | 3 +- .../adapter_partial/config_protocol.py | 3 +- 2022/adapter/adapter_partial/main.py | 1 - 2022/async/after-1/iot/service.py | 9 +- 2022/async/after-2/iot/service.py | 9 +- 2022/async/before/iot/service.py | 9 +- 2022/asyncio_2/asyncio_gather.py | 1 - 2022/asyncio_2/asyncio_iter.py | 1 - 2022/asyncio_2/sync_to_async_before.py | 1 - 2022/asyncio_2/sync_to_async_correct.py | 1 - .../bridge_pattern/with_abc/stream/service.py | 1 - .../with_function/stream/service.py | 9 +- .../with_function/stream/twitch_stream.py | 1 - .../with_function/stream/youtube_stream.py | 1 - .../with_protocol/stream/device.py | 3 +- .../with_protocol/stream/service.py | 9 +- .../with_protocol/stream/twitch_stream.py | 1 - .../with_protocol/stream/youtube_stream.py | 1 - 2022/cicd/functions/routes.py | 1 + 2022/code_roast/after/main.py | 1 - 2022/code_roast/after/scrape/fetch.py | 1 - 2022/code_roast/after/scrape/scraper.py | 3 +- 2022/code_roast_battleship/after.py | 1 - 2022/code_roast_rpsls/before/entity.py | 2 +- 2022/code_roast_rpsls/before/game.py | 60 +- 2022/code_roast_rpsls/before/main.py | 8 +- 2022/code_roast_rpsls/before/rules.py | 103 +- 2022/code_roast_rpsls/before/scoreboard.py | 14 +- .../after/TowerDefense.py | 3 +- .../before/TowerDefense.py | 1861 ++++++++++------- .../with_state/main.py | 1 - .../with_transaction/banking/transaction.py | 3 +- .../with_transaction/main.py | 1 - .../after/banking/transaction.py | 9 +- 2022/command_with_undo/after/main.py | 1 - 2022/command_with_undo/before/main.py | 1 - 2022/configs/after/ds/load_data.py | 8 +- 2022/configs/after/ds/tensorboard.py | 1 - 2022/configs/after/ds/utils.py | 3 +- 2022/configs/after/parse_raw_data.py | 16 +- 2022/configs/before/ds/load_data.py | 8 +- 2022/configs/before/ds/tensorboard.py | 1 - 2022/configs/before/ds/utils.py | 3 +- 2022/configs/before/main.py | 1 - 2022/configs/before/parse_raw_data.py | 16 +- 2022/configs/before/plot.py | 28 +- 2022/context_manager/create_db.py | 17 +- 2022/coupling/Introduce_abstraction.py | 18 +- 2022/coupling/intimacy_after.py | 12 +- 2022/coupling/intimacy_before.py | 12 +- 2022/dash_tutorial/part2/main.py | 1 - 2022/dash_tutorial/part3/main.py | 1 - 2022/datascience_tips/after/ds/load_data.py | 8 +- 2022/datascience_tips/after/ds/tensorboard.py | 1 - 2022/datascience_tips/after/ds/utils.py | 3 +- 2022/datascience_tips/after/main.py | 1 - 2022/datascience_tips/after/parse_raw_data.py | 16 +- 2022/datascience_tips/after/plot.py | 28 +- 2022/datascience_tips/before/main.py | 45 +- 2022/datascience_tips/before/src/dataset.py | 13 +- 2022/datascience_tips/before/src/load_data.py | 8 +- 2022/datascience_tips/before/src/tracking.py | 43 +- 2022/datascience_tips/before/src/utils.py | 12 +- 2022/datascience_tips/compose_example.py | 1 + 2022/datetime/pendulum_example.py | 1 - .../even_more_code_smells/after/pos/system.py | 3 +- .../before/pos/payment.py | 6 +- 2022/f_strings/main.py | 1 - 2022/facade/before/iot/service.py | 12 +- 2022/facade/with_controller/iot/service.py | 12 +- 2022/facade/with_facade/iot/service.py | 12 +- 2022/facade/with_facade/iot_controller.py | 6 +- 2022/func_takeaways/oop_v1.py | 1 - 2022/functions/4_minimal_arguments.py | 9 +- 2022/functions/5_create_use_after.py | 3 +- 2022/gui_architecture/mvp/presenter.py | 18 +- 2022/gui_architecture/mvp/view.py | 6 +- .../test/generated/test_office_1.py | 1 - .../test/generated/test_office_2.py | 1 - 2022/itertools/iterator_basics.py | 1 - 2022/more_code_smells/after.py | 1 + 2022/more_code_smells/before.py | 2 +- 2022/oop_done_well/abuse_after.py | 3 +- 2022/partial_functions/strategy_before.py | 1 + 2022/partial_functions/strategy_fn.py | 1 + 2022/partial_functions/strategy_fn_closure.py | 1 + 2022/partial_functions/strategy_fn_partial.py | 1 + 2022/plugin_system/after/example.py | 3 - 2022/plugin_system/after/game/loader.py | 1 + 2022/plugin_system/after/plugins/bard.py | 1 - 2022/plugin_system/before/example.py | 3 - .../protocols_abc/protocol/iot/diagnostics.py | 3 +- 2022/protocols_abc/protocol/iot/service.py | 9 +- 2022/pulumi/basic_project/__main__.py | 1 - 2022/pulumi/cloud_func/functions/main.py | 1 + 2022/pulumi/cloud_run_v2/__main__.py | 1 - 2022/quick_tips_shorts/05_type_alias/after.py | 1 - .../quick_tips_shorts/05_type_alias/before.py | 1 - 2022/quick_tips_shorts/13_numbers/after.py | 3 +- 2022/quick_tips_shorts/13_numbers/before.py | 3 +- .../22_custom_exception/after.py | 1 - .../22_custom_exception/before.py | 1 - .../26_dep_inversion/after.py | 3 +- .../27_protocol_segregation/after.py | 6 +- .../27_protocol_segregation/before.py | 6 +- .../27_protocol_segregation/iot/service.py | 6 +- .../28_func_composition/after.py | 1 + .../28_func_composition/before.py | 1 + 2022/red_green_refactor/green/employee.py | 1 + .../red_green_refactor/green/test_employee.py | 1 + 2022/red_green_refactor/red/employee.py | 1 + 2022/red_green_refactor/red/test_employee.py | 1 + 2022/red_green_refactor/refactor/employee.py | 1 + .../refactor/test_employee.py | 1 + .../refactor/testing_tips.py | 1 + 2022/strategy_parameters/before.py | 1 + 2022/strategy_parameters/with_init_args.py | 2 +- 2022/strategy_parameters/with_keyword_args.py | 1 + .../with_parameters_class.py | 1 + 2022/structural_pattern_matching/example.py | 12 +- 2022/types/example.py | 1 - 2023/classguide/3_dependency_injection.py | 3 +- 2023/classguide/4_email_function.py | 3 +- 2023/decorator/decorator_pattern_classic.py | 1 - 2023/doc/src/better_doc with_docstrings.py | 20 +- 2023/doc/src/better_doc.py | 11 +- 2023/dunder/c2_after.py | 3 +- 2023/fastapi/1_basic_app.py | 4 +- 2023/fastapi/3_more_routing.py | 5 - 2023/fastapi/4_main.py | 4 +- .../5_validation_with_Query_and_Path.py | 1 - .../fastapi/6_adding_openapi_documentation.py | 11 +- 2023/funclass/src/classes.py | 2 - 2023/generic/after.py | 3 + 2023/generic/constrained.py | 2 + 2023/generic/upper_bound_after.py | 4 +- 2023/gildedrose/after/gilded_rose.py | 6 +- 2023/gildedrose/after/texttest_fixture.py | 23 +- 2023/gildedrose/before/texttest_fixture.py | 23 +- 2023/grasp/04-protected_variation_after.py | 9 +- 2023/grasp/05-indirection_before.py | 1 - 2023/grasp/06-low_coupling_after.py | 3 +- 2023/grasp/07-high_cohesion_after.py | 1 - 2023/grasp/07-high_cohesion_before.py | 1 - 2023/grasp/09-pure_fabrication_after.py | 1 - 2023/grasp/09-pure_fabrication_before.py | 1 - 2023/jupyter/dice.py | 2 +- 2023/openai/text_to_speech.py | 1 - 2023/rust/python/hello_world.py | 2 +- 2023/rust/python/iot.py | 19 +- 2023/rust/python/user.py | 7 +- .../before/src/UtilPackage/Algorithms.py | 151 +- .../before/src/UtilPackage/EncodingApi.py | 35 +- .../before/src/UtilPackage/HashingApi.py | 11 +- .../before/src/UtilPackage/Shell.py | 103 +- .../shellroast/before/src/UtilPackage/Tool.py | 6 +- .../before/src/UtilPackage/UtilFuncs.py | 70 +- .../before/src/UtilPackage/__init__.py | 2 - 2023/shellroast/before/src/main.py | 279 ++- 2023/state/classic.py | 24 +- 2023/strict/1_after.py | 12 +- 2023/strict/1_before.py | 12 +- 2024/golroast/after/game.py | 7 +- 2024/golroast/after/visualizers/console.py | 6 +- 2024/golroast/after/visualizers/plot.py | 6 +- 2024/golroast/before/test.py | 160 +- 2024/golroast/before/visualizer.py | 2 +- 2024/rust_bindings/main_step1.py | 4 +- 2024/rust_bindings/main_step2.py | 3 +- .../custom_exceptions/basic_example.py | 4 +- .../before/email_sender.py | 5 +- .../before/test_email_sender.py | 1 + .../fail_fast/employee_portal/after_main.py | 24 +- .../employee_portal/database/database.py | 9 +- .../fail_fast/employee_portal/employees.py | 5 +- .../fail_fast/employee_portal/payment.py | 4 + .../fail_fast/employee_portal/position.py | 10 +- .../tuesday_tips/fail_fast/tests/test_main.py | 4 +- 2024/tuesday_tips/openai/async_main.py | 2 +- 2024/tuesday_tips/openai/client.py | 16 +- 2024/tuesday_tips/openai/main.py | 1 + 2024/tuesday_tips/openai/models.py | 4 +- 2024/tuesday_tips/openai/tip_1/chunker.py | 2 +- 2024/tuesday_tips/openai/tip_1/encoding.py | 4 +- .../tuesday_tips/openai/tip_2/rate_limiter.py | 7 +- .../openai/tip_2/request_handler.py | 4 +- .../openai/tip_3/request_handler.py | 10 +- 2024/tuesday_tips/openai/tip_3/timer.py | 15 +- 2024/tuesday_tips/regex/benchmark/main.py | 2 +- 2024/tuesday_tips/regex/benchmark/timer.py | 8 +- .../tuesday_tips/regex/benchmark/validator.py | 3 +- .../regex/dashboard/src/components/layout.py | 4 +- .../regex/dashboard/src/data/reader.py | 1 + .../regex/dashboard/src/formatter.py | 2 +- 2024/tuesday_tips/testing_async/main.py | 1 - .../test/fixture_based_fetch_event_test.py | 6 +- 197 files changed, 2043 insertions(+), 1833 deletions(-) diff --git a/2022/ab_testing/with_tracking/feature.py b/2022/ab_testing/with_tracking/feature.py index bf6b6771..53381dcc 100644 --- a/2022/ab_testing/with_tracking/feature.py +++ b/2022/ab_testing/with_tracking/feature.py @@ -11,7 +11,6 @@ class Config: def read_config() -> Config: - api_key = os.getenv("GROWTHBOOK_KEY") or "" response = requests.get( f"https://cdn.growthbook.io/api/features/{api_key}", timeout=5 diff --git a/2022/adapter/adapter/config_protocol.py b/2022/adapter/adapter/config_protocol.py index 2af070a3..3ad92e57 100644 --- a/2022/adapter/adapter/config_protocol.py +++ b/2022/adapter/adapter/config_protocol.py @@ -2,5 +2,4 @@ class Config(Protocol): - def get(self, key: str) -> Any | None: - ... + def get(self, key: str) -> Any | None: ... diff --git a/2022/adapter/adapter_partial/config_protocol.py b/2022/adapter/adapter_partial/config_protocol.py index 5acdea0f..cf3099f3 100644 --- a/2022/adapter/adapter_partial/config_protocol.py +++ b/2022/adapter/adapter_partial/config_protocol.py @@ -2,5 +2,4 @@ class Config(Protocol): - def get(self, key: str, default: Any = None) -> Any | None: - ... + def get(self, key: str, default: Any = None) -> Any | None: ... diff --git a/2022/adapter/adapter_partial/main.py b/2022/adapter/adapter_partial/main.py index 39061467..c9ec2299 100644 --- a/2022/adapter/adapter_partial/main.py +++ b/2022/adapter/adapter_partial/main.py @@ -8,7 +8,6 @@ def main() -> None: - with open("config.json", encoding="utf8") as file: config = json.load(file) with open("config.xml", encoding="utf8") as file: diff --git a/2022/async/after-1/iot/service.py b/2022/async/after-1/iot/service.py index 8e0209b8..22040d13 100644 --- a/2022/async/after-1/iot/service.py +++ b/2022/async/after-1/iot/service.py @@ -11,14 +11,11 @@ def generate_id(length: int = 8): class Device(Protocol): - async def connect(self) -> None: - ... + async def connect(self) -> None: ... - async def disconnect(self) -> None: - ... + async def disconnect(self) -> None: ... - async def send_message(self, message_type: MessageType, data: str = "") -> None: - ... + async def send_message(self, message_type: MessageType, data: str = "") -> None: ... class IOTService: diff --git a/2022/async/after-2/iot/service.py b/2022/async/after-2/iot/service.py index fb5bbdc8..bacc2775 100644 --- a/2022/async/after-2/iot/service.py +++ b/2022/async/after-2/iot/service.py @@ -11,14 +11,11 @@ def generate_id(length: int = 8): class Device(Protocol): - async def connect(self) -> None: - ... + async def connect(self) -> None: ... - async def disconnect(self) -> None: - ... + async def disconnect(self) -> None: ... - async def send_message(self, message_type: MessageType, data: str = "") -> None: - ... + async def send_message(self, message_type: MessageType, data: str = "") -> None: ... class IOTService: diff --git a/2022/async/before/iot/service.py b/2022/async/before/iot/service.py index 6ef10f27..f1255cf2 100644 --- a/2022/async/before/iot/service.py +++ b/2022/async/before/iot/service.py @@ -10,14 +10,11 @@ def generate_id(length: int = 8): class Device(Protocol): - def connect(self) -> None: - ... + def connect(self) -> None: ... - def disconnect(self) -> None: - ... + def disconnect(self) -> None: ... - def send_message(self, message_type: MessageType, data: str) -> None: - ... + def send_message(self, message_type: MessageType, data: str) -> None: ... class IOTService: diff --git a/2022/asyncio_2/asyncio_gather.py b/2022/asyncio_2/asyncio_gather.py index 1996a0e7..3e9d3524 100644 --- a/2022/asyncio_2/asyncio_gather.py +++ b/2022/asyncio_2/asyncio_gather.py @@ -24,7 +24,6 @@ async def get_random_pokemon_name() -> str: async def main() -> None: - # synchronous call time_before = perf_counter() for _ in range(20): diff --git a/2022/asyncio_2/asyncio_iter.py b/2022/asyncio_2/asyncio_iter.py index 42ab52f9..bb1696f7 100644 --- a/2022/asyncio_2/asyncio_iter.py +++ b/2022/asyncio_2/asyncio_iter.py @@ -22,7 +22,6 @@ async def next_pokemon(total: int) -> AsyncIterable[str]: async def main(): - # retrieve the next 10 pokemon names async for name in next_pokemon(10): print(name) diff --git a/2022/asyncio_2/sync_to_async_before.py b/2022/asyncio_2/sync_to_async_before.py index efbcbcbe..0c67cfc5 100644 --- a/2022/asyncio_2/sync_to_async_before.py +++ b/2022/asyncio_2/sync_to_async_before.py @@ -21,7 +21,6 @@ def send_request(url: str) -> int: async def main() -> None: - status_code = send_request("https://www.arjancodes.com") print(f"Got HTTP response with status {status_code}") diff --git a/2022/asyncio_2/sync_to_async_correct.py b/2022/asyncio_2/sync_to_async_correct.py index bbda72cc..0ed9aab0 100644 --- a/2022/asyncio_2/sync_to_async_correct.py +++ b/2022/asyncio_2/sync_to_async_correct.py @@ -25,7 +25,6 @@ async def send_async_request(url: str) -> int: async def main() -> None: - status_code, _ = await asyncio.gather( send_async_request("https://www.arjancodes.com"), counter() ) diff --git a/2022/bridge_pattern/with_abc/stream/service.py b/2022/bridge_pattern/with_abc/stream/service.py index 471b5878..582bd8be 100644 --- a/2022/bridge_pattern/with_abc/stream/service.py +++ b/2022/bridge_pattern/with_abc/stream/service.py @@ -6,7 +6,6 @@ @dataclass class StreamingService(ABC): - devices: list[Buffer] = field(default_factory=list) def add_device(self, device: Buffer) -> None: diff --git a/2022/bridge_pattern/with_function/stream/service.py b/2022/bridge_pattern/with_function/stream/service.py index 2ca80f45..47d3e4ee 100644 --- a/2022/bridge_pattern/with_function/stream/service.py +++ b/2022/bridge_pattern/with_function/stream/service.py @@ -2,11 +2,8 @@ class StreamingService(Protocol): - def start_stream(self) -> str: - ... + def start_stream(self) -> str: ... - def fill_buffer(self, stream_reference: str) -> None: - ... + def fill_buffer(self, stream_reference: str) -> None: ... - def stop_stream(self, stream_reference: str) -> None: - ... + def stop_stream(self, stream_reference: str) -> None: ... diff --git a/2022/bridge_pattern/with_function/stream/twitch_stream.py b/2022/bridge_pattern/with_function/stream/twitch_stream.py index 02d2dd6c..aa5a4e77 100644 --- a/2022/bridge_pattern/with_function/stream/twitch_stream.py +++ b/2022/bridge_pattern/with_function/stream/twitch_stream.py @@ -6,7 +6,6 @@ @dataclass class TwitchStreamingService: - buffer: Buffer def start_stream(self) -> str: diff --git a/2022/bridge_pattern/with_function/stream/youtube_stream.py b/2022/bridge_pattern/with_function/stream/youtube_stream.py index 05ad629e..7ed1a256 100644 --- a/2022/bridge_pattern/with_function/stream/youtube_stream.py +++ b/2022/bridge_pattern/with_function/stream/youtube_stream.py @@ -6,7 +6,6 @@ @dataclass class YouTubeStreamingService: - buffer: Buffer def start_stream(self) -> str: diff --git a/2022/bridge_pattern/with_protocol/stream/device.py b/2022/bridge_pattern/with_protocol/stream/device.py index d2e5ec4d..014cf791 100644 --- a/2022/bridge_pattern/with_protocol/stream/device.py +++ b/2022/bridge_pattern/with_protocol/stream/device.py @@ -4,5 +4,4 @@ class StreamingDevice(Protocol): - def get_buffer_data(self) -> BufferData: - ... + def get_buffer_data(self) -> BufferData: ... diff --git a/2022/bridge_pattern/with_protocol/stream/service.py b/2022/bridge_pattern/with_protocol/stream/service.py index 2ca80f45..47d3e4ee 100644 --- a/2022/bridge_pattern/with_protocol/stream/service.py +++ b/2022/bridge_pattern/with_protocol/stream/service.py @@ -2,11 +2,8 @@ class StreamingService(Protocol): - def start_stream(self) -> str: - ... + def start_stream(self) -> str: ... - def fill_buffer(self, stream_reference: str) -> None: - ... + def fill_buffer(self, stream_reference: str) -> None: ... - def stop_stream(self, stream_reference: str) -> None: - ... + def stop_stream(self, stream_reference: str) -> None: ... diff --git a/2022/bridge_pattern/with_protocol/stream/twitch_stream.py b/2022/bridge_pattern/with_protocol/stream/twitch_stream.py index fc745bb4..6f40e2f9 100644 --- a/2022/bridge_pattern/with_protocol/stream/twitch_stream.py +++ b/2022/bridge_pattern/with_protocol/stream/twitch_stream.py @@ -7,7 +7,6 @@ @dataclass class TwitchStreamingService: - device: StreamingDevice def start_stream(self) -> str: diff --git a/2022/bridge_pattern/with_protocol/stream/youtube_stream.py b/2022/bridge_pattern/with_protocol/stream/youtube_stream.py index 873db583..38a36bb6 100644 --- a/2022/bridge_pattern/with_protocol/stream/youtube_stream.py +++ b/2022/bridge_pattern/with_protocol/stream/youtube_stream.py @@ -7,7 +7,6 @@ @dataclass class YouTubeStreamingService: - device: StreamingDevice def start_stream(self) -> str: diff --git a/2022/cicd/functions/routes.py b/2022/cicd/functions/routes.py index bce59c2c..eb5774e5 100644 --- a/2022/cicd/functions/routes.py +++ b/2022/cicd/functions/routes.py @@ -5,6 +5,7 @@ # Define an internal Flask app app = Flask("internal") + # Define the internal paths, idiomatic Flask definition @app.route("/channels/", methods=["GET", "POST"]) def channel(channel_id: str): diff --git a/2022/code_roast/after/main.py b/2022/code_roast/after/main.py index f21fefb4..e00f4118 100644 --- a/2022/code_roast/after/main.py +++ b/2022/code_roast/after/main.py @@ -7,7 +7,6 @@ def main() -> None: - # read the configuration settings from a JSON file config = read_config("./config.json") diff --git a/2022/code_roast/after/scrape/fetch.py b/2022/code_roast/after/scrape/fetch.py index fa386f68..2cc2cb3f 100644 --- a/2022/code_roast/after/scrape/fetch.py +++ b/2022/code_roast/after/scrape/fetch.py @@ -34,7 +34,6 @@ def fetch_terms_from_pubid(target: pd.DataFrame, scraper: Scraper) -> pd.DataFra def fetch_terms_from_pdf_files(config: ScrapeConfig) -> pd.DataFrame: - search_terms = [ path.join(config.paper_folder, file) for file in listdir(config.paper_folder) diff --git a/2022/code_roast/after/scrape/scraper.py b/2022/code_roast/after/scrape/scraper.py index ce4501fe..0fdd6bdf 100644 --- a/2022/code_roast/after/scrape/scraper.py +++ b/2022/code_roast/after/scrape/scraper.py @@ -11,5 +11,4 @@ class ScrapeResult: class Scraper(Protocol): - def scrape(self, search_text: str) -> ScrapeResult: - ... + def scrape(self, search_text: str) -> ScrapeResult: ... diff --git a/2022/code_roast_battleship/after.py b/2022/code_roast_battleship/after.py index dd332698..360da5d1 100644 --- a/2022/code_roast_battleship/after.py +++ b/2022/code_roast_battleship/after.py @@ -94,7 +94,6 @@ def play_game(player_count: int, board: BattleshipBoard) -> None: won_game = False while total_guesses < GUESSES_COUNT * player_count: - # determine the current player and the remaining guesses current_player = (total_guesses % player_count) + 1 remaining_guesses = GUESSES_COUNT - total_guesses // player_count diff --git a/2022/code_roast_rpsls/before/entity.py b/2022/code_roast_rpsls/before/entity.py index 70268774..f63cc737 100644 --- a/2022/code_roast_rpsls/before/entity.py +++ b/2022/code_roast_rpsls/before/entity.py @@ -9,4 +9,4 @@ class Entity(Enum): LIZARD = auto() def __repr__(self) -> str: - return f"{self.name} : {self.value}" \ No newline at end of file + return f"{self.name} : {self.value}" diff --git a/2022/code_roast_rpsls/before/game.py b/2022/code_roast_rpsls/before/game.py index 33a87b87..68f8f5d4 100644 --- a/2022/code_roast_rpsls/before/game.py +++ b/2022/code_roast_rpsls/before/game.py @@ -3,34 +3,37 @@ from rules import Rules from entity import Entity + class Game: - """Game class - """ + """Game class""" + def __init__(self, user: str, max_round: int = 5) -> None: print("Rock paper scissor spock and lizard...\n Welcome to the game.") print("Rules are simple...") - print("Scissors decapitate Lizard, Scissors cuts paper, paper covers rock, rock crushes lizard, lizard poisons Spock, Spock smashes scissors, scissors decapitates lizard, lizard eats paper, paper disproves Spock, Spock vaporizes rock, and as it always has, rock crushes scissors.") + print( + "Scissors decapitate Lizard, Scissors cuts paper, paper covers rock, rock crushes lizard, lizard poisons Spock, Spock smashes scissors, scissors decapitates lizard, lizard eats paper, paper disproves Spock, Spock vaporizes rock, and as it always has, rock crushes scissors." + ) print("To begin press [Enter]") _ = input() - + self.scoreboard = Scoreboard() self.max_round = max_round self.entities = Entity self.rules = Rules() self.user: str = user self.cpu: str = "cpu" - + # register players in scoreboard self.scoreboard.register_player(self.user) self.scoreboard.register_player(self.cpu) - - + def display_entity_to_select(self) -> None: - """Displays the user choices - """ - choices_text = ", ".join(f"({entity.value} for {entity.name})" for entity in self.entities) - print(f"Select {choices_text}:", end='\t') - + """Displays the user choices""" + choices_text = ", ".join( + f"({entity.value} for {entity.name})" for entity in self.entities + ) + print(f"Select {choices_text}:", end="\t") + def get_user_input(self) -> Entity: """Takes user inputs and selects the entities @@ -42,14 +45,14 @@ def get_user_input(self) -> Entity: try: self.display_entity_to_select() choice = int(input()) - + if choice not in available_choices: print("Please select from available choices") else: return self.entities(choice) except ValueError: print("You entered something other than a number") - + def get_cpu_input(self) -> Entity: """Selects a random entity @@ -58,7 +61,7 @@ def get_cpu_input(self) -> Entity: """ cpu_choice = random.randint(1, len(self.entities)) return self.entities(cpu_choice) - + def display_current_round(self, user_entity: Entity, cpu_entity: Entity) -> None: """Displays current round @@ -68,13 +71,14 @@ def display_current_round(self, user_entity: Entity, cpu_entity: Entity) -> None """ print(f"{self.user} ({user_entity.name}) x {self.cpu} ({cpu_entity.name})") print("....") - + def display_tie(self) -> None: - """Display tie message - """ + """Display tie message""" print(f"It's a tie..") - - def display_round_winner(self, winner_name: str, winner_entity: Entity, message: str) -> None: + + def display_round_winner( + self, winner_name: str, winner_entity: Entity, message: str + ) -> None: """Display the winner of the round Args: @@ -83,13 +87,12 @@ def display_round_winner(self, winner_name: str, winner_entity: Entity, message: message (str): Reason for wins """ print(f"{winner_name} ({winner_entity.name}) wins the round as {message}") - + def do_turn(self) -> None: - """Function to continue the rounds - """ + """Function to continue the rounds""" user_entity = self.get_user_input() cpu_entity = self.get_cpu_input() - + self.display_current_round(user_entity, cpu_entity) if cpu_entity == user_entity: self.display_tie() @@ -102,7 +105,7 @@ def do_turn(self) -> None: else: self.display_round_winner(self.cpu, cpu_entity, message) self.scoreboard.points[self.cpu] += 1 - + @staticmethod def get_user_name() -> str: """Static method to get user name as input @@ -110,11 +113,10 @@ def get_user_name() -> str: Returns: str: Name enterd by user """ - print("Please enter your name:", end='\t') + print("Please enter your name:", end="\t") return str(input().strip()) - - + def play(self): for i in range(self.max_round): self.do_turn() - self.scoreboard.display_scores() \ No newline at end of file + self.scoreboard.display_scores() diff --git a/2022/code_roast_rpsls/before/main.py b/2022/code_roast_rpsls/before/main.py index bc10c057..3bc9754f 100644 --- a/2022/code_roast_rpsls/before/main.py +++ b/2022/code_roast_rpsls/before/main.py @@ -1,12 +1,12 @@ from game import Game + def main() -> None: - """Main function to start the game - """ + """Main function to start the game""" user_name = Game.get_user_name() game = Game(user_name) game.play() -if __name__ == '__main__': + +if __name__ == "__main__": main() - \ No newline at end of file diff --git a/2022/code_roast_rpsls/before/rules.py b/2022/code_roast_rpsls/before/rules.py index bd5ab926..e3a8dd25 100644 --- a/2022/code_roast_rpsls/before/rules.py +++ b/2022/code_roast_rpsls/before/rules.py @@ -1,53 +1,53 @@ from entity import Entity from typing import Tuple + class Rules: - """Class to register all the rules - """ + """Class to register all the rules""" + rules = { - (Entity.PAPER, Entity.ROCK): { - 'winner': Entity.PAPER, - 'message': 'Paper covers Rock' - }, - (Entity.PAPER, Entity.SPOCK): { - 'winner': Entity.PAPER, - 'message': 'Paper disapproves Spock' - }, - (Entity.ROCK, Entity.LIZARD): { - 'winner': Entity.ROCK, - 'message': 'Rock crushes Lizard' - }, - (Entity.ROCK, Entity.SCISSOR): { - 'winner': Entity.ROCK, - 'message': 'Rock crushes Scissor' - }, - (Entity.SCISSOR, Entity.PAPER): { - 'winner': Entity.SCISSOR, - 'message': 'Scissor cuts Paper' - }, - (Entity.SCISSOR, Entity.LIZARD): { - 'winner': Entity.SCISSOR, - 'message': 'Scissor decapitates Lizard' - }, - (Entity.SPOCK, Entity.SCISSOR): { - 'winner': Entity.SPOCK, - 'message': 'Spock smashes Scissor' - }, - (Entity.SPOCK, Entity.ROCK): { - 'winner': Entity.SPOCK, - 'message': 'Spock vaporizes Rock' - }, - (Entity.LIZARD, Entity.SPOCK): { - 'winner': Entity.LIZARD, - 'message': 'Lizard poisons Spock' - }, - (Entity.LIZARD, Entity.PAPER): { - 'winner': Entity.PAPER, - 'message': 'Lizard eats Paper' - }, - - } - + (Entity.PAPER, Entity.ROCK): { + "winner": Entity.PAPER, + "message": "Paper covers Rock", + }, + (Entity.PAPER, Entity.SPOCK): { + "winner": Entity.PAPER, + "message": "Paper disapproves Spock", + }, + (Entity.ROCK, Entity.LIZARD): { + "winner": Entity.ROCK, + "message": "Rock crushes Lizard", + }, + (Entity.ROCK, Entity.SCISSOR): { + "winner": Entity.ROCK, + "message": "Rock crushes Scissor", + }, + (Entity.SCISSOR, Entity.PAPER): { + "winner": Entity.SCISSOR, + "message": "Scissor cuts Paper", + }, + (Entity.SCISSOR, Entity.LIZARD): { + "winner": Entity.SCISSOR, + "message": "Scissor decapitates Lizard", + }, + (Entity.SPOCK, Entity.SCISSOR): { + "winner": Entity.SPOCK, + "message": "Spock smashes Scissor", + }, + (Entity.SPOCK, Entity.ROCK): { + "winner": Entity.SPOCK, + "message": "Spock vaporizes Rock", + }, + (Entity.LIZARD, Entity.SPOCK): { + "winner": Entity.LIZARD, + "message": "Lizard poisons Spock", + }, + (Entity.LIZARD, Entity.PAPER): { + "winner": Entity.PAPER, + "message": "Lizard eats Paper", + }, + } + def get_winner(self, entity1: Entity, entity2: Entity) -> Tuple[Entity, str]: """A function to find the winner between two entities and reason for win @@ -63,10 +63,11 @@ def get_winner(self, entity1: Entity, entity2: Entity) -> Tuple[Entity, str]: str: Reason for win """ if (entity1, entity2) in self.rules: - return self.rules[(entity1, entity2)]['winner'], self.rules[(entity1, entity2)]['message'] + return self.rules[(entity1, entity2)]["winner"], self.rules[ + (entity1, entity2) + ]["message"] elif (entity2, entity1) in self.rules: - return self.rules[(entity2, entity1)]['winner'], self.rules[(entity2, entity1)]['message'] - raise KeyError('Invalid entities') - - - + return self.rules[(entity2, entity1)]["winner"], self.rules[ + (entity2, entity1) + ]["message"] + raise KeyError("Invalid entities") diff --git a/2022/code_roast_rpsls/before/scoreboard.py b/2022/code_roast_rpsls/before/scoreboard.py index 2255a15e..a0eb3e4c 100644 --- a/2022/code_roast_rpsls/before/scoreboard.py +++ b/2022/code_roast_rpsls/before/scoreboard.py @@ -3,17 +3,17 @@ class Scoreboard: - """Scoreboard class to register player, track points and display the card - """ + """Scoreboard class to register player, track points and display the card""" + def __init__(self) -> None: self.points: Dict[str, int] = defaultdict(int) - - def register_player(self, user_name:str): + + def register_player(self, user_name: str): self.points[user_name] = 0 - + def display_scores(self): print("Scoreboard:") print("======================================") for user, score in self.points.items(): - print(f"{user} : {score}", end='\t') - print("\n======================================") \ No newline at end of file + print(f"{user} : {score}", end="\t") + print("\n======================================") diff --git a/2022/code_roast_tower_defense/after/TowerDefense.py b/2022/code_roast_tower_defense/after/TowerDefense.py index d406cc04..bc52dd2f 100644 --- a/2022/code_roast_tower_defense/after/TowerDefense.py +++ b/2022/code_roast_tower_defense/after/TowerDefense.py @@ -444,7 +444,6 @@ def displaySpecific(self): self.canvas.create_image(5, 5, image=self.towerImage, anchor=NW) if issubclass(displayTower.__class__, TargetingTower): - self.currentButtons.append(TargetButton(26, 30, 35, 39, 0)) self.canvas.create_text( 37, 28, text="> Health", font=("times", 12), fill="white", anchor=NW @@ -719,7 +718,7 @@ def move(self): def checkHit(self): if ( - self.speed ** 2 + self.speed**2 > (self.x - (self.target.x)) ** 2 + (self.y - (self.target.y)) ** 2 ): self.hit = True diff --git a/2022/code_roast_tower_defense/before/TowerDefense.py b/2022/code_roast_tower_defense/before/TowerDefense.py index e25ff9a5..d78d1355 100644 --- a/2022/code_roast_tower_defense/before/TowerDefense.py +++ b/2022/code_roast_tower_defense/before/TowerDefense.py @@ -1,4 +1,4 @@ -#IMPORTANT INFORMATION: the use of 'self' ALWAYS refers to the class that it is in. EVERY FUNCTION INSIDE OF A CLASS MUST DECLARE SELF! ex: 'def exampleFunction(self, input1, input2): +# IMPORTANT INFORMATION: the use of 'self' ALWAYS refers to the class that it is in. EVERY FUNCTION INSIDE OF A CLASS MUST DECLARE SELF! ex: 'def exampleFunction(self, input1, input2): from tkinter import * from PIL import Image @@ -6,14 +6,34 @@ from PIL import ImageTk import random import math -gridSize = 30 #the height and width of the array of blocks -blockSize = 20 #pixels wide of each block -mapSize = gridSize*blockSize -blockGrid = [[0 for y in range(gridSize)] for x in range(gridSize)] #creates the array for the grid -blockDictionary = ["NormalBlock", "PathBlock","WaterBlock"] -monsterDictionary = ["Monster1", "Monster2","AlexMonster","BenMonster","LeoMonster","MonsterBig"] -towerDictionary = {"Arrow Shooter":"ArrowShooterTower", "Bullet Shooter":"BulletShooterTower", "Tack Tower": "TackTower", "Power Tower": "PowerTower"} -towerCost = {"Arrow Shooter":150,"Bullet Shooter":150,"Tack Tower":150, "Power Tower":200} + +gridSize = 30 # the height and width of the array of blocks +blockSize = 20 # pixels wide of each block +mapSize = gridSize * blockSize +blockGrid = [ + [0 for y in range(gridSize)] for x in range(gridSize) +] # creates the array for the grid +blockDictionary = ["NormalBlock", "PathBlock", "WaterBlock"] +monsterDictionary = [ + "Monster1", + "Monster2", + "AlexMonster", + "BenMonster", + "LeoMonster", + "MonsterBig", +] +towerDictionary = { + "Arrow Shooter": "ArrowShooterTower", + "Bullet Shooter": "BulletShooterTower", + "Tack Tower": "TackTower", + "Power Tower": "PowerTower", +} +towerCost = { + "Arrow Shooter": 150, + "Bullet Shooter": 150, + "Tack Tower": 150, + "Power Tower": 200, +} towerGrid = [[None for y in range(gridSize)] for x in range(gridSize)] pathList = [] spawnx = 0 @@ -23,939 +43,1184 @@ monstersByHealthReversed = [] monstersByDistance = [] monstersByDistanceReversed = [] -monstersListList = [monstersByHealth,monstersByHealthReversed,monstersByDistance,monstersByDistanceReversed] +monstersListList = [ + monstersByHealth, + monstersByHealthReversed, + monstersByDistance, + monstersByDistanceReversed, +] projectiles = [] health = 100 money = 5000000000 selectedTower = "" displayTower = None -class Game(): #the main class that we call "Game" - def __init__(self): #setting up the window for the game here - self.root=Tk() #saying this window will use tkinter - self.root.title("Tower Defense Ultra Mode") - self.RUN=True #creating a variable RUN. does nothing yet.hu - self.root.protocol("WM_DELETE_WINDOW", self.end) - - self.frame = Frame(master= self.root) - self.frame.grid(row = 0, column = 0) - - self.canvas = Canvas(master = self.frame, width=mapSize, height=mapSize, bg = "white", highlightthickness = 0) #actually creates a window and puts our frame on it - self.canvas.grid(row = 0,column = 0,rowspan = 2, columnspan = 1) #makes the window called "canvas" complete - - self.displayboard = Displayboard(self) - - self.infoboard = Infoboard(self) - - self.towerbox = Towerbox(self) - - self.mouse = Mouse(self) - - self.gameMap = Map() - - self.wavegenerator = Wavegenerator(self) - - self.run() #calls the function 'def run(self):' - - self.root.mainloop() #starts running the tkinter graphics loop - - def run(self): - if self.RUN is True: #always going to be true for now - self.update() #calls the function 'def update(self):' - self.paint() #calls the function 'def paint(self):' - - self.root.after(50, self.run) #does a run of the function every 50/1000 = 1/20 of a second - - def end(self): - self.root.destroy() #closes the game window and ends the program - - def update(self): - self.mouse.update() - self.wavegenerator.update() - self.displayboard.update() - for i in range(len(projectiles)): - try: - projectiles[i].update() - except: - pass - for y in range(gridSize): - for x in range(gridSize): - blockGrid[x][y].update() #updates each block one by one by going to its 'def update():' command - for i in range(len(monsters)): - try: - monsters[i].update() - except: - pass - global monstersByHealth - global monstersByHealthReversed - global monstersByDistance - global monstersByDistanceReversed - global monstersListList - monstersByHealth = sorted(monsters, key=lambda x: x.health, reverse=True) - monstersByDistance = sorted(monsters, key=lambda x: x.distanceTravelled, reverse=True) - monstersByHealthReversed = sorted(monsters, key=lambda x: x.health, reverse=False) - monstersByDistanceReversed = sorted(monsters, key=lambda x: x.distanceTravelled, reverse=False) - monstersListList = [monstersByHealth,monstersByHealthReversed,monstersByDistance,monstersByDistanceReversed] - - for y in range(gridSize): - for x in range(gridSize): - if towerGrid[x][y]: - towerGrid[x][y].update() #updates each tower one by one by going to its 'def update():' command - - def paint(self): - self.canvas.delete(ALL) #clear the screen - self.gameMap.paint(self.canvas) - self.mouse.paint(self.canvas) #draw the mouse dot by going to its 'def paint(canvas):' command - for y in range(gridSize): - for x in range(gridSize): - if towerGrid[x][y]: - towerGrid[x][y].paint(self.canvas) - for i in range(len(monstersByDistanceReversed)): - monstersByDistanceReversed[i].paint(self.canvas) - for i in range(len(projectiles)): - projectiles[i].paint(self.canvas) - if displayTower: - displayTower.paintSelect(self.canvas) - self.displayboard.paint() - -class Map(): + +class Game: # the main class that we call "Game" + def __init__(self): # setting up the window for the game here + self.root = Tk() # saying this window will use tkinter + self.root.title("Tower Defense Ultra Mode") + self.RUN = True # creating a variable RUN. does nothing yet.hu + self.root.protocol("WM_DELETE_WINDOW", self.end) + + self.frame = Frame(master=self.root) + self.frame.grid(row=0, column=0) + + self.canvas = Canvas( + master=self.frame, + width=mapSize, + height=mapSize, + bg="white", + highlightthickness=0, + ) # actually creates a window and puts our frame on it + self.canvas.grid( + row=0, column=0, rowspan=2, columnspan=1 + ) # makes the window called "canvas" complete + + self.displayboard = Displayboard(self) + + self.infoboard = Infoboard(self) + + self.towerbox = Towerbox(self) + + self.mouse = Mouse(self) + + self.gameMap = Map() + + self.wavegenerator = Wavegenerator(self) + + self.run() # calls the function 'def run(self):' + + self.root.mainloop() # starts running the tkinter graphics loop + + def run(self): + if self.RUN is True: # always going to be true for now + self.update() # calls the function 'def update(self):' + self.paint() # calls the function 'def paint(self):' + + self.root.after( + 50, self.run + ) # does a run of the function every 50/1000 = 1/20 of a second + + def end(self): + self.root.destroy() # closes the game window and ends the program + + def update(self): + self.mouse.update() + self.wavegenerator.update() + self.displayboard.update() + for i in range(len(projectiles)): + try: + projectiles[i].update() + except: + pass + for y in range(gridSize): + for x in range(gridSize): + blockGrid[x][ + y + ].update() # updates each block one by one by going to its 'def update():' command + for i in range(len(monsters)): + try: + monsters[i].update() + except: + pass + global monstersByHealth + global monstersByHealthReversed + global monstersByDistance + global monstersByDistanceReversed + global monstersListList + monstersByHealth = sorted(monsters, key=lambda x: x.health, reverse=True) + monstersByDistance = sorted( + monsters, key=lambda x: x.distanceTravelled, reverse=True + ) + monstersByHealthReversed = sorted( + monsters, key=lambda x: x.health, reverse=False + ) + monstersByDistanceReversed = sorted( + monsters, key=lambda x: x.distanceTravelled, reverse=False + ) + monstersListList = [ + monstersByHealth, + monstersByHealthReversed, + monstersByDistance, + monstersByDistanceReversed, + ] + + for y in range(gridSize): + for x in range(gridSize): + if towerGrid[x][y]: + towerGrid[x][ + y + ].update() # updates each tower one by one by going to its 'def update():' command + + def paint(self): + self.canvas.delete(ALL) # clear the screen + self.gameMap.paint(self.canvas) + self.mouse.paint( + self.canvas + ) # draw the mouse dot by going to its 'def paint(canvas):' command + for y in range(gridSize): + for x in range(gridSize): + if towerGrid[x][y]: + towerGrid[x][y].paint(self.canvas) + for i in range(len(monstersByDistanceReversed)): + monstersByDistanceReversed[i].paint(self.canvas) + for i in range(len(projectiles)): + projectiles[i].paint(self.canvas) + if displayTower: + displayTower.paintSelect(self.canvas) + self.displayboard.paint() + + +class Map: def __init__(self): self.image = None self.loadMap("LeoMap") - def loadMap(self,mapName): - self.drawnMap = Image.new("RGBA", (mapSize, mapSize), (255,255,255,255)) - self.mapFile = open("texts/mapTexts/"+mapName+".txt","r") + + def loadMap(self, mapName): + self.drawnMap = Image.new("RGBA", (mapSize, mapSize), (255, 255, 255, 255)) + self.mapFile = open("texts/mapTexts/" + mapName + ".txt", "r") self.gridValues = list(map(int, (self.mapFile.read()).split())) for y in range(gridSize): - for x in range(gridSize): - global blockGrid - self.blockNumber = self.gridValues[gridSize*y + x] - self.blockType = globals()[blockDictionary[self.blockNumber]] - blockGrid[x][y] = self.blockType(x*blockSize+blockSize/2,y*blockSize+blockSize/2,self.blockNumber,x,y) #creates a grid of Blocks - blockGrid[x][y].paint(self.drawnMap) - self.drawnMap.save("images/mapImages/"+mapName+".png") - self.image = Image.open("images/mapImages/"+mapName+".png") + for x in range(gridSize): + global blockGrid + self.blockNumber = self.gridValues[gridSize * y + x] + self.blockType = globals()[blockDictionary[self.blockNumber]] + blockGrid[x][y] = self.blockType( + x * blockSize + blockSize / 2, + y * blockSize + blockSize / 2, + self.blockNumber, + x, + y, + ) # creates a grid of Blocks + blockGrid[x][y].paint(self.drawnMap) + self.drawnMap.save("images/mapImages/" + mapName + ".png") + self.image = Image.open("images/mapImages/" + mapName + ".png") self.image = ImageTk.PhotoImage(self.image) - + def saveMap(self): - self.mapFile = open("firstMap.txt","w") + self.mapFile = open("firstMap.txt", "w") for y in range(gridSize): - for x in range(gridSize): - self.mapFile.write(blockGrid[x][y].blockType + " ") + for x in range(gridSize): + self.mapFile.write(blockGrid[x][y].blockType + " ") self.mapFile.close() def paint(self, canvas): - canvas.create_image(0,0, image = self.image, anchor = NW) - - -class Wavegenerator(): - def __init__(self,game): - self.game = game - self.done = False - self.currentWave = [] - self.currentMonster = 0 - self.direction = None - self.gridx = 0 - self.gridy = 0 - self.findSpawn() - self.decideMove() - self.ticks = 1 - self.maxTicks = 2 - self.waveFile = open("texts/waveTexts/WaveGenerator2.txt","r") - - def getWave(self): - self.game.displayboard.nextWaveButton.canPress = False - self.currentMonster = 1 - self.waveLine = self.waveFile.readline() - if len(self.waveLine) == 0: - self.done = True - else: - self.currentWave = self.waveLine.split() - self.currentWave = list(map(int, self.currentWave)) - self.maxTicks = self.currentWave[0] - - def findSpawn(self): - global spawnx - global spawny - for x in range(gridSize): - if isinstance(blockGrid[x][0], PathBlock): - self.gridx = x - spawnx = x*blockSize + blockSize/2 - spawny = 0 - return - for y in range(gridSize): - if isinstance(blockGrid[0][y], PathBlock): - self.gridy = y - spawnx = 0 - spawny = y*blockSize + blockSize/2 - return - - def move(self): + canvas.create_image(0, 0, image=self.image, anchor=NW) + + +class Wavegenerator: + def __init__(self, game): + self.game = game + self.done = False + self.currentWave = [] + self.currentMonster = 0 + self.direction = None + self.gridx = 0 + self.gridy = 0 + self.findSpawn() + self.decideMove() + self.ticks = 1 + self.maxTicks = 2 + self.waveFile = open("texts/waveTexts/WaveGenerator2.txt", "r") + + def getWave(self): + self.game.displayboard.nextWaveButton.canPress = False + self.currentMonster = 1 + self.waveLine = self.waveFile.readline() + if len(self.waveLine) == 0: + self.done = True + else: + self.currentWave = self.waveLine.split() + self.currentWave = list(map(int, self.currentWave)) + self.maxTicks = self.currentWave[0] + + def findSpawn(self): + global spawnx + global spawny + for x in range(gridSize): + if isinstance(blockGrid[x][0], PathBlock): + self.gridx = x + spawnx = x * blockSize + blockSize / 2 + spawny = 0 + return + for y in range(gridSize): + if isinstance(blockGrid[0][y], PathBlock): + self.gridy = y + spawnx = 0 + spawny = y * blockSize + blockSize / 2 + return + + def move(self): global pathList pathList.append(self.direction) if self.direction == 1: - self.gridx += 1 + self.gridx += 1 if self.direction == 2: - self.gridx -= 1 + self.gridx -= 1 if self.direction == 3: - self.gridy +=1 + self.gridy += 1 if self.direction == 4: - self.gridy -=1 + self.gridy -= 1 self.decideMove() - def decideMove(self): - if self.direction != 2 and self.gridx < gridSize-1 and self.gridy >= 0 and self.gridy <= gridSize-1: - if isinstance(blockGrid[self.gridx+1][self.gridy], PathBlock): + def decideMove(self): + if ( + self.direction != 2 + and self.gridx < gridSize - 1 + and self.gridy >= 0 + and self.gridy <= gridSize - 1 + ): + if isinstance(blockGrid[self.gridx + 1][self.gridy], PathBlock): self.direction = 1 self.move() return - - if self.direction != 1 and self.gridx > 0 and self.gridy >= 0 and self.gridy <= gridSize-1: - if isinstance(blockGrid[self.gridx-1][self.gridy], PathBlock): + + if ( + self.direction != 1 + and self.gridx > 0 + and self.gridy >= 0 + and self.gridy <= gridSize - 1 + ): + if isinstance(blockGrid[self.gridx - 1][self.gridy], PathBlock): self.direction = 2 self.move() return - if self.direction != 4 and self.gridy < gridSize-1 and self.gridx >= 0 and self.gridx <= gridSize-1: - if isinstance(blockGrid[self.gridx][self.gridy+1], PathBlock): + if ( + self.direction != 4 + and self.gridy < gridSize - 1 + and self.gridx >= 0 + and self.gridx <= gridSize - 1 + ): + if isinstance(blockGrid[self.gridx][self.gridy + 1], PathBlock): self.direction = 3 self.move() return - - if self.direction != 3 and self.gridy > 0 and self.gridx >= 0 and self.gridx <= gridSize-1: - if isinstance(blockGrid[self.gridx][self.gridy-1], PathBlock): + + if ( + self.direction != 3 + and self.gridy > 0 + and self.gridx >= 0 + and self.gridx <= gridSize - 1 + ): + if isinstance(blockGrid[self.gridx][self.gridy - 1], PathBlock): self.direction = 4 self.move() return - global pathList - pathList.append(5) + global pathList + pathList.append(5) + + def spawnMonster(self): + self.monsterType = globals()[ + monsterDictionary[self.currentWave[self.currentMonster]] + ] + monsters.append(self.monsterType(0)) + self.currentMonster = self.currentMonster + 1 - def spawnMonster(self): - self.monsterType = globals()[monsterDictionary[self.currentWave[self.currentMonster]]] - monsters.append(self.monsterType(0)) - self.currentMonster = self.currentMonster + 1 + def update(self): + if self.done == False: + if self.currentMonster == len(self.currentWave): + self.game.displayboard.nextWaveButton.canPress = True + else: + self.ticks = self.ticks + 1 + if self.ticks == self.maxTicks: + self.ticks = 0 + self.spawnMonster() - def update(self): - if self.done == False: - if self.currentMonster == len(self.currentWave): - self.game.displayboard.nextWaveButton.canPress = True - else: - self.ticks = self.ticks+1 - if self.ticks == self.maxTicks: - self.ticks = 0 - self.spawnMonster() class NextWaveButton: - def __init__(self,game): - self.game = game - self.x = 450 - self.y = 25 - self.xTwo = 550 - self.yTwo = 50 - self.canPress = True - - def checkPress(self, click, x, y): - if x >=self.x and y >= self.y and x <= self.xTwo and y <= self.yTwo: - if self.canPress and click and len(monsters) == 0: - self.game.wavegenerator.getWave() - - def paint(self, canvas): - if self.canPress and len(monsters) == 0: - self.color = "blue" - else: - self.color = "red" - canvas.create_rectangle(self.x, self.y, self.xTwo, self.yTwo, fill=self.color, outline = self.color) #draws a rectangle where the pointer is - canvas.create_text(500,37,text = "Next Wave") - + def __init__(self, game): + self.game = game + self.x = 450 + self.y = 25 + self.xTwo = 550 + self.yTwo = 50 + self.canPress = True + + def checkPress(self, click, x, y): + if x >= self.x and y >= self.y and x <= self.xTwo and y <= self.yTwo: + if self.canPress and click and len(monsters) == 0: + self.game.wavegenerator.getWave() + + def paint(self, canvas): + if self.canPress and len(monsters) == 0: + self.color = "blue" + else: + self.color = "red" + canvas.create_rectangle( + self.x, self.y, self.xTwo, self.yTwo, fill=self.color, outline=self.color + ) # draws a rectangle where the pointer is + canvas.create_text(500, 37, text="Next Wave") + + class MyButton(object): - def __init__(self, x, y, xTwo, yTwo): + def __init__(self, x, y, xTwo, yTwo): self.x = x self.y = y self.xTwo = xTwo self.yTwo = yTwo - - def checkPress(self, click, x, y): - if x >=self.x and y >= self.y and x <= self.xTwo and y <= self.yTwo: - self.pressed() - return True + + def checkPress(self, click, x, y): + if x >= self.x and y >= self.y and x <= self.xTwo and y <= self.yTwo: + self.pressed() + return True return False - def pressed(self): - pass + def pressed(self): + pass + + def paint(self, canvas): + canvas.create_rectangle( + self.x, self.y, self.xTwo, self.yTwo, fill="red", outline="black" + ) - def paint(self, canvas): - canvas.create_rectangle(self.x, self.y, self.xTwo, self.yTwo, fill="red", outline = "black") class TargetButton(MyButton): def __init__(self, x, y, xTwo, yTwo, myType): - super(TargetButton,self).__init__( x, y, xTwo, yTwo) + super(TargetButton, self).__init__(x, y, xTwo, yTwo) self.type = myType - + def pressed(self): - global displayTower - displayTower.targetList = self.type + global displayTower + displayTower.targetList = self.type + class StickyButton(MyButton): def __init__(self, x, y, xTwo, yTwo): - super(StickyButton,self).__init__(x, y, xTwo, yTwo) - + super(StickyButton, self).__init__(x, y, xTwo, yTwo) + def pressed(self): - global displayTower - if displayTower.stickyTarget == False: - displayTower.stickyTarget = True - else: - displayTower.stickyTarget = False + global displayTower + if displayTower.stickyTarget == False: + displayTower.stickyTarget = True + else: + displayTower.stickyTarget = False + class SellButton(MyButton): def __init__(self, x, y, xTwo, yTwo): - super(SellButton,self).__init__(x, y, xTwo, yTwo) - + super(SellButton, self).__init__(x, y, xTwo, yTwo) + def pressed(self): - global displayTower - displayTower.sold() - displayTower = None + global displayTower + displayTower.sold() + displayTower = None + class UpgradeButton(MyButton): def __init__(self, x, y, xTwo, yTwo): - super(UpgradeButton,self).__init__(x, y, xTwo, yTwo) - + super(UpgradeButton, self).__init__(x, y, xTwo, yTwo) + def pressed(self): - global money - global displayTower - if money >= displayTower.upgradeCost: - money -= displayTower.upgradeCost - displayTower.upgrade() - + global money + global displayTower + if money >= displayTower.upgradeCost: + money -= displayTower.upgradeCost + displayTower.upgrade() + + class Infoboard: - def __init__(self, game): - self.canvas = Canvas(master = game.frame, width = 162, height = 174, bg = "gray", highlightthickness = 0) - self.canvas.grid(row = 0, column = 1) - self.image = ImageTk.PhotoImage(Image.open("images/infoBoard.png")) - self.canvas.create_image(0,0 , image = self.image, anchor = NW) - self.currentButtons = [] - - def buttonsCheck(self, click, x, y): - if click: - for i in range(len(self.currentButtons)): - if self.currentButtons[i].checkPress(click, x, y): - self.displaySpecific() - return - - def displaySpecific(self): - self.canvas.delete(ALL) #clear the screen - self.canvas.create_image(0,0, image = self.image, anchor = NW) - self.currentButtons = [] - if displayTower== None: - return - - self.towerImage = ImageTk.PhotoImage(Image.open("images/towerImages/"+displayTower.__class__.__name__+"/"+str(displayTower.level)+ ".png")) - self.canvas.create_text(80,75,text = displayTower.name, font = ("times",20)) - self.canvas.create_image(5,5 , image = self.towerImage, anchor = NW) - - if issubclass(displayTower.__class__, TargetingTower): - - self.currentButtons.append(TargetButton(26,30,35,39,0)) - self.canvas.create_text(37,28,text = "> Health", font = ("times",12), fill = "white", anchor = NW) - - self.currentButtons.append(TargetButton(26,50,35,59,1)) - self.canvas.create_text(37,48,text = "< Health", font = ("times",12), fill = "white", anchor = NW) - - self.currentButtons.append(TargetButton(92,50,101,59,2)) - self.canvas.create_text(103,48,text = "> Distance", font = ("times",12), fill = "white", anchor = NW) - - self.currentButtons.append(TargetButton(92,30,101,39,3)) - self.canvas.create_text(103,28,text = "< Distance", font = ("times",12), fill = "white", anchor = NW) - - - - self.currentButtons.append(StickyButton(10,40,19,49)) - self.currentButtons.append(SellButton(5,145,78,168)) - if displayTower.upgradeCost: - self.currentButtons.append(UpgradeButton(82,145,155,168)) - self.canvas.create_text(120,157,text = "Upgrade: "+ str(displayTower.upgradeCost), font = ("times",12), fill = "light green", anchor = CENTER) - - self.canvas.create_text(28,146,text = "Sell", font = ("times",22), fill = "light green", anchor = NW) - - self.currentButtons[displayTower.targetList].paint(self.canvas) - if displayTower.stickyTarget == True: - self.currentButtons[4].paint(self.canvas) - - def displayGeneric(self): - self.currentButtons = [] - if selectedTower == "": - self.text = None - self.towerImage = None - else: - self.text = selectedTower + " cost: " + str(towerCost[selectedTower]) - self.towerImage = ImageTk.PhotoImage(Image.open("images/towerImages/"+towerDictionary[selectedTower]+"/1.png")) - self.canvas.delete(ALL) #clear the screen - self.canvas.create_image(0,0, image = self.image, anchor = NW) - self.canvas.create_text(80,75,text = self.text) - self.canvas.create_image(5,5 , image = self.towerImage, anchor = NW) - + def __init__(self, game): + self.canvas = Canvas( + master=game.frame, width=162, height=174, bg="gray", highlightthickness=0 + ) + self.canvas.grid(row=0, column=1) + self.image = ImageTk.PhotoImage(Image.open("images/infoBoard.png")) + self.canvas.create_image(0, 0, image=self.image, anchor=NW) + self.currentButtons = [] + + def buttonsCheck(self, click, x, y): + if click: + for i in range(len(self.currentButtons)): + if self.currentButtons[i].checkPress(click, x, y): + self.displaySpecific() + return + + def displaySpecific(self): + self.canvas.delete(ALL) # clear the screen + self.canvas.create_image(0, 0, image=self.image, anchor=NW) + self.currentButtons = [] + if displayTower == None: + return + + self.towerImage = ImageTk.PhotoImage( + Image.open( + "images/towerImages/" + + displayTower.__class__.__name__ + + "/" + + str(displayTower.level) + + ".png" + ) + ) + self.canvas.create_text(80, 75, text=displayTower.name, font=("times", 20)) + self.canvas.create_image(5, 5, image=self.towerImage, anchor=NW) + + if issubclass(displayTower.__class__, TargetingTower): + self.currentButtons.append(TargetButton(26, 30, 35, 39, 0)) + self.canvas.create_text( + 37, 28, text="> Health", font=("times", 12), fill="white", anchor=NW + ) + + self.currentButtons.append(TargetButton(26, 50, 35, 59, 1)) + self.canvas.create_text( + 37, 48, text="< Health", font=("times", 12), fill="white", anchor=NW + ) + + self.currentButtons.append(TargetButton(92, 50, 101, 59, 2)) + self.canvas.create_text( + 103, 48, text="> Distance", font=("times", 12), fill="white", anchor=NW + ) + + self.currentButtons.append(TargetButton(92, 30, 101, 39, 3)) + self.canvas.create_text( + 103, 28, text="< Distance", font=("times", 12), fill="white", anchor=NW + ) + + self.currentButtons.append(StickyButton(10, 40, 19, 49)) + self.currentButtons.append(SellButton(5, 145, 78, 168)) + if displayTower.upgradeCost: + self.currentButtons.append(UpgradeButton(82, 145, 155, 168)) + self.canvas.create_text( + 120, + 157, + text="Upgrade: " + str(displayTower.upgradeCost), + font=("times", 12), + fill="light green", + anchor=CENTER, + ) + + self.canvas.create_text( + 28, 146, text="Sell", font=("times", 22), fill="light green", anchor=NW + ) + + self.currentButtons[displayTower.targetList].paint(self.canvas) + if displayTower.stickyTarget == True: + self.currentButtons[4].paint(self.canvas) + + def displayGeneric(self): + self.currentButtons = [] + if selectedTower == "": + self.text = None + self.towerImage = None + else: + self.text = selectedTower + " cost: " + str(towerCost[selectedTower]) + self.towerImage = ImageTk.PhotoImage( + Image.open( + "images/towerImages/" + towerDictionary[selectedTower] + "/1.png" + ) + ) + self.canvas.delete(ALL) # clear the screen + self.canvas.create_image(0, 0, image=self.image, anchor=NW) + self.canvas.create_text(80, 75, text=self.text) + self.canvas.create_image(5, 5, image=self.towerImage, anchor=NW) + + class Displayboard: def __init__(self, game): - self.canvas = Canvas(master = game.frame, width = 600, height = 80, bg = "gray", highlightthickness = 0) - self.canvas.grid(row = 2, column = 0) - self.healthbar = Healthbar() - self.moneybar = Moneybar() - self.nextWaveButton = NextWaveButton(game) - self.paint() + self.canvas = Canvas( + master=game.frame, width=600, height=80, bg="gray", highlightthickness=0 + ) + self.canvas.grid(row=2, column=0) + self.healthbar = Healthbar() + self.moneybar = Moneybar() + self.nextWaveButton = NextWaveButton(game) + self.paint() + def update(self): self.healthbar.update() self.moneybar.update() - - def paint(self): - self.canvas.delete(ALL) #clear the screen - self.healthbar.paint(self.canvas) - self.moneybar.paint(self.canvas) - self.nextWaveButton.paint(self.canvas) - + + def paint(self): + self.canvas.delete(ALL) # clear the screen + self.healthbar.paint(self.canvas) + self.moneybar.paint(self.canvas) + self.nextWaveButton.paint(self.canvas) + class Towerbox: - def __init__(self, game): - self.game = game - self.box = Listbox(master =game.frame, selectmode = "SINGLE", font = ("times",18), height = 18, width = 13, bg = "gray", fg = "dark blue", bd = 1, highlightthickness = 0) - self.box.insert(END, "") - for i in towerDictionary: - self.box.insert(END, i) - for i in range(50): - self.box.insert(END, "") - self.box.grid(row = 1, column = 1, rowspan = 2) - self.box.bind("<>", self.onselect) - def onselect(self,event): - global selectedTower - global displayTower - selectedTower = str(self.box.get(self.box.curselection())) - displayTower = None - self.game.infoboard.displayGeneric() -class Mouse(): - def __init__(self,game): #when i define a "Mouse", this is what happens - self.game = game - self.x = 0 - self.y = 0 - self.gridx = 0 - self.gridy = 0 - self.xoffset = 0 - self.yoffset = 0 - self.pressed = False - game.root.bind("", self.clicked) #whenever left mouse button is pressed, go to def released(event) - game.root.bind("", self.released) #whenever left mouse button is released, go to def released(event) - game.root.bind("", self.motion) #whenever left mouse button is dragged, go to def released(event) - self.image = Image.open("images/mouseImages/HoveringCanPress.png") - self.image = ImageTk.PhotoImage(self.image) - self.canNotPressImage = Image.open("images/mouseImages/HoveringCanNotPress.png") - self.canNotPressImage = ImageTk.PhotoImage(self.canNotPressImage) - - def clicked(self, event): - self.pressed = True #sets a variable + def __init__(self, game): + self.game = game + self.box = Listbox( + master=game.frame, + selectmode="SINGLE", + font=("times", 18), + height=18, + width=13, + bg="gray", + fg="dark blue", + bd=1, + highlightthickness=0, + ) + self.box.insert(END, "") + for i in towerDictionary: + self.box.insert(END, i) + for i in range(50): + self.box.insert(END, "") + self.box.grid(row=1, column=1, rowspan=2) + self.box.bind("<>", self.onselect) + + def onselect(self, event): + global selectedTower + global displayTower + selectedTower = str(self.box.get(self.box.curselection())) + displayTower = None + self.game.infoboard.displayGeneric() + + +class Mouse: + def __init__(self, game): # when i define a "Mouse", this is what happens + self.game = game + self.x = 0 + self.y = 0 + self.gridx = 0 + self.gridy = 0 + self.xoffset = 0 + self.yoffset = 0 + self.pressed = False + game.root.bind( + "", self.clicked + ) # whenever left mouse button is pressed, go to def released(event) + game.root.bind( + "", self.released + ) # whenever left mouse button is released, go to def released(event) + game.root.bind( + "", self.motion + ) # whenever left mouse button is dragged, go to def released(event) + self.image = Image.open("images/mouseImages/HoveringCanPress.png") + self.image = ImageTk.PhotoImage(self.image) + self.canNotPressImage = Image.open("images/mouseImages/HoveringCanNotPress.png") + self.canNotPressImage = ImageTk.PhotoImage(self.canNotPressImage) + + def clicked(self, event): + self.pressed = True # sets a variable self.image = Image.open("images/mouseImages/Pressed.png") - self.image = ImageTk.PhotoImage(self.image) - - def released(self, event): + self.image = ImageTk.PhotoImage(self.image) + + def released(self, event): self.pressed = False self.image = Image.open("images/mouseImages/HoveringCanPress.png") - self.image = ImageTk.PhotoImage(self.image) - - def motion(self, event): - if event.widget == self.game.canvas: - self.xoffset = 0 - self.yoffset = 0 - elif event.widget == self.game.infoboard.canvas: - self.xoffset = mapSize - self.yoffset = 0 - elif event.widget == self.game.towerbox.box: - self.xoffset = mapSize - self.yoffset = 174 - elif event.widget == self.game.displayboard.canvas: - self.yoffset = mapSize - self.xoffset = 0 - self.x = event.x +self.xoffset#sets the "Mouse" x to the real mouse's x - self.y = event.y +self.yoffset#sets the "Mouse" y to the real mouse's y - if self.x < 0: self.x = 0 - if self.y < 0: self.y = 0 - self.gridx = int((self.x-(self.x%blockSize))/blockSize) - self.gridy = int((self.y-(self.y%blockSize))/blockSize) - - def update(self): - if self.gridx >= 0 and self.gridx <= gridSize-1 and self.gridy >= 0 and self.gridy <= gridSize-1: - blockGrid[self.gridx][self.gridy].hoveredOver(self.pressed, self.game) - else: - self.game.displayboard.nextWaveButton.checkPress(self.pressed, self.x-self.xoffset, self.y-self.yoffset) - self.game.infoboard.buttonsCheck(self.pressed, self.x-self.xoffset, self.y-self.yoffset) - def paint(self, canvas): - if self.gridx >= 0 and self.gridx <= gridSize-1 and self.gridy >= 0 and self.gridy <= gridSize-1: - if blockGrid[self.gridx][self.gridy].canPlace: - canvas.create_image(self.gridx*blockSize,self.gridy*blockSize, image = self.image, anchor = NW) - else: - canvas.create_image(self.gridx*blockSize,self.gridy*blockSize, image = self.canNotPressImage, anchor = NW) - - -class Healthbar(): - def __init__(self): - self.text = str(health) - - def update(self): + self.image = ImageTk.PhotoImage(self.image) + + def motion(self, event): + if event.widget == self.game.canvas: + self.xoffset = 0 + self.yoffset = 0 + elif event.widget == self.game.infoboard.canvas: + self.xoffset = mapSize + self.yoffset = 0 + elif event.widget == self.game.towerbox.box: + self.xoffset = mapSize + self.yoffset = 174 + elif event.widget == self.game.displayboard.canvas: + self.yoffset = mapSize + self.xoffset = 0 + self.x = event.x + self.xoffset # sets the "Mouse" x to the real mouse's x + self.y = event.y + self.yoffset # sets the "Mouse" y to the real mouse's y + if self.x < 0: + self.x = 0 + if self.y < 0: + self.y = 0 + self.gridx = int((self.x - (self.x % blockSize)) / blockSize) + self.gridy = int((self.y - (self.y % blockSize)) / blockSize) + + def update(self): + if ( + self.gridx >= 0 + and self.gridx <= gridSize - 1 + and self.gridy >= 0 + and self.gridy <= gridSize - 1 + ): + blockGrid[self.gridx][self.gridy].hoveredOver(self.pressed, self.game) + else: + self.game.displayboard.nextWaveButton.checkPress( + self.pressed, self.x - self.xoffset, self.y - self.yoffset + ) + self.game.infoboard.buttonsCheck( + self.pressed, self.x - self.xoffset, self.y - self.yoffset + ) + + def paint(self, canvas): + if ( + self.gridx >= 0 + and self.gridx <= gridSize - 1 + and self.gridy >= 0 + and self.gridy <= gridSize - 1 + ): + if blockGrid[self.gridx][self.gridy].canPlace: + canvas.create_image( + self.gridx * blockSize, + self.gridy * blockSize, + image=self.image, + anchor=NW, + ) + else: + canvas.create_image( + self.gridx * blockSize, + self.gridy * blockSize, + image=self.canNotPressImage, + anchor=NW, + ) + + +class Healthbar: + def __init__(self): self.text = str(health) - - def paint(self, canvas): - canvas.create_text(40, 40, text="Health: " + self.text,fill="black") - - -class Moneybar(): - def __init__(self): - self.text = str(money) - - def update(self): + + def update(self): + self.text = str(health) + + def paint(self, canvas): + canvas.create_text(40, 40, text="Health: " + self.text, fill="black") + + +class Moneybar: + def __init__(self): + self.text = str(money) + + def update(self): self.text = str(money) - - def paint(self, canvas): - canvas.create_text(240, 40, text="Money: " + self.text,fill="black") + + def paint(self, canvas): + canvas.create_text(240, 40, text="Money: " + self.text, fill="black") + class Projectile(object): - def __init__(self,x,y,damage,speed): + def __init__(self, x, y, damage, speed): self.hit = False self.x = x self.y = y - self.speed = blockSize/2 + self.speed = blockSize / 2 self.damage = damage self.speed = speed - #self.image = Image.open("images/projectileImages/"+self.__class__.__name__+ ".png") - #self.image = ImageTk.PhotoImage(self.image) - - def update(self): - try: - if target.alive == False: - projectiles.remove(self) - return - except: - if self.hit: - self.gotMonster() - self.move() - self.checkHit() - - def gotMonster(self): + # self.image = Image.open("images/projectileImages/"+self.__class__.__name__+ ".png") + # self.image = ImageTk.PhotoImage(self.image) + + def update(self): + try: + if target.alive == False: + projectiles.remove(self) + return + except: + if self.hit: + self.gotMonster() + self.move() + self.checkHit() + + def gotMonster(self): self.target.health -= self.damage projectiles.remove(self) - - def paint(self,canvas): - canvas.create_image(self.x,self.y,image = self.image) - + + def paint(self, canvas): + canvas.create_image(self.x, self.y, image=self.image) + class TrackingBullet(Projectile): - def __init__(self,x,y,damage,speed,target): - super(TrackingBullet,self).__init__(x,y, damage,speed) - self.target = target - self.image = Image.open("images/projectileImages/bullet.png") - self.image = ImageTk.PhotoImage(self.image) - + def __init__(self, x, y, damage, speed, target): + super(TrackingBullet, self).__init__(x, y, damage, speed) + self.target = target + self.image = Image.open("images/projectileImages/bullet.png") + self.image = ImageTk.PhotoImage(self.image) + def move(self): - self.length = ((self.x-(self.target.x))**2 + (self.y-(self.target.y))**2)**0.5 - self.x += self.speed*((self.target.x)-self.x)/self.length - self.y += self.speed*((self.target.y)-self.y)/self.length - + self.length = ( + (self.x - (self.target.x)) ** 2 + (self.y - (self.target.y)) ** 2 + ) ** 0.5 + self.x += self.speed * ((self.target.x) - self.x) / self.length + self.y += self.speed * ((self.target.y) - self.y) / self.length + def checkHit(self): - if self.speed**2 > (self.x-(self.target.x))**2 + (self.y-(self.target.y))**2: + if ( + self.speed**2 + > (self.x - (self.target.x)) ** 2 + (self.y - (self.target.y)) ** 2 + ): self.hit = True + class PowerShot(TrackingBullet): - def __init__(self,x,y,damage,speed,target,slow): - super(PowerShot,self).__init__(x,y, damage,speed,target) - self.slow = slow - self.image = Image.open("images/projectileImages/powerShot.png") - self.image = ImageTk.PhotoImage(self.image) + def __init__(self, x, y, damage, speed, target, slow): + super(PowerShot, self).__init__(x, y, damage, speed, target) + self.slow = slow + self.image = Image.open("images/projectileImages/powerShot.png") + self.image = ImageTk.PhotoImage(self.image) def gotMonster(self): self.target.health -= self.damage - if self.target.movement > (self.target.speed)/self.slow: - self.target.movement = (self.target.speed)/self.slow - projectiles.remove(self) - + if self.target.movement > (self.target.speed) / self.slow: + self.target.movement = (self.target.speed) / self.slow + projectiles.remove(self) + + class AngledProjectile(Projectile): - def __init__(self,x,y,damage,speed,angle,givenRange): - super(AngledProjectile,self).__init__(x,y,damage,speed) - self.xChange = speed*math.cos(angle) - self.yChange = speed*math.sin(-angle) - self.range = givenRange - self.image = Image.open("images/projectileImages/arrow.png") - self.image = ImageTk.PhotoImage(self.image.rotate(math.degrees(angle))) - self.target = None - self.speed = speed - self.distance = 0 - - def checkHit(self): - for i in range(len(monsters)): - if (monsters[i].x-self.x)**2+(monsters[i].y-self.y)**2 <= (blockSize)**2: - self.hit = True - self.target = monsters[i] - return - - def gotMonster(self): + def __init__(self, x, y, damage, speed, angle, givenRange): + super(AngledProjectile, self).__init__(x, y, damage, speed) + self.xChange = speed * math.cos(angle) + self.yChange = speed * math.sin(-angle) + self.range = givenRange + self.image = Image.open("images/projectileImages/arrow.png") + self.image = ImageTk.PhotoImage(self.image.rotate(math.degrees(angle))) + self.target = None + self.speed = speed + self.distance = 0 + + def checkHit(self): + for i in range(len(monsters)): + if (monsters[i].x - self.x) ** 2 + (monsters[i].y - self.y) ** 2 <= ( + blockSize + ) ** 2: + self.hit = True + self.target = monsters[i] + return + + def gotMonster(self): self.target.health -= self.damage self.target.tick = 0 self.target.maxTick = 5 projectiles.remove(self) - def move(self): - self.x += self.xChange - self.y += self.yChange - self.distance += self.speed - if self.distance >= self.range: - projectiles.remove(self) - - + def move(self): + self.x += self.xChange + self.y += self.yChange + self.distance += self.speed + if self.distance >= self.range: + projectiles.remove(self) + + class Tower(object): - def __init__(self,x,y,gridx,gridy): - self.upgradeCost = None - self.level = 1 - self.range = 0 - self.clicked = False - self.x = x - self.y = y - self.gridx = gridx - self.gridy = gridy - self.image = Image.open("images/towerImages/"+self.__class__.__name__+"/1.png") - self.image = ImageTk.PhotoImage(self.image) - - def update(self): - pass - - def upgrade(self): - self.level = self.level+1 - self.image = Image.open("images/towerImages/"+self.__class__.__name__+"/"+str(self.level)+".png") - self.image = ImageTk.PhotoImage(self.image) - self.nextLevel() - - def sold(self): - towerGrid[self.gridx][self.gridy] = None - - def paintSelect(self,canvas): - canvas.create_oval(self.x-self.range,self.y-self.range,self.x + self.range,self.y + self.range,fill=None, outline = "white") - - def paint(self, canvas): - canvas.create_image(self.x,self.y, image = self.image, anchor = CENTER) + def __init__(self, x, y, gridx, gridy): + self.upgradeCost = None + self.level = 1 + self.range = 0 + self.clicked = False + self.x = x + self.y = y + self.gridx = gridx + self.gridy = gridy + self.image = Image.open( + "images/towerImages/" + self.__class__.__name__ + "/1.png" + ) + self.image = ImageTk.PhotoImage(self.image) + + def update(self): + pass + + def upgrade(self): + self.level = self.level + 1 + self.image = Image.open( + "images/towerImages/" + + self.__class__.__name__ + + "/" + + str(self.level) + + ".png" + ) + self.image = ImageTk.PhotoImage(self.image) + self.nextLevel() + + def sold(self): + towerGrid[self.gridx][self.gridy] = None + + def paintSelect(self, canvas): + canvas.create_oval( + self.x - self.range, + self.y - self.range, + self.x + self.range, + self.y + self.range, + fill=None, + outline="white", + ) + + def paint(self, canvas): + canvas.create_image(self.x, self.y, image=self.image, anchor=CENTER) + class ShootingTower(Tower): - def __init__(self,x,y,gridx,gridy): - super(ShootingTower,self).__init__(x,y,gridx,gridy) + def __init__(self, x, y, gridx, gridy): + super(ShootingTower, self).__init__(x, y, gridx, gridy) self.bulletsPerSecond = None self.ticks = 0 self.damage = 0 self.speed = None - def update(self): - self.prepareShot() - + def update(self): + self.prepareShot() + + class TargetingTower(ShootingTower): - def __init__(self,x,y,gridx,gridy): - super(TargetingTower,self).__init__(x,y,gridx,gridy) + def __init__(self, x, y, gridx, gridy): + super(TargetingTower, self).__init__(x, y, gridx, gridy) self.target = None self.targetList = 0 self.stickyTarget = False - + def prepareShot(self): - self.checkList = monstersListList[self.targetList] - if self.ticks != 20/self.bulletsPerSecond: - self.ticks += 1 - if self.stickyTarget == False: - for i in range(len(self.checkList)): - if (self.range+blockSize/2)**2 >= (self.x-self.checkList[i].x)**2 + (self.y-self.checkList[i].y)**2: - self.target = self.checkList[i] - if self.target: - if self.target.alive and (self.range +blockSize/2) >= ((self.x-self.target.x)**2 + (self.y-self.target.y)**2)**0.5: - if self.ticks >= 20/self.bulletsPerSecond: - self.shoot() - self.ticks = 0 - else: - self.target = None - elif self.stickyTarget == True: - for i in range(len(self.checkList)): - if (self.range+blockSize/2)**2 >= (self.x-self.checkList[i].x)**2 + (self.y-self.checkList[i].y)**2: - self.target = self.checkList[i] - + self.checkList = monstersListList[self.targetList] + if self.ticks != 20 / self.bulletsPerSecond: + self.ticks += 1 + if self.stickyTarget == False: + for i in range(len(self.checkList)): + if (self.range + blockSize / 2) ** 2 >= ( + self.x - self.checkList[i].x + ) ** 2 + (self.y - self.checkList[i].y) ** 2: + self.target = self.checkList[i] + if self.target: + if ( + self.target.alive + and (self.range + blockSize / 2) + >= ((self.x - self.target.x) ** 2 + (self.y - self.target.y) ** 2) + ** 0.5 + ): + if self.ticks >= 20 / self.bulletsPerSecond: + self.shoot() + self.ticks = 0 + else: + self.target = None + elif self.stickyTarget == True: + for i in range(len(self.checkList)): + if (self.range + blockSize / 2) ** 2 >= ( + self.x - self.checkList[i].x + ) ** 2 + (self.y - self.checkList[i].y) ** 2: + self.target = self.checkList[i] + class ArrowShooterTower(TargetingTower): - def __init__(self,x,y,gridx,gridy): - super(ArrowShooterTower,self).__init__(x,y,gridx,gridy) - self.name = "Arrow Shooter" - self.infotext = "ArrowShooterTower at [" + str(gridx) + "," + str(gridy) + "]." - self.range = blockSize*10 - self.bulletsPerSecond = 1 - self.damage = 10 - self.speed = blockSize - self.upgradeCost = 50 - - def nextLevel(self): - if self.level == 2: - self.upgradeCost = 100 - self.range = blockSize*11 - self.damage = 12 - elif self.level == 3: - self.upgradeCost = None - self.bulletsPerSecond = 2 - - def shoot(self): - self.angle = math.atan2(self.y- self.target.y,self.target.x-self.x) - projectiles.append(AngledProjectile(self.x , self.y, self.damage, self.speed, self.angle,self.range+blockSize/2)) - + def __init__(self, x, y, gridx, gridy): + super(ArrowShooterTower, self).__init__(x, y, gridx, gridy) + self.name = "Arrow Shooter" + self.infotext = "ArrowShooterTower at [" + str(gridx) + "," + str(gridy) + "]." + self.range = blockSize * 10 + self.bulletsPerSecond = 1 + self.damage = 10 + self.speed = blockSize + self.upgradeCost = 50 + + def nextLevel(self): + if self.level == 2: + self.upgradeCost = 100 + self.range = blockSize * 11 + self.damage = 12 + elif self.level == 3: + self.upgradeCost = None + self.bulletsPerSecond = 2 + + def shoot(self): + self.angle = math.atan2(self.y - self.target.y, self.target.x - self.x) + projectiles.append( + AngledProjectile( + self.x, + self.y, + self.damage, + self.speed, + self.angle, + self.range + blockSize / 2, + ) + ) + + class BulletShooterTower(TargetingTower): - def __init__(self,x,y,gridx,gridy): - super(BulletShooterTower,self).__init__(x,y,gridx,gridy) - self.name = "Bullet Shooter" - self.infotext = "BulletShooterTower at [" + str(gridx) + "," + str(gridy) + "]." - self.range = blockSize*6 - self.bulletsPerSecond = 4 - self.damage = 5 - self.speed = blockSize/2 - - def shoot(self): - projectiles.append(TrackingBullet(self.x , self.y, self.damage, self.speed, self.target)) + def __init__(self, x, y, gridx, gridy): + super(BulletShooterTower, self).__init__(x, y, gridx, gridy) + self.name = "Bullet Shooter" + self.infotext = "BulletShooterTower at [" + str(gridx) + "," + str(gridy) + "]." + self.range = blockSize * 6 + self.bulletsPerSecond = 4 + self.damage = 5 + self.speed = blockSize / 2 + + def shoot(self): + projectiles.append( + TrackingBullet(self.x, self.y, self.damage, self.speed, self.target) + ) + class PowerTower(TargetingTower): - def __init__(self,x,y,gridx,gridy): - super(PowerTower,self).__init__(x,y,gridx,gridy) - self.name = "Power Tower" - self.infotext = "PowerTower at [" + str(gridx) + "," + str(gridy) + "]." - self.range = blockSize*8 - self.bulletsPerSecond = 10 - self.damage = 1 - self.speed = blockSize - self.slow = 3 - - def shoot(self): - projectiles.append(PowerShot(self.x , self.y, self.damage, self.speed, self.target,self.slow)) - + def __init__(self, x, y, gridx, gridy): + super(PowerTower, self).__init__(x, y, gridx, gridy) + self.name = "Power Tower" + self.infotext = "PowerTower at [" + str(gridx) + "," + str(gridy) + "]." + self.range = blockSize * 8 + self.bulletsPerSecond = 10 + self.damage = 1 + self.speed = blockSize + self.slow = 3 + + def shoot(self): + projectiles.append( + PowerShot(self.x, self.y, self.damage, self.speed, self.target, self.slow) + ) + + class TackTower(TargetingTower): - def __init__(self,x,y,gridx,gridy): - super(TackTower,self).__init__(x,y,gridx,gridy) - self.name = "Tack Tower" - self.infotext = "TackTower at [" + str(gridx) + "," + str(gridy) + "]." - self.range = blockSize*5 - self.bulletsPerSecond = 1 - self.damage = 10 - self.speed = blockSize - - def shoot(self): - for i in range(8): - self.angle = math.radians(i*45) - projectiles.append(AngledProjectile(self.x , self.y, self.damage, self.speed, self.angle,self.range)) - - + def __init__(self, x, y, gridx, gridy): + super(TackTower, self).__init__(x, y, gridx, gridy) + self.name = "Tack Tower" + self.infotext = "TackTower at [" + str(gridx) + "," + str(gridy) + "]." + self.range = blockSize * 5 + self.bulletsPerSecond = 1 + self.damage = 10 + self.speed = blockSize + + def shoot(self): + for i in range(8): + self.angle = math.radians(i * 45) + projectiles.append( + AngledProjectile( + self.x, self.y, self.damage, self.speed, self.angle, self.range + ) + ) + + class Monster(object): - def __init__(self,distance): - self.alive = True - self.image = None - self.health = 0 - self.maxHealth = 0 - self.speed = 0.0 - self.movement = 0.0 - self.tick = 0 - self.maxTick = 1 - self.distanceTravelled = distance - if self.distanceTravelled <=0: - self.distanceTravelled = 0 - self.x,self.y = self.positionFormula(self.distanceTravelled) - self.armor = 0 - self.magicresist = 0 - self.value = 0 - self.image = Image.open("images/monsterImages/"+self.__class__.__name__+ ".png") - self.image = ImageTk.PhotoImage(self.image) - - def update(self): - if self.health <= 0: - self.killed() - self.move() - - def move(self): - if self.tick >= self.maxTick: - self.distanceTravelled += self.movement - self.x,self.y = self.positionFormula(self.distanceTravelled) - - self.movement = self.speed - self.tick = 0 - self.maxTick = 1 - self.tick+=1 - - def positionFormula(self,distance): - self.xPos = spawnx - self.yPos = spawny + blockSize/2 - self.blocks = int((distance-(distance%blockSize))/blockSize) - if self.blocks != 0: - for i in range(self.blocks): - if pathList[i] == 1: - self.xPos += blockSize - elif pathList[i] == 2: - self.xPos -= blockSize - elif pathList[i] == 3: - self.yPos += blockSize - else: - self.yPos -= blockSize - if distance%blockSize != 0: - if pathList[self.blocks] == 1: - self.xPos += (distance%blockSize) - elif pathList[self.blocks] == 2: - self.xPos -= (distance%blockSize) - elif pathList[self.blocks] == 3: - self.yPos += (distance%blockSize) - else: - self.yPos -= (distance%blockSize) - if pathList[self.blocks] == 5: - self.gotThrough() - return self.xPos,self.yPos - - def killed(self): - global money - money += self.value - self.die() - - def gotThrough(self): - global health - health -= 1 - self.die() - - def die(self): - self.alive = False - monsters.remove(self) - - def paint(self,canvas): - canvas.create_rectangle(self.x-self.axis, self.y-3*self.axis/2, self.x+self.axis-1, self.y-self.axis-1, fill="red", outline = "black") - canvas.create_rectangle(self.x-self.axis+1, self.y-3*self.axis/2 +1, self.x-self.axis+(self.axis*2-2)*self.health/self.maxHealth, self.y-self.axis-2, fill="green", outline = "green") - canvas.create_image(self.x,self.y, image = self.image, anchor = CENTER) - + def __init__(self, distance): + self.alive = True + self.image = None + self.health = 0 + self.maxHealth = 0 + self.speed = 0.0 + self.movement = 0.0 + self.tick = 0 + self.maxTick = 1 + self.distanceTravelled = distance + if self.distanceTravelled <= 0: + self.distanceTravelled = 0 + self.x, self.y = self.positionFormula(self.distanceTravelled) + self.armor = 0 + self.magicresist = 0 + self.value = 0 + self.image = Image.open( + "images/monsterImages/" + self.__class__.__name__ + ".png" + ) + self.image = ImageTk.PhotoImage(self.image) + + def update(self): + if self.health <= 0: + self.killed() + self.move() + + def move(self): + if self.tick >= self.maxTick: + self.distanceTravelled += self.movement + self.x, self.y = self.positionFormula(self.distanceTravelled) + + self.movement = self.speed + self.tick = 0 + self.maxTick = 1 + self.tick += 1 + + def positionFormula(self, distance): + self.xPos = spawnx + self.yPos = spawny + blockSize / 2 + self.blocks = int((distance - (distance % blockSize)) / blockSize) + if self.blocks != 0: + for i in range(self.blocks): + if pathList[i] == 1: + self.xPos += blockSize + elif pathList[i] == 2: + self.xPos -= blockSize + elif pathList[i] == 3: + self.yPos += blockSize + else: + self.yPos -= blockSize + if distance % blockSize != 0: + if pathList[self.blocks] == 1: + self.xPos += distance % blockSize + elif pathList[self.blocks] == 2: + self.xPos -= distance % blockSize + elif pathList[self.blocks] == 3: + self.yPos += distance % blockSize + else: + self.yPos -= distance % blockSize + if pathList[self.blocks] == 5: + self.gotThrough() + return self.xPos, self.yPos + + def killed(self): + global money + money += self.value + self.die() + + def gotThrough(self): + global health + health -= 1 + self.die() + + def die(self): + self.alive = False + monsters.remove(self) + + def paint(self, canvas): + canvas.create_rectangle( + self.x - self.axis, + self.y - 3 * self.axis / 2, + self.x + self.axis - 1, + self.y - self.axis - 1, + fill="red", + outline="black", + ) + canvas.create_rectangle( + self.x - self.axis + 1, + self.y - 3 * self.axis / 2 + 1, + self.x - self.axis + (self.axis * 2 - 2) * self.health / self.maxHealth, + self.y - self.axis - 2, + fill="green", + outline="green", + ) + canvas.create_image(self.x, self.y, image=self.image, anchor=CENTER) class Monster1(Monster): - def __init__(self,distance): - super(Monster1,self).__init__(distance) - self.maxHealth = 30 - self.health = self.maxHealth - self.value = 5 - self.speed = float(blockSize)/2 - self.movement = blockSize/3 - self.axis = blockSize/2 - + def __init__(self, distance): + super(Monster1, self).__init__(distance) + self.maxHealth = 30 + self.health = self.maxHealth + self.value = 5 + self.speed = float(blockSize) / 2 + self.movement = blockSize / 3 + self.axis = blockSize / 2 + + class Monster2(Monster): - def __init__(self,distance): - super(Monster2,self).__init__(distance) - self.maxHealth = 50 - self.health = self.maxHealth - self.value = 10 - self.speed = float(blockSize)/4 - self.movement = float(blockSize)/4 - self.axis = blockSize/2 - - def killed(self): - global money - money += self.value - monsters.append(Monster1(self.distanceTravelled + blockSize*(.5-random.random()))) - self.die() + def __init__(self, distance): + super(Monster2, self).__init__(distance) + self.maxHealth = 50 + self.health = self.maxHealth + self.value = 10 + self.speed = float(blockSize) / 4 + self.movement = float(blockSize) / 4 + self.axis = blockSize / 2 + + def killed(self): + global money + money += self.value + monsters.append( + Monster1(self.distanceTravelled + blockSize * (0.5 - random.random())) + ) + self.die() + class AlexMonster(Monster): - def __init__(self,distance): - super(AlexMonster,self).__init__(distance) - self.maxHealth = 500 - self.health = self.maxHealth - self.value = 100 - self.speed = float(blockSize)/5 - self.movement = float(blockSize)/5 - self.axis = blockSize - - def killed(self): - global money - money += self.value - for i in range(5): - monsters.append(Monster2(self.distanceTravelled + blockSize*(.5-random.random()))) - self.die() + def __init__(self, distance): + super(AlexMonster, self).__init__(distance) + self.maxHealth = 500 + self.health = self.maxHealth + self.value = 100 + self.speed = float(blockSize) / 5 + self.movement = float(blockSize) / 5 + self.axis = blockSize + + def killed(self): + global money + money += self.value + for i in range(5): + monsters.append( + Monster2(self.distanceTravelled + blockSize * (0.5 - random.random())) + ) + self.die() + class BenMonster(Monster): - def __init__(self,distance): - super(BenMonster,self).__init__(distance) - self.maxHealth = 200 - self.health = self.maxHealth - self.value = 30 - self.speed = float(blockSize)/4 - self.movement = float(blockSize)/4 - self.axis = blockSize/2 - - def killed(self): - global money - money += self.value - for i in range(2): - monsters.append(LeoMonster(self.distanceTravelled + blockSize*(.5-random.random()))) - self.die() + def __init__(self, distance): + super(BenMonster, self).__init__(distance) + self.maxHealth = 200 + self.health = self.maxHealth + self.value = 30 + self.speed = float(blockSize) / 4 + self.movement = float(blockSize) / 4 + self.axis = blockSize / 2 + + def killed(self): + global money + money += self.value + for i in range(2): + monsters.append( + LeoMonster(self.distanceTravelled + blockSize * (0.5 - random.random())) + ) + self.die() + class LeoMonster(Monster): - def __init__(self,distance): - super(LeoMonster,self).__init__(distance) - self.maxHealth = 20 - self.health = self.maxHealth - self.value = 2 - self.speed = float(blockSize)/2 - self.movement = float(blockSize)/2 - self.axis = blockSize/4 - + def __init__(self, distance): + super(LeoMonster, self).__init__(distance) + self.maxHealth = 20 + self.health = self.maxHealth + self.value = 2 + self.speed = float(blockSize) / 2 + self.movement = float(blockSize) / 2 + self.axis = blockSize / 4 + + class MonsterBig(Monster): - def __init__(self,distance): - super(MonsterBig,self).__init__(distance) - self.maxHealth = 1000 - self.health = self.maxHealth - self.value = 10 - self.speed = float(blockSize)/6 - self.movement = float(blockSize)/6 - self.axis = 3*blockSize/2 + def __init__(self, distance): + super(MonsterBig, self).__init__(distance) + self.maxHealth = 1000 + self.health = self.maxHealth + self.value = 10 + self.speed = float(blockSize) / 6 + self.movement = float(blockSize) / 6 + self.axis = 3 * blockSize / 2 + class Block(object): - def __init__(self, x, y, blockNumber,gridx,gridy): #when i define a "Block", this is what happens - self.x = x #sets Block x to the given 'x' - self.y = y #sets Block y to the given 'y' - self.canPlace = True - self.blockNumber = blockNumber - self.gridx = gridx - self.gridy = gridy - self.image = None - self.axis = blockSize/2 - - def hoveredOver(self,click,game): - if click == True: - global towerGrid - global money - if towerGrid[self.gridx][self.gridy]: - if selectedTower == "": - towerGrid[self.gridx][self.gridy].clicked = True - global displayTower - displayTower = towerGrid[self.gridx][self.gridy] - game.infoboard.displaySpecific() - elif selectedTower != "" and self.canPlace == True and money >= towerCost[selectedTower]: - self.towerType = globals()[towerDictionary[selectedTower]] - towerGrid[self.gridx][self.gridy] = self.towerType(self.x,self.y,self.gridx,self.gridy) - money -= towerCost[selectedTower] - - - def update(self): - pass - - def paint(self, draw): - self.image = Image.open("images/blockImages/"+ self.__class__.__name__+".png") - self.offset = (int(self.x - self.axis),int(self.y - self.axis)) - draw.paste(self.image, self.offset) - self.image = None + def __init__( + self, x, y, blockNumber, gridx, gridy + ): # when i define a "Block", this is what happens + self.x = x # sets Block x to the given 'x' + self.y = y # sets Block y to the given 'y' + self.canPlace = True + self.blockNumber = blockNumber + self.gridx = gridx + self.gridy = gridy + self.image = None + self.axis = blockSize / 2 + + def hoveredOver(self, click, game): + if click == True: + global towerGrid + global money + if towerGrid[self.gridx][self.gridy]: + if selectedTower == "": + towerGrid[self.gridx][self.gridy].clicked = True + global displayTower + displayTower = towerGrid[self.gridx][self.gridy] + game.infoboard.displaySpecific() + elif ( + selectedTower != "" + and self.canPlace == True + and money >= towerCost[selectedTower] + ): + self.towerType = globals()[towerDictionary[selectedTower]] + towerGrid[self.gridx][self.gridy] = self.towerType( + self.x, self.y, self.gridx, self.gridy + ) + money -= towerCost[selectedTower] + + def update(self): + pass + + def paint(self, draw): + self.image = Image.open( + "images/blockImages/" + self.__class__.__name__ + ".png" + ) + self.offset = (int(self.x - self.axis), int(self.y - self.axis)) + draw.paste(self.image, self.offset) + self.image = None + class NormalBlock(Block): - def __init__(self,x,y,blockNumber,gridx,gridy): - super(NormalBlock,self).__init__(x,y,blockNumber,gridx,gridy) + def __init__(self, x, y, blockNumber, gridx, gridy): + super(NormalBlock, self).__init__(x, y, blockNumber, gridx, gridy) + class PathBlock(Block): - def __init__(self,x,y,blockNumber,gridx,gridy): - super(PathBlock,self).__init__(x,y,blockNumber,gridx,gridy) - self.canPlace = False + def __init__(self, x, y, blockNumber, gridx, gridy): + super(PathBlock, self).__init__(x, y, blockNumber, gridx, gridy) + self.canPlace = False -class WaterBlock(Block): - def __init__(self,x,y,blockNumber,gridx,gridy): - super(WaterBlock,self).__init__(x,y,blockNumber,gridx,gridy) - self.canPlace = False - -game=Game() #start the application at Class Game() +class WaterBlock(Block): + def __init__(self, x, y, blockNumber, gridx, gridy): + super(WaterBlock, self).__init__(x, y, blockNumber, gridx, gridy) + self.canPlace = False +game = Game() # start the application at Class Game() diff --git a/2022/command_transaction_vs_state/with_state/main.py b/2022/command_transaction_vs_state/with_state/main.py index b30069e8..6a9fa14d 100644 --- a/2022/command_transaction_vs_state/with_state/main.py +++ b/2022/command_transaction_vs_state/with_state/main.py @@ -4,7 +4,6 @@ def main() -> None: - # create a bank bank = Bank() diff --git a/2022/command_transaction_vs_state/with_transaction/banking/transaction.py b/2022/command_transaction_vs_state/with_transaction/banking/transaction.py index b2600eb9..1b2361a0 100644 --- a/2022/command_transaction_vs_state/with_transaction/banking/transaction.py +++ b/2022/command_transaction_vs_state/with_transaction/banking/transaction.py @@ -2,5 +2,4 @@ class Transaction(Protocol): - def execute(self) -> None: - ... + def execute(self) -> None: ... diff --git a/2022/command_transaction_vs_state/with_transaction/main.py b/2022/command_transaction_vs_state/with_transaction/main.py index 5f0f1975..b724efd8 100644 --- a/2022/command_transaction_vs_state/with_transaction/main.py +++ b/2022/command_transaction_vs_state/with_transaction/main.py @@ -4,7 +4,6 @@ def main() -> None: - # create a bank bank = Bank() diff --git a/2022/command_with_undo/after/banking/transaction.py b/2022/command_with_undo/after/banking/transaction.py index ba42943e..489a54fa 100644 --- a/2022/command_with_undo/after/banking/transaction.py +++ b/2022/command_with_undo/after/banking/transaction.py @@ -2,11 +2,8 @@ class Transaction(Protocol): - def execute(self) -> None: - ... + def execute(self) -> None: ... - def undo(self) -> None: - ... + def undo(self) -> None: ... - def redo(self) -> None: - ... + def redo(self) -> None: ... diff --git a/2022/command_with_undo/after/main.py b/2022/command_with_undo/after/main.py index b30069e8..6a9fa14d 100644 --- a/2022/command_with_undo/after/main.py +++ b/2022/command_with_undo/after/main.py @@ -4,7 +4,6 @@ def main() -> None: - # create a bank bank = Bank() diff --git a/2022/command_with_undo/before/main.py b/2022/command_with_undo/before/main.py index 85c46a4b..b6f99c99 100644 --- a/2022/command_with_undo/before/main.py +++ b/2022/command_with_undo/before/main.py @@ -2,7 +2,6 @@ def main() -> None: - # create a bank bank = Bank() diff --git a/2022/configs/after/ds/load_data.py b/2022/configs/after/ds/load_data.py index 17161966..9e3de8b4 100644 --- a/2022/configs/after/ds/load_data.py +++ b/2022/configs/after/ds/load_data.py @@ -7,10 +7,10 @@ ALLOWED_TYPES = { "UNSIGNED_BYTE": b"\x08", "SIGNED_BYTE": b"\x09", - "SHORT": b"\x0B", - "INT": b"\x0C", - "SINGLE": b"\x0D", - "DOUBLE": b"\x0E", + "SHORT": b"\x0b", + "INT": b"\x0c", + "SINGLE": b"\x0d", + "DOUBLE": b"\x0e", } diff --git a/2022/configs/after/ds/tensorboard.py b/2022/configs/after/ds/tensorboard.py index 340a2f84..db201ecc 100644 --- a/2022/configs/after/ds/tensorboard.py +++ b/2022/configs/after/ds/tensorboard.py @@ -11,7 +11,6 @@ class TensorboardExperiment: def __init__(self, log_path: str, create: bool = True): - log_dir = create_experiment_log_dir(root=log_path) self.stage = Stage.TRAIN self._validate_log_dir(log_dir, create=create) diff --git a/2022/configs/after/ds/utils.py b/2022/configs/after/ds/utils.py index 35a29432..81084958 100644 --- a/2022/configs/after/ds/utils.py +++ b/2022/configs/after/ds/utils.py @@ -18,8 +18,7 @@ def create_from_missing(root: pathlib.Path) -> pathlib.Path: def create_from_existing(root: pathlib.Path) -> pathlib.Path: children = [ - int(c.name) for c in root.glob("*") - if (c.is_dir() and c.name.isnumeric()) + int(c.name) for c in root.glob("*") if (c.is_dir() and c.name.isnumeric()) ] if is_first_experiment(children): child = create_from_missing(root) diff --git a/2022/configs/after/parse_raw_data.py b/2022/configs/after/parse_raw_data.py index 571ca51e..756a7300 100644 --- a/2022/configs/after/parse_raw_data.py +++ b/2022/configs/after/parse_raw_data.py @@ -15,7 +15,7 @@ TRAIN_DATA_RAW = pathlib.Path(f"{RAW_DATA}/train-images-idx3-ubyte.gz") TRAIN_LABELS_RAW = pathlib.Path(f"{RAW_DATA}/train-labels-idx1-ubyte.gz") -PROCESSED_DATA = './data/processed' +PROCESSED_DATA = "./data/processed" TEST_DIR_PROCESSED = pathlib.Path(f"{PROCESSED_DATA}/test") TRAIN_DIR_PROCESSED = pathlib.Path(f"{PROCESSED_DATA}/tain") @@ -25,12 +25,12 @@ def main(): make_tree(TEST_DIR_PROCESSED, reset=True) save_dataset_to_png( - TRAIN_DIR_PROCESSED, - zip(load_image_data(TRAIN_DATA_RAW), load_label_data(TRAIN_LABELS_RAW)) + TRAIN_DIR_PROCESSED, + zip(load_image_data(TRAIN_DATA_RAW), load_label_data(TRAIN_LABELS_RAW)), ) save_dataset_to_png( - TEST_DIR_PROCESSED, - zip(load_image_data(TEST_DATA_RAW), load_label_data(TEST_LABELS_RAW)) + TEST_DIR_PROCESSED, + zip(load_image_data(TEST_DATA_RAW), load_label_data(TEST_LABELS_RAW)), ) @@ -44,7 +44,7 @@ def make_tree(root: pathlib.Path, reset: bool = False) -> None: def reset_tree(root: pathlib.Path) -> None: - print('Resetting tree.') + print("Resetting tree.") shutil.rmtree(root, ignore_errors=True) @@ -59,8 +59,8 @@ def save_xy_to_png( root: pathlib.Path, xy: Tuple[np.ndarray, np.ndarray], name: str ) -> None: x, y = xy - Image.fromarray(x).save(root / str(int(y)) / f'{name}.jpg') + Image.fromarray(x).save(root / str(int(y)) / f"{name}.jpg") -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/2022/configs/before/ds/load_data.py b/2022/configs/before/ds/load_data.py index 17161966..9e3de8b4 100644 --- a/2022/configs/before/ds/load_data.py +++ b/2022/configs/before/ds/load_data.py @@ -7,10 +7,10 @@ ALLOWED_TYPES = { "UNSIGNED_BYTE": b"\x08", "SIGNED_BYTE": b"\x09", - "SHORT": b"\x0B", - "INT": b"\x0C", - "SINGLE": b"\x0D", - "DOUBLE": b"\x0E", + "SHORT": b"\x0b", + "INT": b"\x0c", + "SINGLE": b"\x0d", + "DOUBLE": b"\x0e", } diff --git a/2022/configs/before/ds/tensorboard.py b/2022/configs/before/ds/tensorboard.py index 340a2f84..db201ecc 100644 --- a/2022/configs/before/ds/tensorboard.py +++ b/2022/configs/before/ds/tensorboard.py @@ -11,7 +11,6 @@ class TensorboardExperiment: def __init__(self, log_path: str, create: bool = True): - log_dir = create_experiment_log_dir(root=log_path) self.stage = Stage.TRAIN self._validate_log_dir(log_dir, create=create) diff --git a/2022/configs/before/ds/utils.py b/2022/configs/before/ds/utils.py index 35a29432..81084958 100644 --- a/2022/configs/before/ds/utils.py +++ b/2022/configs/before/ds/utils.py @@ -18,8 +18,7 @@ def create_from_missing(root: pathlib.Path) -> pathlib.Path: def create_from_existing(root: pathlib.Path) -> pathlib.Path: children = [ - int(c.name) for c in root.glob("*") - if (c.is_dir() and c.name.isnumeric()) + int(c.name) for c in root.glob("*") if (c.is_dir() and c.name.isnumeric()) ] if is_first_experiment(children): child = create_from_missing(root) diff --git a/2022/configs/before/main.py b/2022/configs/before/main.py index db83b316..05dce4c2 100644 --- a/2022/configs/before/main.py +++ b/2022/configs/before/main.py @@ -22,7 +22,6 @@ def main(): - # Model and Optimizer model = LinearNet() optimizer = torch.optim.Adam(model.parameters(), lr=LR) diff --git a/2022/configs/before/parse_raw_data.py b/2022/configs/before/parse_raw_data.py index 571ca51e..756a7300 100644 --- a/2022/configs/before/parse_raw_data.py +++ b/2022/configs/before/parse_raw_data.py @@ -15,7 +15,7 @@ TRAIN_DATA_RAW = pathlib.Path(f"{RAW_DATA}/train-images-idx3-ubyte.gz") TRAIN_LABELS_RAW = pathlib.Path(f"{RAW_DATA}/train-labels-idx1-ubyte.gz") -PROCESSED_DATA = './data/processed' +PROCESSED_DATA = "./data/processed" TEST_DIR_PROCESSED = pathlib.Path(f"{PROCESSED_DATA}/test") TRAIN_DIR_PROCESSED = pathlib.Path(f"{PROCESSED_DATA}/tain") @@ -25,12 +25,12 @@ def main(): make_tree(TEST_DIR_PROCESSED, reset=True) save_dataset_to_png( - TRAIN_DIR_PROCESSED, - zip(load_image_data(TRAIN_DATA_RAW), load_label_data(TRAIN_LABELS_RAW)) + TRAIN_DIR_PROCESSED, + zip(load_image_data(TRAIN_DATA_RAW), load_label_data(TRAIN_LABELS_RAW)), ) save_dataset_to_png( - TEST_DIR_PROCESSED, - zip(load_image_data(TEST_DATA_RAW), load_label_data(TEST_LABELS_RAW)) + TEST_DIR_PROCESSED, + zip(load_image_data(TEST_DATA_RAW), load_label_data(TEST_LABELS_RAW)), ) @@ -44,7 +44,7 @@ def make_tree(root: pathlib.Path, reset: bool = False) -> None: def reset_tree(root: pathlib.Path) -> None: - print('Resetting tree.') + print("Resetting tree.") shutil.rmtree(root, ignore_errors=True) @@ -59,8 +59,8 @@ def save_xy_to_png( root: pathlib.Path, xy: Tuple[np.ndarray, np.ndarray], name: str ) -> None: x, y = xy - Image.fromarray(x).save(root / str(int(y)) / f'{name}.jpg') + Image.fromarray(x).save(root / str(int(y)) / f"{name}.jpg") -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/2022/configs/before/plot.py b/2022/configs/before/plot.py index 4cf97530..ef81ab0c 100644 --- a/2022/configs/before/plot.py +++ b/2022/configs/before/plot.py @@ -24,17 +24,17 @@ def main(dataset: str) -> None: def load(dataset: str) -> Tuple[np.ndarray, np.ndarray]: dataset = { - 'train': { - 'data': TRAIN_DATA, - 'labels': TRAIN_LABELS, + "train": { + "data": TRAIN_DATA, + "labels": TRAIN_LABELS, + }, + "test": { + "data": TEST_DATA, + "labels": TEST_LABELS, }, - 'test': { - 'data': TEST_DATA, - 'labels': TEST_LABELS, - } }[dataset] - data = load_image_data(dataset['data']) - labels = load_label_data(dataset['labels']) + data = load_image_data(dataset["data"]) + labels = load_label_data(dataset["labels"]) return data, labels @@ -56,15 +56,15 @@ def plot( axes = axes.flatten() for ax in axes: - ax.imshow(next(data), cmap='Greys') - ax.text(1, 5, str(next(labels)), color='red', fontsize=15) + ax.imshow(next(data), cmap="Greys") + ax.text(1, 5, str(next(labels)), color="red", fontsize=15) ax.set_xticks([]) ax.set_yticks([]) - fig.suptitle(f'Dataset: {dataset}') + fig.suptitle(f"Dataset: {dataset}") plt.subplots_adjust(wspace=0, hspace=0) plt.show() -if __name__ == '__main__': - main(dataset='train') # 'train' or 'test' +if __name__ == "__main__": + main(dataset="train") # 'train' or 'test' diff --git a/2022/context_manager/create_db.py b/2022/context_manager/create_db.py index c12cec20..20f33fe7 100644 --- a/2022/context_manager/create_db.py +++ b/2022/context_manager/create_db.py @@ -1,19 +1,24 @@ import sqlite3 -con = sqlite3.connect('application.db') + +con = sqlite3.connect("application.db") cur = con.cursor() # Create table -cur.execute('''CREATE TABLE blogs - (id text not null primary key, date text, title text, content text, public integer)''') +cur.execute("""CREATE TABLE blogs + (id text not null primary key, date text, title text, content text, public integer)""") # Insert a few rows of data -cur.execute("INSERT INTO blogs VALUES ('first-blog', '2021-03-07', 'My first blog' ,'Some content', 1)") -cur.execute("INSERT INTO blogs VALUES ('private-blog', '2021-03-07', 'Secret blog' ,'This is a secret', 0)") +cur.execute( + "INSERT INTO blogs VALUES ('first-blog', '2021-03-07', 'My first blog' ,'Some content', 1)" +) +cur.execute( + "INSERT INTO blogs VALUES ('private-blog', '2021-03-07', 'Secret blog' ,'This is a secret', 0)" +) # Save (commit) the changes con.commit() # We can also close the connection if we are done with it. # Just be sure any changes have been committed or they will be lost. -con.close() \ No newline at end of file +con.close() diff --git a/2022/coupling/Introduce_abstraction.py b/2022/coupling/Introduce_abstraction.py index 2384f371..26597c15 100644 --- a/2022/coupling/Introduce_abstraction.py +++ b/2022/coupling/Introduce_abstraction.py @@ -9,23 +9,17 @@ class EmailServer(Protocol): @property - def _host(self) -> str: - ... + def _host(self) -> str: ... - def connect(self, host: str, port: int) -> None: - ... + def connect(self, host: str, port: int) -> None: ... - def starttls(self) -> None: - ... + def starttls(self) -> None: ... - def login(self, login: str, password: str) -> None: - ... + def login(self, login: str, password: str) -> None: ... - def quit(self) -> None: - ... + def quit(self) -> None: ... - def sendmail(self, from_address: str, to_address: str, message: str) -> None: - ... + def sendmail(self, from_address: str, to_address: str, message: str) -> None: ... class EmailClient: diff --git a/2022/coupling/intimacy_after.py b/2022/coupling/intimacy_after.py index d593dfa9..c9d6c25c 100644 --- a/2022/coupling/intimacy_after.py +++ b/2022/coupling/intimacy_after.py @@ -27,14 +27,14 @@ def generate_breadcrumbs(geolocation: Geolocation) -> dict[str, str]: breadcrumbs: dict[str, str] = {} main_url = "https://myapi.com" if geolocation.postal_code: - breadcrumbs[ - "postal_code_url" - ] = f"{main_url}/postal_code/{geolocation.postal_code}/" + breadcrumbs["postal_code_url"] = ( + f"{main_url}/postal_code/{geolocation.postal_code}/" + ) if geolocation.city: city_slug = geolocation.city.lower().replace(" ", "-") breadcrumbs["city_url"] = f"{main_url}/region/{city_slug}/" if geolocation.province: - breadcrumbs[ - "province_url" - ] = f"{main_url}/region/province/{geolocation.province.lower()}/" + breadcrumbs["province_url"] = ( + f"{main_url}/region/province/{geolocation.province.lower()}/" + ) return breadcrumbs diff --git a/2022/coupling/intimacy_before.py b/2022/coupling/intimacy_before.py index 4b55b1ce..cc825177 100644 --- a/2022/coupling/intimacy_before.py +++ b/2022/coupling/intimacy_before.py @@ -28,14 +28,14 @@ def generate_breadcrumbs(location: Location) -> dict[str, str]: main_url = "https://myapi.com" if location.geolocation[0]: if location.geolocation[0].postal_code: - breadcrumbs[ - "postal_code_url" - ] = f"{main_url}/postal_code/{location.geolocation[0].postal_code}/" + breadcrumbs["postal_code_url"] = ( + f"{main_url}/postal_code/{location.geolocation[0].postal_code}/" + ) if location.geolocation[0].city: city_slug = location.geolocation[0].city.lower().replace(" ", "-") breadcrumbs["city_url"] = f"{main_url}/region/{city_slug}/" if location.geolocation[0].province: - breadcrumbs[ - "province_url" - ] = f"{main_url}/region/province/{location.geolocation[0].province.lower()}/" + breadcrumbs["province_url"] = ( + f"{main_url}/region/province/{location.geolocation[0].province.lower()}/" + ) return breadcrumbs diff --git a/2022/dash_tutorial/part2/main.py b/2022/dash_tutorial/part2/main.py index 08f5b324..fa495863 100644 --- a/2022/dash_tutorial/part2/main.py +++ b/2022/dash_tutorial/part2/main.py @@ -8,7 +8,6 @@ def main() -> None: - # load the data and create the data manager data = load_transaction_data(DATA_PATH) diff --git a/2022/dash_tutorial/part3/main.py b/2022/dash_tutorial/part3/main.py index 06aa2f69..0ad7caa5 100644 --- a/2022/dash_tutorial/part3/main.py +++ b/2022/dash_tutorial/part3/main.py @@ -11,7 +11,6 @@ def main() -> None: - # set the locale and load the translations i18n.set("locale", LOCALE) i18n.load_path.append("locale") diff --git a/2022/datascience_tips/after/ds/load_data.py b/2022/datascience_tips/after/ds/load_data.py index 17161966..9e3de8b4 100644 --- a/2022/datascience_tips/after/ds/load_data.py +++ b/2022/datascience_tips/after/ds/load_data.py @@ -7,10 +7,10 @@ ALLOWED_TYPES = { "UNSIGNED_BYTE": b"\x08", "SIGNED_BYTE": b"\x09", - "SHORT": b"\x0B", - "INT": b"\x0C", - "SINGLE": b"\x0D", - "DOUBLE": b"\x0E", + "SHORT": b"\x0b", + "INT": b"\x0c", + "SINGLE": b"\x0d", + "DOUBLE": b"\x0e", } diff --git a/2022/datascience_tips/after/ds/tensorboard.py b/2022/datascience_tips/after/ds/tensorboard.py index 340a2f84..db201ecc 100644 --- a/2022/datascience_tips/after/ds/tensorboard.py +++ b/2022/datascience_tips/after/ds/tensorboard.py @@ -11,7 +11,6 @@ class TensorboardExperiment: def __init__(self, log_path: str, create: bool = True): - log_dir = create_experiment_log_dir(root=log_path) self.stage = Stage.TRAIN self._validate_log_dir(log_dir, create=create) diff --git a/2022/datascience_tips/after/ds/utils.py b/2022/datascience_tips/after/ds/utils.py index 35a29432..81084958 100644 --- a/2022/datascience_tips/after/ds/utils.py +++ b/2022/datascience_tips/after/ds/utils.py @@ -18,8 +18,7 @@ def create_from_missing(root: pathlib.Path) -> pathlib.Path: def create_from_existing(root: pathlib.Path) -> pathlib.Path: children = [ - int(c.name) for c in root.glob("*") - if (c.is_dir() and c.name.isnumeric()) + int(c.name) for c in root.glob("*") if (c.is_dir() and c.name.isnumeric()) ] if is_first_experiment(children): child = create_from_missing(root) diff --git a/2022/datascience_tips/after/main.py b/2022/datascience_tips/after/main.py index 48ca69a8..56c5ed21 100644 --- a/2022/datascience_tips/after/main.py +++ b/2022/datascience_tips/after/main.py @@ -22,7 +22,6 @@ def main(): - # Model and Optimizer model = LinearNet() optimizer = torch.optim.Adam(model.parameters(), lr=LR) diff --git a/2022/datascience_tips/after/parse_raw_data.py b/2022/datascience_tips/after/parse_raw_data.py index 571ca51e..756a7300 100644 --- a/2022/datascience_tips/after/parse_raw_data.py +++ b/2022/datascience_tips/after/parse_raw_data.py @@ -15,7 +15,7 @@ TRAIN_DATA_RAW = pathlib.Path(f"{RAW_DATA}/train-images-idx3-ubyte.gz") TRAIN_LABELS_RAW = pathlib.Path(f"{RAW_DATA}/train-labels-idx1-ubyte.gz") -PROCESSED_DATA = './data/processed' +PROCESSED_DATA = "./data/processed" TEST_DIR_PROCESSED = pathlib.Path(f"{PROCESSED_DATA}/test") TRAIN_DIR_PROCESSED = pathlib.Path(f"{PROCESSED_DATA}/tain") @@ -25,12 +25,12 @@ def main(): make_tree(TEST_DIR_PROCESSED, reset=True) save_dataset_to_png( - TRAIN_DIR_PROCESSED, - zip(load_image_data(TRAIN_DATA_RAW), load_label_data(TRAIN_LABELS_RAW)) + TRAIN_DIR_PROCESSED, + zip(load_image_data(TRAIN_DATA_RAW), load_label_data(TRAIN_LABELS_RAW)), ) save_dataset_to_png( - TEST_DIR_PROCESSED, - zip(load_image_data(TEST_DATA_RAW), load_label_data(TEST_LABELS_RAW)) + TEST_DIR_PROCESSED, + zip(load_image_data(TEST_DATA_RAW), load_label_data(TEST_LABELS_RAW)), ) @@ -44,7 +44,7 @@ def make_tree(root: pathlib.Path, reset: bool = False) -> None: def reset_tree(root: pathlib.Path) -> None: - print('Resetting tree.') + print("Resetting tree.") shutil.rmtree(root, ignore_errors=True) @@ -59,8 +59,8 @@ def save_xy_to_png( root: pathlib.Path, xy: Tuple[np.ndarray, np.ndarray], name: str ) -> None: x, y = xy - Image.fromarray(x).save(root / str(int(y)) / f'{name}.jpg') + Image.fromarray(x).save(root / str(int(y)) / f"{name}.jpg") -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/2022/datascience_tips/after/plot.py b/2022/datascience_tips/after/plot.py index 4cf97530..ef81ab0c 100644 --- a/2022/datascience_tips/after/plot.py +++ b/2022/datascience_tips/after/plot.py @@ -24,17 +24,17 @@ def main(dataset: str) -> None: def load(dataset: str) -> Tuple[np.ndarray, np.ndarray]: dataset = { - 'train': { - 'data': TRAIN_DATA, - 'labels': TRAIN_LABELS, + "train": { + "data": TRAIN_DATA, + "labels": TRAIN_LABELS, + }, + "test": { + "data": TEST_DATA, + "labels": TEST_LABELS, }, - 'test': { - 'data': TEST_DATA, - 'labels': TEST_LABELS, - } }[dataset] - data = load_image_data(dataset['data']) - labels = load_label_data(dataset['labels']) + data = load_image_data(dataset["data"]) + labels = load_label_data(dataset["labels"]) return data, labels @@ -56,15 +56,15 @@ def plot( axes = axes.flatten() for ax in axes: - ax.imshow(next(data), cmap='Greys') - ax.text(1, 5, str(next(labels)), color='red', fontsize=15) + ax.imshow(next(data), cmap="Greys") + ax.text(1, 5, str(next(labels)), color="red", fontsize=15) ax.set_xticks([]) ax.set_yticks([]) - fig.suptitle(f'Dataset: {dataset}') + fig.suptitle(f"Dataset: {dataset}") plt.subplots_adjust(wspace=0, hspace=0) plt.show() -if __name__ == '__main__': - main(dataset='train') # 'train' or 'test' +if __name__ == "__main__": + main(dataset="train") # 'train' or 'test' diff --git a/2022/datascience_tips/before/main.py b/2022/datascience_tips/before/main.py index e1e2b476..ecad527e 100644 --- a/2022/datascience_tips/before/main.py +++ b/2022/datascience_tips/before/main.py @@ -10,23 +10,18 @@ from src.utils import generate_tensorboard_experiment_directory # Hyperparameters -hparams = { - 'EPOCHS': 20, - 'LR': 5e-5, - 'OPTIMIZER': 'Adam', - 'BATCH_SIZE': 128 -} +hparams = {"EPOCHS": 20, "LR": 5e-5, "OPTIMIZER": "Adam", "BATCH_SIZE": 128} # Data -train_loader = get_train_dataloader(batch_size=hparams.get('BATCH_SIZE')) -test_loader = get_test_dataloader(batch_size=hparams.get('BATCH_SIZE')) +train_loader = get_train_dataloader(batch_size=hparams.get("BATCH_SIZE")) +test_loader = get_test_dataloader(batch_size=hparams.get("BATCH_SIZE")) # Model and Optimizer model = LinearNet() -optimizer = torch.optim.Adam(model.parameters(), lr=hparams.get('LR')) +optimizer = torch.optim.Adam(model.parameters(), lr=hparams.get("LR")) # Objective (loss) function -compute_loss = torch.nn.CrossEntropyLoss(reduction='mean') +compute_loss = torch.nn.CrossEntropyLoss(reduction="mean") # Metric Containers train_accuracy = Metric() @@ -35,16 +30,16 @@ y_pred_batches = [] # Experiment Trackers -log_dir = generate_tensorboard_experiment_directory(root='./runs') +log_dir = generate_tensorboard_experiment_directory(root="./runs") experiment = TensorboardExperiment(log_dir=log_dir) # Batch Counters test_batch = 0 train_batch = 0 -for epoch in range(hparams.get('EPOCHS')): +for epoch in range(hparams.get("EPOCHS")): # Testing Loop - for x_test, y_test in tqdm(test_loader, desc='Validation Batches', ncols=80): + for x_test, y_test in tqdm(test_loader, desc="Validation Batches", ncols=80): test_batch += 1 test_batch_size = x_test.shape[0] test_pred = model(x_test) @@ -56,12 +51,12 @@ batch_test_accuracy = accuracy_score(y_test_np, y_test_pred_np) test_accuracy.update(batch_test_accuracy, test_batch_size) experiment.set_stage(Stage.VAL) - experiment.add_batch_metric('accuracy', batch_test_accuracy, test_batch) + experiment.add_batch_metric("accuracy", batch_test_accuracy, test_batch) y_true_batches += [y_test_np] y_pred_batches += [y_test_pred_np] # Training Loop - for x_train, y_train in tqdm(train_loader, desc='Train Batches', ncols=80): + for x_train, y_train in tqdm(train_loader, desc="Train Batches", ncols=80): train_batch += 1 train_batch_size = x_train.shape[0] train_pred = model(x_train) @@ -73,7 +68,7 @@ batch_train_accuracy = accuracy_score(y_train_np, y_train_pred_np) train_accuracy.update(batch_train_accuracy, train_batch_size) experiment.set_stage(Stage.TRAIN) - experiment.add_batch_metric('accuracy', batch_train_accuracy, train_batch) + experiment.add_batch_metric("accuracy", batch_train_accuracy, train_batch) # Reverse-mode AutoDiff (backpropagation) optimizer.zero_grad() @@ -81,21 +76,23 @@ optimizer.step() # Compute Average Epoch Metrics - summary = ', '.join([ - f"[Epoch: {epoch + 1}/{hparams.get('EPOCHS')}]", - f"Test Accuracy: {test_accuracy.average: 0.4f}", - f"Train Accuracy: {train_accuracy.average: 0.4f}", - ]) - print('\n' + summary + '\n') + summary = ", ".join( + [ + f"[Epoch: {epoch + 1}/{hparams.get('EPOCHS')}]", + f"Test Accuracy: {test_accuracy.average: 0.4f}", + f"Train Accuracy: {train_accuracy.average: 0.4f}", + ] + ) + print("\n" + summary + "\n") # Log Validation Epoch Metrics experiment.set_stage(Stage.VAL) - experiment.add_epoch_metric('accuracy', test_accuracy.average, epoch) + experiment.add_epoch_metric("accuracy", test_accuracy.average, epoch) experiment.add_epoch_confusion_matrix(y_true_batches, y_pred_batches, epoch) # Log Validation Epoch Metrics experiment.set_stage(Stage.TRAIN) - experiment.add_epoch_metric('accuracy', train_accuracy.average, epoch) + experiment.add_epoch_metric("accuracy", train_accuracy.average, epoch) # Reset metrics train_accuracy.reset() diff --git a/2022/datascience_tips/before/src/dataset.py b/2022/datascience_tips/before/src/dataset.py index ef0c5e26..c93790e6 100644 --- a/2022/datascience_tips/before/src/dataset.py +++ b/2022/datascience_tips/before/src/dataset.py @@ -2,7 +2,12 @@ import torch from torch.utils.data import Dataset, DataLoader -from src.load_data import load_train_labels, load_train_data, load_test_data, load_test_labels +from src.load_data import ( + load_train_labels, + load_train_data, + load_test_data, + load_test_labels, +) class MNIST(Dataset): @@ -16,8 +21,10 @@ class MNIST(Dataset): def __init__(self, data: np.ndarray, targets: np.ndarray): if len(data) != len(targets): - raise ValueError('data and targets must be the same length. ' - f'{len(data)} != {len(targets)}') + raise ValueError( + "data and targets must be the same length. " + f"{len(data)} != {len(targets)}" + ) self.data = data self.targets = targets diff --git a/2022/datascience_tips/before/src/load_data.py b/2022/datascience_tips/before/src/load_data.py index 72715764..d2306333 100644 --- a/2022/datascience_tips/before/src/load_data.py +++ b/2022/datascience_tips/before/src/load_data.py @@ -9,10 +9,10 @@ ALLOWED_TYPES = { "UNSIGNED_BYTE": b"\x08", "SIGNED_BYTE": b"\x09", - "SHORT": b"\x0B", - "INT": b"\x0C", - "SINGLE": b"\x0D", - "DOUBLE": b"\x0E", + "SHORT": b"\x0b", + "INT": b"\x0c", + "SINGLE": b"\x0d", + "DOUBLE": b"\x0e", } diff --git a/2022/datascience_tips/before/src/tracking.py b/2022/datascience_tips/before/src/tracking.py index 5681bc7b..f480cbc6 100644 --- a/2022/datascience_tips/before/src/tracking.py +++ b/2022/datascience_tips/before/src/tracking.py @@ -12,9 +12,9 @@ @dataclass(frozen=True) class Stage: - TRAIN: str = 'train' - TEST: str = 'test' - VAL: str = 'val' + TRAIN: str = "train" + TEST: str = "test" + VAL: str = "val" class ExperimentTracker(ABC): @@ -33,7 +33,9 @@ def add_epoch_confusion_matrix(self, y_true: np.array, y_pred: np.array, step: i """Implements logging a confusion matrix at epoch-level.""" @abstractmethod - def add_hparams(self, hparams: dict[str, Union[str, Real]], metrics: dict[str, Real]): + def add_hparams( + self, hparams: dict[str, Union[str, Real]], metrics: dict[str, Real] + ): """Implements logging hyperparameters.""" def add_batch_metrics(self, values: dict[str, Real], step: int): @@ -46,7 +48,6 @@ def add_epoch_metrics(self, values: dict[str, Real], step: int): class TensorboardExperiment(ExperimentTracker): - def __init__(self, log_dir: str, create=True): self._validate_log_dir(log_dir, create=create) self._writer = SummaryWriter(log_dir=log_dir) @@ -67,43 +68,51 @@ def _validate_log_dir(log_dir, create=True): elif not log_dir.exists() and create: log_dir.mkdir(parents=True) else: - raise NotADirectoryError(f'log_dir {log_dir} does not exist.') + raise NotADirectoryError(f"log_dir {log_dir} does not exist.") def add_batch_metric(self, name: str, value: Real, step: int): - tag = f'{self.stage}/batch/{name}' + tag = f"{self.stage}/batch/{name}" self._writer.add_scalar(tag, value, step) def add_epoch_metric(self, name: str, value: Real, step: int): - tag = f'{self.stage}/epoch/{name}' + tag = f"{self.stage}/epoch/{name}" self._writer.add_scalar(tag, value, step) - def add_epoch_confusion_matrix(self, y_true: list[np.array], y_pred: list[np.array], step: int): + def add_epoch_confusion_matrix( + self, y_true: list[np.array], y_pred: list[np.array], step: int + ): y_true, y_pred = self.collapse_batches(y_true, y_pred) fig = self.create_confusion_matrix(y_true, y_pred, step) - tag = f'{self.stage}/epoch/confusion_matrix' + tag = f"{self.stage}/epoch/confusion_matrix" self._writer.add_figure(tag, fig, step) @staticmethod - def collapse_batches(y_true: list[np.array], y_pred: list[np.array]) -> Tuple[np.ndarray, np.ndarray]: + def collapse_batches( + y_true: list[np.array], y_pred: list[np.array] + ) -> Tuple[np.ndarray, np.ndarray]: return np.concatenate(y_true), np.concatenate(y_pred) - def create_confusion_matrix(self, y_true: np.array, y_pred: np.array, step: int) -> plt.Figure: - cm = ConfusionMatrixDisplay(confusion_matrix(y_true, y_pred)).plot(cmap='Blues') + def create_confusion_matrix( + self, y_true: np.array, y_pred: np.array, step: int + ) -> plt.Figure: + cm = ConfusionMatrixDisplay(confusion_matrix(y_true, y_pred)).plot(cmap="Blues") fig: plt.Figure = cm.figure_ ax: plt.Axes = cm.ax_ - ax.set_title(f'{self.stage.title()} Epoch: {step}') + ax.set_title(f"{self.stage.title()} Epoch: {step}") return fig - def add_hparams(self, hparams: dict[str, Union[str, Real]], metrics: dict[str, Real]): + def add_hparams( + self, hparams: dict[str, Union[str, Real]], metrics: dict[str, Real] + ): _metrics = self._validate_hparam_metric_keys(metrics) self._writer.add_hparams(hparams, _metrics) @staticmethod def _validate_hparam_metric_keys(metrics): _metrics = metrics.copy() - prefix = 'hparam/' + prefix = "hparam/" for name in _metrics.keys(): if not name.startswith(prefix): - _metrics[f'{prefix}{name}'] = _metrics[name] + _metrics[f"{prefix}{name}"] = _metrics[name] del _metrics[name] return _metrics diff --git a/2022/datascience_tips/before/src/utils.py b/2022/datascience_tips/before/src/utils.py index 2768ecc4..d74d90ab 100644 --- a/2022/datascience_tips/before/src/utils.py +++ b/2022/datascience_tips/before/src/utils.py @@ -3,19 +3,23 @@ def generate_tensorboard_experiment_directory(root: str, parents=True) -> str: root = Path(root).resolve() - child = create_from_missing(root) if not root.exists() else create_from_existing(root) + child = ( + create_from_missing(root) if not root.exists() else create_from_existing(root) + ) child.mkdir(parents=parents) return child.as_posix() def create_from_missing(root): - return root / '0' + return root / "0" def create_from_existing(root): - children = [int(c.name) for c in root.glob('*') if (c.is_dir() and c.name.isnumeric())] + children = [ + int(c.name) for c in root.glob("*") if (c.is_dir() and c.name.isnumeric()) + ] if is_first_experiment(children): - child = root / '0' + child = root / "0" else: child = root / increment_experiment_number(children) return child diff --git a/2022/datascience_tips/compose_example.py b/2022/datascience_tips/compose_example.py index 8fb42f03..3427b514 100644 --- a/2022/datascience_tips/compose_example.py +++ b/2022/datascience_tips/compose_example.py @@ -3,6 +3,7 @@ ComposableFunction = Callable[[float], float] + # Helper function for composing functions def compose(*functions: ComposableFunction) -> ComposableFunction: return functools.reduce(lambda f, g: lambda x: g(f(x)), functions) diff --git a/2022/datetime/pendulum_example.py b/2022/datetime/pendulum_example.py index a050d3da..c622ba8e 100644 --- a/2022/datetime/pendulum_example.py +++ b/2022/datetime/pendulum_example.py @@ -2,7 +2,6 @@ def main() -> None: - # Pendulum dates are timezone aware by default some_date = pendulum.datetime(2022, 10, 9, 18, 0, tz="UTC") print(some_date) diff --git a/2022/even_more_code_smells/after/pos/system.py b/2022/even_more_code_smells/after/pos/system.py index 0742928d..ad9e85d5 100644 --- a/2022/even_more_code_smells/after/pos/system.py +++ b/2022/even_more_code_smells/after/pos/system.py @@ -11,8 +11,7 @@ def generate_id(length: int = 6) -> str: class PaymentProcessor(Protocol): - def process_payment(self, reference: str, price: int) -> None: - ... + def process_payment(self, reference: str, price: int) -> None: ... class POSSystem: diff --git a/2022/even_more_code_smells/before/pos/payment.py b/2022/even_more_code_smells/before/pos/payment.py index d97cbe42..0f15e6f0 100644 --- a/2022/even_more_code_smells/before/pos/payment.py +++ b/2022/even_more_code_smells/before/pos/payment.py @@ -8,11 +8,9 @@ class PaymentServiceConnectionError(Exception): class OrderRepository(Protocol): - def find_order(self, order_id: str) -> Order: - ... + def find_order(self, order_id: str) -> Order: ... - def compute_order_total_price(self, order: Order) -> int: - ... + def compute_order_total_price(self, order: Order) -> int: ... class StripePaymentProcessor: diff --git a/2022/f_strings/main.py b/2022/f_strings/main.py index 8c2dd531..adc93fc1 100644 --- a/2022/f_strings/main.py +++ b/2022/f_strings/main.py @@ -12,7 +12,6 @@ def __str__(self): def main(): - ############################ # Number formatting ############################ diff --git a/2022/facade/before/iot/service.py b/2022/facade/before/iot/service.py index 14ee55e9..cd1a6818 100644 --- a/2022/facade/before/iot/service.py +++ b/2022/facade/before/iot/service.py @@ -8,17 +8,13 @@ def generate_id(length: int = 8): class Device(Protocol): - def connect(self) -> None: - ... + def connect(self) -> None: ... - def disconnect(self) -> None: - ... + def disconnect(self) -> None: ... - def connection_info(self) -> tuple[str, int]: - ... + def connection_info(self) -> tuple[str, int]: ... - def status_update(self) -> str: - ... + def status_update(self) -> str: ... class IOTService: diff --git a/2022/facade/with_controller/iot/service.py b/2022/facade/with_controller/iot/service.py index 14ee55e9..cd1a6818 100644 --- a/2022/facade/with_controller/iot/service.py +++ b/2022/facade/with_controller/iot/service.py @@ -8,17 +8,13 @@ def generate_id(length: int = 8): class Device(Protocol): - def connect(self) -> None: - ... + def connect(self) -> None: ... - def disconnect(self) -> None: - ... + def disconnect(self) -> None: ... - def connection_info(self) -> tuple[str, int]: - ... + def connection_info(self) -> tuple[str, int]: ... - def status_update(self) -> str: - ... + def status_update(self) -> str: ... class IOTService: diff --git a/2022/facade/with_facade/iot/service.py b/2022/facade/with_facade/iot/service.py index 14ee55e9..cd1a6818 100644 --- a/2022/facade/with_facade/iot/service.py +++ b/2022/facade/with_facade/iot/service.py @@ -8,17 +8,13 @@ def generate_id(length: int = 8): class Device(Protocol): - def connect(self) -> None: - ... + def connect(self) -> None: ... - def disconnect(self) -> None: - ... + def disconnect(self) -> None: ... - def connection_info(self) -> tuple[str, int]: - ... + def connection_info(self) -> tuple[str, int]: ... - def status_update(self) -> str: - ... + def status_update(self) -> str: ... class IOTService: diff --git a/2022/facade/with_facade/iot_controller.py b/2022/facade/with_facade/iot_controller.py index ee327f0b..3fdb04ea 100644 --- a/2022/facade/with_facade/iot_controller.py +++ b/2022/facade/with_facade/iot_controller.py @@ -3,11 +3,9 @@ class IOTFacade(Protocol): - def power_speaker(self, on: bool) -> None: - ... + def power_speaker(self, on: bool) -> None: ... - def get_status(self) -> str: - ... + def get_status(self) -> str: ... def get_status(iot: IOTFacade) -> str: diff --git a/2022/func_takeaways/oop_v1.py b/2022/func_takeaways/oop_v1.py index a170727b..cfc281be 100644 --- a/2022/func_takeaways/oop_v1.py +++ b/2022/func_takeaways/oop_v1.py @@ -20,7 +20,6 @@ def greet_list(self, names: list[str]) -> None: def main() -> None: - name = input("Enter your name: ") greeting = Greeting() diff --git a/2022/functions/4_minimal_arguments.py b/2022/functions/4_minimal_arguments.py index 1b4a3da8..c3f9dd91 100644 --- a/2022/functions/4_minimal_arguments.py +++ b/2022/functions/4_minimal_arguments.py @@ -35,16 +35,13 @@ class Customer: class CardInfo(Protocol): @property - def number(self) -> str: - ... + def number(self) -> str: ... @property - def exp_month(self) -> int: - ... + def exp_month(self) -> int: ... @property - def exp_year(self) -> int: - ... + def exp_year(self) -> int: ... def validate_card(card: CardInfo) -> bool: diff --git a/2022/functions/5_create_use_after.py b/2022/functions/5_create_use_after.py index 6e644856..a883b54b 100644 --- a/2022/functions/5_create_use_after.py +++ b/2022/functions/5_create_use_after.py @@ -16,8 +16,7 @@ def handle_payment(self, amount: int) -> None: class PaymentHandler(Protocol): - def handle_payment(self, amount: int) -> None: - ... + def handle_payment(self, amount: int) -> None: ... def order_food(items: list[str], payment_handler: PaymentHandler) -> None: diff --git a/2022/gui_architecture/mvp/presenter.py b/2022/gui_architecture/mvp/presenter.py index 46582b85..25620127 100644 --- a/2022/gui_architecture/mvp/presenter.py +++ b/2022/gui_architecture/mvp/presenter.py @@ -6,24 +6,18 @@ class View(Protocol): - def init_ui(self, presenter: Presenter) -> None: - ... + def init_ui(self, presenter: Presenter) -> None: ... - def get_entry_text(self) -> str: - ... + def get_entry_text(self) -> str: ... - def clear_entry(self) -> None: - ... + def clear_entry(self) -> None: ... - def update_task_list(self, tasks: list[str]) -> None: - ... + def update_task_list(self, tasks: list[str]) -> None: ... @property - def selected_task(self) -> str: - ... + def selected_task(self) -> str: ... - def mainloop(self) -> None: - ... + def mainloop(self) -> None: ... class Presenter: diff --git a/2022/gui_architecture/mvp/view.py b/2022/gui_architecture/mvp/view.py index a9ff2fd9..72083fc8 100644 --- a/2022/gui_architecture/mvp/view.py +++ b/2022/gui_architecture/mvp/view.py @@ -6,11 +6,9 @@ class Presenter(Protocol): - def handle_add_task(self, event=None) -> None: - ... + def handle_add_task(self, event=None) -> None: ... - def handle_delete_task(self, event=None) -> None: - ... + def handle_delete_task(self, event=None) -> None: ... class TodoList(tk.Tk): diff --git a/2022/hypothesis_testing/test/generated/test_office_1.py b/2022/hypothesis_testing/test/generated/test_office_1.py index 9d3acaad..4fa8a62e 100644 --- a/2022/hypothesis_testing/test/generated/test_office_1.py +++ b/2022/hypothesis_testing/test/generated/test_office_1.py @@ -8,4 +8,3 @@ @given(size=st.integers()) def test_fuzz_generate_random_team(size): office.generate_random_team(size=size) - diff --git a/2022/hypothesis_testing/test/generated/test_office_2.py b/2022/hypothesis_testing/test/generated/test_office_2.py index 3e93fe16..218fc14a 100644 --- a/2022/hypothesis_testing/test/generated/test_office_2.py +++ b/2022/hypothesis_testing/test/generated/test_office_2.py @@ -8,4 +8,3 @@ @given(team=st.lists(st.sampled_from(office.Employee))) def test_fuzz_fire_random_employee(team): office.fire_random_employee(team=team) - diff --git a/2022/itertools/iterator_basics.py b/2022/itertools/iterator_basics.py index f2b06e51..5014bb93 100644 --- a/2022/itertools/iterator_basics.py +++ b/2022/itertools/iterator_basics.py @@ -1,5 +1,4 @@ def main() -> None: - countries = ("Germany", "France", "Italy", "Spain", "Portugal", "Greece") country_iterator = iter(countries) diff --git a/2022/more_code_smells/after.py b/2022/more_code_smells/after.py index d02d9029..6b9277d2 100644 --- a/2022/more_code_smells/after.py +++ b/2022/more_code_smells/after.py @@ -1,6 +1,7 @@ """ Basic example of a Vehicle registration system. """ + import random import string from dataclasses import dataclass diff --git a/2022/more_code_smells/before.py b/2022/more_code_smells/before.py index a4eb7bf5..66714d76 100644 --- a/2022/more_code_smells/before.py +++ b/2022/more_code_smells/before.py @@ -1,6 +1,7 @@ """ Basic example of a Vehicle registration system. """ + from dataclasses import dataclass from enum import Enum, auto from random import * @@ -119,7 +120,6 @@ def online_status(self) -> RegistryStatus: if __name__ == "__main__": - # create a registry instance registry = VehicleRegistry() diff --git a/2022/oop_done_well/abuse_after.py b/2022/oop_done_well/abuse_after.py index 803eb2d2..f366db9e 100644 --- a/2022/oop_done_well/abuse_after.py +++ b/2022/oop_done_well/abuse_after.py @@ -8,8 +8,7 @@ class PaymentMethod(Enum): class Payment(Protocol): - def pay(self, amount: int) -> None: - ... + def pay(self, amount: int) -> None: ... class PaypalPayment(Payment): diff --git a/2022/partial_functions/strategy_before.py b/2022/partial_functions/strategy_before.py index 6d2d31fc..58708280 100644 --- a/2022/partial_functions/strategy_before.py +++ b/2022/partial_functions/strategy_before.py @@ -1,6 +1,7 @@ """ Basic example of a Trading bot with a strategy pattern. """ + import statistics from dataclasses import dataclass from typing import Protocol diff --git a/2022/partial_functions/strategy_fn.py b/2022/partial_functions/strategy_fn.py index 73b1061d..8267a711 100644 --- a/2022/partial_functions/strategy_fn.py +++ b/2022/partial_functions/strategy_fn.py @@ -1,6 +1,7 @@ """ Basic example of a Trading bot with a strategy pattern. """ + import statistics from dataclasses import dataclass from typing import Callable diff --git a/2022/partial_functions/strategy_fn_closure.py b/2022/partial_functions/strategy_fn_closure.py index 51841f9c..4c0af54e 100644 --- a/2022/partial_functions/strategy_fn_closure.py +++ b/2022/partial_functions/strategy_fn_closure.py @@ -1,6 +1,7 @@ """ Basic example of a Trading bot with a strategy pattern. """ + import statistics from dataclasses import dataclass from typing import Callable diff --git a/2022/partial_functions/strategy_fn_partial.py b/2022/partial_functions/strategy_fn_partial.py index da193fe9..dc8f5d99 100644 --- a/2022/partial_functions/strategy_fn_partial.py +++ b/2022/partial_functions/strategy_fn_partial.py @@ -1,6 +1,7 @@ """ Basic example of a Trading bot with a strategy pattern. """ + import statistics from dataclasses import dataclass from functools import partial diff --git a/2022/plugin_system/after/example.py b/2022/plugin_system/after/example.py index d5c45c48..df889c08 100644 --- a/2022/plugin_system/after/example.py +++ b/2022/plugin_system/after/example.py @@ -11,7 +11,6 @@ @dataclass class Sorcerer: - name: str def make_a_noise(self) -> None: @@ -20,7 +19,6 @@ def make_a_noise(self) -> None: @dataclass class Wizard: - name: str def make_a_noise(self) -> None: @@ -29,7 +27,6 @@ def make_a_noise(self) -> None: @dataclass class Witcher: - name: str def make_a_noise(self) -> None: diff --git a/2022/plugin_system/after/game/loader.py b/2022/plugin_system/after/game/loader.py index c88929e0..6bab61e9 100644 --- a/2022/plugin_system/after/game/loader.py +++ b/2022/plugin_system/after/game/loader.py @@ -1,4 +1,5 @@ """A simple plugin loader.""" + import importlib diff --git a/2022/plugin_system/after/plugins/bard.py b/2022/plugin_system/after/plugins/bard.py index 38973bf2..cf008e4b 100644 --- a/2022/plugin_system/after/plugins/bard.py +++ b/2022/plugin_system/after/plugins/bard.py @@ -7,7 +7,6 @@ @dataclass class Bard: - name: str instrument: str = "flute" diff --git a/2022/plugin_system/before/example.py b/2022/plugin_system/before/example.py index 1717d124..e24490f7 100644 --- a/2022/plugin_system/before/example.py +++ b/2022/plugin_system/before/example.py @@ -11,7 +11,6 @@ @dataclass class Sorcerer: - name: str def make_a_noise(self) -> None: @@ -20,7 +19,6 @@ def make_a_noise(self) -> None: @dataclass class Wizard: - name: str def make_a_noise(self) -> None: @@ -29,7 +27,6 @@ def make_a_noise(self) -> None: @dataclass class Witcher: - name: str def make_a_noise(self) -> None: diff --git a/2022/protocols_abc/protocol/iot/diagnostics.py b/2022/protocols_abc/protocol/iot/diagnostics.py index e079e3e3..88d8cc9f 100644 --- a/2022/protocols_abc/protocol/iot/diagnostics.py +++ b/2022/protocols_abc/protocol/iot/diagnostics.py @@ -2,8 +2,7 @@ class DiagnosticsSource(Protocol): - def status_update(self) -> str: - ... + def status_update(self) -> str: ... def collect_diagnostics(device: DiagnosticsSource) -> None: diff --git a/2022/protocols_abc/protocol/iot/service.py b/2022/protocols_abc/protocol/iot/service.py index cd7fd390..3e29958d 100644 --- a/2022/protocols_abc/protocol/iot/service.py +++ b/2022/protocols_abc/protocol/iot/service.py @@ -10,14 +10,11 @@ def generate_id(length: int = 8): class Device(Protocol): - def connect(self) -> None: - ... + def connect(self) -> None: ... - def disconnect(self) -> None: - ... + def disconnect(self) -> None: ... - def send_message(self, message_type: MessageType, data: str) -> None: - ... + def send_message(self, message_type: MessageType, data: str) -> None: ... class IOTService: diff --git a/2022/pulumi/basic_project/__main__.py b/2022/pulumi/basic_project/__main__.py index 45950f45..96975f76 100644 --- a/2022/pulumi/basic_project/__main__.py +++ b/2022/pulumi/basic_project/__main__.py @@ -5,7 +5,6 @@ def main() -> None: - # Create a GCP resource (Storage Bucket) bucket = storage.Bucket( "my-bucket", diff --git a/2022/pulumi/cloud_func/functions/main.py b/2022/pulumi/cloud_func/functions/main.py index ec006e68..57393c75 100644 --- a/2022/pulumi/cloud_func/functions/main.py +++ b/2022/pulumi/cloud_func/functions/main.py @@ -15,6 +15,7 @@ for channel_raw in channels_raw: channels[channel_raw["id"]] = channel_raw + # Define the internal path, idiomatic Flask definition @app.route("/channels/", methods=["GET", "POST"]) def name(channel_id: str): diff --git a/2022/pulumi/cloud_run_v2/__main__.py b/2022/pulumi/cloud_run_v2/__main__.py index f87dd27a..9e7f2a21 100644 --- a/2022/pulumi/cloud_run_v2/__main__.py +++ b/2022/pulumi/cloud_run_v2/__main__.py @@ -68,7 +68,6 @@ def create_noauth_iam_policy(service: gcp.cloudrun.Service) -> None: def main() -> None: - # Create a private GCR repository. registry_url = create_registry(REGISTRY) diff --git a/2022/quick_tips_shorts/05_type_alias/after.py b/2022/quick_tips_shorts/05_type_alias/after.py index 444432c5..67009d10 100644 --- a/2022/quick_tips_shorts/05_type_alias/after.py +++ b/2022/quick_tips_shorts/05_type_alias/after.py @@ -7,7 +7,6 @@ @dataclass class TradingBot: - buy_strategy: TradingStrategyFunction sell_strategy: TradingStrategyFunction diff --git a/2022/quick_tips_shorts/05_type_alias/before.py b/2022/quick_tips_shorts/05_type_alias/before.py index ae362081..db272665 100644 --- a/2022/quick_tips_shorts/05_type_alias/before.py +++ b/2022/quick_tips_shorts/05_type_alias/before.py @@ -5,7 +5,6 @@ @dataclass class TradingBot: - buy_strategy: Callable[[list[int]], bool] sell_strategy: Callable[[list[int]], bool] diff --git a/2022/quick_tips_shorts/13_numbers/after.py b/2022/quick_tips_shorts/13_numbers/after.py index 33d4b38e..12923566 100644 --- a/2022/quick_tips_shorts/13_numbers/after.py +++ b/2022/quick_tips_shorts/13_numbers/after.py @@ -2,8 +2,7 @@ class PaymentHandler(Protocol): - def handle_payment(self, amount: int) -> None: - ... + def handle_payment(self, amount: int) -> None: ... class StripePaymentHandler: diff --git a/2022/quick_tips_shorts/13_numbers/before.py b/2022/quick_tips_shorts/13_numbers/before.py index 270dbe7c..a1d2de13 100644 --- a/2022/quick_tips_shorts/13_numbers/before.py +++ b/2022/quick_tips_shorts/13_numbers/before.py @@ -2,8 +2,7 @@ class PaymentHandler(Protocol): - def handle_payment(self, amount: int) -> None: - ... + def handle_payment(self, amount: int) -> None: ... class StripePaymentHandler: diff --git a/2022/quick_tips_shorts/22_custom_exception/after.py b/2022/quick_tips_shorts/22_custom_exception/after.py index f58748d6..e274c356 100644 --- a/2022/quick_tips_shorts/22_custom_exception/after.py +++ b/2022/quick_tips_shorts/22_custom_exception/after.py @@ -9,7 +9,6 @@ class VacationDaysShortageError(Exception): @dataclass class Employee: - name: str vacation_days: int = 25 diff --git a/2022/quick_tips_shorts/22_custom_exception/before.py b/2022/quick_tips_shorts/22_custom_exception/before.py index aeb091ad..fd9c5d54 100644 --- a/2022/quick_tips_shorts/22_custom_exception/before.py +++ b/2022/quick_tips_shorts/22_custom_exception/before.py @@ -3,7 +3,6 @@ @dataclass class Employee: - name: str vacation_days: int = 25 diff --git a/2022/quick_tips_shorts/26_dep_inversion/after.py b/2022/quick_tips_shorts/26_dep_inversion/after.py index 173b33f7..dfc90a39 100644 --- a/2022/quick_tips_shorts/26_dep_inversion/after.py +++ b/2022/quick_tips_shorts/26_dep_inversion/after.py @@ -2,8 +2,7 @@ class PaymentHandler(Protocol): - def handle_payment(self, amount: int) -> None: - ... + def handle_payment(self, amount: int) -> None: ... class StripePaymentHandler: diff --git a/2022/quick_tips_shorts/27_protocol_segregation/after.py b/2022/quick_tips_shorts/27_protocol_segregation/after.py index 724854e1..da09fa17 100644 --- a/2022/quick_tips_shorts/27_protocol_segregation/after.py +++ b/2022/quick_tips_shorts/27_protocol_segregation/after.py @@ -5,13 +5,11 @@ class Device(Protocol): - def send_message(self, message_type: MessageType, data: str) -> None: - ... + def send_message(self, message_type: MessageType, data: str) -> None: ... class StatusSource(Protocol): - def check_status(self) -> None: - ... + def check_status(self) -> None: ... def run_program(program: list[Message], devices: dict[str, Device]) -> None: diff --git a/2022/quick_tips_shorts/27_protocol_segregation/before.py b/2022/quick_tips_shorts/27_protocol_segregation/before.py index 3b177b99..9514f85d 100644 --- a/2022/quick_tips_shorts/27_protocol_segregation/before.py +++ b/2022/quick_tips_shorts/27_protocol_segregation/before.py @@ -5,11 +5,9 @@ class Device(Protocol): - def check_status(self) -> None: - ... + def check_status(self) -> None: ... - def send_message(self, message_type: MessageType, data: str) -> None: - ... + def send_message(self, message_type: MessageType, data: str) -> None: ... def run_program(program: list[Message], devices: dict[str, Device]) -> None: diff --git a/2022/quick_tips_shorts/27_protocol_segregation/iot/service.py b/2022/quick_tips_shorts/27_protocol_segregation/iot/service.py index 1ec52934..673f6136 100644 --- a/2022/quick_tips_shorts/27_protocol_segregation/iot/service.py +++ b/2022/quick_tips_shorts/27_protocol_segregation/iot/service.py @@ -4,11 +4,9 @@ class Device(Protocol): - def check_status(self) -> None: - ... + def check_status(self) -> None: ... - def send_message(self, message_type: MessageType, data: str) -> None: - ... + def send_message(self, message_type: MessageType, data: str) -> None: ... class IOTService: diff --git a/2022/quick_tips_shorts/28_func_composition/after.py b/2022/quick_tips_shorts/28_func_composition/after.py index 6277ed9c..de65a5ec 100644 --- a/2022/quick_tips_shorts/28_func_composition/after.py +++ b/2022/quick_tips_shorts/28_func_composition/after.py @@ -3,6 +3,7 @@ ComposableFunction = Callable[[float], float] + # Helper function for composing functions def compose(*functions: ComposableFunction) -> ComposableFunction: return functools.reduce(lambda f, g: lambda x: g(f(x)), functions) diff --git a/2022/quick_tips_shorts/28_func_composition/before.py b/2022/quick_tips_shorts/28_func_composition/before.py index 794a409d..2b652add 100644 --- a/2022/quick_tips_shorts/28_func_composition/before.py +++ b/2022/quick_tips_shorts/28_func_composition/before.py @@ -3,6 +3,7 @@ ComposableFunction = Callable[[float], float] + # Helper function for composing functions def compose(*functions: ComposableFunction) -> ComposableFunction: return functools.reduce(lambda f, g: lambda x: g(f(x)), functions) diff --git a/2022/red_green_refactor/green/employee.py b/2022/red_green_refactor/green/employee.py index d24bbc62..e73e17af 100644 --- a/2022/red_green_refactor/green/employee.py +++ b/2022/red_green_refactor/green/employee.py @@ -1,6 +1,7 @@ """ Very advanced Employee management system. """ + from dataclasses import dataclass diff --git a/2022/red_green_refactor/green/test_employee.py b/2022/red_green_refactor/green/test_employee.py index 7302f512..2940007a 100644 --- a/2022/red_green_refactor/green/test_employee.py +++ b/2022/red_green_refactor/green/test_employee.py @@ -1,6 +1,7 @@ """ Employee class tests. """ + import unittest from employee import Employee diff --git a/2022/red_green_refactor/red/employee.py b/2022/red_green_refactor/red/employee.py index 993ece6d..aaffcf54 100644 --- a/2022/red_green_refactor/red/employee.py +++ b/2022/red_green_refactor/red/employee.py @@ -1,6 +1,7 @@ """ Very advanced Employee management system. """ + from dataclasses import dataclass diff --git a/2022/red_green_refactor/red/test_employee.py b/2022/red_green_refactor/red/test_employee.py index 7302f512..2940007a 100644 --- a/2022/red_green_refactor/red/test_employee.py +++ b/2022/red_green_refactor/red/test_employee.py @@ -1,6 +1,7 @@ """ Employee class tests. """ + import unittest from employee import Employee diff --git a/2022/red_green_refactor/refactor/employee.py b/2022/red_green_refactor/refactor/employee.py index 9349037b..e8ee8349 100644 --- a/2022/red_green_refactor/refactor/employee.py +++ b/2022/red_green_refactor/refactor/employee.py @@ -1,6 +1,7 @@ """ Very advanced Employee management system. """ + from dataclasses import dataclass diff --git a/2022/red_green_refactor/refactor/test_employee.py b/2022/red_green_refactor/refactor/test_employee.py index 6160f09f..20727100 100644 --- a/2022/red_green_refactor/refactor/test_employee.py +++ b/2022/red_green_refactor/refactor/test_employee.py @@ -1,6 +1,7 @@ """ Employee class tests. """ + import unittest from employee import Employee diff --git a/2022/red_green_refactor/refactor/testing_tips.py b/2022/red_green_refactor/refactor/testing_tips.py index 6053472a..d0374aa7 100644 --- a/2022/red_green_refactor/refactor/testing_tips.py +++ b/2022/red_green_refactor/refactor/testing_tips.py @@ -1,6 +1,7 @@ """ Employee class tests. """ + import unittest from employee import Employee diff --git a/2022/strategy_parameters/before.py b/2022/strategy_parameters/before.py index c22a51e9..27a36d40 100644 --- a/2022/strategy_parameters/before.py +++ b/2022/strategy_parameters/before.py @@ -1,6 +1,7 @@ """ Basic example of a Trading bot with a strategy pattern. """ + import statistics from abc import ABC, abstractmethod diff --git a/2022/strategy_parameters/with_init_args.py b/2022/strategy_parameters/with_init_args.py index 98fa6cdf..95064c9d 100644 --- a/2022/strategy_parameters/with_init_args.py +++ b/2022/strategy_parameters/with_init_args.py @@ -1,6 +1,7 @@ """ Basic example of a Trading bot with a strategy pattern. """ + import statistics from abc import ABC, abstractmethod from dataclasses import dataclass @@ -27,7 +28,6 @@ class AverageTradingStrategy(TradingStrategy): window_size: int = 3 def should_buy(self, prices: list[float]) -> bool: - list_window = prices[-int(self.window_size) :] return prices[-1] < statistics.mean(list_window) diff --git a/2022/strategy_parameters/with_keyword_args.py b/2022/strategy_parameters/with_keyword_args.py index 527fad68..b83021e0 100644 --- a/2022/strategy_parameters/with_keyword_args.py +++ b/2022/strategy_parameters/with_keyword_args.py @@ -1,6 +1,7 @@ """ Basic example of a Trading bot with a strategy pattern. """ + import statistics from abc import ABC, abstractmethod diff --git a/2022/strategy_parameters/with_parameters_class.py b/2022/strategy_parameters/with_parameters_class.py index 9c6a2034..57ff2ae1 100644 --- a/2022/strategy_parameters/with_parameters_class.py +++ b/2022/strategy_parameters/with_parameters_class.py @@ -1,6 +1,7 @@ """ Basic example of a Trading bot with a strategy pattern. """ + import statistics from abc import ABC, abstractmethod from dataclasses import dataclass diff --git a/2022/structural_pattern_matching/example.py b/2022/structural_pattern_matching/example.py index a524619c..8b5c9499 100644 --- a/2022/structural_pattern_matching/example.py +++ b/2022/structural_pattern_matching/example.py @@ -16,6 +16,7 @@ def run_command_v1(command: str) -> None: case other: print(f"Unknown command '{other}'.") + def run_command_v2(command: str) -> None: match command.split(): case ["load", filename]: @@ -31,6 +32,7 @@ def run_command_v2(command: str) -> None: case _: print(f"Unknown command '{command}'.") + def run_command_v3(command: str) -> None: match command.split(): case ["load", filename]: @@ -46,20 +48,24 @@ def run_command_v3(command: str) -> None: case _: print(f"Unknown command {command!r}.") + @dataclass class Command: """Class that represents a command.""" - + command: str arguments: List[str] + def run_command_v4(command: Command) -> None: match command: case Command(command="load", arguments=[filename]): print(f"Loading filename {filename}.") case Command(command="save", arguments=[filename]): print(f"Saving filename {filename}.") - case Command(command="quit" | "exit" | "bye", arguments=["--force" | "-f", *rest]): + case Command( + command="quit" | "exit" | "bye", arguments=["--force" | "-f", *rest] + ): print("Sending SIGTERM to all processes and quitting the program.") quit() case Command(command="quit" | "exit" | "bye"): @@ -84,5 +90,3 @@ def main() -> None: if __name__ == "__main__": main() - - diff --git a/2022/types/example.py b/2022/types/example.py index 844cb35a..9bda6127 100644 --- a/2022/types/example.py +++ b/2022/types/example.py @@ -52,7 +52,6 @@ def digits_of(nr): def main(): - print(luhn_checksum(1249190007575069)) # oops print(luhn_checksum_with_doc(1249190007575069)) # oops diff --git a/2023/classguide/3_dependency_injection.py b/2023/classguide/3_dependency_injection.py index 549d838a..ecc767b3 100644 --- a/2023/classguide/3_dependency_injection.py +++ b/2023/classguide/3_dependency_injection.py @@ -11,8 +11,7 @@ class EmailSender(Protocol): - def send_message(self, to_email: str, subject: str, body: str) -> None: - ... + def send_message(self, to_email: str, subject: str, body: str) -> None: ... @lru_cache diff --git a/2023/classguide/4_email_function.py b/2023/classguide/4_email_function.py index a21a3b39..041ffd41 100644 --- a/2023/classguide/4_email_function.py +++ b/2023/classguide/4_email_function.py @@ -11,8 +11,7 @@ class EmailSender(Protocol): - def __call__(self, to_email: str, subject: str, body: str) -> None: - ... + def __call__(self, to_email: str, subject: str, body: str) -> None: ... @lru_cache diff --git a/2023/decorator/decorator_pattern_classic.py b/2023/decorator/decorator_pattern_classic.py index 006b081d..40d99cd1 100644 --- a/2023/decorator/decorator_pattern_classic.py +++ b/2023/decorator/decorator_pattern_classic.py @@ -26,7 +26,6 @@ def __init__(self, decorated: AbstractComponent) -> None: class ConcreteComponent(AbstractComponent): def execute(self, upper_bound: int) -> int: - count = 0 for number in range(upper_bound): if is_prime(number): diff --git a/2023/doc/src/better_doc with_docstrings.py b/2023/doc/src/better_doc with_docstrings.py index 00feac9b..56bebc4a 100644 --- a/2023/doc/src/better_doc with_docstrings.py +++ b/2023/doc/src/better_doc with_docstrings.py @@ -1,6 +1,6 @@ """Bank account system that emulate bank account and operations betweem them.""" -from __future__ import annotations # * To allow type hints +from __future__ import annotations # * To allow type hints from datetime import datetime from enum import StrEnum, auto @@ -17,12 +17,13 @@ class TransactionType(StrEnum): Transaction = tuple[TransactionType, datetime, int] -class InsufficientBalanceError(Exception): - ... +class InsufficientBalanceError(Exception): ... + class BankAccount: """Represents a bank account entity.""" - def __init__(self, initial_balance = 0) -> None: + + def __init__(self, initial_balance=0) -> None: self._balance: int = initial_balance self._transaction_history: list[Transaction] = [] @@ -58,7 +59,6 @@ def withdraw(self, amount: int) -> None: self._transaction_history.append( (TransactionType.WITHDRAWAL, datetime.now(), amount) ) - def transfer(self, other: BankAccount, amount: int) -> None: """Transfer money from this account to another one. @@ -81,10 +81,7 @@ def transfer(self, other: BankAccount, amount: int) -> None: self._balance -= amount other._balance += amount # ! Can't append operation at other instance class - self._transaction_history.append( - (TransactionType.TRANSFER, timestamp, amount) - ) - + self._transaction_history.append((TransactionType.TRANSFER, timestamp, amount)) def _sufficient_balance(self, amount: int) -> bool: """Check if the balance is non-negative. @@ -99,7 +96,7 @@ def _sufficient_balance(self, amount: int) -> bool: bool True if resulting balance is non-negative, false otherwhise. """ - + return amount <= self._balance @property @@ -134,5 +131,6 @@ def main() -> None: print(account1.balance) + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/2023/doc/src/better_doc.py b/2023/doc/src/better_doc.py index 2665d346..f0382b00 100644 --- a/2023/doc/src/better_doc.py +++ b/2023/doc/src/better_doc.py @@ -1,6 +1,6 @@ """Bank account operations using OOP.""" -from __future__ import annotations # * To allow type hints +from __future__ import annotations # * To allow type hints from datetime import datetime from enum import StrEnum, auto @@ -15,12 +15,12 @@ class TransactionType(StrEnum): Transaction = tuple[TransactionType, datetime, int] -class InsufficientBalanceError(Exception): - ... +class InsufficientBalanceError(Exception): ... + class BankAccount: # TODO: insert docstring - def __init__(self, initial_balance = 0) -> None: + def __init__(self, initial_balance=0) -> None: self._balance = initial_balance self._transaction_history: list[Transaction] = [] @@ -72,5 +72,6 @@ def main() -> None: print(account1.balance) + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/2023/dunder/c2_after.py b/2023/dunder/c2_after.py index 8cd28400..e54e253d 100644 --- a/2023/dunder/c2_after.py +++ b/2023/dunder/c2_after.py @@ -8,8 +8,7 @@ class PaymentMethod(StrEnum): class Payment(Protocol): - def pay(self, amount: int) -> None: - ... + def pay(self, amount: int) -> None: ... class PaypalPayment: diff --git a/2023/fastapi/1_basic_app.py b/2023/fastapi/1_basic_app.py index 67b6efc4..2a60fd5f 100644 --- a/2023/fastapi/1_basic_app.py +++ b/2023/fastapi/1_basic_app.py @@ -6,8 +6,8 @@ class Category(Enum): - TOOLS = 'tools' - CONSUMABLES = 'consumables' + TOOLS = "tools" + CONSUMABLES = "consumables" class Item(BaseModel): diff --git a/2023/fastapi/3_more_routing.py b/2023/fastapi/3_more_routing.py index a744f62b..5d9ae2ff 100644 --- a/2023/fastapi/3_more_routing.py +++ b/2023/fastapi/3_more_routing.py @@ -29,13 +29,11 @@ class Item(BaseModel): @app.get("/") def index() -> dict[str, dict[int, Item]]: - return {"items": items} @app.get("/items/{item_id}") def query_item_by_id(item_id: int) -> Item: - if item_id not in items: HTTPException(status_code=404, detail=f"Item with {item_id=} does not exist.") @@ -74,7 +72,6 @@ def check_item(item: Item): @app.post("/") def add_item(item: Item) -> dict[str, Item]: - if item.id in items: HTTPException(status_code=400, detail=f"Item with {item.id=} already exists.") @@ -89,7 +86,6 @@ def update( price: float | None = None, count: int | None = None, ) -> dict[str, Item]: - if item_id not in items: HTTPException(status_code=404, detail=f"Item with {item_id=} does not exist.") if all(info is None for info in (name, price, count)): @@ -110,7 +106,6 @@ def update( @app.delete("/delete/{item_id}") def delete_item(item_id: int) -> dict[str, Item]: - if item_id not in items: raise HTTPException( status_code=404, detail=f"Item with {item_id=} does not exist." diff --git a/2023/fastapi/4_main.py b/2023/fastapi/4_main.py index 2e4810f5..6efe0413 100644 --- a/2023/fastapi/4_main.py +++ b/2023/fastapi/4_main.py @@ -18,8 +18,6 @@ print( requests.post( "http://127.0.0.1:8000/", - json={"name": "Screwdriver", "price": 3.99, "count": 'Hello', "id": 4}, + json={"name": "Screwdriver", "price": 3.99, "count": "Hello", "id": 4}, ).json() ) - - diff --git a/2023/fastapi/5_validation_with_Query_and_Path.py b/2023/fastapi/5_validation_with_Query_and_Path.py index b9c389ff..fcef772a 100644 --- a/2023/fastapi/5_validation_with_Query_and_Path.py +++ b/2023/fastapi/5_validation_with_Query_and_Path.py @@ -108,7 +108,6 @@ def update( @app.delete("/delete/{item_id}") def delete_item(item_id: int) -> dict[str, Item]: - if item_id not in items: raise HTTPException( status_code=404, detail=f"Item with {item_id=} does not exist." diff --git a/2023/fastapi/6_adding_openapi_documentation.py b/2023/fastapi/6_adding_openapi_documentation.py index cfb59c15..3af7983b 100644 --- a/2023/fastapi/6_adding_openapi_documentation.py +++ b/2023/fastapi/6_adding_openapi_documentation.py @@ -12,6 +12,7 @@ version="0.1.0", ) + # Docstrings of classes will be reflected in the API documentation in the 'Schemas' section class Category(Enum): """Category of an item""" @@ -104,23 +105,20 @@ def update( item_id: int = Path( title="Item ID", description="Unique integer that specifies an item.", ge=0 ), - name: str - | None = Query( + name: str | None = Query( title="Name", description="New name of the item.", default=None, min_length=1, max_length=8, ), - price: float - | None = Query( + price: float | None = Query( title="Price", description="New price of the item in Euro.", default=None, gt=0.0, ), - count: int - | None = Query( + count: int | None = Query( title="Count", description="New amount of instances of this item in stock.", default=None, @@ -147,7 +145,6 @@ def update( @app.delete("/delete/{item_id}") def delete_item(item_id: int) -> dict[str, Item]: - if item_id not in items: raise HTTPException( status_code=404, detail=f"Item with {item_id=} does not exist." diff --git a/2023/funclass/src/classes.py b/2023/funclass/src/classes.py index 793841db..4ef21306 100644 --- a/2023/funclass/src/classes.py +++ b/2023/funclass/src/classes.py @@ -5,7 +5,6 @@ class TransactionType(StrEnum): - DEPOSIT = auto() WITHDRAWAL = auto() TRANSFER = auto() @@ -58,7 +57,6 @@ def transaction_history(self) -> list[Transaction]: def main() -> None: - account1 = BankAccount(initial_balance=100) account2 = BankAccount(initial_balance=500) diff --git a/2023/generic/after.py b/2023/generic/after.py index 1ad16360..4442bc16 100644 --- a/2023/generic/after.py +++ b/2023/generic/after.py @@ -4,6 +4,7 @@ # A generic type alias type ListOrSet[T] = list[T] | set[T] + class Box[T]: def __init__(self, item: T): self.item = item @@ -14,10 +15,12 @@ def get_item(self) -> T: def set_item(self, new_item: T) -> None: self.item = new_item + # generic function example def get_first_item[T](items: list[T]) -> T: return items[0] + def main() -> None: # For integers int_box = Box(123) diff --git a/2023/generic/constrained.py b/2023/generic/constrained.py index 457e3a7f..3cfc8e35 100644 --- a/2023/generic/constrained.py +++ b/2023/generic/constrained.py @@ -20,10 +20,12 @@ class Boat(Vehicle): def display(self) -> None: print(f"Boat model: {self.model}") + class Plane(Vehicle): def display(self) -> None: print(f"Plane model: {self.model}") + class VehicleRegistry[V: (Car, Boat)]: def __init__(self) -> None: self.vehicles: list[V] = [] diff --git a/2023/generic/upper_bound_after.py b/2023/generic/upper_bound_after.py index ac8fd135..84ca26e0 100644 --- a/2023/generic/upper_bound_after.py +++ b/2023/generic/upper_bound_after.py @@ -20,10 +20,12 @@ class Boat(Vehicle): def display(self) -> None: print(f"Boat model: {self.model}") + class Plane(Vehicle): def display(self) -> None: print(f"Plane model: {self.model}") - + + class VehicleRegistry[V: Vehicle]: def __init__(self) -> None: self.vehicles: list[V] = [] diff --git a/2023/gildedrose/after/gilded_rose.py b/2023/gildedrose/after/gilded_rose.py index 483af719..d0c823cf 100755 --- a/2023/gildedrose/after/gilded_rose.py +++ b/2023/gildedrose/after/gilded_rose.py @@ -19,11 +19,9 @@ def increase_item_quality(item: Item, amount: int = 1, max_quality: int = 50) -> class ItemUpdater(Protocol): - def update_sell_in(self, item: Item) -> None: - ... + def update_sell_in(self, item: Item) -> None: ... - def update_quality(self, item: Item) -> None: - ... + def update_quality(self, item: Item) -> None: ... class DefaultItemUpdater: diff --git a/2023/gildedrose/after/texttest_fixture.py b/2023/gildedrose/after/texttest_fixture.py index 86af5ef7..dd5949d9 100644 --- a/2023/gildedrose/after/texttest_fixture.py +++ b/2023/gildedrose/after/texttest_fixture.py @@ -4,21 +4,22 @@ from gilded_rose import * if __name__ == "__main__": - print ("OMGHAI!") + print("OMGHAI!") items = [ - Item(name="+5 Dexterity Vest", sell_in=10, quality=20), - Item(name="Aged Brie", sell_in=2, quality=0), - Item(name="Elixir of the Mongoose", sell_in=5, quality=7), - Item(name="Sulfuras, Hand of Ragnaros", sell_in=0, quality=80), - Item(name="Sulfuras, Hand of Ragnaros", sell_in=-1, quality=80), - Item(name="Backstage passes to a TAFKAL80ETC concert", sell_in=15, quality=20), - Item(name="Backstage passes to a TAFKAL80ETC concert", sell_in=10, quality=49), - Item(name="Backstage passes to a TAFKAL80ETC concert", sell_in=5, quality=49), - Item(name="Conjured Mana Cake", sell_in=3, quality=6), # <-- :O - ] + Item(name="+5 Dexterity Vest", sell_in=10, quality=20), + Item(name="Aged Brie", sell_in=2, quality=0), + Item(name="Elixir of the Mongoose", sell_in=5, quality=7), + Item(name="Sulfuras, Hand of Ragnaros", sell_in=0, quality=80), + Item(name="Sulfuras, Hand of Ragnaros", sell_in=-1, quality=80), + Item(name="Backstage passes to a TAFKAL80ETC concert", sell_in=15, quality=20), + Item(name="Backstage passes to a TAFKAL80ETC concert", sell_in=10, quality=49), + Item(name="Backstage passes to a TAFKAL80ETC concert", sell_in=5, quality=49), + Item(name="Conjured Mana Cake", sell_in=3, quality=6), # <-- :O + ] days = 2 import sys + if len(sys.argv) > 1: days = int(sys.argv[1]) + 1 for day in range(days): diff --git a/2023/gildedrose/before/texttest_fixture.py b/2023/gildedrose/before/texttest_fixture.py index 86af5ef7..dd5949d9 100644 --- a/2023/gildedrose/before/texttest_fixture.py +++ b/2023/gildedrose/before/texttest_fixture.py @@ -4,21 +4,22 @@ from gilded_rose import * if __name__ == "__main__": - print ("OMGHAI!") + print("OMGHAI!") items = [ - Item(name="+5 Dexterity Vest", sell_in=10, quality=20), - Item(name="Aged Brie", sell_in=2, quality=0), - Item(name="Elixir of the Mongoose", sell_in=5, quality=7), - Item(name="Sulfuras, Hand of Ragnaros", sell_in=0, quality=80), - Item(name="Sulfuras, Hand of Ragnaros", sell_in=-1, quality=80), - Item(name="Backstage passes to a TAFKAL80ETC concert", sell_in=15, quality=20), - Item(name="Backstage passes to a TAFKAL80ETC concert", sell_in=10, quality=49), - Item(name="Backstage passes to a TAFKAL80ETC concert", sell_in=5, quality=49), - Item(name="Conjured Mana Cake", sell_in=3, quality=6), # <-- :O - ] + Item(name="+5 Dexterity Vest", sell_in=10, quality=20), + Item(name="Aged Brie", sell_in=2, quality=0), + Item(name="Elixir of the Mongoose", sell_in=5, quality=7), + Item(name="Sulfuras, Hand of Ragnaros", sell_in=0, quality=80), + Item(name="Sulfuras, Hand of Ragnaros", sell_in=-1, quality=80), + Item(name="Backstage passes to a TAFKAL80ETC concert", sell_in=15, quality=20), + Item(name="Backstage passes to a TAFKAL80ETC concert", sell_in=10, quality=49), + Item(name="Backstage passes to a TAFKAL80ETC concert", sell_in=5, quality=49), + Item(name="Conjured Mana Cake", sell_in=3, quality=6), # <-- :O + ] days = 2 import sys + if len(sys.argv) > 1: days = int(sys.argv[1]) + 1 for day in range(days): diff --git a/2023/grasp/04-protected_variation_after.py b/2023/grasp/04-protected_variation_after.py index 5e1d8ffb..63eb0cd5 100644 --- a/2023/grasp/04-protected_variation_after.py +++ b/2023/grasp/04-protected_variation_after.py @@ -50,14 +50,11 @@ def get_products(self) -> list[tuple[str, float]]: class AppInterface(Protocol): - def bind_add_product(self): - ... + def bind_add_product(self): ... - def bind_del_product(self): - ... + def bind_del_product(self): ... - def update_products_list(self): - ... + def update_products_list(self): ... class App(tk.Tk, AppInterface): diff --git a/2023/grasp/05-indirection_before.py b/2023/grasp/05-indirection_before.py index 96bf98ec..aa4602ed 100644 --- a/2023/grasp/05-indirection_before.py +++ b/2023/grasp/05-indirection_before.py @@ -42,7 +42,6 @@ def get_discount(self) -> float: def main() -> None: - henry = Customer(since=date(2023, 1, 1)) order1 = Order(henry) print(f"Henry got {order1.get_discount() * 100:.0f} % discount") diff --git a/2023/grasp/06-low_coupling_after.py b/2023/grasp/06-low_coupling_after.py index d933c5b7..2caf03ec 100644 --- a/2023/grasp/06-low_coupling_after.py +++ b/2023/grasp/06-low_coupling_after.py @@ -26,8 +26,7 @@ def total_line_price(self) -> int: class PaymentMethod(Protocol): """Payment method interface.""" - def net_price(self, total_price: int) -> int: - ... + def net_price(self, total_price: int) -> int: ... @dataclass diff --git a/2023/grasp/07-high_cohesion_after.py b/2023/grasp/07-high_cohesion_after.py index 846e9e45..cc6efea9 100644 --- a/2023/grasp/07-high_cohesion_after.py +++ b/2023/grasp/07-high_cohesion_after.py @@ -43,7 +43,6 @@ def print(self): @dataclass class VehicleRegistry: - vehicle_info: dict[Brand, VehicleInfo] = field(default_factory=dict) def __post_init__(self): diff --git a/2023/grasp/07-high_cohesion_before.py b/2023/grasp/07-high_cohesion_before.py index 2d0c4a31..811d38bb 100644 --- a/2023/grasp/07-high_cohesion_before.py +++ b/2023/grasp/07-high_cohesion_before.py @@ -27,7 +27,6 @@ def generate_vehicle_license(self, id: str) -> str: def register_vehicle(brand: Brand) -> None: - registry = VehicleRegistry() vehicle_id = registry.generate_vehicle_id(12) diff --git a/2023/grasp/09-pure_fabrication_after.py b/2023/grasp/09-pure_fabrication_after.py index 0dea6cfe..9171def7 100644 --- a/2023/grasp/09-pure_fabrication_after.py +++ b/2023/grasp/09-pure_fabrication_after.py @@ -48,7 +48,6 @@ def handle_payment(self, payment: Payment) -> None: def main() -> None: - persistent_storage = PersistentStorage() payment_handler = PaymentHandler(persistent_storage) diff --git a/2023/grasp/09-pure_fabrication_before.py b/2023/grasp/09-pure_fabrication_before.py index 9bd26167..d91cd91d 100644 --- a/2023/grasp/09-pure_fabrication_before.py +++ b/2023/grasp/09-pure_fabrication_before.py @@ -20,7 +20,6 @@ def show_storage_records(self) -> None: def main() -> None: - payment = Payment() payment.pay(100) diff --git a/2023/jupyter/dice.py b/2023/jupyter/dice.py index e5c92251..20e3841c 100644 --- a/2023/jupyter/dice.py +++ b/2023/jupyter/dice.py @@ -9,4 +9,4 @@ def roll_n_dice(n_dice: int, n_sides: int) -> int: roll_n_d6 = functools.partial(roll_n_dice, n_sides=6) -roll_n_d20 = functools.partial(roll_n_dice, n_sides=20) \ No newline at end of file +roll_n_d20 = functools.partial(roll_n_dice, n_sides=20) diff --git a/2023/openai/text_to_speech.py b/2023/openai/text_to_speech.py index a743353e..530bd88e 100644 --- a/2023/openai/text_to_speech.py +++ b/2023/openai/text_to_speech.py @@ -30,7 +30,6 @@ def list_available_names() -> list[str]: def convert_text_to_mp3(message: str, voice_name: str, mp3_filename: str) -> None: - voices_response = requests.get( f"{BASE_URL}/v1/voices", params={"xi-api-key": API_KEY}, timeout=5 ) diff --git a/2023/rust/python/hello_world.py b/2023/rust/python/hello_world.py index da228e8c..1d5ef657 100644 --- a/2023/rust/python/hello_world.py +++ b/2023/rust/python/hello_world.py @@ -1,2 +1,2 @@ if __name__ == "__main__": - print("Hello, World") \ No newline at end of file + print("Hello, World") diff --git a/2023/rust/python/iot.py b/2023/rust/python/iot.py index 25ee91fd..0c8a2dd5 100644 --- a/2023/rust/python/iot.py +++ b/2023/rust/python/iot.py @@ -1,6 +1,7 @@ import abc import enum + class Connection: def __init__(self): self.name = None @@ -9,7 +10,11 @@ def __init__(self): @property def status(self): - return ConnectionStatus.CONNECTED if all([self.name, self.ip, self.port]) else ConnectionStatus.DISCONNECTED + return ( + ConnectionStatus.CONNECTED + if all([self.name, self.ip, self.port]) + else ConnectionStatus.DISCONNECTED + ) def connect(self, name, ip, port): self.name = name @@ -22,10 +27,10 @@ def disconnect(self): self.port = None def send(self, message): - print(f'Sent {message} to {self.name} at {self.ip}:{self.port}') + print(f"Sent {message} to {self.name} at {self.ip}:{self.port}") def receive(self): - return f'Received message from {self.name} at {self.ip}:{self.port}' + return f"Received message from {self.name} at {self.ip}:{self.port}" class IOTDevice(abc.ABC): @@ -63,17 +68,15 @@ def receive(self): return self.connection.receive() - class ConnectionStatus(enum.Enum): CONNECTED = 1 DISCONNECTED = 2 - -if __name__ == '__main__': +if __name__ == "__main__": connection = Connection() print(connection.status) - connection.connect('Arjan', 'localhost', 8080) + connection.connect("Arjan", "localhost", 8080) print(connection.status) connection.disconnect() - print(connection.status) \ No newline at end of file + print(connection.status) diff --git a/2023/rust/python/user.py b/2023/rust/python/user.py index 99007b9f..5513ab89 100644 --- a/2023/rust/python/user.py +++ b/2023/rust/python/user.py @@ -1,9 +1,10 @@ # Storing Data + Implementations + class User: def __init__(self, name, age): self.name = name - self.email = name + '@arjancodes.com' - + self.email = name + "@arjancodes.com" + def send_email(self, message): - print(f'Sent {message} to {self.email}') \ No newline at end of file + print(f"Sent {message} to {self.email}") diff --git a/2023/shellroast/before/src/UtilPackage/Algorithms.py b/2023/shellroast/before/src/UtilPackage/Algorithms.py index 3eadf556..49543410 100644 --- a/2023/shellroast/before/src/UtilPackage/Algorithms.py +++ b/2023/shellroast/before/src/UtilPackage/Algorithms.py @@ -1,99 +1,98 @@ import cryptography -from .EncodingApi import EncodingManager, ENCODE, DECODE # EncodingManager(Func: callable, s: str | bytes, Op: int) -from .HashingApi import Hasher # Hasher(HashingFunc: callable, s: str | bytes) -> str: +from .EncodingApi import ( + EncodingManager, + ENCODE, + DECODE, +) # EncodingManager(Func: callable, s: str | bytes, Op: int) +from .HashingApi import Hasher # Hasher(HashingFunc: callable, s: str | bytes) -> str: from binascii import hexlify, unhexlify from hashlib import ( - blake2b, - blake2s, - md5, - sha1, - sha224, - sha256, - sha384, - sha3_224, - sha3_256, - sha3_384, - sha3_512, - sha512, + blake2b, + blake2s, + md5, + sha1, + sha224, + sha256, + sha384, + sha3_224, + sha3_256, + sha3_384, + sha3_512, + sha512, ) from base64 import ( - a85decode, - a85encode, - - b16decode, - b16encode, - - b32decode, - b32encode, - - b32hexdecode, - b32hexencode, - - b64decode, - b64encode, - - b85decode, - b85encode + a85decode, + a85encode, + b16decode, + b16encode, + b32decode, + b32encode, + b32hexdecode, + b32hexencode, + b64decode, + b64encode, + b85decode, + b85encode, ) Encoding_Algorithms = [ - "aA85", - "base16", - "base32", - "base32hex", - "base64", - "base85", - "hexlify" + "aA85", + "base16", + "base32", + "base32hex", + "base64", + "base85", + "hexlify", ] ENCODING = { - "A85": [a85encode, a85decode], - "BASE16": [b16encode, b16decode], - "BASE32": [b32encode, b32decode], - "BASE32HEX": [b32hexencode, b32hexdecode], - "BASE64": [b64encode, b64decode], - "BASE85": [b85encode, b85decode], - "HEXLIFY": [hexlify, unhexlify], - "Doc": [ -f""" + "A85": [a85encode, a85decode], + "BASE16": [b16encode, b16decode], + "BASE32": [b32encode, b32decode], + "BASE32HEX": [b32hexencode, b32hexdecode], + "BASE64": [b64encode, b64decode], + "BASE85": [b85encode, b85decode], + "HEXLIFY": [hexlify, unhexlify], + "Doc": [ + f""" Syntax: Encode < {" | ".join(Encoding_Algorithms)} > """, -f""" + f""" Syntax: Decode < {" | ".join(Encoding_Algorithms)} > -""" - ] +""", + ], } Hashing_Algorithms = [ - "blake2s", - "blake2b", - "md5", - "sha1", - "sha224", - "sha256", - "sha384", - "sha3_224", - "sha3_256", - "sha3_384", - "sha3_512", - "sha512" + "blake2s", + "blake2b", + "md5", + "sha1", + "sha224", + "sha256", + "sha384", + "sha3_224", + "sha3_256", + "sha3_384", + "sha3_512", + "sha512", ] HASHING = { - "BLAKE2B": blake2b, - "BLAKE2S": blake2s, - "MD5": md5, - "SHA1": sha1, - "SHA224": sha224, - "SHA256": sha256, - "SHA384": sha384, - "SHA3_224": sha3_224, - "SHA3_256": sha3_256, - "SHA3_384": sha3_384, - "SHA3_512": sha3_512, - "SHA512": sha512, - "Doc": f""" + "BLAKE2B": blake2b, + "BLAKE2S": blake2s, + "MD5": md5, + "SHA1": sha1, + "SHA224": sha224, + "SHA256": sha256, + "SHA384": sha384, + "SHA3_224": sha3_224, + "SHA3_256": sha3_256, + "SHA3_384": sha3_384, + "SHA3_512": sha3_512, + "SHA512": sha512, + "Doc": f""" Syntax: Hash < {" | ".join(Hashing_Algorithms)} > - """ + """, } diff --git a/2023/shellroast/before/src/UtilPackage/EncodingApi.py b/2023/shellroast/before/src/UtilPackage/EncodingApi.py index b265e90e..6a729ebc 100644 --- a/2023/shellroast/before/src/UtilPackage/EncodingApi.py +++ b/2023/shellroast/before/src/UtilPackage/EncodingApi.py @@ -1,18 +1,25 @@ +ENCODE, DECODE = 0, 1 +def EncodingManager(Func: callable, Op: int) -> str: + assert Op in [0, 1], ( + "This Operation is not NotImplemented or incorrect!, index [%s]" % Op + ) + if Op == ENCODE: -ENCODE, DECODE = 0, 1 + def Func_(s: str | bytes): + assert isinstance(s, str) or isinstance(s, bytes), ( + "This function can not encode %s Object" % str(type(s)) + ) + if isinstance(s, str): + s = s.encode() + return Func(s).decode() + elif Op == DECODE: -def EncodingManager(Func: callable, Op: int) -> str: - assert Op in [0, 1], 'This Operation is not NotImplemented or incorrect!, index [%s]' % Op - if Op == ENCODE: - def Func_(s: str | bytes): - assert isinstance(s, str) or isinstance(s, bytes), "This function can not encode %s Object" % str(type(s)) - if isinstance(s, str): - s = s.encode() - return Func(s).decode() - elif Op == DECODE: - def Func_(s: str | bytes): - assert isinstance(s, str), "This function can not encode %s Object" % str(type(s)) - return Func(s).decode() - return Func_ + def Func_(s: str | bytes): + assert isinstance(s, str), "This function can not encode %s Object" % str( + type(s) + ) + return Func(s).decode() + + return Func_ diff --git a/2023/shellroast/before/src/UtilPackage/HashingApi.py b/2023/shellroast/before/src/UtilPackage/HashingApi.py index a895884f..5f187c0e 100644 --- a/2023/shellroast/before/src/UtilPackage/HashingApi.py +++ b/2023/shellroast/before/src/UtilPackage/HashingApi.py @@ -1,8 +1,9 @@ def Hasher(HashingFunc: callable, s: str | bytes) -> str: - assert isinstance(s, str) or isinstance(s, bytes), "This function can not hash a %s object" % str(type(s)) - - if isinstance(s, str): - s = s.encode() + assert isinstance(s, str) or isinstance(s, bytes), ( + "This function can not hash a %s object" % str(type(s)) + ) - return HashingFunc(s).hexdigest() + if isinstance(s, str): + s = s.encode() + return HashingFunc(s).hexdigest() diff --git a/2023/shellroast/before/src/UtilPackage/Shell.py b/2023/shellroast/before/src/UtilPackage/Shell.py index fa8168c4..a60f2cc3 100644 --- a/2023/shellroast/before/src/UtilPackage/Shell.py +++ b/2023/shellroast/before/src/UtilPackage/Shell.py @@ -1,74 +1,51 @@ - from colorama import Fore as f from dataclasses import dataclass @dataclass class Command: - CMD: str - argv: list[str] - def __repr__(self): return f'' - def getArgStr(self): return ' ,'.join([f'{i}\n' for i in self.argv]) - def __str__(self): return self.__repr__() - - -class Shell: - """ A basic shell out of the box. """ - - def shellInput(self, Tool: str = None) -> Command | bool: - """ Gets User input then returns a parsed command. """ - if Tool: - re_val = self.parseCmd(input(f" {f.YELLOW}[*][{Tool}] {f.CYAN}-> {f.WHITE}")) - if re_val: - return re_val - else: - return False - else: - re_val = self.parseCmd(input(f" {f.YELLOW}[*] {f.CYAN}-> {f.WHITE}")) - if re_val: - return re_val - else: - return False - - def parseCmd(self, cmd: str) -> Command | bool: - """ Parses a command and returns the command and its args. """ - if len(cmd) > 0: - if len(cmd.split(' ')) > 1: - return Command( - cmd.split(' ')[0].strip().upper(), - [i.strip() for i in cmd.split(' ')[1:]] - ) - else: - return Command( - cmd.split(' ')[0].strip().upper(), - [] - ) - else: - return False - - - - - - - - - - - - - - - - - - - - - - + CMD: str + argv: list[str] + def __repr__(self): + return f"" + def getArgStr(self): + return " ,".join([f"{i}\n" for i in self.argv]) + def __str__(self): + return self.__repr__() +class Shell: + """A basic shell out of the box.""" + + def shellInput(self, Tool: str = None) -> Command | bool: + """Gets User input then returns a parsed command.""" + if Tool: + re_val = self.parseCmd( + input(f" {f.YELLOW}[*][{Tool}] {f.CYAN}-> {f.WHITE}") + ) + if re_val: + return re_val + else: + return False + else: + re_val = self.parseCmd(input(f" {f.YELLOW}[*] {f.CYAN}-> {f.WHITE}")) + if re_val: + return re_val + else: + return False + + def parseCmd(self, cmd: str) -> Command | bool: + """Parses a command and returns the command and its args.""" + if len(cmd) > 0: + if len(cmd.split(" ")) > 1: + return Command( + cmd.split(" ")[0].strip().upper(), + [i.strip() for i in cmd.split(" ")[1:]], + ) + else: + return Command(cmd.split(" ")[0].strip().upper(), []) + else: + return False diff --git a/2023/shellroast/before/src/UtilPackage/Tool.py b/2023/shellroast/before/src/UtilPackage/Tool.py index 4d18a4c4..eaa3bef0 100644 --- a/2023/shellroast/before/src/UtilPackage/Tool.py +++ b/2023/shellroast/before/src/UtilPackage/Tool.py @@ -1,9 +1,7 @@ - from dataclasses import dataclass - @dataclass class Tool: - Name: str - FunctionMapping: dict \ No newline at end of file + Name: str + FunctionMapping: dict diff --git a/2023/shellroast/before/src/UtilPackage/UtilFuncs.py b/2023/shellroast/before/src/UtilPackage/UtilFuncs.py index daf9a1ec..3dd8d7d2 100644 --- a/2023/shellroast/before/src/UtilPackage/UtilFuncs.py +++ b/2023/shellroast/before/src/UtilPackage/UtilFuncs.py @@ -1,43 +1,43 @@ - from json import loads from dataclasses import dataclass - - @dataclass class Config: - ALGORITHMS: set - -def LoadConfig(configFilePath: str = "./Config.json") -> Config: - """ LOAD THE CONFIG File and sets the properties. """ - with open(configFilePath) as fp: - Data = loads(fp.read()) - return Config(**Data) - -def TestFunction(): pass - # Success = 0 - # ENCODE, DECODE = 0, 1 - # DidNotWorkObj = {} - # # Test. - # for i in ALGO.keys(): - # try: - # Encoded = ALGO[i][ENCODE]("String_") - # except Exception as e: - # print("ERROR: ", e) - # DidNotWorkObj[i] = [ENCODE] - # try: - # Decoded = ALGO[i][DECODE](Encoded) - # except Exception as e: - # print("ERROR: ", e) - # if i in DidNotWorkObj.keys(): - # DidNotWorkObj[i].append(DECODE) - # else: - # DidNotWorkObj[i] = [DECODE] - - # if DidNotWorkObj: - # print(DidNotWorkObj) - # else: - # print('sucess :)') + ALGORITHMS: set +def LoadConfig(configFilePath: str = "./Config.json") -> Config: + """LOAD THE CONFIG File and sets the properties.""" + with open(configFilePath) as fp: + Data = loads(fp.read()) + return Config(**Data) + + +def TestFunction(): + pass + + +# Success = 0 +# ENCODE, DECODE = 0, 1 +# DidNotWorkObj = {} +# # Test. +# for i in ALGO.keys(): +# try: +# Encoded = ALGO[i][ENCODE]("String_") +# except Exception as e: +# print("ERROR: ", e) +# DidNotWorkObj[i] = [ENCODE] +# try: +# Decoded = ALGO[i][DECODE](Encoded) +# except Exception as e: +# print("ERROR: ", e) +# if i in DidNotWorkObj.keys(): +# DidNotWorkObj[i].append(DECODE) +# else: +# DidNotWorkObj[i] = [DECODE] + +# if DidNotWorkObj: +# print(DidNotWorkObj) +# else: +# print('sucess :)') diff --git a/2023/shellroast/before/src/UtilPackage/__init__.py b/2023/shellroast/before/src/UtilPackage/__init__.py index c28ab557..94fc6357 100644 --- a/2023/shellroast/before/src/UtilPackage/__init__.py +++ b/2023/shellroast/before/src/UtilPackage/__init__.py @@ -1,5 +1,3 @@ from .Shell import Command, Shell from .UtilFuncs import LoadConfig from .Algorithms import * - - diff --git a/2023/shellroast/before/src/main.py b/2023/shellroast/before/src/main.py index 5b69642b..b52682d9 100644 --- a/2023/shellroast/before/src/main.py +++ b/2023/shellroast/before/src/main.py @@ -1,4 +1,3 @@ - """ Author: Hossin azmoud (Moody0101) @@ -11,14 +10,14 @@ from time import sleep, time from colorama import Fore as f from UtilPackage import ( - Shell, - Command, - ENCODING, - HASHING, - EncodingManager, # EncodingManager(Func: callable, s: str | bytes, Op: int) - ENCODE, - DECODE, - Hasher # Hasher(HashingFunc: callable, s: str | bytes) -> str: + Shell, + Command, + ENCODING, + HASHING, + EncodingManager, # EncodingManager(Func: callable, s: str | bytes, Op: int) + ENCODE, + DECODE, + Hasher, # Hasher(HashingFunc: callable, s: str | bytes) -> str: ) DOC = f"""{f.YELLOW} @@ -38,102 +37,99 @@ Hash only for help. """ + class Interface: - """ An interface that handles user interactions with the shell program """ - - def __init__(self) -> None: - # Shell initializer - self.shell = Shell() - - - self.DefaultCommands = { - 'EXIT': self.Exit, - 'HELP': self.Help, - "HASH": self.hashDoc, - "DECODE": self.DeDoc, - "ENCODE": self.EnDoc - } - - self.Commands = { - "HASH": self.hashVal, - "DECODE": self.Decode, - "ENCODE": self.Encode - } - - def hashDoc(self): - """ Displays doc for hashing """ - return HASHING["Doc"] - - def DeDoc(self): - """ Displays doc for decoding """ - return ENCODING["Doc"][DECODE] - - def EnDoc(self): - """ Displays doc for encoding """ - return ENCODING["Doc"][ENCODE] - - def Encode(self, Text, EncoderName): - if EncoderName.upper().strip() not in ENCODING.keys(): - print() - print(f" False algorithm name, {EncoderName}") - print(" you can only use from this list:") - for i in ENCODING.keys(): - print(" %s", i) - return - - # Get Encoder function - func_ = ENCODING[EncoderName.upper().strip()][ENCODE] - # Map the value - encode = EncodingManager(func_, ENCODE) - # return the value - return encode(Text) - - def Decode(self, Text, DecoderName): - if DecoderName.upper().strip() not in ENCODING.keys(): - print() - print(f" False algorithm name, {DecoderName}") - print(" you can only use from this list:") - for i in ENCODING.keys(): - print(" %s", i) - return - - # Get Encoder function - func_ = ENCODING[DecoderName.upper().strip()][DECODE] - # Map the value - decode = EncodingManager(func_, DECODE) - # return the value - return decode(Text) - - def hashVal(self, Text, HasherName): - if HasherName.upper().strip() not in HASHING.keys(): - print() - print(f" False algorithm name, {DecoderName}") - print(" you can only use from this list:") - for i in HASHING.keys(): - print(" %s", i) - return - - return Hasher(HASHING[HasherName.upper().strip()], Text) - - def showFuncs(self): - - if self.Tool: - for i in CONFIG[self.Tool].keys(): - print(" ", i) - - - def SetText(self, Text = None): - self.text = Text - - def Exit(self) -> None: - - for i in ['.', '..', '...']: - print(f" Exiting{i}", end="\r") - sleep(1) - exit(0) - - def Help(self): - return """ + """An interface that handles user interactions with the shell program""" + + def __init__(self) -> None: + # Shell initializer + self.shell = Shell() + + self.DefaultCommands = { + "EXIT": self.Exit, + "HELP": self.Help, + "HASH": self.hashDoc, + "DECODE": self.DeDoc, + "ENCODE": self.EnDoc, + } + + self.Commands = { + "HASH": self.hashVal, + "DECODE": self.Decode, + "ENCODE": self.Encode, + } + + def hashDoc(self): + """Displays doc for hashing""" + return HASHING["Doc"] + + def DeDoc(self): + """Displays doc for decoding""" + return ENCODING["Doc"][DECODE] + + def EnDoc(self): + """Displays doc for encoding""" + return ENCODING["Doc"][ENCODE] + + def Encode(self, Text, EncoderName): + if EncoderName.upper().strip() not in ENCODING.keys(): + print() + print(f" False algorithm name, {EncoderName}") + print(" you can only use from this list:") + for i in ENCODING.keys(): + print(" %s", i) + return + + # Get Encoder function + func_ = ENCODING[EncoderName.upper().strip()][ENCODE] + # Map the value + encode = EncodingManager(func_, ENCODE) + # return the value + return encode(Text) + + def Decode(self, Text, DecoderName): + if DecoderName.upper().strip() not in ENCODING.keys(): + print() + print(f" False algorithm name, {DecoderName}") + print(" you can only use from this list:") + for i in ENCODING.keys(): + print(" %s", i) + return + + # Get Encoder function + func_ = ENCODING[DecoderName.upper().strip()][DECODE] + # Map the value + decode = EncodingManager(func_, DECODE) + # return the value + return decode(Text) + + def hashVal(self, Text, HasherName): + if HasherName.upper().strip() not in HASHING.keys(): + print() + print(f" False algorithm name, {DecoderName}") + print(" you can only use from this list:") + for i in HASHING.keys(): + print(" %s", i) + return + + return Hasher(HASHING[HasherName.upper().strip()], Text) + + def showFuncs(self): + if self.Tool: + for i in CONFIG[self.Tool].keys(): + print(" ", i) + + def SetText(self, Text=None): + self.text = Text + + def Exit(self) -> None: + for i in [".", "..", "..."]: + print(f" Exiting{i}", end="\r") + sleep(1) + exit(0) + + def Help(self): + return """ To encode/Decode: Encode/Decode @@ -144,54 +140,35 @@ def Help(self): """ - def execute(self, command: Command) -> None: - """ """ - if command.CMD in self.DefaultCommands.keys(): - if len(command.argv) > 0: - print(self.Commands[command.CMD](*command.argv)) - else: - print(self.DefaultCommands[command.CMD]()) - elif command.CMD in self.Commands.keys(): - if len(command.argv) > 0: - print(self.Commands[command.CMD](*command.argv)) - else: - print(self.Commands[command.CMD]()) - - - - - - def run(self) -> None: - print() - print(DOC) - Interact = True - while Interact: - self.command = self.shell.shellInput() - if self.command: - self.execute(self.command) - else: - pass - -def main(): - Interface_ = Interface() - Interface_.run() - - -if __name__ == '__main__': - main() - - - - - - - - - - - - + def execute(self, command: Command) -> None: + """ """ + if command.CMD in self.DefaultCommands.keys(): + if len(command.argv) > 0: + print(self.Commands[command.CMD](*command.argv)) + else: + print(self.DefaultCommands[command.CMD]()) + elif command.CMD in self.Commands.keys(): + if len(command.argv) > 0: + print(self.Commands[command.CMD](*command.argv)) + else: + print(self.Commands[command.CMD]()) + + def run(self) -> None: + print() + print(DOC) + Interact = True + while Interact: + self.command = self.shell.shellInput() + if self.command: + self.execute(self.command) + else: + pass +def main(): + Interface_ = Interface() + Interface_.run() +if __name__ == "__main__": + main() diff --git a/2023/state/classic.py b/2023/state/classic.py index 4301fa86..d707373e 100644 --- a/2023/state/classic.py +++ b/2023/state/classic.py @@ -3,33 +3,25 @@ class DocumentState(Protocol): - def edit(self): - ... + def edit(self): ... - def review(self): - ... + def review(self): ... - def finalize(self): - ... + def finalize(self): ... class DocumentContext(Protocol): content: list[str] - def set_state(self, state: DocumentState) -> None: - ... + def set_state(self, state: DocumentState) -> None: ... - def edit(self): - ... + def edit(self): ... - def review(self): - ... + def review(self): ... - def finalize(self): - ... + def finalize(self): ... - def show_content(self): - ... + def show_content(self): ... @dataclass diff --git a/2023/strict/1_after.py b/2023/strict/1_after.py index 5e93b078..04aa03e0 100644 --- a/2023/strict/1_after.py +++ b/2023/strict/1_after.py @@ -27,16 +27,16 @@ def generate_breadcrumbs(geolocation: Geolocation) -> dict[str, str]: breadcrumbs: dict[str, str] = {} main_url = "https://myapi.com" if geolocation.postal_code: - breadcrumbs[ - "postal_code_url" - ] = f"{main_url}/postal_code/{geolocation.postal_code}/" + breadcrumbs["postal_code_url"] = ( + f"{main_url}/postal_code/{geolocation.postal_code}/" + ) if geolocation.city: city_slug = geolocation.city.lower().replace(" ", "-") breadcrumbs["city_url"] = f"{main_url}/region/{city_slug}/" if geolocation.province: - breadcrumbs[ - "province_url" - ] = f"{main_url}/region/province/{geolocation.province.lower()}/" + breadcrumbs["province_url"] = ( + f"{main_url}/region/province/{geolocation.province.lower()}/" + ) return breadcrumbs diff --git a/2023/strict/1_before.py b/2023/strict/1_before.py index da34d57f..e6791e85 100644 --- a/2023/strict/1_before.py +++ b/2023/strict/1_before.py @@ -28,16 +28,16 @@ def generate_breadcrumbs(location: Location) -> dict[str, str]: main_url = "https://myapi.com" if location.geolocation[0]: if location.geolocation[0].postal_code: - breadcrumbs[ - "postal_code_url" - ] = f"{main_url}/postal_code/{location.geolocation[0].postal_code}/" + breadcrumbs["postal_code_url"] = ( + f"{main_url}/postal_code/{location.geolocation[0].postal_code}/" + ) if location.geolocation[0].city: city_slug = location.geolocation[0].city.lower().replace(" ", "-") breadcrumbs["city_url"] = f"{main_url}/region/{city_slug}/" if location.geolocation[0].province: - breadcrumbs[ - "province_url" - ] = f"{main_url}/region/province/{location.geolocation[0].province.lower()}/" + breadcrumbs["province_url"] = ( + f"{main_url}/region/province/{location.geolocation[0].province.lower()}/" + ) return breadcrumbs diff --git a/2024/golroast/after/game.py b/2024/golroast/after/game.py index cc6dfa79..aacdcb5f 100644 --- a/2024/golroast/after/game.py +++ b/2024/golroast/after/game.py @@ -3,6 +3,7 @@ type Rule = Callable[[int, int], int | None] + class Game: def __init__(self, grid: Grid, rules: list[Rule] | None = None): self.grid = grid @@ -21,9 +22,9 @@ def update(self): alive_neighbors = self.grid.alive_neighbors(row, col) new_cell = self._apply_rules_to_cell(cell, alive_neighbors) new_grid.set_cell(row, col, new_cell) - + self.grid = new_grid - + def _apply_rules_to_cell(self, cell: int, alive_neighbors: int) -> int: for rule in self.rules: result = rule(cell, alive_neighbors) @@ -31,6 +32,6 @@ def _apply_rules_to_cell(self, cell: int, alive_neighbors: int) -> int: return result return cell - + def __str__(self): return str(self.grid) diff --git a/2024/golroast/after/visualizers/console.py b/2024/golroast/after/visualizers/console.py index 336eb673..e1720ae7 100644 --- a/2024/golroast/after/visualizers/console.py +++ b/2024/golroast/after/visualizers/console.py @@ -3,12 +3,10 @@ class Game(Protocol): - def update(self): - ... + def update(self): ... @property - def raw_grid(self) -> list[list[int]]: - ... + def raw_grid(self) -> list[list[int]]: ... def visualize_console(game: Game, generations: int, sleep_time: float): diff --git a/2024/golroast/after/visualizers/plot.py b/2024/golroast/after/visualizers/plot.py index ce43f35c..864c67e0 100644 --- a/2024/golroast/after/visualizers/plot.py +++ b/2024/golroast/after/visualizers/plot.py @@ -3,12 +3,10 @@ class Game(Protocol): - def update(self): - ... + def update(self): ... @property - def raw_grid(self) -> list[list[int]]: - ... + def raw_grid(self) -> list[list[int]]: ... def visualize_plot(game: Game, generations: int, sleep_time: float): diff --git a/2024/golroast/before/test.py b/2024/golroast/before/test.py index f4fcc2dd..c44fc43c 100644 --- a/2024/golroast/before/test.py +++ b/2024/golroast/before/test.py @@ -1,66 +1,124 @@ import unittest -from game_of_life import BirthRule, LonelyDeathRule, StayAliveRule, OverPopulateRule, Grid, Game +from game_of_life import ( + BirthRule, + LonelyDeathRule, + StayAliveRule, + OverPopulateRule, + Grid, + Game, +) class TestBirthRule(unittest.TestCase): def test_birth_rule_with_dead_cell_and_three_live_neighbors(self): - self.assertEqual(BirthRule.apply(0, 3), 1, "Dead cell with 3 live neighbors should be born.") + self.assertEqual( + BirthRule.apply(0, 3), 1, "Dead cell with 3 live neighbors should be born." + ) def test_birth_rule_with_dead_cell_and_two_live_neighbors(self): - self.assertIsNone(BirthRule.apply(0, 2), "Dead cell with 2 live neighbors should remain dead.") + self.assertIsNone( + BirthRule.apply(0, 2), "Dead cell with 2 live neighbors should remain dead." + ) def test_birth_rule_with_alive_cell(self): - self.assertIsNone(BirthRule.apply(1, 3), "Alive cell should not be affected by BirthRule.") + self.assertIsNone( + BirthRule.apply(1, 3), "Alive cell should not be affected by BirthRule." + ) def test_birth_rule_with_dead_cell_and_four_live_neighbors(self): - self.assertIsNone(BirthRule.apply(0, 4), "Dead cell with 4 live neighbors should remain dead.") + self.assertIsNone( + BirthRule.apply(0, 4), "Dead cell with 4 live neighbors should remain dead." + ) class TestLonelyDeathRule(unittest.TestCase): def test_lonely_death_rule_with_alive_cell_and_one_live_neighbor(self): - self.assertEqual(LonelyDeathRule.apply(1, 1), 0, "Alive cell with 1 live neighbor should die.") + self.assertEqual( + LonelyDeathRule.apply(1, 1), + 0, + "Alive cell with 1 live neighbor should die.", + ) def test_lonely_death_rule_with_alive_cell_and_zero_live_neighbors(self): - self.assertEqual(LonelyDeathRule.apply(1, 0), 0, "Alive cell with 0 live neighbors should die.") + self.assertEqual( + LonelyDeathRule.apply(1, 0), + 0, + "Alive cell with 0 live neighbors should die.", + ) def test_lonely_death_rule_with_alive_cell_and_two_live_neighbors(self): - self.assertIsNone(LonelyDeathRule.apply(1, 2), "Alive cell with 2 live neighbors should not be affected by LonelyDeathRule.") + self.assertIsNone( + LonelyDeathRule.apply(1, 2), + "Alive cell with 2 live neighbors should not be affected by LonelyDeathRule.", + ) def test_lonely_death_rule_with_dead_cell(self): - self.assertIsNone(LonelyDeathRule.apply(0, 1), "Dead cell should not be affected by LonelyDeathRule.") + self.assertIsNone( + LonelyDeathRule.apply(0, 1), + "Dead cell should not be affected by LonelyDeathRule.", + ) class TestStayAliveRule(unittest.TestCase): def test_stay_alive_rule_with_alive_cell_and_two_live_neighbors(self): - self.assertEqual(StayAliveRule.apply(1, 2), 1, "Alive cell with 2 live neighbors should stay alive.") + self.assertEqual( + StayAliveRule.apply(1, 2), + 1, + "Alive cell with 2 live neighbors should stay alive.", + ) def test_stay_alive_rule_with_alive_cell_and_three_live_neighbors(self): - self.assertEqual(StayAliveRule.apply(1, 3), 1, "Alive cell with 3 live neighbors should stay alive.") + self.assertEqual( + StayAliveRule.apply(1, 3), + 1, + "Alive cell with 3 live neighbors should stay alive.", + ) def test_stay_alive_rule_with_alive_cell_and_one_live_neighbor(self): - self.assertIsNone(StayAliveRule.apply(1, 1), - "Alive cell with 1 live neighbor should not be affected by StayAliveRule.") + self.assertIsNone( + StayAliveRule.apply(1, 1), + "Alive cell with 1 live neighbor should not be affected by StayAliveRule.", + ) def test_stay_alive_rule_with_alive_cell_and_four_live_neighbors(self): - self.assertIsNone(StayAliveRule.apply(1, 4), - "Alive cell with 4 live neighbors should not be affected by StayAliveRule.") + self.assertIsNone( + StayAliveRule.apply(1, 4), + "Alive cell with 4 live neighbors should not be affected by StayAliveRule.", + ) def test_stay_alive_rule_with_dead_cell(self): - self.assertIsNone(StayAliveRule.apply(0, 2), "Dead cell should not be affected by StayAliveRule.") + self.assertIsNone( + StayAliveRule.apply(0, 2), + "Dead cell should not be affected by StayAliveRule.", + ) class TestOverPopulateRule(unittest.TestCase): def test_over_populate_rule_with_alive_cell_and_four_live_neighbors(self): - self.assertEqual(OverPopulateRule.apply(1, 4), 0, "Alive cell with 4 live neighbors should die.") + self.assertEqual( + OverPopulateRule.apply(1, 4), + 0, + "Alive cell with 4 live neighbors should die.", + ) def test_over_populate_rule_with_alive_cell_and_five_live_neighbors(self): - self.assertEqual(OverPopulateRule.apply(1, 5), 0, "Alive cell with 5 live neighbors should die.") + self.assertEqual( + OverPopulateRule.apply(1, 5), + 0, + "Alive cell with 5 live neighbors should die.", + ) def test_over_populate_rule_with_alive_cell_and_three_live_neighbors(self): - self.assertIsNone(OverPopulateRule.apply(1, 3), "Alive cell with 3 live neighbors should not be affected by OverPopulateRule.") + self.assertIsNone( + OverPopulateRule.apply(1, 3), + "Alive cell with 3 live neighbors should not be affected by OverPopulateRule.", + ) def test_over_populate_rule_with_dead_cell(self): - self.assertIsNone(OverPopulateRule.apply(0, 4), "Dead cell should not be affected by OverPopulateRule.") + self.assertIsNone( + OverPopulateRule.apply(0, 4), + "Dead cell should not be affected by OverPopulateRule.", + ) class TestGrid(unittest.TestCase): @@ -84,21 +142,35 @@ def test_is_alive_with_dead_cell(self): def test_is_alive_with_alive_cell(self): self.grid.grid[1][1] = 1 - self.assertEqual(self.grid.is_alive(1, 1), 1, "Cell should be alive after being set.") + self.assertEqual( + self.grid.is_alive(1, 1), 1, "Cell should be alive after being set." + ) def test_is_alive_with_out_of_bounds_cell(self): - self.assertEqual(self.grid.is_alive(-1, 1), 0, "Out of bounds cell should be considered dead.") + self.assertEqual( + self.grid.is_alive(-1, 1), + 0, + "Out of bounds cell should be considered dead.", + ) def test_alive_neighbors_for_center_cell(self): self.grid.grid[0][1] = 1 self.grid.grid[1][0] = 1 self.grid.grid[1][2] = 1 - self.assertEqual(self.grid.alive_neighbors(1, 1), 3, "Center cell should have 3 alive neighbors.") + self.assertEqual( + self.grid.alive_neighbors(1, 1), + 3, + "Center cell should have 3 alive neighbors.", + ) def test_alive_neighbors_for_corner_cell(self): self.grid.grid[0][1] = 1 self.grid.grid[1][0] = 1 - self.assertEqual(self.grid.alive_neighbors(0, 0), 2, "Top-left corner cell should have 2 alive neighbors.") + self.assertEqual( + self.grid.alive_neighbors(0, 0), + 2, + "Top-left corner cell should have 2 alive neighbors.", + ) class TestGame(unittest.TestCase): @@ -106,16 +178,8 @@ def setUp(self): self.rules = [BirthRule, LonelyDeathRule, StayAliveRule, OverPopulateRule] def test_grid_1(self): - initial_state = [ - [0, 0, 0], - [1, 1, 1], - [0, 0, 0] - ] - expected_state = [ - [0, 1, 0], - [0, 1, 0], - [0, 1, 0] - ] + initial_state = [[0, 0, 0], [1, 1, 1], [0, 0, 0]] + expected_state = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] game = Game(3, 3, self.rules) game.grid.grid = initial_state @@ -123,18 +187,8 @@ def test_grid_1(self): self.assertEqual(game.grid.grid, expected_state) def test_grid_2(self): - initial_state = [ - [1, 1, 0, 0], - [1, 1, 0, 0], - [0, 0, 1, 1], - [0, 0, 1, 1] - ] - expected_state = [ - [1, 1, 0, 0], - [1, 0, 0, 0], - [0, 0, 0, 1], - [0, 0, 1, 1] - ] + initial_state = [[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, 1]] + expected_state = [[1, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 1]] game = Game(4, 4, self.rules) game.grid.grid = initial_state @@ -142,18 +196,10 @@ def test_grid_2(self): self.assertEqual(game.grid.grid, expected_state) def test_grid_3(self): - initial_state = [ - [1, 1, 1], - [1, 1, 1], - [0, 1, 0] - ] - expected_state = [ - [1, 0, 1], - [0, 0, 0], - [1, 1, 1] - ] + initial_state = [[1, 1, 1], [1, 1, 1], [0, 1, 0]] + expected_state = [[1, 0, 1], [0, 0, 0], [1, 1, 1]] game = Game(3, 3, self.rules) game.grid.grid = initial_state game.update() - self.assertEqual(game.grid.grid, expected_state) \ No newline at end of file + self.assertEqual(game.grid.grid, expected_state) diff --git a/2024/golroast/before/visualizer.py b/2024/golroast/before/visualizer.py index a3bafbaf..d188b233 100644 --- a/2024/golroast/before/visualizer.py +++ b/2024/golroast/before/visualizer.py @@ -4,7 +4,7 @@ def visualize(game, generations, sleep_time): fig, ax = plt.subplots() - game_display = ax.imshow(game.grid.grid, cmap='gray_r') + game_display = ax.imshow(game.grid.grid, cmap="gray_r") ax.set_xticks([]) ax.set_yticks([]) diff --git a/2024/rust_bindings/main_step1.py b/2024/rust_bindings/main_step1.py index 4401101c..227d054f 100644 --- a/2024/rust_bindings/main_step1.py +++ b/2024/rust_bindings/main_step1.py @@ -1,7 +1,9 @@ import pyo3_rust + def main(): print(pyo3_rust.sum_as_string(1, 2)) + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/2024/rust_bindings/main_step2.py b/2024/rust_bindings/main_step2.py index 4403e2ff..ce557f45 100644 --- a/2024/rust_bindings/main_step2.py +++ b/2024/rust_bindings/main_step2.py @@ -1,5 +1,6 @@ from pyo3_rust import Attachment, AttachmentType, Email + def main(): attachment = Attachment("attachment.txt", AttachmentType.File) print(attachment) @@ -7,6 +8,6 @@ def main(): print(email) email.send("Example@ArjanCodes.com") - + if __name__ == "__main__": main() diff --git a/2024/tuesday_tips/custom_exceptions/basic_example.py b/2024/tuesday_tips/custom_exceptions/basic_example.py index 6fc30346..2918d9aa 100644 --- a/2024/tuesday_tips/custom_exceptions/basic_example.py +++ b/2024/tuesday_tips/custom_exceptions/basic_example.py @@ -13,6 +13,7 @@ def age(self, value: int): raise ValueError("Age cannot be negative") self._age = value + def main() -> None: try: person = Person("John") @@ -21,5 +22,6 @@ def main() -> None: except ValueError as error: print(f"Error occurred: {error}") + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/2024/tuesday_tips/dependency_injection/before/email_sender.py b/2024/tuesday_tips/dependency_injection/before/email_sender.py index 5da1af17..588e7bdf 100644 --- a/2024/tuesday_tips/dependency_injection/before/email_sender.py +++ b/2024/tuesday_tips/dependency_injection/before/email_sender.py @@ -34,8 +34,5 @@ def send_email( return email_sender.send_email( to_address=to_address, subject=subject, body=body ) - - return MailChimp().send_email( - to_address=to_address, subject=subject, body=body - ) + return MailChimp().send_email(to_address=to_address, subject=subject, body=body) diff --git a/2024/tuesday_tips/dependency_injection/before/test_email_sender.py b/2024/tuesday_tips/dependency_injection/before/test_email_sender.py index e7e5b7f1..a7ea61b5 100644 --- a/2024/tuesday_tips/dependency_injection/before/test_email_sender.py +++ b/2024/tuesday_tips/dependency_injection/before/test_email_sender.py @@ -1,5 +1,6 @@ from email_sender import EmailSender, Service + def test_send_email_mailchimp(): email_sender = EmailSender() result = email_sender.send_email( diff --git a/2024/tuesday_tips/fail_fast/employee_portal/after_main.py b/2024/tuesday_tips/fail_fast/employee_portal/after_main.py index a727a6be..6b11084d 100644 --- a/2024/tuesday_tips/fail_fast/employee_portal/after_main.py +++ b/2024/tuesday_tips/fail_fast/employee_portal/after_main.py @@ -23,10 +23,15 @@ @app.post("/employees/", response_model=None) def create_employee(name: str, position: Position, salary: Decimal): if not isinstance(salary, float): - raise HTTPException(status_code=400, detail="Salary type or value is incorrect. Use decimal") - + raise HTTPException( + status_code=400, detail="Salary type or value is incorrect. Use decimal" + ) + if salary < 0: - raise HTTPException(status_code=400, detail="Salary value is incorrect. Give an positive decimal value") + raise HTTPException( + status_code=400, + detail="Salary value is incorrect. Give an positive decimal value", + ) create(connector, name, position, salary) return {"message": "Record inserted successfully"} @@ -50,12 +55,17 @@ def update_employee(employee_id: int, name: str, position: Position, salary: Dec existing_employee = show(connector, employee_id) if not existing_employee: raise HTTPException(status_code=404, detail="Employee not found") - + if not isinstance(salary, float): - raise HTTPException(status_code=400, detail="Salart type or value is incorrect. Use decimal") - + raise HTTPException( + status_code=400, detail="Salart type or value is incorrect. Use decimal" + ) + if salary < 0: - raise HTTPException(status_code=400, detail="Salart value is incorrect. Give an positive decimal value") + raise HTTPException( + status_code=400, + detail="Salart value is incorrect. Give an positive decimal value", + ) update(connector, employee_id, name, position, salary) return {"message": f"Employee with ID {employee_id} updated successfully"} diff --git a/2024/tuesday_tips/fail_fast/employee_portal/database/database.py b/2024/tuesday_tips/fail_fast/employee_portal/database/database.py index 271752d8..ceff345b 100644 --- a/2024/tuesday_tips/fail_fast/employee_portal/database/database.py +++ b/2024/tuesday_tips/fail_fast/employee_portal/database/database.py @@ -3,14 +3,11 @@ class DatabaseConnector(Protocol): - def connect(self, database: str) -> sqlite3.Connection: - ... + def connect(self, database: str) -> sqlite3.Connection: ... - def create_cursor(self, conn: sqlite3.Connection) -> sqlite3.Cursor: - ... + def create_cursor(self, conn: sqlite3.Connection) -> sqlite3.Cursor: ... - def close_connection(self, conn: sqlite3.Connection) -> None: - ... + def close_connection(self, conn: sqlite3.Connection) -> None: ... class SQLiteConnector(DatabaseConnector): diff --git a/2024/tuesday_tips/fail_fast/employee_portal/employees.py b/2024/tuesday_tips/fail_fast/employee_portal/employees.py index e61f4e9c..7b0561a4 100644 --- a/2024/tuesday_tips/fail_fast/employee_portal/employees.py +++ b/2024/tuesday_tips/fail_fast/employee_portal/employees.py @@ -5,6 +5,7 @@ DATABASE = "./examples.db" + def create( connector: DatabaseConnector, name: str, position: Position, salary: Decimal ): @@ -44,7 +45,9 @@ def index(connector: DatabaseConnector) -> list[tuple[int, str, str, Decimal]]: connector.close_connection(conn) -def show(connector: DatabaseConnector, employee_id: int) -> tuple[int, str, str, Decimal]: +def show( + connector: DatabaseConnector, employee_id: int +) -> tuple[int, str, str, Decimal]: conn = connector.connect(DATABASE) cursor = connector.create_cursor(conn) diff --git a/2024/tuesday_tips/fail_fast/employee_portal/payment.py b/2024/tuesday_tips/fail_fast/employee_portal/payment.py index 933264b2..97702909 100644 --- a/2024/tuesday_tips/fail_fast/employee_portal/payment.py +++ b/2024/tuesday_tips/fail_fast/employee_portal/payment.py @@ -1,21 +1,25 @@ from typing import Protocol from decimal import Decimal + # Define the PaymentStrategy interface using Protocol class PaymentStrategy(Protocol): def process_payment(self, amount: Decimal) -> None: pass + # Concrete implementation of PaymentStrategy for Credit Card payments class CreditCardPayment(PaymentStrategy): def process_payment(self, amount: Decimal) -> None: print(f"Processing credit card payment for ${amount}") + # Concrete implementation of PaymentStrategy for PayPal payments class RedeemBuddyPayment(PaymentStrategy): def process_payment(self, amount: Decimal) -> None: print(f"Processing PeyPel payment for ${amount}") + # Context class that uses a PaymentStrategy class PaymentProcessor: def __init__(self, payment_strategy: PaymentStrategy = RedeemBuddyPayment()): diff --git a/2024/tuesday_tips/fail_fast/employee_portal/position.py b/2024/tuesday_tips/fail_fast/employee_portal/position.py index c0191099..15e07ad1 100644 --- a/2024/tuesday_tips/fail_fast/employee_portal/position.py +++ b/2024/tuesday_tips/fail_fast/employee_portal/position.py @@ -2,8 +2,8 @@ class Position(StrEnum): - SOFTWARE_ENGINEER = 'Software Engineer' - DATA_SCIENTIST = 'Data Scientist' - PROJECT_MANAGER = 'Project Manager' - SYSTEM_ADMINISTRATOR = 'System Administrator' - BUSINESS_ANALYST = 'Business Analyst' + SOFTWARE_ENGINEER = "Software Engineer" + DATA_SCIENTIST = "Data Scientist" + PROJECT_MANAGER = "Project Manager" + SYSTEM_ADMINISTRATOR = "System Administrator" + BUSINESS_ANALYST = "Business Analyst" diff --git a/2024/tuesday_tips/fail_fast/tests/test_main.py b/2024/tuesday_tips/fail_fast/tests/test_main.py index c4241c5d..8d91d217 100644 --- a/2024/tuesday_tips/fail_fast/tests/test_main.py +++ b/2024/tuesday_tips/fail_fast/tests/test_main.py @@ -3,6 +3,7 @@ client = TestClient(app) + def test_successful_employee_update(): data = {"name": "John Doe", "position": "Software Engineer", "salary": 50000.0} response = client.put(url="/employees/1", params=data) @@ -11,6 +12,7 @@ def test_successful_employee_update(): assert response.status_code == 200 assert response.json() == {"message": "Employee with ID 1 updated successfully"} + def test_update_non_existing_employee(): data = {"name": "John Doe", "position": "Software Engineer", "salary": 50000.0} response = client.put(url="/employees/999", params=data) @@ -18,9 +20,9 @@ def test_update_non_existing_employee(): assert response.status_code == 404 assert response.json() == {"detail": "Employee not found"} + def test_invalid_update_missing_fields(): data = {"position": "Manager", "salary": 50000.0} response = client.put(url="/employees/1", params=data) assert response.status_code == 422 - diff --git a/2024/tuesday_tips/openai/async_main.py b/2024/tuesday_tips/openai/async_main.py index 36b3c3e0..abc43c2c 100644 --- a/2024/tuesday_tips/openai/async_main.py +++ b/2024/tuesday_tips/openai/async_main.py @@ -27,5 +27,5 @@ async def main() -> None: if __name__ == "__main__": - logging.basicConfig(level='INFO') + logging.basicConfig(level="INFO") asyncio.run(main()) diff --git a/2024/tuesday_tips/openai/client.py b/2024/tuesday_tips/openai/client.py index 17bb9166..4fc51345 100644 --- a/2024/tuesday_tips/openai/client.py +++ b/2024/tuesday_tips/openai/client.py @@ -2,20 +2,24 @@ from openai import AsyncOpenAI, OpenAI -SYSTEM_MESSAGE = "You are an translation tool that always translate to dutch" - +SYSTEM_MESSAGE = "You are an translation tool that always translate to dutch" + + def initialize_openai_client() -> OpenAI: api_key = os.getenv("OPENAI_API_KEY") if not api_key: - raise ValueError("No API key found. Please set your OPENAI_API_KEY in the .env file.") + raise ValueError( + "No API key found. Please set your OPENAI_API_KEY in the .env file." + ) return OpenAI(api_key=api_key) + def initialize__async_openai_client() -> AsyncOpenAI: api_key = os.getenv("OPENAI_API_KEY") if not api_key: - raise ValueError("No API key found. Please set your OPENAI_API_KEY in the .env file.") + raise ValueError( + "No API key found. Please set your OPENAI_API_KEY in the .env file." + ) return AsyncOpenAI(api_key=api_key) - - diff --git a/2024/tuesday_tips/openai/main.py b/2024/tuesday_tips/openai/main.py index 79a75a30..8bb553b9 100644 --- a/2024/tuesday_tips/openai/main.py +++ b/2024/tuesday_tips/openai/main.py @@ -7,6 +7,7 @@ load_dotenv() + def main() -> None: client = initialize_openai_client() diff --git a/2024/tuesday_tips/openai/models.py b/2024/tuesday_tips/openai/models.py index 45613ddb..572232d0 100644 --- a/2024/tuesday_tips/openai/models.py +++ b/2024/tuesday_tips/openai/models.py @@ -1,14 +1,16 @@ from enum import StrEnum + class OpenAIModels(StrEnum): GPT3_TURBO = "gpt-3.5-turbo-1106" GPT4 = "gpt-4" GPT4_TURBO_VISION = "gpt-4-vision-preview" GPT4_TURBO = "gpt-4-1106-preview" + MODEL_TOKEN_LIMITS = { OpenAIModels.GPT3_TURBO: 4096, # Assuming token limit for GPT-3.5 Turbo - OpenAIModels.GPT4: 8192, # Assuming token limit for GPT-4 + OpenAIModels.GPT4: 8192, # Assuming token limit for GPT-4 OpenAIModels.GPT4_TURBO_VISION: 128000, # Assuming token limit for GPT-4 Turbo Vision OpenAIModels.GPT4_TURBO: 128000, # Assuming token limit for GPT-4 Turbo } diff --git a/2024/tuesday_tips/openai/tip_1/chunker.py b/2024/tuesday_tips/openai/tip_1/chunker.py index 9dbc6411..3e0c7021 100644 --- a/2024/tuesday_tips/openai/tip_1/chunker.py +++ b/2024/tuesday_tips/openai/tip_1/chunker.py @@ -19,7 +19,7 @@ def concatenate_sentences(sentences: list[str], limit: int) -> list[str]: extra_sentence = tmp.pop() text = "".join(tmp) concatenated_sentences.append(text) - tmp=[extra_sentence] + tmp = [extra_sentence] return concatenated_sentences diff --git a/2024/tuesday_tips/openai/tip_1/encoding.py b/2024/tuesday_tips/openai/tip_1/encoding.py index e130413f..8833344c 100644 --- a/2024/tuesday_tips/openai/tip_1/encoding.py +++ b/2024/tuesday_tips/openai/tip_1/encoding.py @@ -3,7 +3,9 @@ def get_number_of_tokens(text: str, model: OpenAIModels) -> int: - encoding = tiktoken.get_encoding("cl100k_base") # This is going to be an problem, better if we can store it in the Enum + encoding = tiktoken.get_encoding( + "cl100k_base" + ) # This is going to be an problem, better if we can store it in the Enum tokens = encoding.encode(text) diff --git a/2024/tuesday_tips/openai/tip_2/rate_limiter.py b/2024/tuesday_tips/openai/tip_2/rate_limiter.py index 1e59c929..ff6456f8 100644 --- a/2024/tuesday_tips/openai/tip_2/rate_limiter.py +++ b/2024/tuesday_tips/openai/tip_2/rate_limiter.py @@ -2,13 +2,13 @@ from functools import wraps from typing import Any, Callable + def rate_limit(max_calls: int, period: float = 1.0) -> Callable[[Any], Any]: def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]: timestamps: list[float] = [] @wraps(func) - def wrapper(*args: Any, **kwargs: Any)-> Any: - + def wrapper(*args: Any, **kwargs: Any) -> Any: now = time.time() timestamps[:] = [t for t in timestamps if now - t < period] @@ -22,4 +22,5 @@ def wrapper(*args: Any, **kwargs: Any)-> Any: return wrapper(*args, **kwargs) return wrapper - return decorator \ No newline at end of file + + return decorator diff --git a/2024/tuesday_tips/openai/tip_2/request_handler.py b/2024/tuesday_tips/openai/tip_2/request_handler.py index 1f8ddab4..534211e7 100644 --- a/2024/tuesday_tips/openai/tip_2/request_handler.py +++ b/2024/tuesday_tips/openai/tip_2/request_handler.py @@ -5,7 +5,8 @@ from models import MODEL_TOKEN_LIMITS, OpenAIModels from tip_2.rate_limiter import rate_limit -@rate_limit(max_calls=2, period=5) + +@rate_limit(max_calls=2, period=5) def send_request(query: str, model: OpenAIModels, client: OpenAI) -> str | None: response = client.chat.completions.create( model=model.value, @@ -17,6 +18,7 @@ def send_request(query: str, model: OpenAIModels, client: OpenAI) -> str | None: return response.choices[0].message.content + def handle_request(query: str, model: OpenAIModels, client: OpenAI) -> str: number_of_tokens: int = get_number_of_tokens(query, model) diff --git a/2024/tuesday_tips/openai/tip_3/request_handler.py b/2024/tuesday_tips/openai/tip_3/request_handler.py index 01348f3d..80419731 100644 --- a/2024/tuesday_tips/openai/tip_3/request_handler.py +++ b/2024/tuesday_tips/openai/tip_3/request_handler.py @@ -9,10 +9,10 @@ from tip_3.timer import timer - @rate_limit(max_calls=10, period=10) -async def send_request_async(query: str, model: OpenAIModels, client: AsyncOpenAI) -> str | None: - +async def send_request_async( + query: str, model: OpenAIModels, client: AsyncOpenAI +) -> str | None: response = await client.chat.completions.create( model=model.value, messages=[ @@ -21,7 +21,8 @@ async def send_request_async(query: str, model: OpenAIModels, client: AsyncOpenA ], ) - return response.choices[0].message.content + return response.choices[0].message.content + @timer async def handle_request(query: str, model: OpenAIModels, client: AsyncOpenAI) -> str: @@ -36,4 +37,3 @@ async def handle_request(query: str, model: OpenAIModels, client: AsyncOpenAI) - *(send_request_async(client=client, model=model, query=part) for part in parts) ) return "".join(responses) - diff --git a/2024/tuesday_tips/openai/tip_3/timer.py b/2024/tuesday_tips/openai/tip_3/timer.py index 914c3dad..8b827292 100644 --- a/2024/tuesday_tips/openai/tip_3/timer.py +++ b/2024/tuesday_tips/openai/tip_3/timer.py @@ -8,7 +8,9 @@ from models import OpenAIModels -def timer(func: Callable[[str, OpenAIModels, AsyncOpenAI], str]) -> Callable[[str, OpenAIModels, AsyncOpenAI], str]: +def timer( + func: Callable[[str, OpenAIModels, AsyncOpenAI], str], +) -> Callable[[str, OpenAIModels, AsyncOpenAI], str]: @functools.wraps(func) async def wrapper(*args, **kwargs): start = time.time() @@ -16,17 +18,18 @@ async def wrapper(*args, **kwargs): result = await func(*args, **kwargs) except Exception: finish = time.time() - start - logging.info('%s failed in %.2f', func, finish) + logging.info("%s failed in %.2f", func, finish) raise else: finish = time.time() - start model: OpenAIModels = kwargs["model"] if model: - logging.info(f'{func} with model: {model.name} succeeded in {finish:.2f}') + logging.info( + f"{func} with model: {model.name} succeeded in {finish:.2f}" + ) else: - logging.info(f'{func} succeeded in {finish:.2f}') + logging.info(f"{func} succeeded in {finish:.2f}") + return result - return result - return wrapper diff --git a/2024/tuesday_tips/regex/benchmark/main.py b/2024/tuesday_tips/regex/benchmark/main.py index 994eccca..559b45ba 100644 --- a/2024/tuesday_tips/regex/benchmark/main.py +++ b/2024/tuesday_tips/regex/benchmark/main.py @@ -4,7 +4,7 @@ def main() -> None: email = "support@arjancodes.com" - + validate_email(EMAIL_REGEX_1, email) diff --git a/2024/tuesday_tips/regex/benchmark/timer.py b/2024/tuesday_tips/regex/benchmark/timer.py index 126a4e07..7546b437 100644 --- a/2024/tuesday_tips/regex/benchmark/timer.py +++ b/2024/tuesday_tips/regex/benchmark/timer.py @@ -1,11 +1,15 @@ import time from typing import Any, Callable -def timer_decorator(func: Callable[..., Any]) -> Callable[...,Any]: + +def timer_decorator(func: Callable[..., Any]) -> Callable[..., Any]: def wrapper(*args: Any, **kwargs: Any) -> Any: start_time = time.time() result = func(*args, **kwargs) end_time = time.time() - print(f"{func.__name__} with input {args[-1]} took {end_time - start_time:.5f} seconds to execute.") + print( + f"{func.__name__} with input {args[-1]} took {end_time - start_time:.5f} seconds to execute." + ) return result + return wrapper diff --git a/2024/tuesday_tips/regex/benchmark/validator.py b/2024/tuesday_tips/regex/benchmark/validator.py index a7be7556..8fc6eecf 100644 --- a/2024/tuesday_tips/regex/benchmark/validator.py +++ b/2024/tuesday_tips/regex/benchmark/validator.py @@ -1,6 +1,7 @@ import re from timer import timer_decorator + @timer_decorator def validate_email(regex: str, email: str) -> re.Match[str] | None: - return re.match(regex, email) \ No newline at end of file + return re.match(regex, email) diff --git a/2024/tuesday_tips/regex/dashboard/src/components/layout.py b/2024/tuesday_tips/regex/dashboard/src/components/layout.py index b198d4ce..15efebff 100644 --- a/2024/tuesday_tips/regex/dashboard/src/components/layout.py +++ b/2024/tuesday_tips/regex/dashboard/src/components/layout.py @@ -20,7 +20,7 @@ def create_layout(app: Dash) -> html.Div: line_chart.render(app, data), html.Div( className="cardbox", - children = [ + children=[ html.Li( id=key, className="card", @@ -30,7 +30,7 @@ def create_layout(app: Dash) -> html.Div: ], ) for key in data - ] + ], ), ], ) diff --git a/2024/tuesday_tips/regex/dashboard/src/data/reader.py b/2024/tuesday_tips/regex/dashboard/src/data/reader.py index 82409c43..ae19bf31 100644 --- a/2024/tuesday_tips/regex/dashboard/src/data/reader.py +++ b/2024/tuesday_tips/regex/dashboard/src/data/reader.py @@ -1,5 +1,6 @@ import pandas as pd + def load_json(file_path: str) -> pd.DataFrame: """ Reads a JSON file and creates a pandas DataFrame. diff --git a/2024/tuesday_tips/regex/dashboard/src/formatter.py b/2024/tuesday_tips/regex/dashboard/src/formatter.py index 37a33c65..13992a0b 100644 --- a/2024/tuesday_tips/regex/dashboard/src/formatter.py +++ b/2024/tuesday_tips/regex/dashboard/src/formatter.py @@ -1,2 +1,2 @@ def title_case(value: str) -> str: - return value.replace("_", " ").replace("-", " ").capitalize() \ No newline at end of file + return value.replace("_", " ").replace("-", " ").capitalize() diff --git a/2024/tuesday_tips/testing_async/main.py b/2024/tuesday_tips/testing_async/main.py index 06216c26..b3327353 100644 --- a/2024/tuesday_tips/testing_async/main.py +++ b/2024/tuesday_tips/testing_async/main.py @@ -17,4 +17,3 @@ async def main() -> None: if __name__ == "__main__": asyncio.run(main()) - diff --git a/2024/tuesday_tips/testing_async/test/fixture_based_fetch_event_test.py b/2024/tuesday_tips/testing_async/test/fixture_based_fetch_event_test.py index 283a7ec2..ec292048 100644 --- a/2024/tuesday_tips/testing_async/test/fixture_based_fetch_event_test.py +++ b/2024/tuesday_tips/testing_async/test/fixture_based_fetch_event_test.py @@ -6,11 +6,13 @@ from fetch_event import fetch_event + @pytest.fixture async def session(): with patch("aiohttp.ClientSession") as mock: yield mock + @pytest.fixture def event_loop(): asyncio.get_event_loop_policy().set_event_loop(asyncio.new_event_loop()) @@ -18,10 +20,11 @@ def event_loop(): yield loop loop.close() + def test_fetch_event(session: ClientSession, event_loop: asyncio.AbstractEventLoop): results = event_loop.run_until_complete(fetch_event(session=session, event_id="1")) assert len(results) > 0 - + def test_fetch_multiple_events_with_custom_event_loop( session: ClientSession, event_loop: asyncio.AbstractEventLoop @@ -29,4 +32,3 @@ def test_fetch_multiple_events_with_custom_event_loop( tasks = [fetch_event(session=session, event_id=str(i)) for i in range(1, 5)] results = event_loop.run_until_complete(asyncio.gather(*tasks)) assert len(results) == 4 -