analitics

Pages

Sunday, November 24, 2024

Python 3.13.0 : emoji symbols with PIL.

Today I want to use emoji symbols and I wrote this python script:
from PIL import Image, ImageDraw, ImageFont
import os

# Font size and image dimensions
font_size = 88
width = 640
height = 480

# Use Symbola.ttf from current directory
font_path = "Symbola.ttf"

# Create image
img = Image.new('RGB', (width, height), color='white')
draw = ImageDraw.Draw(img)

# Get font
font = ImageFont.truetype(font_path, font_size)

# Emoji matrix
emoji_matrix = [
    ['😀', '😁', '😂', '🤣', '😃'],
    ['😄', '😅', '😆', '😇', '😈'],
    ['😉', '😊', '😋', '😌', '😍'],
    ['😎', '😏', '😐', '😑', '😒']
]

# Calculate spacing
x_spacing = font_size + 10
y_spacing = font_size + 10

# Calculate starting position to center the grid
start_x = (width - (len(emoji_matrix[0]) * x_spacing)) // 2
start_y = (height - (len(emoji_matrix) * y_spacing)) // 2

# Draw emojis
for i, row in enumerate(emoji_matrix):
    for j, emoji in enumerate(row):
        x = start_x + (j * x_spacing)
        y = start_y + (i * y_spacing)
        draw.text((x, y), emoji, font=font, fill='black')

# Save the image
img.save('emoji_art.png')
print("Emoji art has been created successfully! Check emoji_art.png")
The result image named emoji_art.png is this:

Wednesday, November 20, 2024

Python 3.13.0 : generates multiple deformed polygonal shapes .

Today I created this source code in python that generates eight random convex polygons. The idea was to create sprites for a 2D game: snowballs, boulders, or similar objects... Obviously I also used Sonet 3.5 artificial intelligence. You can find the source code on the pagure account in fedora.
#!/usr/bin/env python3
"""
SVG Polygon Generator

This script generates multiple deformed polygonal shapes and saves them as separate SVG files.
Each polygon maintains convex properties while having controlled random deformations.

Features:
    - Generates 8 unique polygonal shapes
    - Controls deformation through radial and angular factors
    - Maintains convex properties
    - Exports each shape to a separate SVG file
    - Uses random colors for visual distinction

Usage:
    python generate_svgs.py

Output:
    Creates 8 SVG files named 'polygon_1.svg' through 'polygon_8.svg'
"""

from lxml import etree
import random
import math
from pathlib import Path


def create_svg_root():
    """Create and return a base SVG root element with standard attributes."""
    root = etree.Element("svg")
    root.set("width", "500")
    root.set("height", "500")
    root.set("xmlns", "http://www.w3.org/2000/svg")
    return root


def calculate_points(center_x: float, center_y: float, radius: float, 
                    num_sides: int, deform_factor: float) -> list:
    """
    Calculate polygon points with controlled deformation.

    Args:
        center_x: X coordinate of polygon center
        center_y: Y coordinate of polygon center
        radius: Base radius of the polygon
        num_sides: Number of polygon sides
        deform_factor: Maximum allowed deformation factor

    Returns:
        List of tuples containing (x, y) coordinates
    """
    points = []
    angle_step = 2 * math.pi / num_sides
    
    for i in range(num_sides):
        angle = i * angle_step
        radial_deform = random.uniform(-deform_factor, deform_factor)
        angular_deform = random.uniform(-deform_factor/2, deform_factor/2)
        
        modified_angle = angle + angular_deform
        modified_radius = radius * (1 + radial_deform)
        
        x = center_x + modified_radius * math.cos(modified_angle)
        y = center_y + modified_radius * math.sin(modified_angle)
        points.append((x, y))
    
    return points


def generate_deformed_shapes():
    """Generate multiple deformed polygons and save them to separate SVG files."""
    # Base parameters
    num_sides = 8
    center_x = 250
    center_y = 250
    base_radius = 150
    max_deformation = 0.15
    output_dir = Path("generated_polygons")
    
    # Create output directory if it doesn't exist
    output_dir.mkdir(exist_ok=True)

    for i in range(8):
        root = create_svg_root()
        points = calculate_points(center_x, center_y, base_radius, 
                                num_sides, max_deformation)
        
        path = etree.SubElement(root, "path")
        path_data = f"M {points[0][0]} {points[0][1]}"
        path_data += "".join(f" L {p[0]} {p[1]}" for p in points[1:])
        path_data += " Z"
        
        path.set("d", path_data)
        path.set("fill", "none")
        path.set("stroke", f"#{random.randint(0, 16777215):06X}")
        path.set("stroke-width", "2")
        path.set("opacity", "0.7")

        # Save individual SVG file
        output_file = output_dir / f"polygon_{i+1}.svg"
        tree = etree.ElementTree(root)
        tree.write(str(output_file), pretty_print=True, 
                  xml_declaration=True, encoding='utf-8')
    
    print(f"Generated {num_sides} polygons in {output_dir}")

