analitics

Pages

Saturday, December 5, 2026

News : JetBrains Subscription Prices Will Increase on February 1, 2027

On February 1, 2027, subscription prices for our IDEs and .NET tools, dotUltimate, and the All Products Pack will increase. Here is some information about what is changing, why, and how you can keep your current price for longer.
Why we’re raising prices
Our costs keep going up. The rising cost of running our business, including expenses associated with the infrastructure and services our products depend on, along with inflation, makes our current prices hard to sustain. The increase also helps us continue to invest in our products – improving performance, building new features, and expanding support for more of the technologies and workflows you use.

Python 3.9.25 : Terminal interface for IBM Quantum hardware on Oracle ARM64.

What it does:
1. Connects to IBM Quantum Platform using API Key + CRN (stored in ibm_quantum_config.json, chmod 600)
2. Fetches live calibration data from all operational QPUs:
  • Single-qubit: SX gate error, readout error, T1/T2, frequency, anharmonicity
  • Two-qubit: CZ gate error per qubit pair (your screenshot: q131-q138: 0.2256%, etc.)
  • Computes a score = weighted sum of median errors + queue depth
3. Displays in 5 panels:
  • Top-left: Backend table (11 metrics × all backends)
  • Top-center: Circuit parameters (qubits, layers, optimization level, shots)
  • Top-right: Live activity log
  • Bottom-left (65% height): Full backend detail — medians, what each metric measures, sample counts, value ranges, per-pair CZ errors
  • Bottom-right (65% height): Extended log / job output
4. Actions (status bar buttons + keys):
  • Refresh QPU / r — reload calibration
  • Pick Best / b — auto-select lowest-score backend
  • Transpile / p — build complex circuit (H + RY/RZ layers + CX ring), transpile to ISA at optimization level 0-3 via generate_preset_pass_manager
  • Run Circuit — submit ISA circuit via SamplerV2 (consumes RUs)
  • Stop Job / s — cancel running job (job.cancel())
5. Logs everything to ibm_quantum_tui.log with timestamps.
Your screenshot shows: 156-qubit backend (ibm_fez?) with CZ errors per coupling pair — median of 2 calibration samples each. This lets you see which qubit links are highest fidelity for circuit mapping.
Let's see the bash script:
#!/bin/bash
# IBM Quantum TUI Project - Initialization Script
# Usage: source init.sh

cd ~/ibm_quantum_tui
source .venv/bin/activate
echo "IBM Quantum TUI environment activated"
echo "Python: $(python --version)"
echo "Qiskit: $(python -c 'import qiskit; print(qiskit.__version__)')"
echo "Textual: $(python -c 'import textual; print(textual.__version__)')"
Let's see the python script for the IBM Quantum hardware with TUI:
import asyncio
import json
import os
from datetime import datetime
from pathlib import Path
from typing import Any

from qiskit import QuantumCircuit
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2
from textual.app import App, ComposeResult
from textual.containers import Container, Horizontal, Vertical
from textual.widgets import Button, DataTable, Footer, Header, Input, Label, RichLog, Select


CONFIG_PATH = Path(__file__).resolve().parent / "ibm_quantum_config.json"
LOG_PATH = Path(__file__).resolve().parent / "ibm_quantum_tui.log"


def _median(values: list[float]) -> float | None:
    if not values:
        return None
    ordered = sorted(values)
    mid = len(ordered) // 2
    if len(ordered) % 2 == 1:
        return ordered[mid]
    return (ordered[mid - 1] + ordered[mid]) / 2.0


def extract_calibration_metrics(backend: Any) -> dict[str, Any]:
    status = backend.status()
    props = backend.properties()

    cz_errors: list[float] = []
    cz_qubit_pairs: list[tuple[int, int]] = []
    sx_errors: list[float] = []
    readout_errors: list[float] = []
    t1_us: list[float] = []
    t2_us: list[float] = []
    qubit_freqs: list[float] = []
    anharmonicities: list[float] = []

    if props is not None:
        for q in range(backend.num_qubits):
            try:
                ro = props.readout_error(q)
                if ro is not None:
                    readout_errors.append(float(ro))
                t1 = props.t1(q)
                if t1 is not None:
                    t1_us.append(float(t1) * 1e6)
                t2 = props.t2(q)
                if t2 is not None:
                    t2_us.append(float(t2) * 1e6)
                freq = props.frequency(q)
                if freq is not None:
                    qubit_freqs.append(float(freq) / 1e9)
                anharm = props.anharmonicity(q)
                if anharm is not None:
                    anharmonicities.append(float(anharm) / 1e9)
            except Exception:
                continue

        for gate in props.gates:
            if gate.gate == "cz":
                qubits = tuple(sorted(gate.qubits))
                for param in gate.parameters:
                    if param.name == "gate_error" and param.value is not None:
                        cz_errors.append(float(param.value))
                        cz_qubit_pairs.append(qubits)
            if gate.gate == "sx":
                for param in gate.parameters:
                    if param.name == "gate_error" and param.value is not None:
                        sx_errors.append(float(param.value))

    med_cz = _median(cz_errors)
    med_sx = _median(sx_errors)
    med_ro = _median(readout_errors)
    med_t1 = _median(t1_us)
    med_t2 = _median(t2_us)
    med_freq = _median(qubit_freqs)
    med_anharm = _median(anharmonicities)

    cz_penalty = (med_cz * 1000.0) if med_cz is not None else 50.0
    sx_penalty = (med_sx * 500.0) if med_sx is not None else 5.0
    ro_penalty = (med_ro * 100.0) if med_ro is not None else 10.0
    queue_penalty = float(status.pending_jobs) * 0.05
    score = cz_penalty + sx_penalty + ro_penalty + queue_penalty

    return {
        "backend": backend,
        "name": backend.name,
        "qubits": backend.num_qubits,
        "operational": bool(status.operational),
        "pending_jobs": int(status.pending_jobs),
        "med_cz": med_cz,
        "med_sx": med_sx,
        "med_ro": med_ro,
        "med_t1": med_t1,
        "med_t2": med_t2,
        "med_freq": med_freq,
        "med_anharm": med_anharm,
        "score": score,
        "cz_errors": cz_errors,
        "cz_qubit_pairs": cz_qubit_pairs,
        "sx_errors": sx_errors,
        "readout_errors": readout_errors,
        "t1_us": t1_us,
        "t2_us": t2_us,
        "qubit_freqs": qubit_freqs,
        "anharmonicities": anharmonicities,
    }


def build_complex_circuit(num_qubits: int, layers: int) -> QuantumCircuit:
    qc = QuantumCircuit(num_qubits)

    for q in range(num_qubits):
        qc.h(q)

    for layer in range(layers):
        for q in range(num_qubits):
            angle_y = 0.35 * (layer + 1) * (q + 1) / num_qubits
            angle_z = 0.21 * (layer + 1)
            qc.ry(angle_y, q)
            qc.rz(angle_z, q)

        for q in range(num_qubits - 1):
            qc.cx(q, q + 1)
        if num_qubits > 2:
            qc.cx(num_qubits - 1, 0)

    qc.measure_all()
    return qc


