Python can process data from an HLS (.m3u8) video stream, such as the one used on the Fălticeni webcam page (which loads the stream through index.m3u8).

Python tutorials with source code, examples, guides, and tips and tricks for Windows and Linux development.

pip install manim
...
Successfully installed audioop-lts-0.2.2 av-16.1.0 cloup-3.0.8 glcontext-3.0.0 isosurfaces-0.1.2 manim-0.20.1 manimpango-0.6.1 mapbox-earcut-2.0.0 moderngl-5.12.0 moderngl-window-3.1.1 pycairo-1.29.0 pydub-0.25.1 pyglet-2.1.13 pyglm-2.8.3 screeninfo-0.8.1 skia-pathops-0.9.2 srt-3.5.3import subprocess
import sys
import datetime
log_file = "upgrade_log.txt"
def log(msg):
with open(log_file, "a", encoding="utf-8") as f:
f.write(msg + "\n")
print(msg)
def get_installed_packages():
result = subprocess.run(
[sys.executable, "-m", "pip", "list", "--format=freeze"],
capture_output=True,
text=True
)
lines = result.stdout.strip().split("\n")
packages = []
for line in lines:
if "@" in line: # skip direct URL installs
pkg = line.split("@")[0]
else:
pkg = line.split("==")[0]
packages.append(pkg)
return sorted(packages)
def upgrade_package(package):
log(f"\n=== Updating: {package} ===")
try:
subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", package])
log(f"[OK] Updated: {package}")
except subprocess.CalledProcessError:
log(f"[FAILED] Could not update: {package}")
def main():
log(f"\n--- Upgrade started at {datetime.datetime.now()} ---\n")
packages = get_installed_packages()
log(f"Found {len(packages)} packages.\n")
for pkg in packages:
upgrade_package(pkg)
log(f"\n--- Upgrade finished at {datetime.datetime.now()} ---\n")
if __name__ == "__main__":
main()python -m pip install build123d
Collecting build123d
Downloading build123d-0.10.0-py3-none-any.whl.metadata (6.7 kB)
...
Successfully installed anytree-2.13.0 asttokens-3.0.1 build123d-0.10.0 cadquery-ocp-7.8.1.1.post1 cadquery_ocp_proxy-7.9.3.1 cadquery_vtk-9.3.1 decorator-5.2.1 executing-2.2.1 ezdxf-1.4.3 ipython-9.10.0 ipython-pygments-lexers-1.1.1 lib3mf-2.5.0 matplotlib-inline-0.2.1 ocp_gordon-0.2.0 ocpsvg-0.5.0 pure-eval-0.2.3 stack_data-0.6.3 svgelements-1.9.6 svgpathtools-1.7.2 traitlets-5.14.3 trianglesolver-1.2 webcolors-24.8.0
import os
import sys
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtCore import QUrl
import py3Dmol
SEROTONIN_SMILES = "C1=CC2=C(C=C1)C(=CN2)CCN"
def generate_html(smiles):
view = py3Dmol.view(width=800, height=600)
view.addModel(smiles, "smiles")
view.setStyle({"stick": {}})
view.zoomTo()
return view._make_html()
class MoleculeViewer(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Structura 3D – Serotonină")
layout = QVBoxLayout(self)
self.browser = QWebEngineView()
html = generate_html(SEROTONIN_SMILES)
# IMPORTANT: QUrl, nu string!
self.browser.setHtml(html, baseUrl=QUrl("https://localhost/"))
layout.addWidget(self.browser)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MoleculeViewer()
window.resize(900, 700)
window.show()
sys.exit(app.exec())


C:\Python313_64bit>python
Python 3.13.0 (tags/v3.13.0:60403a5, Oct 7 2024, 09:38:07) [MSC v.1941 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import sys
(r-search `os') import os


import time
import sys
import logging
import argparse
import msvcrt # Windows keyboard input
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn
from rich.syntax import Syntax
from rich.layout import Layout
from rich.live import Live
from rich.theme import Theme
from rich.logging import RichHandler
# ---------------------------------------------------------
# 1. DARK THEME
# ---------------------------------------------------------
dark_theme = Theme({
"info": "bold cyan",
"warning": "bold yellow",
"error": "bold red",
"success": "bold green",
"title": "bold magenta",
"data": "bold white",
})
console = Console(theme=dark_theme)
# ---------------------------------------------------------
# 2. LOGGING (RichHandler)
# ---------------------------------------------------------
logging.basicConfig(
level="INFO",
format="%(message)s",
datefmt="[%H:%M:%S]",
handlers=[RichHandler(console=console)]
)
log = logging.getLogger("CLI")
# ---------------------------------------------------------
# 3. CLI ARGUMENTS
# ---------------------------------------------------------
def parse_args():
parser = argparse.ArgumentParser(
description="Rich CLI + Dashboard + Menu + Buttons"
)
parser.add_argument("--demo", action="store_true", help="Run the demo")
parser.add_argument("--dashboard", action="store_true", help="Start the dashboard")
return parser.parse_args()
# ---------------------------------------------------------
# 4. WINDOWS KEY READER
# ---------------------------------------------------------
def get_key():
if msvcrt.kbhit():
return msvcrt.getch().decode(errors="ignore")
return None
# ---------------------------------------------------------
# 5. MENU + BUTTONS
# ---------------------------------------------------------
menu_items = ["Statistics", "Processes", "Settings", "Exit"]
selected = 0
def render_menu():
table = Table(show_header=False, expand=True)
for i, item in enumerate(menu_items):
if i == selected:
table.add_row(f"[black on cyan] {item} [/]")
else:
table.add_row(f"[cyan] {item} [/]")
return Panel(table, title="Menu", border_style="cyan")
def render_content():
if menu_items[selected] == "Statistics":
return Panel("CPU: 37%\nRAM: 62%\nDisk: 128MB/s", title="System Statistics")
elif menu_items[selected] == "Processes":
return Panel("proc1\nproc2\nproc3", title="Running Processes")
elif menu_items[selected] == "Settings":
return Panel("Settings will appear here", title="Settings")
elif menu_items[selected] == "Exit":
return Panel("[red]Press ENTER to exit[/red]", title="Exit")
# ---------------------------------------------------------
# 6. DASHBOARD LAYOUT (original + menu added)
# ---------------------------------------------------------
def build_dashboard():
layout = Layout()
layout.split(
Layout(name="header", size=3),
Layout(name="body", ratio=1),
Layout(name="footer", size=3),
)
layout["body"].split_row(
Layout(name="left", size=30),
Layout(name="right")
)
layout["header"].update(
Panel("[title]LIVE DASHBOARD — Rich Dark Mode[/title]", style="bold magenta")
)
layout["left"].update(render_menu())
layout["right"].update(render_content())
layout["footer"].update(
Panel("[info]Status: Running in real time[/info]")
)
return layout
# ---------------------------------------------------------
# 7. DEMO (unchanged from first script)
# ---------------------------------------------------------
def run_demo():
console.print("[success]Rich Dark Mode Demo Started[/success]")
table = Table(title="Example Table", expand=True)
table.add_column("ID", style="yellow")
table.add_column("Name", style="cyan")
table.add_column("Status", style="green")
table.add_row("1", "Catalin", "Active")
table.add_row("2", "Rich CLI", "OK")
table.add_row("3", "Dashboard", "Ready")
console.print(table)
log.info("This is an INFO message")
log.warning("This is a WARNING message")
log.error("This is an ERROR message")
with Progress(
SpinnerColumn(),
BarColumn(),
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
console=console,
) as progress:
task = progress.add_task("Processing...", total=100)
for _ in range(100):
time.sleep(0.02)
progress.update(task, advance=1)
code = """
def greet(name):
return f"Hello, {name}!"
print(greet("Catalin"))
"""
syntax = Syntax(code, "python", theme="monokai", line_numbers=True)
console.print(Panel(syntax, title="Syntax Highlight"))
# ---------------------------------------------------------
# 8. MAIN LOOP
# ---------------------------------------------------------
if __name__ == "__main__":
args = parse_args()
if args.demo:
run_demo()
if args.dashboard:
with Live(build_dashboard(), refresh_per_second=10) as live:
while True:
key = get_key()
if key == "w":
selected = (selected - 1) % len(menu_items)
elif key == "s":
selected = (selected + 1) % len(menu_items)
elif key == "\r":
if menu_items[selected] == "Exit":
break
live.update(build_dashboard())

mkdir my_app_catafest
cd my_app_catafest
my_app_catafest>python -m venv .venv
my_app_catafest>.venv\Scripts\activate
(.venv) C:\PyQt6\reflex_framework\my_app_catafest>pip install reflex
Collecting reflex
Using cached reflex-0.8.26-py3-none-any.whl.metadata (13 kB)
...
Installing collected packages: wrapt, typing-extensions, redis, python-multipart, pygments, psutil, platformdirs, packaging, mdurl, MarkupSafe, idna, h11, greenlet, colorama, certifi, bidict, annotated-types, wsproto, typing-inspection, SQLAlchemy, pydantic-core, markdown-it-py, Mako, httpcore, click, anyio, watchfiles, starlette, simple-websocket, rich, pydantic, httpx, granian, alembic, sqlmodel, reflex-hosting-cli, python-engineio, python-socketio, reflex
Successfully installed Mako-1.3.10 MarkupSafe-3.0.3 SQLAlchemy-2.0.46 alembic-1.18.1 annotated-types-0.7.0 anyio-4.12.1 bidict-0.23.1 certifi-2026.1.4 click-8.3.1 colorama-0.4.6 granian-2.6.1 greenlet-3.3.1 h11-0.16.0 httpcore-1.0.9 httpx-0.28.1 idna-3.11 markdown-it-py-4.0.0 mdurl-0.1.2 packaging-25.0 platformdirs-4.5.1 psutil-7.2.1 pydantic-2.12.5 pydantic-core-2.41.5 pygments-2.19.2 python-engineio-4.13.0 python-multipart-0.0.22 python-socketio-5.16.0 redis-7.1.0 reflex-0.8.26 reflex-hosting-cli-0.1.61 rich-14.3.1 simple-websocket-1.1.0 sqlmodel-0.0.31 starlette-0.52.1 typing-extensions-4.15.0 typing-inspection-0.4.2 watchfiles-1.1.1 wrapt-2.0.1 wsproto-1.3.2
(.venv) C:\PyQt6\reflex_framework\my_app_catafest>reflex init
──────────────────────────────────────────── Initializing my_app_catafest ─────────────────────────────────────────────
[14:21:36] Initializing the web directory. console.py:231
Get started with a template:
(0) A blank Reflex app.
(1) Premade templates built by the Reflex team.
(2) Try our AI builder.
Which template would you like to use? (0):
[14:21:39] Initializing the app directory. console.py:231
Success: Initialized my_app_catafest using the blank template.
(.venv) C:\PyQt6\reflex_framework\my_app_catafest>reflex run
Warning: Windows Subsystem for Linux (WSL) is recommended for improving initial install times.
────────────────────────────────────── Starting Reflex App ──────────────────────────────────────
[14:27:31] Compiling: ---------------------------------------- 100% 21/21 0:00:02
⠙ Installing base frontend packages Resolving dependencies
... 
python -m pip install catboost
Collecting catboost
...
Installing collected packages: narwhals, plotly, catboost
Successfully installed catboost-1.2.8 narwhals-2.15.0 plotly-6.5.21 6 12 16 17 33 17 26 30 35 36 44 23 24 28 34 48 49 5 11 22 34 42 43 7 12 17 30 33 49 12 23 32 41 43 48 4 6 33 35 36 39 4 6 33 35 36 39 13 14 20 21 38 49 4 9 11 15 37 47 ...


import requests
import base64
import time
IMAGE_PATH = "test.png"
OLLAMA_URL = "http://localhost:11434/api/generate"
# Load and encode image
with open(IMAGE_PATH, "rb") as f:
img_bytes = f.read()
img_b64 = base64.b64encode(img_bytes).decode("utf-8")
def query_model(model_name, prompt):
payload = {
"model": model_name,
"prompt": prompt,
"images": [img_b64],
"stream": False
}
start = time.time()
r = requests.post(OLLAMA_URL, json=payload)
end = time.time()
r.raise_for_status()
response_text = r.json().get("response", "").strip()
elapsed = end - start
return response_text, elapsed
# Run Moondream
moondream_output, moondream_time = query_model("moondream", "Describe the image in detail")
# Run BakLLaVA
bakllava_output, bakllava_time = query_model("bakllava", "Describe the image in detail")
# Print results
print("=== Moondream Output ===")
print(moondream_output)
print(f"\n[Moondream time: {moondream_time:.2f} seconds]")
print("\n=== BakLLaVA Output ===")
print(bakllava_output)
print(f"\n[BakLLaVA time: {bakllava_time:.2f} seconds]")python test_time.py === Moondream Output === The image shows a video game screen with four players engaged in an intense battle. The player on the left is holding a sword, while another player stands nearby wielding a shield. A third player is seen running towards them, and the fourth player is positioned further back, also armed with a sword. The background of the scene features a dark and mysterious setting, possibly a cave or underground area. [Moondream time: 506.34 seconds] === BakLLaVA Output === The scene displays a group of monsters standing around a central point, creating an atmosphere reminiscent of a Dungeons & Dragons game. A total of nine monsters can be seen throughout the image, with some located closer to the center and others nearer corners. In addition to the monsters, there are several items scattered around, such as a bottle situated in the lower-left part of the scene. Interestingly, this image also contains text box information and appears to have a web address displayed, possibly related to the game or providing additional context for the scene. [BakLLaVA time: 597.49 seconds]




pip install potracer[cli]
Collecting potracer[cli]
...
Successfully installed potrace-cli-0.0.4 potracer-0.0.4dir(potrace)
['BezierSegment', 'Bitmap', 'COS179', 'CornerSegment', 'Curve', 'INFTY', 'Optional', 'POTRACE_CORNER',
'POTRACE_CURVETO', 'POTRACE_TURNPOLICY_BLACK', 'POTRACE_TURNPOLICY_LEFT', 'POTRACE_TURNPOLICY_MAJORITY',
'POTRACE_TURNPOLICY_MINORITY', 'POTRACE_TURNPOLICY_RANDOM', 'POTRACE_TURNPOLICY_RIGHT', 'POTRACE_TURNPOLICY_WHITE',
'Path', 'Tuple', 'Union', '_Curve', '_Path', '_Point', '_Segment', '_Sums', '__builtins__', '__cached__', '__doc__',
'__file__', '__loader__', '__name__', '__package__', '__spec__', '_adjust_vertices', '_bestpolygon', '_calc_lon',
'_calc_sums', '_opticurve', '_smooth', 'bezier', 'bm_to_pathlist', 'cprod', 'cyclic', 'ddenom', 'ddist', 'detrand',
'detrand_t', 'dorth_infty', 'dpara', 'findnext', 'findpath', 'floordiv', 'interval', 'iprod', 'iprod1', 'majority',
'math', 'mod', 'np', 'opti_penalty', 'opti_t', 'pathlist_to_tree', 'penalty3', 'pointslope', 'process_path', 'quadform',
'reverse', 'setbbox_path', 'sign', 'sq', 'tangent', 'xor_path', 'xor_to_ref', 'xprod']from PyQt6.QtWidgets import QStyleFactory
print(QStyleFactory.keys())
['windows11', 'windowsvista', 'Windows', 'Fusion']import sys
from PyQt6.QtWidgets import (
QApplication, QLabel, QLineEdit, QComboBox, QPushButton,
QCheckBox, QSlider, QVBoxLayout, QWidget
)
from PyQt6.QtCore import Qt
app = QApplication(sys.argv)
app.setStyle('windows11')
window = QWidget()
layout = QVBoxLayout(window)
# 1. QLabel
layout.addWidget(QLabel("Acesta este un QLabel"))
# 2. QLineEdit
layout.addWidget(QLineEdit("Text editabil"))
# 3. QComboBox
combo = QComboBox()
combo.addItems(["Optiunea 1", "Optiunea 2", "Optiunea 3"])
layout.addWidget(combo)
# 4. QCheckBox
layout.addWidget(QCheckBox("Bifează această opțiune"))
# 5. QSlider
slider = QSlider(Qt.Orientation.Horizontal)
layout.addWidget(slider)
# 5. QPushButton
button = QPushButton('Simple button !')
layout.addWidget(button)
# show the main windows
window.show()
sys.exit(app.exec())import sys
import ssl
import socket
from datetime import datetime
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from PyQt6.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QLabel,
QLineEdit, QPushButton, QTextEdit
)
def fetch_certificate_raw(hostname):
"""
Connects to the server and retrieves the certificate in DER format.
Also returns a validation status message.
"""
# Create a default SSL context (validates certificates)
context = ssl.create_default_context()
try:
# First attempt: strict validation
with socket.create_connection((hostname, 443), timeout=5) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
der_cert = ssock.getpeercert(binary_form=True)
return der_cert, "Certificate is VALID"
except ssl.SSLError as e:
# Certificate is invalid → try to retrieve it anyway
try:
unverified_context = ssl._create_unverified_context()
with socket.create_connection((hostname, 443), timeout=5) as sock:
with unverified_context.wrap_socket(sock, server_hostname=hostname) as ssock:
der_cert = ssock.getpeercert(binary_form=True)
return der_cert, f"Certificate is INVALID: {str(e)}"
except Exception:
return None, f"Could not retrieve certificate: {str(e)}"
except Exception as e:
return None, f"Connection error: {str(e)}"
def parse_certificate(der_cert):
"""
Converts a DER-encoded certificate into a cryptography.x509 object.
"""
return x509.load_der_x509_certificate(der_cert, default_backend())
class CertViewer(QWidget):
"""
Main GUI window for the HTTPS certificate viewer.
"""
def __init__(self):
super().__init__()
self.setWindowTitle("HTTPS Certificate Checker")
self.setGeometry(200, 200, 700, 600)
layout = QVBoxLayout()
# Input label + text field
layout.addWidget(QLabel("Enter URL (example: example.com):"))
self.input = QLineEdit()
layout.addWidget(self.input)
# Button to trigger certificate check
self.button = QPushButton("Check Certificate")
self.button.clicked.connect(self.check_certificate)
layout.addWidget(self.button)
# Output text box
self.output = QTextEdit()
self.output.setReadOnly(True)
layout.addWidget(self.output)
self.setLayout(layout)
def check_certificate(self):
"""
Triggered when the user presses the button.
Retrieves and displays certificate information.
"""
hostname = self.input.text().strip()
# Clean URL (remove http://, https://, and paths)
for prefix in ("https://", "http://"):
if hostname.startswith(prefix):
hostname = hostname[len(prefix):]
hostname = hostname.split("/")[0]
# Fetch certificate
der_cert, status = fetch_certificate_raw(hostname)
if der_cert is None:
self.output.setText(status)
return
# Parse certificate
cert = parse_certificate(der_cert)
# Build output text
text = f"=== CERTIFICATE STATUS ===\n{status}\n\n"
text += "=== CERTIFICATE DETAILS ===\n\n"
text += f"Subject:\n{cert.subject}\n\n"
text += f"Issuer:\n{cert.issuer}\n\n"
text += f"Serial Number: {cert.serial_number}\n\n"
text += f"Version: {cert.version}\n\n"
text += f"Valid From: {cert.not_valid_before}\n"
text += f"Valid To: {cert.not_valid_after}\n\n"
# Check expiration
if cert.not_valid_after < datetime.utcnow():
text += f"⚠ Certificate EXPIRED on: {cert.not_valid_after}\n\n"
# Subject Alternative Names (SAN)
try:
san = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName)
text += f"Subject Alternative Names:\n{san.value}\n\n"
except Exception:
text += "Subject Alternative Names: (none)\n\n"
self.output.setText(text)
if __name__ == "__main__":
app = QApplication(sys.argv)
viewer = CertViewer()
viewer.show()
sys.exit(app.exec())
import win32serviceutil
import win32service
import win32event
import servicemanagerpython service_test_001.py install
Installing service MyPythonService
Service installedimport win32serviceutil
import win32service
import win32event
import servicemanager
import time
class MyService(win32serviceutil.ServiceFramework):
_svc_name_ = "MyPythonService"
_svc_display_name_ = "My Python Windows Service"
_svc_description_ = "A minimal Windows service example written in Python."
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.stop_event = win32event.CreateEvent(None, 0, 0, None)
self.running = True
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.stop_event)
self.running = False
def SvcDoRun(self):
servicemanager.LogInfoMsg("MyPythonService is starting.")
self.main()
def main(self):
while self.running:
# Your service logic goes here
time.sleep(5)
servicemanager.LogInfoMsg("MyPythonService heartbeat.")
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(MyService)
pip install pywin32python C:\Python313\Scripts\pywin32_postinstall.py -install
Parsed arguments are: Namespace(install=True, remove=False, wait=None, silent=False, quiet=False, destination= ...D:\Python313_64bit>python
Python 3.13.0 (tags/v3.13.0:60403a5, Oct 7 2024, 09:38:07) [MSC v.1941 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import win32api
>>> print(win32api.GetVersion())
import sys
import csv
import os
import subprocess
from datetime import datetime
from PyQt6.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QCalendarWidget,
QInputDialog, QMessageBox
)
from PyQt6.QtCore import QDate
CSV_FILE = "note.csv"
class CalendarApp(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Calendar cu notițe")
self.resize(400, 300)
self.layout = QVBoxLayout()
self.setLayout(self.layout)
self.calendar = QCalendarWidget()
self.calendar.clicked.connect(self.adauga_nota)
self.layout.addWidget(self.calendar)
# Dicționar pentru notițe
self.note = {}
# La pornire, citește CSV și deschide în Notepad
self.incarca_note()
def adauga_nota(self, date: QDate):
zi = date.toString("yyyy-MM-dd")
text, ok = QInputDialog.getText(self, "Adaugă notiță",
f"Introdu text pentru {zi}:")
if ok and text.strip():
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
self.note[timestamp] = text.strip()
QMessageBox.information(self, "Salvat",
"Notița a fost adăugată.")
def incarca_note(self):
if os.path.exists(CSV_FILE):
try:
with open(CSV_FILE, "r", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
if len(row) == 2:
self.note[row[0]] = row[1]
# Deschide în Notepad
subprocess.Popen(["notepad.exe", CSV_FILE])
except Exception as e:
QMessageBox.warning(self, "Eroare",
f"Nu pot citi fișierul CSV:\n{e}")
def closeEvent(self, event):
try:
with open(CSV_FILE, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
for timestamp, text in self.note.items():
writer.writerow([timestamp, text])
except Exception as e:
QMessageBox.warning(self, "Eroare",
f"Nu pot salva fișierul CSV:\n{e}")
event.accept()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = CalendarApp()
window.show()
sys.exit(app.exec())

Python 3.12.12 (main, Oct 10 2025, 08:52:57) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