if __name__ == "__main__":
    generate_deformed_shapes()

Monday, November 18, 2024

Python 3.13.0 : Tested TinyDB on Fedora 41.

Today I tested the TinyDB python package on Fedora 41 Linux distro:
TinyDB is a lightweight document oriented database optimized for your happiness :) It’s written in pure Python and has no external dependencies. The target are small apps that would be blown away by a SQL-DB or an external database server.
The documentation for this python package can be found on the official website.
The install on Fedora 14 distro can be done with pip tool:
pip install tinydb
This is the source code I tested:
from tinydb import TinyDB, Query
import datetime

# Create a TinyDB instance
db = TinyDB('my_database.json')

# Define a schema for our documents
UserSchema = {
    'name': str,
    'email': str,
    'age': int,
    'created_at': datetime.datetime
}# Insert some sample data
users = [
    {'name': 'John Doe', 'email': 'john@example.com', 'age': 30},
    {'name': 'Jane Smith', 'email': 'jane@example.com', 'age': 25},
    {'name': 'Bob Johnson', 'email': 'bob@example.com', 'age': 35}
]

for user in users:
    db.insert(user)

# Querying all users
print("\nQuerying all users:")
all_users = db.all()
for user in all_users:
    print(f"Name: {user['name']}, Email: {user['email']}, Age: {user['age']}")

# Filtering data
print("\nFidig users older than 28:")
older_than_28 = db.search(Query().age > 28)
for user in older_than_28:
    print(f"Name: {user['name']}, Email: {user['email']}, Age: {user['age']}")

# Updating data
print("\nUpdatig John Doe's age:")
db.update({'age': 31}, Query().name == 'John Doe')

# Deleting data
print("\nDeletig Jane Smith:")
doc_ids = [doc.doc_id for doc in db.search(Query().email == 'jane@example.com')]
if doc_ids:
    db.remove(doc_ids=doc_ids)
else:
    print("No document found with email 'jane@example.com'")

# Adding a new field
print("\nAddig a 'city' field to all users:")
for user in db.all():
    user['city'] = 'New York'
    db.update(user, doc_ids=[doc.doc_id for doc in db.search(Query().name == user['name'])])

# Sorting data
print("\nSorting users by age:")
sorted_users = sorted(db.all(), key=lambda x: x['age'])
for user in sorted_users:
    print(f"Name: {user['name']}, Email: {user['email']}, Age: {user['age']}")

# Getting document count
print("\nTotal number of users:", len(db.all()))

# Closing the database connection
db.close()
This is the result:
$ python test_001.py 

Querying all users:
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 30
Name: Jane Smith, Email: jane@example.com, Age: 25
Name: Bob Johnson, Email: bob@example.com, Age: 35

Fidig users older than 28:
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: John Doe, Email: john@example.com, Age: 30
Name: Bob Johnson, Email: bob@example.com, Age: 35

Updatig John Doe's age:

Deletig Jane Smith:

Addig a 'city' field to all users:

Sorting users by age:
Name: John Doe, Email: john@example.com, Age: 31
Name: John Doe, Email: john@example.com, Age: 31
Name: John Doe, Email: john@example.com, Age: 31
Name: John Doe, Email: john@example.com, Age: 31
Name: John Doe, Email: john@example.com, Age: 31
Name: John Doe, Email: john@example.com, Age: 31
Name: John Doe, Email: john@example.com, Age: 31
Name: John Doe, Email: john@example.com, Age: 31
Name: John Doe, Email: john@example.com, Age: 31
Name: John Doe, Email: john@example.com, Age: 31
Name: John Doe, Email: john@example.com, Age: 31
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: Bob Johnson, Email: bob@example.com, Age: 35
Name: Bob Johnson, Email: bob@example.com, Age: 35

Total number of users: 22

Saturday, November 16, 2024

