analitics

Pages

Showing posts with label 2024. Show all posts
Showing posts with label 2024. Show all posts

Friday, February 23, 2024

Saturday, February 17, 2024

Python 3.10.12 : Few example for CUDA and NVCC - part 044.

NVCC use CUDA C/C++ source code and allows developers to write high-performance GPU-accelerated applications by leveraging the power of NVIDIA GPUs for parallel processing tasks.
Today I test some simple examples with this tool on Google Colab using the nvcc4jupyter python package.
You need to install it with the pip and know how to use the CUDA C/C++ source code, or use the basic example from documentation.
pip install nvcc4jupyter
I change some source code because is need to install this library and I don't have time to learn and test.
But this will allow me to test better, because on my desktop I don't have a good hardware.
This is the source I change and I cut the source code linked on error_handling.h.
This is the changed source code , you can see more on my GitHub repo for Google Colab ! !
#include 
//#include "error_handling.h"

const int DSIZE = 4096;
const int block_size = 256;

// vector add kernel: C = A + B
__global__ void vadd(const float *A, const float *B, float *C, int ds){
    int idx = threadIdx.x + blockIdx.x * blockDim.x;
    if (idx < ds) {
        C[idx] = A[idx] + B[idx];
    }
}

int main(){
    float *h_A, *h_B, *h_C, *d_A, *d_B, *d_C;

    // allocate space for vectors in host memory
    h_A = new float[DSIZE];
    h_B = new float[DSIZE];
    h_C = new float[DSIZE];

    // initialize vectors in host memory to random values (except for the
    // result vector whose values do not matter as they will be overwritten)
    for (int i = 0; i < DSIZE; i++) {
        h_A[i] = rand()/(float)RAND_MAX;
        h_B[i] = rand()/(float)RAND_MAX;
    }

    // allocate space for vectors in device memory
    cudaMalloc(&d_A, DSIZE*sizeof(float));
    cudaMalloc(&d_B, DSIZE*sizeof(float));
    cudaMalloc(&d_C, DSIZE*sizeof(float));
    //cudaCheckErrors("cudaMalloc failure"); // error checking

    // copy vectors A and B from host to device:
    cudaMemcpy(d_A, h_A, DSIZE*sizeof(float), cudaMemcpyHostToDevice);
    cudaMemcpy(d_B, h_B, DSIZE*sizeof(float), cudaMemcpyHostToDevice);
    //cudaCheckErrors("cudaMemcpy H2D failure");

    // launch the vector adding kernel
    vadd<<<(DSIZE+block_size-1)/block_size, block_size>>>(d_A, d_B, d_C, DSIZE);
    //cudaCheckErrors("kernel launch failure");

    // wait for the kernel to finish execution
    cudaDeviceSynchronize();
    //cudaCheckErrors("kernel execution failure");

    cudaMemcpy(h_C, d_C, DSIZE*sizeof(float), cudaMemcpyDeviceToHost);
    //cudaCheckErrors("cudaMemcpy D2H failure");

    printf("A[0] = %f\n", h_A[0]);
    printf("B[0] = %f\n", h_B[0]);
    printf("C[0] = %f\n", h_C[0]);
    return 0;
}
This is result ...
A[0] = 0.840188
B[0] = 0.394383
C[0] = 0.000000

Wednesday, February 7, 2024

Python 3.12.1 : Simple view for sqlite table with PyQt6.

This is the source code that show you how to use QSqlDatabase, QSqlQuery, QSqlTableModel:
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QTableView
from PyQt6.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel

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

        # Initialize the database
        self.init_db()

        # Set up the GUI
        self.table_view = QTableView(self)
        self.setCentralWidget(self.table_view)

        # Set up the model and connect it to the database
        self.model = QSqlTableModel(self)
        self.model.setTable('files')
        self.model.select()
        self.table_view.setModel(self.model)

    def init_db(self):
        # Connect to the database
        db = QSqlDatabase.addDatabase('QSQLITE')
        db.setDatabaseName('file_paths.db')
        if not db.open():
            print('Could not open database')
            sys.exit(1)

    def create_table(self):
        # Create the 'files' table if it doesn't exist
        query = QSqlQuery()
        query.exec('CREATE TABLE IF NOT EXISTS files (id INTEGER PRIMARY KEY, path TEXT)')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