class IBMQuantumTUI(App):
    TITLE = "IBM Quantum Open - Oracle ARM64 TUI"
    BINDINGS = [
        ("q", "quit", "Quit"),
        ("r", "refresh", "Refresh"),
        ("b", "pick_best", "Pick Best"),
        ("p", "prepare_circuit", "Prepare"),
        ("s", "stop_job", "Stop Job"),
    ]

    CSS = """
    Screen {
        layout: vertical;
    }
    #status_bar {
        height: 3;
        border: solid $accent;
        padding: 0 1;
        margin: 0 1 1 1;
    }
    .status_row {
        height: 1;
        margin: 0;
    }
    .status_label {
        width: 14;
        content-align: right middle;
        text-style: bold;
    }
    .status_value {
        width: 1fr;
        content-align: left middle;
    }
    #main_area {
        height: 35%;
        margin: 0 1;
    }
    #backends_panel {
        width: 2fr;
        border: solid $primary;
        padding: 0 1;
        margin-right: 1;
    }
    #prep_panel {
        width: 1fr;
        border: solid $secondary;
        padding: 0 1;
        margin-right: 1;
    }
    #log_panel_right {
        width: 1fr;
        border: solid $success;
        padding: 0 1;
    }
    #backends_table {
        height: 1fr;
    }
    #log_box_right {
        height: 1fr;
    }
    #bottom_area {
        height: 65%;
        margin: 0 1;
        border: solid $warning;
    }
    #bottom_split {
        height: 1fr;
    }
    #detail_panel_bottom {
        width: 1fr;
        border-right: solid $surface;
        padding: 0 1;
    }
    #log_panel_bottom {
        width: 1fr;
        padding: 0 1;
    }
    #detail_box {
        height: 1fr;
    }
    #log_box_bottom {
        height: 1fr;
    }
    .btn_row {
        height: 3;
        margin: 1 0;
    }
    """

    def __init__(self) -> None:
        super().__init__()
        self.service: QiskitRuntimeService | None = None
        self.backends_info: dict[str, dict[str, Any]] = {}
        self.selected_backend_name: str | None = None
        self.prepared_isa_circuit: QuantumCircuit | None = None
        self.running_job = None
        self.job_future = None

    def compose(self) -> ComposeResult:
        yield Header(show_clock=True)

        # Compact status bar with action buttons
        with Container(id="status_bar"):
            with Horizontal(classes="status_row"):
                yield Label("Status:", classes="status_label")
                yield Label("Disconnected", id="conn_status", classes="status_value")
                yield Label("Backend:", classes="status_label")
                yield Label("None", id="backend_status", classes="status_value")
            with Horizontal(classes="status_row"):
                yield Label("Config:", classes="status_label")
                yield Label("Loading...", id="config_status", classes="status_value")
                yield Button("Reconfigure", id="btn_reconfig", variant="default")
                yield Button("Refresh QPU", id="btn_refresh", variant="primary")
                yield Button("Pick Best", id="btn_best", variant="warning")
                yield Button("Transpile", id="btn_prepare", variant="success")
                yield Button("Run Circuit", id="btn_run", variant="primary")
                yield Button("Stop Job", id="btn_stop", variant="error", disabled=True)

        with Horizontal(id="main_area"):
            with Vertical(id="backends_panel"):
                yield Label("QPU Backends & Calibration Metrics")
                yield DataTable(id="backends_table", cursor_type="row")

            with Vertical(id="prep_panel"):
                yield Label("Circuit Parameters (0 RUs for transpile)")
                with Horizontal(classes="status_row"):
                    yield Label("Qubits:", classes="status_label")
                    yield Input(id="qubits_input", value="6")
                with Horizontal(classes="status_row"):
                    yield Label("Layers:", classes="status_label")
                    yield Input(id="layers_input", value="2")
                with Horizontal(classes="status_row"):
                    yield Label("Optimization:", classes="status_label")
                    yield Select(
                        options=[("Level 0", 0), ("Level 1", 1), ("Level 2", 2), ("Level 3", 3)],
                        value=3,
                        id="opt_select",
                    )
                with Horizontal(classes="status_row"):
                    yield Label("Shots:", classes="status_label")
                    yield Input(id="shots_input", value="1024")

            with Vertical(id="log_panel_right"):
                yield Label("Activity Log (Live)")
                yield RichLog(id="log_box_right", highlight=False, markup=False, wrap=True)

        # Bottom area (65%) - split: Detail panel (left) + Extended Log (right)
        with Horizontal(id="bottom_area"):
            with Vertical(id="detail_panel_bottom"):
                yield Label("Backend Detail & Calibration")
                yield RichLog(id="detail_box", highlight=False, markup=False, wrap=True)

            with Vertical(id="log_panel_bottom"):
                yield Label("Extended Log / Job Output")
                yield RichLog(id="log_box_bottom", highlight=False, markup=False, wrap=True)

        yield Footer()

    def on_mount(self) -> None:
        table = self.query_one("#backends_table", DataTable)
        table.add_columns(
            "Backend", "Qubits", "Queue", "CZ %", "SX %", "RO %",
            "T1 µs", "T2 µs", "Freq GHz", "Anharm GHz", "Score"
        )
        self._load_saved_config()

    def _log(self, message: str) -> None:
        timestamp = datetime.now().strftime("%H:%M:%S")
        formatted = f"[{timestamp}] {message}"
        # Write to both log panels
        for log_id in ("#log_box_right", "#log_box_bottom"):
            try:
                log_widget = self.query_one(log_id, RichLog)
                log_widget.write(formatted)
            except Exception:
                pass
        try:
            with LOG_PATH.open("a", encoding="utf-8") as f:
                f.write(formatted + "\n")
        except Exception:
            pass

    def _load_saved_config(self) -> None:
        if not CONFIG_PATH.exists():
            self.query_one("#config_status", Label).update("Missing - click Reconfigure")
            self._log("[INIT] No config file. Click Reconfigure to enter credentials.")
            return
        try:
            data = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
            api_key = data.get("api_key", "")
            crn = data.get("crn", "")
            if api_key and crn:
                masked_key = api_key[:8] + "..." + api_key[-4:] if len(api_key) > 12 else "***"
                self.query_one("#config_status", Label).update(f"Loaded ({masked_key})")
                self._log(f"[INIT] Config loaded from {CONFIG_PATH.name}.")
                asyncio.create_task(self._connect_and_load_async(api_key, crn))
            else:
                self.query_one("#config_status", Label).update("Incomplete - click Reconfigure")
                self._log("[INIT] Config incomplete. Click Reconfigure.")
        except Exception as exc:
            self.query_one("#config_status", Label).update(f"Error: {exc}")
            self._log(f"[ERROR] Failed to read config: {exc}")

    def _save_config(self, api_key: str, crn: str) -> None:
        try:
            payload = {"api_key": api_key, "crn": crn}
            CONFIG_PATH.write_text(json.dumps(payload, indent=2), encoding="utf-8")
            os.chmod(CONFIG_PATH, 0o600)
        except Exception as exc:
            self._log(f"[WARNING] Error saving config: {exc}")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        button_id = event.button.id
        if button_id == "btn_reconfig":
            self._show_config_dialog()
        elif button_id == "btn_refresh":
            if self.service is None:
                self._show_config_dialog()
            else:
                asyncio.create_task(self._refresh_backends_async())
        elif button_id == "btn_best":
            self.action_pick_best()
        elif button_id == "btn_prepare":
            self.action_prepare_circuit()
        elif button_id == "btn_run":
            self.action_run_circuit()
        elif button_id == "btn_stop":
            self.action_stop_job()

    def _show_config_dialog(self) -> None:
        self._log("[CONFIG] Edit ~/ibm_quantum_tui/ibm_quantum_config.json:")
        self._log('  {"api_key": "YOUR_KEY", "crn": "YOUR_CRN"}')
        self._log("  Then click Refresh QPU to reload.")

    def on_data_table_row_selected(self, event: DataTable.RowSelected) -> None:
        table = self.query_one("#backends_table", DataTable)
        row_values = table.get_row(event.row_key)
        if row_values:
            self.selected_backend_name = str(row_values[0])
            self.query_one("#backend_status", Label).update(self.selected_backend_name)
            self._log(f"[SELECTION] Active backend: {self.selected_backend_name}")
            self._show_backend_details(self.selected_backend_name)

    def _show_backend_details(self, name: str) -> None:
        info = self.backends_info.get(name)
        if not info:
            return
        detail = self.query_one("#detail_box", RichLog)
        detail.clear()

        # Header
        detail.write(f"=== {name} ===")
        detail.write(f"Qubits: {info['qubits']} | Operational: {'Yes' if info['operational'] else 'No'}")
        detail.write(f"Queue: {info['pending_jobs']} | Score: {info['score']:.2f} (lower=better)")
        detail.write("")

        # Median calibration metrics
        detail.write("--- Median Calibration Metrics ---")
        cz = f"{info['med_cz']*100:.4f}%" if info['med_cz'] else "N/A"
        sx = f"{info['med_sx']*100:.4f}%" if info['med_sx'] else "N/A"
        ro = f"{info['med_ro']*100:.4f}%" if info['med_ro'] else "N/A"
        t1 = f"{info['med_t1']:.1f} µs" if info['med_t1'] else "N/A"
        t2 = f"{info['med_t2']:.1f} µs" if info['med_t2'] else "N/A"
        freq = f"{info['med_freq']:.3f} GHz" if info['med_freq'] else "N/A"
        anharm = f"{info['med_anharm']:.3f} GHz" if info['med_anharm'] else "N/A"
        detail.write(f"CZ Error:     {cz}")
        detail.write(f"SX Error:     {sx}")
        detail.write(f"Readout Err:  {ro}")
        detail.write(f"T1 (relax):   {t1}")
        detail.write(f"T2 (coher):   {t2}")
        detail.write(f"Freq:         {freq}")
        detail.write(f"Anharm:       {anharm}")
        detail.write("")

        # What each metric measures
        detail.write("--- What Metrics Measure ---")
        detail.write("CZ Error    : Two-qubit entangling gate infidelity")
        detail.write("SX Error    : Single-qubit sqrt(X) gate infidelity")
        detail.write("Readout Err : Measurement assignment error rate")
        detail.write("T1          : Energy relaxation time |1> -> |0>")
        detail.write("T2          : Phase coherence time (dephasing)")
        detail.write("Frequency   : Qubit transition frequency (GHz)")
        detail.write("Anharmonicity: |0>->|1> vs |1>->|2> spacing (GHz)")
        detail.write("")

        # Sample counts & ranges
        detail.write("--- Calibration Sample Counts ---")
        detail.write(f"CZ gates    : {len(info['cz_errors'])} samples")
        detail.write(f"SX gates    : {len(info['sx_errors'])} samples")
        detail.write(f"Readout     : {len(info['readout_errors'])} samples")
        detail.write(f"T1          : {len(info['t1_us'])} samples")
        detail.write(f"T2          : {len(info['t2_us'])} samples")
        detail.write(f"Frequency   : {len(info['qubit_freqs'])} samples")
        detail.write(f"Anharm      : {len(info['anharmonicities'])} samples")
        detail.write("")

        # Ranges if available
        def _range(vals: list[float], scale: float = 1.0, unit: str = "") -> str:
            if not vals:
                return "N/A"
            vmin = min(vals) * scale
            vmax = max(vals) * scale
            return f"{vmin:.4f} - {vmax:.4f} {unit}"

        detail.write("--- Value Ranges ---")
        detail.write(f"CZ Error    : {_range(info['cz_errors'], 100, ' %')}")
        detail.write(f"SX Error    : {_range(info['sx_errors'], 100, ' %')}")
        detail.write(f"Readout Err : {_range(info['readout_errors'], 100, ' %')}")
        detail.write(f"T1          : {_range(info['t1_us'], 1.0, ' µs')}")
        detail.write(f"T2          : {_range(info['t2_us'], 1.0, ' µs')}")
        detail.write(f"Frequency   : {_range(info['qubit_freqs'], 1.0, ' GHz')}")
        detail.write(f"Anharm      : {_range(info['anharmonicities'], 1.0, ' GHz')}")

        # Per-qubit-pair CZ errors (2-qubit gate errors)
        if info.get('cz_qubit_pairs') and info.get('cz_errors'):
            detail.write("")
            detail.write("--- 2-Qubit CZ Errors by Qubit Pair ---")
            # Group by qubit pair (in case multiple calibrations per pair)
            pair_errors: dict[tuple[int, int], list[float]] = {}
            for pair, err in zip(info['cz_qubit_pairs'], info['cz_errors']):
                if pair not in pair_errors:
                    pair_errors[pair] = []
                pair_errors[pair].append(err)
            
            for pair in sorted(pair_errors.keys()):
                errs = pair_errors[pair]
                if len(errs) == 1:
                    detail.write(f"  q{pair[0]}-q{pair[1]}: {errs[0]*100:.4f}%")
                else:
                    med = _median(errs)
                    detail.write(f"  q{pair[0]}-q{pair[1]}: {med*100:.4f}% (median of {len(errs)} samples)")
            detail.write(f"  Total unique pairs: {len(pair_errors)} | Total CZ calibrations: {len(info['cz_errors'])}")

    def action_connect_ibm(self) -> None:
        self._show_config_dialog()

    async def _connect_and_load_async(self, api_key: str, crn: str) -> None:
        self.query_one("#conn_status", Label).update("Connecting...")
        self._log("[CONNECT] Contacting IBM Quantum Platform...")
        try:
            service = await asyncio.to_thread(self._init_service_blocking, api_key, crn)
            self.service = service
            self.query_one("#conn_status", Label).update("Connected")
            self._log("[OK] Connected to IBM Quantum Platform.")
            await self._refresh_backends_async()
        except Exception as exc:
            self.query_one("#conn_status", Label).update(f"Failed: {exc}")
            self._log(f"[CONNECT ERROR] {exc}")

    @staticmethod
    def _init_service_blocking(api_key: str, crn: str) -> QiskitRuntimeService:
        QiskitRuntimeService.save_account(
            channel="ibm_quantum_platform",
            token=api_key,
            instance=crn,
            overwrite=True,
        )
        return QiskitRuntimeService(channel="ibm_quantum_platform", instance=crn)

    async def _refresh_backends_async(self) -> None:
        if self.service is None:
            self._log("[INFO] Not connected. Configure credentials first.")
            return
        self.query_one("#conn_status", Label).update("Loading...")
        self._log("[CALIBRATION] Fetching QPU status and calibration data...")
        try:
            metrics_list = await asyncio.to_thread(self._fetch_all_metrics_blocking, self.service)
            table = self.query_one("#backends_table", DataTable)
            table.clear()
            self.backends_info.clear()

            for item in metrics_list:
                self.backends_info[item["name"]] = item
                cz = f"{item['med_cz']*100:.3f}%" if item["med_cz"] else "N/A"
                sx = f"{item['med_sx']*100:.3f}%" if item["med_sx"] else "N/A"
                ro = f"{item['med_ro']*100:.3f}%" if item["med_ro"] else "N/A"
                t1 = f"{item['med_t1']:.1f}" if item["med_t1"] else "N/A"
                t2 = f"{item['med_t2']:.1f}" if item["med_t2"] else "N/A"
                freq = f"{item['med_freq']:.3f}" if item["med_freq"] else "N/A"
                anharm = f"{item['med_anharm']:.3f}" if item["med_anharm"] else "N/A"
                table.add_row(
                    item["name"],
                    str(item["qubits"]),
                    str(item["pending_jobs"]),
                    cz, sx, ro, t1, t2, freq, anharm,
                    f"{item['score']:.2f}",
                )

            if metrics_list and self.selected_backend_name not in self.backends_info:
                self.selected_backend_name = metrics_list[0]["name"]
                self.query_one("#backend_status", Label).update(self.selected_backend_name)
                self._show_backend_details(self.selected_backend_name)

            self.query_one("#conn_status", Label).update("Connected")
            self._log(f"[INSTANCES] Loaded {len(metrics_list)} QPU backends.")
        except Exception as exc:
            self.query_one("#conn_status", Label).update("Error")
            self._log(f"[CALIBRATION ERROR] {exc}")

    @staticmethod
    def _fetch_all_metrics_blocking(service: QiskitRuntimeService) -> list[dict[str, Any]]:
        backends = service.backends(operational=True, simulator=False)
        return [extract_calibration_metrics(b) for b in backends]

    def action_pick_best(self) -> None:
        if not self.backends_info:
            self._log("[INFO] Load backends first (Refresh QPU).")
            return
        best = min(self.backends_info.values(), key=lambda x: x["score"])
        self.selected_backend_name = best["name"]
        self.query_one("#backend_status", Label).update(best["name"])
        cz = f"{best['med_cz']*100:.3f}%" if best["med_cz"] else "N/A"
        self._log(f"[OPTIMAL] {best['name']} | Queue: {best['pending_jobs']} | CZ: {cz} | Score: {best['score']:.2f}")
        self._show_backend_details(best["name"])

    def action_prepare_circuit(self) -> None:
        if not self.selected_backend_name or self.selected_backend_name not in self.backends_info:
            self._log("[VALIDATION] Select a backend first (click table row or Pick Best).")
            return

        try:
            num_qubits = int(self.query_one("#qubits_input", Input).value.strip())
            layers = int(self.query_one("#layers_input", Input).value.strip())
            opt_level = int(self.query_one("#opt_select", Select).value)
            if num_qubits < 2 or num_qubits > 32 or layers < 1 or layers > 12:
                raise ValueError("Range: qubits 2..32, layers 1..12.")
        except Exception as exc:
            self._log(f"[INVALID PARAMS] {exc}")
            return

        backend_obj = self.backends_info[self.selected_backend_name]["backend"]
        asyncio.create_task(self._prepare_circuit_async(backend_obj, num_qubits, layers, opt_level))

    async def _prepare_circuit_async(
        self, backend_obj: Any, num_qubits: int, layers: int, opt_level: int
    ) -> None:
        self._log(f"[TRANSPILE] {num_qubits}q/{layers}L on {backend_obj.name} (opt={opt_level})...")
        try:
            qc, isa_circuit, physical_qubits = await asyncio.to_thread(
                self._transpile_blocking, backend_obj, num_qubits, layers, opt_level
            )
            self.prepared_isa_circuit = isa_circuit
            ops = dict(isa_circuit.count_ops())
            cz_count = ops.get("cz", 0)

            self._log(f"[LOGICAL] Depth: {qc.depth()} | Ops: {dict(qc.count_ops())}")
            self._log(f"[ISA] {backend_obj.name} | Depth: {isa_circuit.depth()} | CZ: {cz_count} | Native: {ops}")
            if physical_qubits:
                self._log(f"[LAYOUT] Physical qubits: {sorted(physical_qubits)}")
            self._log("[STATUS] Transpiled. Ready to run (consumes RUs).")
        except Exception as exc:
            self._log(f"[TRANSPILE ERROR] {exc}")

    def action_run_circuit(self) -> None:
        if self.prepared_isa_circuit is None:
            self._log("[VALIDATION] Transpile a circuit first (Transpile button).")
            return
        if not self.selected_backend_name or self.service is None:
            self._log("[VALIDATION] No backend selected or not connected.")
            return

        try:
            shots = int(self.query_one("#shots_input", Input).value.strip())
            if shots < 1 or shots > 100000:
                raise ValueError("Shots range: 1..100000")
        except Exception as exc:
            self._log(f"[INVALID SHOTS] {exc}")
            return

        backend_obj = self.backends_info[self.selected_backend_name]["backend"]
        self.query_one("#btn_stop", Button).disabled = False
        self.query_one("#btn_run", Button).disabled = True
        self._log(f"[RUN] Submitting to {backend_obj.name} with {shots} shots...")
        asyncio.create_task(self._run_circuit_async(backend_obj, shots))

    async def _run_circuit_async(self, backend_obj: Any, shots: int) -> None:
        try:
            sampler = await asyncio.to_thread(SamplerV2, mode=backend_obj)
            job = await asyncio.to_thread(sampler.run, [self.prepared_isa_circuit], shots=shots)
            self.running_job = job
            self._log(f"[JOB] Submitted: {job.job_id()} | Status: {job.status()}")
            self._log("[WAIT] Waiting for completion (Stop Job to cancel)...")

            result = await asyncio.to_thread(job.result)
            self._log(f"[DONE] Job completed: {job.job_id()}")
            counts = result[0].data.meas.get_counts()
            self._log(f"[RESULTS] Counts: {dict(list(counts.items())[:10])}...")
            if len(counts) > 10:
                self._log(f"  ... and {len(counts) - 10} more outcomes")
        except Exception as exc:
            self._log(f"[JOB ERROR] {exc}")
        finally:
            self.running_job = None
            self.query_one("#btn_stop", Button).disabled = True
            self.query_one("#btn_run", Button).disabled = False

    def action_stop_job(self) -> None:
        if self.running_job is not None:
            self._log(f"[STOP] Cancelling job {self.running_job.job_id()}...")
            try:
                self.running_job.cancel()
                self._log("[STOP] Cancellation requested.")
            except Exception as exc:
                self._log(f"[STOP ERROR] {exc}")
        else:
            self._log("[STOP] No running job to cancel.")

    @staticmethod
    def _transpile_blocking(
        backend_obj: Any, num_qubits: int, layers: int, opt_level: int
    ) -> tuple[QuantumCircuit, QuantumCircuit, list[int]]:
        qc = build_complex_circuit(num_qubits, layers)
        pass_manager = generate_preset_pass_manager(
            optimization_level=opt_level,
            backend=backend_obj,
        )
        isa_circuit = pass_manager.run(qc)

        physical_qubits: list[int] = []
        if isa_circuit.layout and isa_circuit.layout.initial_layout:
            v2p = isa_circuit.layout.initial_layout.get_virtual_bits()
            physical_qubits = [
                int(phys)
                for virt, phys in v2p.items()
                if getattr(virt, "_register", None) and virt._register.name == "q"
            ]
        return qc, isa_circuit, physical_qubits