Python 3.13.0 : Test the gi python package on Fedora distro linux.

The gi (GObject Introspection) Python package is excellent! It provides Python bindings for GObject-based libraries like GTK, GLib, and Secret Service. It enables you to write native GNOME applications in Python and access system services seamlessly.
First, install these Fedora packages:
[mythcat@fedora ~]# dnf5 install python3-gobject libsecret-devel
...
Package "python3-gobject-3.48.2-3.fc41.x86_64" is already installed.
Package "libsecret-devel-0.21.4-3.fc41.x86_64" is already installed.
...
[mythcat@fedora ~]# dnf5 install gnome-shell gnome-keyring libsecret
...
I used this simple python source code to test the gi python package:
import gi

# Specify the version of Gio and Secret we want to use
gi.require_version('Gio', '2.0')
gi.require_version('Secret', '1')

from gi.repository import Gio, Secret, GLib

def check_schema(schema_name):
    try:
        Gio.Settings.new(schema_name)
        print(f"Schema '{schema_name}' is available")
        return True
    except GLib.GError as e:
        print(f"Schema '{schema_name}' is not installed: {str(e)}")
        return False

def store_secret():
    schema = Secret.Schema.new("org.example.Password",
        Secret.SchemaFlags.NONE,
        {
            "username": Secret.SchemaAttributeType.STRING,
        }
    )
    
    Secret.password_store_sync(schema, 
        {"username": "myuser"},
        Secret.COLLECTION_DEFAULT,
        "My secret item",
        "Hello, World!",
        None)
    
    print("Secret stored successfully")

def get_secret():
    schema = Secret.Schema.new("org.example.Password",
        Secret.SchemaFlags.NONE,
        {
            "username": Secret.SchemaAttributeType.STRING,
        }
    )
    
    password = Secret.password_lookup_sync(schema,
        {"username": "myuser"},
        None)
    
    if password is not None:
        print(f"Retrieved secret: {password}")
    else:
        print("No secret found")

if __name__ == "__main__":
    print("Starting secret operations...")
    store_secret()
    get_secret()
    print("Finished secret operations.")
The result is this:
$ python test_001.py 
Starting secret operations...
Secret stored successfully
Retrieved secret: Hello, World!
Finished secret operations.

Sunday, October 27, 2024

Python 3.13.0 : know this -OOt ?

Today, I follow the actions from NEMO the basic explorer files from linux and I found this: -OOt
This first source code:
#!/usr/bin/python3 -OOt
... this is new, and refers to Python compiler optimizations.
The -OOt par in the shebang line #!/usr/bin/python3 -OOt refers to Python compiler optimizations:
  1. -O: This flag enables basic optimizations. It tells the Python compiler to optimize constants and global variables.
  2. -O2: This flag enables more aggressive optimizations. It applies additional compiler passes to further optimize the code .
  3. -Ot: This flag optimizes for size. It reduces memory usage by eliminating unused variables and dead code.
So, -OOt combines three levels of optimization:
  • Basic optimization (-O)
  • More aggressive optimization (-O2)
  • Optimization for size (-Ot)

Friday, October 25, 2024

Python 3.13.0 : Testing ntplib on Fedora 42.

Today I tested the ntplib python package on Fedora 42 with the python 3.13.0 version.
This is the source code:
from ntplib import NTPClient
import socket
import os
import datetime

def sync_ntp_server(server_address='pool.ntp.org'):
    try:
        client = NTPClient()
        response = client.request(server_address)
        
        # Get the offset in seconds
        offset = response.offset
        
        # Calculate the drift rate (seconds per day)
        drift_rate = offset * 86400 / response.tx_time
        
        print(f"NTP synchronization successful. Offset: {offset:.2f} seconds")
        print(f"Drift rate: {drift_rate:.2f} seconds per day")
        
        # Apply the offset to the system clock
        os.system(f"date -s '@{response.tx_time}'")
        
        # Optionally, you can also apply the drift rate to the system clock
        # However, this is generally not recommended as it can lead to further drift
        # os.system(f"ntpdate -d {server_address}")
        
    except Exception as e:
        print(f"Error synchronizing NTP: {e}")

# Disable SELinux temporarily
os.system("setenforce 0")

# Sync with NTP server
sync_ntp_server()

