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
""" Figure 6 """ import numpy as np import pandas as pd import seaborn as sns from scipy.stats import ttest_ind, zscore from .common import getSetup, subplotLabel def makeFigure(): """Get a list of the axis objects and create a figure.""" ax, f = getSetup((7, 7), (3, 3)) subplotLabel(ax) data = np....
meyer-lab/RISE
analysis/figures/figure6.py
.py
161ba54c0d991370
7.42
6
""" Figure S2 """ import anndata import numpy as np import pacmap import pandas as pd import scanpy as sc import scib from sklearn.decomposition import PCA # from RISE.plotting import plot_r2x from RISE.plotting import plot_labels_pacmap from ..imports import import_thomson_factors from .common import getSetup, subp...
meyer-lab/RISE
analysis/figures/figureS2.py
.py
888ae46e924af5e6
7.42
6
""" Figure S3 """ import anndata import seaborn as sns from matplotlib.axes import Axes from RISE.plotting import cell_count_perc_df, rotate_xaxis from ..imports import import_thomson_factors from .common import getSetup, subplotLabel def makeFigure(): """Get a list of the axis objects and create a figure.""" ...
meyer-lab/RISE
analysis/figures/figureS3.py
.py
6ae756643b5de85b
7.42
6
""" Figure S7 """ import numpy as np import pandas as pd import seaborn as sns from anndata import AnnData from matplotlib.axes import Axes from scipy.stats import linregress from analysis.imports import import_thomson from RISE.factorization import pf2 from .common import getSetup, subplotLabel def makeFigure(): ...
meyer-lab/RISE
analysis/figures/figureS7.py
.py
cb1af09461f3ea5e
7.42
6
""" Figure 8a_d """ import anndata import seaborn as sns from matplotlib.axes import Axes from .common import getSetup, subplotLabel def makeFigure(): """Get a list of the axis objects and create a figure.""" ax, f = getSetup((6, 6), (2, 2)) subplotLabel(ax) X = anndata.read_h5ad("/opt/andrew/lupus...
meyer-lab/RISE
analysis/figures/figureS8a_d.py
.py
cdd3fbbb4fcc8360
7.42
6
""" Figure 9a_d """ import os import time import tracemalloc import anndata import cupy as cp import numpy as np import pandas as pd import scanorama # import scvi import seaborn as sns # import torch from harmonypy import run_harmony from scipy.sparse import csr_array from analysis.imports import import_lupus fro...
meyer-lab/RISE
analysis/figures/figureS9a_d.py
.py
d201dd21826fd8ca
7.42
6
""" Figure 9e_f """ import anndata import numpy as np import pandas as pd import seaborn as sns from matplotlib.axes import Axes from analysis.figures.commonFuncs.plotLupus import samples_only_lupus from analysis.logisticReg import logistic_regression from RISE.factorization import correct_conditions from RISE.plotti...
meyer-lab/RISE
analysis/figures/figureS9e_f.py
.py
f9e66a28e7ed3980
7.42
6
import os import urllib.request import anndata import h5py import pandas as pd import vcsc from anndata.io import read_elem from parafac2.normalize import prepare_dataset THOMSON_RAW_URL = ( "https://ucla.box.com/shared/static/jy53rcort51xn5t2dr5927wfj13g9e7j.h5" ) def download_thomson_raw( dest_path: str =...
meyer-lab/RISE
analysis/imports.py
.py
11be12d24fd872cf
7.42
6
""" Test the cross validation accuracy. """ import os import numpy as np import pytest from analysis.imports import import_lupus, import_thomson, import_thomson_factors @pytest.mark.parametrize( "import_func", [ import_thomson, import_lupus, ], ) def test_imports(import_func): """Te...
meyer-lab/RISE
analysis/tests/test_import.py
.py
a778374823272c55
7.92
6
"""Generate figures for the RISE tutorial documentation dynamically during doc build.""" import os from pathlib import Path import hdf5plugin # noqa: F401 import matplotlib matplotlib.use("Agg") # Non-interactive backend import matplotlib.pyplot as plt from analysis.imports import import_thomson_factors from RISE...
meyer-lab/RISE
docs/generate_tutorial_figures.py
.py
4ce793af88eea259
7.42
6
# ABOUTME: Async httpx client for the Raindrop.io REST API. # ABOUTME: Paginates raindrops and merges root, nested, and the synthetic "All" collection. from __future__ import annotations import os from typing import Protocol import httpx BASE_URL = "https://api.raindrop.io/rest/v1" PER_PAGE = 50 # Raindrop's system...
JoshuaOliphant/avocet
avocet/raindrop_api.py
.py
efbae0c5d3a7c3ea
7.64
18
# ABOUTME: Summary provider seam — Claude and OpenAI real providers, plus a test stub. # ABOUTME: Fetches a bookmark's page text and asks an LLM for a concise summary, cached by the DB. from __future__ import annotations import os from typing import Protocol import httpx from avocet.models import Raindrop CLAUDE_MO...
JoshuaOliphant/avocet
avocet/summary.py
.py
bcd0f1f5d595bdeb
7.64
18
# ABOUTME: Shared test double for the Raindrop API client used by interaction tests. # ABOUTME: Implements the full RaindropClient protocol; tests subclass and override what they use. from __future__ import annotations class BaseFakeRaindrop: """A complete RaindropClient stand-in for tests. Every method rais...
JoshuaOliphant/avocet
tests/fakes.py
.py
52321033352b981c
8.14
18
# ABOUTME: Verifies the app syncs from a (fake) RaindropAPI into the DB on refresh. # ABOUTME: The fake API returns canned collections/raindrops; no network involved. from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool from avocet.app import Avocet from avocet.database_manager import DatabaseMa...
JoshuaOliphant/avocet
tests/test_app_sync.py
.py
8217ba98ced75978
7.14
18
# ABOUTME: Verifies theme changes persist to the DB settings table. # ABOUTME: Drives a theme change via Pilot and reads the DB settings table to confirm persistence. from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool from avocet.app import Avocet from avocet.database_manager import DatabaseMa...
JoshuaOliphant/avocet
tests/test_app_theme.py
.py
98bdd5ca417a8115
7.14
18
# ABOUTME: Tests for DatabaseManager against a real in-memory SQLite engine. # ABOUTME: StaticPool keeps the schema alive across the sessions the manager opens. import pytest from sqlalchemy import create_engine from sqlalchemy.pool import StaticPool from avocet.database_manager import DatabaseManager @pytest.fixtur...
JoshuaOliphant/avocet
tests/test_database_manager.py
.py
e282d8a3d4a68e71
7.14
18
# ABOUTME: Tests for the SQLAlchemy declarative models. # ABOUTME: Verifies table creation and the Raindrop.summary nullable column. from sqlalchemy import create_engine, inspect from sqlalchemy.pool import StaticPool from avocet.models import Base, Collection, Raindrop, Setting def test_tables_create(): engine ...
JoshuaOliphant/avocet
tests/test_models.py
.py
0677b443eddd68f0
7.14
18
# ABOUTME: Tests for the modal screen result dataclasses. # ABOUTME: Confirms AddResult carries the fields the app needs to call the API. from avocet.screens import AddResult def test_add_result_fields(): result = AddResult(link="https://x", collection_id=1, title="Mine", tags=["py", "tui"]) assert result.lin...
JoshuaOliphant/avocet
tests/test_screens.py
.py
8d803272b2d8eb78
7.14
18
# ABOUTME: Visual regression snapshots via pytest-textual-snapshot. # ABOUTME: Determinism comes from the seeded in-memory DB + stub provider in seeded_app.py. from pathlib import Path APP = str(Path(__file__).parent / "snapshot_apps" / "seeded_app.py") # Navigate from All (index=None) to Python: first down moves to ...
JoshuaOliphant/avocet
tests/test_snapshots.py
.py
c9bb647ccd29d8da
7.14
18
"""Real GDB integration tests for per-session isolation. Prerequisites: - GDB installed on system (gdb --version) - g++ installed (g++ --version) - Flask server running with threaded=True """ import requests import threading import time import os import subprocess import unittest BASE_URL = "http://localhost:10000" ...
c2siorg/GDB-UI
gdbui_server/real_gdb_integration_test.py
.py
1e0ca1e5f42ca25e
8.07
13
"""Per-session Docker container management for GDB sandboxing. Each session gets a dedicated container with read-only rootfs and no network. GDB and g++ are invoked via ``docker exec``. The session's output directory is bind-mounted at /workspace so compiled binaries are immediately available. Usage:: from sandb...
c2siorg/GDB-UI
gdbui_server/sandbox.py
.py
a994cc46ded29a5f
7.57
13
"""Integration tests for WebSocket connection lifecycle and streaming output. Uses flask-socketio's SocketIOTestClient to exercise the real Socket.IO server in-process, without requiring a real WebSocket connection or running server. These tests verify the full pipeline: create_session -> WebSocket connect -> strea...
c2siorg/GDB-UI
gdbui_server/tests/test_websocket_integration.py
.py
0ecf06801dd85e42
8.07
13
"""Unit tests for the per-session reader greenlet.""" import unittest from unittest.mock import patch, MagicMock import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) from session_manager import SessionManager class TestWebSocketReader(unittest.TestCase): def setUp(self): ...
c2siorg/GDB-UI
gdbui_server/tests/test_websocket_reader.py
.py
9e0495abac4ce45b
7.07
13
"""Platform for Fancoil Modbus.""" from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, ClassVar from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( ClimateEntityFeature, HVACMode, ) from homeassistant.components....
lorenzo93/homeassistant-innova
custom_components/modbus_innova/climate.py
.py
45ef1dd061f421d2
7.54
11
"""Platform for Fancoil Modbus water temperature sensor.""" from __future__ import annotations import logging from typing import TYPE_CHECKING from homeassistant.components.modbus import get_hub from homeassistant.components.modbus.const import CALL_TYPE_REGISTER_HOLDING from homeassistant.components.sensor import (...
lorenzo93/homeassistant-innova
custom_components/modbus_innova/sensor.py
.py
d80045cbefbd5e98
7.54
11
""" Access definition generator for SurrealDB authentication. Generates DEFINE ACCESS ... TYPE RECORD statements for user authentication using SurrealDB's built-in JWT support. """ from dataclasses import dataclass, field from typing import TYPE_CHECKING from ..types import EncryptionAlgorithm, TableType if TYPE_CH...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/auth/access.py
.py
d30b6035bcf16b9d
7.52
10
""" Debug and profiling utilities for SurrealDB ORM. Provides ``QueryLogger``, an async context manager that captures all ORM queries with timing information for performance profiling and debugging. Example:: from surreal_orm.debug import QueryLogger async with QueryLogger() as logger: users = await...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/debug.py
.py
fa360cde4676cd1a
7.52
10
""" Encrypted field type for password and sensitive data storage. This module provides the Encrypted[T] type that automatically generates the appropriate SurrealDB crypto functions in schema definitions. """ from dataclasses import dataclass from typing import TYPE_CHECKING, Annotated, Any, get_args, get_origin from...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/fields/encrypted.py
.py
003973db7435e674
7.52
10
""" Geospatial annotation helpers for SurrealDB. Provides ``GeoDistance`` that can be used with ``QuerySet.annotate()`` to compute distances between a field and a reference point. Example:: from surreal_orm import GeoDistance results = await Restaurant.objects().nearby( "location", (-73.98, 40.74), ...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/geo.py
.py
f594065dff49b9a0
7.52
10
""" ORM-level Live Streaming for SurrealDB. Provides typed model change events via Live Queries (WebSocket) and Change Feeds (HTTP). Usage: # Live Models (WebSocket, real-time) async with User.objects().filter(role="admin").live() as stream: async for event in stream: print(event.action, e...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/live.py
.py
f9fc6cc98d433bdf
7.52
10
""" Database introspector for reverse schema extraction. Reads the live schema from a SurrealDB database using ``INFO FOR DB`` and ``INFO FOR TABLE`` commands, then parses the returned DEFINE statements into a ``SchemaState`` that can be compared against the forward-introspected model state. """ from __future__ impor...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/migrations/db_introspector.py
.py
137e96c866e0b58c
8.02
10
""" Migration executor for applying migrations to the database. This module handles: - Tracking applied migrations in the database - Applying pending migrations - Rolling back migrations - Executing data migrations (upgrade command) """ import importlib.util import logging from pathlib import Path from typing import ...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/migrations/executor.py
.py
ed32dc87392ae55b
7.52
10
""" Model introspection for migration generation. This module extracts schema information from Pydantic models to build a SchemaState that can be compared against the current database state. """ import types from typing import TYPE_CHECKING, Any, get_args, get_origin, get_type_hints from pydantic.fields import Field...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/migrations/introspector.py
.py
f6629507441d10a8
8.02
10
""" Migration class and utilities for SurrealDB schema migrations. A Migration represents a set of operations to be applied to the database in a specific order, with optional dependencies on other migrations. """ from dataclasses import dataclass, field from datetime import UTC, datetime from typing import TYPE_CHECK...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/migrations/migration.py
.py
f2bd5948b2a9f7a7
7.52
10
""" Model code generator from schema state. Generates Python source code for ``BaseSurrealModel`` subclasses from a ``SchemaState`` obtained via ``DatabaseIntrospector``. This is the reverse of the ``ModelIntrospector`` → ``SchemaState`` path used by ``makemigrations``. """ from __future__ import annotations import...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/migrations/model_generator.py
.py
0620edc2579ced80
7.52
10
""" Prefetch descriptor for fine-grained control over ``prefetch_related()``. A ``Prefetch`` object lets you customise which related objects are loaded and how they are attached to the parent instances. Example:: from surreal_orm import Prefetch # Default prefetch (equivalent to a plain string) users = ...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/prefetch.py
.py
f8080809a13aca7e
7.52
10
""" Q objects for building complex query expressions with AND, OR, and NOT logic. Usage: from surreal_orm import Q # OR query users = await User.objects().filter( Q(name__contains="alice") | Q(email__contains="alice"), ).exec() # AND with OR users = await User.objects().filter( ...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/q.py
.py
9209088a791cd015
7.52
10
""" Subquery class for embedding a QuerySet as a filter value in another QuerySet. Subqueries are compiled to inline sub-SELECT expressions with parameterized variables that are remapped to avoid collisions with the outer query. Example:: from surreal_orm import Subquery # Users whose age matches any active...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/subquery.py
.py
1f398b645303f0a1
7.52
10
""" Declarative test fixtures for SurrealDB ORM. Provides ``SurrealFixture`` base class and ``@fixture`` decorator for defining reusable test data that is automatically saved to and cleaned up from the database. Example:: from surreal_orm.testing import SurrealFixture, fixture @fixture class UserFixture...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/testing/fixtures.py
.py
bd12336aefaa9e7f
8.02
10
""" Type definitions for SurrealDB ORM. This module contains enums and type definitions used throughout the ORM for table types, schema modes, and field types. """ from enum import StrEnum class TableType(StrEnum): """ Table type classification for migration behavior and connection preferences. Each ta...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/types.py
.py
c6184c3e20d4a7b6
7.52
10
import asyncio import functools import json import logging import random import re from collections.abc import Callable from typing import Any, TypeVar logger = logging.getLogger(__name__) F = TypeVar("F", bound=Callable[..., Any]) # Shared identifier validation regex — used by query_set, model_base, aggregations, e...
EulogySnowfall/SurrealDB-ORM
src/surreal_orm/utils.py
.py
80a137d960073edf
7.52
10
""" SurrealDB SDK - A custom Python SDK for SurrealDB. This SDK provides direct connection to SurrealDB via HTTP and WebSocket without depending on the official surrealdb package. Supports: - HTTP connections (stateless, ideal for microservices) - WebSocket connections (stateful, for real-time features) - Live Querie...
EulogySnowfall/SurrealDB-ORM
src/surreal_sdk/__init__.py
.py
8e872788725d979b
7.52
10
import os from time import sleep from assertpy import assert_that from integration_tests.deployment.aws.utils.awslambda import invoke_lambda from integration_tests.deployment.aws.utils.dynamodb import vulnerability_detected_in_time_period from integration_tests.deployment.aws.utils.general import random_string from i...
domain-protect/terraform-aws-domain-protect
integration_tests/deployment/aws/test_vulnerabilities.py
.py
b5b13919896b700c
7.13
17
# Cloudflare Python version 3.1.1 import os from time import sleep from assertpy import assert_that from integration_tests.deployment.aws.utils.awslambda import invoke_lambda from integration_tests.deployment.aws.utils.dynamodb import vulnerability_detected_in_time_period from integration_tests.deployment.aws.utils.g...
domain-protect/terraform-aws-domain-protect
integration_tests/deployment/cloudflare/test_cf_vulnerabilities.py
.py
93fb96b1cf0f1e75
7.13
17
# Currently not in use - written for Cloudflare Python v2, needs update for v4 # Ignored by pytest.ini file import uuid class Zone: def __init__(self, name) -> None: self.Name = name self.Id = uuid.uuid4().hex self.dns_records = [] class DNSRecord: def __init__(self, name, record_typ...
domain-protect/terraform-aws-domain-protect
integration_tests/mocks/cloudflare_mock.py
.py
d26a67ae89c85bec
7.13
17
from functools import wraps from typing import Any, Callable def require_admin(require_guild: bool = True) -> Callable: """Enforce admin role and optional guild context for command handlers.""" def decorator(func: Callable) -> Callable: @wraps(func) async def wrapper(*args: Any, **kwargs: Any...
compsci-adl/duckbot
src/commands/command_helpers.py
.py
af3a77edfbfbed13
7.65
19
import csv import logging import os import os.path import random import re import tempfile import time from collections import defaultdict from enum import IntEnum from typing import List, Optional import requests from discord import Embed from dotenv import load_dotenv from google import genai from google.genai impor...
compsci-adl/duckbot
src/commands/gemini.py
.py
e888239c468eabfb
7.65
19
from discord import ( ButtonStyle, Color, Embed, Interaction, SelectOption, app_commands, ui, ) class HelpMenu(ui.View): currentpage: int = 0 commands = [] maxpages: int def __init__(self, client): super().__init__() self.value = None # Fetch global...
compsci-adl/duckbot
src/commands/help_menu.py
.py
4cb1f938d8bde885
7.65
19
import asyncio import logging from functools import wraps from pathlib import Path from typing import List import aiosqlite def get_db_folder(): """Gets the database folder, and creates one if it doesn't exist""" db_dir = Path.cwd() / "db" db_dir.mkdir(exist_ok=True) return db_dir class Database: ...
compsci-adl/duckbot
src/models/database.py
.py
664f95658087331c
7.65
19
import sqlite3 from pathlib import Path from models.schema.admin_settings_sql import AdminSettingsSQL class AdminSettingsDB: def __init__(self, db_path: str = "db/admin_settings.db"): # Ensure the data directory exists Path(db_path).parent.mkdir(parents=True, exist_ok=True) self.db_path ...
compsci-adl/duckbot
src/models/databases/admin_settings_db.py
.py
108419a0b2cafe2e
7.65
19
from models.database import Database from models.databases.admin_settings_db import AdminSettingsDB from models.schema.skullboard_sql import SkullSQL from utils import time class SkullboardDB(Database): """Singleton class for the skullboard Database""" _instance = None def __new__(cls, *args, **kwargs):...
compsci-adl/duckbot
src/models/databases/skullboard_database.py
.py
8dd45db1d6de70be
7.65
19
import logging import os from datetime import datetime, timezone from typing import Any, Dict, List, Optional from zoneinfo import ZoneInfo import requests from utils import cms_helpers _raw_cms_url = (os.getenv("CMS_URL") or "").strip().strip('"').strip("'").rstrip("/") if not _raw_cms_url: _raw_cms_url = "http...
compsci-adl/duckbot
src/utils/cms.py
.py
725a9295e715319b
7.65
19
from __future__ import annotations from typing import Any, Dict, List def summarise_docs( docs: List[Dict[str, Any]], title_key: str = "title", desc_keys: List[str] = ["details", "description"], max_items: int = 100, desc_limit: int = 200, prefix: str | None = None, ) -> str: """Return a ...
compsci-adl/duckbot
src/utils/cms_helpers.py
.py
89f4225b563bcc41
7.65
19
import logging from discord.enums import EventStatus def get_event_role_name(event_name: str) -> str: """Return the role name for a given event.""" return f"Event: {event_name}" class EventRoleManager: """Manages auto-assignment and deletion of event notification roles.""" def __init__(self, bot):...
compsci-adl/duckbot
src/utils/event_roles.py
.py
9f8015504d7d2bd5
7.65
19
from __future__ import annotations import difflib import logging import re from typing import Optional from utils import cms def matches_any(tokens: list[str], keywords: list[str], cutoff: float = 0.8) -> bool: """Return True if any token approximately matches any keyword. Uses difflib.get_close_matches fo...
compsci-adl/duckbot
src/utils/gemini_rag.py
.py
09d01b1b3a66bff8
7.65
19
import datetime import os import re import aiohttp import discord import Levenshtein from dotenv import load_dotenv from models.databases.admin_settings_db import AdminSettingsDB # Load environment variables from .env file load_dotenv() CMS_URL = os.getenv("CMS_URL") KNOWN_SPAM_MESSAGES_URL = f"{CMS_URL}/api/known-s...
compsci-adl/duckbot
src/utils/spam_detection.py
.py
05b781d274c9914f
7.65
19
from datetime import datetime import pytz # Adelaide timezone (UTC+9:30) tz = pytz.timezone("Australia/Adelaide") def get_current_day(): """Generates a numerical value for each day""" now = datetime.now(tz) epoch = datetime(1970, 1, 1, tzinfo=tz) days_since_epoch = (now - epoch).days return days...
compsci-adl/duckbot
src/utils/time.py
.py
4a91a76ddfcc3d50
7.65
19
import numpy as np import scipy.linalg import numpy.typing as npt from pyscf import gto, scf from pyscf.lib import logger class CQED_RHF: def __init__(self, molecule: gto.Mole, lambda_vec: npt.NDArray): """Initialize RHF calculator with a PySCF Mole object.""" self.mol_ = molecule self.lam...
Yxwxwx/Model
cqed/cqed-rhf/cqed_rhf.py
.py
a511a35b6f5e9291
7.42
6
"""Reproduce Colbert–Miller JCP 96, 1982 (1992) — Section II.B, Figs. 1–2. Fig. 1: V_c large (box not limiting) → pure Δx discretisation error. Fig. 2: Δx small (discretisation not limiting) → pure V_c boundary error. """ import numpy as np from dvr import SincDVR import matplotlib matplotlib.use("Agg") import matpl...
Yxwxwx/Model
dvr/tests/simple_test.py
.py
c6f4850317604a14
7.92
6
import numpy as np import scipy.sparse import scipy.sparse.linalg import time from typing import Tuple, List, Dict class HeisenbergDMRG: """ 1D Heisenberg 模型的哈密顿量 H H = J * ∑(i=1 to L-1) S_i ⋅ S_(i+1) = J/2 * ∑(i=1 to L-1) (S⁺_i S⁻_(i+1) + S⁻_i S⁺_(i+1)) + J * ∑(i=1 to L-1) Sᶻ_i Sᶻ_(i+1) 其中: ...
Yxwxwx/Model
idmrg/superblock.py
.py
5c68e4f8e7d1a970
7.42
6
import jax import jax.numpy as jnp import flax.nnx as nnx import grain.python as grain from pathlib import Path from typing import List import matplotlib.pyplot as plt def load_stories_from_file(file_path: Path, max_stories: int = 1000) -> List[str]: """ Streams the file and splits stories, ensuring each sto...
Yxwxwx/Model
minigpt/helper.py
.py
3ea75c0c73b21d00
7.42
6
"""Asynchronous Python client for National Energy Dashboard NL.""" from __future__ import annotations from typing import Any class NedNLError(Exception): """Generic NED NL exception.""" def __init__(self, data: dict[str, Any] | str) -> None: """Initialize the exception. Args: ---- ...
klaasnicolaas/python-nednl
src/nednl/exceptions.py
.py
ade267a4b47a61b4
7.48
8
"""Asynchronous Python client for National Energy Dashboard NL.""" from __future__ import annotations import asyncio import json import socket from dataclasses import dataclass from importlib import metadata from typing import Any, Self from aiohttp import ClientError, ClientResponseError, ClientSession from aiohttp...
klaasnicolaas/python-nednl
src/nednl/nednl.py
.py
7dd8e3bdc554f0af
7.48
8
from royalur.game import Game from royalur.lut.board_encoder import SimpleGameStateEncoding from royalur.lut.reader import LutReader from royalur.model.player import PlayerType class LutAgent: """ An agent that uses a look-up table to play the game. NOTE: This agent is only for the light player. It w...
RosetteGames/royalur-python
royalur/lut/lut_player.py
.py
c5f4eafc9c75916f
7.5
9
import json from typing import Any, Dict import sys import time import numpy as np class Lut: """ This class provides a way to look up values in a Royal Game of Ur look-up table (LUT). """ def __init__( self, keys: bytes, values: bytes, file_metadata: Dict[str, Any...
RosetteGames/royalur-python
royalur/lut/reader.py
.py
07ad37d02bf160e6
7.5
9
from enum import Enum from typing import Optional class PlayerType(Enum): """ Represents the players of a game. """ LIGHT = (1, "Light", 'L') """ The light player. """ DARK = (2, "Dark", 'D') """ The dark player. """ def __init__(self, value: int, text_name: str, char...
RosetteGames/royalur-python
royalur/model/player.py
.py
48b1714c3b90659e
7.5
9
class Tile: """ Represents a position on or off the board. """ __slots__ = ("_x", "_y", "_ix", "_iy") _x: int _y: int _ix: int _iy: int def __init__(self, x: int, y: int): if x < 1 or x > 26: raise ValueError( f"x must fall within the range [1,...
RosetteGames/royalur-python
royalur/model/tile.py
.py
165c1ed770a8607f
7.5
9
from royalur.model import ( Board, BoardShape, GameMetadata, GameSettings, Move, PathPair, Piece, Dice, PlayerType, PlayerState, Roll ) from royalur.rules.state import ( GameState, WaitingForRollGameState, WaitingForMoveGameState, RolledGameState, MovedGameState, WinGameState, ) from...
RosetteGames/royalur-python
royalur/rules/simple.py
.py
a8b81637fd672608
7.5
9
from royalur.model import Board, PlayerState, PlayerType, Roll, Move from .state import OngoingGameState from overrides import overrides class PlayableGameState(OngoingGameState): """ A game state where we are waiting for interactions from a player. """ __slots__ = () @overrides def is_playab...
RosetteGames/royalur-python
royalur/rules/state/playable.py
.py
1598dc7993773f7e
7.5
9
import unittest import random from royalur import Game class TestExample(unittest.TestCase): def test_example(self): # Create a new game using the Finkel rules. game = Game.create_finkel() while not game.is_finished(): turn_player_name = game.get_turn().text_name ...
RosetteGames/royalur-python
test/test_example.py
.py
d58f37bd22b3de47
7
9
from __future__ import annotations import traceback from contextlib import contextmanager from dataclasses import dataclass from functools import partial from pathlib import Path from typing import TYPE_CHECKING import sqlparse from django import db from django.db.backends import utils as _django_utils from django.db...
MrThearMan/graphene-django-query-optimizer
example_project/app/utils.py
.py
ff712c3a9d699d70
7.66
20
from __future__ import annotations import logging import traceback from pathlib import Path from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from collections.abc import Callable logger = logging.getLogger(__name__) BASE_PATH = str(Path(__file__).resolve().parent.parent) class DotPathFormatter(logging.F...
MrThearMan/graphene-django-query-optimizer
example_project/config/logging.py
.py
aec679b25a8b5ad9
7.66
20
from __future__ import annotations import contextlib from typing import TYPE_CHECKING import graphene from graphene.utils.str_converters import to_snake_case from graphene_django.settings import graphene_settings from graphene_django.utils import DJANGO_FILTER_INSTALLED from graphql import get_argument_values from gr...
MrThearMan/graphene-django-query-optimizer
query_optimizer/filter_info.py
.py
98928783693a7233
7.66
20
from __future__ import annotations import dataclasses from copy import copy from typing import TYPE_CHECKING from django.contrib.contenttypes.fields import GenericRelation from django.core.exceptions import ValidationError from django.db import models from django.db.models import ManyToManyField, ManyToManyRel, Prefe...
MrThearMan/graphene-django-query-optimizer
query_optimizer/optimizer.py
.py
cec469c846df6a92
7.66
20
from __future__ import annotations from collections import defaultdict from typing import TYPE_CHECKING, TypeAlias from unittest.mock import patch from django.db.models import ManyToManyField from django.db.models.fields.related_descriptors import _filter_prefetch_queryset from .settings import optimizer_settings i...
MrThearMan/graphene-django-query-optimizer
query_optimizer/prefetch_hack.py
.py
1ae64c5ee02ec428
7.66
20
from __future__ import annotations from typing import TYPE_CHECKING import graphene import graphene_django from django_filters.constants import ALL_FIELDS from graphene_django.utils import is_valid_django_model from .compiler import optimize_single from .settings import optimizer_settings from .typing import Optimiz...
MrThearMan/graphene-django-query-optimizer
query_optimizer/types.py
.py
ccadfaff4a03924f
7.66
20
from __future__ import annotations import logging from typing import TYPE_CHECKING from django.db import models from django.db.models.manager import BaseManager from .settings import optimizer_settings if TYPE_CHECKING: from .typing import Any, ParamSpec, TypeVar, Union T = TypeVar("T") P = ParamSpec("...
MrThearMan/graphene-django-query-optimizer
query_optimizer/utils.py
.py
e6239f3cf4e614b7
7.66
20
from __future__ import annotations from graphene_django.settings import graphene_settings from graphql_relay import cursor_to_offset from .typing import TypedDict __all__ = [ "validate_pagination_args", ] class PaginationArgs(TypedDict): after: int | None before: int | None first: int | None la...
MrThearMan/graphene-django-query-optimizer
query_optimizer/validators.py
.py
2e6113d4affb66ea
7.66
20
""" Definition of heuristic and policy neural networks and parallel functions """ from abc import abstractmethod, ABC from typing import List, Any, TypeVar, Tuple, Optional, Generic, Type from deepxube.base.nnet_input import NNetInput, PolicyNNetIn import torch from torch import nn, Tensor from torch import optim fro...
forestagostinelli/deepxube
deepxube/base/nnet.py
.py
fbd1db9f98215ece
7.64
18
from typing import List, Tuple, Optional, cast import torch from torch import Tensor import torch.nn as nn from torch.multiprocessing import Queue, get_context from deepxube.base.domain import Domain, ActsEnum, StartGoalWalkable, State, Goal, Action from deepxube.pytorch.nnet_utils import NNetPar from deepxube.base.n...
forestagostinelli/deepxube
deepxube/tests_cli/time_tests.py
.py
3d978ee593a88fc2
7.14
18
# wom.py - An asynchronous wrapper for the Wise Old Man API. # Copyright (c) 2023-present Jonxslays # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without li...
Jonxslays/wom.py
tests/services/test_base.py
.py
11762dbd5182ed90
7.07
13
# wom.py - An asynchronous wrapper for the Wise Old Man API. # Copyright (c) 2023-present Jonxslays # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without li...
Jonxslays/wom.py
tests/services/test_behavior.py
.py
a749d9ffcd6bc108
8.07
13
# wom.py - An asynchronous wrapper for the Wise Old Man API. # Copyright (c) 2023-present Jonxslays # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without li...
Jonxslays/wom.py
tests/test_enums.py
.py
6eec34a09f7d38c5
7.07
13
# wom.py - An asynchronous wrapper for the Wise Old Man API. # Copyright (c) 2023-present Jonxslays # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without li...
Jonxslays/wom.py
tests/test_models.py
.py
cba0a25518e06f08
7.07
13
# wom.py - An asynchronous wrapper for the Wise Old Man API. # Copyright (c) 2023-present Jonxslays # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without li...
Jonxslays/wom.py
tests/test_result.py
.py
b5aade6bb927ff5d
7.07
13
# wom.py - An asynchronous wrapper for the Wise Old Man API. # Copyright (c) 2023-present Jonxslays # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without li...
Jonxslays/wom.py
tests/test_routes.py
.py
02b03f3e3a9fbaad
7.07
13
# wom.py - An asynchronous wrapper for the Wise Old Man API. # Copyright (c) 2023-present Jonxslays # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without li...
Jonxslays/wom.py
tests/test_serializer.py
.py
80078d021583981a
7.07
13
# wom.py - An asynchronous wrapper for the Wise Old Man API. # Copyright (c) 2023-present Jonxslays # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without li...
Jonxslays/wom.py
wom/enums.py
.py
498df09f9a6b621e
7.57
13
# wom.py - An asynchronous wrapper for the Wise Old Man API. # Copyright (c) 2023-present Jonxslays # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without li...
Jonxslays/wom.py
wom/models/competitions/models.py
.py
f52ff2a22602fc03
7.57
13
# wom.py - An asynchronous wrapper for the Wise Old Man API. # Copyright (c) 2023-present Jonxslays # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without li...
Jonxslays/wom.py
wom/models/groups/enums.py
.py
6ec2cd2c7e4c6feb
7.57
13
# wom.py - An asynchronous wrapper for the Wise Old Man API. # Copyright (c) 2023-present Jonxslays # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without li...
Jonxslays/wom.py
wom/models/names/models.py
.py
e5e4626bc04f72f3
7.57
13
# wom.py - An asynchronous wrapper for the Wise Old Man API. # Copyright (c) 2023-present Jonxslays # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without li...
Jonxslays/wom.py
wom/models/players/enums.py
.py
1735a6259b66d0ec
7.57
13
"""Define Microsoft providers.""" from __future__ import annotations import asyncio from typing import Final from msal import PublicClientApplication from liminal.auth import AuthProvider from liminal.auth.microsoft.models import ( MSALCacheTokenResponse, MSALIdentityProviderTokenResponse, ) from liminal.co...
liminal-ai-security/liminal-sdk-python
liminal/auth/microsoft/device_code_flow.py
.py
34a219571e94b1fe
7.42
6
"""Define models for the auth endpoint.""" from __future__ import annotations from dataclasses import dataclass from typing import Literal from liminal.helpers.model import BaseModel @dataclass(frozen=True, kw_only=True) class MSALCacheTokenResponse(BaseModel): """Define an MSAL token response from Entra ID.""...
liminal-ai-security/liminal-sdk-python
liminal/auth/microsoft/models.py
.py
4bd079bb4a969bdb
7.42
6
"""Define the LLM endpoint.""" from __future__ import annotations from collections.abc import Awaitable, Callable from typing import cast from liminal.endpoints.llm.models import ModelInstance from liminal.endpoints.llm.schemas import GetAvailableModelInstancesResponse from liminal.errors import ModelInstanceUnknown...
liminal-ai-security/liminal-sdk-python
liminal/endpoints/llm/__init__.py
.py
f9b6a68132f3e053
7.42
6
"""Define models for the LLM endpoint.""" from __future__ import annotations from dataclasses import dataclass, field from datetime import datetime from enum import StrEnum from typing import Literal from mashumaro import field_options from liminal.endpoints.llm.models import ModelInstance from liminal.helpers.mode...
liminal-ai-security/liminal-sdk-python
liminal/endpoints/thread/models.py
.py
0b6a0ef57db08578
7.42
6
"""Define Microsoft auth tests tests.""" from __future__ import annotations from typing import NamedTuple from unittest.mock import Mock import httpx import pytest from pytest_httpx import HTTPXMock from liminal import Client from liminal.auth.microsoft.device_code_flow import DeviceCodeFlowProvider from liminal.er...
liminal-ai-security/liminal-sdk-python
tests/auth/test_microsoft.py
.py
fb0f0d39aef4551c
7.92
6
"""Define LLM endpoint tests.""" from __future__ import annotations from datetime import UTC, datetime from typing import Any, NamedTuple import pytest from pytest_httpx import HTTPXMock from liminal import Client from liminal.errors import ModelInstanceUnknownError from tests.common import TEST_API_SERVER_URL @p...
liminal-ai-security/liminal-sdk-python
tests/test_llm.py
.py
aa281e2fd5500a43
7.92
6
from typing import Any, Dict def get_msg_template(method: str) -> Dict[str, Any]: ''' Create generic message template for the given method call. ''' message = {} message["method"] = method message["data"] = {} return message def geometry_to_json(x: float, y: float, w: float, h: float): ...
WayfireWM/pywayfire
wayfire/core/template.py
.py
8d9467a144c40757
7.15
19
# SPDX-FileCopyrightText: 2024-present Hasan Sezer Tasan <hasansezertasan@gmail.com> # # SPDX-License-Identifier: MIT """ Basic FastUI Admin example with User and Post models. Run with: uvicorn examples.basic.main:app --reload --port 5000 Then visit: http://localhost:5000/admin/ """ from __future__ import an...
hasansezertasan/fastui-admin
examples/basic/main.py
.py
ea1718528ead86a7
7.45
7