Skip to content
Open

Lab33 #141

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added reports/Melnik/lab3/rep/rep3.pdf
Binary file not shown.
93 changes: 93 additions & 0 deletions reports/Melnik/lab3/src/task_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
"""Модуль реализует кофейный автомат (паттерн Factory Method)."""

from abc import ABC, abstractmethod


class Coffee(ABC): # pylint: disable=too-few-public-methods
"""Абстрактный класс кофейного напитка."""

@abstractmethod
def prepare(self) -> str:
"""Приготовить напиток."""


class Espresso(Coffee): # pylint: disable=too-few-public-methods
"""Класс напитка Espresso."""

def prepare(self) -> str:
"""Приготовление эспрессо."""
return "Готовится Espresso"


class Americano(Coffee): # pylint: disable=too-few-public-methods
"""Класс напитка Americano."""

def prepare(self) -> str:
"""Приготовление американо."""
return "Готовится Americano"


class Latte(Coffee): # pylint: disable=too-few-public-methods
"""Класс напитка Latte."""

def prepare(self) -> str:
"""Приготовление латте."""
return "Готовится Latte"


class Cappuccino(Coffee): # pylint: disable=too-few-public-methods
"""Класс напитка Cappuccino."""

def prepare(self) -> str:
"""Приготовление капучино."""
return "Готовится Cappuccino"


class Mocha(Coffee): # pylint: disable=too-few-public-methods
"""Класс напитка Mocha."""

def prepare(self) -> str:
"""Приготовление мокка."""
return "Готовится Mocha"


class CoffeeFactory: # pylint: disable=too-few-public-methods
"""Фабрика кофейных напитков."""

@staticmethod
def create_coffee(coffee_type: str) -> Coffee:
"""Создать объект кофе."""
coffees = {
"espresso": Espresso,
"americano": Americano,
"latte": Latte,
"cappuccino": Cappuccino,
"mocha": Mocha,
}

coffee_class = coffees.get(coffee_type.lower())

if coffee_class is None:
raise ValueError("Неизвестный тип кофе")

return coffee_class()


class CoffeeMachine: # pylint: disable=too-few-public-methods
"""Класс кофейного автомата."""

def order(self, coffee_type: str) -> str:
"""Заказать кофе."""
coffee = CoffeeFactory.create_coffee(coffee_type)
return coffee.prepare()


def main() -> None:
"""Точка входа."""
machine = CoffeeMachine()
coffee_type = input("Введите тип кофе: ")
print(machine.order(coffee_type))


if __name__ == "__main__":
main()
50 changes: 50 additions & 0 deletions reports/Melnik/lab3/src/task_2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""Модуль реализует адаптацию аналоговых часов к цифровым (Adapter)."""

from abc import ABC, abstractmethod


class DigitalClockInterface(ABC): # pylint: disable=too-few-public-methods
"""Интерфейс цифровых часов."""

@abstractmethod
def get_time(self) -> str:
"""Получить время."""


class AnalogClock: # pylint: disable=too-few-public-methods
"""Аналоговые часы."""

def __init__(self, hour_angle: float, minute_angle: float) -> None:
"""Инициализация углов стрелок."""
self.hour_angle = hour_angle
self.minute_angle = minute_angle


class ClockAdapter(DigitalClockInterface): # pylint: disable=too-few-public-methods
"""Адаптер аналоговых часов."""

def __init__(self, analog_clock: AnalogClock) -> None:
"""Инициализация адаптера."""
self.analog_clock = analog_clock

def get_time(self) -> str:
"""Вернуть цифровое время."""
hour = int(self.analog_clock.hour_angle / 30) % 12
minute = int(self.analog_clock.minute_angle / 6)

return f"{hour:02d}:{minute:02d}"


def main() -> None:
"""Точка входа."""
hour_angle = float(input("Введите угол часовой стрелки: "))
minute_angle = float(input("Введите угол минутной стрелки: "))

analog = AnalogClock(hour_angle, minute_angle)
adapter = ClockAdapter(analog)

print("Цифровое время:", adapter.get_time())


if __name__ == "__main__":
main()
77 changes: 77 additions & 0 deletions reports/Melnik/lab3/src/task_3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""Модуль реализует настраиваемый калькулятор (Command)."""

from abc import ABC, abstractmethod