if __name__ == "__main__":
    IBMQuantumTUI().run()
This is the result:

Wednesday, December 2, 2026

tkinter : post-quantum key exchange X25519MLKEM768 with raw sockets

This Python Tkinter GUI script probes a target host and port over a raw TCP socket by sending a custom TLS 1.3 ClientHello that advertises post-quantum hybrid key agreement (X25519MLKEM768, 0x11ec) alongside classical groups (x25519 and secp256r1), with an option to include a 1216-byte 0x11ec key_share entry. It parses the server's initial TLS handshake response (ServerHello or HelloRetryRequest), extracts the negotiated TLS version, cipher suite, and key_share group, and displays both a summary and a detailed extension log with copy, paste, and clear controls.
Let's see the source code:
import os
import socket
import struct
import threading
import tkinter as tk
from tkinter import scrolledtext

DEFAULT_HOST = "pq.cloudflareresearch.com"
DEFAULT_PORT = 443

HRR_RANDOM = bytes.fromhex(
    "cf21ad74e59a6111be1d8c021e65b891c2a211167abb8c5e079e09e2c8a8339c"
)


def build_client_hello(hostname: str, include_pqc_key_share: bool = False) -> bytes:
    client_random = os.urandom(32)
    session_id = os.urandom(32)

    cipher_suites = struct.pack("!H", 4) + struct.pack("!HH", 0x1301, 0x1302)
    legacy_compression = b"\x01\x00"

    extensions = bytearray()

    # 0x0000: server_name (SNI)
    sni_bytes = hostname.encode("ascii")
    sni_entry = struct.pack("!BH", 0, len(sni_bytes)) + sni_bytes
    sni_list = struct.pack("!H", len(sni_entry)) + sni_entry
    extensions += struct.pack("!HH", 0x0000, len(sni_list)) + sni_list

    # 0x002b: supported_versions -> TLS 1.3 (0x0304)
    sv_data = b"\x02\x03\x04"
    extensions += struct.pack("!HH", 0x002B, len(sv_data)) + sv_data

    # 0x000a: supported_groups -> X25519MLKEM768 (0x11ec), x25519 (0x001d), secp256r1 (0x0017)
    groups = [0x11EC, 0x001D, 0x0017]
    groups_data = struct.pack("!H", len(groups) * 2) + struct.pack(
        f"!{len(groups)}H", *groups
    )
    extensions += struct.pack("!HH", 0x000A, len(groups_data)) + groups_data

    # 0x0033: key_share
    ks_entries = bytearray()
    if include_pqc_key_share:
        # X25519MLKEM768 client key_share = 32B (x25519) + 1184B (ML-KEM-768) = 1216B
        pqc_ks_bytes = os.urandom(1216)
        ks_entries += struct.pack("!HH", 0x11EC, len(pqc_ks_bytes)) + pqc_ks_bytes

    x25519_pub = os.urandom(32)
    ks_entries += struct.pack("!HH", 0x001D, len(x25519_pub)) + x25519_pub

    ks_data = struct.pack("!H", len(ks_entries)) + bytes(ks_entries)
    extensions += struct.pack("!HH", 0x0033, len(ks_data)) + ks_data

    # 0x000d: signature_algorithms
    sig_algs = [0x0403, 0x0804]
    sig_data = struct.pack("!H", len(sig_algs) * 2) + struct.pack(
        f"!{len(sig_algs)}H", *sig_algs
    )
    extensions += struct.pack("!HH", 0x000D, len(sig_data)) + sig_data

    ch_body = (
        b"\x03\x03"
        + client_random
        + bytes([len(session_id)])
        + session_id
        + cipher_suites
        + legacy_compression
        + struct.pack("!H", len(extensions))
        + bytes(extensions)
    )

    ch_len = len(ch_body)
    handshake_msg = struct.pack("!B", 1) + ch_len.to_bytes(3, "big") + ch_body
    return struct.pack("!BHH", 22, 0x0301, len(handshake_msg)) + handshake_msg


def recv_exact(sock: socket.socket, n: int) -> bytes:
    buf = bytearray()
    while len(buf) < n:
        chunk = sock.recv(n - len(buf))
        if not chunk:
            raise ConnectionError("Socket closed prematurely")
        buf.extend(chunk)
    return bytes(buf)


