open_text = 'текст' # открытый текст
# letters - именно строка, одна позиция - один символ
letters = ''.join(['а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф',
'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я'])
key = 5 # ключ к шифру - величина сдвига. Может быть >0 или <0
# генерируем таблицы подстановки
encrypt_table = str.maketrans(letters, letters[key:]+letters[:key]) # для шифрования
decrypt_table = str.maketrans(letters, letters[-key:]+letters[:-key]) # для дешифрования
cypher_text = open_text.translate(encrypt_table)
restored_text = cypher_text.translate(decrypt_table)
print(open_text)
print(cypher_text)
print(restored_text)
import numpy
import matplotlib.pyplot as plt
with open('data.txt', 'rt') as src:
src.readline() # пропускаем заголовок
points = numpy.array([
[int(v) for v in row.split(';')]
for row in src
])
width = points[:, 0].max()
height = points[:, 1].max()
image = numpy.array((height, width), dtype=numpy.uint8)
for x, y, c in points:
image[y, x] = c
plt.imshow(image, cmap='gray')
plt.show()
import typing as tp
Func = tp.Callable[[], None] # функция без апарметров, возвращает None
class FuncMap:
def __init__(self):
self.map: tp.Dict[str, Func] = dict()
def register(self, key: str) -> tp.Callable[[Func], Func]:
def decorate(f: Func) -> Func:
self.map[key] = f
return f
return decorate
def get(self, key: str) -> Func:
return self.map[key]
def run(self, key: str):
return self.map[key]()
# а вот так этот класс используется
fmap = FuncMap()
@fmap.register('11')
def test():
print('This is test()')
fmap.run('11')
# handlers.py
def setup(dp, pool):
# внутри setup уже объявляешь обработчики
@dp.message_handler(content_types=['text'])
def some_handler(message: types.message):
...
# main.py
connection_pool = await create_asyncpg_connection_pool()
dp = ...
import handlers
handlers.setup(dp, connection_pool) # вызывать строго один раз!
elif user_data[5] == '<:939223290105454632:1164940159050059786>':
...
elif user_data[5] == '<:939195860317773856:1164153649296048148>':
...
elif user_data[5] == '<:939223290105454632:1164940159050059786>': # Добавлено условие для железной кирки
...
x = 1
if x == 0:
print('Ноль!')
elif x == 1:
print('Один!')
elif x == 2:
print('Два!')
elif x == 1:
print('Раз!')
x = 1
if x == 0:
print('Ноль!')
elif x == 1:
print('Раз!')
elif x == 2:
print('Два!')
from pathlib import Path
import importlib
import sys
SCRIPT = Path(sys.argv[0]).parent.resolve()
IMPORT_FROM = 'webhooks'
for fpath in (SCRIPT / IMPORT_FROM).iterdir():
# импортим .py файлы и подкаталоги c __init__.py внутри
# игнорим __init__.py и подобное, а также файлы, начинающиеся с .
if not fpath.stem.startswith('_') and not fpath.stem.startswith('.') and \
((fpath.suffix == '.py') or (fpath.is_dir() and (fpath / '__init__.py').is_file())):
try:
# эквивалент import webhooks.имяфайла as module
module = importlib.import_module(f'{IMPORT_FROM}.{fpath.stem}')
dp.include_router(module.router)
except Exception as err:
print(err) # журналируй ошибку
schedule(event_handler, path, recursive=False)
Schedules watching a path and calls appropriate methods specified in the given event handler in response to file system events.
Parameters:
event_handler (watchdog.events.FileSystemEventHandler or a subclass) – An event handler instance that has appropriate event handling methods which will be called by the observer in response to file system events.
path (str) – Directory path that will be monitored.
recursive (bool) – True if events will be emitted for sub-directories traversed recursively; False otherwise.
Returns:
An ObservedWatch object instance representing a watch.