Tests from two days ago with conversion from PNG format to SVG format with the python potrace package ...


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


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())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.



import os
import sqlite3
import datetime
import requests
from bs4 import BeautifulSoup
import shutil
# Locația tipică pentru istoricul Edge (Windows)
edge_history_path = os.path.expanduser(
r"~\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\History"
)
# Copiem fișierul History în folderul curent
def copy_history_file(src_path, dst_name="edge_history_copy.db"):
if not os.path.exists(src_path):
print("Nu am găsit istoricul Edge.")
return None
dst_path = os.path.join(os.getcwd(), dst_name)
try:
shutil.copy(src_path, dst_path)
print(f"Am copiat baza de date în {dst_path}")
return dst_path
except Exception as e:
print(f"Eroare la copiere: {e}")
return None
def extract_copilot_links(db_path):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("""
SELECT url, title, last_visit_time
FROM urls
WHERE url LIKE '%copilot%'
""")
results = []
for url, title, last_visit_time in cursor.fetchall():
ts = datetime.datetime(1601, 1, 1) + datetime.timedelta(microseconds=last_visit_time)
results.append({
"url": url,
"title": title,
"last_visit": ts.strftime("%Y-%m-%d %H:%M:%S")
})
conn.close()
return results
def fetch_conversation(url):
try:
resp = requests.get(url)
if resp.status_code == 200:
soup = BeautifulSoup(resp.text, "html.parser")
texts = soup.get_text(separator="\n", strip=True)
return texts
else:
return f"Eroare acces {url}: {resp.status_code}"
except Exception as e:
return f"Eroare acces {url}: {e}"
if __name__ == "__main__":
copy_path = copy_history_file(edge_history_path)
if copy_path:
chats = extract_copilot_links(copy_path)
if chats:
with open("copilot_conversations.txt", "w", encoding="utf-8") as f:
for chat in chats:
content = fetch_conversation(chat["url"])
f.write(f"=== Conversație: {chat['title']} ({chat['last_visit']}) ===\n")
f.write(content)
f.write("\n\n")
print("Am salvat conversațiile în copilot_conversations.txt")
else:
print("Nu am găsit conversații Copilot în istoricul Edge.")