# Print current system time after sync
current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(f"Current system time after sync: {current_time}")
The result is output is in the romanian language but this is not a problem for programmers:
[mythcat@fedora network_python_tools]$ pip install ntplib
Defaulting to user installation because normal site-packages is not writeable
Collecting ntplib
  Downloading ntplib-0.4.0-py2.py3-none-any.whl.metadata (1.6 kB)
Downloading ntplib-0.4.0-py2.py3-none-any.whl (6.8 kB)
Installing collected packages: ntplib
Successfully installed ntplib-0.4.0
[mythcat@fedora network_python_tools]$ python ntplib_test_001.py 
...
NTP synchronization successful. Offset: -5.25 seconds
Drift rate: -0.00 seconds per day
date: nu se poate stabili data: Operație nepermisă
vineri 25 octombrie 2024, 22:24:13 +0300
Current system time after sync: 2024-10-25 22:24:19

Sunday, September 22, 2024

Python 3.13.0rc1 : ... pkg_resources is deprecated as an API .

I tried an old version of python script for upgrade all my ython packages on windows 10 with pkg_resources python package.
I got this error:
DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html
... and this python script will upgrade all python packages
import subprocess

try:
    # Obține lista pachetelor învechite
    outdated_packages = subprocess.check_output(["pip", "list", "--outdated", "--format=columns"]).decode("utf-8")
    packages = [line.split()[0] for line in outdated_packages.splitlines()[2:]]
    
    if not packages:
        print("Toate pachetele sunt deja actualizate.")
    else:
        print("Pachete Python învechite: ", packages)
        
        # Actualizează fiecare pachet
        for package in packages:
            print("Actualizează pachetul: ", package)
            subprocess.check_call(["pip", "install", "--upgrade", package])
except subprocess.CalledProcessError as e:
    print("A apărut o eroare la rularea comenzii pip:", e)
except Exception as e:
    print("A apărut o eroare neașteptată:", e)

Saturday, September 21, 2024

Python 3.12.3 : 8in8 game project with pygame and agentpy - 001.

I started a game project with the python packages pygame and agentpy in the Fedora Linux distribution.
You can find it on my fedora pagure repo

Tuesday, September 17, 2024

Python 3.12.3 : PyGame, DuckDB and AgentPy on Fedora 42 linux distro.

Today I tested the installation of some python packages in the Fedora 42 Linux distribution. On the Windows 10 operating system I failed to install pygame because it was trying to build.

[mythcat@fedora ~]$ pip install duckdb --upgrade
Defaulting to user installation because normal site-packages is not writeable
Collecting duckdb
...
Installing collected packages: duckdb
Successfully installed duckdb-1.1.0
[mythcat@fedora ~]$ pip install pygame
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: pygame in ./.local/lib/python3.12/site-packages (2.5.2)
[mythcat@fedora ~]$ pip install agentpy
...
Installing collected packages: scipy, networkx, kiwisolver, joblib, fonttools, dill, cycler, contourpy, pandas, multiprocess, matplotlib, SALib, agentpy
Successfully installed SALib-1.5.1 agentpy-0.1.5 contourpy-1.3.0 cycler-0.12.1 dill-0.3.8 fonttools-4.53.1 joblib-1.4.2 kiwisolver-1.4.7 matplotlib-3.9.2 multiprocess-0.70.16 networkx-3.3 pandas-2.2.2 scipy-1.14.1

Saturday, September 14, 2024

Python 3.13.0rc1 : AgentPy python module ...

AgentPy is an open-source library for the development and analysis of agent-based models in Python.
The project can be found on the GitHub repo.
This can be install with the pip tool:
pip install agentpy
Collecting agentpy
...
Successfully installed SALib-1.5.1 agentpy-0.1.5 contourpy-1.3.0 cycler-0.12.1 dill-0.3.8 fonttools-4.53.1 
joblib-1.4.2 kiwisolver-1.4.7 matplotlib-3.9.2 multiprocess-0.70.16 networkx-3.3 packaging-24.1 
pillow-10.4.0 pyparsing-3.1.4 scipy-1.14.1
This is the source code:
import agentpy as ap
import matplotlib.pyplot as plt

# define Agent class
class RandomWalker(ap.Agent):
    def setup(self):
        self.position = [0, 0]

    def step(self):
        self.position += self.model.random.choice([[1, 0], [-1, 0], [0, 1], [0, -1]])