def probe_tls(host: str, port: int, include_pqc_key_share: bool = False) -> dict:
    hello = build_client_hello(host, include_pqc_key_share=include_pqc_key_share)
    lines = [
        f"Target: {host}:{port}",
        f"ClientHello record size: {len(hello)} bytes",
        "Advertised supported_groups: 0x11ec (X25519MLKEM768), 0x001d (x25519), 0x0017 (secp256r1)",
        (
            "Sent key_share: 0x11ec (1216 bytes) + 0x001d (32 bytes)"
            if include_pqc_key_share
            else "Sent key_share: 0x001d (32 bytes)"
        ),
    ]

    with socket.create_connection((host, port), timeout=10) as sock:
        sock.sendall(hello)
        hdr = recv_exact(sock, 5)
        rec_type, rec_ver, rec_len = struct.unpack("!BHH", hdr)
        payload = recv_exact(sock, rec_len)

    lines.append(
        f"Record received: type={rec_type}, legacy_version=0x{rec_ver:04x}, len={rec_len}"
    )

    summary = {
        "status": "OK",
        "msg_type": f"0x{payload[0]:02x}" if payload else "N/A",
        "cipher": "N/A",
        "version": "N/A",
        "key_share": "N/A",
    }

    if len(payload) < 4:
        summary["status"] = "SHORT PAYLOAD"
        lines.append(f"Raw payload ({len(payload)}B): {payload.hex()}")
        return {"summary": summary, "log": "\n".join(lines)}

    msg_type = payload[0]
    msg_len = int.from_bytes(payload[1:4], "big")
    body = payload[4 : 4 + msg_len]

    if msg_type == 2 and len(body) >= 35:
        srv_random = body[2:34]
        is_hrr = srv_random == HRR_RANDOM
        summary["msg_type"] = "HelloRetryRequest (2)" if is_hrr else "ServerHello (2)"

        sid_len = body[34]
        idx = 35 + sid_len
        if idx + 4 <= len(body):
            cipher_suite = struct.unpack("!H", body[idx : idx + 2])[0]
            comp_method = body[idx + 2]
            ext_total_len = struct.unpack("!H", body[idx + 3 : idx + 5])[0]
            idx += 5
            ext_end = min(idx + ext_total_len, len(body))

            summary["cipher"] = f"0x{cipher_suite:04x}"
            lines.append(
                f"Cipher suite: 0x{cipher_suite:04x}, compression: 0x{comp_method:02x}"
            )

            while idx + 4 <= ext_end:
                ext_type, ext_len = struct.unpack("!HH", body[idx : idx + 4])
                ext_val = body[idx + 4 : idx + 4 + ext_len]
                idx += 4 + ext_len
                lines.append(f"Extension 0x{ext_type:04x} ({ext_len}B): {ext_val.hex()}")

                if ext_type == 0x002B and len(ext_val) >= 2:
                    ver = struct.unpack("!H", ext_val[:2])[0]
                    summary["version"] = f"0x{ver:04x}"
                elif ext_type == 0x0033 and len(ext_val) >= 2:
                    grp = struct.unpack("!H", ext_val[:2])[0]
                    grp_label = {
                        0x11EC: "0x11ec (X25519MLKEM768 - PQC Hybrid)",
                        0x001D: "0x001d (x25519 - Classical)",
                        0x0017: "0x0017 (secp256r1 - Classical)",
                    }.get(grp, f"0x{grp:04x} (Other)")
                    summary["key_share"] = grp_label
    else:
        summary["msg_type"] = f"Type {msg_type}"
        lines.append(f"Handshake len={msg_len}, hex={body[:64].hex()}")

    return {"summary": summary, "log": "\n".join(lines)}


class PqcProbeApp(tk.Tk):
    def __init__(self) -> None:
        super().__init__()
        self.title("TLS 1.3 PQC Probe")
        self.configure(bg="#ffffff")

        btn_opts = {
            "bg": "#e0e0e0",
            "fg": "#000000",
            "activebackground": "#c8c8c8",
            "activeforeground": "#000000",
            "relief": tk.SOLID,
            "bd": 1,
            "padx": 8,
            "pady": 3,
            "font": ("TkDefaultFont", 10, "bold"),
        }

        # Row 1: Host + Port
        row1 = tk.Frame(self, bg="#ffffff", padx=8, pady=4)
        row1.pack(fill=tk.X)

        tk.Label(
            row1,
            text="Host:",
            bg="#ffffff",
            fg="#000000",
            font=("TkDefaultFont", 10, "bold"),
        ).pack(side=tk.LEFT)

        self.host_var = tk.StringVar(value=DEFAULT_HOST)
        self.host_entry = tk.Entry(
            row1,
            textvariable=self.host_var,
            bg="#ffffff",
            fg="#000000",
            insertbackground="#000000",
            relief=tk.SOLID,
            bd=1,
            font=("TkDefaultFont", 10),
        )
        self.host_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(4, 6))

        tk.Label(
            row1,
            text="Port:",
            bg="#ffffff",
            fg="#000000",
            font=("TkDefaultFont", 10, "bold"),
        ).pack(side=tk.LEFT)

        self.port_var = tk.StringVar(value=str(DEFAULT_PORT))
        self.port_entry = tk.Entry(
            row1,
            textvariable=self.port_var,
            width=5,
            bg="#ffffff",
            fg="#000000",
            insertbackground="#000000",
            relief=tk.SOLID,
            bd=1,
            font=("TkDefaultFont", 10),
        )
        self.port_entry.pack(side=tk.LEFT, padx=(4, 0))

        # Row 2: Action buttons (Run / Paste Host / Copy Output / Clear)
        row2 = tk.Frame(self, bg="#ffffff", padx=8, pady=3)
        row2.pack(fill=tk.X)

        self.run_btn = tk.Button(row2, text="Run Probe", command=self.on_run, **btn_opts)
        self.run_btn.pack(side=tk.LEFT, padx=(0, 6))

        self.paste_btn = tk.Button(
            row2, text="Paste Host", command=self.on_paste_host, **btn_opts
        )
        self.paste_btn.pack(side=tk.LEFT, padx=(0, 6))

        self.copy_btn = tk.Button(
            row2, text="Copy Output", command=self.on_copy_output, **btn_opts
        )
        self.copy_btn.pack(side=tk.LEFT, padx=(0, 6))

        self.clear_btn = tk.Button(
            row2, text="Clear", command=self.on_clear, **btn_opts
        )
        self.clear_btn.pack(side=tk.LEFT)

        # Row 3: Option checkbox for full 1216B 0x11ec key_share
        row3 = tk.Frame(self, bg="#ffffff", padx=8, pady=2)
        row3.pack(fill=tk.X)

        self.send_pqc_ks_var = tk.BooleanVar(value=False)
        self.pqc_ks_chk = tk.Checkbutton(
            row3,
            text="Send 0x11ec key_share (1216B)",
            variable=self.send_pqc_ks_var,
            bg="#ffffff",
            fg="#000000",
            activebackground="#ffffff",
            activeforeground="#000000",
            selectcolor="#ffffff",
            font=("TkDefaultFont", 9, "bold"),
        )
        self.pqc_ks_chk.pack(side=tk.LEFT)

        # Summary grid
        grid_frame = tk.Frame(
            self, bg="#f4f4f4", relief=tk.SOLID, bd=1, padx=8, pady=6
        )
        grid_frame.pack(fill=tk.X, padx=8, pady=(4, 6))

        self.fields = {}
        rows = [
            ("Status", "status"),
            ("Handshake Msg", "msg_type"),
            ("TLS Version", "version"),
            ("Cipher Suite", "cipher"),
            ("Key Share", "key_share"),
        ]
        for r_idx, (label, key) in enumerate(rows):
            tk.Label(
                grid_frame,
                text=f"{label}:",
                bg="#f4f4f4",
                fg="#000000",
                font=("TkDefaultFont", 9, "bold"),
                anchor="w",
                width=14,
            ).grid(row=r_idx, column=0, sticky="w", pady=1)

            val_lbl = tk.Label(
                grid_frame,
                text="-",
                bg="#f4f4f4",
                fg="#000000",
                font=("TkFixedFont", 9),
                anchor="w",
            )
            val_lbl.grid(row=r_idx, column=1, sticky="w", pady=1)
            self.fields[key] = val_lbl

        # Log area
        tk.Label(
            self,
            text="Output:",
            bg="#ffffff",
            fg="#000000",
            font=("TkDefaultFont", 9, "bold"),
            anchor="w",
        ).pack(fill=tk.X, padx=8)

        self.log_box = scrolledtext.ScrolledText(
            self,
            bg="#ffffff",
            fg="#000000",
            insertbackground="#000000",
            relief=tk.SOLID,
            bd=1,
            font=("TkFixedFont", 9),
            wrap=tk.WORD,
            height=8,
        )
        self.log_box.pack(fill=tk.BOTH, expand=True, padx=8, pady=(2, 8))

    def on_paste_host(self) -> None:
        try:
            text = self.clipboard_get().strip()
            if text:
                if ":" in text and not text.startswith("["):
                    parts = text.rsplit(":", 1)
                    if parts[1].isdigit():
                        self.host_var.set(parts[0])
                        self.port_var.set(parts[1])
                        return
                self.host_var.set(text)
        except tk.TclError:
            pass

    def on_copy_output(self) -> None:
        summary_lines = [
            f"{lbl}: {self.fields[key].cget('text')}"
            for lbl, key in [
                ("Status", "status"),
                ("Handshake Msg", "msg_type"),
                ("TLS Version", "version"),
                ("Cipher Suite", "cipher"),
                ("Key Share", "key_share"),
            ]
        ]
        log_text = self.log_box.get("1.0", tk.END).strip()
        full_text = "\n".join(summary_lines)
        if log_text:
            full_text += "\n\n" + log_text

        self.clipboard_clear()
        self.clipboard_append(full_text)
        self.fields["status"].config(text="COPIED")

    def on_clear(self) -> None:
        for widget in self.fields.values():
            widget.config(text="-")
        self.log_box.delete("1.0", tk.END)

    def on_run(self) -> None:
        host = self.host_var.get().strip()
        try:
            port = int(self.port_var.get().strip())
        except ValueError:
            self.set_error("Invalid port number")
            return

        if not host:
            self.set_error("Host cannot be empty")
            return

        include_pqc_ks = self.send_pqc_ks_var.get()
        self.run_btn.config(state=tk.DISABLED)
        self.fields["status"].config(text="Running...")
        self.log_box.delete("1.0", tk.END)
        self.log_box.insert(tk.END, f"Connecting to {host}:{port}...\n")

        threading.Thread(
            target=self._worker,
            args=(host, port, include_pqc_ks),
            daemon=True,
        ).start()

    def _worker(self, host: str, port: int, include_pqc_ks: bool) -> None:
        try:
            result = probe_tls(host, port, include_pqc_key_share=include_pqc_ks)
            self.after(0, self._apply_result, result)
        except Exception as exc:
            self.after(0, self.set_error, str(exc))

    def _apply_result(self, result: dict) -> None:
        summary = result["summary"]
        for key, widget in self.fields.items():
            widget.config(text=summary.get(key, "-"))
        self.log_box.delete("1.0", tk.END)
        self.log_box.insert(tk.END, result["log"])
        self.run_btn.config(state=tk.NORMAL)

    def set_error(self, msg: str) -> None:
        self.fields["status"].config(text="ERROR")
        self.log_box.delete("1.0", tk.END)
        self.log_box.insert(tk.END, f"Error: {msg}\n")
        self.run_btn.config(state=tk.NORMAL)


if __name__ == "__main__":
    app = PqcProbeApp()
    app.mainloop()

Monday, November 30, 2026

textual : simple Julia fractal animation on TUI.

Today, testing textual python package with Julia fractal animation.
Textual is a Rapid Application Development framework for Python, built by Textualize.io.
Build sophisticated user interfaces with a simple Python API. Run your apps in the terminal or a web browser!
Let's see the source code:
import math
from rich.color import Color
from rich.segment import Segment
from rich.style import Style
from textual.app import App, ComposeResult
from textual.strip import Strip
from textual.widget import Widget
from textual.widgets import Footer, Header


def hsl_to_rgb(h: float, s: float, l: float) -> tuple[int, int, int]:
    """Convertește coordonate HSL (0..1) în tuple RGB (0..255)."""
    if s == 0.0:
        v = int(l * 255)
        return v, v, v

    def hue_to_rgb(p: float, q: float, t: float) -> float:
        if t < 0.0:
            t += 1.0
        if t > 1.0:
            t -= 1.0
        if t < 1.0 / 6.0:
            return p + (q - p) * 6.0 * t
        if t < 1.0 / 2.0:
            return q
        if t < 2.0 / 3.0:
            return p + (q - p) * (2.0 / 3.0 - t) * 6.0
        return p

    q = l * (1.0 + s) if l < 0.5 else l + s - l * s
    p = 2.0 * l - q
    r = hue_to_rgb(p, q, h + 1.0 / 3.0)
    g = hue_to_rgb(p, q, h)
    b = hue_to_rgb(p, q, h - 1.0 / 3.0)
    return int(r * 255), int(g * 255), int(b * 255)