Monday, February 5, 2024

Python 3.12.1 : Simple browser with PyQt6-WebEngine.

This is a source code for a minimal browser with PyQt6 and PyQt6-WebEngine.
You need to install it with the pip tool:
pip install PyQt6 PyQt6-WebEngine
You can update the pip tool with
python.exe -m pip install --upgrade pip
Create a python script use the source code and run it.
Let's see the source code:
import sys
from PyQt6.QtCore import QUrl
from PyQt6.QtGui import QKeySequence, QAction
from PyQt6.QtWidgets import QApplication, QMainWindow, QLineEdit, QToolBar
from PyQt6.QtWebEngineWidgets import QWebEngineView
 
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
         
        # Create a web view
        self.web_view = QWebEngineView()
        self.web_view.setUrl(QUrl("127.0.0.1"))
        self.setCentralWidget(self.web_view)
 
        # Create a toolbar
        toolbar = QToolBar()
        self.addToolBar(toolbar)
         
        # Add a back action to the toolbar
        back_action = QAction("Back", self)
        back_action.setShortcut(QKeySequence("Back"))
        back_action.triggered.connect(self.web_view.back)
        toolbar.addAction(back_action)
         
        # Add a forward action to the toolbar
        forward_action = QAction("Forward", self)
        forward_action.setShortcut(QKeySequence("Forward"))
        forward_action.triggered.connect(self.web_view.forward)
        toolbar.addAction(forward_action)
         
        # Add a reload action to the toolbar
        reload_action = QAction("Reload", self)
        reload_action.setShortcut(QKeySequence("Refresh"))
        reload_action.triggered.connect(self.web_view.reload)
        toolbar.addAction(reload_action)
         
        # Add a search bar to the toolbar
        self.search_bar = QLineEdit()
        self.search_bar.returnPressed.connect(self.load_url)
        toolbar.addWidget(self.search_bar)
         
         
    def load_url(self):
        url = self.search_bar.text()
        if not url.startswith("http"):
            url = "https://" + url
        self.web_view.load(QUrl(url))
         
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec()

Tuesday, January 16, 2024

News : How to use ShellExecuteA with Python programming language.

I just discovery this option to use ShellExecuteA in Python.
Let's see some example:
import ctypes
import sys

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

if not is_admin():
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
... and another example:
import sys
import ctypes

#fix unicode access
import sys
if sys.version_info[0] >= 3:
    unicode = str

def run_as_admin(argv=None, debug=False):
    shell32 = ctypes.windll.shell32
    if argv is None and shell32.IsUserAnAdmin():
        return True    
    if argv is None:
        argv = sys.argv
    if hasattr(sys, '_MEIPASS'):
        # Support pyinstaller wrapped program.
        arguments = map(unicode, argv[1:])
    else:
        arguments = map(unicode, argv)
    argument_line = u' '.join(arguments)
    executable = unicode(sys.executable)
    if debug:
        print('Command line: ', executable, argument_line)
    ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
    if int(ret) <= 32:
        return False
    return None  

if __name__ == '__main__':
    ret = run_as_admin()
    if ret is True:
        print ('I have admin privilege.')
        input('Press ENTER to exit.')
    elif ret is None:
        print('I am elevating to admin privilege.')
        input('Press ENTER to exit.')
    else:
        print('Error(ret=%d): cannot elevate privilege.' % (ret, ))

Thursday, January 11, 2024

News : NVIDIA Kaolin library provides a PyTorch API.

