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
"""Tail-calibration audit: do extreme forecasts resolve as often as they claim? Issue #10 alleges blind aggregation is overconfident at the tails — but its evidence is distance to a teacher on 4 selected cases. This audits the same claim against RESOLVED outcomes only (the honest metric) on any run_bench results whose...
edisonymy/forecast-scaffold
bench/tail_audit.py
.py
0cc5831e4769a5d4
7
0
"""Optional AskNews research-source integration for the RESEARCH run (ships DARK). AskNews was the first-choice research provider of winning Metaculus bots, and research-source breadth is a measured winner correlate. This module lets the tournament research run start from a small, dated, linked set of news articles fo...
edisonymy/forecast-scaffold
bot/asknews.py
.py
4dbb03797eefe5ae
7
0
"""Read the community prediction on the questions where Metaculus's API exposes it. Metaculus's API omits aggregation data (the Community Prediction) on almost every question. Per the docs, CP ships on only ``~50`` curated questions; separately, bot tournaments (Bot Testing Area etc.) expose CP on their own questions....
edisonymy/forecast-scaffold
bot/crowd.py
.py
ef79d40c8d80c8da
7
0
"""Session-wide test guards. The tournament research run now OPTIONALLY starts from AskNews articles (bot/asknews.py), appended inside forecast_question. On a dev machine where the operator's real keyfile (~/.asknews/key[.txt]) exists, that would make LIVE API calls inside every forecast_question test. So default AskN...
edisonymy/forecast-scaffold
tests/conftest.py
.py
2b66f6b81f17f5c4
7.5
0
""" Experiment Matrix Logger and Serializer Module. Captures system environment metadata, execution metrics, and optimization configurations. Exports reproducible results to local JSON and CSV files. """ from typing import Dict, Any, List, Tuple import json import csv import sys import os import platform import time i...
FaizaQiyyum/PyTorch-Model-Execution-and-Hardware-Optimization-Analyzer
analyzer/experiment_matrix.py
.py
e2a2d23b936934d3
7
0
""" Computational Graph Extraction and Analysis Module using torch.fx and NetworkX. Provides symbolic tracer node extraction, dependency topological order, and Matplotlib graph visualization. """ from typing import Dict, Any, List, Tuple import torch import torch.nn as nn import torch.fx as fx import networkx as nx im...
FaizaQiyyum/PyTorch-Model-Execution-and-Hardware-Optimization-Analyzer
analyzer/graph_analyzer.py
.py
763922d0cf14498e
7
0
""" Model Inspector Module for PyTorch Structure Analysis. Provides exact parameter counts, calculated parameter memory sizes, and layer shape tracking. """ from typing import Dict, Any, List, Tuple import torch import torch.nn as nn def count_parameters(model: nn.Module) -> Tuple[int, int]: """ Calculates to...
FaizaQiyyum/PyTorch-Model-Execution-and-Hardware-Optimization-Analyzer
analyzer/model_inspector.py
.py
d63248021471691b
7.5
0
""" Model Loader and Synthetic Tensor Generator for PyTorch Execution Analyzer. """ from typing import Tuple, Dict, Any import torch import torch.nn as nn from models.cnn import SimpleCNN from models.mlp import DeepMLP from models.transformer import MiniTransformer from models.resnet18 import get_resnet18 from analyz...
FaizaQiyyum/PyTorch-Model-Execution-and-Hardware-Optimization-Analyzer
analyzer/model_loader.py
.py
3210c707d9f8b226
7
0
""" Optimizer Module for PyTorch Optimization Experiments. Evaluates model.eval(), torch.no_grad(), torch.inference_mode(), batch size scaling, mixed precision (torch.autocast), and torch.compile. """ from typing import Dict, Any, List, Tuple import time import statistics import torch import torch.nn as nn from analy...
FaizaQiyyum/PyTorch-Model-Execution-and-Hardware-Optimization-Analyzer
analyzer/optimizer.py
.py
d8a96c3a414f7ced
7
0
""" Input Validation and Security Bounds Module for PyTorch Execution Analyzer. Enforces strict input bounds, type checking, model registry safety, and path sanitization. Prevents arbitrary execution, path traversal, and resource exhaustion attacks. """ from typing import Tuple, List, Dict, Any ALLOWED_MODELS = ["Si...
FaizaQiyyum/PyTorch-Model-Execution-and-Hardware-Optimization-Analyzer
analyzer/validation.py
.py
97545b03442f6f8c
7
0
""" SimpleCNN Architecture for PyTorch Model Execution Profiling. """ import torch import torch.nn as nn class SimpleCNN(nn.Module): """ A 4-layer Convolutional Neural Network with BatchNorm, ReLU, MaxPool, and Linear layers. Designed for vision workload profiling and compute/activation graph analysis. ...
FaizaQiyyum/PyTorch-Model-Execution-and-Hardware-Optimization-Analyzer
models/cnn.py
.py
1b9ddd34b4327007
7
0
""" DeepMLP Architecture for PyTorch Model Execution Profiling. """ import torch import torch.nn as nn class DeepMLP(nn.Module): """ A 5-layer Multi-Layer Perceptron (MLP) featuring dense Linear layers, GELU activations, and BatchNorm1d for dense matrix multiplication profiling. """ def __init__(s...
FaizaQiyyum/PyTorch-Model-Execution-and-Hardware-Optimization-Analyzer
models/mlp.py
.py
9ac5fd231486b279
7
0
""" MiniTransformer Architecture for PyTorch Model Execution Profiling. """ import torch import torch.nn as nn class MiniTransformer(nn.Module): """ A lightweight Transformer Encoder model with MultiheadAttention, LayerNorm, and FeedForward layers. Designed for profiling self-attention mechanisms and tens...
FaizaQiyyum/PyTorch-Model-Execution-and-Hardware-Optimization-Analyzer
models/transformer.py
.py
732bbf315a133541
7
0
from __future__ import annotations import numpy as np REGION_ORDER = ( "LEFT_UP", "UP", "RIGHT_UP", "LEFT", "CENTER", "RIGHT", "LEFT_DOWN", "DOWN", "RIGHT_DOWN", ) KEYPAD_TARGETS = { ord("1"): "LEFT_DOWN", ord("2"): "DOWN", ord("3"): "RIGHT_DOWN", ord("4"): "LEFT", ord("5"): "CENTER", ord("6"): ...
cavallarinmaurizio371-collab/all
evaluation/coordinate_adapter.py
.py
8ba50c257a70e036
7
0
import logging from opentelemetry.instrumentation.alephalpha.config import Config import traceback def dont_throw(func): """ A decorator that wraps the passed in function and logs exceptions instead of throwing them. @param func: The function to wrap @return: The wrapper function """ # Obtain...
rajath-raman/openllmetry
packages/opentelemetry-instrumentation-alephalpha/opentelemetry/instrumentation/alephalpha/utils.py
.py
0dbc56502ebac136
7
0
from botocore.response import StreamingBody from botocore.exceptions import ( ReadTimeoutError, ResponseStreamingError, ) from urllib3.exceptions import ProtocolError as URLLib3ProtocolError from urllib3.exceptions import ReadTimeoutError as URLLib3ReadTimeoutError class ReusableStreamingBody(StreamingBody): ...
rajath-raman/openllmetry
packages/opentelemetry-instrumentation-bedrock/opentelemetry/instrumentation/bedrock/reusable_streaming_body.py
.py
fff45010d990afec
7
0
import logging import traceback from opentelemetry.instrumentation.bedrock.config import Config def dont_throw(func): """ A decorator that wraps the passed in function and logs exceptions instead of throwing them. @param func: The function to wrap @return: The wrapper function """ # Obtain a...
rajath-raman/openllmetry
packages/opentelemetry-instrumentation-bedrock/opentelemetry/instrumentation/bedrock/utils.py
.py
ec754b44231bdfb3
7
0
import logging import traceback from opentelemetry.instrumentation.chromadb.config import Config def dont_throw(func): """ A decorator that wraps the passed in function and logs exceptions instead of throwing them. @param func: The function to wrap @return: The wrapper function """ # Obtain a...
rajath-raman/openllmetry
packages/opentelemetry-instrumentation-chromadb/opentelemetry/instrumentation/chromadb/utils.py
.py
4d2e65ef246484e0
7
0
"""Feedback log helpers — save/load/update trade feedback entries. Each user's feedback is stored in logs/users/{chat_id}/feedback.jsonl. Used by telegram_bot.py (write) and feedback_stats.py (read). """ import json import uuid from datetime import datetime, timezone from pathlib import Path ROOT = Path(__file__).res...
krivonosoff161/trading-bot-v2
scripts/analysis/feedback.py
.py
ff1e3349786c06e3
7.15
1
""" Load and join signals from signals.jsonl for backtesting. Usage in backtest scripts: from scripts.load_signals import load_trades, load_no_trades trades = load_trades("logs_archive/logs_2026-03-08_12-00/signals.jsonl") for t in trades: print(t["symbol"], t["ema_gap"], t["pnl"], t["reason"]) ""...
krivonosoff161/trading-bot-v2
scripts/analysis/load_signals.py
.py
5e7b6a5837b75606
7.15
1
""" verify_signals_from_tape.py For each signal in signal_log.jsonl, replay actual OKX trades from tape/*.csv[.gz] and compute: - real first touch of TP / SL (timestamp, elapsed minutes) - real MFE / MAE at multiple horizons (150m, 300m, 480m, 720m, 1440m) - outcome under hypotheses: original : exit at fir...
krivonosoff161/trading-bot-v2
scripts/analysis/verify_signals_from_tape.py
.py
f1703dd23a05af0e
7.15
1
import json import re from google import genai from google.genai import types from src.agents.schemas import AgentType, IntentDecision class IntentClassifier: """ Classifies student queries into specific agent domains and intent categories. """ def __init__( self, model: str = "gemi...
Wafaeyy/EduTwin
src/agents/intent_classifier.py
.py
ddfa46ef8776d1a2
7
0
""" orchestrator.py Main agent routing and orchestration engine for EduTwin. Coordinates intent classification, context building, agent execution, and output parsing (including Twin signals and proposals). """ import json from pathlib import Path from typing import Any from google import genai from google.genai impo...
Wafaeyy/EduTwin
src/agents/orchestrator.py
.py
c7cf118a042c98c7
7
0
""" parsers.py Parses raw LLM outputs from agents into clean student-facing replies and structured diagnostic signals/reports for the Digital Twin. """ import json import re from typing import Any from src.agents.schemas import CoachSignal, MentorProposal def parse_coach_output(raw_text: str) -> tuple[str, list[Co...
Wafaeyy/EduTwin
src/agents/parsers.py
.py
2e04efb2b9b706fe
7
0
""" Resource Content Understanding (Section 24) - Articles & Research Papers. Piece 1: fetching a resource's REAL content (not just a search snippet) and extracting readable text from it -- either a normal web page (HTML) or a downloadable PDF (common for research papers, e.g. arXiv). Piece 2: sending that real text t...
Wafaeyy/EduTwin
src/agents/recommendation_system/analysis/article_content_analyzer.py
.py
d7d1ea6387939113
7
0
""" Resource Analysis: infers real difficulty and format from a resource's actual title, description, and URL. Uses word-boundary regex to avoid false matches (e.g. "intro" incorrectly matching inside "introducing"). Format inference is deliberately conservative: it returns None rather than guessing. An unknown format...
Wafaeyy/EduTwin
src/agents/recommendation_system/analysis/resource_analyzer.py
.py
26346ce9dfd6db43
7
0
""" The resource catalog: the single gatekeeper between the pipeline and stored resources. Loads from the real PostgreSQL database (Supabase) on first use. If the database cannot be reached, falls back to SEED_RESOURCES in memory so the program still runs -- degraded, but honest about it. SEED_RESOURCES is deliberate...
Wafaeyy/EduTwin
src/agents/recommendation_system/database/resource_store.py
.py
2df9800724a28b99
7
0
""" The Resource class: a structured blueprint for what an educational resource looks like, replacing plain dictionaries. """ class Resource: def __init__(self, title, url, description, topic, difficulty, format, duration): self.title = title self.url = url self.description = description ...
Wafaeyy/EduTwin
src/agents/recommendation_system/models/resource.py
.py
ab44757da7ccff3d
7
0
""" Code-based scoring: format 30 / level 30 / duration 20 / goal 20 = 100 max. Also computes personalization_confidence. TOPIC GATE: when the learner has named a topic, a resource that is not genuinely about that topic scores ZERO, whatever else it matches. A machine learning video is not a useful answer to "recommen...
Wafaeyy/EduTwin
src/agents/recommendation_system/recommendation/scorer.py
.py
c04ecdcd141c64c0
7
0
""" External Resource Discovery: real internet search via DuckDuckGo (ddgs). Format-aware query building so results aren't biased toward any one content type, plus deterministic query VARIATION so a learner who has already seen the obvious results gets genuinely different ones next time. The query templates are a fix...
Wafaeyy/EduTwin
src/agents/recommendation_system/retrieval/discover.py
.py
b7a59ef83f98b012
7
0
""" Real neural embeddings, using a pretrained sentence-transformers model instead of our own simplified word-counting. HONEST NOTE: the first time this runs, it downloads about 80MB of model weights from Hugging Face -- this needs a real internet connection. After that first download, the model is cached on disk and ...
Wafaeyy/EduTwin
src/agents/recommendation_system/retrieval/embeddings.py
.py
fb23e5f915c56817
7
0
""" Orchestrates retrieval with tiered fallback: 1. Exact topic + exact level match 2. Exact topic match, any level 3. Semantic (meaning-based) match -- real neural embeddings if available, else word-count fallback 4. Everything in the database (broad last resort) 5. External Resource Discovery -> Analysis -> Verificat...
Wafaeyy/EduTwin
src/agents/recommendation_system/retrieval/retriever.py
.py
be7484bed4747f6c
7
0
""" Everything related to getting and cleaning up learner state. """ from src.agents.recommendation_system.config import FIELD_ALIASES, KNOWN_LEVELS, KNOWN_FORMATS, KNOWN_DURATIONS # Stand-in for a real learner's twin_id. Team Alpha's StudentTwin generates a # UUID per learner; until we integrate, every mock request ...
Wafaeyy/EduTwin
src/agents/recommendation_system/twin/mock_twin.py
.py
b404a7bdf4c3fdfa
7
0
""" Extracts what the learner is asking for RIGHT NOW from their message. Separate from context_extractor.py, which reads the stored Digital Twin briefing. That gives long-term state ("this learner wants to become an AI engineer"). This gives the immediate request ("show me 10 videos about calculus"). THREE LAYERS, c...
Wafaeyy/EduTwin
src/agents/recommendation_system/twin/request_extractor.py
.py
115924b53a02f4a2
7
0
# -*- coding: utf-8 -*- """历史条件概率统计:单日大跌≥2%后,次日/后日怎么走? 用于回答:明天后天会不会继续跌""" import urllib.request, json def fetch_kline(code="sh000001", start="2024-01-01", count=700, end=None): import datetime as _dt if end is None: end = _dt.date.today().strftime("%Y-%m-%d") url = ("https://web.ifzq.gtimg.cn/appst...
xiaojinglong/A-stock-trade-wisdom-skill
scripts/predict_analysis.py
.py
8ae52b61e2d1afca
7.15
1
"""aiohttp-compatible wrapper over httpx for gradual migration. Mirrors the ``aiohttp.ClientSession`` API so existing scrapers migrate without surgery, while fixing the gaps that a raw pass-through would lose: * ``allow_redirects`` is honored (defaults to following like aiohttp/asyncio). * ``proxy`` is forwarded to h...
Ajay0916/t-api
helper/httpx_compat.py
.py
58be8836c355da18
7
0
"""Vj-wz style logging setup — FileHandler(log.txt) + StreamHandler.""" import logging import os import sys LOG_FILE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "log.txt") _FORMAT = "[%(asctime)s] [%(levelname)s] - %(message)s" _DATEFMT = "%d-%b-%y %I:%M:%S %p" def setup_logging(level...
Ajay0916/t-api
helper/logging_setup.py
.py
3334f259c5f2e727
7
0
import asyncio import httpx as _httpx from helper.httpx_compat import aiohttp _connector = None _transport = None _TRANSPORT_LIMITS = _httpx.Limits(max_connections=100, max_keepalive_connections=20) def _get_shared_transport(): """A process-wide httpx AsyncHTTPTransport that provides real connection reuse ...
Ajay0916/t-api
helper/session.py
.py
0202402e48664b3d
7
0
import hashlib import json import os import threading import time # Tiny persistent store mapping a short token -> the real proxy URL + name. # Lets the bot hand out /api/v1/torrent_file/<token> links instead of # carrying the full url=...&name=... query (rutracker/libgen titles make # those links 1KB+). Entries expir...
Ajay0916/t-api
helper/short_links.py
.py
49ba1c57ca5b9b74
7
0
import subprocess import os import time _start_time = time.time() _REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) _COMMIT_INFO = os.path.join(_REPO, "COMMIT_INFO") _ENV = {**os.environ, "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"} def _run_git(args): for git_bin in ...
Ajay0916/t-api
helper/version_info.py
.py
5317a41df22ea85d
7
0
"""Vj-wz style log viewer endpoint. GET /api/v1/log?lines=50&format=text → Plain text (Vj-wz bot format) GET /api/v1/log?lines=50&format=json → JSON with metadata GET /api/v1/log?format=tail → Last N lines only (raw) """ import os from datetime import datetime, timezone from fastapi import APIRouter...
Ajay0916/t-api
routers/v1/log_router.py
.py
1717a42d78f07f22
7
0
import asyncio import re from helper.logging_setup import get_logger LOGGER = get_logger("tapi.torrent") from urllib.parse import quote, unquote, urlsplit import aiohttp from fastapi import APIRouter, Request from fastapi.responses import JSONResponse, Response, StreamingResponse from constants.headers import HEADER_...
Ajay0916/t-api
routers/v1/torrent_file_router.py
.py
d3b6b6d921abb7ee
7
0
from __future__ import annotations import argparse import hashlib import json from datetime import UTC, datetime from pathlib import Path from typing import Any, Sequence from finance_crawler_poc.contracts import validate_contract from finance_crawler_poc.radar import build_topic_snapshot from finance_crawler_poc.tar...
ai-cooperation/finance-crawler-validation
src/finance_crawler_poc/h3_assemble.py
.py
2573e91d8b787dbc
7
0
"""Install Symbiosis Brain statusline wrapper into ~/.claude/settings.json. Auto-detects existing user statusline; saves it in env-var so the wrapper delegates to it. Idempotent. Backs up settings.json before each write. """ from __future__ import annotations import argparse import json from pathlib import Path from...
Krill113/symbiosis-brain
scripts/install_statusline.py
.py
b6068032ead7d979
7
0
"""Shared helpers for Symbiosis Brain installers. Used by: - scripts/install_statusline.py — pre-existing statusline installer - src/symbiosis_brain/install_cli.py — full setup CLI """ from __future__ import annotations import copy import json import os import shutil from collections.abc import Iterable from datetim...
Krill113/symbiosis-brain
src/symbiosis_brain/install_lib.py
.py
bfe08ff71eaa5f58
7
0
from pathlib import Path from symbiosis_brain.gist_limits import GIST_SOFT_LIMIT from symbiosis_brain.storage import Storage from symbiosis_brain.resolver import ( resolve_target, build_path_index, compute_linked_canonicals, is_external_ref, ) # Reused, not re-derived: not_indexed only means anything i...
Krill113/symbiosis-brain
src/symbiosis_brain/lint.py
.py
da1c5e3d80ad2864
7
0
import re from datetime import date as _date, datetime as _datetime from typing import Any import frontmatter # `[^\]\n]` — без \n намеренно: незакрытая '[[' иначе жадно матчится через перенос # строки до ближайшего ']]' и съедает следующую строку (B1, рецидивы 28.07/07.08/10.08). # Многострочных wiki-ссылок в vault ...
Krill113/symbiosis-brain
src/symbiosis_brain/markdown_parser.py
.py
55396335d79422ce
7
0
"""Onboarding lockfile — prevents concurrent brain-project-init sessions from creating duplicate artifacts for the same scope. Spec: /tmp/symbiosis-brain-onboard-<scope>.lock holds PID + timestamp. Stale (older than timeout_s) locks are reclaimed. """ import os import tempfile import time from pathlib import Path LOC...
Krill113/symbiosis-brain
src/symbiosis_brain/onboard_lock.py
.py
5c6ffc235366466d
7
0
""" Parent process death watchdog (Windows-specific kernel-level wait). Detects when our parent process terminates and fires a callback to initiate graceful shutdown. Uses Win32 OpenProcess + WaitForSingleObject (kernel wait, zero CPU while parent alive, immune to PID reuse). On non-Windows returns an inert no-op hand...
Krill113/symbiosis-brain
src/symbiosis_brain/parent_watchdog.py
.py
deb01a12c9c416e5
7
0
"""Config loader for pre-action recall hook (B1). Loads `~/.claude/symbiosis-brain-pre-action.json` with fall-back to defaults. Missing or malformed file → defaults + log to the path _debug_log_path() picks (SYMBIOSIS_BRAIN_DEBUG_LOG, else <TMPDIR>/brain-hook-debug.log). """ from __future__ import annotations import ...
Krill113/symbiosis-brain
src/symbiosis_brain/pre_action_config.py
.py
5ba6e63a7254a02b
7
0
"""Pre-action recall orchestrator (B1 hook). Pure-Python module — no I/O side effects (caller wires SearchEngine). """ from __future__ import annotations import os import time from pathlib import Path from typing import Any, Optional from symbiosis_brain.pre_action_config import PreActionConfig _DEFAULT_FTS_MODE = ...
Krill113/symbiosis-brain
src/symbiosis_brain/pre_action_recall.py
.py
b7c180790e6624a0
7
0
"""Provenance: who last wrote a note, and who asked for a retrieval. Stage 2 slice 1 (CP-2) ships ONLY `client_id`. `written_by_value` and the model bridge arrive in CP-4 and CP-5 (Р2) — do not anticipate them here. The client label is SELF-REPORTED by the MCP client and is a good-faith mark, not an authentication ([...
Krill113/symbiosis-brain
src/symbiosis_brain/provenance.py
.py
a5571cac7b0ba722
7
0
"""Session-scoped recall dedup (Stage 1). Suppresses recall hits already shown earlier in the same session within a short TTL window, so the per-tool-call recall block stops re-emitting the same hits (which trains the agent to ignore recall — see [[feedback/symbiosis-brain-usage-self-critique-2026-05-15]]). Keyed by ...
Krill113/symbiosis-brain
src/symbiosis_brain/recall_dedup.py
.py
e4c56ccec7a450a5
7
0
"""Atomic refactor operations on the vault. brain_rename(old_path, new_path) — rewrite all inbound [[old]] references to [[new]] in source notes, then move the file. Idempotent on the file move (refuses to overwrite if new_path already exists). brain_delete(path, mode) — `safe` mode refuses if inbound refs exist (lis...
Krill113/symbiosis-brain
src/symbiosis_brain/refactor.py
.py
0c0941be304dd271
7
0
from __future__ import annotations from typing import TYPE_CHECKING import re as _re if TYPE_CHECKING: from symbiosis_brain.storage import Storage def _strip_md(p: str) -> str: return p[:-3] if p.lower().endswith(".md") else p def _strip_anchor(p: str) -> str: """Remove '#anchor' suffix from a wiki-l...
Krill113/symbiosis-brain
src/symbiosis_brain/resolver.py
.py
ce6916dd88dc3b45
7
0
"""Scope detection helpers — normalize, parse marker, detect.""" import re from dataclasses import dataclass from pathlib import Path from typing import Optional _SEPARATOR_RE = re.compile(r"[._\s]+") _CAMEL_RE = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])") _NON_ALNUM_DASH = re.compile(r"[^a-z0-9-]")...
Krill113/symbiosis-brain
src/symbiosis_brain/scope_resolver.py
.py
79d1321946a58168
7
0
import re from typing import TypedDict from symbiosis_brain.markdown_parser import _mask_code_regions # Matches any ATX heading h1-h6 (`#`..`######`). Single capture group = the # heading text. SC1: append targets any level (not just h2). SECTION_HEADING_RE = re.compile(r"^#{1,6}\s+(.+?)\s*$", re.MULTILINE) def _he...
Krill113/symbiosis-brain
src/symbiosis_brain/sections.py
.py
d415ff0c1255117e
7
0
"""SQLite build health checks. Upstream SQLite carried a WAL-Reset race from 3.7.0 through 3.51.2: with WAL journaling and two or more connections (threads or processes) writing and checkpointing at the same time, a reset of the write-ahead log could drop or corrupt committed pages. Fixed upstream in 3.51.3 (2026-03-1...
Krill113/symbiosis-brain
src/symbiosis_brain/sqlite_health.py
.py
30125d9b296e947b
7
0
import hashlib from dataclasses import dataclass, field from pathlib import Path # PyYAML is a hard dependency of python-frontmatter, which is what actually # raises here — parse_note -> frontmatter.loads -> yaml. import yaml from symbiosis_brain.markdown_parser import extract_wikilinks, parse_note from symbiosis_bra...
Krill113/symbiosis-brain
src/symbiosis_brain/sync.py
.py
4b2427ca40ea5adb
7
0
"""Parse reference/scope-taxonomy.md as single source of truth for scopes + folder-type map.""" from __future__ import annotations import re from pathlib import Path _TAXONOMY_REL = Path("reference") / "scope-taxonomy.md" def _read_taxonomy(vault_path: Path) -> str: file_path = vault_path / _TAXONOMY_REL if...
Krill113/symbiosis-brain
src/symbiosis_brain/taxonomy.py
.py
27516fa8a4726211
7
0
"""Stage-4 tool-routing engine (C3). Fail-open everywhere. Loads a package-default routing catalog (``data/tool-routing.json``, a BARE top-level JSON array) merged with an optional per-vault override (``tool-routing.local.json``) by ``id``, compiles each route's regex triggers, evaluates a ``when``-gate (platform / sk...
Krill113/symbiosis-brain
src/symbiosis_brain/tool_routing.py
.py
28f9ee0b8d3a8350
7
0
"""Write-time validation gates for brain_write / brain_append / brain_patch. Two classes of rule: - hard-block: raise ValidationError, file is NOT written - soft-warn: return a Warning_ entry in the warnings list, file IS written Hard-block list (structural breakage): - missing_gist: frontmatter has no gist field - ...
Krill113/symbiosis-brain
src/symbiosis_brain/validation.py
.py
fb185a0999a09876
7
0
"""Per-note file lock — serializes concurrent writes to the same note across processes (and threads within the same process). Mirrors `onboard_lock.py` pattern: atomic O_EXCL creation + stale-lock reclamation by mtime. Hash key is `(vault_path.resolve(), rel_path)` so: - Different vaults don't collide on the same rel_...
Krill113/symbiosis-brain
src/symbiosis_brain/write_lock.py
.py
c4febc09ad8cc465
7
0
"""Locate a usable bash for tests that spawn the hook scripts. Never a bare "bash": on a Windows GitHub runner that resolves to the WSL stub in %SystemRoot% (exit 1, empty stderr), and on a dev box whose PATH lacks Git\\bin it resolves to nothing at all. Probe Git-for-Windows locations by absolute path and health-chec...
Krill113/symbiosis-brain
tests/_bash_resolver.py
.py
f6a3090d5806755c
7.5
0
import os import sqlite3 import tempfile from pathlib import Path import pytest from symbiosis_brain.sync import VAULT_DIRS @pytest.fixture def tmp_vault(tmp_path: Path) -> Path: """Create a temporary vault directory with standard structure.""" for d in VAULT_DIRS: (tmp_path / d).mkdir() return ...
Krill113/symbiosis-brain
tests/conftest.py
.py
4d9da3097e4bab15
7.5
0
import os, subprocess, json, tempfile, shutil, pathlib import pytest # NEW — file previously imported only os/subprocess/json/tempfile/shutil/pathlib HOOK = pathlib.Path(__file__).resolve().parents[1] / 'hooks' / 'brain-save-trigger.sh' START = pathlib.Path(__file__).resolve().parents[1] / 'hooks' / 'brain-session-st...
Krill113/symbiosis-brain
tests/test_brain_save_trigger_routing.py
.py
85691c2c4d83dcff
7.5
0
"""Coverage for the brain_sync MCP tool: default targeted-diff behavior vs full=true triggering a full re-embed. Uses the canonical server-test pattern (see test_server_refactor_tools.py) — `server_mod._init(...)` + `await server_mod.call_tool(name, args)` + teardown reset. """ import json from pathlib import Path imp...
Krill113/symbiosis-brain
tests/test_brain_sync_tool.py
.py
95a3c54cb885060a
7.5
0
"""Tests for tools/changelog_section.py — the release-notes extractor used by the `release` job in .github/workflows/publish.yml. The module lives in tools/ (repo tooling, not shipped in the wheel), so it is loaded by path instead of being imported as a package. """ import importlib.util import sys from pathlib import...
Krill113/symbiosis-brain
tests/test_changelog_section.py
.py
c86e32609e50564b
7.5
0
"""渠道调用者授权:生产默认拒绝,开发态全开放必须双重显式开启。""" from __future__ import annotations import os from dataclasses import dataclass, field from typing import Mapping _TRUE = {"1", "true", "yes", "on"} _DEVELOPMENT_ENVS = {"dev", "development", "local", "test"} def explicit_development_allow_all( channel: str, environ: Mappin...
wg5759/nachuan
bridge/access.py
.py
9737e4a3215df099
7
0
"""桥接策略:白名单、限频、命令解析(平台无关的纯逻辑,便于单测)。 用途:群聊里别人 @ 机器人也能用同样能力,但花的是机主额度 —— 所以: · 白名单:只允许指定用户(空=不限制); · 限频:每用户每分钟上限,防止有人狂刷烧额度; · 命令:/whoami 查自己的 open_id(用于配“机主统一记忆”)、👍/👎 反馈。 """ from __future__ import annotations import re import threading import time from collections import OrderedDict, deque def is_allowed(use...
wg5759/nachuan
bridge/policy.py
.py
7c7b7d0e25297faa
7
0
"""Telegram 桥接:手机发消息 → 本地引擎处理 → 回复手机。 用长轮询(getUpdates),桥接进程主动外连 Telegram,**无需公网/webhook**。 需要一个 Bot Token(@BotFather 创建)。 """ from __future__ import annotations import asyncio from collections import OrderedDict from typing import Any import httpx from bridge.access import ChannelAccessPolicy class TelegramBridg...
wg5759/nachuan
bridge/telegram.py
.py
dfeb7daeeb5ad343
7
0
"""Production defaults for the pip-installed ``nachuan-engine`` command.""" from __future__ import annotations import os import sys from pathlib import Path _MANAGED_SUBSCRIPTION_ENVIRONMENT = ( "CODEX_CLI_PATH", "CODEX_CLI_SHA256", "CODEX_CLI_TEMP_ROOT", "KIMI_CLI_PATH", "KIMI_CLI_SHA256", ...
wg5759/nachuan
cli/engine_entrypoint.py
.py
f2ce946888a8ad65
7
0
import math import types from collections.abc import Callable, Iterator from dataclasses import dataclass from datetime import tzinfo from types import EllipsisType from typing import ( TYPE_CHECKING, Annotated, Any, Literal, Protocol, SupportsFloat, SupportsIndex, TypeVar, Union, ...
DnlSQ/AI-Document-Intelligence
.venv/Lib/site-packages/annotated_types/__init__.py
.py
a7104a4d439b27a9
7
0
import math from collections.abc import Iterable, Iterator from datetime import date, datetime, timedelta, timezone from decimal import Decimal from typing import Annotated, Any, NamedTuple import annotated_types as at class Case(NamedTuple): """ A test case for `annotated_types`. """ annotation: An...
DnlSQ/AI-Document-Intelligence
.venv/Lib/site-packages/annotated_types/test_cases.py
.py
d867472acb57b81c
7.5
0
from __future__ import annotations import math import sys import threading from collections.abc import Awaitable, Callable, Generator from contextlib import contextmanager from contextvars import Token from importlib import import_module from typing import TYPE_CHECKING, Any, TypeVar from ._exceptions import NoEventL...
DnlSQ/AI-Document-Intelligence
.venv/Lib/site-packages/anyio/_core/_eventloop.py
.py
0726547890fd6a53
7
0
from __future__ import annotations import math import sys from collections.abc import ( Coroutine, Generator, ) from contextlib import ( contextmanager, ) from enum import Enum, auto from inspect import iscoroutine from types import TracebackType from typing import Any, Generic, final from ..abc import Ta...
DnlSQ/AI-Document-Intelligence
.venv/Lib/site-packages/anyio/_core/_tasks.py
.py
cbdf6f462f801731
7
0
from __future__ import annotations import sys from abc import ABCMeta, abstractmethod from collections.abc import Callable, Coroutine from contextvars import Context from types import TracebackType from typing import TYPE_CHECKING, Any, Literal, Protocol, final, overload if sys.version_info >= (3, 13): from typin...
DnlSQ/AI-Document-Intelligence
.venv/Lib/site-packages/anyio/abc/_tasks.py
.py
9be16d138a61c5e3
7
0
from __future__ import annotations __all__ = ( "BlockingPortal", "BlockingPortalProvider", "check_cancelled", "run", "run_sync", "start_blocking_portal", ) import sys from collections.abc import Awaitable, Callable, Coroutine, Generator from concurrent.futures import Future from contextlib imp...
DnlSQ/AI-Document-Intelligence
.venv/Lib/site-packages/anyio/from_thread.py
.py
258b1b68268807f2
7
0
from __future__ import annotations __all__ = ( "EventLoopToken", "RunvarToken", "RunVar", "checkpoint", "checkpoint_if_cancelled", "cancel_shielded_checkpoint", "current_token", ) import enum from dataclasses import dataclass from types import TracebackType from typing import TYPE_CHECKING...
DnlSQ/AI-Document-Intelligence
.venv/Lib/site-packages/anyio/lowlevel.py
.py
fb9f78f3867a2b98
7
0
from __future__ import annotations __all__ = ( "BufferedByteReceiveStream", "BufferedByteStream", "BufferedConnectable", ) import sys from collections.abc import Callable, Iterable, Mapping from dataclasses import dataclass, field from typing import Any, SupportsIndex from .. import ClosedResourceError, ...
DnlSQ/AI-Document-Intelligence
.venv/Lib/site-packages/anyio/streams/buffered.py
.py
bbb8420fc48dad81
7
0
from __future__ import annotations __all__ = ( "FileReadStream", "FileStreamAttribute", "FileWriteStream", ) from collections.abc import Callable, Mapping from io import SEEK_SET, UnsupportedOperation from os import PathLike from pathlib import Path from typing import IO, Any from .. import ( BrokenR...
DnlSQ/AI-Document-Intelligence
.venv/Lib/site-packages/anyio/streams/file.py
.py
ea3ba32369be4092
7
0
from __future__ import annotations __all__ = ( "TextConnectable", "TextReceiveStream", "TextSendStream", "TextStream", ) import codecs import sys from collections.abc import Callable, Mapping from dataclasses import InitVar, dataclass, field from typing import Any from ..abc import ( AnyByteRecei...
DnlSQ/AI-Document-Intelligence
.venv/Lib/site-packages/anyio/streams/text.py
.py
05c540189c35551b
7
0
from __future__ import annotations __all__ = ( "TLSAttribute", "TLSConnectable", "TLSListener", "TLSStream", ) import logging import re import ssl import sys from collections.abc import Callable, Mapping from dataclasses import dataclass from functools import wraps from ssl import SSLContext from typi...
DnlSQ/AI-Document-Intelligence
.venv/Lib/site-packages/anyio/streams/tls.py
.py
1afb3ef983a81717
7
0
from __future__ import annotations __all__ = ( "current_default_process_limiter", "process_worker", "run_sync", ) import os import pickle import runpy import subprocess import sys from collections import deque from collections.abc import Callable from types import ModuleType from typing import TypeVar, ca...
DnlSQ/AI-Document-Intelligence
.venv/Lib/site-packages/anyio/to_process.py
.py
8c7c3bbfa5c704d2
7
0
from __future__ import annotations __all__ = ( "run_sync", "current_default_thread_limiter", ) import sys from collections.abc import Callable from typing import TYPE_CHECKING, TypeVar from warnings import warn from ._core._eventloop import get_async_backend if TYPE_CHECKING: from ._core._synchronizatio...
DnlSQ/AI-Document-Intelligence
.venv/Lib/site-packages/anyio/to_thread.py
.py
6d8b335b49420df4
7
0
""" certifi.py ~~~~~~~~~~ This module returns the installation location of cacert.pem or its contents. """ import sys import atexit def exit_cacert_ctx() -> None: _CACERT_CTX.__exit__(None, None, None) # type: ignore[union-attr] if sys.version_info >= (3, 11): from importlib.resources import as_file, file...
DnlSQ/AI-Document-Intelligence
.venv/Lib/site-packages/certifi/core.py
.py
5c55f2727746e697
7
0
""" Stage 2, step 1: momentum-space function of the CONTINUUM-averaged nonlocal d'Alembertian in d=2. Pure analysis -- no discrete matrix, no BB^dagger. Continuum-averaged operator (already validated in b_eps.py): Bbar phi(x) = (1/xi^2)[ -2 phi(x) + 4 rho int_{J^-(x)} dV e^{-rho V}(1 - 2 rho V + (r...
dr17414/lightspeed-fundamental-theory
analysis/gmom_2d.py
.py
a0698352e9e2d127
7
0
""" Cross-check: repo's own continuum g(p^2) vs literature Eq.(15) of Belenchia, Benincasa, Marciano, Modesto, arXiv:1507.00330 (PRD 93, 044017). Paper d=2 minimal nonlocal d'Alembertian, momentum space (their Eq. 15): g^(2)(k^2) = a2 * rho + 2 rho * sum_{n=0..2} (b_n/n!) * gam^n * int...
dr17414/lightspeed-fundamental-theory
analysis/gmom_2d_bbmm.py
.py
676bfda6eab278d6
7
0
"""Candidate-independent hard controls for Stage 5C C8.4. This module deliberately contains no candidate kernel. It constructs two 1+1-dimensional continuum targets whose finite sprinklings remain permutation orders, while their continuum massless-chiral transfer targets have opposite directions. The two targets are...
dr17414/lightspeed-fundamental-theory
analysis/stage5c_hard_controls.py
.py
da6d277831d4e985
7
0
"""Track B, stage 1: 4D operator of Saravani--Aslanbeigi, arXiv:1502.01655. This module implements ONLY the source-faithful position/momentum kernel on the real spacelike section Z>0. It deliberately does not yet implement complex-plane stability, quantum spectral density, Wick rotation, P(s), or d_s. Primary source...
dr17414/lightspeed-fundamental-theory
analysis/track_b_4d.py
.py
450afb66c56cff66
7
0
""" B_eps_2d: smeared causal-set d'Alembertian, 1+1 Minkowski. Formula taken verbatim from Dowker-Glaser / Sorkin -- no self-designed smearing. B_eps^(2) phi(x) = (eps/l^2)[ -2 phi(x) + 4 eps sum_{y<x} f_2(n,eps) phi(y) ] f_2(n,eps) = (1-eps)^n [ 1 - 2 eps n/(1-eps) + eps^2 n(n-1)/(2(1-eps)^2) ] eps = (l/x...
dr17414/lightspeed-fundamental-theory
benchmarks/b_eps_2d.py
.py
ae54b2c97a4247e4
7
0
""" test_appendix_b.py =================== Regression test for 零時光網/因果相位網 研究進度與AI交接文件 v1.0, Appendix B. Purpose ------- 1. Confirms (empirically, on random finite causal sets) that the naive retarded operator (D_C psi)_i = sum_{j prec i} f(|I(j,i)|) U_ij psi_j is always strictly lower-triangular under any...
dr17414/lightspeed-fundamental-theory
tests/test_appendix_b.py
.py
ea79842b1f795e39
7.5
0
""" test_order_invariants.py ======================== Unit tests for causal-set order invariants. Verifies transitivity, irreflexivity, antisymmetry, and generator sanity checks across the entire FAMILY of posets in order_bench.py. """ import sys import os import numpy as np # Ensure benchmarks folder is in python mod...
dr17414/lightspeed-fundamental-theory
tests/test_order_invariants.py
.py
164a6e41e2aad30c
7.5
0
""" Regression tests for the d=2 spectral dimension pipeline. Every assertion below is a statement made by Belenchia, Benincasa, Marciano, Modesto, arXiv:1507.00330 (PRD 93, 044017) about their own operators. None is a target we invented. If a future change to analysis/spectral_dim_2d.py silently swaps in a differ...
dr17414/lightspeed-fundamental-theory
tests/test_spectral_dim_2d.py
.py
e34e088bb6bdc3b7
7.5
0
""" Regression tests for the d=4 spectral dimension pipeline (Track A replication). Verifies key limits and constants for the 4D GCB operator, including the IR limit, UV limit, regularized UV limit, and spectral dimension flow. """ import os import sys import numpy as np import pytest sys.path.insert(0, os.path.dirn...
dr17414/lightspeed-fundamental-theory
tests/test_spectral_dim_4d.py
.py
cda51ddd6f63211c
7.5
0
"""Regression tests for Stage 5B-2 limited Result B. These tests pin three independent claims: * the rank diagnostic must be three-valued to respect the global U<->V swap; * independent monotone null-coordinate reparameterisations preserve the order and the rank diagnostic while a metric comparison can change;...
dr17414/lightspeed-fundamental-theory
tests/test_stage5b_link_channel.py
.py
cecd032d9f1f8c12
7.5
0
"""Stage-1 regression tests for arXiv:1502.01655 Track B 4D operator.""" import os import sys import numpy as np import pytest from scipy import integrate sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from analysis.track_b_4d import A, DELTA_COEFF, f_smooth, delta_g, g_spacelike def...
dr17414/lightspeed-fundamental-theory
tests/test_track_b_4d.py
.py
690a34bdca9fc890
7.5
0
import asyncio import importlib import os import pkgutil from logging.config import fileConfig from alembic import context from sqlalchemy import pool from sqlalchemy.engine import Connection from sqlalchemy.ext.asyncio import async_engine_from_config from src.infrastructure.config.settings import settings from src.i...
lakshyakumarsaini07/Salesforce-QA-Agent
backend/migrations/env.py
.py
6e0d09417992e80b
7
0
"""Authentication-specific HTTP exceptions. This module provides HTTP exceptions specifically designed for authentication and authorization scenarios, extending the base FastCRUD exceptions with auth-specific functionality like CSRF protection. The module re-exports commonly used HTTP exceptions from FastCRUD for con...
lakshyakumarsaini07/Salesforce-QA-Agent
backend/src/infrastructure/auth/http_exceptions.py
.py
a4aa4cae965b2299
7
0
import json from typing import Any try: import aiomcache except ImportError: raise ImportError( "The aiomcache package is not installed. " "Please install it with 'pip install aiomcache' or 'pip install -e \".[memcached]\"'" ) from pydantic import BaseModel from ...config.settings import ...
lakshyakumarsaini07/Salesforce-QA-Agent
backend/src/infrastructure/cache/backends/memcached.py
.py
00c407762d27dc0e
7
0