class Command(ABC): # pylint: disable=too-few-public-methods
"""Интерфейс команды."""

@abstractmethod
def execute(self, a: float, b: float) -> float:
"""Выполнить команду."""


class AddCommand(Command): # pylint: disable=too-few-public-methods
"""Команда сложения."""

def execute(self, a: float, b: float) -> float:
"""Сложение."""
return a + b


class SubtractCommand(Command): # pylint: disable=too-few-public-methods
"""Команда вычитания."""

def execute(self, a: float, b: float) -> float:
"""Вычитание."""
return a - b


class MultiplyCommand(Command): # pylint: disable=too-few-public-methods
"""Команда умножения."""

def execute(self, a: float, b: float) -> float:
"""Умножение."""
return a * b


class Button: # pylint: disable=too-few-public-methods
"""Кнопка калькулятора."""

def __init__(self, command: Command) -> None:
"""Инициализация кнопки."""
self.command = command

def press(self, a: float, b: float) -> float:
"""Нажать кнопку."""
return self.command.execute(a, b)

def set_command(self, command: Command) -> None:
"""Изменить команду."""
self.command = command


class Calculator: # pylint: disable=too-few-public-methods
"""Калькулятор."""

def __init__(self) -> None:
"""Инициализация."""
self.add_button = Button(AddCommand())
self.sub_button = Button(SubtractCommand())
self.custom_button = Button(MultiplyCommand())


def main() -> None:
"""Точка входа."""
calc = Calculator()

a = float(input("Введите первое число: "))
b = float(input("Введите второе число: "))

print("Сложение:", calc.add_button.press(a, b))
print("Вычитание:", calc.sub_button.press(a, b))
print("Умножение:", calc.custom_button.press(a, b))


if __name__ == "__main__":
main()
Binary file added reports/Melnik/lab4/rep/rep.pdf
Binary file not shown.
Empty file.
87 changes: 87 additions & 0 deletions reports/Melnik/lab4/src/task.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# pylint: disable=invalid-name
"""
Скрипт для автоматического отслеживания новых релизов в репозиториях GitHub.
Использует GitHub REST API и сохраняет состояние в JSON файл.
"""

import json
import os
import requests

STATE_FILE = "last_releases.json"


def get_latest_release(repo: str) -> dict:
"""
Получает информацию о последнем релизе репозитория через GitHub API.
"""
url = f"https://api.github.com/repos/{repo}/releases/latest"
headers = {"Accept": "application/vnd.github.v3+json"}

try:
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 200:
return response.json()
return None
except requests.exceptions.RequestException as err:
print(f"Ошибка сети для {repo}: {err}")
return None


def load_state() -> dict:
"""Загружает данные о прошлых проверках из JSON файла."""
if os.path.exists(STATE_FILE):
with open(STATE_FILE, "r", encoding="utf-8") as f:
return json.load(f)
return {}


def save_state(state: dict) -> None:
"""Сохраняет текущие данные о версиях в JSON файл."""
with open(STATE_FILE, "w", encoding="utf-8") as f:
json.dump(state, f, ensure_ascii=False, indent=4)


def main() -> None:
"""Основная логика мониторинга обновлений."""
user_input = input("Введите репозитории для отслеживания (через запятую): ")
repo_list = [r.strip() for r in user_input.split(",") if r.strip()]

if not repo_list:
print("Список репозиториев пуст.")
return

last_state = load_state()
new_state = last_state.copy()

for repo in repo_list:
print(f"\nПроверяем обновления для {repo}...")
release_data = get_latest_release(repo)

if not release_data:
print(f"Информация о релизах в {repo} не найдена.")
continue

version = release_data.get("tag_name")
last_seen_version = last_state.get(repo)

if version != last_seen_version:
date = release_data.get("published_at", "не указана")[:10]
link = release_data.get("html_url")
body = release_data.get("body", "Нет описания")
changelog = "\n".join(body.splitlines()[:5])

print(f"✅ НАЙДЕН НОВЫЙ РЕЛИЗ: {version} ({date})")
print(f" Ссылка: {link}")
print(f" Основные изменения:\n{changelog}...")

new_state[repo] = version
else:
print(f"😴 Новых обновлений для {repo} нет (текущая: {version}).")

save_state(new_state)
print("\nПроверка завершена. Состояние сохранено в last_releases.json")


if __name__ == "__main__":
main()
Loading