# define Model class
class RandomWalkModel(ap.Model):
    def setup(self):
        self.agents = ap.AgentList(self, self.p.agents, RandomWalker)
        self.agents.setup()

    def step(self):
        self.agents.step()

    def update(self):
        self.record('Positions', [agent.position for agent in self.agents])

    def end(self):
        positions = self.log['Positions']
        plt.figure()
        for pos in positions:
            plt.plot(*zip(*pos))
        plt.show()

# configuration and running 
parameters = {'agents': 5, 'steps': 20}
model = RandomWalkModel(parameters)
results = model.run()
The result is a simple graph with these output:
python test001.py
Matplotlib is building the font cache; this may take a moment.
Completed: 20 steps
Run time: 0:00:50.823483
Simulation finished

Monday, September 9, 2024

Python Qt6 : Use regular expression with PyQt6.

Today I tested a python source code with PyQt6.
This source code let you to clean the text by HTML tags and regular expression in realtime.
If you want to parse in realtime then check the Realtime and add the regular expresion in editbox.
This is the result:
This is the source code I used to parse realtime regular expresion on editbox
from PyQt6.QtWidgets import QApplication, QMainWindow, QTextEdit, QVBoxLayout, QHBoxLayout, QWidget, QPushButton, QCheckBox, QLineEdit, QLabel
from PyQt6.QtGui import QTextDocument
from PyQt6.QtCore import Qt
import re

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("HTML Cleaner")

        self.text_edit = QTextEdit()
        self.clean_button = QPushButton("Clean HTML")
        self.transform_div_checkbox = QCheckBox("Transform 
tags") self.realtime_checkbox = QCheckBox("Realtime") self.regex_edit = QLineEdit() self.regex_edit.setPlaceholderText("Enter regex pattern") self.regex_edit.setEnabled(False) # Dezactivăm inițial top_layout = QHBoxLayout() top_layout.addWidget(self.clean_button) top_layout.addWidget(self.transform_div_checkbox) top_layout.addWidget(QLabel("Regex:")) top_layout.addWidget(self.regex_edit) top_layout.addWidget(self.realtime_checkbox) main_layout = QVBoxLayout() main_layout.addLayout(top_layout) main_layout.addWidget(self.text_edit) container = QWidget() container.setLayout(main_layout) self.setCentralWidget(container) self.clean_button.clicked.connect(self.clean_html) self.realtime_checkbox.stateChanged.connect(self.toggle_realtime) self.regex_edit.textChanged.connect(self.realtime_update) def clean_html(self): html_text = self.text_edit.toPlainText() clean_text = self.remove_html_tags(html_text) self.text_edit.setPlainText(clean_text) def remove_html_tags(self, text): # Remove CSS text = re.sub(r'.*?', '', text, flags=re.DOTALL) # Remove JavaScript text = re.sub(r'.*?', '', text, flags=re.DOTALL) # Remove HTML comments text = re.sub(r'', '', text, flags=re.DOTALL) # Transform
tags if checkbox is checked if self.transform_div_checkbox.isChecked(): text = re.sub(r']*>', '
', text) # Remove HTML tags but keep content clean = re.compile('<.*?>') text = re.sub(clean, '', text) # Remove empty lines text = re.sub(r'\n\s*\n', '\n', text) return text def toggle_realtime(self): if self.realtime_checkbox.isChecked(): self.regex_edit.setEnabled(True) # Activăm editbox-ul self.text_edit.textChanged.connect(self.realtime_update) else: self.regex_edit.setEnabled(False) # Dezactivăm editbox-ul self.text_edit.textChanged.disconnect(self.realtime_update) def realtime_update(self): if self.realtime_checkbox.isChecked(): html_text = self.text_edit.toPlainText() regex_pattern = self.regex_edit.text() if regex_pattern: try: html_text = re.sub(regex_pattern, '', html_text) except re.error: pass # Ignore regex errors self.text_edit.blockSignals(True) self.text_edit.setPlainText(html_text) self.text_edit.blockSignals(False) app = QApplication([]) window = MainWindow() window.show() app.exec()

Saturday, September 7, 2024

News : Python and the Intel's NPU Acceleration Library.

You can find the Intel's NPU Acceleration Library on this GitHub repo with Python code samples.

News : Python in Visual Studio Code – September 2024 Release

We’re excited to announce the September 2024 release of the Python and Jupyter extensions for Visual Studio Code!
This release includes the following announcements:
Django unit test support
Go to definition from inlay hints with Pylance
If you’re interested, you can check the full list of improvements in our changelogs for the Python, Jupyter and Pylance extensions.
Read more on the offcial website.