text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
"""Dropdown component — a themed popup of options under a trigger.
The same pattern as Select's custom popup: a trigger Div (tabindex 0,
combobox role, chevron flip) with a glass panel of native ``<button>``
rows anchored below. Keyboard: Enter/Space opens, ArrowDown/Up moves
the highlighted row (clamped at the ends ... | HarcicYang/Neony | src/neony/application/elements/dropdown.py | .py | 4af0c4cbe3898787 | 7.15 | 1 |
"""Heading component — token-coloured, size-mapped."""
from __future__ import annotations
from typing import Literal
from neony.application.theme import stub
from neony.dom import H1 as _H1
from neony.dom import H2 as _H2
from neony.dom import H3 as _H3
from neony.dom import H4 as _H4
from neony.dom import H5 as _H5... | HarcicYang/Neony | src/neony/application/elements/heading.py | .py | b1d09d91d0505989 | 7.15 | 1 |
"""Unified icon value type for the component library.
An :class:`Icon` is either an image, an explicit custom text glyph, or a
private built-in font glyph supplied through :data:`neony.application.icons`.
Never pass a raw string to a component's ``icon`` parameter.
"""
from __future__ import annotations
from typing ... | HarcicYang/Neony | src/neony/application/elements/icon.py | .py | 78d1fde4bc6d7153 | 7.15 | 1 |
"""Image component — a themed frame around a single ``<img>``.
The component accepts an already-built URL string (``file_url(path)``,
``data_url(path)``, an ``https://`` URL, …) and never converts paths
itself — keeping that boundary in the caller's hands. A rounded,
overflow-hidden frame wraps the image so ``object-... | HarcicYang/Neony | src/neony/application/elements/image.py | .py | bc33bfca860ba6a1 | 7.15 | 1 |
"""Text input component — stateful, themed, source-aware events."""
from __future__ import annotations
from typing import Literal
from neony.application.theme import Theme, stub
from neony.dom import Border, DomEvent, Filter, Styles, Transition
from neony.dom import Input as _InputElem
from .base import Component, ... | HarcicYang/Neony | src/neony/application/elements/input.py | .py | 797032157c64247f | 7.15 | 1 |
"""List component — a scrollable, single-select data list.
A :class:`List` renders a flat column of :class:`ListItem` entries in a
scroll container. Exactly one entry is selected at a time; selection is
the listbox model — arrow keys move the selection directly (each move
fires ``change``), Home/End jump to the ends,... | HarcicYang/Neony | src/neony/application/elements/list.py | .py | d64d3e4c742958ca | 7.15 | 1 |
"""Progress component — a themed bar with an animated fill.
The fill is a child of a rounded, overflow-hidden track; its width
transitions over 0.3s on value changes, so updates glide instead of
snapping. ``indeterminate=True`` swaps in a sliding sweep animation
(the built-in ``neony-indeterminate`` keyframe, injecte... | HarcicYang/Neony | src/neony/application/elements/progress.py | .py | 642d7b69de839117 | 7.15 | 1 |
"""PromptDialog component — a modal that asks the user for a single line of text.
A thin specialisation of :class:`Dialog`: a themed scrim + centered glass
panel with a message, a single :class:`Input` field, and a confirm /
cancel button row. Confirm (the primary button or pressing ``Enter`` while
the field has focu... | HarcicYang/Neony | src/neony/application/elements/prompt_dialog.py | .py | d2652a338a4a5af9 | 7.15 | 1 |
"""Radio component — custom-styled native radio input.
A :class:`Radio` alone is a single toggle; a :class:`RadioGroup` owns
mutual exclusion (exactly one checked item) and dispatches a group
``change`` carrying the selected item's ``value``. The native
``name`` is generated by the group so screen readers group optio... | HarcicYang/Neony | src/neony/application/elements/radio.py | .py | b9ad1b3e6cf2108d | 7.15 | 1 |
"""RichText — a Python-driven inline rich-text editor.
The editor is a ``contenteditable`` region managed by the internal JS
engine (``window.neony.richText``), so the Python diff never rewrites its
DOM while the user is typing, composing IME text, or moving the caret.
Python holds the ordered segment model and syncs ... | HarcicYang/Neony | src/neony/application/elements/rich_text.py | .py | cb47fe2d4e098cd3 | 7.15 | 1 |
#!/usr/bin/python3
import sys
import argparse
from pathlib import Path
from html.parser import HTMLParser
from urllib.parse import urlsplit
class MetricsParser(HTMLParser):
def __init__(self):
super().__init__()
self.int_link_count = 0
self.ext_link_count = 0
self.fragment_count =... | canonical/valkey-operator | docs/.sphinx/metrics/build_metrics.py | .py | 7f30ea40a9fb917b | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Charmed k8s operator for Valkey."""
import logging
import ops
from data_platform_helpers.advanced_statuses.handler import StatusHandler
from common.custom_events import RestartWorkloadEvent, TopologyChangedCharmEvent... | canonical/valkey-operator | src/charm.py | .py | 7c669fb7faf66342 | 7.24 | 2 |
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Collection of custom events for the charm."""
import ops
class RestartWorkloadEvent(ops.EventBase):
"""Event for restarting the workload when certain events happen, e.g. IP change.
Args:
restart_valkey(bool): Whether to re... | canonical/valkey-operator | src/common/custom_events.py | .py | eef5133833ea735d | 7.24 | 2 |
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""K8sClient utility class to connect to the Kubernetes API server."""
import logging
from lightkube.core.client import Client
from lightkube.core.exceptions import ApiError
from lightkube.models.core_v1 import ServicePort, ServiceSpec
from li... | canonical/valkey-operator | src/common/k8s_client.py | .py | f135153df36b72ef | 7.24 | 2 |
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Collection of locks for cluster operations."""
import logging
import time
from abc import abstractmethod
from typing import TYPE_CHECKING, Protocol, override
from tenacity import Retrying, stop_after_attempt, wait_fixed
from common.client ... | canonical/valkey-operator | src/common/locks.py | .py | f3fcf75cdd5f9fe7 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Objects representing the cluster state of Valkey."""
import logging
import ops
from data_platform_helpers.advanced_statuses.components import StatusesState
from data_platform_helpers.advanced_statuses.protocol import ... | canonical/valkey-operator | src/core/cluster_state.py | .py | 8493772cba28f46b | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Collection of state objects for the Valkey relations, apps and units."""
import json
import logging
from collections.abc import MutableMapping
from typing import Any, final
import ops
from charmlibs.interfaces.tls_cer... | canonical/valkey-operator | src/core/models.py | .py | b0ed354e22e9d8cc | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Limited
# See LICENSE file for licensing details.
"""External clients related event handlers."""
import logging
import time
from typing import TYPE_CHECKING, cast
import ops
from charmlibs.interfaces.certificate_transfer import (
CertificatesAvailableEvent,
C... | canonical/valkey-operator | src/events/external_clients.py | .py | 89c0f214f6f86941 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Limited
# See LICENSE file for licensing details.
"""TLS related event handlers."""
import logging
from typing import TYPE_CHECKING
import ops
from charmlibs.interfaces.tls_certificates import (
CertificateAvailableEvent,
CertificateDeniedEvent,
Certifica... | canonical/valkey-operator | src/events/tls.py | .py | 6578318c97f99053 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Collection of global literals for the Valkey charm."""
from enum import StrEnum
CHARM = "valkey"
CONTAINER = "valkey"
SNAP_NAME = "charmed-valkey"
SNAP_REVISIONS = {"x86_64": 49, "aarch64": 48}
SNAP_SERVICE = "server... | canonical/valkey-operator | src/literals.py | .py | d389f2d70c56bd0c | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Manager for authentication and authorization."""
import hashlib
import logging
import secrets
import ssl
import string
from pathlib import Path
import ldap3
import ldap3.core.exceptions
from data_platform_helpers.adva... | canonical/valkey-operator | src/managers/auth.py | .py | e2bfb6aa2ab814b1 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Manager for all cluster related tasks."""
import logging
from collections.abc import Callable
from time import sleep
from data_platform_helpers.advanced_statuses.models import StatusObject
from data_platform_helpers.a... | canonical/valkey-operator | src/managers/cluster.py | .py | 3f21d48a209c6169 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Manager for all config related tasks."""
import logging
from pathlib import Path
from data_platform_helpers.advanced_statuses.models import StatusObject
from data_platform_helpers.advanced_statuses.protocol import Man... | canonical/valkey-operator | src/managers/config.py | .py | 9954f4744cfde57a | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Manager for handling external clients."""
import logging
from data_platform_helpers.advanced_statuses.models import StatusObject
from data_platform_helpers.advanced_statuses.protocol import ManagerStatusProtocol
from ... | canonical/valkey-operator | src/managers/external_clients.py | .py | 83d1696a0e1c3c09 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Manager for Cluster Topology."""
import logging
import os
import signal
import subprocess
from pathlib import Path
from sys import version_info
from core.base_workload import WorkloadBase
from core.cluster_state impor... | canonical/valkey-operator | src/managers/topology.py | .py | 6bbd54a880cbc636 | 7.24 | 2 |
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Topology observer class for checking changes in Primary/Replica topology."""
import logging
import signal
import subprocess
import sys
import time
from valkey.sentinel import MasterNotFoundError, Sentinel
from literals import PRIMARY_NAME,... | canonical/valkey-operator | src/scripts/topology_observer.py | .py | 9dd2dad922cbb9d4 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Implementation of WorkloadBase for running Valkey on K8s."""
import collections
import logging
import signal
import threading
from typing import IO, BinaryIO, override
import ops
from charmlibs import pathops
from ops... | canonical/valkey-operator | src/workload_k8s.py | .py | 9328377c19663676 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Implementation of WorkloadBase for running Valkey on VMs."""
import collections
import logging
import os
import platform
import shutil
import subprocess
import threading
import time
from typing import BinaryIO, overrid... | canonical/valkey-operator | src/workload_vm.py | .py | 261d15751b081971 | 7.24 | 2 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Fixtures for S3 backup integration tests, backed by MicroCeph.
MicroCeph's RGW is fronted with a self-signed TLS certificate generated here,
so the suite exercises the charm's full S3-over-TLS path (CA-chain
distributi... | canonical/valkey-operator | tests/integration/backup/conftest.py | .py | 1599b6aad278a45f | 7.74 | 2 |
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""ValkeyClient utility class to connect to valkey servers."""
import json
import logging
import os
from glide import (
AdvancedGlideClientConfiguration,
GlideClient,
GlideClientConfiguration,
NodeAddress,
ServerCredentials... | canonical/valkey-operator | tests/integration/clients/requirer-charm/src/client.py | .py | 5482a2573fe4f469 | 7.74 | 2 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Continuous writes daemon for Valkey integration testing.
Spawned by the requirer charm's start-continuous-writes action. Reads
connection config from a JSON file, writes incrementing integers to a
Valkey list, and trac... | canonical/valkey-operator | tests/integration/clients/requirer-charm/src/continuous_writes.py | .py | 49650635adede8d2 | 7.74 | 2 |
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Helpers for the continuous-writes daemon used by the requirer charm."""
import enum
import logging
import os
import signal
import time
from pathlib import Path
from continuous_writes import KEY as CW_KEY
from continuous_writes import Daemon... | canonical/valkey-operator | tests/integration/clients/requirer-charm/src/cw_helpers.py | .py | 4320a4b3e5638d5e | 7.74 | 2 |
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Serialization/deserialization helpers for GlideClientConfiguration objects.
Converts a GlideClientConfiguration (and its nested objects) to/from a JSON
string so it can be passed as a Juju action parameter.
Bytes fields are base64-encoded; ... | canonical/valkey-operator | tests/integration/clients/requirer-charm/src/glide_helpers.py | .py | cb05fbf08090191e | 7.74 | 2 |
"""The ``/dexport`` slash command, rendered for each coding agent.
One prompt (:data:`PROMPT`), several wrappers: every agent keeps its commands
in a different place and spells "the rest of what the user typed" differently.
:func:`render` produces the file body for a target, :func:`target_path` says
where it goes, and... | Patruxs/dexport | src/agents.py | .py | 0279bfc786107603 | 7 | 0 |
"""The ``install-agent`` command: drop a ``/dexport`` slash command into
whatever coding agents are installed."""
from __future__ import annotations
from pathlib import Path
from typing import Annotated
import typer
from .. import agents
from .common import console, fail
commands = typer.Typer()
_KEYS = ", ".join... | Patruxs/dexport | src/cli/agent.py | .py | f2116ce3ebc37d50 | 7 | 0 |
"""The Typer application and its root callback (global connection options)."""
from __future__ import annotations
import typer
from .. import __version__
from ..config import DEFAULT_CDP_PORT
from .common import ConnectionOptions
app = typer.Typer(
add_completion=False,
no_args_is_help=True,
help=(
... | Patruxs/dexport | src/cli/app.py | .py | 64ab4abe85f41496 | 7 | 0 |
"""Read-only verbs: whoami / guilds / channels / read / export."""
from __future__ import annotations
from typing import Annotated
import typer
from ..messages import fetch_history
from ..render import (
EXPORT_EXTENSIONS,
export_to_file,
get_exporter,
render_terminal,
summarize_author,
)
from .... | Patruxs/dexport | src/cli/read.py | .py | d3e2110e1e9cd68b | 7 | 0 |
"""The facade that wires the whole pipeline together.
``Dexport.acquire`` runs the full pipeline (see docs/ARCHITECTURE.md) — launcher -> attach ->
header snapshot -> api core + rate limiter + resolver — and hands back a ready
object. Use it as a context manager so the CDP session is always released and
the resolver c... | Patruxs/dexport | src/client.py | .py | c06c0291af8f26e4 | 7 | 0 |
"""Exception hierarchy for dexport.
Every failure that is *expected* (a step in the pipeline that can go wrong for
an understandable reason) is raised as a :class:`DexportError` subclass so the
CLI can present a clean message instead of a traceback.
"""
from __future__ import annotations
class DexportError(Exceptio... | Patruxs/dexport | src/errors.py | .py | 9b45e7961ef9294e | 7 | 0 |
"""Header snapshot — the trick that makes requests look like the client.
We watch the Discord page's outgoing requests and wait for the first
``/api/v9/*`` request that carries an ``Authorization`` header. We snapshot the
*whole* header cluster (not just the token) so that ``X-Super-Properties``,
``X-Discord-Locale``,... | Patruxs/dexport | src/headers.py | .py | b0e01555cc47fc59 | 7 | 0 |
"""Session lifecycle: make sure Discord is running with a live CDP port.
Strategy (see docs/ARCHITECTURE.md):
1. Is the CDP port alive? (``GET /json/version`` returns 200) -> use it.
2. If not, find the Discord binary for this OS (:mod:`.discovery`) and
(re)launch it with ``--remote-debugging-port=<port>`` (:mod:`... | Patruxs/dexport | src/launcher/__init__.py | .py | 195ce5a48d634c29 | 7 | 0 |
"""Find the Discord desktop binary and build its launch command, per OS.
Everything here is pure (no processes spawned) apart from the optional
``flatpak info`` probe on Linux, so it can be unit-tested with a fake home
directory. To support a new install location, add it to the matching
``_*_candidates`` function.
"""... | Patruxs/dexport | src/launcher/discovery.py | .py | 2da4764eac0e9c8f | 7 | 0 |
"""Start, find and stop the Discord desktop process.
On Unix we signal specific PIDs rather than using ``pkill -f`` with a
substring, which would match — and kill — unrelated processes whose command
line merely contains the pattern.
"""
from __future__ import annotations
import os
import platform
import signal
impor... | Patruxs/dexport | src/launcher/process.py | .py | 968472b9ddd47d95 | 7 | 0 |
"""Lightweight shapes for the Discord objects dexport touches.
Discord's JSON is passed around as plain dicts (``Message`` etc. are aliases,
not classes) so nothing here constrains what the API may return. The
``TypedDict``s describe what dexport itself *stores* in the resolver cache.
"""
from __future__ import annot... | Patruxs/dexport | src/models.py | .py | 5f19aa3e7b46fb05 | 7 | 0 |
"""Small pure helpers shared across modules.
Kept dependency-free (stdlib only) so it is trivially unit-testable and cheap
to import.
"""
from __future__ import annotations
import re
import unicodedata
_WS_RE = re.compile(r"\s+")
def strip_diacritics(text: str) -> str:
"""Remove combining marks, turning ``"lư... | Patruxs/dexport | src/util.py | .py | 13ead199cab2f1dc | 7 | 0 |
"""Developer ambiguity decisions (closes the R4.2 loop).
A decisions file maps claim IDs to the branch chosen by a human:
{"C2": "C2.b"}
Applying decisions converts an ambiguous claim into one resolved claim whose
text records both the decision and who made it. Undecided claims stay
ambiguous and keep generating p... | viki22uied/intent-divergence-engine | src/intent_ide/decisions.py | .py | 51f21b8748f44d79 | 7 | 0 |
import pytest
from intent_ide.safety import validate_generated_code
def assert_blocked(code: str):
safe, reason = validate_generated_code(code)
assert not safe, f"expected blocked but was safe: {reason}"
assert "blocked" in reason.lower()
def assert_safe(code: str):
safe, reason = validate_generate... | viki22uied/intent-divergence-engine | tests/test_safety.py | .py | 44fdbebc4f50d085 | 7.5 | 0 |
import logging
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Final
import anyio
from asyncpg import Pool, PostgresError, Record, create_pool
from asyncpg.pool import PoolConnectionProxy
from app.const... | finki-hub/chat-bot | api/app/data/connection.py | .py | 2335c112ad31d222 | 7.15 | 1 |
from dataclasses import dataclass
from typing import Final, assert_never
from uuid import UUID
from asyncpg import Record
from asyncpg.pool import PoolConnectionProxy
from app.data.connection import Database
from app.data.embedding_lifecycle_sql import (
COUNT_SQL,
DIRTY_SELECT_SQL,
PERSIST_SQL,
REBUI... | finki-hub/chat-bot | api/app/data/embedding_lifecycle.py | .py | c64ae230857e65da | 7.15 | 1 |
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Literal
from app.llms.models import (
BGE_M3_EMBEDDING_SPEC_VERSION,
HALFVEC_EMBEDDING_MODELS,
MODEL_EMBEDDINGS_COLUMNS,
Model,
is_bge_m3_lifecycle_model,
)
type SqlTableAlias = Literal["c"]
@dataclass(froz... | finki-hub/chat-bot | api/app/data/embedding_sql.py | .py | ae823449d6ae9202 | 7.15 | 1 |
import logging
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from typing import Protocol
from uuid import UUID
import anyio
from asyncpg import InterfaceError, PostgresError, connect
from app.data.connection import Database
from app.data.embedding_lifecycle_sql import Embedd... | finki-hub/chat-bot | api/app/embedding_worker.py | .py | 7be3f32014c09c14 | 7.15 | 1 |
import logging
from collections.abc import Generator
from fastapi.responses import StreamingResponse
from langchain.agents import create_agent
from langchain_anthropic import ChatAnthropic
from langchain_core.messages import BaseMessage, HumanMessage, SystemMessage
from pydantic import SecretStr
from app.llms.agents ... | finki-hub/chat-bot | api/app/llms/anthropic.py | .py | e08b6e0b334fcbd8 | 7.15 | 1 |
"""Common configuration models for observability integrations."""
from dataclasses import dataclass
import os
import json
LOCAL_METRICS_URL: str = "http://localhost:4318/v1/metrics"
DEFAULT_SERVICE_NAME: str = "observability"
ENV_VAR_TGEDR_OBSERVABILITY_SERVICE: str = "TGEDR_OBSERVABILITY_SERVICE"
ENV_VAR_TGEDR_OBSER... | jtviegas/observability | src/tgedr_observability/commons.py | .py | 16e299b8e6fd191e | 7 | 0 |
"""OpenTelemetry logging setup and singleton manager for application logs."""
import logging
from pathlib import Path
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import (
BatchLogRecordProcesso... | jtviegas/observability | src/tgedr_observability/logs.py | .py | 6b2c8425bae55d4d | 7 | 0 |
"""Metrics manager and helpers for OpenTelemetry instrumentation."""
from pathlib import Path
from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.metrics import Instrument
from opentelemetry.sdk.metrics... | jtviegas/observability | src/tgedr_observability/metrics.py | .py | 8e20e1c676e5fc96 | 7 | 0 |
"""Helpers to read exported OpenTelemetry metrics files and plot them.
The file exporter configured by `Metrics` writes `ConsoleMetricExporter`
output: one JSON document per flush, appended to the file. A single file can
therefore contain several concatenated JSON documents. These helpers parse that
format and render ... | jtviegas/observability | src/tgedr_observability/plot.py | .py | eb19640f3c6bae1f | 7 | 0 |
"""test configurations."""
from pathlib import Path
import sys
import tempfile
from typing import Generator
import pytest
sys.path.insert(0, str(Path(__file__).parent.parent.joinpath("src").absolute())) # isort:skip
@pytest.fixture(scope="session")
def resources_folder() -> str:
"""Provides the location of te... | jtviegas/observability | test/conftest.py | .py | 69fdacdcdb1bbb21 | 7.5 | 0 |
"""
transformer/attention.py — 注意力机制(Attention Mechanism)
注意力机制是 Transformer 的核心。它让模型在处理序列中的每个位置时,
能够"关注"序列中所有其他位置的信息,并根据相关性分配不同权重。
本模块包含两个核心组件:
1. scaled_dot_product_attention — 基础的缩放点积注意力函数
2. MultiHeadAttention — 多头注意力机制(Multi-Head Attention)
== 缩放点积注意力的数学原理 ==
Attention(Q, K, V) = softmax(Q · K^T / sqrt(d... | MIKE-He-525/transformer-from-scratch | transformer/attention.py | .py | 4aced9a8427e3c63 | 7 | 0 |
"""
transformer/embedding.py — 词嵌入(Token Embedding)与位置编码(Positional Encoding)
在 Transformer 中,输入由两个部分组成:
1. Token Embedding:将离散的 token ID 映射为连续的高维向量,使语义相近
的 token 在向量空间中也更接近。
2. Positional Encoding:由于 Transformer 不含递归和卷积,模型本身无法感知
token 在序列中的位置。位置编码将位置信息注入到嵌入向量中。
本模块实现了两种核心组件:
- Embedding:可学习的词向量表,与标准的... | MIKE-He-525/transformer-from-scratch | transformer/embedding.py | .py | 03b9c325686f137d | 7 | 0 |
"""
transformer/feed_forward.py — 逐位置前馈神经网络(Position-wise Feed-Forward Network)
前馈网络(FFN)是 Transformer 中每个编码器/解码器层内的另一个核心组件。
它紧跟在多头注意力层之后,对序列中每个位置的向量独立地进行非线性变换。
架构:
FFN(x) = ReLU(x · W₁ + b₁) · W₂ + b₂
- W₁: (d_model, hidden_dim) 第一层线性变换,升维到 hidden_dim
- b₁: (hidden_dim,) 第一层偏置
- ReLU: 激活函数,引入非线性
... | MIKE-He-525/transformer-from-scratch | transformer/feed_forward.py | .py | fc834b6daad1f803 | 7 | 0 |
"""
transformer/utils.py — Mask 工具函数
在 Transformer 中,mask 用于控制注意力机制的可见范围。本模块提供以下三种 mask:
1. Padding Mask(填充掩码)
- 目的:忽略序列中填充(padding)位置的 token,防止模型关注无效字符。
- 场景:源序列(encoder)和交叉注意力(decoder cross-attention)中。
2. Causal Mask(因果掩码 / 下三角掩码)
- 目的:确保解码器在预测第 t 个位置时,只能看到前 t-1 个位置,不能"偷看"未来。
- 场景:解码器自注意力(decoder self... | MIKE-He-525/transformer-from-scratch | transformer/utils.py | .py | 8f66eccb654d50b3 | 7 | 0 |
"""
fetch_ign_only.py — ingesta histórica completa solo desde IGN.
Uso: python scripts/fetch_ign_only.py
Diseñado para la primera carga desde cero.
"""
from __future__ import annotations
import json, logging, sys
from pathlib import Path
from calendar import monthrange
from datetime import datetime, timezone
sys.path... | miqueas-gg/sismocan | scripts/fetch_ign_only.py | .py | 1da5f500b8a1abf1 | 7.15 | 1 |
import asyncio
import json
import logging
import threading
import time
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional
from collections import defaultdict
from dataclasses import dataclass, asdict
from core.config import Config
logger = logging.getLogger(__name__)
@data... | Abolfazlmo15/telegram_simple_ai_bot | core/analytics/analytics_engine.py | .py | 1a3183e9798befd6 | 7 | 0 |
"""Document analysis engine for PDF and DOCX files.
Extracts text, handles captions, and uses AI models for Q&A/summarization.
"""
import logging
import io
from typing import Optional, Tuple, Dict, Any
from core.config import Config
from core.managers.user_data_manager import UserDataManager
logger = logging.getLogge... | Abolfazlmo15/telegram_simple_ai_bot | core/engines/analysis/document_engine.py | .py | aa1a06f4e644c7c9 | 7 | 0 |
"""
Unified cache manager with TTL support for various data types.
Provides in-memory caching with expiration, LRU eviction, and persistence support.
"""
import logging
import time
import json
import asyncio
from typing import Dict, Any, Optional, List, Tuple, Callable
from dataclasses import dataclass, field
from date... | Abolfazlmo15/telegram_simple_ai_bot | core/managers/cache_manager.py | .py | 3936be7f3d87dd69 | 7 | 0 |
"""
Health checker for monitoring model availability and API endpoints.
Runs background checks on configured models and providers to proactively
skip unhealthy endpoints before they cause request failures.
"""
import logging
import threading
import time
import random
import httpx
from typing import Dict, List, Optional... | Abolfazlmo15/telegram_simple_ai_bot | core/managers/health_checker.py | .py | 535c4be75c1249c9 | 7 | 0 |
"""Dynamic manager for OpenRouter image generation models."""
import logging
import threading
import time
import httpx
from typing import List, Optional
from core.config import Config
logger = logging.getLogger(__name__)
class ImageModelManager:
"""
Manages available image generation models from OpenRouter.
... | Abolfazlmo15/telegram_simple_ai_bot | core/managers/image_model_manager.py | .py | 4c6bd529be449ba0 | 7 | 0 |
"""
Structured memory management for users.
Handles short-term, long-term memory, summarization, and semantic retrieval.
"""
import json
import logging
import hashlib
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, List, Optional, Any, Tuple
from collections import defaultdict... | Abolfazlmo15/telegram_simple_ai_bot | core/managers/memory_manager.py | .py | a44144cdceae9f22 | 7 | 0 |
"""
Simple in-memory rate limiter with sliding window per user.
"""
import time
import asyncio
import logging
from collections import defaultdict
from typing import Tuple
logger = logging.getLogger(__name__)
class RateLimiter:
"""Simple in-memory rate limiter with sliding window per user."""
def __init__(se... | Abolfazlmo15/telegram_simple_ai_bot | core/managers/rate_limiter.py | .py | 7087cf12f6698215 | 7 | 0 |
"""
Topic detection and tracking for conversations.
"""
import logging
import re
from typing import Dict, List, Optional, Set, Any, Tuple
from collections import defaultdict
from datetime import datetime, timedelta
from pathlib import Path
from core.config import Config
logger = logging.getLogger(__name__)
class Top... | Abolfazlmo15/telegram_simple_ai_bot | core/managers/topic_manager.py | .py | 4165b0a70dcd4022 | 7 | 0 |
"""Dynamic manager for voice/speech-to-text models."""
import logging
import threading
import time
import httpx
from typing import List, Optional
from core.config import Config
logger = logging.getLogger(__name__)
class VoiceModelManager:
"""
Manages available speech-to-text models from OpenRouter.
Auto-... | Abolfazlmo15/telegram_simple_ai_bot | core/managers/voice_model_manager.py | .py | 4f1bd2655ff81df2 | 7 | 0 |
"""Image processing utilities for vision engine."""
import logging
import io
import base64
from typing import Union, Optional
from PIL import Image
import asyncio
logger = logging.getLogger(__name__)
class ImageProcessor:
"""
Handles image preprocessing for vision models.
Resizes, optimizes, and encodes ... | Abolfazlmo15/telegram_simple_ai_bot | core/utils/image_processor.py | .py | 01f499256b9d53f8 | 7 | 0 |
from dataclasses import dataclass
from typing import Dict, List, Optional
from enum import Enum
class PromptCategory(Enum):
"""Categories for different types of prompts"""
TECHNICAL_CODING = "technical_coding"
CREATIVE_WRITING = "creative_writing"
DATA_ANALYSIS = "data_analysis"
EDUCATIONAL_TUTOR ... | Abolfazlmo15/telegram_simple_ai_bot | core/utils/prompt_library.py | .py | ace45d5de28cfb96 | 7 | 0 |
from dataclasses import dataclass
from typing import Dict, List, Optional
@dataclass
class EmojiSet:
"""Emoji mappings for different response types"""
success: str = "✅"
error: str = "❌"
warning: str = "⚠️"
info: str = "ℹ️"
code: str = "💻"
tip: str = "💡"
question: str = "❓"
check... | Abolfazlmo15/telegram_simple_ai_bot | core/utils/response_config.py | .py | acd9f7f504abfe5c | 7 | 0 |
import logging
import asyncio
from typing import Optional, Dict, Tuple, Any
import httpx
from telegram import Update
from telegram.ext import ContextTypes
from core.config import Config
from core.utils.network import retry_async
from core.utils.response_formatter import ResponseFormatter
from core.managers.memory_manag... | Abolfazlmo15/telegram_simple_ai_bot | handlers/base_handler.py | .py | 90bfde909e2f387b | 7 | 0 |
import asyncio
import logging
from telegram import Update, CallbackQuery
from telegram.ext import ContextTypes
logger = logging.getLogger(__name__)
class CancelHandler:
"""Handles the cancel button callback."""
async def cancel_task(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
... | Abolfazlmo15/telegram_simple_ai_bot | handlers/commands/cancel_handler.py | .py | 6905f4964df4c2a5 | 7 | 0 |
"""Base class for all detectors."""
from abc import ABC, abstractmethod
from typing import Dict, Any, Optional
class BaseDetector(ABC):
"""Abstract base class for detectors."""
def __init__(self):
self.name = self.__class__.__name__
@abstractmethod
async def detect(self, text: str, context: ... | Abolfazlmo15/telegram_simple_ai_bot | prompt_engineering/base/base_detector.py | .py | f1e07f8bdee32d99 | 7 | 0 |
"""
Load và render các system prompt từ file YAML trong thư mục prompts/.
Cách dùng:
from agents.prompts.prompts_loader import get_system_prompt
prompt = get_system_prompt(
"planner",
topic="MCP cho AI Engineer",
article_type="blog",
target_audience="AI Engineer",
tone... | huynhnguyendev/multi_agent_writer | agents/prompts/prompts_loader.py | .py | 209be94423505097 | 7.15 | 1 |
"""
Schema cho kết quả đánh giá của node Evaluator.
Evaluator không chỉ chấm một điểm duy nhất, mà chia thành
nhiều tiêu chí:
Factuality (Tính xác thực)
Completeness (Mức độ đầy đủ)
Coherence (Tính logic/mạch lạc)
Writing Quality (Chất lượng văn phong)
... | huynhnguyendev/multi_agent_writer | agents/schemas/evaluation.py | .py | 8de67334b7a2df01 | 7.15 | 1 |
"""
Schema cho việc tìm kiếm và gắn ảnh vào bài viết.
Worker không trực tiếp nhúng image vào article.
Worker chỉ đề xuất: image_queries
Sau đó Image layer / Image subgraph sẽ:
query → Wikimedia (MCP) → ImageCandidate → ImageSpec
Cách này giúp tách:
Content generation và Image retrieval
khỏi nhau.
"""
from... | huynhnguyendev/multi_agent_writer | agents/schemas/image.py | .py | 7fd2cab921bb0852 | 7.15 | 1 |
"""
Schema dùng để chuẩn hóa dữ liệu trả về từ Tavily / MCP research tool.
KHÔNG nên đưa raw response của Tavily thẳng vào State.
Thay vào đó normalize thành schema riêng của project.
Điều này giúp sau này đổi:
Tavily → MCP Search → Google Search
mà Worker không cần biết implementation bên dưới.
"""
from pydanti... | huynhnguyendev/multi_agent_writer | agents/schemas/research.py | .py | 0d20f3990fd0b95c | 7.15 | 1 |
"""
Sign-flip symmetry analysis.
For each model with signflip data, compute:
Δ+ = baseline - sweep_best (suppression by +ΔW at best layer)
Δ− = signflip_at_best_layer - baseline (amplification by −ΔW at best layer)
symmetry_score = |Δ+ − Δ−| / max(|Δ+|, |Δ−|) → 0=symmetric, 1=asymmetric
Output: results/anal... | GDM1nu/EMNLP-2026-LEVEE | scripts/analyze_signflip_symmetry.py | .py | 72a467bf342bede0 | 7 | 0 |
"""
Cosine similarity visualization — 3 figures.
Plot A: 9-model N×N heatmap grid
Plot B: Distance-decay overlay (all models, family-colored)
Plot C: Ref-direction cosine 3×3 grid
"""
import sys
from pathlib import Path
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import ... | GDM1nu/EMNLP-2026-LEVEE | scripts/plot_cosine.py | .py | 3efb2be1292ac305 | 7 | 0 |
#!/usr/bin/env python
"""
C1 — Stratified multinomial bootstrap CIs for BBQ ambig bias_score (GPU-free).
Per-item predictions were not saved, but every result JSON stores per-category
ambig counts (n_biased / n_anti_biased / n_unknown / total). Each ambig item
falls into exactly one outcome class, so the empirical per... | GDM1nu/EMNLP-2026-LEVEE | scripts/rebuttal/bootstrap_ci.py | .py | 12e8e2e3b5fa1b93 | 7 | 0 |
"""
Task-vector-style cross-model ΔW alignment.
Two complementary metrics:
1. Energy profile Spearman correlation
Per model: layer-wise ||ΔW||²_F summed across modules, normalized to sum=1.
Correlate profiles between model pairs at matched normalized depth.
≥3B models should cluster (high r); ≤1.5B should be... | GDM1nu/EMNLP-2026-LEVEE | src/analysis/compute_crossmodel_alignment.py | .py | fb23ba028dc00c37 | 7 | 0 |
#!/usr/bin/env python3
"""
DARE Sparsity Analysis — ΔW magnitude distribution per layer.
Based on: Yu et al. (2024) "Language Models are Super Mario: Absorbing Abilities
from pathlib import Path
from Homologous Models as a Free Lunch" (ICML 2024).
DARE showed that most ΔW parameters are near-zero and can be dropped w... | GDM1nu/EMNLP-2026-LEVEE | src/analysis/compute_dare_sparsity.py | .py | 7c6926317a07d441 | 7 | 0 |
#!/usr/bin/env python3
"""
ΔW Norm vs BBQ/MMLU Dissociation Analysis.
Hypothesis: the third with highest ΔW Frobenius norm predicts BBQ bias sensitivity
but NOT MMLU capability sensitivity — i.e., ΔW magnitude concentration is bias-specific.
For each model:
- dw_norm thirds: which third has highest mean_frob_norm?
... | GDM1nu/EMNLP-2026-LEVEE | src/analysis/compute_norm_mmlu_dissociation.py | .py | ba0b529ee988fd39 | 7 | 0 |
#!/usr/bin/env python3
"""
BBQ bias probing–bias score correlation analysis.
Correlates per-layer linear probe accuracy (correct_answer_3class)
with per-layer ΔW injection bias score (ambig bias_score from sweep_thirds).
Limitation: only llama3_8b has probing results; bias_binary label mode
is not yet implemented so ... | GDM1nu/EMNLP-2026-LEVEE | src/analysis/compute_probe_bias_corr.py | .py | ae7a2e890be402c5 | 7 | 0 |
"""
LoRA-style rank-k capture analysis.
For each model × layer: what fraction of ||ΔW||²_F is captured by top-k singular vectors?
Low k → high concentration → bias signal is low-rank and transferable.
Output: results/analysis/rankk_capture.json
"""
from __future__ import annotations
import json
import re
from pathl... | GDM1nu/EMNLP-2026-LEVEE | src/analysis/compute_rankk_capture.py | .py | 73cd80e907ec062b | 7 | 0 |
#!/usr/bin/env python3
"""Assemble test report directories and log files into a timestamped output.
Collects report directories and optional log files into a single timestamped
directory suitable for deployment to GitHub Pages.
Usage:
python3 assemble-reports.py \
--report-name e-2-e-playwright \
... | cuioss/cuioss-organization | .github/actions/assemble-test-reports/assemble-reports.py | .py | 9896057709870ca5 | 7.5 | 0 |
#!/usr/bin/env python3
"""Generate an overview index.html for deployed test reports.
Scans a target directory for timestamped report subdirectories, groups them
by report name, and generates an HTML overview page sorted newest-first.
Usage:
python3 generate-overview-index.py --target-dir <path> --title <name>
Ti... | cuioss/cuioss-organization | .github/actions/assemble-test-reports/generate-overview-index.py | .py | c51fc94fd82418e2 | 7.5 | 0 |
#!/usr/bin/env python3
"""Read project.yml and output all fields in GITHUB_OUTPUT format.
This script uses a field registry pattern for easy expandability.
Adding a new field requires only one line in FIELD_REGISTRY.
Usage:
python3 read-config.py --config .github/project.yml
Output:
Writes key=value pairs to... | cuioss/cuioss-organization | .github/actions/read-project-config/read-config.py | .py | a6dfd1a4b6e98963 | 7 | 0 |
#!/usr/bin/env python3
"""Build script with module filtering support.
Provides canonical commands (compile, test, quality-gate, verify)
with optional module filtering.
Usage:
./pw build compile # All production sources
./pw build compile workflow # Single module (workflow scri... | cuioss/cuioss-organization | build.py | .py | 8dee56f746ee007d | 7 | 0 |
#!/usr/bin/env python3
"""Verify and fix organization integration for cuioss repositories.
Identifies and removes:
- Repo-level secrets that should be org-level
- Duplicate community health files (inherited from cuioss/.github)
Requires: gh cli (https://cli.github.com/)
Usage:
./verify-org-integration.py --repo ... | cuioss/cuioss-organization | repo-settings/verify-org-integration.py | .py | 44a6cbbc0d2d83ee | 7 | 0 |
"""Shared test fixtures for cuioss-organization Python scripts."""
import subprocess
import sys
from collections import namedtuple
from pathlib import Path
import pytest
PROJECT_ROOT = Path(__file__).parent.parent
ScriptResult = namedtuple("ScriptResult", ["returncode", "stdout", "stderr"])
def run_script(script_p... | cuioss/cuioss-organization | test/conftest.py | .py | 475e3e9fc6a66b52 | 7.5 | 0 |
"""Regression tests for the PR-Agent empty-review guard's trigger scope.
The guard in `.github/workflows/reusable-pr-agent-review.yml` fails the job when the
reviewer produced no structured output. That assertion is only sound on runs the runner
is contractually obliged to review, so the guard's `if:` mirrors PR-Agent... | cuioss/cuioss-organization | test/workflow/test_pr_agent_review_guard.py | .py | 5aa4cc2ffa7119ac | 7.5 | 0 |
"""Every reusable workflow must fit inside the permissions its caller example grants.
A called workflow can only RESTRICT the caller's GITHUB_TOKEN, never escalate it.
The moment a job requests a permission the caller does not grant, GitHub rejects
the run with a startup failure before any job executes -- in the consu... | cuioss/cuioss-organization | test/workflow/test_reusable_caller_contract.py | .py | ac54912f53166709 | 7.5 | 0 |
"""Tests for update-consumer-repo.py argument validation and auto-merge config."""
import importlib.util
import sys
from pathlib import Path
# Add parent to path to access conftest
sys.path.insert(0, str(Path(__file__).parent.parent))
from conftest import PROJECT_ROOT, run_script
SCRIPT_PATH = PROJECT_ROOT / "workfl... | cuioss/cuioss-organization | test/workflow/test_update_consumer_repo.py | .py | 578c23cda97bd5ed | 7.5 | 0 |
#!/usr/bin/env python3
"""
Verify that reusable workflows execute only immutably-pinned actions.
A reusable workflow is consumed by pinning it at an immutable SHA. If that
commit's own ``uses:`` refs point at a mutable ref (a tag such as ``@v0.12.0``,
or ``@main``), moving that tag silently changes the code every cons... | cuioss/cuioss-organization | workflow-scripts/check-internal-pinning.py | .py | 5c58682094d9024d | 7 | 0 |
#!/usr/bin/env python3
"""Poll Maven Central repository until an artifact version is available.
Waits for a specific artifact to appear on Maven Central, useful after
a release to ensure the artifact is available before triggering consumers.
Uses the repo1.maven.org repository directly (HEAD request on the POM)
inste... | cuioss/cuioss-organization | workflow-scripts/check-maven-central.py | .py | 9e722fe16a798567 | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.