3446. Sort Matrix by Diagonals

You are given an n x n square matrix of integers grid. Return the matrix such that: The diagonals in the bottom-left triangle (including the middle diagonal) are sorted in non-increasing order. The diagonals in the top-right triangle are sorted in non-decreasing order.
/**
 * @param {number[][]} grid
 * @return {number[][]}
 */
var sortMatrix = function(grid) {
    const n = grid.length;

    // Helper to extract a matrix starting at (row, col)
    function getMatrix(row, col) {
        const matrix = [];
        while (row < n && col < n) {
            matrix.push(grid[row][col]);
            row++;
            col++;
        }
        return matrix;
    }

    // Helper to write a sorted matrix back into the grid
    function setMatrix(row, col, sorted) {
  

Disable KVM permanently (so VirtualBox can use AMD-V)

# Disable KVM permanently (so VirtualBox can use AMD-V) and restore it later if you need QEMU/virt-manager again.


## Disable KVM so VirtualBox can use AMD-V 
1. Create a blacklist file for KVM modules:<br> 
`echo -e "blacklist kvm\nblacklist kvm_amd" | sudo tee /etc/modprobe.d/disable-kvm.conf`
2. Rebuild initramfs so the blacklist applies at early boot (needed on Ubuntu/Debian; harmless to run anyway):<br>
`sudo update-initramfs -u`
3. Reboot your system. After reboot, verify that kvm is not 

CEM-Net

# CEM-Net (Minimal) — Emotion-Aware Music Modeling with Cultural Context This repository provides a compact PyTorch implementation of an emotion-aware music model that fuses **temporal audio features** with **culture embeddings**. It follows the spirit of the CEM-Net + CAES framework: a BiGRU temporal encoder, attention pooling over time, culture-aware fusion, and a flexible decoder for **classification** or **valence–arousal regression**. - Temporal encoder: BiGRU over frame-level features (e.g., log-mel, chroma, MFCC). - Attention pooling: learns which time steps matter for affect. - Cultural embeddings: inject cultural priors and enable culture-aware predictions. - Decoder: softmax (classification) or tanh-bounded (regression). - Optional losses: alignment/contrast hooks for cross-cultural consistency. > Architecture inspiration: the **schematic on page 6 (Figure 1)** highlights temporal encoding + culture-aware fusion + alignment; the **contrastive/CAES pipeline on page 9–11 (Figure 2–3)** motivates the provided loss hooks and cultural disentanglement options. :contentReference[oaicite:0]{index=0} --- ## 1. Why this repo? - **Starter kit** for research or product prototyping on music emotion recognition (MER) with cultural context. - Clean, dependency-light PyTorch model that you can drop into your training loop. - Easy to switch between **classification** and **regression** heads. --- ## 2. Quickstart ### 2.1. Environment ```bash python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install torch torchaudio numpy

---

# model.py

```python
from dataclasses import dataclass
from typing import Optional, Tuple, Literal

import torch
import torch.nn as nn
import torch.nn.functional as F


# --------------------------
# Config
# --------------------------

@dataclass
class CEMConfig:
    # Input
    feat_dim: int = 128          # frame feature size F
    # Temporal encoder
    hidden_size: int = 256       # GRU hidden (per direction)
    num_layers: int = 1
    dropout: float = 0.1

TriLanSphere

# TriLanSphere (Minimal) – Multimodal Policy Model A minimal, educational PyTorch implementation of a **tri-modal policy network** inspired by research on grounded language learning in 3D environments. It fuses: - **Language encoder** (token embeddings + Transformer encoder) - **Spatial perception encoder** (object features + voxel grid via 3D conv) - **Cross-modal attention** (spatial ↔ language) - **Temporal grounding memory** (GRU over fused features) - **Policy head** (action logits or continuous controls) > This repository provides a compact reference to help you bootstrap experiments or demos. It is **not** a full training pipeline or dataset release. --- ## Features - Plug-and-play `TriLanSphere` model in `model.py` - Works with discrete action spaces out of the box - Modular subcomponents so you can swap encoders or policy heads - Type hints and docstrings for quick integration --- ## Quickstart ### 1) Install ```bash python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate pip install torch --index-url https://download.pytorch.org/whl/cpu # or your CUDA wheel

---

# model.py

```python
from dataclasses import dataclass
from typing import Dict, Tuple, Optional

import math
import torch
import torch.nn as nn
import torch.nn.functional as F


# -------------------------
# Config
# -------------------------
@dataclass
class TriLanSphereConfig:
    # Text
    vocab_size: int = 32000
    d_model: int = 256
    max_len: int = 128
    n_heads: int = 4
    n_layers_text: int = 2
    dropout: float = 0.1

    # Spatial (objects + v

AeroVISTA

# AeroVISTA: Trajectory-Level Sightseeing Quality Scoring A reference PyTorch implementation of **AeroVISTA** — an evaluation model for low-altitude sightseeing experience that fuses **visual**, **geospatial**, and **landmark-graph** signals to produce a **trajectory-level utility score**. The design follows a dual-system idea: a data-driven perception model (AeroVISTA) complemented by a rule/metric toolbox (SCENORAMA-style regularizers) for interpretability. > Core ideas: semantic visual encoding → attention-gated temporal memory → geospatial embedding → landmark graph integration → permutation-invariant trajectory pooling → utility scoring with occlusion & angular smoothness regularization. :contentReference[oaicite:0]{index=0} ## Features - **Semantic visual encoder** (pluggable backbone; uses a lightweight CNN by default). - **Attention-gated GRU** for long-range temporal coherence. - **Geospatial encoder** for 3D positions (x, y, z). - **Landmark Graph Integration** via a single-step GNN (GCN-like) over a landmark adjacency matrix. - **Trajectory pooling** to get a compact descriptor of the full flight. - **Utility scoring** in \[0,1], with optional **occlusion** and **view-angle smoothness** penalties. > See the schematic of the pipeline in **Figure 1 (page 6)** and the trajectory-level scoring in **Figure 2 (page 8)** of the accompanying paper for high-level architecture and objective components. ## Installation ```bash pip install torch torchvision

---

# model.py

```python
"""
AeroVISTA: Trajectory-Level Sightseeing Quality Scoring
-------------------------------------------------------

This module implements a compact PyTorch version of the AeroVISTA model:

- Semantic visual encoding (lightweight CNN by default; pluggable backbone)
- Attention-gated GRU for temporal aggregation
- Geospatial encoder for (x, y, z)
- Landmark Graph Integration (GCN-like)
- Permutation-invariant trajectory pooling
- Utility scoring with 

LexiTrace + LinguoScope

# LexiTrace + LinguoScope (Minimal PyTorch Reference) A lightweight, educational PyTorch implementation of a **multimodal learner modeling** stack featuring: - **LexiTrace** — a gated, competency-tracking encoder over learner events with curriculum-aware graph propagation. - **LinguoScope** — a curriculum-aligned projection & recommendation head for evaluation, deviation analysis, and next-task selection. This repo is intended for fast prototyping and reproducible baselines. It follows the core ideas (gated update, temporal smoothness, curriculum projection, deviation and monotonicity penalties, and task-directional recommendation) described in the attached paper. :contentReference[oaicite:0]{index=0} > Quick pointers to the paper’s components: > - **Gated competency update** (LexiTrace): Eq. (7)–(9); **temporal smoothness**: Eq. (10)/(18). > - **Curriculum graph propagation**: Eq. (11)–(15). > - **Curriculum projection & deviation/monotonicity** (LinguoScope): Eq. (22)–(25). > - **Next-task direction & cosine selection**: Eq. (26)–(27), and multi-objective score: Eq. (28)–(30). > - **Directional gain & structural utility**: Eq. (31)–(35). > Figures illustrating the encoder and projection appear on **page 6–7 (Fig. 1–2)** and **page 10 (Fig. 4)** of the PDF. :contentReference[oaicite:1]{index=1} --- ## Features - Minimal, readable **PyTorch** code (`model.py`) with type hints. - Pluggable **task embeddings**, **behavioral features**, and **prerequisite graph** hooks. - Built-in **loss dictionary**: prediction MSE, smoothness, task-alignment (cosine/angle), entropy, deviation, regression penalty, and a utility score. --- ## Installation ```bash pip install torch numpy

---

# model.py

```python
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional, List, Dict, Tuple

import torch
import torch.nn as nn
import torch.nn.functional as F


# ----------------------------
# Data containers
# ----------------------------

@dataclass
class Batch:
    z: torch.Tensor                   # (B, T, d_z): multimodal/event features per step
    c0: torch.Tensor                  # (B, d_c): initial competency (s

Add an element based on the amount of items in twig (after two items you add a n svg)

<div class="speeldata-container">
    {% set pairs = (speeldata|length / 2)|round(0, 'floor') %}

    {% if pairs > 0 %}
        <div class="lines">
            {% for i in 1..pairs %}
                {% set shape_position = i is odd ? 'left' : 'right' %}
                <div class="line-shape">
                    {% include 'partials/svg.twig' with {
                        attr_height:'250',
                        id:'vertical-line-' ~ shape_position,
                        ariaLabel:'Lange

SCAN

# SCAN: Spatio-Competitive Attention Network (minimal PyTorch) A minimal, self-contained PyTorch implementation of the **Spatio-Competitive Attention Network (SCAN)** with the **Adversarial Contextual Reinforcement Strategy (ACRS)** for sports action recognition and competition behavior analysis. This repo provides: - `model.py` – SCAN backbone (agent encoder, relational encoder, graph attention fusion, temporal memory) and ACRS losses (contextual policy shaping, adversarial role regularization, strategic distance constraint) in a compact, easy-to-read form. - An example training step demonstrating how to call the losses. > Design and notation follow the paper “Cultural Heritage-Inspired Deep Framework for Sports Action Recognition and Competition Behavior Analysis,” especially Sections **3.2–3.4** (SCAN & ACRS), equations (1)–(35), and Figures 1–4. :contentReference[oaicite:1]{index=1} --- ## Features - **Agent-centric temporal encoder** (linear projection + GRU) over multimodal agent tokens. - **Relational encoder** with pairwise MLP and **multi-head competitive attention** to aggregate inter-agent context. - **Temporal memory augmentation** (EMA + gate) to carry long-horizon strategy. - **Dual heads**: action classification and behavioral role prediction. - **ACRS training components**: - Contextual Policy Shaping (reward-weighted NLL) - Adversarial Role Regularization (role prior discriminator + gradient penalty) - Strategic Distance Constraint (margin in latent space for visually similar but behaviorally distinct pairs) - Optional relational contrastive & alignment regularizers --- ## Installation ```bash pip install torch torchvision

---

# model.py

```python
# model.py
# Minimal SCAN + ACRS (PyTorch)
# MIT License

from __future__ import annotations
import math
from typing import Dict, Optional, Tuple

import torch
import torch.nn as nn
import torch.nn.functional as F


def _pairwise_diff(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """
    Compute pairwise differences a[:, :, None, :] - b[:, None, :, :]

    a: (B, N, D)
    b: (B, N, D)
    return: (B, N, N, D)
    """
    return a.u

NeuroSymNet

# NeuroSymNet (PyTorch) – Multimodal Stress Detection A reference PyTorch implementation of a **neural–symbolic** model for psychological stress detection, tailored for professional women and real-world multimodal inputs. The model follows the architecture and training ideas described in the paper *“Multimodal Deep Representation Learning for Psychological Stress Detection in Professional Women”* (NeuroSymNet + CortexoRoute). > High level: a physiological encoder (Conv1D + BiGRU) with **cycle-phase gating** and **cross-channel attention**, a **symbolic temporal abstraction** layer that turns short windows into trend symbols (↑, ↓, →), and a **graph-style temporal propagation** (attention across time) before a 3-class stress head. See the *architecture diagram on page 7 (Fig. 1)* and the *multimodal encoder diagram on page 8 (Fig. 2)* of the paper for visual intuition. :contentReference[oaicite:0]{index=0} --- ## Features - **Physiological encoder**: Conv1D over time + BiGRU for temporal context. - **Cycle-phase gating**: sinusoidal phase embedding modulates representations, matching the paper’s phase-aware design. - **Cross-channel attention**: lets the model emphasize informative channels when others are noisy. - **Symbolic temporal abstraction**: converts short windows into qualitative trend symbols (↑/↓/→) and embeds them. - **Temporal graph propagation**: self-attention across time steps for relational reasoning. - **Ordinal utility**: helper loss encouraging ordered stress levels (0: none, 1: moderate, 2: high). - **MC-dropout** utilities for simple epistemic/aleatoric uncertainty estimates. These components mirror the paper’s modules (physiological encoder, symbolic abstraction, neuro-relational core, and CortexoRoute’s calibration ideas). The paper reports stronger robustness and interpretability; our code offers a compact, training-ready version you can extend. **See pages 7–12 for the method details and equations.** :contentReference[oaicite:1]{index=1} --- ## Installation ```bash python -m venv .venv && source .venv/bin/activate # (Windows: .venv\Scripts\activate) pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121 # choose your CUDA/CPU wheel

---

## model.py

```python
# model.py
# A compact PyTorch implementation of NeuroSymNet-style stress detection.
# Components:
# - Physiological encoder: Conv1D + Positional encoding + BiGRU
# - Cycle-phase gating (sinusoidal phase embedding -> sigmoid gate)
# - Cross-channel attention
# - Symbolic temporal abstraction (↑/↓/→)
# - Temporal graph-style propagation (self-attention across time)
# - 3-class classifier head (+ helper ordinal loss and MC-dropout utilities)

from typin

SpineBERT

# SpineBERT: Attention-Driven Behavioral Recognition for Spinal Disorders An open-source PyTorch implementation of **SpineBERT**, an attention-driven, biomechanically-aware model for behavioral recognition and functional assessment from spatiotemporal motion signals. > High-level design: a transformer-style encoder with anatomical embeddings and spatial bias, a segment-level **Graphical Propagation Layer**, **Conditional LayerNorm** with subject embeddings, and a **contrastive alignment head** in addition to a classification head. See the architecture schematic (Figure 1 on page 7) and the multimodal encoder diagram (Figure 2 on page 8) for visual intuition. :contentReference[oaicite:0]{index=0} --- ## Highlights - **Anatomy-aware attention**: injects spatial bias using joint positions to guide attention over time and space. (Page 7, Eq. 10–11; see the attention block in Figure 2 on page 8.) :contentReference[oaicite:1]{index=1} - **Graphical Propagation Layer (GPL)**: summarizes non-overlapping temporal windows and propagates information over a segment graph to capture mid-range dependencies. (Page 7–8, Eq. 12–13.) :contentReference[oaicite:2]{index=2} - **Conditional LayerNorm (CLN)** with subject embeddings: adapts normalization to individual biomechanical baselines. (Page 8, Eq. 14.) :contentReference[oaicite:3]{index=3} - **Gated fusion** of local vs. propagated features for robust temporal coherence. (Page 8, Eq. 15.) :contentReference[oaicite:4]{index=4} - **Dual heads**: classification head for diagnostic labels (Page 9, Eq. 16) and a contrastive alignment head to cluster same-behavior samples across subjects (Page 9, Eq. 17–20). :contentReference[oaicite:5]{index=5} --- ## Installation ```bash conda create -n spinebert python=3.10 -y conda activate spinebert pip install torch torchvision torchaudio # choose CUDA/CPU build as needed pip install numpy
# model.py
# SpineBERT: attention-driven behavioral recognition with biomechanical priors
# Minimal, self-contained PyTorch implementation inspired by the reference design.
# See equations and figures referenced in the accompanying README. :contentReference[oaicite:18]{index=18}

from dataclasses import dataclass
from typing import Optional, Tuple

import math
import torch
import torch.nn as nn
import torch.nn.functional as F


# -----------------------------
# Utilities
# ------

Synergetic Ethical Embedding Network (SEEN)

# Synergetic Ethical Embedding Network (SEEN) A minimal, PyTorch-based reference implementation of the **Synergetic Ethical Embedding Network (SEEN)** and the **Reflective Physical Co-training Strategy (RPCS)** for modeling the co-evolution of *physical performance* and *moral cognition* in structured training environments. > **Why this repo?** > Traditional PE systems often treat physical and moral development as separate. SEEN provides a principled architecture to **fuse** those dimensions and to **adapt** task routing using synergy feedback (RPCS), enabling research on holistic training. According to the paper, SEEN is a **dual-stream** model (physical + moral) with **cross-attention fusion**, **graph-based relational interaction**, and **curriculum-aware synergy activation**; RPCS adds **adaptive task routing**, **ethical feedback integration**, and **synergy preservation**. See the schematic figures (e.g., *Figure 1 on p.6*, *Figure 3 on p.9*) for the end-to-end flow. :contentReference[oaicite:0]{index=0} --- ## Features - **Dual-Stream Embedding Fusion**: learnable projections for physical/moral latents with multi-head cross attention. - **Relational Moral Interaction**: lightweight message passing over a social/interaction graph. - **Curriculum-Aware Synergy Activation**: task embeddings gate the joint state and yield a synergy scalar. - **RPCS**: adaptive task selection with fatigue control, priority boosts for low moral attributes, and a simple synergy-drop safeguard. - **Batteries included**: clean, typed PyTorch modules and an example training loop. --- ## Installation ```bash pip install torch torchvision torchaudio # choose CUDA/CPU build as needed
# model.py
# Minimal reference implementation of SEEN + RPCS (PyTorch)
# Author: Legend Co., Ltd. (Savannah Banks) — reference implementation
# License: MIT

from __future__ import annotations
from dataclasses import dataclass
from typing import Optional, Tuple

import torch
import torch.nn as nn
import torch.nn.functional as F


# ----------------------------
# Utilities
# ----------------------------

class MLP(nn.Module):
    def __init__(self, d_in: int, d_hidden: int, d_o

AthlEthosNet

# AthlEthosNet (Minimal) — Dual-State Modeling for Sports–Morality Integration A lightweight PyTorch implementation that models *two intertwined latent states* per student: - **Moral state** (`mu`) — an interpretable vector of moral traits. - **Behavior state** (`psi`) — an embedding of observed athletic/interaction features. The model couples these states via **gated, mutually-influential dynamics** and augments the behavior stream with a **memory-guided attention** over historical moral states. It also includes a **coherence loss** that encourages moral–behavioral alignment. > **Why this repo?** > To give you a compact, trainable reference implementation suitable for research prototypes, ablations, or course projects. --- ## Key Ideas - **Dual-State Representation:** separate moral and behavior embeddings that evolve jointly. - **Mutually Influential Dynamics:** GRU-style gates let behavior inform moral updates (and vice versa). - **Memory-Guided Behavioral Modeling:** attention over past moral states conditions current behavior encoding. - **Coherence Regularizer:** cosine alignment between projected moral and behavior vectors. These components follow the structure outlined by the *AthlEthosNet* style of modeling (see paper figures and equations around pages 6–10). :contentReference[oaicite:1]{index=1} --- ## Quick Start ### 1) Install ```bash pip install torch
"""
AthlEthosNet (Minimal)
----------------------
A compact PyTorch module demonstrating:
  - Dual-State Representation (moral `mu`, behavior `psi`)
  - Mutually Influential (gated) updates
  - Memory-Guided Behavioral Modeling (attention over moral history)
  - Coherence regularizer (cosine alignment between projected moral & behavior)

Shapes (per forward step)
-------------------------
Inputs:
  o_t:        (B, obs_dim)
  mu_tm1:     (B, moral_dim)
  psi_tm1:    (B, beh_dim)
  

vec to string in c++

std::string vec_to_string(const std::vector<int>& vec)
{
	return std::accumulate(	std::next(vec.begin()), vec.end(), 
							std::to_string(vec.front()), 
							[](std::string acc, int b) { return std::move(acc) + ',' + std::to_string(b); }
                          );
};

std::cout << vec_to_string( {1,2,3,4} ) << std::endl;

Prompt-E3-E4

# About me
I'm a junior Python data/AI developer with intermediate level, working on a project for which  I need your 
pedagogical and technical guidance on.


# Project description
I want to build an SQL Agent interact with thanks to a chatbot UI, and leave feedbacks.
The users are French native speakers, asking hence questions in French and being answered in French.
The database contains also data in French language.


# Your task
I want you to act as a senior Python developer spec

Django collect static file excluding for ignored folder

# collectstatic command with ignore list

# run manually:
# run from terminal
# manage.py collectstatic -v 2 -i "admin/*" -i "katan/*" -i "rest_framework/*" -i "debug_toolbar/*"
# or from django shell:
# collectstatic -v 2 -i admin/* -i katan/* -i rest_framework/* -i debug_toolbar/*


#!/usr/bin/env python
import os
import sys
from django.core.management import execute_from_command_line

project_name = "Django_project_4"

# Patterns to ignore
IGNORE_PATTERNS = [
    "admin/*",

C# Currying and partial aplication #2

// pass in the parms required
var addThings = AddItems(true, 4, myList);

// Now it only requires the things
myThings.ForEach(addThings);


// The first set of parms are added to the currying func to return the final func
// item is projected out of the list it will be run in
private Action<Thing> AddItems(bool isTrue, int numberOfThings, List<Thing> list) =>
item => AddItemToList(isTrue, numberOfThings, list, item);



// The original method you want to curry the first three pars