class RangeSlider(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self._min, self._max = 0, 1000
self._start, self._end = 0, 1000
self._dragging = None
self.setMinimumHeight(24)
def setRange(self, minimum, maximum):
self._min, self._max = minimum, maximum
self._start, self._end = minimum, maximum
self.update()
def setStart(self, val):
self._start = max(self._min, min(val, self._end))
self.update()
def setEnd(self, val):
self._end = min(self._max, max(val, self._start))
self.update()
def start(self): return self._start
def end(self): return self._end
def _pos_to_val(self, x):
w = self.width()
ratio = max(0, min(x, w)) / w if w else 0
return int(self._min + ratio*(self._max-self._min))
def _val_to_pos(self, val):
w = self.width()
return int((val-self._min)/(self._max-self._min)*w) if self._max>self._min else 0
def mousePressEvent(self, e):
x = e.position().x()
sx, ex = self._val_to_pos(self._start), self._val_to_pos(self._end)
self._dragging = "start" if abs(x-sx)<abs(x-ex) else "end"
self.mouseMoveEvent(e)
def mouseMoveEvent(self, e):
if self._dragging:
val = self._pos_to_val(int(e.position().x()))
if self._dragging=="start": self.setStart(val)
else: self.setEnd(val)
def mouseReleaseEvent(self,e): self._dragging=None
def paintEvent(self,e):
p=QPainter(self); rect=self.rect()
sx,ex=self._val_to_pos(self._start),self._val_to_pos(self._end)
p.fillRect(rect,QColor(220,220,220))
p.fillRect(QRect(QPoint(sx,0),QPoint(ex,rect.height())),QColor(100,200,100,120))
p.setBrush(QColor(50,120,200)); p.setPen(Qt.PenStyle.NoPen)
p.drawEllipse(QPoint(sx,rect.center().y()),6,6)
p.drawEllipse(QPoint(ex,rect.center().y()),6,6)
import os
from xai_sdk import Client
from xai_sdk.chat import user
client = Client(
api_key=os.getenv("XAI_API_KEY"),
api_host="us-east-1.api.x.ai" # Without the https://
)
chat = client.chat.create(model="grok-4")
chat.append(user("What is the meaning of life?"))
completion = chat.sample()

import sys
import os
import shutil
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QFileDialog, QMessageBox
from PyQt6.QtCore import QDateTime
class FileRenamer(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Redenumire fișiere cu dată și index")
self.setGeometry(100, 100, 400, 150)
layout = QVBoxLayout()
self.button = QPushButton("Selectează folderul și redenumește fișierele")
self.button.clicked.connect(self.rename_files)
layout.addWidget(self.button)
self.setLayout(layout)
def rename_files(self):
folder = QFileDialog.getExistingDirectory(self, "Selectează folderul")
if not folder:
return
files = [f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]
files.sort() # Sortează pentru consistență
for index, filename in enumerate(files, start=1):
old_path = os.path.join(folder, filename)
try:
creation_time = os.path.getctime(old_path)
dt = QDateTime.fromSecsSinceEpoch(int(creation_time))
date_str = dt.toString("yyyyMMdd_HHmmss")
ext = os.path.splitext(filename)[1]
new_name = f"{date_str}_{index:03d}{ext}"
new_path = os.path.join(folder, new_name)
# Evită suprascrierea fișierelor existente
if not os.path.exists(new_path):
shutil.move(old_path, new_path)
except Exception as e:
QMessageBox.critical(self, "Eroare", f"Eroare la fișierul {filename}:\n{str(e)}")
continue
QMessageBox.information(self, "Succes", "Fișierele au fost redenumite cu succes!")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = FileRenamer()
window.show()
sys.exit(app.exec())



pipe = StableVideoDiffusionPipeline.from_pretrained(
'stabilityai/stable-video-diffusion-img2vid-xt',
torch_dtype=torch.float16,
variant='fp16'
)
pipe.enable_model_cpu_offload()python -m pip install -U nuitka
Collecting nuitka
Downloading Nuitka-2.7.tar.gz (3.9 MB)
...
Successfully built nuitka
Installing collected packages: zstandard, ordered-set, nuitka
Successfully installed nuitka-2.7 ordered-set-4.1.0 zstandard-0.23.0
[notice] A new release of pip is available: 25.0.1 -> 25.1.1
[notice] To update, run: python.exe -m pip install --upgrade pippython.exe -m pip install --upgrade pip
...
Successfully installed pip-25.1.1
python -m nuitka --version
2.7
Commercial: None
Python: 3.13.0rc1 (tags/v3.13.0rc1:e4a3e78, Jul 31 2024, 20:58:38) [MSC v.1940 64 bit (AMD64)]
Flavor: CPython Official
GIL: yes
Executable: C:\Python313\python.exe
OS: Windows
Arch: x86_64
WindowsRelease: 10
Nuitka-Scons:WARNING: Windows SDK must be installed in Visual Studio for it to be usable
Nuitka-Scons:WARNING: with Nuitka. Use the Visual Studio installer for adding it.
Version C compiler: ~\AppData\Local\Nuitka\Nuitka\Cache\downloads\gcc\x86_64\14.2.0posix-19.1.1-12.0.0-msvcrt-r2\mingw64\bin\gcc.exe (gcc 14.2.0).python -m nuitka --version
2.7
Commercial: None
Python: 3.13.3 (tags/v3.13.3:6280bb5, Apr 8 2025, 14:47:33) [MSC v.1943 64 bit (AMD64)]
Flavor: CPython Official
GIL: yes
Executable: C:\Python313\python.exe
OS: Windows
Arch: x86_64
WindowsRelease: 10
Nuitka-Scons:WARNING: Windows SDK must be installed in Visual Studio for it to be usable
Nuitka-Scons:WARNING: with Nuitka. Use the Visual Studio installer for adding it.
Version C compiler: ~\AppData\Local\Nuitka\Nuitka\Cache\downloads\gcc\x86_64\14.2.0posix-19.1.1-12.0.0-msvcrt-r2\mingw64\bin\gcc.exe (gcc 14.2.0).python -m pip install -U nuitka
Collecting nuitka
...
Installing collected packages: zstandard, ordered-set, nuitka
Successfully installed nuitka-2.7 ordered-set-4.1.0 zstandard-0.23.0
[notice] A new release of pip is available: 24.2 -> 25.1.1
[notice] To update, run: python.exe -m pip install --upgrade pip
python.exe -m pip install --upgrade pip
Requirement already satisfied: pip in c:\python_3_13_0\lib\site-packages (24.2)
...
Successfully installed pip-25.1.1py -3.12 -m pip install -U nuitka
Collecting nuitka
Using cached Nuitka-2.7.tar.gz (3.9 MB)
Installing build dependencies ... done
...
Installing collected packages: zstandard, ordered-set, nuitka
Successfully installed nuitka-2.7 ordered-set-4.1.0 zstandard-0.23.0
[notice] A new release of pip is available: 24.2 -> 25.1.1
[notice] To update, run: C:\Python312\python.exe -m pip install --upgrade pip
py -0
-V:3.13 * Python 3.13 (64-bit)
-V:3.12 Python 3.12 (64-bit)
py -3.12 -m nuitka --mingw64 hello.py
Nuitka-Options: Used command line options:
Nuitka-Options: --mingw64 hello.py
Nuitka-Options:WARNING: You did not specify to follow or include anything but main
Nuitka-Options:WARNING: program. Check options and make sure that is intended.
Nuitka: Starting Python compilation with:
Nuitka: Version '2.7' on Python 3.12 (flavor 'CPython Official')
Nuitka: commercial grade 'not installed'.
Nuitka: Completed Python level compilation and optimization.
Nuitka: Generating source code for C backend compiler.
Nuitka: Running data composer tool for optimal constant value handling.
Nuitka: Running C compilation via Scons.
Nuitka-Scons: Backend C compiler: gcc (gcc 14.2.0).
Nuitka-Scons: Backend C linking with 6 files (no progress information available for
Nuitka-Scons: this stage).
Nuitka-Scons: Compiled 6 C files using ccache.
Nuitka-Scons: Cached C files (using ccache) with result 'cache miss': 6
Nuitka: Keeping build directory 'hello.build'.
Nuitka: Successfully created 'D:\PythonProjects\hello.exe'.
Nuitka: Execute it by launching 'hello.cmd', the batch file needs to set environment.def talk(message):
return "Talk " + message
def main():
print(talk("Hello World"))
if __name__ == "__main__":
main()hello.exe
Talk Hello Worldsystem32>setx.exe FAL_KEY "e6fd708c-8065-4c73-ac2a-e3c73c6ff0fe:f70e0adb08362a3073993efa31b6acee"
SUCCESS: Specified value was saved.import fal_client
response = fal_client.run("fal-ai/fast-sdxl", arguments={"prompt": "a cute cat, realistic, orange"})
print(response["images"][0]["url"])python test_fal_client_001.py
https://v3.fal.media/files/rabbit/kY2MZG6LLkzjyIT8J3oiI.jpe
pip install pig-python
Collecting pig-python
...
Successfully installed aiohttp-retry-2.9.1 click-8.1.8 iso8601-2.1.0 pig-python-0.1.2 simple-term-menu-1.6.6 tabulate-0.9.0piglet join --secret the_API_key
Display dimensions: 1280x720
Local server running at http://localhost:3000
Connected to control server
"""
Example script showing how to properly initialize the Pig client with an API key
using both environment variable and direct constructor methods.
"""
import os
from pig import Client
# Example API key (replace with your actual API key in production)
API_KEY = "SK-..."
def initialize_with_env_variable():
"""
Method 1: Initialize Pig client using environment variable
This is the recommended approach for production environments
"""
# Set the environment variable
os.environ["PIG_SECRET_KEY"] = API_KEY
# Initialize the client (it will automatically use the environment variable)
client = Client()
print("Client initialized using environment variable")
return client
def initialize_with_direct_key():
"""
Method 2: Initialize Pig client by passing the API key directly
Useful for testing or when environment variables are not preferred
"""
# Initialize the client by passing the API key directly to the constructor
client = Client(api_key=API_KEY)
print("Client initialized by passing API key directly")
return client
if __name__ == "__main__":
# Example 1: Using environment variable
client1 = initialize_with_env_variable()
# Example 2: Passing API key directly
client2 = initialize_with_direct_key()
# Both methods achieve the same result
print("Both initialization methods are complete!")git clone https://github.com/jaypatel15406/Ollama-Adaptive-Image-Code-Gen.git
Cloning into 'Ollama-Adaptive-Image-Code-Gen'...
Resolving deltas: 100% (30/30), done.
cd Ollama-Adaptive-Image-Code-Gen
Ollama-Adaptive-Image-Code-Gen>pip3 install -r requirements.txt
Collecting ollama (from -r requirements.txt (line 1))
...
Installing collected packages: propcache, multidict, frozenlist, aiohappyeyeballs, yarl, aiosignal, ollama,
aiohttp
Successfully installed aiohappyeyeballs-2.4.8 aiohttp-3.11.13 aiosignal-1.3.2 frozenlist-1.5.0 multidict-6.1.0
ollama-0.4.7 propcache-0.3.0 yarl-1.18.3
Ollama-Adaptive-Image-Code-Gen>python main.py
utility : pull_model_instance : Instansiating 'llama3.1' ...
utility : pull_model_instance : 'llama3.1' Model Fetching Status : pulling manifest
utility : pull_model_instance : 'llama3.1' Model Fetching Status : pulling 667b0c1932bc
Ollama-Adaptive-Image-Code-Gen>python main.py
utility : pull_model_instance : Instansiating 'llama3.1' ...
utility : pull_model_instance : 'llama3.1' Model Fetching Status : pulling manifest
utility : pull_model_instance : 'llama3.1' Model Fetching Status : pulling 667b0c1932bc
utility : pull_model_instance : 'llama3.1' Model Fetching Status : pulling 948af2743fc7
utility : pull_model_instance : 'llama3.1' Model Fetching Status : pulling 0ba8f0e314b4
utility : pull_model_instance : 'llama3.1' Model Fetching Status : pulling 56bb8bd477a5
utility : pull_model_instance : 'llama3.1' Model Fetching Status : pulling 455f34728c9b
utility : pull_model_instance : 'llama3.1' Model Fetching Status : verifying sha256 digest
utility : pull_model_instance : 'llama3.1' Model Fetching Status : writing manifest
utility : pull_model_instance : 'llama3.1' Model Fetching Status : success
=========================================================================================
utility : get_prompt_response : Prompt : Choose the dimension of the shape: '2D' or '3D'. NOTE: Return only the chosen dimension.
ERROR:root: utility : get_prompt_response : Error : model requires more system memory (5.5 GiB) than is available (5.1 GiB) (status code: 500) ...