class JuliaPixelCanvas(Widget):
    """Fiecare celulă din grilă este tratată ca un pixel pătrat (1 celulă = 1 eșantion)."""

    DEFAULT_CSS = """
    JuliaPixelCanvas {
        width: 100%;
        height: 100%;
    }
    """

    def __init__(self) -> None:
        super().__init__()
        self.angle: float = 0.0
        self.zoom: float = 1.0
        self.paused: bool = False
        self.max_iter: int = 36
        # Raport lățime/înălțime al unei celule din terminal (~0.5 pentru font monospace standard)
        self.cell_ratio: float = 0.5

    def on_mount(self) -> None:
        self.set_interval(1 / 15, self.step_animation)

    def step_animation(self) -> None:
        if not self.paused:
            self.angle = (self.angle + 0.045) % (2.0 * math.pi)
            self.refresh()

    def _cell_color(self, x: int, y: int, width: int, height: int, cx: float, cy: float) -> Color:
        # Mapăm centrul fiecărei celule (x + 0.5, y + 0.5) în planul complex
        # Folosim o scară comună pe ambele axe, corectată cu cell_ratio,
        # astfel încât pașii în planul complex să fie pătrați (Δzx == Δzy)
        min_dim = max(1, min(width * self.cell_ratio, height))
        scale = 3.1 / (self.zoom * min_dim)

        zx = ((x + 0.5) - width / 2.0) * (scale * self.cell_ratio)
        zy = ((y + 0.5) - height / 2.0) * scale

        iteration = 0
        max_iter = self.max_iter

        while zx * zx + zy * zy < 4.0 and iteration < max_iter:
            xtemp = zx * zx - zy * zy + cx
            zy = 2.0 * zx * zy + cy
            zx = xtemp
            iteration += 1

        if iteration == max_iter:
            return Color.from_rgb(10, 12, 20)

        hue = ((iteration / max_iter) + self.angle / (2.0 * math.pi)) % 1.0
        r, g, b = hsl_to_rgb(hue, 0.88, 0.54)
        return Color.from_rgb(r, g, b)

    def render_line(self, y: int) -> Strip:
        width = self.size.width
        height = self.size.height

        if width <= 0 or height <= 0 or y >= height:
            return Strip([])

        cx = 0.7885 * math.cos(self.angle)
        cy = 0.7885 * math.sin(self.angle)

        segments: list[Segment] = []
        for x in range(width):
            color = self._cell_color(x, y, width, height, cx, cy)
            # "█" (Full Block) face ca fiecare celulă să arate ca un bloc/pixel plin
            segments.append(Segment("█", Style(color=color)))

        return Strip(segments)


class JuliaPixelApp(App):
    """Aplicație Textual cu pătrate la nivel de celulă (pixel de terminal)."""

    TITLE = "Julia Pixel TUI"
    BINDINGS = [
        ("space", "toggle_pause", "Pauză"),
        ("plus", "zoom_in", "Zoom+"),
        ("equal", "zoom_in", "Zoom+"),
        ("minus", "zoom_out", "Zoom-"),
        ("left_square_bracket", "ratio_down", "Pătrat-"),
        ("right_square_bracket", "ratio_up", "Pătrat+"),
        ("r", "reset_view", "Reset"),
        ("q", "quit", "Ieșire"),
    ]

    def compose(self) -> ComposeResult:
        yield Header(show_clock=False)
        yield JuliaPixelCanvas()
        yield Footer()

    def action_toggle_pause(self) -> None:
        canvas = self.query_one(JuliaPixelCanvas)
        canvas.paused = not canvas.paused

    def action_zoom_in(self) -> None:
        canvas = self.query_one(JuliaPixelCanvas)
        canvas.zoom *= 1.25
        canvas.max_iter = min(96, int(36 + math.log2(max(1.0, canvas.zoom)) * 10))
        canvas.refresh()

    def action_zoom_out(self) -> None:
        canvas = self.query_one(JuliaPixelCanvas)
        canvas.zoom = max(0.4, canvas.zoom / 1.25)
        canvas.refresh()

    def action_ratio_down(self) -> None:
        canvas = self.query_one(JuliaPixelCanvas)
        canvas.cell_ratio = max(0.25, round(canvas.cell_ratio - 0.05, 2))
        canvas.refresh()

    def action_ratio_up(self) -> None:
        canvas = self.query_one(JuliaPixelCanvas)
        canvas.cell_ratio = min(1.0, round(canvas.cell_ratio + 0.05, 2))
        canvas.refresh()

    def action_reset_view(self) -> None:
        canvas = self.query_one(JuliaPixelCanvas)
        canvas.zoom = 1.0
        canvas.angle = 0.0
        canvas.max_iter = 36
        canvas.cell_ratio = 0.5
        canvas.paused = False
        canvas.refresh()


if __name__ == "__main__":
    JuliaPixelApp().run()

Sunday, November 29, 2026

tkinter : basic security & DNS audit tool with httpx

Introduction to HTTPX and Security HTTPX is a modern Python HTTP client supporting sync and async requests, HTTP/1.1 and HTTP/2, connection pooling, and proxies.
In security audits, HTTPX helps enforce TLS verification (verify=True), set granular timeouts, limit connections, control redirects (follow_redirects=False), and inspect response headers, CDNs, and DNS-over-HTTPS.
Best practices: keep TLS verification enabled, set timeouts and connection limits, use a clear User-Agent with controlled pacing, and reuse client context managers.
Let's see the source code:
import importlib.util
import queue
import sys
import threading
import time
import tkinter as tk
from tkinter import scrolledtext
from urllib.parse import urlparse

REQUIRED = ["tkinter", "httpx"]
OPTIONAL = ["h2"]

missing_req = [p for p in REQUIRED if importlib.util.find_spec(p) is None]
if missing_req:
    print("Lipsesc pachete obligatorii:", ", ".join(missing_req))
    print("Instaleaza din Pip in Pydroid 3: httpx")
    sys.exit(1)

import httpx

HAS_H2 = importlib.util.find_spec("h2") is not None
missing_opt = [p for p in OPTIONAL if importlib.util.find_spec(p) is None]

CORE_HEADERS = [
    "strict-transport-security",
    "x-content-type-options",
    "content-security-policy",
    "x-frame-options",
]


def extract_host(url: str) -> str:
    parsed = urlparse(url)
    return (parsed.hostname or "").strip()


def evaluate_medium_headers(url: str, resp: httpx.Response) -> list[str]:
    out: list[str] = []
    h = {k.lower(): v for k, v in resp.headers.items()}
    ctype = h.get("content-type", "")
    is_html = "text/html" in ctype.lower()

    out.append(f"Status: {resp.status_code} | HTTP: {resp.http_version} | Type: {ctype or 'n/a'}")

    if resp.status_code in (301, 302, 303, 307, 308):
        out.append(f"  [REDIRECT] Location: {h.get('location', 'MISSING')}")
        return out

    csp_val = h.get("content-security-policy", "")
    has_frame_ancestors = "frame-ancestors" in csp_val.lower()

    for name in CORE_HEADERS:
        val = h.get(name)
        if name == "strict-transport-security":
            if not url.startswith("https://"):
                out.append("  strict-transport-security: N/A (HTTP)")
            else:
                out.append(f"  strict-transport-security: {val if val else 'MISSING (med)'}")
        elif name == "x-content-type-options":
            out.append(f"  x-content-type-options: {val if val else 'MISSING (med)'}")
        elif name == "content-security-policy":
            if val:
                out.append(f"  content-security-policy: PRESENT ({len(val)} chars)")
            else:
                lvl = "MISSING (med)" if is_html else "MISSING (low/non-html)"
                out.append(f"  content-security-policy: {lvl}")
        elif name == "x-frame-options":
            if val:
                out.append(f"  x-frame-options: {val}")
            elif has_frame_ancestors:
                out.append("  x-frame-options: COVERED BY CSP frame-ancestors")
            else:
                lvl = "MISSING (med)" if is_html else "MISSING (low/non-html)"
                out.append(f"  x-frame-options: {lvl}")

    return out


def check_cloudflare(client: httpx.Client, host: str, resp_headers: dict[str, str]) -> list[str]:
    out: list[str] = ["  [Cloudflare]"]
    cf_ray = resp_headers.get("cf-ray")
    cf_cache = resp_headers.get("cf-cache-status")
    server = resp_headers.get("server", "")

    is_cf = bool(cf_ray or "cloudflare" in server.lower())
    out.append(
        f"    Detected: {'YES' if is_cf else 'NO'} "
        f"(server={server or 'n/a'}, cf-ray={cf_ray or 'n/a'}, cache={cf_cache or 'n/a'})"
    )

    if is_cf and host:
        try:
            tr = client.get(f"https://{host}/cdn-cgi/trace", timeout=5.0)
            if tr.status_code == 200 and "colo=" in tr.text:
                kv = dict(line.split("=", 1) for line in tr.text.splitlines() if "=" in line)
                out.append(
                    f"    Trace: colo={kv.get('colo', 'n/a')} | http={kv.get('http', 'n/a')} "
                    f"| tls={kv.get('tls', 'n/a')} | warp={kv.get('warp', 'n/a')}"
                )
        except httpx.HTTPError:
            out.append("    Trace: unavailable")

    return out


def doh_query(client: httpx.Client, provider: str, domain: str, rtype: str) -> tuple[list[str], bool]:
    if provider == "google":
        url = "https://dns.google/resolve"
    else:
        url = "https://cloudflare-dns.com/dns-query"

    params = {"name": domain, "type": rtype}
    req_headers = {"Accept": "application/dns-json"}

    r = client.get(url, params=params, headers=req_headers, timeout=6.0)
    r.raise_for_status()
    data = r.json()
    ad_flag = bool(data.get("AD", False))
    answers = [str(item.get("data", "")) for item in data.get("Answer", []) if item.get("data")]
    return answers, ad_flag


def check_dns_doh(client: httpx.Client, host: str) -> list[str]:
    out: list[str] = [f"  [DNS DoH: {host}]"]
    if not host:
        out.append("    Invalid host")
        return out

    for rtype in ("A", "AAAA", "NS"):
        g_ans, c_ans = [], []
        g_ad, c_ad = False, False
        g_err, c_err = "", ""

        try:
            g_ans, g_ad = doh_query(client, "google", host, rtype)
        except httpx.HTTPError as e:
            g_err = str(e)

        try:
            c_ans, c_ad = doh_query(client, "cloudflare", host, rtype)
        except httpx.HTTPError as e:
            c_err = str(e)

        g_txt = ",".join(g_ans[:3]) if g_ans else (f"ERR:{g_err[:25]}" if g_err else "none")
        c_txt = ",".join(c_ans[:3]) if c_ans else (f"ERR:{c_err[:25]}" if c_err else "none")
        match = "OK" if (not g_err and not c_err and set(g_ans) == set(c_ans)) else "DIFF/ERR"
        out.append(f"    {rtype}: G=[{g_txt}](AD={g_ad}) | CF=[{c_txt}](AD={c_ad}) -> {match}")

    return out