NVIDIA Kaolin library provides a PyTorch API for working with a variety of 3D representations and includes a growing collection of GPU-optimized operations such as modular differentiable rendering, fast conversions between representations, data loading, 3D checkpoints, differentiable camera API, differentiable lighting with spherical harmonics and spherical gaussians, powerful quadtree acceleration structure called Structured Point Clouds, interactive 3D visualizer for jupyter notebooks, convenient batched mesh container and more ... from GitHub repo - kaolin.
See this example from NVIDIA:
NVIDIA Kaolin library has introduced the SurfaceMesh class to make it easier to track attributes such as faces, vertices, normals, face_normals, and others associated with surface meshes.

Monday, January 8, 2024

Python 3.12.1 : Create a simple color palette.

Today I tested a simple source code for a color palette created with PIL python package.
This is the result:
Let's see the source code:
from PIL import Image, ImageDraw

# 640x640 pixeli with 10x10 squares 64x64 
img = Image.new('RGB', (640, 640))
draw = ImageDraw.Draw(img)

# color list
colors = []
# for 100 colors you need to set steps with 62,62,64 
# or you can change 64,62,62 some little changes 
for r in range(0, 256, 62):
    for g in range(0, 256, 62):
        for b in range(0, 256, 64):
            colors.append((r, g, b))

# show result of colors and size up 100 items 
print(colors)
print(len(colors))

# create 10x10 colors and fill the image 
for i in range(10):
    for j in range(10):
        x0 = j * 64
        y0 = i * 64
        x1 = x0 + 64
        y1 = y0 + 64
        color = colors[i*10 + j]  # Selectarea culorii din lista
        draw.rectangle([x0, y0, x1, y1], fill=color)

# save teh image
img.save('rgb_color_matrix.png')

Saturday, January 6, 2024

Python 3.10.12 : LaTeX on colab notebook - part 043.

Today I tested with a simple LaTeX examples in the Colab notebook.
If you open my notebook colab then you will see some issues and how can be fixed.
You can find this on my notebook - catafest_056.ipynb on colab repo.

Friday, January 5, 2024

Python 3.12.1 : How to read all CLSID with winreg.

The winreg python module can be found default into python instalation.
This is the source code I used to list all of CLSID:
import winreg

# Open the CLSID key under HKEY_CLASSES_ROOT
clsid_key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "CLSID")

# Iterate through all the subkeys
for i in range(winreg.QueryInfoKey(clsid_key)[0]):
    # Get the name of the subkey
    subkey_name = winreg.EnumKey(clsid_key, i)
    # Open the subkey
    subkey = winreg.OpenKey(clsid_key, subkey_name, 0, winreg.KEY_READ)
    try:
        # Read the default value of the subkey
        value, type = winreg.QueryValueEx(subkey, "")
        # Print the subkey name and the value
        print(subkey_name, value)
    except:
        # Skip the subkeys that cannot be read
        pass
    # Close the subkey
    winreg.CloseKey(subkey)

# Close the CLSID key
winreg.CloseKey(clsid_key)
... and this source code comes with an text file output:
import winreg

# Open the CLSID key under HKEY_CLASSES_ROOT
clsid_key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "CLSID")

# Open the file for writing
with open("clsid_info.txt", "w") as f:
    # Iterate through all the subkeys
    for i in range(winreg.QueryInfoKey(clsid_key)[0]):
        # Get the name of the subkey
        subkey_name = winreg.EnumKey(clsid_key, i)
        # Open the subkey
        subkey = winreg.OpenKey(clsid_key, subkey_name, 0, winreg.KEY_READ)
        try:
            # Read the default value of the subkey
            value, type = winreg.QueryValueEx(subkey, "")
            # Write the subkey name and the value to the file
            f.write(subkey_name + " " + value + "\n")
        except:
            # Skip the subkeys that cannot be read
            pass
        # Close the subkey
        winreg.CloseKey(subkey)

# Close the CLSID key
winreg.CloseKey(clsid_key)