id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
179,835
import codecs import os import re import typing as t import winreg from dataclasses import dataclass from module.device.platform.utils import cached_property, iter_folder from module.device.platform.emulator_base import EmulatorBase, EmulatorInstanceBase, EmulatorManagerBase class RegValue: name: str value: str typ: int The provided code snippet includes necessary dependencies for implementing the `list_key` function. Write a Python function `def list_key(reg) -> t.List[RegValue]` to solve the following problem: List all values in a reg key Here is the function: def list_key(reg) -> t.List[RegValue]: """ List all values in a reg key """ rows = [] index = 0 try: while 1: value = winreg.EnumKey(reg, index) index += 1 rows.append(value) except OSError: pass return rows
List all values in a reg key
179,836
import codecs import os import re import typing as t import winreg from dataclasses import dataclass from module.device.platform.utils import cached_property, iter_folder from module.device.platform.emulator_base import EmulatorBase, EmulatorInstanceBase, EmulatorManagerBase def abspath(path): return os.path.abspath(path).replace('\\', '/')
null
179,837
import os import re import typing as t from dataclasses import dataclass from module.device.platform.utils import cached_property, iter_folder def abspath(path): return os.path.abspath(path).replace('\\', '/')
null
179,838
import os import re import typing as t from dataclasses import dataclass from module.device.platform.utils import cached_property, iter_folder The provided code snippet includes necessary dependencies for implementing the `get_serial_pair` function. Write a Python function `def get_serial_pair(serial)` to solve the following problem: Args: serial (str): Returns: str, str: `127.0.0.1:5555+{X}` and `emulator-5554+{X}`, 0 <= X <= 32 Here is the function: def get_serial_pair(serial): """ Args: serial (str): Returns: str, str: `127.0.0.1:5555+{X}` and `emulator-5554+{X}`, 0 <= X <= 32 """ if serial.startswith('127.0.0.1:'): try: port = int(serial[10:]) if 5555 <= port <= 5555 + 32: return f'127.0.0.1:{port}', f'emulator-{port - 1}' except (ValueError, IndexError): pass if serial.startswith('emulator-'): try: port = int(serial[9:]) if 5554 <= port <= 5554 + 32: return f'127.0.0.1:{port + 1}', f'emulator-{port}' except (ValueError, IndexError): pass return None, None
Args: serial (str): Returns: str, str: `127.0.0.1:5555+{X}` and `emulator-5554+{X}`, 0 <= X <= 32
179,839
import ctypes import re import subprocess import psutil from deploy.Windows.utils import DataProcessInfo from module.base.decorator import run_once from module.base.timer import Timer from module.device.connection import AdbDeviceWithStatus from module.device.platform.platform_base import PlatformBase from module.device.platform.emulator_windows import Emulator, EmulatorInstance, EmulatorManager from module.logger import logger def get_focused_window(): return ctypes.windll.user32.GetForegroundWindow()
null
179,840
import ctypes import re import subprocess import psutil from deploy.Windows.utils import DataProcessInfo from module.base.decorator import run_once from module.base.timer import Timer from module.device.connection import AdbDeviceWithStatus from module.device.platform.platform_base import PlatformBase from module.device.platform.emulator_windows import Emulator, EmulatorInstance, EmulatorManager from module.logger import logger def set_focus_window(hwnd): ctypes.windll.user32.SetForegroundWindow(hwnd)
null
179,841
import ctypes import re import subprocess import psutil from deploy.Windows.utils import DataProcessInfo from module.base.decorator import run_once from module.base.timer import Timer from module.device.connection import AdbDeviceWithStatus from module.device.platform.platform_base import PlatformBase from module.device.platform.emulator_windows import Emulator, EmulatorInstance, EmulatorManager from module.logger import logger def minimize_window(hwnd): ctypes.windll.user32.ShowWindow(hwnd, 6)
null
179,842
import ctypes import re import subprocess import psutil from deploy.Windows.utils import DataProcessInfo from module.base.decorator import run_once from module.base.timer import Timer from module.device.connection import AdbDeviceWithStatus from module.device.platform.platform_base import PlatformBase from module.device.platform.emulator_windows import Emulator, EmulatorInstance, EmulatorManager from module.logger import logger The provided code snippet includes necessary dependencies for implementing the `get_window_title` function. Write a Python function `def get_window_title(hwnd)` to solve the following problem: Returns the window title as a string. Here is the function: def get_window_title(hwnd): """Returns the window title as a string.""" text_len_in_characters = ctypes.windll.user32.GetWindowTextLengthW(hwnd) string_buffer = ctypes.create_unicode_buffer( text_len_in_characters + 1) # +1 for the \0 at the end of the null-terminated string. ctypes.windll.user32.GetWindowTextW(hwnd, string_buffer, text_len_in_characters + 1) return string_buffer.value
Returns the window title as a string.
179,843
import ctypes import re import subprocess import psutil from deploy.Windows.utils import DataProcessInfo from module.base.decorator import run_once from module.base.timer import Timer from module.device.connection import AdbDeviceWithStatus from module.device.platform.platform_base import PlatformBase from module.device.platform.emulator_windows import Emulator, EmulatorInstance, EmulatorManager from module.logger import logger def flash_window(hwnd, flash=True): ctypes.windll.user32.FlashWindow(hwnd, flash)
null
179,844
import collections import itertools import sys from module.base.timer import Timer from module.device.app_control import AppControl from module.device.control import Control from module.device.screenshot import Screenshot from module.exception import ( EmulatorNotRunningError, GameNotRunningError, GameStuckError, GameTooManyClickError, RequestHumanTakeover ) from module.logger import logger logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) logger.addHandler(console_hdlr) logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) The provided code snippet includes necessary dependencies for implementing the `show_function_call` function. Write a Python function `def show_function_call()` to solve the following problem: INFO 21:07:31.554 │ Function calls: <string> L1 <module> spawn.py L116 spawn_main() spawn.py L129 _main() process.py L314 _bootstrap() process.py L108 run() process_manager.py L149 run_process() alas.py L285 loop() alas.py L69 run() src.py L55 rogue() rogue.py L36 run() rogue.py L18 rogue_once() entry.py L335 rogue_world_enter() path.py L193 rogue_path_select() Here is the function: def show_function_call(): """ INFO 21:07:31.554 │ Function calls: <string> L1 <module> spawn.py L116 spawn_main() spawn.py L129 _main() process.py L314 _bootstrap() process.py L108 run() process_manager.py L149 run_process() alas.py L285 loop() alas.py L69 run() src.py L55 rogue() rogue.py L36 run() rogue.py L18 rogue_once() entry.py L335 rogue_world_enter() path.py L193 rogue_path_select() """ import os import traceback stack = traceback.extract_stack() func_list = [] for row in stack: filename, line_number, function_name, _ = row filename = os.path.basename(filename) # /tasks/character/switch.py:64 character_update() func_list.append([filename, str(line_number), function_name]) max_filename = max([len(row[0]) for row in func_list]) max_linenum = max([len(row[1]) for row in func_list]) + 1 def format_(file, line, func): file = file.rjust(max_filename, " ") line = f'L{line}'.rjust(max_linenum, " ") if not func.startswith('<'): func = f'{func}()' return f'{file} {line} {func}' func_list = [f'\n{format_(*row)}' for row in func_list] logger.info('Function calls:' + ''.join(func_list))
INFO 21:07:31.554 │ Function calls: <string> L1 <module> spawn.py L116 spawn_main() spawn.py L129 _main() process.py L314 _bootstrap() process.py L108 run() process_manager.py L149 run_process() alas.py L285 loop() alas.py L69 run() src.py L55 rogue() rogue.py L36 run() rogue.py L18 rogue_once() entry.py L335 rogue_world_enter() path.py L193 rogue_path_select()
179,850
import random import re import socket import time import typing as t import uiautomator2 as u2 from adbutils import AdbTimeout from lxml import etree from module.base.decorator import cached_property from module.logger import logger The provided code snippet includes necessary dependencies for implementing the `remove_suffix` function. Write a Python function `def remove_suffix(s, suffix)` to solve the following problem: Remove suffix of a string or bytes like `string.removesuffix(suffix)`, which is on Python3.9+ Args: s (str, bytes): suffix (str, bytes): Returns: str, bytes: Here is the function: def remove_suffix(s, suffix): """ Remove suffix of a string or bytes like `string.removesuffix(suffix)`, which is on Python3.9+ Args: s (str, bytes): suffix (str, bytes): Returns: str, bytes: """ return s[:len(suffix)] if s.endswith(suffix) else s
Remove suffix of a string or bytes like `string.removesuffix(suffix)`, which is on Python3.9+ Args: s (str, bytes): suffix (str, bytes): Returns: str, bytes:
179,854
import re from functools import wraps import cv2 import numpy as np import time from adbutils.errors import AdbError from lxml import etree from module.base.decorator import Config from module.device.connection import Connection from module.device.method.utils import (RETRY_TRIES, retry_sleep, remove_prefix, handle_adb_error, ImageTruncated, PackageNotInstalled) from module.exception import RequestHumanTakeover, ScriptError from module.logger import logger RETRY_TRIES = 5 class PackageNotInstalled(Exception): class ImageTruncated(Exception): def retry_sleep(trial): def handle_adb_error(e): class RequestHumanTakeover(Exception): logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) logger.addHandler(console_hdlr) logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) def retry(func): @wraps(func) def retry_wrapper(self, *args, **kwargs): """ Args: self (Adb): """ init = None for _ in range(RETRY_TRIES): try: if callable(init): retry_sleep(_) init() return func(self, *args, **kwargs) # Can't handle except RequestHumanTakeover: break # When adb server was killed except ConnectionResetError as e: logger.error(e) def init(): self.adb_reconnect() # AdbError except AdbError as e: if handle_adb_error(e): def init(): self.adb_reconnect() else: break # Package not installed except PackageNotInstalled as e: logger.error(e) def init(): self.detect_package() # ImageTruncated except ImageTruncated as e: logger.error(e) def init(): pass # Unknown except Exception as e: logger.exception(e) def init(): pass logger.critical(f'Retry {func.__name__}() failed') raise RequestHumanTakeover return retry_wrapper
null
179,862
import typing as t from functools import wraps import cv2 import numpy as np import requests from adbutils.errors import AdbError from module.base.decorator import Config, cached_property, del_cached_property from module.base.timer import Timer from module.device.method.uiautomator_2 import Uiautomator2, ProcessInfo from module.device.method.utils import (retry_sleep, RETRY_TRIES, handle_adb_error, ImageTruncated, PackageNotInstalled) from module.exception import RequestHumanTakeover from module.logger import logger class DroidCastVersionIncompatible(Exception): pass RETRY_TRIES = 5 class PackageNotInstalled(Exception): pass class ImageTruncated(Exception): pass def retry_sleep(trial): # First trial if trial == 0: pass # Failed once, fast retry elif trial == 1: pass # Failed twice elif trial == 2: time.sleep(1) # Failed more else: time.sleep(RETRY_DELAY) def handle_adb_error(e): """ Args: e (Exception): Returns: bool: If should retry """ text = str(e) if 'not found' in text: # When you call `adb disconnect <serial>` # Or when adb server was killed (low possibility) # AdbError(device '127.0.0.1:59865' not found) logger.error(e) return True elif 'timeout' in text: # AdbTimeout(adb read timeout) logger.error(e) return True elif 'closed' in text: # AdbError(closed) # Usually after AdbTimeout(adb read timeout) # Disconnect and re-connect should fix this. logger.error(e) return True elif 'device offline' in text: # AdbError(device offline) # When a device that has been connected wirelessly is disconnected passively, # it does not disappear from the adb device list, # but will be displayed as offline. # In many cases, such as disconnection and recovery caused by network fluctuations, # or after VMOS reboot when running Alas on a phone, # the device is still available, but it needs to be disconnected and re-connected. logger.error(e) return True elif 'is offline' in text: # RuntimeError: USB device 127.0.0.1:7555 is offline # Raised by uiautomator2 when current adb service is killed by another version of adb service. logger.error(e) return True elif 'unknown host service' in text: # AdbError(unknown host service) # Another version of ADB service started, current ADB service has been killed. # Usually because user opened a Chinese emulator, which uses ADB from the Stone Age. logger.error(e) return True else: # AdbError() logger.exception(e) possible_reasons( 'If you are using BlueStacks or LD player or WSA, please enable ADB in the settings of your emulator', 'Emulator died, please restart emulator', 'Serial incorrect, no such device exists or emulator is not running' ) return False class RequestHumanTakeover(Exception): # Request human takeover # Alas is unable to handle such error, probably because of wrong settings. pass logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) logger.addHandler(console_hdlr) logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) def retry(func): @wraps(func) def retry_wrapper(self, *args, **kwargs): """ Args: self (Adb): """ init = None for _ in range(RETRY_TRIES): try: if callable(init): retry_sleep(_) init() return func(self, *args, **kwargs) # Can't handle except RequestHumanTakeover: break # When adb server was killed except ConnectionResetError as e: logger.error(e) def init(): self.adb_reconnect() # AdbError except AdbError as e: if handle_adb_error(e): def init(): self.adb_reconnect() else: break # Package not installed except PackageNotInstalled as e: logger.error(e) def init(): self.detect_package() # DroidCast not running # requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')) # ReadTimeout: HTTPConnectionPool(host='127.0.0.1', port=20482): Read timed out. (read timeout=3) except (requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout) as e: logger.error(e) def init(): self.droidcast_init() # DroidCastVersionIncompatible except DroidCastVersionIncompatible as e: logger.error(e) def init(): self.droidcast_init() # ImageTruncated except ImageTruncated as e: logger.error(e) def init(): pass # Unknown except Exception as e: logger.exception(e) def init(): pass logger.critical(f'Retry {func.__name__}() failed') raise RequestHumanTakeover return retry_wrapper
null
179,863
import ipaddress import logging import platform import re import socket import subprocess import time from functools import wraps import uiautomator2 as u2 from adbutils import AdbClient, AdbDevice, AdbTimeout, ForwardItem, ReverseItem from adbutils.errors import AdbError import module.config.server as server_ from module.base.decorator import Config, cached_property, del_cached_property from module.base.utils import SelectedGrids, ensure_time from module.device.connection_attr import ConnectionAttr from module.device.method.utils import ( PackageNotInstalled, RETRY_TRIES, get_serial_pair, handle_adb_error, possible_reasons, random_port, recv_all, remove_shell_warning, retry_sleep) from module.exception import EmulatorNotRunningError, RequestHumanTakeover from module.logger import logger RETRY_TRIES = 5 class PackageNotInstalled(Exception): pass def retry_sleep(trial): # First trial if trial == 0: pass # Failed once, fast retry elif trial == 1: pass # Failed twice elif trial == 2: time.sleep(1) # Failed more else: time.sleep(RETRY_DELAY) def handle_adb_error(e): """ Args: e (Exception): Returns: bool: If should retry """ text = str(e) if 'not found' in text: # When you call `adb disconnect <serial>` # Or when adb server was killed (low possibility) # AdbError(device '127.0.0.1:59865' not found) logger.error(e) return True elif 'timeout' in text: # AdbTimeout(adb read timeout) logger.error(e) return True elif 'closed' in text: # AdbError(closed) # Usually after AdbTimeout(adb read timeout) # Disconnect and re-connect should fix this. logger.error(e) return True elif 'device offline' in text: # AdbError(device offline) # When a device that has been connected wirelessly is disconnected passively, # it does not disappear from the adb device list, # but will be displayed as offline. # In many cases, such as disconnection and recovery caused by network fluctuations, # or after VMOS reboot when running Alas on a phone, # the device is still available, but it needs to be disconnected and re-connected. logger.error(e) return True elif 'is offline' in text: # RuntimeError: USB device 127.0.0.1:7555 is offline # Raised by uiautomator2 when current adb service is killed by another version of adb service. logger.error(e) return True elif 'unknown host service' in text: # AdbError(unknown host service) # Another version of ADB service started, current ADB service has been killed. # Usually because user opened a Chinese emulator, which uses ADB from the Stone Age. logger.error(e) return True else: # AdbError() logger.exception(e) possible_reasons( 'If you are using BlueStacks or LD player or WSA, please enable ADB in the settings of your emulator', 'Emulator died, please restart emulator', 'Serial incorrect, no such device exists or emulator is not running' ) return False class RequestHumanTakeover(Exception): # Request human takeover # Alas is unable to handle such error, probably because of wrong settings. pass logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) logger.addHandler(console_hdlr) logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) def retry(func): @wraps(func) def retry_wrapper(self, *args, **kwargs): """ Args: self (Adb): """ init = None for _ in range(RETRY_TRIES): try: if callable(init): retry_sleep(_) init() return func(self, *args, **kwargs) # Can't handle except RequestHumanTakeover: break # When adb server was killed except ConnectionResetError as e: logger.error(e) def init(): self.adb_reconnect() # AdbError except AdbError as e: if handle_adb_error(e): def init(): self.adb_reconnect() else: break # Package not installed except PackageNotInstalled as e: logger.error(e) def init(): self.detect_package() # Unknown, probably a trucked image except Exception as e: logger.exception(e) def init(): pass logger.critical(f'Retry {func.__name__}() failed') raise RequestHumanTakeover return retry_wrapper
null
179,864
import datetime import logging import os import sys from typing import Callable, List from rich.console import Console, ConsoleOptions, ConsoleRenderable, NewLine from rich.highlighter import NullHighlighter, RegexHighlighter from rich.logging import RichHandler from rich.rule import Rule from rich.style import Style from rich.theme import Theme from rich.traceback import Traceback def empty_function(*args, **kwargs): pass
null
179,865
import datetime import logging import os import sys from typing import Callable, List from rich.console import Console, ConsoleOptions, ConsoleRenderable, NewLine from rich.highlighter import NullHighlighter, RegexHighlighter from rich.logging import RichHandler from rich.rule import Rule from rich.style import Style from rich.theme import Theme from rich.traceback import Traceback logging.basicConfig = empty_function logging.raiseExceptions = True class RichFileHandler(RichHandler): # Rename pass logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) file_formatter = logging.Formatter( fmt='%(asctime)s.%(msecs)03d | %(levelname)s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S') logger.addHandler(console_hdlr) os.chdir(os.path.join(os.path.dirname(__file__), '../../')) pyw_name = os.path.splitext(os.path.basename(sys.argv[0]))[0] logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) import os os.chdir(os.path.join(os.path.dirname(__file__), '../../')) def _set_file_logger(name=pyw_name): if '_' in name: name = name.split('_', 1)[0] log_file = f'./log/{datetime.date.today()}_{name}.txt' try: file = logging.FileHandler(log_file, encoding='utf-8') except FileNotFoundError: os.mkdir('./log') file = logging.FileHandler(log_file, encoding='utf-8') file.setFormatter(file_formatter) logger.handlers = [h for h in logger.handlers if not isinstance( h, (logging.FileHandler, RichFileHandler))] logger.addHandler(file) logger.log_file = log_file
null
179,866
import datetime import logging import os import sys from typing import Callable, List from rich.console import Console, ConsoleOptions, ConsoleRenderable, NewLine from rich.highlighter import NullHighlighter, RegexHighlighter from rich.logging import RichHandler from rich.rule import Rule from rich.style import Style from rich.theme import Theme from rich.traceback import Traceback logging.basicConfig = empty_function logging.raiseExceptions = True class RichFileHandler(RichHandler): # Rename pass logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) file_formatter = logging.Formatter( fmt='%(asctime)s.%(msecs)03d | %(levelname)s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S') logger.addHandler(console_hdlr) os.chdir(os.path.join(os.path.dirname(__file__), '../../')) pyw_name = os.path.splitext(os.path.basename(sys.argv[0]))[0] logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) import os os.chdir(os.path.join(os.path.dirname(__file__), '../../')) def set_file_logger(name=pyw_name): if '_' in name: name = name.split('_', 1)[0] log_file = f'./log/{datetime.date.today()}_{name}.txt' try: file = open(log_file, mode='a', encoding='utf-8') except FileNotFoundError: os.mkdir('./log') file = open(log_file, mode='a', encoding='utf-8') file_console = Console( file=file, no_color=True, highlight=False, width=119, ) hdlr = RichFileHandler( console=file_console, show_path=False, show_time=False, show_level=False, rich_tracebacks=True, tracebacks_show_locals=True, tracebacks_extra_lines=3, highlighter=NullHighlighter(), ) hdlr.setFormatter(file_formatter) logger.handlers = [h for h in logger.handlers if not isinstance( h, (logging.FileHandler, RichFileHandler))] logger.addHandler(hdlr) logger.log_file = log_file
null
179,867
import datetime import logging import os import sys from typing import Callable, List from rich.console import Console, ConsoleOptions, ConsoleRenderable, NewLine from rich.highlighter import NullHighlighter, RegexHighlighter from rich.logging import RichHandler from rich.rule import Rule from rich.style import Style from rich.theme import Theme from rich.traceback import Traceback class RichRenderableHandler(RichHandler): """ Pass renderable into a function """ def __init__(self, *args, func: Callable[[ConsoleRenderable], None] = None, **kwargs): super().__init__(*args, **kwargs) self._func = func def emit(self, record: logging.LogRecord) -> None: message = self.format(record) traceback = None if ( self.rich_tracebacks and record.exc_info and record.exc_info != (None, None, None) ): exc_type, exc_value, exc_traceback = record.exc_info assert exc_type is not None assert exc_value is not None traceback = Traceback.from_exception( exc_type, exc_value, exc_traceback, width=self.tracebacks_width, extra_lines=self.tracebacks_extra_lines, theme=self.tracebacks_theme, word_wrap=self.tracebacks_word_wrap, show_locals=self.tracebacks_show_locals, locals_max_length=self.locals_max_length, locals_max_string=self.locals_max_string, ) message = record.getMessage() if self.formatter: record.message = record.getMessage() formatter = self.formatter if hasattr(formatter, "usesTime") and formatter.usesTime(): record.asctime = formatter.formatTime( record, formatter.datefmt) message = formatter.formatMessage(record) message_renderable = self.render_message(record, message) log_renderable = self.render( record=record, traceback=traceback, message_renderable=message_renderable ) # Directly put renderable into function self._func(log_renderable) def handle(self, record: logging.LogRecord) -> bool: if not self._func: return True super().handle(record) class HTMLConsole(Console): """ Force full feature console but not working lol :( """ def options(self) -> ConsoleOptions: return ConsoleOptions( max_height=self.size.height, size=self.size, legacy_windows=False, min_width=1, max_width=self.width, encoding='utf-8', is_terminal=False, ) class Highlighter(RegexHighlighter): base_style = 'web.' highlights = [ # (r'(?P<datetime>(\d{2}|\d{4})(?:\-)?([0]{1}\d{1}|[1]{1}[0-2]{1})' # r'(?:\-)?([0-2]{1}\d{1}|[3]{1}[0-1]{1})(?:\s)?([0-1]{1}\d{1}|' # r'[2]{1}[0-3]{1})(?::)?([0-5]{1}\d{1})(?::)?([0-5]{1}\d{1}).\d+\b)'), (r'(?P<time>([0-1]{1}\d{1}|[2]{1}[0-3]{1})(?::)?' r'([0-5]{1}\d{1})(?::)?([0-5]{1}\d{1})(.\d+\b))'), r"(?P<brace>[\{\[\(\)\]\}])", r"\b(?P<bool_true>True)\b|\b(?P<bool_false>False)\b|\b(?P<none>None)\b", r"(?P<path>(([A-Za-z]\:)|.)?\B([\/\\][\w\.\-\_\+]+)*[\/\\])(?P<filename>[\w\.\-\_\+]*)?", # r"(?<![\\\w])(?P<str>b?\'\'\'.*?(?<!\\)\'\'\'|b?\'.*?(?<!\\)\'|b?\"\"\".*?(?<!\\)\"\"\"|b?\".*?(?<!\\)\")", ] WEB_THEME = Theme({ "web.brace": Style(bold=True), "web.bool_true": Style(color="bright_green", italic=True), "web.bool_false": Style(color="bright_red", italic=True), "web.none": Style(color="magenta", italic=True), "web.path": Style(color="magenta"), "web.filename": Style(color="bright_magenta"), "web.str": Style(color="green", italic=False, bold=False), "web.time": Style(color="cyan"), "rule.text": Style(bold=True), }) logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO)eb_formatter = logging.Formatter( fmt='%(asctime)s.%(msecs)03d │ %(message)s', datefmt='%H:%M:%S') logger.addHandler(console_hdlr) logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) def set_func_logger(func): console = HTMLConsole( force_terminal=False, force_interactive=False, width=80, color_system='truecolor', markup=False, safe_box=False, highlighter=Highlighter(), theme=WEB_THEME ) hdlr = RichRenderableHandler( func=func, console=console, show_path=False, show_time=False, show_level=True, rich_tracebacks=True, tracebacks_show_locals=True, tracebacks_extra_lines=2, highlighter=Highlighter(), ) hdlr.setFormatter(web_formatter) logger.handlers = [h for h in logger.handlers if not isinstance( h, RichRenderableHandler)] logger.addHandler(hdlr)
null
179,868
import datetime import logging import os import sys from typing import Callable, List from rich.console import Console, ConsoleOptions, ConsoleRenderable, NewLine from rich.highlighter import NullHighlighter, RegexHighlighter from rich.logging import RichHandler from rich.rule import Rule from rich.style import Style from rich.theme import Theme from rich.traceback import Traceback logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) logger.addHandler(console_hdlr) logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) def attr_align(name, text, front='', align=22): name = str(name).rjust(align) if front: name = front + name[len(front):] logger.info('%s: %s' % (name, str(text)))
null
179,869
import datetime import logging import os import sys from typing import Callable, List from rich.console import Console, ConsoleOptions, ConsoleRenderable, NewLine from rich.highlighter import NullHighlighter, RegexHighlighter from rich.logging import RichHandler from rich.rule import Rule from rich.style import Style from rich.theme import Theme from rich.traceback import Traceback logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) logger.addHandler(console_hdlr) def hr(title, level=3): logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) def show(): logger.info('INFO') logger.warning('WARNING') logger.debug('DEBUG') logger.error('ERROR') logger.critical('CRITICAL') logger.hr('hr0', 0) logger.hr('hr1', 1) logger.hr('hr2', 2) logger.hr('hr3', 3) logger.info(r'Brace { [ ( ) ] }') logger.info(r'True, False, None') logger.info(r'E:/path\\to/alas/alas.exe, /root/alas/, ./relative/path/log.txt') local_var1 = 'This is local variable' # Line before exception raise Exception("Exception") # Line below exception
null
179,870
import datetime import logging import os import sys from typing import Callable, List from rich.console import Console, ConsoleOptions, ConsoleRenderable, NewLine from rich.highlighter import NullHighlighter, RegexHighlighter from rich.logging import RichHandler from rich.rule import Rule from rich.style import Style from rich.theme import Theme from rich.traceback import Traceback def error_convert(func): def error_wrapper(msg, *args, **kwargs): if isinstance(msg, Exception): msg = f'{type(msg).__name__}: {msg}' return func(msg, *args, **kwargs) return error_wrapper
null
179,876
import datetime import logging import os import sys from typing import Callable, List from rich.console import Console, ConsoleOptions, ConsoleRenderable, NewLine from rich.highlighter import NullHighlighter, RegexHighlighter from rich.logging import RichHandler from rich.rule import Rule from rich.style import Style from rich.theme import Theme from rich.traceback import Traceback logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) logger.addHandler(console_hdlr) def hr(title, level=3): title = str(title).upper() if level == 1: logger.rule(title, characters='═') logger.info(title) if level == 2: logger.rule(title, characters='─') logger.info(title) if level == 3: logger.info(f"[bold]<<< {title} >>>[/bold]", extra={"markup": True}) if level == 0: logger.rule(characters='═') logger.rule(title, characters=' ') logger.rule(characters='═') logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) def show(): logger.info('INFO') logger.warning('WARNING') logger.debug('DEBUG') logger.error('ERROR') logger.critical('CRITICAL') logger.hr('hr0', 0) logger.hr('hr1', 1) logger.hr('hr2', 2) logger.hr('hr3', 3) logger.info(r'Brace { [ ( ) ] }') logger.info(r'True, False, None') logger.info(r'E:/path\\to/alas/alas.exe, /root/alas/, ./relative/path/log.txt') local_var1 = 'This is local variable' # Line before exception raise Exception("Exception") # Line below exception
null
179,878
The provided code snippet includes necessary dependencies for implementing the `handle_sensitive_image` function. Write a Python function `def handle_sensitive_image(image)` to solve the following problem: Args: image: Returns: np.ndarray: Here is the function: def handle_sensitive_image(image): """ Args: image: Returns: np.ndarray: """ # Paint UID to black image[680:720, 0:180, :] = 0 return image
Args: image: Returns: np.ndarray:
179,879
def handle_sensitive_logs(logs): return logs
null
179,880
from module.logger import logger logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) logger.addHandler(console_hdlr) logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) def handle_notify(*args, **kwargs): logger.error('Error notify is not supported yet')
null
179,881
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write def str_presenter(dumper, data): if len(data.splitlines()) > 1: # check for multiline string return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') return dumper.represent_scalar('tag:yaml.org,2002:str', data)
null
179,882
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write def filepath_args(filename='args', mod_name='alas'): return f'./module/config/argument/{filename}.json'
null
179,883
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write def filepath_argument(filename): return f'./module/config/argument/{filename}.yaml'
null
179,884
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write def filepath_config(filename, mod_name='alas'): if mod_name == 'alas': return os.path.join('./config', f'{filename}.json') else: return os.path.join('./config', f'{filename}.{mod_name}.json')
null
179,885
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write def filepath_code(): return './module/config/config_generated.py'
null
179,886
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write The provided code snippet includes necessary dependencies for implementing the `alas_template` function. Write a Python function `def alas_template()` to solve the following problem: Returns: list[str]: Name of all Alas instances, except `template`. Here is the function: def alas_template(): """ Returns: list[str]: Name of all Alas instances, except `template`. """ out = [] for file in os.listdir('./config'): name, extension = os.path.splitext(file) if name == 'template' and extension == '.json': out.append(f'{name}-src') # out.extend(mod_template()) return out
Returns: list[str]: Name of all Alas instances, except `template`.
179,887
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write The provided code snippet includes necessary dependencies for implementing the `alas_instance` function. Write a Python function `def alas_instance()` to solve the following problem: Returns: list[str]: Name of all Alas instances, except `template`. Here is the function: def alas_instance(): """ Returns: list[str]: Name of all Alas instances, except `template`. """ out = [] for file in os.listdir('./config'): name, extension = os.path.splitext(file) config_name, mod_name = os.path.splitext(name) mod_name = mod_name[1:] if name != 'template' and extension == '.json' and mod_name == '': out.append(name) # out.extend(mod_instance()) if not len(out): out = ['src'] return out
Returns: list[str]: Name of all Alas instances, except `template`.
179,888
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write The provided code snippet includes necessary dependencies for implementing the `deep_pop` function. Write a Python function `def deep_pop(d, keys, default=None)` to solve the following problem: Pop value from dictionary safely, imitating deep_get(). Here is the function: def deep_pop(d, keys, default=None): """ Pop value from dictionary safely, imitating deep_get(). """ if isinstance(keys, str): keys = keys.split('.') assert type(keys) is list if not isinstance(d, dict): return default if not keys: return default elif len(keys) == 1: return d.pop(keys[0], default) return deep_pop(d.get(keys[0]), keys[1:], default)
Pop value from dictionary safely, imitating deep_get().
179,889
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write The provided code snippet includes necessary dependencies for implementing the `deep_default` function. Write a Python function `def deep_default(d, keys, value)` to solve the following problem: Set default value into dictionary safely, imitating deep_get(). Value is set only when the dict doesn't contain such keys. Here is the function: def deep_default(d, keys, value): """ Set default value into dictionary safely, imitating deep_get(). Value is set only when the dict doesn't contain such keys. """ if isinstance(keys, str): keys = keys.split('.') assert type(keys) is list if not keys: if d: return d else: return value if not isinstance(d, dict): d = {} d[keys[0]] = deep_default(d.get(keys[0], {}), keys[1:], value) return d
Set default value into dictionary safely, imitating deep_get(). Value is set only when the dict doesn't contain such keys.
179,890
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write The provided code snippet includes necessary dependencies for implementing the `parse_value` function. Write a Python function `def parse_value(value, data)` to solve the following problem: Convert a string to float, int, datetime, if possible. Args: value (str): data (dict): Returns: Here is the function: def parse_value(value, data): """ Convert a string to float, int, datetime, if possible. Args: value (str): data (dict): Returns: """ if 'option' in data: if value not in data['option']: return data['value'] if isinstance(value, str): if value == '': return None if value == 'true' or value == 'True': return True if value == 'false' or value == 'False': return False if '.' in value: try: return float(value) except ValueError: pass else: try: return int(value) except ValueError: pass try: return datetime.fromisoformat(value) except ValueError: pass return value
Convert a string to float, int, datetime, if possible. Args: value (str): data (dict): Returns:
179,891
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write The provided code snippet includes necessary dependencies for implementing the `data_to_type` function. Write a Python function `def data_to_type(data, **kwargs)` to solve the following problem: | Condition | Type | | ------------------------------------ | -------- | | `value` is bool | checkbox | | Arg has `options` | select | | Arg has `stored` | select | | `Filter` is in name (in data['arg']) | textarea | | Rest of the args | input | Args: data (dict): kwargs: Any additional properties Returns: str: Here is the function: def data_to_type(data, **kwargs): """ | Condition | Type | | ------------------------------------ | -------- | | `value` is bool | checkbox | | Arg has `options` | select | | Arg has `stored` | select | | `Filter` is in name (in data['arg']) | textarea | | Rest of the args | input | Args: data (dict): kwargs: Any additional properties Returns: str: """ kwargs.update(data) if isinstance(kwargs.get('value'), bool): return 'checkbox' elif 'option' in kwargs and kwargs['option']: return 'select' elif 'stored' in kwargs and kwargs['stored']: return 'stored' elif 'Filter' in kwargs['arg']: return 'textarea' else: return 'input'
| Condition | Type | | ------------------------------------ | -------- | | `value` is bool | checkbox | | Arg has `options` | select | | Arg has `stored` | select | | `Filter` is in name (in data['arg']) | textarea | | Rest of the args | input | Args: data (dict): kwargs: Any additional properties Returns: str:
179,892
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write The provided code snippet includes necessary dependencies for implementing the `data_to_path` function. Write a Python function `def data_to_path(data)` to solve the following problem: Args: data (dict): Returns: str: <func>.<group>.<arg> Here is the function: def data_to_path(data): """ Args: data (dict): Returns: str: <func>.<group>.<arg> """ return '.'.join([data.get(attr, '') for attr in ['func', 'group', 'arg']])
Args: data (dict): Returns: str: <func>.<group>.<arg>
179,893
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write The provided code snippet includes necessary dependencies for implementing the `path_to_arg` function. Write a Python function `def path_to_arg(path)` to solve the following problem: Convert dictionary keys in .yaml files to argument names in config. Args: path (str): Such as `Scheduler.ServerUpdate` Returns: str: Such as `Scheduler_ServerUpdate` Here is the function: def path_to_arg(path): """ Convert dictionary keys in .yaml files to argument names in config. Args: path (str): Such as `Scheduler.ServerUpdate` Returns: str: Such as `Scheduler_ServerUpdate` """ return path.replace('.', '_')
Convert dictionary keys in .yaml files to argument names in config. Args: path (str): Such as `Scheduler.ServerUpdate` Returns: str: Such as `Scheduler_ServerUpdate`
179,894
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write The provided code snippet includes necessary dependencies for implementing the `dict_to_kv` function. Write a Python function `def dict_to_kv(dictionary, allow_none=True)` to solve the following problem: Args: dictionary: Such as `{'path': 'Scheduler.ServerUpdate', 'value': True}` allow_none (bool): Returns: str: Such as `path='Scheduler.ServerUpdate', value=True` Here is the function: def dict_to_kv(dictionary, allow_none=True): """ Args: dictionary: Such as `{'path': 'Scheduler.ServerUpdate', 'value': True}` allow_none (bool): Returns: str: Such as `path='Scheduler.ServerUpdate', value=True` """ return ', '.join([f'{k}={repr(v)}' for k, v in dictionary.items() if allow_none or v is not None])
Args: dictionary: Such as `{'path': 'Scheduler.ServerUpdate', 'value': True}` allow_none (bool): Returns: str: Such as `path='Scheduler.ServerUpdate', value=True`
179,895
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write def random_normal_distribution_int(a, b, n=3): """ A non-numpy implementation of the `random_normal_distribution_int` in module.base.utils Generate a normal distribution int within the interval. Use the average value of several random numbers to simulate normal distribution. Args: a (int): The minimum of the interval. b (int): The maximum of the interval. n (int): The amount of numbers in simulation. Default to 3. Returns: int """ if a < b: output = sum([random.randint(a, b) for _ in range(n)]) / n return int(round(output)) else: return b The provided code snippet includes necessary dependencies for implementing the `ensure_time` function. Write a Python function `def ensure_time(second, n=3, precision=3)` to solve the following problem: Ensure to be time. Args: second (int, float, tuple): time, such as 10, (10, 30), '10, 30' n (int): The amount of numbers in simulation. Default to 5. precision (int): Decimals. Returns: float: Here is the function: def ensure_time(second, n=3, precision=3): """Ensure to be time. Args: second (int, float, tuple): time, such as 10, (10, 30), '10, 30' n (int): The amount of numbers in simulation. Default to 5. precision (int): Decimals. Returns: float: """ if isinstance(second, tuple): multiply = 10 ** precision return random_normal_distribution_int(second[0] * multiply, second[1] * multiply, n) / multiply elif isinstance(second, str): if ',' in second: lower, upper = second.replace(' ', '').split(',') lower, upper = int(lower), int(upper) return ensure_time((lower, upper), n=n, precision=precision) if '-' in second: lower, upper = second.replace(' ', '').split('-') lower, upper = int(lower), int(upper) return ensure_time((lower, upper), n=n, precision=precision) else: return int(second) else: return second
Ensure to be time. Args: second (int, float, tuple): time, such as 10, (10, 30), '10, 30' n (int): The amount of numbers in simulation. Default to 5. precision (int): Decimals. Returns: float:
179,896
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write def get_os_next_reset(): """ Get the first day of next month. Returns: datetime.datetime """ diff = server_time_offset() server_now = datetime.now() - diff server_reset = (server_now.replace(day=1) + timedelta(days=32)) \ .replace(day=1, hour=0, minute=0, second=0, microsecond=0) local_reset = server_reset + diff return local_reset logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) logger.addHandler(console_hdlr) logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) The provided code snippet includes necessary dependencies for implementing the `get_os_reset_remain` function. Write a Python function `def get_os_reset_remain()` to solve the following problem: Returns: int: number of days before next opsi reset Here is the function: def get_os_reset_remain(): """ Returns: int: number of days before next opsi reset """ from module.logger import logger next_reset = get_os_next_reset() now = datetime.now() logger.attr('OpsiNextReset', next_reset) remain = int((next_reset - now).total_seconds() // 86400) logger.attr('ResetRemain', remain) return remain
Returns: int: number of days before next opsi reset
179,897
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write def get_server_last_update(daily_trigger): """ Args: daily_trigger (list[str], str): [ "00:00", "12:00", "18:00",] Returns: datetime.datetime """ if isinstance(daily_trigger, str): daily_trigger = daily_trigger.replace(' ', '').split(',') diff = server_time_offset() local_now = datetime.now() trigger = [] for t in daily_trigger: h, m = [int(x) for x in t.split(':')] future = local_now.replace(hour=h, minute=m, second=0, microsecond=0) + diff s = (future - local_now).total_seconds() % 86400 - 86400 future = local_now + timedelta(seconds=s) trigger.append(future) update = sorted(trigger)[-1] return update The provided code snippet includes necessary dependencies for implementing the `get_server_last_monday_update` function. Write a Python function `def get_server_last_monday_update(daily_trigger)` to solve the following problem: Args: daily_trigger (list[str], str): [ "00:00", "12:00", "18:00",] Returns: datetime.datetime Here is the function: def get_server_last_monday_update(daily_trigger): """ Args: daily_trigger (list[str], str): [ "00:00", "12:00", "18:00",] Returns: datetime.datetime """ update = get_server_last_update(daily_trigger) diff = update.weekday() update = update - timedelta(days=diff) return update
Args: daily_trigger (list[str], str): [ "00:00", "12:00", "18:00",] Returns: datetime.datetime
179,898
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write def get_server_next_update(daily_trigger): """ Args: daily_trigger (list[str], str): [ "00:00", "12:00", "18:00",] Returns: datetime.datetime """ if isinstance(daily_trigger, str): daily_trigger = daily_trigger.replace(' ', '').split(',') diff = server_time_offset() local_now = datetime.now() trigger = [] for t in daily_trigger: h, m = [int(x) for x in t.split(':')] future = local_now.replace(hour=h, minute=m, second=0, microsecond=0) + diff s = (future - local_now).total_seconds() % 86400 future = local_now + timedelta(seconds=s) trigger.append(future) update = sorted(trigger)[0] return update The provided code snippet includes necessary dependencies for implementing the `get_server_next_monday_update` function. Write a Python function `def get_server_next_monday_update(daily_trigger)` to solve the following problem: Args: daily_trigger (list[str], str): [ "00:00", "12:00", "18:00",] Returns: datetime.datetime Here is the function: def get_server_next_monday_update(daily_trigger): """ Args: daily_trigger (list[str], str): [ "00:00", "12:00", "18:00",] Returns: datetime.datetime """ update = get_server_next_update(daily_trigger) diff = (7 - update.weekday()) % 7 update = update + timedelta(days=diff) return update
Args: daily_trigger (list[str], str): [ "00:00", "12:00", "18:00",] Returns: datetime.datetime
179,899
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write The provided code snippet includes necessary dependencies for implementing the `nearest_future` function. Write a Python function `def nearest_future(future, interval=120)` to solve the following problem: Get the neatest future time. Return the last one if two things will finish within `interval`. Args: future (list[datetime.datetime]): interval (int): Seconds Returns: datetime.datetime: Here is the function: def nearest_future(future, interval=120): """ Get the neatest future time. Return the last one if two things will finish within `interval`. Args: future (list[datetime.datetime]): interval (int): Seconds Returns: datetime.datetime: """ future = [datetime.fromisoformat(f) if isinstance(f, str) else f for f in future] future = sorted(future) next_run = future[0] for finish in future: if finish - next_run < timedelta(seconds=interval): next_run = finish return next_run
Get the neatest future time. Return the last one if two things will finish within `interval`. Args: future (list[datetime.datetime]): interval (int): Seconds Returns: datetime.datetime:
179,900
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write def server_time_offset() -> timedelta: """ To convert local time to server time: server_time = local_time + server_time_offset() To convert server time to local time: local_time = server_time - server_time_offset() """ return datetime.now(timezone.utc).astimezone().utcoffset() - server_timezone() The provided code snippet includes necessary dependencies for implementing the `get_nearest_weekday_date` function. Write a Python function `def get_nearest_weekday_date(target)` to solve the following problem: Get nearest weekday date starting from current date Args: target (int): target weekday to calculate Returns: datetime.datetime Here is the function: def get_nearest_weekday_date(target): """ Get nearest weekday date starting from current date Args: target (int): target weekday to calculate Returns: datetime.datetime """ diff = server_time_offset() server_now = datetime.now() - diff days_ahead = target - server_now.weekday() if days_ahead <= 0: # Target day has already happened days_ahead += 7 server_reset = (server_now + timedelta(days=days_ahead)) \ .replace(hour=0, minute=0, second=0, microsecond=0) local_reset = server_reset + diff return local_reset
Get nearest weekday date starting from current date Args: target (int): target weekday to calculate Returns: datetime.datetime
179,901
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write def server_time_offset() -> timedelta: """ To convert local time to server time: server_time = local_time + server_time_offset() To convert server time to local time: local_time = server_time - server_time_offset() """ return datetime.now(timezone.utc).astimezone().utcoffset() - server_timezone() The provided code snippet includes necessary dependencies for implementing the `get_server_weekday` function. Write a Python function `def get_server_weekday()` to solve the following problem: Returns: int: The server's current day of the week Here is the function: def get_server_weekday(): """ Returns: int: The server's current day of the week """ diff = server_time_offset() server_now = datetime.now() - diff result = server_now.weekday() return result
Returns: int: The server's current day of the week
179,902
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write The provided code snippet includes necessary dependencies for implementing the `to_list` function. Write a Python function `def to_list(text, length=1)` to solve the following problem: Args: text (str): Such as `1, 2, 3` length (int): If there's only one digit, return a list expanded to given length, i.e. text='3', length=5, returns `[3, 3, 3, 3, 3]` Returns: list[int]: Here is the function: def to_list(text, length=1): """ Args: text (str): Such as `1, 2, 3` length (int): If there's only one digit, return a list expanded to given length, i.e. text='3', length=5, returns `[3, 3, 3, 3, 3]` Returns: list[int]: """ if text.isdigit(): return [int(text)] * length out = [int(letter.strip()) for letter in text.split(',')] return out
Args: text (str): Such as `1, 2, 3` length (int): If there's only one digit, return a list expanded to given length, i.e. text='3', length=5, returns `[3, 3, 3, 3, 3]` Returns: list[int]:
179,903
import json import os import random import string from datetime import datetime, timedelta, timezone import yaml from filelock import FileLock import module.config.server as server_ from module.config.atomicwrites import atomic_write if __name__ == '__main__': get_os_reset_remain() The provided code snippet includes necessary dependencies for implementing the `type_to_str` function. Write a Python function `def type_to_str(typ)` to solve the following problem: Convert any types or any objects to a string。 Remove <> to prevent them from being parsed as HTML tags. Args: typ: Returns: str: Such as `int`, 'datetime.datetime'. Here is the function: def type_to_str(typ): """ Convert any types or any objects to a string。 Remove <> to prevent them from being parsed as HTML tags. Args: typ: Returns: str: Such as `int`, 'datetime.datetime'. """ if not isinstance(typ, type): typ = type(typ).__name__ return str(typ)
Convert any types or any objects to a string。 Remove <> to prevent them from being parsed as HTML tags. Args: typ: Returns: str: Such as `int`, 'datetime.datetime'.
179,904
import re import typing as t from copy import deepcopy from cached_property import cached_property from deploy.Windows.utils import DEPLOY_TEMPLATE, poor_yaml_read, poor_yaml_write from module.base.timer import timer from module.config.convert import * from module.config.server import VALID_SERVER from module.config.utils import * DICT_GUI_TO_INGAME = { 'zh-CN': 'cn', 'en-US': 'en', 'ja-JP': 'jp', 'zh-TW': 'cht', 'es-ES': 'es', } def gui_lang_to_ingame_lang(lang: str) -> str: return DICT_GUI_TO_INGAME.get(lang, 'en')
null
179,905
import re import typing as t from copy import deepcopy from cached_property import cached_property from deploy.Windows.utils import DEPLOY_TEMPLATE, poor_yaml_read, poor_yaml_write from module.base.timer import timer from module.config.convert import * from module.config.server import VALID_SERVER from module.config.utils import * class CodeGenerator: def __init__(self): def add(self, line, comment=False, newline=True): def generate(self): def print(self): def write(self, file: str = None): def _line_with_tabs(self, line, comment=False, newline=True): def _repr(self, obj): def tab(self): def Empty(self): def Pass(self): def Import(self, text, empty=2): def Variable(self, name): def Value(self, key=None, value=None, type_=None, **kwargs): def Comment(self, text): def CommentAutoGenerage(self, file): def List(self, key=None): def ListItem(self, value): def Dict(self, key=None): def DictItem(self, key=None, value=None): def Object(self, object_class, key=None): def ObjectAttr(self, key=None, value=None): def Class(self, name, inherit=None): def Def(self, name, args=''): def get_generator(): from module.base.code_generator import CodeGenerator return CodeGenerator()
null
179,906
def convert_daily(value): if value == "Calyx_Crimson_Hunt": value = "Calyx_Crimson_The_Hunt" return value
null
179,907
def convert_20_dungeon(value): if value == 'Calyx_Golden_Memories': return 'Calyx_Golden_Memories_Jarilo_VI' if value == 'Calyx_Golden_Aether': return 'Calyx_Golden_Aether_Jarilo_VI' if value == 'Calyx_Golden_Treasures': return 'Calyx_Golden_Treasures_Jarilo_VI' if value == 'Calyx_Golden_Memories': return 'Calyx_Golden_Memories_Jarilo_VI' if value == 'Calyx_Crimson_Destruction': return 'Calyx_Crimson_Destruction_Herta_StorageZone' if value == 'Calyx_Crimson_The_Hunt': return 'Calyx_Crimson_The_Hunt_Jarilo_OutlyingSnowPlains' if value == 'Calyx_Crimson_Erudition': return 'Calyx_Crimson_Erudition_Jarilo_RivetTown' if value == 'Calyx_Crimson_Harmony': return 'Calyx_Crimson_Harmony_Jarilo_RobotSettlement' if value == 'Calyx_Crimson_Nihility': return 'Calyx_Crimson_Nihility_Jarilo_GreatMine' if value == 'Calyx_Crimson_Preservation': return 'Calyx_Crimson_Preservation_Herta_SupplyZone' if value == 'Calyx_Crimson_Abundance': return 'Calyx_Crimson_Abundance_Jarilo_BackwaterPass' return value
null
179,908
from datetime import datetime from functools import cached_property as functools_cached_property from module.base.decorator import cached_property from module.config.utils import DEFAULT_TIME, deep_get, get_server_last_monday_update, get_server_last_update from module.exception import ScriptError def now(): return datetime.now().replace(microsecond=0)
null
179,909
from datetime import datetime from functools import cached_property as functools_cached_property from module.base.decorator import cached_property from module.config.utils import DEFAULT_TIME, deep_get, get_server_last_monday_update, get_server_last_update from module.exception import ScriptError The provided code snippet includes necessary dependencies for implementing the `iter_attribute` function. Write a Python function `def iter_attribute(cls)` to solve the following problem: Args: cls: Class or object Yields: str, obj: Attribute name, attribute value Here is the function: def iter_attribute(cls): """ Args: cls: Class or object Yields: str, obj: Attribute name, attribute value """ for attr in dir(cls): if attr.startswith('_'): continue value = getattr(cls, attr) if type(value).__name__ in ['function', 'property']: continue yield attr, value
Args: cls: Class or object Yields: str, obj: Attribute name, attribute value
179,910
import copy import datetime import operator import threading import pywebio from module.base.decorator import cached_property, del_cached_property from module.base.filter import Filter from module.config.config_generated import GeneratedConfig from module.config.config_manual import ManualConfig, OutputConfig from module.config.config_updater import ConfigUpdater from module.config.stored.classes import iter_attribute from module.config.stored.stored_generated import StoredGenerated from module.config.utils import * from module.config.watcher import ConfigWatcher from module.exception import RequestHumanTakeover, ScriptError from module.logger import logger class Function: def __init__(self, data): self.enable = deep_get(data, keys="Scheduler.Enable", default=False) self.command = deep_get(data, keys="Scheduler.Command", default="Unknown") self.next_run = deep_get(data, keys="Scheduler.NextRun", default=DEFAULT_TIME) def __str__(self): enable = "Enable" if self.enable else "Disable" return f"{self.command} ({enable}, {str(self.next_run)})" __repr__ = __str__ def __eq__(self, other): if not isinstance(other, Function): return False if self.command == other.command and self.next_run == other.next_run: return True else: return False The provided code snippet includes necessary dependencies for implementing the `name_to_function` function. Write a Python function `def name_to_function(name)` to solve the following problem: Args: name (str): Returns: Function: Here is the function: def name_to_function(name): """ Args: name (str): Returns: Function: """ function = Function({}) function.command = name function.enable = True return function
Args: name (str): Returns: Function:
179,911
lang = 'cn' def release_resources(next_task=''): # Release all OCR models # det models take 400MB if not next_task: from module.ocr.models import OCR_MODEL OCR_MODEL.resource_release() # Release assets cache # module.ui has about 80 assets and takes about 3MB # Alas has about 800 assets, but they are not all loaded. # Template images take more, about 6MB each for key, obj in Resource.instances.items(): # Preserve assets for ui switching if next_task and str(obj) in _preserved_assets.ui: continue # if Resource.is_loaded(obj): # logger.info(f'Release {obj}') obj.resource_release() # If no task, check in-game text language again at next run # cause user may change it if not next_task: from tasks.base.main_page import MainPage MainPage._lang_checked = False # Useless in most cases, but just call it # gc.collect() The provided code snippet includes necessary dependencies for implementing the `set_lang` function. Write a Python function `def set_lang(lang_: str)` to solve the following problem: Change language and this will affect globally, including assets and language specific methods. Args: lang_: package name or server. Here is the function: def set_lang(lang_: str): """ Change language and this will affect globally, including assets and language specific methods. Args: lang_: package name or server. """ global lang lang = lang_ from module.base.resource import release_resources release_resources()
Change language and this will affect globally, including assets and language specific methods. Args: lang_: package name or server.
179,912
VALID_SERVER = { 'CN-Official': 'com.miHoYo.hkrpg', 'CN-Bilibili': 'com.miHoYo.hkrpg.bilibili', 'OVERSEA-America': 'com.HoYoverse.hkrpgoversea', 'OVERSEA-Asia': 'com.HoYoverse.hkrpgoversea', 'OVERSEA-Europe': 'com.HoYoverse.hkrpgoversea', 'OVERSEA-TWHKMO': 'com.HoYoverse.hkrpgoversea', } The provided code snippet includes necessary dependencies for implementing the `to_server` function. Write a Python function `def to_server(package_or_server: str) -> str` to solve the following problem: Convert package/server to server. To unknown packages, consider they are a CN channel servers. Here is the function: def to_server(package_or_server: str) -> str: """ Convert package/server to server. To unknown packages, consider they are a CN channel servers. """ # Can't distinguish different regions of oversea servers, # assume it's 'OVERSEA-Asia' if package_or_server == 'com.HoYoverse.hkrpgoversea': return 'OVERSEA-Asia' for key, value in VALID_SERVER.items(): if value == package_or_server: return key if key == package_or_server: return key raise ValueError(f'Package invalid: {package_or_server}')
Convert package/server to server. To unknown packages, consider they are a CN channel servers.
179,913
VALID_SERVER = { 'CN-Official': 'com.miHoYo.hkrpg', 'CN-Bilibili': 'com.miHoYo.hkrpg.bilibili', 'OVERSEA-America': 'com.HoYoverse.hkrpgoversea', 'OVERSEA-Asia': 'com.HoYoverse.hkrpgoversea', 'OVERSEA-Europe': 'com.HoYoverse.hkrpgoversea', 'OVERSEA-TWHKMO': 'com.HoYoverse.hkrpgoversea', } The provided code snippet includes necessary dependencies for implementing the `to_package` function. Write a Python function `def to_package(package_or_server: str) -> str` to solve the following problem: Convert package/server to package. Here is the function: def to_package(package_or_server: str) -> str: """ Convert package/server to package. """ for key, value in VALID_SERVER.items(): if value == package_or_server: return value if key == package_or_server: return value raise ValueError(f'Server invalid: {package_or_server}')
Convert package/server to package.
179,926
import datetime import operator import re import sys import threading import time import traceback from queue import Queue from typing import Callable, Generator, List import pywebio from module.config.utils import deep_iter from module.logger import logger from module.webui.setting import State from pywebio.input import PASSWORD, input from pywebio.output import PopupSize, popup, put_html, toast from pywebio.session import eval_js from pywebio.session import info as session_info from pywebio.session import register_thread, run_js from rich.console import Console, ConsoleOptions from rich.terminal_theme import TerminalTheme TRACEBACK_CODE_FORMAT = """\ <code class="rich-traceback"> <pre class="rich-traceback-code">{code}</pre> </code> """ DARK_TERMINAL_THEME = TerminalTheme( (30, 30, 30), # Background (204, 204, 204), # Foreground [ (0, 0, 0), # Black (205, 49, 49), # Red (13, 188, 121), # Green (229, 229, 16), # Yellow (36, 114, 200), # Blue (188, 63, 188), # Purple / Magenta (17, 168, 205), # Cyan (229, 229, 229), # White ], [ # Bright (102, 102, 102), # Black (241, 76, 76), # Red (35, 209, 139), # Green (245, 245, 67), # Yellow (59, 142, 234), # Blue (214, 112, 214), # Purple / Magenta (41, 184, 219), # Cyan (229, 229, 229), # White ], ) LIGHT_TERMINAL_THEME = TerminalTheme( (255, 255, 255), # Background (97, 97, 97), # Foreground [ (0, 0, 0), # Black (205, 49, 49), # Red (0, 188, 0), # Green (148, 152, 0), # Yellow (4, 81, 165), # Blue (188, 5, 188), # Purple / Magenta (5, 152, 188), # Cyan (85, 85, 85), # White ], [ # Bright (102, 102, 102), # Black (205, 49, 49), # Red (20, 206, 20), # Green (181, 186, 0), # Yellow (4, 81, 165), # Blue (188, 5, 188), # Purple / Magenta (5, 152, 188), # Cyan (165, 165, 165), # White ], ) logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) logger.addHandler(console_hdlr) logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) class State: def init(cls): def clearup(cls): def deploy_config(self) -> "DeployConfig": def config_updater(self) -> "ConfigUpdater": def on_task_exception(self): logger.exception("An internal error occurred in the application") toast_msg = ( "应用发生内部错误" if "zh" in session_info.user_language else "An internal error occurred in the application" ) e_type, e_value, e_tb = sys.exc_info() lines = traceback.format_exception(e_type, e_value, e_tb) traceback_msg = "".join(lines) traceback_console = Console( color_system="truecolor", tab_size=2, record=True, width=90 ) with traceback_console.capture(): # prevent logging to stdout again traceback_console.print_exception( word_wrap=True, extra_lines=1, show_locals=True ) if State.theme == "dark": theme = DARK_TERMINAL_THEME else: theme = LIGHT_TERMINAL_THEME html = traceback_console.export_html( theme=theme, code_format=TRACEBACK_CODE_FORMAT, inline_styles=True ) try: popup(title=toast_msg, content=put_html(html), size=PopupSize.LARGE) run_js( "console.error(traceback_msg)", traceback_msg="Internal Server Error\n" + traceback_msg, ) except Exception: pass
null
179,930
import argparse import queue import threading import time from datetime import datetime from functools import partial from typing import Dict, List, Optional from pywebio import config as webconfig from pywebio.output import ( Output, clear, close_popup, popup, put_button, put_buttons, put_collapse, put_column, put_error, put_html, put_link, put_loading, put_markdown, put_row, put_scope, put_table, put_text, put_warning, toast, use_scope, ) from pywebio.pin import pin, pin_on_change from pywebio.session import go_app, info, local, register_thread, run_js, set_env import module.webui.lang as lang from module.config.config import AzurLaneConfig, Function from module.config.utils import ( alas_instance, alas_template, deep_get, deep_iter, deep_set, dict_to_kv, filepath_args, filepath_config, read_file, ) from module.logger import logger from module.webui.base import Frame from module.webui.fake import ( get_config_mod, load_config, ) from module.webui.fastapi import asgi_app from module.webui.lang import _t, t from module.webui.pin import put_input, put_select from module.webui.process_manager import ProcessManager from module.webui.remote_access import RemoteAccess from module.webui.setting import State from module.webui.updater import updater from module.webui.utils import ( Icon, Switch, TaskHandler, add_css, filepath_css, get_alas_config_listen_path, get_localstorage, get_window_visibility_state, login, parse_pin_value, raise_exception, re_fullmatch, to_pin_value, ) from module.webui.widgets import ( BinarySwitchButton, RichLog, T_Output_Kwargs, put_icon_buttons, put_loading_text, put_none, put_output, ) class AlasGUI(Frame): def initial(self) -> None: def __init__(self) -> None: def set_aside(self) -> None: def set_status(self, state: int) -> None: def set_theme(cls, theme="default") -> None: def alas_set_menu(self) -> None: def alas_set_group(self, task: str) -> None: def set_group(self, group, arg_dict, config, task): def set_navigator(self, group): def set_dashboard(self, arg, arg_dict, config): def set_value(dic): def alas_overview(self) -> None: def _init_alas_config_watcher(self) -> None: def put_queue(path, value): def _alas_thread_update_config(self) -> None: def _save_config( self, modified: Dict[str, str], config_name: str, config_updater: AzurLaneConfig = State.config_updater, ) -> None: def alas_update_overview_task(self) -> None: def put_task(func: Function): def alas_daemon_overview(self, task: str) -> None: def dev_set_menu(self) -> None: def dev_translate(self) -> None: def dev_update(self) -> None: def update_table(): def u(state): def dev_utils(self) -> None: def _force_restart(): def dev_remote(self) -> None: def u(state): def ui_develop(self) -> None: def ui_alas(self, config_name: str) -> None: def ui_add_alas(self) -> None: def get_unused_name(): def add(): def put(name=None, origin=None): def show(self) -> None: def set_language(l): def set_theme(t): def _disable(): def run(self) -> None: def goto_update(): def debug(): def startup(): def clearup(): logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) logger.addHandler(console_hdlr) logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) def asgi_app( applications, cdn=True, static_dir=None, debug=False, allowed_origins=None, check_origin=None, **starlette_settings ): class ProcessManager: def __init__(self, config_name: str = "alas") -> None: def start(self, func, ev: threading.Event = None) -> None: def start_log_queue_handler(self): def stop(self) -> None: def _thread_log_queue_handler(self) -> None: def alive(self) -> bool: def state(self) -> int: def get_manager(cls, config_name: str) -> "ProcessManager": def run_process( config_name, func: str, q: queue.Queue, e: threading.Event = None ) -> None: def running_instances(cls) -> List["ProcessManager"]: def restart_processes( instances: List[Union["ProcessManager", str]] = None, ev: threading.Event = None ): class State: def init(cls): def clearup(cls): def deploy_config(self) -> "DeployConfig": def config_updater(self) -> "ConfigUpdater": updater = Updater() def login(password): def app(): parser = argparse.ArgumentParser(description="Alas web service") parser.add_argument( "-k", "--key", type=str, help="Password of alas. No password by default" ) parser.add_argument( "--cdn", action="store_true", help="Use jsdelivr cdn for pywebio static files (css, js). Self host cdn by default.", ) parser.add_argument( "--run", nargs="+", type=str, help="Run alas by config names on startup", ) args, _ = parser.parse_known_args() # Apply config AlasGUI.set_theme(theme=State.deploy_config.Theme) lang.LANG = State.deploy_config.Language key = args.key or State.deploy_config.Password cdn = args.cdn if args.cdn else State.deploy_config.CDN runs = None if args.run: runs = args.run elif State.deploy_config.Run: # TODO: refactor poor_yaml_read() to support list tmp = State.deploy_config.Run.split(",") runs = [l.strip(" ['\"]") for l in tmp if len(l)] instances: List[str] = runs logger.hr("Webui configs") logger.attr("Theme", State.deploy_config.Theme) logger.attr("Language", lang.LANG) logger.attr("Password", True if key else False) logger.attr("CDN", cdn) def index(): if key is not None and not login(key): logger.warning(f"{info.user_ip} login failed.") time.sleep(1.5) run_js("location.reload();") return gui = AlasGUI() local.gui = gui gui.run() app = asgi_app( applications=[index], cdn=cdn, static_dir=None, debug=True, on_startup=[ startup, lambda: ProcessManager.restart_processes( instances=instances, ev=updater.event ), ], on_shutdown=[clearup], ) return app
null
179,931
from filelock import FileLock from deploy.Windows.config import DeployConfig as _DeployConfig from deploy.Windows.utils import * def poor_yaml_read_with_lock(file): if not os.path.exists(file): return {} with FileLock(f"{file}.lock"): return poor_yaml_read(file)
null
179,932
from filelock import FileLock from deploy.Windows.config import DeployConfig as _DeployConfig from deploy.Windows.utils import * def poor_yaml_write_with_lock(data, file, template_file=DEPLOY_TEMPLATE): folder = os.path.dirname(file) if not os.path.exists(folder): os.mkdir(folder) with FileLock(f"{file}.lock"): with FileLock(f"{DEPLOY_TEMPLATE}.lock"): return poor_yaml_write(data, file, template_file)
null
179,933
import copy import json import random import string from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional, Union from pywebio.exceptions import SessionException from pywebio.io_ctrl import Output from pywebio.output import * from pywebio.session import eval_js, local, run_js from rich.console import ConsoleRenderable from module.logger import WEB_THEME, Highlighter, HTMLConsole from module.webui.lang import t from module.webui.pin import put_checkbox, put_input, put_select, put_textarea from module.webui.process_manager import ProcessManager from module.webui.setting import State from module.webui.utils import ( DARK_TERMINAL_THEME, LIGHT_TERMINAL_THEME, LOG_CODE_FORMAT, Switch, ) def put_icon_buttons( icon_html: str, buttons: List[Dict[str, str]], onclick: Union[List[Callable[[], None]], Callable[[], None]], ) -> Output: value = buttons[0]["value"] return put_column( [ output(put_html(icon_html)).style( "z-index: 1; margin-left: 8px;text-align: center" ), put_buttons(buttons, onclick).style(f"z-index: 2; --aside-{value}--;"), ], size="0", )
null
179,934
import copy import json import random import string from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional, Union from pywebio.exceptions import SessionException from pywebio.io_ctrl import Output from pywebio.output import * from pywebio.session import eval_js, local, run_js from rich.console import ConsoleRenderable from module.logger import WEB_THEME, Highlighter, HTMLConsole from module.webui.lang import t from module.webui.pin import put_checkbox, put_input, put_select, put_textarea from module.webui.process_manager import ProcessManager from module.webui.setting import State from module.webui.utils import ( DARK_TERMINAL_THEME, LIGHT_TERMINAL_THEME, LOG_CODE_FORMAT, Switch, ) def put_none() -> Output: return put_html("<div></div>")
null
179,935
import copy import json import random import string from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional, Union from pywebio.exceptions import SessionException from pywebio.io_ctrl import Output from pywebio.output import * from pywebio.session import eval_js, local, run_js from rich.console import ConsoleRenderable from module.logger import WEB_THEME, Highlighter, HTMLConsole from module.webui.lang import t from module.webui.pin import put_checkbox, put_input, put_select, put_textarea from module.webui.process_manager import ProcessManager from module.webui.setting import State from module.webui.utils import ( DARK_TERMINAL_THEME, LIGHT_TERMINAL_THEME, LOG_CODE_FORMAT, Switch, ) T_Output_Kwargs = Dict[str, Union[str, Dict[str, Any]]] def get_title_help(kwargs: T_Output_Kwargs) -> Output: title: str = kwargs.get("title") help_text: str = kwargs.get("help") if help_text: res = put_column( [ put_text(title).style("--arg-title--"), put_text(help_text).style("--arg-help--"), ], size="auto 1fr", ) else: res = put_text(title).style("--arg-title--") return res def put_input(name, type='text', *, label='', value=None, placeholder=None, readonly=None, datalist=None, help_text=None, scope=None, position=OutputPosition.BOTTOM, **other_html_attrs) -> Output: """Output an input widget. Refer to: `pywebio.input.input()`""" from pywebio.input import input check_dom_name_value(name, 'pin `name`') single_input_return = input(name=name, label=label, value=value, type=type, placeholder=placeholder, readonly=readonly, datalist=datalist, help_text=help_text, **other_html_attrs) return _pin_output(single_input_return, scope, position) def put_arg_input(kwargs: T_Output_Kwargs) -> Output: name: str = kwargs["name"] options: List = kwargs.get("options") if options is not None: kwargs.setdefault("datalist", options) return put_scope( f"arg_container-input-{name}", [ get_title_help(kwargs), put_input(**kwargs).style("--input--"), ], )
null
179,936
import copy import json import random import string from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional, Union from pywebio.exceptions import SessionException from pywebio.io_ctrl import Output from pywebio.output import * from pywebio.session import eval_js, local, run_js from rich.console import ConsoleRenderable from module.logger import WEB_THEME, Highlighter, HTMLConsole from module.webui.lang import t from module.webui.pin import put_checkbox, put_input, put_select, put_textarea from module.webui.process_manager import ProcessManager from module.webui.setting import State from module.webui.utils import ( DARK_TERMINAL_THEME, LIGHT_TERMINAL_THEME, LOG_CODE_FORMAT, Switch, ) T_Output_Kwargs = Dict[str, Union[str, Dict[str, Any]]] def get_title_help(kwargs: T_Output_Kwargs) -> Output: title: str = kwargs.get("title") help_text: str = kwargs.get("help") if help_text: res = put_column( [ put_text(title).style("--arg-title--"), put_text(help_text).style("--arg-help--"), ], size="auto 1fr", ) else: res = put_text(title).style("--arg-title--") return res def product_stored_row(kwargs: T_Output_Kwargs, key, value): kwargs = copy.copy(kwargs) kwargs["name"] += f'_{key}' kwargs["value"] = value return put_input(**kwargs).style("--input--") def put_arg_stored(kwargs: T_Output_Kwargs) -> Output: name: str = kwargs["name"] kwargs["disabled"] = True values = kwargs.pop("value", {}) time_ = values.pop("time", "") rows = [product_stored_row(kwargs, key, value) for key, value in values.items() if value] if time_: rows += [product_stored_row(kwargs, "time", time_)] return put_scope( f"arg_container-stored-{name}", [ get_title_help(kwargs), put_scope( f"arg_stored-stored-value-{name}", rows, ) ] )
null
179,937
import copy import json import random import string from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional, Union from pywebio.exceptions import SessionException from pywebio.io_ctrl import Output from pywebio.output import * from pywebio.session import eval_js, local, run_js from rich.console import ConsoleRenderable from module.logger import WEB_THEME, Highlighter, HTMLConsole from module.webui.lang import t from module.webui.pin import put_checkbox, put_input, put_select, put_textarea from module.webui.process_manager import ProcessManager from module.webui.setting import State from module.webui.utils import ( DARK_TERMINAL_THEME, LIGHT_TERMINAL_THEME, LOG_CODE_FORMAT, Switch, ) T_Output_Kwargs = Dict[str, Union[str, Dict[str, Any]]] def get_title_help(kwargs: T_Output_Kwargs) -> Output: def put_select(name, options=None, *, label='', multiple=None, value=None, help_text=None, scope=None, position=OutputPosition.BOTTOM, **other_html_attrs) -> Output: def put_arg_select(kwargs: T_Output_Kwargs) -> Output: name: str = kwargs["name"] value: str = kwargs["value"] options: List[str] = kwargs["options"] options_label: List[str] = kwargs.pop("options_label", []) disabled: bool = kwargs.pop("disabled", False) _: str = kwargs.pop("invalid_feedback", None) if disabled: option = [{ "label": next((opt_label for opt, opt_label in zip(options, options_label) if opt == value), value), "value": value, "selected": True, }] else: option = [{ "label": opt_label, "value": opt, "select": opt == value, } for opt, opt_label in zip(options, options_label)] kwargs["options"] = option return put_scope( f"arg_container-select-{name}", [ get_title_help(kwargs), put_select(**kwargs).style("--input--"), ], )
null
179,938
import copy import json import random import string from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional, Union from pywebio.exceptions import SessionException from pywebio.io_ctrl import Output from pywebio.output import * from pywebio.session import eval_js, local, run_js from rich.console import ConsoleRenderable from module.logger import WEB_THEME, Highlighter, HTMLConsole from module.webui.lang import t from module.webui.pin import put_checkbox, put_input, put_select, put_textarea from module.webui.process_manager import ProcessManager from module.webui.setting import State from module.webui.utils import ( DARK_TERMINAL_THEME, LIGHT_TERMINAL_THEME, LOG_CODE_FORMAT, Switch, ) T_Output_Kwargs = Dict[str, Union[str, Dict[str, Any]]] def get_title_help(kwargs: T_Output_Kwargs) -> Output: title: str = kwargs.get("title") help_text: str = kwargs.get("help") if help_text: res = put_column( [ put_text(title).style("--arg-title--"), put_text(help_text).style("--arg-help--"), ], size="auto 1fr", ) else: res = put_text(title).style("--arg-title--") return res def put_select(name, options=None, *, label='', multiple=None, value=None, help_text=None, scope=None, position=OutputPosition.BOTTOM, **other_html_attrs) -> Output: """Output a select widget. Refer to: `pywebio.input.select()`""" from pywebio.input import select check_dom_name_value(name, 'pin `name`') single_input_return = select(name=name, options=options, label=label, multiple=multiple, value=value, help_text=help_text, **other_html_attrs) return _pin_output(single_input_return, scope, position) def put_arg_state(kwargs: T_Output_Kwargs) -> Output: name: str = kwargs["name"] value: str = kwargs["value"] options: List[str] = kwargs["options"] options_label: List[str] = kwargs.pop("options_label", []) _: str = kwargs.pop("invalid_feedback", None) bold: bool = value in kwargs.pop("option_bold", []) light: bool = value in kwargs.pop("option_light", []) option = [{ "label": next((opt_label for opt, opt_label in zip(options, options_label) if opt == value), value), "value": value, "selected": True, }] if bold: kwargs["class"] = "form-control state state-bold" elif light: kwargs["class"] = "form-control state state-light" else: kwargs["class"] = "form-control state" kwargs["options"] = option return put_scope( f"arg_container-select-{name}", [ get_title_help(kwargs), put_select(**kwargs).style("--input--"), ], )
null
179,939
import copy import json import random import string from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional, Union from pywebio.exceptions import SessionException from pywebio.io_ctrl import Output from pywebio.output import * from pywebio.session import eval_js, local, run_js from rich.console import ConsoleRenderable from module.logger import WEB_THEME, Highlighter, HTMLConsole from module.webui.lang import t from module.webui.pin import put_checkbox, put_input, put_select, put_textarea from module.webui.process_manager import ProcessManager from module.webui.setting import State from module.webui.utils import ( DARK_TERMINAL_THEME, LIGHT_TERMINAL_THEME, LOG_CODE_FORMAT, Switch, ) T_Output_Kwargs = Dict[str, Union[str, Dict[str, Any]]] def get_title_help(kwargs: T_Output_Kwargs) -> Output: title: str = kwargs.get("title") help_text: str = kwargs.get("help") if help_text: res = put_column( [ put_text(title).style("--arg-title--"), put_text(help_text).style("--arg-help--"), ], size="auto 1fr", ) else: res = put_text(title).style("--arg-title--") return res def put_textarea(name, *, label='', rows=6, code=None, maxlength=None, minlength=None, value=None, placeholder=None, readonly=None, help_text=None, scope=None, position=OutputPosition.BOTTOM, **other_html_attrs) -> Output: """Output a textarea widget. Refer to: `pywebio.input.textarea()`""" from pywebio.input import textarea check_dom_name_value(name, 'pin `name`') single_input_return = textarea( name=name, label=label, rows=rows, code=code, maxlength=maxlength, minlength=minlength, value=value, placeholder=placeholder, readonly=readonly, help_text=help_text, **other_html_attrs) return _pin_output(single_input_return, scope, position) def put_arg_textarea(kwargs: T_Output_Kwargs) -> Output: name: str = kwargs["name"] mode: str = kwargs.pop("mode", None) kwargs.setdefault( "code", {"lineWrapping": True, "lineNumbers": False, "mode": mode} ) return put_scope( # This aims to be a typo, don't correct it, leave it as it is f"arg_contianer-textarea-{name}", [ get_title_help(kwargs), put_textarea(**kwargs), ], )
null
179,940
import copy import json import random import string from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional, Union from pywebio.exceptions import SessionException from pywebio.io_ctrl import Output from pywebio.output import * from pywebio.session import eval_js, local, run_js from rich.console import ConsoleRenderable from module.logger import WEB_THEME, Highlighter, HTMLConsole from module.webui.lang import t from module.webui.pin import put_checkbox, put_input, put_select, put_textarea from module.webui.process_manager import ProcessManager from module.webui.setting import State from module.webui.utils import ( DARK_TERMINAL_THEME, LIGHT_TERMINAL_THEME, LOG_CODE_FORMAT, Switch, ) T_Output_Kwargs = Dict[str, Union[str, Dict[str, Any]]] def get_title_help(kwargs: T_Output_Kwargs) -> Output: title: str = kwargs.get("title") help_text: str = kwargs.get("help") if help_text: res = put_column( [ put_text(title).style("--arg-title--"), put_text(help_text).style("--arg-help--"), ], size="auto 1fr", ) else: res = put_text(title).style("--arg-title--") return res def put_checkbox(name, options=None, *, label='', inline=None, value=None, help_text=None, scope=None, position=OutputPosition.BOTTOM, **other_html_attrs) -> Output: """Output a checkbox widget. Refer to: `pywebio.input.checkbox()`""" from pywebio.input import checkbox check_dom_name_value(name, 'pin `name`') single_input_return = checkbox(name=name, options=options, label=label, inline=inline, value=value, help_text=help_text, **other_html_attrs) return _pin_output(single_input_return, scope, position) def put_arg_checkbox(kwargs: T_Output_Kwargs) -> Output: # Not real checkbox, use as a switch (on/off) name: str = kwargs["name"] value: str = kwargs["value"] _: str = kwargs.pop("invalid_feedback", None) kwargs["options"] = [{"label": "", "value": True, "selected": value}] return put_scope( f"arg_container-checkbox-{name}", [ get_title_help(kwargs), put_checkbox(**kwargs).style("text-align: center"), ], )
null
179,941
import copy import json import random import string from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional, Union from pywebio.exceptions import SessionException from pywebio.io_ctrl import Output from pywebio.output import * from pywebio.session import eval_js, local, run_js from rich.console import ConsoleRenderable from module.logger import WEB_THEME, Highlighter, HTMLConsole from module.webui.lang import t from module.webui.pin import put_checkbox, put_input, put_select, put_textarea from module.webui.process_manager import ProcessManager from module.webui.setting import State from module.webui.utils import ( DARK_TERMINAL_THEME, LIGHT_TERMINAL_THEME, LOG_CODE_FORMAT, Switch, ) T_Output_Kwargs = Dict[str, Union[str, Dict[str, Any]]] def get_title_help(kwargs: T_Output_Kwargs) -> Output: title: str = kwargs.get("title") help_text: str = kwargs.get("help") if help_text: res = put_column( [ put_text(title).style("--arg-title--"), put_text(help_text).style("--arg-help--"), ], size="auto 1fr", ) else: res = put_text(title).style("--arg-title--") return res def put_input(name, type='text', *, label='', value=None, placeholder=None, readonly=None, datalist=None, help_text=None, scope=None, position=OutputPosition.BOTTOM, **other_html_attrs) -> Output: """Output an input widget. Refer to: `pywebio.input.input()`""" from pywebio.input import input check_dom_name_value(name, 'pin `name`') single_input_return = input(name=name, label=label, value=value, type=type, placeholder=placeholder, readonly=readonly, datalist=datalist, help_text=help_text, **other_html_attrs) return _pin_output(single_input_return, scope, position) def put_arg_datetime(kwargs: T_Output_Kwargs) -> Output: name: str = kwargs["name"] return put_scope( f"arg_container-datetime-{name}", [ get_title_help(kwargs), put_input(**kwargs).style("--input--"), ], )
null
179,942
import copy import json import random import string from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional, Union from pywebio.exceptions import SessionException from pywebio.io_ctrl import Output from pywebio.output import * from pywebio.session import eval_js, local, run_js from rich.console import ConsoleRenderable from module.logger import WEB_THEME, Highlighter, HTMLConsole from module.webui.lang import t from module.webui.pin import put_checkbox, put_input, put_select, put_textarea from module.webui.process_manager import ProcessManager from module.webui.setting import State from module.webui.utils import ( DARK_TERMINAL_THEME, LIGHT_TERMINAL_THEME, LOG_CODE_FORMAT, Switch, ) T_Output_Kwargs = Dict[str, Union[str, Dict[str, Any]]] def t(s, *args, **kwargs): """ Get translation. other args, kwargs pass to .format() """ if TRANSLATE_MODE: return s return _t(s, LANG).format(*args, **kwargs) def put_textarea(name, *, label='', rows=6, code=None, maxlength=None, minlength=None, value=None, placeholder=None, readonly=None, help_text=None, scope=None, position=OutputPosition.BOTTOM, **other_html_attrs) -> Output: """Output a textarea widget. Refer to: `pywebio.input.textarea()`""" from pywebio.input import textarea check_dom_name_value(name, 'pin `name`') single_input_return = textarea( name=name, label=label, rows=rows, code=code, maxlength=maxlength, minlength=minlength, value=value, placeholder=placeholder, readonly=readonly, help_text=help_text, **other_html_attrs) return _pin_output(single_input_return, scope, position) def put_arg_storage(kwargs: T_Output_Kwargs) -> Optional[Output]: name: str = kwargs["name"] if kwargs["value"] == {}: return None kwargs["value"] = json.dumps( kwargs["value"], indent=2, ensure_ascii=False, sort_keys=False, default=str ) kwargs.setdefault( "code", {"lineWrapping": True, "lineNumbers": False, "mode": "json"} ) def clear_callback(): alasgui: "AlasGUI" = local.gui alasgui.modified_config_queue.put( {"name": ".".join(name.split("_")), "value": {}} ) # https://github.com/pywebio/PyWebIO/issues/459 # pin[name] = "{}" return put_scope( f"arg_container-storage-{name}", [ put_textarea(**kwargs), put_html( f'<button class="btn btn-outline-warning btn-block">{t("Gui.Text.Clear")}</button>' ).onclick(clear_callback), ], )
null
179,943
import copy import json import random import string from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional, Union from pywebio.exceptions import SessionException from pywebio.io_ctrl import Output from pywebio.output import * from pywebio.session import eval_js, local, run_js from rich.console import ConsoleRenderable from module.logger import WEB_THEME, Highlighter, HTMLConsole from module.webui.lang import t from module.webui.pin import put_checkbox, put_input, put_select, put_textarea from module.webui.process_manager import ProcessManager from module.webui.setting import State from module.webui.utils import ( DARK_TERMINAL_THEME, LIGHT_TERMINAL_THEME, LOG_CODE_FORMAT, Switch, ) T_Output_Kwargs = Dict[str, Union[str, Dict[str, Any]]] _widget_type_to_func: Dict[str, Callable] = { "input": put_arg_input, "lock": put_arg_input, "datetime": put_arg_input, # TODO "select": put_arg_select, "textarea": put_arg_textarea, "checkbox": put_arg_checkbox, "storage": put_arg_storage, "state": put_arg_state, "stored": put_arg_stored, } def put_output(output_kwargs: T_Output_Kwargs) -> Optional[Output]: return _widget_type_to_func[output_kwargs["widget_type"]](output_kwargs)
null
179,944
import copy import json import random import string from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional, Union from pywebio.exceptions import SessionException from pywebio.io_ctrl import Output from pywebio.output import * from pywebio.session import eval_js, local, run_js from rich.console import ConsoleRenderable from module.logger import WEB_THEME, Highlighter, HTMLConsole from module.webui.lang import t from module.webui.pin import put_checkbox, put_input, put_select, put_textarea from module.webui.process_manager import ProcessManager from module.webui.setting import State from module.webui.utils import ( DARK_TERMINAL_THEME, LIGHT_TERMINAL_THEME, LOG_CODE_FORMAT, Switch, ) The provided code snippet includes necessary dependencies for implementing the `type_to_html` function. Write a Python function `def type_to_html(type_: str) -> str` to solve the following problem: Args: type_: Type defined in _widget_type_to_func and argument.yaml Returns: str: Html element name Here is the function: def type_to_html(type_: str) -> str: """ Args: type_: Type defined in _widget_type_to_func and argument.yaml Returns: str: Html element name """ if type_ == "checkbox": return "checkbox" if type_ in ["input", "lock", "datetime"]: return "input" if type_ in ["select", "state"]: return "select" if type_ in ["textarea", "storage"]: return "textarea" return type_
Args: type_: Type defined in _widget_type_to_func and argument.yaml Returns: str: Html element name
179,945
import copy import json import random import string from typing import TYPE_CHECKING, Any, Callable, Dict, Generator, List, Optional, Union from pywebio.exceptions import SessionException from pywebio.io_ctrl import Output from pywebio.output import * from pywebio.session import eval_js, local, run_js from rich.console import ConsoleRenderable from module.logger import WEB_THEME, Highlighter, HTMLConsole from module.webui.lang import t from module.webui.pin import put_checkbox, put_input, put_select, put_textarea from module.webui.process_manager import ProcessManager from module.webui.setting import State from module.webui.utils import ( DARK_TERMINAL_THEME, LIGHT_TERMINAL_THEME, LOG_CODE_FORMAT, Switch, ) def get_loading_style(shape: str, fill: bool) -> str: if fill: return f"--loading-{shape}-fill--" else: return f"--loading-{shape}--" def put_loading_text( text: str, shape: str = "border", color: str = "dark", fill: bool = False, size: str = "auto 2px 1fr", ): loading_style = get_loading_style(shape=shape, fill=fill) return put_row( [ put_loading(shape=shape, color=color).style(loading_style), None, put_text(text), ], size=size, )
null
179,946
from pywebio.input import (actions, checkbox, input, input_group, input_update, select) from pywebio.output import put_buttons, put_markdown from pywebio.session import defer_call, hold, run_js, set_env import module.webui.lang as lang from module.config.utils import (LANGUAGES, deep_get, deep_iter, deep_set, filepath_i18n, read_file, write_file) LANGUAGES = ['zh-CN', 'en-US', 'ja-JP', 'zh-TW', 'es-ES'] def filepath_i18n(lang, mod_name='alas'): return os.path.join('./module/config/i18n', f'{lang}.json') def read_file(file): """ Read a file, support both .yaml and .json format. Return empty dict if file not exists. Args: file (str): Returns: dict, list: """ folder = os.path.dirname(file) if not os.path.exists(folder): os.mkdir(folder) if not os.path.exists(file): return {} _, ext = os.path.splitext(file) lock = FileLock(f"{file}.lock") with lock: print(f'read: {file}') if ext == '.yaml': with open(file, mode='r', encoding='utf-8') as f: s = f.read() data = list(yaml.safe_load_all(s)) if len(data) == 1: data = data[0] if not data: data = {} return data elif ext == '.json': with open(file, mode='r', encoding='utf-8') as f: s = f.read() return json.loads(s) else: print(f'Unsupported config file extension: {ext}') return {} def write_file(file, data): """ Write data into a file, supports both .yaml and .json format. Args: file (str): data (dict, list): """ folder = os.path.dirname(file) if not os.path.exists(folder): os.mkdir(folder) _, ext = os.path.splitext(file) lock = FileLock(f"{file}.lock") with lock: print(f'write: {file}') if ext == '.yaml': with atomic_write(file, overwrite=True, encoding='utf-8', newline='') as f: if isinstance(data, list): yaml.safe_dump_all(data, f, default_flow_style=False, encoding='utf-8', allow_unicode=True, sort_keys=False) else: yaml.safe_dump(data, f, default_flow_style=False, encoding='utf-8', allow_unicode=True, sort_keys=False) elif ext == '.json': with atomic_write(file, overwrite=True, encoding='utf-8', newline='') as f: s = json.dumps(data, indent=2, ensure_ascii=False, sort_keys=False, default=str) f.write(s) else: print(f'Unsupported config file extension: {ext}') def deep_get(d, keys, default=None): """ Get values in dictionary safely. https://stackoverflow.com/questions/25833613/safe-method-to-get-value-of-nested-dictionary Args: d (dict): keys (str, list): Such as `Scheduler.NextRun.value` default: Default return if key not found. Returns: """ if isinstance(keys, str): keys = keys.split('.') assert type(keys) is list if d is None: return default if not keys: return d return deep_get(d.get(keys[0]), keys[1:], default) def deep_set(d, keys, value): """ Set value into dictionary safely, imitating deep_get(). """ if isinstance(keys, str): keys = keys.split('.') assert type(keys) is list if not keys: return value if not isinstance(d, dict): d = {} d[keys[0]] = deep_set(d.get(keys[0], {}), keys[1:], value) return d def deep_iter(data, depth=0, current_depth=1): """ Iter a dictionary safely. Args: data (dict): depth (int): Maximum depth to iter current_depth (int): Returns: list: Key path Any: """ if isinstance(data, dict) \ and (depth and current_depth <= depth): for key, value in data.items(): for child_path, child_value in deep_iter(value, depth=depth, current_depth=current_depth + 1): yield [key] + child_path, child_value else: yield [], data The provided code snippet includes necessary dependencies for implementing the `translate` function. Write a Python function `def translate()` to solve the following problem: Translate Alas Here is the function: def translate(): """ Translate Alas """ set_env(output_animation=False) run_js(r"""$('head').append('<style>footer {display: none}</style>')""") put_markdown(""" # Translate You can submit(Next) by press `Enter`. """) dict_lang = { "zh-CN": read_file(filepath_i18n('zh-CN')), "zh-TW": read_file(filepath_i18n('zh-TW')), "en-US": read_file(filepath_i18n('en-US')), "ja-JP": read_file(filepath_i18n('ja-JP')), } modified = { "zh-CN": {}, "zh-TW": {}, "en-US": {}, "ja-JP": {}, } list_path = [] # Menu.Task.name list_group = [] # Menu list_arg = [] # Task list_key = [] # name for L, _ in deep_iter(dict_lang['zh-CN'], depth=3): list_path.append('.'.join(L)) list_group.append(L[0]) list_arg.append(L[1]) list_key.append(L[2]) total = len(list_path) class V: lang = lang.LANG untranslated_only = False clear = False idx = -1 group = '' group_idx = 0 groups = list(dict_lang['zh-CN'].keys()) arg = '' arg_idx = 0 args = [] key = '' key_idx = 0 keys = [] def update_var(group=None, arg=None, key=None): if group: V.group = group V.idx = list_group.index(group) V.group_idx = V.idx V.arg = list_arg[V.idx] V.arg_idx = V.idx V.args = list(dict_lang["zh-CN"][V.group].keys()) V.key = list_key[V.idx] V.key_idx = V.idx V.keys = list(dict_lang["zh-CN"][V.group][V.arg].keys()) elif arg: V.arg = arg V.idx = list_arg.index(arg, V.group_idx) V.arg_idx = V.idx V.args = list(dict_lang["zh-CN"][V.group].keys()) V.key = list_key[V.idx] V.key_idx = V.idx V.keys = list(dict_lang["zh-CN"][V.group][V.arg].keys()) elif key: V.key = key V.idx = list_key.index(key, V.arg_idx) V.key_idx = V.idx V.keys = list(dict_lang["zh-CN"][V.group][V.arg].keys()) update_form() def next_key(): if V.idx + 1 > total: V.idx = -1 V.idx += 1 if V.untranslated_only: while True: # print(V.idx) key = deep_get(dict_lang[V.lang], list_path[V.idx]) if list_path[V.idx] == key or list_path[V.idx].split('.')[2] == key: break else: V.idx += 1 if V.idx + 1 > total: V.idx = 0 break (V.group, V.arg, V.key) = tuple(list_path[V.idx].split('.')) V.group_idx = list_group.index(V.group) V.arg_idx = list_arg.index(V.arg, V.group_idx) V.args = list(dict_lang["zh-CN"][V.group].keys()) V.key_idx = list_key.index(V.key, V.arg_idx) V.keys = list(dict_lang["zh-CN"][V.group][V.arg].keys()) def update_form(): input_update('arg', options=V.args, value=V.arg) input_update('key', options=V.keys, value=V.key) for L in LANGUAGES: input_update(L, value=deep_get( dict_lang[L], f'{V.group}.{V.arg}.{V.key}', 'Key not found!')) old = deep_get(dict_lang[V.lang], f'{V.group}.{V.arg}.{V.key}', 'Key not found!') input_update(V.lang, value=None if V.clear else old, help_text=f'{V.group}.{V.arg}.{V.key}', placeholder=old, ) def get_inputs(): out = [] old = deep_get(dict_lang[V.lang], f'{V.group}.{V.arg}.{V.key}', 'Key not found!') out.append( input( name=V.lang, label=V.lang, value=None if V.clear else old, help_text=f'{V.group}.{V.arg}.{V.key}', placeholder=old, ) ) out.append( select(name='group', label='Group', options=V.groups, value=V.group, onchange=lambda g: update_var(group=g), required=True) ) out.append( select(name='arg', label='Arg', options=V.args, value=V.arg, onchange=lambda a: update_var(arg=a), required=True) ) out.append( select(name='key', label='Key', options=V.keys, value=V.key, onchange=lambda k: update_var(key=k), required=True) ) _LANGUAGES = LANGUAGES.copy() _LANGUAGES.remove(V.lang) for L in _LANGUAGES: out.append( input(name=L, label=L, readonly=True, value=deep_get( dict_lang[L], f'{V.group}.{V.arg}.{V.key}', 'Key not found!')) ) out.append( actions(name='action', buttons=[ {"label": "Next", "value": 'Next', "type": "submit", "color": "success"}, {"label": "Next without save", "value": 'Skip', "type": "submit", "color": "secondary"}, {"label": "Submit", "value": "Submit", "type": "submit", "color": "primary"}, {"label": "Quit and save", "type": "cancel", "color": "secondary"}, ]) ) return out def save(): for LANG in LANGUAGES: d = read_file(filepath_i18n(LANG)) for k in modified[LANG].keys(): deep_set(d, k, modified[LANG][k]) write_file(filepath_i18n(LANG), d) defer_call(save) def loop(): while True: data = input_group(inputs=get_inputs()) if data is None: save() break if data['action'] == 'Next': modified[V.lang][f'{V.group}.{V.arg}.{V.key}'] = data[V.lang].replace( "\\n", "\n") deep_set(dict_lang[V.lang], f'{V.group}.{V.arg}.{V.key}', data[V.lang].replace( "\\n", "\n")) next_key() if data['action'] == 'Skip': next_key() elif data['action'] == 'Submit': modified[V.lang][f'{V.group}.{V.arg}.{V.key}'] = data[V.lang].replace( "\\n", "\n") deep_set(dict_lang[V.lang], f'{V.group}.{V.arg}.{V.key}', data[V.lang].replace( "\\n", "\n")) continue def setting(): data = input_group(inputs=[ select(name='language', label='Language', options=LANGUAGES, value=V.lang, required=True), checkbox(name='check', label='Other settings', options=[ {"label": 'Button [Next] only shows untranslated key', 'value': 'untranslated', 'selected': V.untranslated_only}, {"label": 'Do not fill input with old value (only effect the language you selected)', "value": "clear", "selected": V.clear} ]) ]) V.lang = data['language'] V.untranslated_only = True if 'untranslated' in data['check'] else False V.clear = True if 'clear' in data['check'] else False put_buttons([ {"label": "Start", "value": "start"}, {"label": "Setting", "value": "setting"} ], onclick=[loop, setting]) next_key() setting() hold()
Translate Alas
179,947
from module.config.config import AzurLaneConfig def start_ocr_server_process(*args, **kwargs): pass
null
179,948
from module.config.config import AzurLaneConfig def stop_ocr_server_process(*args, **kwargs): pass
null
179,949
from module.config.config import AzurLaneConfig class AzurLaneConfig(ConfigUpdater, ManualConfig, GeneratedConfig, ConfigWatcher): stop_event: threading.Event = None bound = {} # Class property is_hoarding_task = True def __setattr__(self, key, value): if key in self.bound: path = self.bound[key] self.modified[path] = value if self.auto_update: self.update() else: super().__setattr__(key, value) def __init__(self, config_name, task=None): logger.attr("Lang", self.LANG) # This will read ./config/<config_name>.json self.config_name = config_name # Raw json data in yaml file. self.data = {} # Modified arguments. Key: Argument path in yaml file. Value: Modified value. # All variable modifications will be record here and saved in method `save()`. self.modified = {} # Key: Argument name in GeneratedConfig. Value: Path in `data`. self.bound = {} # If write after every variable modification. self.auto_update = True # Force override variables # Key: Argument name in GeneratedConfig. Value: Modified value. self.overridden = {} # Scheduler queue, will be updated in `get_next_task()`, list of Function objects # pending_task: Run time has been reached, but haven't been run due to task scheduling. # waiting_task: Run time haven't been reached, wait needed. self.pending_task = [] self.waiting_task = [] # Task to run and bind. # Task means the name of the function to run in AzurLaneAutoScript class. self.task: Function # Template config is used for dev tools self.is_template_config = config_name.startswith("template") if self.is_template_config: # For dev tools logger.info("Using template config, which is read only") self.auto_update = False self.task = name_to_function("template") else: self.load() if task is None: # Bind `Alas` by default which includes emulator settings. task = name_to_function("Alas") else: # Bind a specific task for debug purpose. task = name_to_function(task) self.bind(task) self.task = task self.save() def load(self): self.data = self.read_file(self.config_name) self.config_override() for path, value in self.modified.items(): deep_set(self.data, keys=path, value=value) def bind(self, func, func_list=None): """ Args: func (str, Function): Function to run func_list (list[str]): List of tasks to be bound """ if isinstance(func, Function): func = func.command # func_list: ["Alas", <task>, *func_list] if func_list is None: func_list = [] if func not in func_list: func_list.insert(0, func) if "Alas" not in func_list: func_list.insert(0, "Alas") logger.info(f"Bind task {func_list}") # Bind arguments visited = set() self.bound.clear() for func in func_list: func_data = self.data.get(func, {}) for group, group_data in func_data.items(): for arg, value in group_data.items(): path = f"{group}.{arg}" if path in visited: continue arg = path_to_arg(path) super().__setattr__(arg, value) self.bound[arg] = f"{func}.{path}" visited.add(path) # Override arguments for arg, value in self.overridden.items(): super().__setattr__(arg, value) def hoarding(self): minutes = int( deep_get( self.data, keys="Alas.Optimization.TaskHoardingDuration", default=0 ) ) return timedelta(minutes=max(minutes, 0)) def close_game(self): return deep_get( self.data, keys="Alas.Optimization.CloseGameDuringWait", default=False ) def stored(self) -> StoredGenerated: stored = StoredGenerated() # Bind config for _, value in iter_attribute(stored): value._bind(self) del_cached_property(value, '_stored') return stored def get_next_task(self): """ Calculate tasks, set pending_task and waiting_task """ pending = [] waiting = [] error = [] now = datetime.now() if AzurLaneConfig.is_hoarding_task: now -= self.hoarding for func in self.data.values(): func = Function(func) if not func.enable: continue if not isinstance(func.next_run, datetime): error.append(func) elif func.next_run < now: pending.append(func) else: waiting.append(func) f = Filter(regex=r"(.*)", attr=["command"]) f.load(self.SCHEDULER_PRIORITY) if pending: pending = f.apply(pending) if waiting: waiting = f.apply(waiting) waiting = sorted(waiting, key=operator.attrgetter("next_run")) if error: pending = error + pending self.pending_task = pending self.waiting_task = waiting def get_next(self): """ Returns: Function: Command to run """ self.get_next_task() if self.pending_task: AzurLaneConfig.is_hoarding_task = False logger.info(f"Pending tasks: {[f.command for f in self.pending_task]}") task = self.pending_task[0] logger.attr("Task", task) return task else: AzurLaneConfig.is_hoarding_task = True if self.waiting_task: logger.info("No task pending") task = copy.deepcopy(self.waiting_task[0]) task.next_run = (task.next_run + self.hoarding).replace(microsecond=0) logger.attr("Task", task) return task else: logger.critical("No task waiting or pending") logger.critical("Please enable at least one task") raise RequestHumanTakeover def save(self, mod_name='alas'): if not self.modified: return False for path, value in self.modified.items(): deep_set(self.data, keys=path, value=value) logger.info( f"Save config {filepath_config(self.config_name, mod_name)}, {dict_to_kv(self.modified)}" ) # Don't use self.modified = {}, that will create a new object. self.modified.clear() del_cached_property(self, 'stored') self.write_file(self.config_name, data=self.data) def update(self): self.load() self.config_override() self.bind(self.task) self.save() def config_override(self): now = datetime.now().replace(microsecond=0) limited = set() def limit_next_run(tasks, limit): for task in tasks: if task in limited: continue limited.add(task) next_run = deep_get( self.data, keys=f"{task}.Scheduler.NextRun", default=None ) if isinstance(next_run, datetime) and next_run > limit: deep_set(self.data, keys=f"{task}.Scheduler.NextRun", value=now) limit_next_run(['BattlePass'], limit=now + timedelta(days=40, seconds=-1)) limit_next_run(self.args.keys(), limit=now + timedelta(hours=24, seconds=-1)) def override(self, **kwargs): """ Override anything you want. Variables stall remain overridden even config is reloaded from yaml file. Note that this method is irreversible. """ for arg, value in kwargs.items(): self.overridden[arg] = value super().__setattr__(arg, value) def set_record(self, **kwargs): """ Args: **kwargs: For example, `Emotion1_Value=150` will set `Emotion1_Value=150` and `Emotion1_Record=now()` """ with self.multi_set(): for arg, value in kwargs.items(): record = arg.replace("Value", "Record") self.__setattr__(arg, value) self.__setattr__(record, datetime.now().replace(microsecond=0)) def multi_set(self): """ Set multiple arguments but save once. Examples: with self.config.multi_set(): self.config.foo1 = 1 self.config.foo2 = 2 """ return MultiSetWrapper(main=self) def cross_get(self, keys, default=None): """ Get configs from other tasks. Args: keys (str, list[str]): Such as `{task}.Scheduler.Enable` default: Returns: Any: """ return deep_get(self.data, keys=keys, default=default) def cross_set(self, keys, value): """ Set configs to other tasks. Args: keys (str, list[str]): Such as `{task}.Scheduler.Enable` value (Any): Returns: Any: """ self.modified[keys] = value if self.auto_update: self.update() def task_delay(self, success=None, server_update=None, target=None, minute=None, task=None): """ Set Scheduler.NextRun Should set at least one arguments. If multiple arguments are set, use the nearest. Args: success (bool): If True, delay Scheduler.SuccessInterval If False, delay Scheduler.FailureInterval server_update (bool, list, str): If True, delay to nearest Scheduler.ServerUpdate If type is list or str, delay to such server update target (datetime.datetime, str, list): Delay to such time. minute (int, float, tuple): Delay several minutes. task (str): Set across task. None for current task. """ def ensure_delta(delay): return timedelta(seconds=int(ensure_time(delay, precision=3) * 60)) run = [] if success is not None: interval = ( 120 if success else 30 ) run.append(datetime.now() + ensure_delta(interval)) if server_update is not None: if server_update is True: server_update = self.Scheduler_ServerUpdate run.append(get_server_next_update(server_update)) if target is not None: target = [target] if not isinstance(target, list) else target target = nearest_future(target) run.append(target) if minute is not None: run.append(datetime.now() + ensure_delta(minute)) if len(run): run = min(run).replace(microsecond=0) kv = dict_to_kv( { "success": success, "server_update": server_update, "target": target, "minute": minute, }, allow_none=False, ) if task is None: task = self.task.command logger.info(f"Delay task `{task}` to {run} ({kv})") self.modified[f'{task}.Scheduler.NextRun'] = run self.update() else: raise ScriptError( "Missing argument in delay_next_run, should set at least one" ) def task_call(self, task, force_call=True): """ Call another task to run. That task will run when current task finished. But it might not be run because: - Other tasks should run first according to SCHEDULER_PRIORITY - Task is disabled by user Args: task (str): Task name to call, such as `Restart` force_call (bool): Returns: bool: If called. """ if deep_get(self.data, keys=f"{task}.Scheduler.NextRun", default=None) is None: raise ScriptError(f"Task to call: `{task}` does not exist in user config") if force_call or self.is_task_enabled(task): logger.info(f"Task call: {task}") self.modified[f"{task}.Scheduler.NextRun"] = datetime.now().replace( microsecond=0 ) self.modified[f"{task}.Scheduler.Enable"] = True if self.auto_update: self.update() return True else: logger.info(f"Task call: {task} (skipped because disabled by user)") return False def task_stop(message=""): """ Stop current task. Raises: TaskEnd: """ if message: raise TaskEnd(message) else: raise TaskEnd def task_switched(self): """ Check if needs to switch task. Raises: bool: If task switched """ # Update event if self.stop_event is not None: if self.stop_event.is_set(): return True prev = self.task self.load() new = self.get_next() if prev == new: logger.info(f"Continue task `{new}`") return False else: logger.info(f"Switch task `{prev}` to `{new}`") return True def check_task_switch(self, message=""): """ Stop current task when task switched. Raises: TaskEnd: """ if self.task_switched(): self.task_stop(message=message) def is_task_enabled(self, task): return bool(self.cross_get(keys=[task, 'Scheduler', 'Enable'], default=False)) def update_daily_quests(self): """ Raises: TaskEnd: Call task `DailyQuest` and stop current task """ if self.stored.DailyActivity.is_expired(): logger.info('DailyActivity expired, call task to update') self.task_call('DailyQuest') self.task_stop() if self.stored.DailyQuest.is_expired(): logger.info('DailyQuest expired, call task to update') self.task_call('DailyQuest') self.task_stop() def update_battle_pass_quests(self): """ Raises: TaskEnd: Call task `BattlePass` and stop current task """ if self.stored.BattlePassWeeklyQuest.is_expired(): if self.stored.BattlePassLevel.is_full(): logger.info('BattlePassLevel full, no updates') else: logger.info('BattlePassTodayQuest expired, call task to update') self.task_call('BattlePass') self.task_stop() def DEVICE_SCREENSHOT_METHOD(self): return self.Emulator_ScreenshotMethod def DEVICE_CONTROL_METHOD(self): return self.Emulator_ControlMethod def temporary(self, **kwargs): """ Cover some settings, and recover later. Usage: backup = self.config.cover(ENABLE_DAILY_REWARD=False) # do_something() backup.recover() Args: **kwargs: Returns: ConfigBackup: """ backup = ConfigBackup(config=self) backup.cover(**kwargs) return backup def load_config(config_name): return AzurLaneConfig(config_name, '')
null
179,950
from module.config.config import AzurLaneConfig The provided code snippet includes necessary dependencies for implementing the `get_config_mod` function. Write a Python function `def get_config_mod(config_name)` to solve the following problem: Args: config_name (str): Here is the function: def get_config_mod(config_name): """ Args: config_name (str): """ return 'alas'
Args: config_name (str):
179,951
from module.config.config import AzurLaneConfig def mod_instance(): return []
null
179,952
from module.config.config import AzurLaneConfig def init_discord_rpc(): pass
null
179,953
from module.config.config import AzurLaneConfig def close_discord_rpc(): pass
null
179,954
import time from typing import Dict from module.config.utils import * from module.webui.fake import list_mod from module.webui.setting import State LANG = "zh-CN" class State: """ Shared settings """ _init = False _clearup = False restart_event: threading.Event = None manager: SyncManager = None electron: bool = False theme: str = "default" def init(cls): cls.manager = multiprocessing.Manager() cls._init = True def clearup(cls): cls.manager.shutdown() cls._clearup = True def deploy_config(self) -> "DeployConfig": """ Returns: DeployConfig: """ from module.webui.config import DeployConfig return DeployConfig() def config_updater(self) -> "ConfigUpdater": """ Returns: ConfigUpdater: """ from module.config.config_updater import ConfigUpdater return ConfigUpdater() def set_language(s: str, refresh=False): global LANG for i, lang in enumerate(LANGUAGES): # pywebio.session.info.user_language return `zh-CN` or `zh-cn`, depends on browser if lang.lower() == s.lower(): LANG = LANGUAGES[i] break else: LANG = "en-US" State.deploy_config.Language = LANG if refresh: from pywebio.session import run_js run_js("location.reload();")
null
179,955
import time from typing import Dict from module.config.utils import * from module.webui.fake import list_mod from module.webui.setting import State def t(s, *args, **kwargs): """ Get translation. other args, kwargs pass to .format() """ if TRANSLATE_MODE: return s return _t(s, LANG).format(*args, **kwargs) The provided code snippet includes necessary dependencies for implementing the `readable_time` function. Write a Python function `def readable_time(before: str) -> str` to solve the following problem: Convert "2023-08-29 12:30:53" to "3 Minutes Ago" Here is the function: def readable_time(before: str) -> str: """ Convert "2023-08-29 12:30:53" to "3 Minutes Ago" """ if not before: return t("Gui.Dashboard.NoData") try: ti = datetime.fromisoformat(before) except ValueError: return t("Gui.Dashboard.TimeError") if ti == DEFAULT_TIME: return t("Gui.Dashboard.NoData") diff = time.time() - ti.timestamp() if diff < -1: return t("Gui.Dashboard.TimeError") elif diff < 60: # < 1 min return t("Gui.Dashboard.JustNow") elif diff < 5400: # < 90 min return t("Gui.Dashboard.MinutesAgo", time=int(diff // 60)) elif diff < 129600: # < 36 hours return t("Gui.Dashboard.HoursAgo", time=int(diff // 3600)) elif diff < 1296000: # < 15 days return t("Gui.Dashboard.DaysAgo", time=int(diff // 86400)) else: # >= 15 days return t("Gui.Dashboard.LongTimeAgo")
Convert "2023-08-29 12:30:53" to "3 Minutes Ago"
179,956
import json import shlex import threading import time from subprocess import PIPE, Popen from typing import TYPE_CHECKING from module.logger import logger from module.config.utils import random_id from module.webui.setting import State _ssh_thread: threading.Thread = None def start_remote_access_service_(**kwargs): logger.info("Start remote access service") try: remote_access_service(**kwargs) except KeyboardInterrupt: # ignore KeyboardInterrupt pass except Exception as e: logger.exception(e) finally: if _ssh_process: logger.info("Exception occurred, killing ssh process") _ssh_process.kill() logger.info("Exit remote access service thread") class ParseError(Exception): pass logger = logging.getLogger('alas') logger.setLevel(logging.DEBUG if logger_debug else logging.INFO) logger.addHandler(console_hdlr) logger.error = error_convert(logger.error) logger.hr = hr logger.attr = attr logger.attr_align = attr_align logger.set_file_logger = set_file_logger logger.set_func_logger = set_func_logger logger.rule = rule logger.print = print logger.log_file: str logger.set_file_logger() logger.hr('Start', level=0) def random_id(length=32): """ Args: length (int): Returns: str: Random azurstat id. """ return ''.join(random.sample(string.ascii_lowercase + string.digits, length)) class State: """ Shared settings """ _init = False _clearup = False restart_event: threading.Event = None manager: SyncManager = None electron: bool = False theme: str = "default" def init(cls): cls.manager = multiprocessing.Manager() cls._init = True def clearup(cls): cls.manager.shutdown() cls._clearup = True def deploy_config(self) -> "DeployConfig": """ Returns: DeployConfig: """ from module.webui.config import DeployConfig return DeployConfig() def config_updater(self) -> "ConfigUpdater": """ Returns: ConfigUpdater: """ from module.config.config_updater import ConfigUpdater return ConfigUpdater() def start_remote_access_service(**kwagrs): global _ssh_thread try: server, server_port = State.deploy_config.SSHServer.split(":") except (ValueError, AttributeError): raise ParseError( f"Failed to parse SSH server [{State.deploy_config.SSHServer}]" ) if State.deploy_config.WebuiHost == "0.0.0.0": local_host = "127.0.0.1" elif State.deploy_config.WebuiHost == "::": local_host = "[::1]" else: local_host = State.deploy_config.WebuiHost if State.deploy_config.SSHUser is None: logger.info("SSHUser is not set, generate a random one") State.deploy_config.SSHUser = random_id(24) server = f"{State.deploy_config.SSHUser}@{server}" kwagrs.setdefault("server", server) kwagrs.setdefault("server_port", server_port) kwagrs.setdefault("local_host", local_host) kwagrs.setdefault("local_port", State.deploy_config.WebuiPort) _ssh_thread = threading.Thread( target=start_remote_access_service_, kwargs=kwagrs, daemon=False, ) _ssh_thread.start() return _ssh_thread
null
179,958
import re from module.base.decorator import cached_property def get_assets_from_file(file): assets = set() regex = re.compile(r"file='(.*?)'") with open(file, 'r', encoding='utf-8') as f: for row in f.readlines(): result = regex.search(row) if result: assets.add(result.group(1)) return assets
null
179,964
import module.config.server as server from module.base.decorator import cached_property, del_cached_property from module.base.resource import Resource from module.base.utils import * from module.exception import ScriptError The provided code snippet includes necessary dependencies for implementing the `match_template` function. Write a Python function `def match_template(image, template, similarity=0.85)` to solve the following problem: Args: image (np.ndarray): Screenshot template (np.ndarray): area (tuple): Crop area of image. offset (int, tuple): Detection area offset. similarity (float): 0-1. Similarity. Lower than this value will return float(0). Returns: bool: Here is the function: def match_template(image, template, similarity=0.85): """ Args: image (np.ndarray): Screenshot template (np.ndarray): area (tuple): Crop area of image. offset (int, tuple): Detection area offset. similarity (float): 0-1. Similarity. Lower than this value will return float(0). Returns: bool: """ res = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED) _, sim, _, point = cv2.minMaxLoc(res) return sim > similarity
Args: image (np.ndarray): Screenshot template (np.ndarray): area (tuple): Crop area of image. offset (int, tuple): Detection area offset. similarity (float): 0-1. Similarity. Lower than this value will return float(0). Returns: bool:
179,969
import numpy as np from scipy import optimize from .utils import area_pad The provided code snippet includes necessary dependencies for implementing the `area2corner` function. Write a Python function `def area2corner(area)` to solve the following problem: Args: area: (x1, y1, x2, y2) Returns: np.ndarray: [upper-left, upper-right, bottom-left, bottom-right] Here is the function: def area2corner(area): """ Args: area: (x1, y1, x2, y2) Returns: np.ndarray: [upper-left, upper-right, bottom-left, bottom-right] """ return np.array([[area[0], area[1]], [area[2], area[1]], [area[0], area[3]], [area[2], area[3]]])
Args: area: (x1, y1, x2, y2) Returns: np.ndarray: [upper-left, upper-right, bottom-left, bottom-right]
179,970
import numpy as np from scipy import optimize from .utils import area_pad def corner2area(corner): """ Args: corner: [upper-left, upper-right, bottom-left, bottom-right] Returns: np.ndarray: (x1, y1, x2, y2) """ x, y = np.array(corner).T return np.rint([np.min(x), np.min(y), np.max(x), np.max(y)]).astype(int) def corner2inner(corner): """ The largest rectangle inscribed in trapezoid. Args: corner: ((x0, y0), (x1, y1), (x2, y2), (x3, y3)) Returns: tuple[int]: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y). """ x0, y0, x1, y1, x2, y2, x3, y3 = np.array(corner).flatten() area = tuple(np.rint((max(x0, x2), max(y0, y1), min(x1, x3), min(y2, y3))).astype(int)) return area def corner2outer(corner): """ The smallest rectangle circumscribed by the trapezoid. Args: corner: ((x0, y0), (x1, y1), (x2, y2), (x3, y3)) Returns: tuple[int]: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y). """ x0, y0, x1, y1, x2, y2, x3, y3 = np.array(corner).flatten() area = tuple(np.rint((min(x0, x2), min(y0, y1), max(x1, x3), max(y2, y3))).astype(int)) return area def area_pad(area, pad=10): """ Inner offset an area. Args: area: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y). pad (int): Returns: tuple: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y). """ upper_left_x, upper_left_y, bottom_right_x, bottom_right_y = area return upper_left_x + pad, upper_left_y + pad, bottom_right_x - pad, bottom_right_y - pad The provided code snippet includes necessary dependencies for implementing the `trapezoid2area` function. Write a Python function `def trapezoid2area(corner, pad=0)` to solve the following problem: Convert corners of a trapezoid to area. Args: corner: ((x0, y0), (x1, y1), (x2, y2), (x3, y3)) pad (int): Positive value for inscribed area. Negative value and 0 for circumscribed area. Returns: tuple[int]: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y). Here is the function: def trapezoid2area(corner, pad=0): """ Convert corners of a trapezoid to area. Args: corner: ((x0, y0), (x1, y1), (x2, y2), (x3, y3)) pad (int): Positive value for inscribed area. Negative value and 0 for circumscribed area. Returns: tuple[int]: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y). """ if pad > 0: return area_pad(corner2inner(corner), pad=pad) elif pad < 0: return area_pad(corner2outer(corner), pad=pad) else: return area_pad(corner2area(corner), pad=pad)
Convert corners of a trapezoid to area. Args: corner: ((x0, y0), (x1, y1), (x2, y2), (x3, y3)) pad (int): Positive value for inscribed area. Negative value and 0 for circumscribed area. Returns: tuple[int]: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).
179,971
import numpy as np from scipy import optimize from .utils import area_pad The provided code snippet includes necessary dependencies for implementing the `points_to_area_generator` function. Write a Python function `def points_to_area_generator(points, shape)` to solve the following problem: Args: points (np.ndarray): N x 2 array. shape (tuple): (x, y). Yields: tuple, np.ndarray: (x, y), [upper-left, upper-right, bottom-left, bottom-right] Here is the function: def points_to_area_generator(points, shape): """ Args: points (np.ndarray): N x 2 array. shape (tuple): (x, y). Yields: tuple, np.ndarray: (x, y), [upper-left, upper-right, bottom-left, bottom-right] """ points = points.reshape(*shape[::-1], 2) for y in range(shape[1] - 1): for x in range(shape[0] - 1): area = np.array([points[y, x], points[y, x + 1], points[y + 1, x], points[y + 1, x + 1]]) yield ((x, y), area)
Args: points (np.ndarray): N x 2 array. shape (tuple): (x, y). Yields: tuple, np.ndarray: (x, y), [upper-left, upper-right, bottom-left, bottom-right]
179,972
import numpy as np from scipy import optimize from .utils import area_pad The provided code snippet includes necessary dependencies for implementing the `get_map_inner` function. Write a Python function `def get_map_inner(points)` to solve the following problem: Args: points (np.ndarray): N x 2 array. Yields: np.ndarray: (x, y). Here is the function: def get_map_inner(points): """ Args: points (np.ndarray): N x 2 array. Yields: np.ndarray: (x, y). """ points = np.array(points) if len(points.shape) == 1: points = np.array([points]) return np.mean(points, axis=0)
Args: points (np.ndarray): N x 2 array. Yields: np.ndarray: (x, y).
179,973
import numpy as np from scipy import optimize from .utils import area_pad The provided code snippet includes necessary dependencies for implementing the `separate_edges` function. Write a Python function `def separate_edges(edges, inner)` to solve the following problem: Args: edges: A iterate object which contains float ot integer. inner (float, int): A inner point to separate edges. Returns: float, float: Lower edge and upper edge. if not found, return None Here is the function: def separate_edges(edges, inner): """ Args: edges: A iterate object which contains float ot integer. inner (float, int): A inner point to separate edges. Returns: float, float: Lower edge and upper edge. if not found, return None """ if len(edges) == 0: return None, None elif len(edges) == 1: edge = edges[0] return (None, edge) if edge > inner else (edge, None) else: lower = [edge for edge in edges if edge < inner] upper = [edge for edge in edges if edge > inner] lower = lower[0] if len(lower) else None upper = upper[-1] if len(upper) else None return lower, upper
Args: edges: A iterate object which contains float ot integer. inner (float, int): A inner point to separate edges. Returns: float, float: Lower edge and upper edge. if not found, return None
179,974
import numpy as np from scipy import optimize from .utils import area_pad The provided code snippet includes necessary dependencies for implementing the `perspective_transform` function. Write a Python function `def perspective_transform(points, data)` to solve the following problem: Args: points: A 2D array with shape (n, 2) data: Perspective data, a 2D array with shape (3, 3), see https://web.archive.org/web/20150222120106/xenia.media.mit.edu/~cwren/interpolator/ Returns: np.ndarray: 2D array with shape (n, 2) Here is the function: def perspective_transform(points, data): """ Args: points: A 2D array with shape (n, 2) data: Perspective data, a 2D array with shape (3, 3), see https://web.archive.org/web/20150222120106/xenia.media.mit.edu/~cwren/interpolator/ Returns: np.ndarray: 2D array with shape (n, 2) """ points = np.pad(np.array(points), ((0, 0), (0, 1)), mode='constant', constant_values=1) matrix = data.dot(points.T) x, y = matrix[0] / matrix[2], matrix[1] / matrix[2] points = np.array([x, y]).T return points
Args: points: A 2D array with shape (n, 2) data: Perspective data, a 2D array with shape (3, 3), see https://web.archive.org/web/20150222120106/xenia.media.mit.edu/~cwren/interpolator/ Returns: np.ndarray: 2D array with shape (n, 2)
179,975
import numpy as np from scipy import optimize from .utils import area_pad The provided code snippet includes necessary dependencies for implementing the `fit_points` function. Write a Python function `def fit_points(points, mod, encourage=1)` to solve the following problem: Get a closet point in a group of points with common difference. Will ignore points in the distance. Args: points: Points on image, a 2D array with shape (n, 2) mod: Common difference of points, (x, y). encourage (int, float): Describe how close to fit a group of points, in pixel. Smaller means closer to local minimum, larger means closer to global minimum. Returns: np.ndarray: (x, y) Here is the function: def fit_points(points, mod, encourage=1): """ Get a closet point in a group of points with common difference. Will ignore points in the distance. Args: points: Points on image, a 2D array with shape (n, 2) mod: Common difference of points, (x, y). encourage (int, float): Describe how close to fit a group of points, in pixel. Smaller means closer to local minimum, larger means closer to global minimum. Returns: np.ndarray: (x, y) """ encourage = np.square(encourage) mod = np.array(mod) points = np.array(points) % mod points = np.append(points - mod, points, axis=0) def cal_distance(point): distance = np.linalg.norm(points - point, axis=1) return np.sum(1 / (1 + np.exp(encourage / distance) / distance)) # Fast local minimizer # result = optimize.minimize(cal_distance, np.mean(points, axis=0), method='SLSQP') # return result['x'] % mod # Brute-force global minimizer area = np.append(-mod - 10, mod + 10) result = optimize.brute(cal_distance, ((area[0], area[2]), (area[1], area[3]))) return result % mod
Get a closet point in a group of points with common difference. Will ignore points in the distance. Args: points: Points on image, a 2D array with shape (n, 2) mod: Common difference of points, (x, y). encourage (int, float): Describe how close to fit a group of points, in pixel. Smaller means closer to local minimum, larger means closer to global minimum. Returns: np.ndarray: (x, y)
179,981
import re import cv2 import numpy as np from PIL import Image The provided code snippet includes necessary dependencies for implementing the `area_center` function. Write a Python function `def area_center(area)` to solve the following problem: Get the center of an area Args: area: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y) Returns: tuple: (x, y) Here is the function: def area_center(area): """ Get the center of an area Args: area: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y) Returns: tuple: (x, y) """ x1, y1, x2, y2 = area return (x1 + x2) / 2, (y1 + y2) / 2
Get the center of an area Args: area: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y) Returns: tuple: (x, y)
179,986
import re import cv2 import numpy as np from PIL import Image REGEX_NODE = re.compile(r'(-?[A-Za-z]+)(-?\d+)') def name2col(col_str): """ Convert a cell reference in A1 notation to a zero indexed row and column. Args: col_str: A1 style string. Returns: row, col: Zero indexed cell row and column indices. """ # Convert base26 column string to number. expn = 0 col = 0 col_neg = col_str.startswith('-') col_str = col_str.strip('-').upper() for char in reversed(col_str): col += (ord(char) - 64) * (26 ** expn) expn += 1 if col_neg: return -col else: return col - 1 # Convert 1-index to zero-index The provided code snippet includes necessary dependencies for implementing the `node2location` function. Write a Python function `def node2location(node)` to solve the following problem: See location2node() Args: node (str): Example: 'E3' Returns: tuple[int]: Example: (4, 2) Here is the function: def node2location(node): """ See location2node() Args: node (str): Example: 'E3' Returns: tuple[int]: Example: (4, 2) """ res = REGEX_NODE.search(node) if res: x, y = res.group(1), res.group(2) y = int(y) if y > 0: y -= 1 return name2col(x), y else: # Whatever return ord(node[0]) % 32 - 1, int(node[1:]) - 1
See location2node() Args: node (str): Example: 'E3' Returns: tuple[int]: Example: (4, 2)
179,992
import re import cv2 import numpy as np from PIL import Image The provided code snippet includes necessary dependencies for implementing the `rgb2gray` function. Write a Python function `def rgb2gray(image)` to solve the following problem: Args: image (np.ndarray): Shape (height, width, channel) Returns: np.ndarray: Shape (height, width) Here is the function: def rgb2gray(image): """ Args: image (np.ndarray): Shape (height, width, channel) Returns: np.ndarray: Shape (height, width) """ r, g, b = cv2.split(image) return cv2.add( cv2.multiply(cv2.max(cv2.max(r, g), b), 0.5), cv2.multiply(cv2.min(cv2.min(r, g), b), 0.5) )
Args: image (np.ndarray): Shape (height, width, channel) Returns: np.ndarray: Shape (height, width)
180,008
from typing import Optional import numpy as np from module.base.decorator import cached_property from module.base.timer import Timer from module.logger import logger from tasks.character.switch import CharacterSwitch from tasks.map.keywords import MapPlane from tasks.map.keywords.plane import ( Herta_MasterControlZone, Herta_ParlorCar, Jarilo_AdministrativeDistrict, Luofu_AurumAlley, Luofu_ExaltingSanctum ) from tasks.map.minimap.minimap import Minimap from tasks.map.resource.resource import SPECIAL_PLANES from tasks.map.route.loader import RouteLoader as RouteLoader_ from tasks.rogue.blessing.ui import RogueUI from tasks.rogue.route.base import RouteBase from tasks.rogue.route.model import RogueRouteListModel, RogueRouteModel def model_from_json(model, file: str): with open(file, 'r', encoding='utf-8') as f: content = f.read() data = model.model_validate_json(content) return data
null
180,009
from module.base.decorator import cached_property from module.base.timer import Timer from module.exception import RequestHumanTakeover from module.logger import logger from tasks.rogue.assets.assets_rogue_path import * from tasks.rogue.assets.assets_rogue_ui import ROGUE_LAUNCH from tasks.rogue.blessing.ui import RogueUI from tasks.rogue.exception import RogueTeamNotPrepared from tasks.rogue.keywords import KEYWORDS_ROGUE_PATH, RoguePath The provided code snippet includes necessary dependencies for implementing the `area_pad_around` function. Write a Python function `def area_pad_around(area, pad)` to solve the following problem: Inner offset an area. Args: area: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y). pad (tuple): Returns: tuple: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y). Here is the function: def area_pad_around(area, pad): """ Inner offset an area. Args: area: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y). pad (tuple): Returns: tuple: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y). """ upper_left_x, upper_left_y, bottom_right_x, bottom_right_y = area upper_left_x_pad, upper_left_y_pad, bottom_right_x_pad, bottom_right_y_pad = pad return upper_left_x + upper_left_x_pad, \ upper_left_y + upper_left_y_pad, \ bottom_right_x - bottom_right_x_pad, \ bottom_right_y - bottom_right_y_pad
Inner offset an area. Args: area: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y). pad (tuple): Returns: tuple: (upper_left_x, upper_left_y, bottom_right_x, bottom_right_y).