class App:
    def __init__(self, root: tk.Tk) -> None:
        self.root = root
        self.root.title("HTTP + CF + DoH Audit")

        self.q: queue.Queue[tuple[str, str]] = queue.Queue()
        self.stop_flag = threading.Event()

        tk.Label(self.root, text="URL-uri / domenii:").pack(anchor="w", padx=6, pady=(4, 2))
        self.urls_box = tk.Text(self.root, height=3)
        self.urls_box.pack(fill=tk.X, padx=6)
        self.urls_box.insert("1.0", "https://google.com\nhttps://cloudflare.com\n")

        row1 = tk.Frame(self.root)
        row1.pack(fill=tk.X, padx=6, pady=(4, 2))

        tk.Label(row1, text="Pauza(s):").pack(side=tk.LEFT)
        self.delay_var = tk.StringVar(value="0.5")
        tk.Entry(row1, textvariable=self.delay_var, width=4).pack(side=tk.LEFT, padx=(2, 6))

        self.chk_cf = tk.BooleanVar(value=True)
        tk.Checkbutton(row1, text="CF", variable=self.chk_cf).pack(side=tk.LEFT)

        self.chk_doh = tk.BooleanVar(value=True)
        tk.Checkbutton(row1, text="DoH", variable=self.chk_doh).pack(side=tk.LEFT)

        row2 = tk.Frame(self.root)
        row2.pack(fill=tk.X, padx=6, pady=(2, 4))

        self.start_btn = tk.Button(row2, text="Start", command=self.start)
        self.start_btn.pack(side=tk.LEFT, padx=(0, 6))

        self.stop_btn = tk.Button(row2, text="Stop", command=self.stop, state=tk.DISABLED)
        self.stop_btn.pack(side=tk.LEFT, padx=(0, 6))

        tk.Button(row2, text="Clear", command=self.clear).pack(side=tk.LEFT)

        self.status_var = tk.StringVar(value="Ready")
        tk.Label(self.root, textvariable=self.status_var, anchor="w").pack(fill=tk.X, padx=6)

        self.out = scrolledtext.ScrolledText(self.root, height=12)
        self.out.pack(fill=tk.BOTH, expand=True, padx=6, pady=(2, 6))
        self.out.configure(state=tk.DISABLED)

        self.log("Pachete OK: tkinter, httpx")
        if missing_opt:
            self.log("Optional lipsa: " + ", ".join(missing_opt) + " (HTTP/1.1)")
        else:
            self.log("Optional OK: h2 (HTTP/2)")

        self.poll()

    def log(self, msg: str) -> None:
        self.out.configure(state=tk.NORMAL)
        self.out.insert(tk.END, msg + "\n")
        self.out.see(tk.END)
        self.out.configure(state=tk.DISABLED)

    def clear(self) -> None:
        self.out.configure(state=tk.NORMAL)
        self.out.delete("1.0", tk.END)
        self.out.configure(state=tk.DISABLED)

    def start(self) -> None:
        urls = []
        for line in self.urls_box.get("1.0", tk.END).splitlines():
            u = line.strip()
            if u:
                if not u.startswith(("http://", "https://")):
                    u = "https://" + u
                urls.append(u)

        if not urls:
            self.log("[!] Niciun URL.")
            return

        try:
            delay = max(0.1, float(self.delay_var.get().strip()))
        except ValueError:
            delay = 0.5

        self.stop_flag.clear()
        self.start_btn.configure(state=tk.DISABLED)
        self.stop_btn.configure(state=tk.NORMAL)
        self.status_var.set("Running...")

        threading.Thread(
            target=self.worker,
            args=(urls, delay, self.chk_cf.get(), self.chk_doh.get()),
            daemon=True,
        ).start()

    def stop(self) -> None:
        self.stop_flag.set()
        self.status_var.set("Stopping...")

    def worker(self, urls: list[str], delay: float, run_cf: bool, run_doh: bool) -> None:
        timeout = httpx.Timeout(connect=5.0, read=10.0, write=5.0, pool=5.0)
        headers = {"User-Agent": "AuthorizedSecurityAudit/1.2"}

        with httpx.Client(
            http2=HAS_H2,
            timeout=timeout,
            headers=headers,
            verify=True,
            follow_redirects=False,
        ) as client:
            for i, url in enumerate(urls, start=1):
                if self.stop_flag.is_set():
                    self.q.put(("log", "[!] Oprit."))
                    break

                self.q.put(("status", f"Checking {i}/{len(urls)}: {url}"))
                lines = [f"=== {url} ==="]
                host = extract_host(url)

                try:
                    r = client.get(url)
                    h_low = {k.lower(): v for k, v in r.headers.items()}
                    lines.extend(evaluate_medium_headers(url, r))
                    if run_cf:
                        lines.extend(check_cloudflare(client, host, h_low))
                except httpx.HTTPError as e:
                    lines.append(f"  [!] HTTP/TLS Eroare: {e}")

                if run_doh and not self.stop_flag.is_set():
                    lines.extend(check_dns_doh(client, host))

                self.q.put(("log", "\n".join(lines)))

                if i < len(urls) and not self.stop_flag.is_set():
                    time.sleep(delay)

        self.q.put(("done", "Done"))

    def poll(self) -> None:
        while not self.q.empty():
            kind, val = self.q.get_nowait()
            if kind == "log":
                self.log(val)
            elif kind == "status":
                self.status_var.set(val)
            elif kind == "done":
                self.status_var.set(val)
                self.start_btn.configure(state=tk.NORMAL)
                self.stop_btn.configure(state=tk.DISABLED)
        self.root.after(100, self.poll)


if __name__ == "__main__":
    root = tk.Tk()
    App(root)
    root.mainloop()

tkinter : FastAPI and uvicorn example.

FastAPI ranks 65th with about 506 million downloads, well ahead of Flask (162nd, about 195 million) and Django (466th, about 49 million)
Recommendation: install fastapi and uvicorn separately first, instead of fastapi[standard], to avoid heavy optional packages or packages that are difficult to compile on Android.
Let's see the source code:
import queue
import threading
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
import urllib.request
import uvicorn
from fastapi import FastAPI
from fastapi.responses import HTMLResponse

SERVER_URL = "http://127.0.0.1:8000"

app = FastAPI()
log_queue: queue.Queue[str] = queue.Queue()


def log_message(msg: str) -> None:
    log_queue.put(msg)


@app.get("/", response_class=HTMLResponse)
def home():
    log_message("GET / -> Page loaded")
    return """
    <html>
      <body>
        <h1>FastAPI Server Active</h1>
        <p>Welcome! The server is running locally.</p>
      </body>
    </html>
    """

@app.get("/status")
def status():
    log_message("GET /status -> Status checked")
    return {"status": "ok", "server": "running"}

def run_server() -> None:
    config = uvicorn.Config(app, host="127.0.0.1", port=8000, log_level="warning")
    server = uvicorn.Server(config)
    log_message("[SERVER] Listening on http://127.0.0.1:8000")
    server.run()

class AppGUI:
    def __init__(self, root: tk.Tk) -> None:
        self.root = root
        self.root.title("FastAPI Split View")
        self.root.geometry("600x480")

        # Vertical split: Top = Browser View, Bottom = Server Messages
        paned = tk.PanedWindow(root, orient=tk.VERTICAL, sashrelief=tk.RAISED, sashwidth=6)
        paned.pack(fill=tk.BOTH, expand=True, padx=8, pady=8)

        # --- TOP ZONE: Simple Browser View ---
        top_frame = tk.LabelFrame(paned, text="Browser View", padx=6, pady=6)

        nav_bar = tk.Frame(top_frame)
        nav_bar.pack(fill=tk.X, pady=(0, 6))

        self.url_var = tk.StringVar(value=f"{SERVER_URL}/")
        url_entry = tk.Entry(nav_bar, textvariable=self.url_var)
        url_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 6))
        url_entry.bind("", lambda _event: self.load_url())

        tk.Button(nav_bar, text="Go", command=self.load_url).pack(side=tk.RIGHT)

        self.browser_view = ScrolledText(
            top_frame, wrap=tk.WORD, height=12, state="disabled", bg="#ffffff"
        )
        self.browser_view.pack(fill=tk.BOTH, expand=True)

        # --- BOTTOM ZONE: Server Messages ---
        bottom_frame = tk.LabelFrame(paned, text="Server Messages", padx=6, pady=6)

        self.log_area = ScrolledText(
            bottom_frame,
            wrap=tk.WORD,
            height=10,
            state="disabled",
            bg="#1e1e1e",
            fg="#d4d4d4",
        )
        self.log_area.pack(fill=tk.BOTH, expand=True)

        paned.add(top_frame, minsize=180)
        paned.add(bottom_frame, minsize=140)

        # Start FastAPI server in background
        threading.Thread(target=run_server, daemon=True).start()

        # Start log polling and load home URL automatically after server starts
        self.poll_queue()
        self.root.after(600, self.load_url)

    def load_url(self) -> None:
        url = self.url_var.get().strip()
        threading.Thread(target=self._fetch_page, args=(url,), daemon=True).start()

    def _fetch_page(self, url: str) -> None:
        try:
            with urllib.request.urlopen(url, timeout=3) as resp:
                content = resp.read().decode("utf-8")
        except Exception as exc:
            content = f"Connection error: {exc}"

        self.root.after(0, self._render_browser, content)

    def _render_browser(self, content: str) -> None:
        self.browser_view.configure(state="normal")
        self.browser_view.delete("1.0", tk.END)
        self.browser_view.insert(tk.END, content)
        self.browser_view.configure(state="disabled")

    def append_log(self, text: str) -> None:
        self.log_area.configure(state="normal")
        self.log_area.insert(tk.END, text + "\n")
        self.log_area.see(tk.END)
        self.log_area.configure(state="disabled")

    def poll_queue(self) -> None:
        while not log_queue.empty():
            self.append_log(log_queue.get_nowait())
        self.root.after(100, self.poll_queue)

if __name__ == "__main__":
    root = tk.Tk()
    AppGUI(root)
    root.mainloop()

Wednesday, November 25, 2026

PySide6 : intro sample on pydroid3

Today, I started a new series of examples and tutorials with PySide6. The source code for today is tested on pydroid3 android I.D.E.
The result is this:
See the source code:
#Pydroid run qt
import sys
from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import (
    QApplication,
    QCheckBox,
    QComboBox,
    QGroupBox,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QListWidget,
    QMainWindow,
    QMessageBox,
    QProgressBar,
    QPushButton,
    QRadioButton,
    QSlider,
    QSpinBox,
    QStatusBar,
    QTableWidget,
    QTableWidgetItem,
    QTabWidget,
    QTextEdit,
    QVBoxLayout,
    QWidget,
)

HIGH_CONTRAST_QSS = """
QMainWindow, QWidget {
    background-color: #F4F6F9;
    color: #111827;
    font-size: 14px;
}

QTabWidget::pane {
    border: 1px solid #94A3B8;
    border-radius: 6px;
    background-color: #F4F6F9;
    top: -1px;
}

QTabBar::tab {
    background-color: #E2E8F0;
    color: #1E293B;
    border: 1px solid #94A3B8;
    border-bottom: none;
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
    padding: 8px 14px;
    margin-right: 4px;
    font-weight: bold;
}

QTabBar::tab:selected {
    background-color: #FFFFFF;
    color: #1D4ED8;
    border-color: #1D4ED8;
}

QGroupBox {
    background-color: #FFFFFF;
    border: 1px solid #94A3B8;
    border-radius: 6px;
    margin-top: 12px;
    padding: 12px 10px 10px 10px;
    font-weight: bold;
}

QGroupBox::title {
    subcontrol-origin: margin;
    subcontrol-position: top left;
    left: 10px;
    padding: 0 6px;
    color: #1D4ED8;
    background-color: #F4F6F9;
}

QLabel {
    color: #111827;
    font-weight: normal;
}

QLineEdit, QComboBox, QSpinBox, QListWidget, QTableWidget, QTextEdit {
    background-color: #FFFFFF;
    color: #111827;
    border: 1.5px solid #64748B;
    border-radius: 5px;
    padding: 6px;
    selection-background-color: #1D4ED8;
    selection-color: #FFFFFF;
}

QLineEdit:focus, QComboBox:focus, QSpinBox:focus, QListWidget:focus, QTableWidget:focus, QTextEdit:focus {
    border: 2px solid #1D4ED8;
}

QLineEdit:read-only {
    background-color: #E2E8F0;
    color: #475569;
}

QComboBox QAbstractItemView {
    background-color: #FFFFFF;
    color: #111827;
    selection-background-color: #1D4ED8;
    selection-color: #FFFFFF;
}

QPushButton {
    background-color: #1D4ED8;
    color: #FFFFFF;
    border: none;
    border-radius: 5px;
    padding: 8px 12px;
    font-weight: bold;
}

QPushButton:hover {
    background-color: #1E40AF;
}

QPushButton:pressed {
    background-color: #172554;
}

QCheckBox, QRadioButton {
    color: #111827;
    spacing: 6px;
}

QCheckBox::indicator, QRadioButton::indicator {
    width: 18px;
    height: 18px;
    border: 1.5px solid #334155;
    background-color: #FFFFFF;
}

QCheckBox::indicator:checked, QRadioButton::indicator:checked {
    background-color: #1D4ED8;
    border-color: #1D4ED8;
}

QProgressBar {
    background-color: #E2E8F0;
    color: #111827;
    border: 1.5px solid #64748B;
    border-radius: 5px;
    text-align: center;
    font-weight: bold;
}

QProgressBar::chunk {
    background-color: #15803D;
    border-radius: 3px;
}

QHeaderView::section {
    background-color: #DBEAFE;
    color: #1E3A8A;
    padding: 6px;
    border: 1px solid #94A3B8;
    font-weight: bold;
}

QStatusBar {
    background-color: #E2E8F0;
    color: #111827;
    border-top: 1px solid #94A3B8;
    font-weight: bold;
}
"""


class ComplexGuiWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("PySide6 - Contrast Ridicat")
        self.resize(520, 680)

        self.tabs = QTabWidget()
        self.setCentralWidget(self.tabs)

        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.status_bar.showMessage("Aplicatie pornita - Tema cu contrast ridicat.")

        self.tabs.addTab(self._build_controls_tab(), "Controale")
        self.tabs.addTab(self._build_data_tab(), "Tabel & Lista")
        self.tabs.addTab(self._build_editor_tab(), "Editor & Log")

        self.timer = QTimer(self)
        self.timer.timeout.connect(self._on_timer_tick)

    def _build_controls_tab(self):
        tab = QWidget()
        layout = QVBoxLayout(tab)
        layout.setSpacing(10)

        input_group = QGroupBox("Date de intrare")
        input_layout = QVBoxLayout(input_group)

        self.text_input = QLineEdit()
        self.text_input.setPlaceholderText("Introdu un titlu sau o valoare...")
        self.text_input.setMinimumHeight(40)

        row_select = QHBoxLayout()
        self.category_combo = QComboBox()
        self.category_combo.addItems(["Optiune A", "Optiune B", "Optiune C", "Optiune D"])
        self.category_combo.setMinimumHeight(40)
        self.category_combo.currentTextChanged.connect(
            lambda txt: self.status_bar.showMessage(f"Selectat: {txt}")
        )

        self.amount_spin = QSpinBox()
        self.amount_spin.setRange(1, 1000)
        self.amount_spin.setValue(10)
        self.amount_spin.setPrefix("Cant: ")
        self.amount_spin.setMinimumHeight(40)

        row_select.addWidget(self.category_combo, 2)
        row_select.addWidget(self.amount_spin, 1)

        input_layout.addWidget(self.text_input)
        input_layout.addLayout(row_select)
        layout.addWidget(input_group)

        options_group = QGroupBox("Selectii si Moduri")
        options_layout = QVBoxLayout(options_group)

        chk_row = QHBoxLayout()
        self.chk_active = QCheckBox("Activ")
        self.chk_active.setChecked(True)
        self.chk_notify = QCheckBox("Notificari")
        self.chk_readonly = QCheckBox("Doar citire")
        self.chk_readonly.toggled.connect(self.text_input.setReadOnly)

        chk_row.addWidget(self.chk_active)
        chk_row.addWidget(self.chk_notify)
        chk_row.addWidget(self.chk_readonly)

        radio_row = QHBoxLayout()
        self.radio_fast = QRadioButton("Rapid")
        self.radio_normal = QRadioButton("Normal")
        self.radio_eco = QRadioButton("Eco")
        self.radio_normal.setChecked(True)

        radio_row.addWidget(self.radio_fast)
        radio_row.addWidget(self.radio_normal)
        radio_row.addWidget(self.radio_eco)

        options_layout.addLayout(chk_row)
        options_layout.addLayout(radio_row)
        layout.addWidget(options_group)

        progress_group = QGroupBox("Progres si Nivel")
        progress_layout = QVBoxLayout(progress_group)

        slider_row = QHBoxLayout()
        self.slider_label = QLabel("Nivel: 40%")
        self.slider_label.setStyleSheet("font-weight: bold;")
        self.level_slider = QSlider(Qt.Horizontal)
        self.level_slider.setRange(0, 100)
        self.level_slider.setValue(40)
        self.level_slider.valueChanged.connect(self._on_slider_change)

        slider_row.addWidget(self.slider_label)
        slider_row.addWidget(self.level_slider)

        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(40)
        self.progress_bar.setMinimumHeight(28)

        timer_btn_row = QHBoxLayout()
        self.btn_start_timer = QPushButton("Porneste Auto-Progres")
        self.btn_start_timer.setMinimumHeight(40)
        self.btn_start_timer.clicked.connect(self._toggle_timer)

        self.btn_add_record = QPushButton("Adauga in Tabel & Lista")
        self.btn_add_record.setMinimumHeight(40)
        self.btn_add_record.clicked.connect(self._add_record)

        timer_btn_row.addWidget(self.btn_start_timer)
        timer_btn_row.addWidget(self.btn_add_record)

        progress_layout.addLayout(slider_row)
        progress_layout.addWidget(self.progress_bar)
        progress_layout.addLayout(timer_btn_row)
        layout.addWidget(progress_group)

        layout.addStretch()
        return tab

    def _build_data_tab(self):
        tab = QWidget()
        layout = QVBoxLayout(tab)
        layout.setSpacing(8)

        lbl_list = QLabel("Lista elemente:")
        lbl_list.setStyleSheet("font-weight: bold;")
        layout.addWidget(lbl_list)

        self.item_list = QListWidget()
        self.item_list.addItems(["Element initial 1", "Element initial 2"])
        self.item_list.itemClicked.connect(
            lambda item: self.status_bar.showMessage(f"Element lista: {item.text()}")
        )
        layout.addWidget(self.item_list, 1)

        lbl_table = QLabel("Tabel date:")
        lbl_table.setStyleSheet("font-weight: bold;")
        layout.addWidget(lbl_table)

        self.data_table = QTableWidget(0, 4)
        self.data_table.setHorizontalHeaderLabels(["Nume", "Categorie", "Cant.", "Mod"])
        self.data_table.horizontalHeader().setStretchLastSection(True)
        layout.addWidget(self.data_table, 2)

        btn_row = QHBoxLayout()
        btn_del = QPushButton("Sterge rand selectat")
        btn_del.setMinimumHeight(40)
        btn_del.clicked.connect(self._delete_selected_row)

        btn_clear_all = QPushButton("Goleste tot")
        btn_clear_all.setMinimumHeight(40)
        btn_clear_all.clicked.connect(self._clear_data)

        btn_row.addWidget(btn_del)
        btn_row.addWidget(btn_clear_all)
        layout.addLayout(btn_row)

        return tab

    def _build_editor_tab(self):
        tab = QWidget()
        layout = QVBoxLayout(tab)
        layout.setSpacing(8)

        lbl_log = QLabel("Zona text / Jurnal evenimente:")
        lbl_log.setStyleSheet("font-weight: bold;")
        layout.addWidget(lbl_log)

        self.log_editor = QTextEdit()
        self.log_editor.setPlaceholderText("Aici apar actiunile sau poti scrie text liber...")
        layout.addWidget(self.log_editor)

        btn_row = QHBoxLayout()
        btn_dialog = QPushButton("Afiseaza Dialog Info")
        btn_dialog.setMinimumHeight(40)
        btn_dialog.clicked.connect(self._show_info_dialog)

        btn_clear_log = QPushButton("Curata Jurnal")
        btn_clear_log.setMinimumHeight(40)
        btn_clear_log.clicked.connect(self.log_editor.clear)

        btn_row.addWidget(btn_dialog)
        btn_row.addWidget(btn_clear_log)
        layout.addLayout(btn_row)

        return tab

    def _on_slider_change(self, value):
        self.slider_label.setText(f"Nivel: {value}%")
        self.progress_bar.setValue(value)

    def _toggle_timer(self):
        if self.timer.isActive():
            self.timer.stop()
            self.btn_start_timer.setText("Porneste Auto-Progres")
            self.status_bar.showMessage("Timer oprit.")
        else:
            self.timer.start(150)
            self.btn_start_timer.setText("Opreste Auto-Progres")
            self.status_bar.showMessage("Timer activ.")

    def _on_timer_tick(self):
        val = self.level_slider.value() + 2
        if val > 100:
            val = 0
        self.level_slider.setValue(val)

    def _get_selected_mode(self):
        if self.radio_fast.isChecked():
            return "Rapid"
        if self.radio_eco.isChecked():
            return "Eco"
        return "Normal"

    def _add_record(self):
        name = self.text_input.text().strip() or f"Articol #{self.data_table.rowCount() + 1}"
        category = self.category_combo.currentText()
        qty = str(self.amount_spin.value())
        mode = self._get_selected_mode()

        row_idx = self.data_table.rowCount()
        self.data_table.insertRow(row_idx)
        self.data_table.setItem(row_idx, 0, QTableWidgetItem(name))
        self.data_table.setItem(row_idx, 1, QTableWidgetItem(category))
        self.data_table.setItem(row_idx, 2, QTableWidgetItem(qty))
        self.data_table.setItem(row_idx, 3, QTableWidgetItem(mode))

        summary = f"{name} | {category} | Cant: {qty} | Mod: {mode}"
        self.item_list.addItem(summary)
        self.log_editor.append(f"[ADAUGAT] {summary}")
        self.status_bar.showMessage(f"Adaugat: {name}")
        self.text_input.clear()

    def _delete_selected_row(self):
        row = self.data_table.currentRow()
        if row >= 0:
            self.data_table.removeRow(row)
            self.log_editor.append(f"[STERS] Randul {row + 1} din tabel.")
            self.status_bar.showMessage("Rand sters.")
        else:
            self.status_bar.showMessage("Selecteaza un rand din tabel mai intai.")

    def _clear_data(self):
        self.data_table.setRowCount(0)
        self.item_list.clear()
        self.log_editor.append("[RESET] Lista si tabelul au fost golite.")
        self.status_bar.showMessage("Date golite.")

    def _show_info_dialog(self):
        QMessageBox.information(
            self,
            "Sumar Stare",
            f"Randuri in tabel: {self.data_table.rowCount()}\n"
            f"Nivel curent: {self.level_slider.value()}%\n"
            f"Activ: {'Da' if self.chk_active.isChecked() else 'Nu'}",
        )


def main():
    app = QApplication(sys.argv)
    app.setStyleSheet(HIGH_CONTRAST_QSS)
    window = ComplexGuiWindow()
    window.show()
    sys.exit(app.exec())


if __name__ == "__main__":
    main()

Friday, November 20, 2026

tkinter : the rich python package - demo reel.

Testing the rich python package on pydroid3 on phone ...
import io
import re
import tkinter as tk
from tkinter import font as tkfont
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

class RichTkConsole:

  def __init__(self, root):
    self.root = root
    self.root.title("Rich Console — Tkinter Terminal")
    self.root.geometry("820x540")
    self.root.configure(bg="#0d1117")

    # Fonts
    self.font_regular = tkfont.Font(family="Consolas", size=11)
    self.font_bold = tkfont.Font(family="Consolas", size=11, weight="bold")
    self.font_italic = tkfont.Font(family="Consolas", size=11, slant="italic")
    self.font_bold_italic = tkfont.Font(
        family="Consolas", size=11, weight="bold", slant="italic"
    )

    # Top bar
    header = tk.Frame(root, bg="#161b22", height=32)
    header.pack(fill=tk.X)
    tk.Label(
        header,
        text="  ● ● ●   RICH TERMINAL EMULATOR (c = Console())",
        fg="#8b949e",
        bg="#161b22",
        font=("Consolas", 10, "bold"),
    ).pack(side=tk.LEFT, pady=6)

    tk.Button(
        header,
        text="▶ Run Demo Reel",
        command=self.run_demo_reel,
        bg="#238636",
        fg="white",
        relief=tk.FLAT,
        font=("Consolas", 9, "bold"),
        padx=10,
        cursor="hand2",
    ).pack(side=tk.RIGHT, padx=8, pady=4)

    tk.Button(
        header,
        text="Clear",
        command=self.clear,
        bg="#30363d",
        fg="#c9d1d9",
        relief=tk.FLAT,
        font=("Consolas", 9),
        padx=10,
        cursor="hand2",
    ).pack(side=tk.RIGHT, padx=2, pady=4)

    # Output area
    self.output = tk.Text(
        root,
        bg="#0d1117",
        fg="#e6edf3",
        insertbackground="#58a6ff",
        font=self.font_regular,
        padx=14,
        pady=12,
        relief=tk.FLAT,
        wrap=tk.WORD,
        state=tk.DISABLED,
    )
    self.output.pack(fill=tk.BOTH, expand=True)

    # Interactive command bar at bottom
    input_frame = tk.Frame(root, bg="#161b22")
    input_frame.pack(fill=tk.X, side=tk.BOTTOM)

    tk.Label(
        input_frame,
        text=" >>> ",
        fg="#58a6ff",
        bg="#161b22",
        font=("Consolas", 11, "bold"),
    ).pack(side=tk.LEFT, pady=8)

    self.cmd_entry = tk.Entry(
        input_frame,
        bg="#0d1117",
        fg="#e6edf3",
        insertbackground="#58a6ff",
        font=self.font_regular,
        relief=tk.FLAT,
    )
    self.cmd_entry.pack(
        side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10), pady=8, ipady=4
    )
    self.cmd_entry.insert(
        0, "c.print('this is amazing', style='bold red on yellow')"
    )
    self.cmd_entry.bind("", self.execute_command)

    # ANSI color palette (modern terminal colors)
    self.ANSI_FG = {
        "30": "#484f58",
        "31": "#ff7b72",
        "32": "#3fb950",
        "33": "#d29922",
        "34": "#58a6ff",
        "35": "#bc8cff",
        "36": "#39c5cf",
        "37": "#e6edf3",
        "90": "#6e7681",
        "91": "#ffa198",
        "92": "#56d364",
        "93": "#e3b341",
        "94": "#79c0ff",
        "95": "#d2a8ff",
        "96": "#56d4dd",
        "97": "#ffffff",
    }
    self.ANSI_BG = {
        "40": "#161b22",
        "41": "#da3633",
        "42": "#238636",
        "43": "#d29922",
        "44": "#1f6feb",
        "45": "#8957e5",
        "46": "#1b7c83",
        "47": "#b1bac4",
        "100": "#484f58",
        "101": "#ff7b72",
        "102": "#3fb950",
        "103": "#e3b341",
        "104": "#58a6ff",
        "105": "#bc8cff",
        "106": "#39c5cf",
        "107": "#ffffff",
    }

  def _get_tag(self, state):
    tag = (
        f"t_{state['bold']}_{state['italic']}_{state['underline']}_"
        f"{state['fg']}_{state['bg']}"
    )
    if tag not in self.output.tag_names():
      if state["bold"] and state["italic"]:
        fnt = self.font_bold_italic
      elif state["bold"]:
        fnt = self.font_bold
      elif state["italic"]:
        fnt = self.font_italic
      else:
        fnt = self.font_regular

      cfg = {"font": fnt, "underline": state["underline"]}
      if state["fg"]:
        cfg["foreground"] = state["fg"]
      if state["bg"]:
        cfg["background"] = state["bg"]
      self.output.tag_configure(tag, **cfg)
    return tag

  def render_rich(self, render_fn):
    """Captures Rich Console output and renders ANSI styles into Tkinter."""
    buf = io.StringIO()
    console = Console(
        file=buf, force_terminal=True, color_system="standard", width=78
    )
    render_fn(console)
    ansi_text = buf.getvalue()

    self.output.config(state=tk.NORMAL)
    state = {
        "bold": False,
        "italic": False,
        "underline": False,
        "fg": None,
        "bg": None,
    }
    pattern = re.compile(r"\x1b\[([0-9;]*)m")
    pos = 0

    for match in pattern.finditer(ansi_text):
      chunk = ansi_text[pos : match.start()]
      if chunk:
        self.output.insert(tk.END, chunk, self._get_tag(state))

      codes = match.group(1).split(";") if match.group(1) else ["0"]
      for code in codes:
        if code in ("0", ""):
          state = {
              "bold": False,
              "italic": False,
              "underline": False,
              "fg": None,
              "bg": None,
          }
        elif code == "1":
          state["bold"] = True
        elif code == "3":
          state["italic"] = True
        elif code == "4":
          state["underline"] = True
        elif code == "22":
          state["bold"] = False
        elif code == "23":
          state["italic"] = False
        elif code == "24":
          state["underline"] = False
        elif code in self.ANSI_FG:
          state["fg"] = self.ANSI_FG[code]
        elif code in self.ANSI_BG:
          state["bg"] = self.ANSI_BG[code]
        elif code == "39":
          state["fg"] = None
        elif code == "49":
          state["bg"] = None
      pos = match.end()

    if pos < len(ansi_text):
      self.output.insert(tk.END, ansi_text[pos:], self._get_tag(state))

    self.output.see(tk.END)
    self.output.config(state=tk.DISABLED)

  def clear(self):
    self.output.config(state=tk.NORMAL)
    self.output.delete("1.0", tk.END)
    self.output.config(state=tk.DISABLED)

  def execute_command(self, event=None):
    cmd = self.cmd_entry.get().strip()
    if not cmd:
      return
    self.render_rich(lambda c: c.print(f"[dim]$ {cmd}[/dim]"))
    try:
      self.render_rich(
          lambda c: exec(cmd, {"c": c, "Panel": Panel, "Table": Table})
      )
    except Exception as exc:
      self.render_rich(lambda c: c.print(f"[bold red]Error:[/] {exc}"))
    self.cmd_entry.delete(0, tk.END)

  def run_demo_reel(self):
    self.clear()
    steps = [
        (
            200,
            lambda c: c.print(
                Panel.fit(
                    "[bold cyan]RICH + TKINTER DEMO REEL[/]\n"
                    "[dim]Rendering genuine Rich console styles inside a GUI"
                    " window[/]",
                    border_style="bright_blue",
                )
            ),
        ),
        (
            900,
            lambda c: c.print(
                "\n[bold white]1. Classic Styled Prints:[/]"
            ),
        ),
        (
            1300,
            lambda c: c.print(
                "this is amazing", style="bold red on yellow"
            ),
        ),
        (
            1800,
            lambda c: c.print(
                "this is amazing", style="italic blue on red"
            ),
        ),
        (
            2400,
            lambda c: c.print(
                "\n[bold white]2. Inline Markup & Typography:[/]"
            ),
        ),
        (
            2900,
            lambda c: c.print(
                "Supports [bold green]bold[/], [italic magenta]italic[/], "
                "[underline cyan]underlined[/], and [black on bright_green]"
                " highlighted badges [/] seamlessly."
            ),
        ),
        (
            3600,
            lambda c: c.print("\n[bold white]3. Structured Rich Tables:[/]"),
        ),
        (4100, self._demo_table),
        (
            5000,
            lambda c: c.print(
                "\n[bold bright_green]✔ Demo complete.[/] "
                "[dim]Type any Python/Rich command below and press Enter![/]\n"
            ),
        ),
    ]
    for delay, fn in steps:
      self.root.after(delay, lambda f=fn: self.render_rich(f))

  @staticmethod
  def _demo_table(c):
    table = Table(title="Live System Telemetry", border_style="cyan")
    table.add_column("Module", style="bold cyan")
    table.add_column("Status", style="bold green")
    table.add_column("Latency", justify="right", style="yellow")
    table.add_row("Rich Engine", "ONLINE", "1.2 ms")
    table.add_row("ANSI Parser", "ACTIVE", "0.4 ms")
    table.add_row("Tkinter Canvas", "RENDERED", "2.1 ms")
    c.print(table)

if __name__ == "__main__":
  root = tk.Tk()
  app = RichTkConsole(root)
  app.run_demo_reel()
  root.mainloop()

Monday, November 2, 2026

News : last month python releases

Last month python development comes with the releases :3.16.0a1,3.15.2,3.15.1,3.15.0,3.15.0rc3,3.14.10,3.14.9,3.14.8,3.13.18,3.13.17,3.13.16,3.12.16,3.12.15,3.11.18,3.11.17,3.10.22

Monday, October 26, 2026

News : PyTorch Conference 2026 with new products and integrations, native PyTorch stack for Google TPUs

Today at PyTorch Conference 2026, we announced a range of new products and integrations designed to help you run PyTorch effectively on Google Cloud or in your own infrastructure. Notably, TorchTPU, our native PyTorch stack for Google TPUs, is now available as open source on GitHub. With TorchTPU, TPUs join GPUs and CPUs as a native option for PyTorch. You can now train, serve, and deploy models on TPUs using the tools you already rely on, including vLLM, SGLang, llm-d, TorchTitan, Ray, TorchRec, Hugging Face, LiteRT. Ultimately, this provides our customers choice across a broad range of workload-optimized computing options including TPUs, GPUs, and CPUs, with a consistent, open software and operational model across the full portfolio.
This project provides a PyTorch backend for Google's Tensor Processing Units (TPUs), enabling users to run PyTorch models and operations on TPU devices. It includes custom ATen kernels for various PyTorch operations, a compilation cache for optimizing execution, and examples for distributed training and model inference.

Sunday, October 25, 2026

Python 3.13.15 : Colab example with Precise Object and Effect Removal with Adaptive Target-Aware Attention.

ObjectClear is an object removal model that can jointly eliminate the target object and its associated effects leveraging Adaptive Target-Aware Attention, while preserving background consistency
See the colab on my GitHub repo based on this GitHub repo.

Wednesday, October 14, 2026

Python 3.13.15 : Colab example with Quantum Portfolio Optimization for four major tech stocks using NVIDIA CUDA-Q

NOTE : I’ve lost track of how many posts I have on this blog regarding Google Colab examples; there are more in the GitHub repo, though I can’t guarantee they still work after updates.
Today, we present a more complex example of quantum processing using NVIDIA CUDA-Q acceleration on a GPU. In this notebook, you will find a few simple demonstrations and a real-world example involving the quantum optimization of a portfolio, based on real volatility and using actual data—comprising the stocks of four major technology companies (NVDA, AAPL, MSFT, AMZN).
See more on my GitHub repo.