Skip to content

Instantly share code, notes, and snippets.

@rejgan318
Last active January 5, 2024 00:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rejgan318/ad441ae00027fca97abf45ecab691aa5 to your computer and use it in GitHub Desktop.
Save rejgan318/ad441ae00027fca97abf45ecab691aa5 to your computer and use it in GitHub Desktop.
[Python] #usefull# - полезности

Полезности и сервис, красивый вывод

colorama_test.py

Тест цвета и позиции курсора

SimpleProgressBar.py

простой однострочный прогресс-бар с параметрыми

download_random_images.py

Download random images from picsum.photos

# red, grenn blue - int 0..255
fore_rgb = lambda red, green, blue: f"\x1b[38;2;{red};{green};{blue}m"
back_rgb = lambda red, green, blue: f"\x1b[48;2;{red};{green};{blue}m"
RESET = "\x1b[0m"
""" https://pypi.org/project/colorama/ """
from colorama import Fore, Back, Style, init, Cursor
from time import sleep, time
tb = time()
init()
print(f'Поехали...{Fore.BLUE}Номного синего {Back.GREEN}и с зеленым фоном'
f'{Fore.RESET}{Back.RESET} '
f'{Style.BRIGHT}немного яркого{Style.NORMAL} обычный')
print(f'Нестандартный {Fore.LIGHTRED_EX}свето-{Style.BRIGHT}красный{Style.NORMAL}{Fore.RESET} цвет')
ForeRED = '\x1b[31m'
ForeRESET = '\x1b[39m'
print(f'Немного {ForeRED}красного текста{ForeRESET} через ESC-последовалености без colorama')
input('Press Enter')
fan = ["-", "\\", "|", "/"]
delay = 0.2
print(Cursor.POS(1, 1)+' '*100, end='')
print(Cursor.POS(1, 2)+' '*100, end='')
print(Cursor.POS(1, 3)+' '*100, end='')
print(Cursor.UP(2))
print(r" -----=------ ")
print(r" / \ ")
print(r"===( )=====( )===", end="")
roll_imdex = 0
for i in range(5):
print(f"{Cursor.BACK(13)}{fan[roll_imdex]}{Cursor.FORWARD(7)}{fan[roll_imdex]}{Cursor.FORWARD(4)}", end="")
roll_imdex = roll_imdex + 1 if roll_imdex < len(fan) - 1 else 0
sleep(delay)
te = time() - tb
print('\nDone')
print('Будет затерто')
print(Cursor.UP(1)+'Затерли выше ')
def dataclass2csv(filename: str, rows: list, header: bool = True):
# from dataclasses import astuple, fields
# rows is list of dataclass
with open(filename, 'w', encoding='utf-8', newline='') as csv_file:
# dialect='unix' for quoting all fields
csv_writer = csv.writer(csv_file, dialect='unix')
if header:
csv_writer.writerow(field.name for field in fields(rows[0]))
csv_writer.writerows([astuple(row) for row in rows])
from random import sample
from pathlib import Path
import requests
# Set False if you don't use tqdm. Else 'pip install tqdm'
USE_TQDM = True
if USE_TQDM:
from tqdm import tqdm
def download_random_images(path: str = None,
count: int = None,
size: tuple[int, int] = None,
use_tqdm: bool = False) -> list[str]:
"""
Download random images from picsum.photos
Note: We can use same threads with count=1
:param path: directory for downloaded images. Must be. Default: current directory
:param count: Count of images to download. Default: 1
:param size: Size of image (width, height) in pixels. Default: (300, 200)
:param use_tqdm: True to show tqdm progress indicator. Default False
:return: List of downloaded images full names
"""
path = Path(path or Path.cwd())
count = count or 1
size = size or (300, 200)
url = f'https://picsum.photos/{size[0]}/{size[1]}' # returns random image every time
range_images = range(count)
if USE_TQDM:
range_images = range_images if not use_tqdm else tqdm(range_images, desc="Downloading images")
random_nums = sample(range(10000), count)
images = []
for i in range_images:
response = requests.get(url)
if response.status_code == 200:
image_name = f'{size[0]}x{size[1]}_{random_nums[i]:04}.jpg'
full_name = str(path / image_name)
with open(full_name, 'wb') as file:
file.write(response.content)
images.append(full_name)
return images
if __name__ == "__main__":
# Example usage
from pprint import pprint
# parameters by default
random_images = download_random_images()
print(f"Downloaded to current directory image {Path(random_images[0]).name}")
IMG_PATH = r"random_images"
IMG_COUNT = 3
IMG_SIZE = (400, 400)
print(f"Download {IMG_COUNT} images to {IMG_PATH} size {IMG_SIZE[0]}x{IMG_SIZE[1]}px")
Path(IMG_PATH).mkdir(parents=True, exist_ok=True)
random_images = download_random_images(path=IMG_PATH, count=IMG_COUNT, size=IMG_SIZE, use_tqdm=True)
pprint(random_images)
# Test for lib keyboard
import keyboard
import time
# Example 1
while True:
event = keyboard.read_event()
if event.event_type == keyboard.KEY_DOWN and event.name == 'f3':
print('f3 pressed!')
elif event.event_type == keyboard.KEY_DOWN and event.name == 'esc':
break
# Example 2
HOT_KEY_OUT = 'esc'
def esc_event(e):
global esc_pressed
esc_pressed = True
keyboard.unhook_key(HOT_KEY_OUT)
print(f" {HOT_KEY_OUT.upper()} was pressed!", end="")
keyboard.hook_key(HOT_KEY_OUT, esc_event)
esc_pressed = False
while not esc_pressed:
print(f"Press {HOT_KEY_OUT} for exit or wait 5 sec...", end='')
time.sleep(5)
print(" next step." if not esc_pressed else " Exit")
# Normalize columns of a dataframe
# https://stackoverflow.com/questions/26414913/normalize-columns-of-a-dataframe
normalized_df=(df-df.mean())/df.std()
###
normalized_df=(df-df.min())/(df.max()-df.min())
###
import pandas as pd
from sklearn import preprocessing
x = df.values #returns a numpy array
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(x)
df = pd.DataFrame(x_scaled)
from functools import partial
str_int = '101'
print(f"{str_int=}")
print(f"{int(str_int, base=10)=}") # 101
print(f"{int(str_int, base=2)=}") # 5
print(f"{int(str_int)=}") # 101
int2 = partial(int, base=2)
print(f"{int2=}") # 101
print(f"{int2(str_int, base=10)=}") # 101
print(f"{int2(str_int, base=2)=}") # 5
print(f"{int2(str_int)=}") # 5
def progress_bar(progress: float | int, total: float | int, symbol: str = '█', empty_symbol: str = '░', width: int = 100) -> None:
"""
горизонтальный прогресс-бар
:param progress: текущеее значение
:param total: максимальное значение
:param symbol: символ вывода прогресса
:param empty_symbol: символ заполнения
:param width: ширина в символах
:return:
"""
print(f'{symbol * int(width * progress / total):{empty_symbol}<{width}} {round(progress / total * 100):3}%', end='\r')
if __name__ == '__main__':
import math
n = 100
for i in range(n):
result = math.factorial(i * 1000)
# Win + . - select unicode char
progress_bar(i+1, n, width=20)
print()
# Monitoring real time cpu and ram usage with tqdm. If you like it please upvote this answer: https://stackoverflow.com/a/69511430/8896457
from tqdm import tqdm
from time import sleep
import psutil
with tqdm(total=100, desc='cpu%', position=1) as cpubar, tqdm(total=100, desc='ram%', position=0) as rambar:
while True:
rambar.n=psutil.virtual_memory().percent
cpubar.n=psutil.cpu_percent()
rambar.refresh()
cpubar.refresh()
sleep(0.5)
# Python warnings managment https://docs.python.org/3/library/warnings.html
import warnings
warnings.filterwarnings("ignore")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment