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
"""Resolve the package's settings, lazily, from three sources. A project configures the package through one ``TELEGRAM_BOT`` dict in its Django settings. Anything it leaves out is looked for in the environment, and anything the environment leaves out comes from :mod:`django_redis_aiogram.defaults`. Nothing here reads...
CorneiZeR/django-redis-aiogram
src/django_redis_aiogram/settings.py
.py
6ace9cea99fe368c
7.63
17
"""Pace outgoing calls to stay under Telegram's published limits. Retrying on ``TelegramRetryAfter`` is reactive: the message has already been refused and the bot has already been told to back off. These limits are documented, so the sane thing is not to exceed them in the first place. Telegram enforces three at once...
CorneiZeR/django-redis-aiogram
src/django_redis_aiogram/throttling.py
.py
7a3502e70d3676f9
7.63
17
"""Receive updates over HTTP instead of polling for them. Long polling needs a process that runs forever. A webhook does not: Telegram posts each update to a URL, so the update arrives in whichever process serves that URL — normally the web one. The view is deliberately synchronous. An async view would run on the ser...
CorneiZeR/django-redis-aiogram
src/django_redis_aiogram/webhook.py
.py
7d3999058754ef34
7.63
17
import fakeredis import fakeredis.aioredis import pytest from django_redis_aiogram import conf # `django_redis_aiogram.bot` is the singleton instance, so the class lives in # `client`; patching the wrong one silently leaves the real connection in place. PATCH_TARGETS = ( 'django_redis_aiogram.redis.get_redis', ...
CorneiZeR/django-redis-aiogram
tests/conftest.py
.py
49a0455f5be963a7
8.13
17
"""Guards for the database suite. Run it with its own settings module: python -m pytest --ds=tests.db_settings tests/db """ import threading import pytest from django.conf import settings from django_redis_aiogram.recorder import WRITER_THREAD, recorder @pytest.fixture(autouse=True) def _no_writer_outlives_i...
CorneiZeR/django-redis-aiogram
tests/db/conftest.py
.py
9353b4abe3bfcc2c
8.13
17
"""The admin: what it shows, what it refuses, and what it will not ask the database.""" import os import subprocess import sys import textwrap import pytest from django.contrib.auth.models import Permission, User from django.db import connection from django.test import override_settings from django.test.utils import ...
CorneiZeR/django-redis-aiogram
tests/db/test_admin.py
.py
e65c9751d95d61e3
7.13
17
"""The table, the migration and the permission surface it creates.""" import io import time import pytest from django.contrib.auth.models import Permission from django.core.management import call_command from django.db import connection from django_redis_aiogram.events import new_correlation_id from django_redis_aio...
CorneiZeR/django-redis-aiogram
tests/db/test_event_log_model.py
.py
7f2278e75fc3739c
8.13
17
"""The database suite's own wiring, asserted before anything relies on it. Every test below fails if `--ds=tests.db_settings` is not in effect, which is the point: the harness is what the rest of this directory is built on. """ import threading import pytest from django.conf import settings from django.contrib.auth ...
CorneiZeR/django-redis-aiogram
tests/db/test_harness.py
.py
1774c3da828b0b37
8.13
17
"""What the middleware and the storage wrapper record, and what they cost off.""" import asyncio from datetime import datetime, timezone import pytest from aiogram import Bot, Dispatcher, Router from aiogram.client.default import DefaultBotProperties from aiogram.dispatcher.event.bases import UNHANDLED from aiogram.f...
CorneiZeR/django-redis-aiogram
tests/db/test_inbound.py
.py
564403d34df504ed
8.13
17
"""Every stage of an outbound message, and the ones that used to leave no trace. Four of these cover sends that were dropped with nothing but a log line before 3.0: refused because the bot was shutting down, refused because the loop was closed, dropped in the hand-off, and cancelled at shutdown. """ import asyncio im...
CorneiZeR/django-redis-aiogram
tests/db/test_outbound.py
.py
b9aeedfc4c115034
7.13
17
"""The only thing that bounds the table's growth.""" import datetime from io import StringIO import pytest from django.core.management import CommandError, call_command from django.db import connection from django.test import override_settings from django.test.utils import CaptureQueriesContext from django.utils impo...
CorneiZeR/django-redis-aiogram
tests/db/test_prune.py
.py
a594be36d47d0d5a
8.13
17
# -*- coding: utf-8 -*- """Definition of Article View in Django Admin Space""" from django.contrib import admin from unfold.admin import ModelAdmin, TabularInline from .models import Article, FeedPosition, ArticleGroup # Register your models here. class FeedPositionInline(TabularInline): """Table of feeds to be...
vanalmsick/news_platform
articles/admin.py
.py
e52f7cd871c360ab
7.52
10
# -*- coding: utf-8 -*- """Containing all Django models related to an individual article/video""" import urllib from django.db import models from django.db.models import Max, Min from django.db.models.signals import post_delete, pre_delete, post_save, pre_save from django.dispatch import receiver from feeds.models i...
vanalmsick/news_platform
articles/models.py
.py
15561613e7673526
7.52
10
# -*- coding: utf-8 -*- """Bounded HTTP helpers for the scrapers. `requests.get(url)` buffers the *entire* response body into memory before it returns. Every article in every feed is fetched this way, so a single mis-advertised URL - a PDF, a video file, a CDN error page that streams megabytes of HTML - is enough to s...
vanalmsick/news_platform
feed_scraper/http_utils.py
.py
06310eb55801502b
7.52
10
# -*- coding: utf-8 -*- """Definition of Publisher and Feed Views in Django Admin Space""" from django.contrib import admin from django.contrib.auth.models import Group, User from import_export import resources from import_export.admin import ImportExportModelAdmin from unfold.admin import ModelAdmin, TabularInline fr...
vanalmsick/news_platform
feeds/admin.py
.py
9ffbcea71985fdf3
7.52
10
# -*- coding: utf-8 -*- from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver NEWS_IMPORTANCE = [ (4, "Lead Articles News"), (3, "Breaking & Top News"), (2, "Frontpage News"), (1, "Latest News"), (0, "Normal"), ] YES_NO = [("Y", "Yes"), ("N...
vanalmsick/news_platform
feeds/models.py
.py
797cebcefb7c36e4
7.52
10
#!/usr/bin/env python # -*- coding: utf-8 -*- """Django's command-line utility for administrative tasks.""" import datetime import os import sys import warnings from dotenv import load_dotenv from news_platform.pwa_splash_screen_generator import create as create_splash_screens def __ensure_db_migration_folders_exi...
vanalmsick/news_platform
manage.py
.py
f6fa579c2fcbd30b
7.52
10
# -*- coding: utf-8 -*- """Django Admin Space for Market Data App/Models""" from django.contrib import admin from import_export import resources from import_export.admin import ImportExportModelAdmin from unfold.admin import ModelAdmin from unfold.contrib.import_export.forms import ExportForm, ImportForm from .models...
vanalmsick/news_platform
markets/admin.py
.py
87b2f979881a290f
7.52
10
# -*- coding: utf-8 -*- """All Market Data Models""" from django.db import models # Create your models here. class DataGroup(models.Model): """Django Model to group market data sources e.g. equities, bonds etc.""" name = models.CharField(max_length=200) position = models.IntegerField() def __str__(...
vanalmsick/news_platform
markets/models.py
.py
7e4daed9217cde39
7.52
10
# -*- coding: utf-8 -*- """Get article data for all views""" import datetime import functools import urllib import operator from django.conf import settings from django.core.cache import cache from django.db.models import F, Q from django.forms.models import model_to_dict from django.http import HttpResponse from dja...
vanalmsick/news_platform
news_platform/pages/pageAPI.py
.py
48f401b43709fe0e
7.52
10
# -*- coding: utf-8 -*- from django import forms from django.conf import settings from django.contrib.auth import authenticate, login from django.shortcuts import redirect, render from articles.models import Article class LoginForm(forms.Form): """Form used on login page to enter password of default user.""" ...
vanalmsick/news_platform
news_platform/pages/pageLogin.py
.py
e0c958f606ca56bd
7.52
10
# -*- coding: utf-8 -*- """models for App called Preferences""" from urllib.parse import parse_qs from django.db import models def url_parm_encode(**kwargs): """function too translate url parameters from GET request in dictionary to hash string""" kwargs = {k: ",".join(v if isinstance(v, list) else [v]).spl...
vanalmsick/news_platform
preferences/models.py
.py
bfad4e4688df57f2
7.52
10
#!/usr/bin/env python3 """ Script to automatically rewrite custom docs sections in README files. This script extracts the generate workflow documentation from ai_clothes_changer/README.md and rewrites it into all README files that have generate methods and custom docs sections. """ import re from pathlib import Path ...
magichourhq/magic-hour-python
codemod/populate_custom_docs.py
.py
3fe6761e40f2e516
7.6
15
import enum import typing class Environment(enum.Enum): """Pre-defined base URLs for the API""" ENVIRONMENT = "https://api.magichour.ai" MOCK_SERVER = "https://api.sideko.dev/v1/mock/magichour/magic-hour/0.75.2" def _get_base_url( *, base_url: typing.Optional[str] = None, environment: Environment )...
magichourhq/magic-hour-python
magic_hour/environment.py
.py
3b459539de871e51
7.6
15
import datetime import pytest import httpx from pathlib import Path from typing import Any, Generator, Literal, Union, List from unittest.mock import Mock, AsyncMock from magic_hour.types import models from magic_hour.resources.v1.audio_projects.client import ( AudioProjectsClient, AsyncAudioProjectsClient, ) ...
magichourhq/magic-hour-python
magic_hour/resources/v1/audio_projects/client_test.py
.py
9f59ccb5981cf534
7.1
15
''' PyTorch has its own implementation of backward function for SVD https://github.com/pytorch/pytorch/blob/291746f11047361100102577ce7d1cfa1833be50/tools/autograd/templates/Functions.cpp#L1577 We reimplement it with a safe inverse function (Lorentzian broadening) in case of degenerated singular values. Theories and d...
sjdu10/vmc_torch
build/lib/vmc_torch/torch_utils.py
.py
f1d847778061f7d6
7.42
6
import os os.environ["OPENBLAS_NUM_THREADS"] = '1' os.environ['MKL_NUM_THREADS'] = '1' os.environ["OMP_NUM_THREADS"] = '1' import numpy as np from mpi4py import MPI # torch import torch # quimb from autoray import do from .global_var import DEBUG, set_debug COMM = MPI.COMM_WORLD SIZE = COMM.Get_size() RANK = COMM.Ge...
sjdu10/vmc_torch
build/lib/vmc_torch/variational_state.py
.py
c32c32e2e22b6051
7.42
6
"""GPU wavefunction base class with single-sample amplitude + auto-vmap. All subclasses define a single-sample amplitude: amplitude(x, params_list) x: (N_sites,) int64 — one configuration params_list: list of parameter tensors returns: scalar amplitude The base class vmaps i...
sjdu10/vmc_torch
vmc_torch/GPU/models/_base.py
.py
6eb3a1eea3ced5a1
7.42
6
"""Pure neural-network wavefunction model for GPU VMC. Architecture: x: (N_sites,) int64 -> embedding lookup (N_sites, embed_dim) -> flatten (N_sites * embed_dim,) -> [Linear -> Tanh] x n_layers -> Linear scalar real Parameter layout in self.params (ParameterList indice...
sjdu10/vmc_torch
vmc_torch/GPU/models/pureNN.py
.py
260fd4ec2073ee42
7.42
6
"""Slater determinant wavefunction model for GPU VMC. psi(x) = det( M[occupied, :] ) For spinful fermions with quimb encoding {0=empty, 1=↓, 2=↑, 3=↑↓}: 1. Convert x to binary occupation: n = [spin_up | spin_dn] 2. occupied = argsort(n, descending)[:N_f] (vmap-friendly) 3. psi = det(M[occupied]) """ ...
sjdu10/vmc_torch
vmc_torch/GPU/models/slater.py
.py
29d69748d632fe44
7.42
6
"""VMC run setup: walker initialization. TN-specific setup moved to ``tensor_network/utils.py`` (``setup_linalg_hooks``, ``load_or_generate_peps``, ``generate_random_spin_peps``); it is re-exported below so existing imports keep working. New code should take those from ``vmc_torch.GPU.tensor_network.utils``. """ impo...
sjdu10/vmc_torch
vmc_torch/GPU/vmc_setup.py
.py
57a02f21ca48f424
7.42
6
"""FAISS-based KNN classifiers for multiclass and multilabel classification.""" import contextlib import sys from typing import Any, Literal, Self import numpy as np if sys.platform == "linux": import torch # before faiss on linux, after on macos (torchgeo/torchgeo-bench#152) try: import faiss except Modul...
isaaccorley/faissknn
src/faissknn/knn.py
.py
f765e7ec90a0cec2
7.48
8
"""Regression test for GH #14: GPU search not stream-ordered off cuda:0. ``faiss.contrib.torch_utils`` syncs faiss's stream against ``torch.cuda.current_device()``, not the device the index actually lives on. Selecting a non-default GPU the idiomatic way (``.to("cuda:N")``, no device context) left faiss's search racin...
isaaccorley/faissknn
tests/test_gpu_stream_ordering.py
.py
5af0f967b283bca1
7.98
8
from collections.abc import Sequence import numpy as np import pytest from faissknn import FaissKNNClassifier, FaissKNNMultilabelClassifier @pytest.mark.parametrize("metric", ["l2", "ip", "cosine"]) def test_multiclass_knn(metric: str, device: str, multiclass_dataset: Sequence[np.ndarray]): x_train, y_train, x_...
isaaccorley/faissknn
tests/test_knn.py
.py
fe9c5dac6f2f03a5
7.98
8
"""End-to-end regression tests against trusted reference implementations. These tests ensure that public ``predict`` / ``predict_proba`` outputs from ``FaissKNNClassifier`` and ``FaissKNNMultilabelClassifier`` agree with independent reference implementations on deterministic dummy data — so refactors can't silently ch...
isaaccorley/faissknn
tests/test_regression.py
.py
be84ecf01bb363c8
7.98
8
#!/usr/bin/env python3 """Named read-only audit packs for Ask-AI device diagnostics. Each pack is an ordered list of (section, command) pairs collected in ONE SSH session. Every command must individually satisfy the Ask-AI read-only policy; that is asserted at import time so any drift between these packs and ai_comma...
aliaydemir/lldpq-src
html/ai_audit_packs.py
.py
55f5bdb0ed99256c
7.59
14
#!/usr/bin/env python3 """Strict command policy for Ask-AI live device diagnostics. The regular Device Details command runner supports interactive workflows and has its own broader policy. Ask-AI is exposed to model-generated text, so it gets a separate fail-closed policy: one diagnostic command, no shell composition,...
aliaydemir/lldpq-src
html/ai_command_policy.py
.py
4c9cb06144d5bda2
7.59
14
#!/usr/bin/env python3 """Keyed runbook knowledge base for Ask-AI. Deep Cumulus/EVPN/RoCE troubleshooting knowledge lives here instead of the cached system prompt. Only :func:`kb_digest` (a ~10 line catalog) belongs in the prompt; :func:`kb_select` runs a deterministic alias-token matcher over the operator question a...
aliaydemir/lldpq-src
html/ai_kb.py
.py
5f0dfcc16a8df655
7.59
14
#!/usr/bin/env python3 """Best-effort per-domain event sidecars for the Timeline page. Analyzers publish compact, uniform event records into monitor-results/events/<domain>.json so the Timeline page can merge every domain client-side without touching the multi-megabyte history monoliths. Contract (mirrors the lldp_ne...
aliaydemir/lldpq-src
lldpq/analysis_events.py
.py
c933ae72a3ba7653
7.59
14
#!/usr/bin/env python3 """Producer/validator sha256 handshake for large analyzer JSON artifacts. Analyzers emit their JSON state through json.dump/json.dumps (or an encoder walking the same containers), so a successfully written file is valid JSON by construction. Post-run validation therefore only needs to prove the...
aliaydemir/lldpq-src
lldpq/analysis_sidecar.py
.py
dd616c43583321f1
7.59
14
#!/usr/bin/env python3 """Validated, structured reader for the Assets web API.""" from __future__ import annotations from datetime import datetime import math import os from pathlib import Path import time from typing import Any try: from .collection_freshness import ( asset_timestamp_tolerance_seconds, ...
aliaydemir/lldpq-src
lldpq/assets_api.py
.py
b632ab6b75e676e4
7.59
14
import os import sys import time from pathlib import Path import httpx from invoke import Context, Exit, task CURRENT_DIRECTORY = Path(__file__).resolve() DOCUMENTATION_DIRECTORY = CURRENT_DIRECTORY.parent / "docs" MAIN_DIRECTORY_PATH = Path(__file__).parent infrahub_address = os.getenv("INFRAHUB_ADDRESS") INFRAHUB...
opsmill/infrahub-demo-service-catalog
tasks.py
.py
d64ce9c380676bcd
7.48
8
import json import os from pathlib import Path from typing import Any import psutil import pytest from fast_depends import Provider, dependency_provider from pytest_httpx import HTTPXMock from infrahub_sdk import Config, InfrahubClientSync from infrahub_sdk.ctl.repository import get_repository_config from infrahub_sd...
opsmill/infrahub-demo-service-catalog
tests/conftest.py
.py
2885887193d26fb2
7.98
8
"""Which image and tag the integration stack runs, resolved in one place. ``infrahub_testcontainers.container`` keeps its defaults in a module-level ``PROJECT_ENV_VARIABLES`` dict. That dict is consulted against ``os.environ`` when the ``.env`` file is written (``container.py:182-183``), so an environment override doe...
opsmill/infrahub-demo-service-catalog
tests/integration/stack_config.py
.py
b701b18b817579a2
7.98
8
import ipaddress import logging from collections.abc import Generator from pathlib import Path import pytest from fast_depends import Provider, dependency_provider from streamlit.testing.v1 import AppTest from infrahub_sdk.client import InfrahubClient, InfrahubClientSync from infrahub_sdk.protocols import CoreGeneric...
opsmill/infrahub-demo-service-catalog
tests/integration/test_create_service.py
.py
c4b425176f8e4920
7.98
8
"""Stack image resolution, which decides what the integration suite actually tests. Marked ``offline``: this reads no deployment, only the resolution logic. """ from __future__ import annotations import pytest from .stack_config import DEFAULT_IMAGE_REPOSITORY, StackImage, resolve_stack_image pytestmark = pytest.m...
opsmill/infrahub-demo-service-catalog
tests/integration/test_stack_config.py
.py
f2e07cf3c8a2b3bf
7.98
8
# -*- coding: utf-8 -*- """ EO Readers - Electro-Optical imagery readers. Provides readers for visible, panchromatic, and VIS/NIR satellite imagery. Planned sensors include Landsat OLI, Sentinel-2, HLS, WorldView, PlanetScope, Pleiades/SPOT, and NAIP. Dependencies ------------ rasterio glymur (for JPEG2000 formats) ...
GEOINT/grdl
grdl/IO/eo/__init__.py
.py
22f1e521cca675ae
7.42
6
# -*- coding: utf-8 -*- """ GeoTIFF Reader - Read GeoTIFF and Cloud-Optimized GeoTIFF imagery. Base data format reader for any GeoTIFF file regardless of modality (EO, SAR GRD, MSI, etc.). Lives at the IO level so modality submodules can use it without cross-submodule dependencies. Dependencies ------------ rasterio ...
GEOINT/grdl
grdl/IO/geotiff.py
.py
6efb0ebac0a7241d
7.42
6
# -*- coding: utf-8 -*- """ HDF5 Reader - Read HDF5 and HDF-EOS5 imagery. Base data format reader for HDF5 files regardless of producer (NASA, ASI, JAXA, etc.). Supports explicit dataset path selection or auto-detection of the first suitable numeric array. Lives at the IO level so modality submodules can use it withou...
GEOINT/grdl
grdl/IO/hdf5.py
.py
ed55f0d43010f392
7.42
6
# -*- coding: utf-8 -*- """ ASTER Reader - Read ASTER L1T and GDEM GeoTIFF products. Sensor-specific reader for ASTER (Advanced Spaceborne Thermal Emission and Reflection Radiometer) products. Wraps ``GeoTIFFReader`` for pixel access and extracts ASTER-specific metadata from GeoTIFF tags and companion XML files into a...
GEOINT/grdl
grdl/IO/ir/aster.py
.py
03beb8d11190ec08
7.42
6
# -*- coding: utf-8 -*- """ JPEG2000 Reader - Read JPEG2000 (JP2/J2K) imagery. Base data format reader for JPEG2000 files (.jp2, .j2k) regardless of producer. Unlocks Sentinel-2 native format (SAFE/JP2), Pleiades, SPOT, and EnMAP imagery. Uses rasterio (GDAL JP2 driver) as the primary backend, with glymur as a fallbac...
GEOINT/grdl
grdl/IO/jpeg2000.py
.py
701d8cd3f692c88a
7.42
6
# -*- coding: utf-8 -*- """ CRSD Metadata - Typed metadata for Compensated Radar Signal Data. Per NGA.STND.0080-1 v1.0 (2025-02-25). Covers the fields required to recover per-channel Doppler/timing behaviour: receive reference point, reference frequency, and the 2-D DwellTime / CODTime polynomials that express apertur...
GEOINT/grdl
grdl/IO/models/crsd.py
.py
481791a036c20447
7.42
6
# -*- coding: utf-8 -*- """ NISAR Metadata - Typed metadata for NASA NISAR L-band/S-band SAR data. Nested dataclass hierarchy for NISAR RSLC (Range Doppler SLC) and GSLC (Geocoded SLC) products. Fields are extracted from the NISAR HDF5 product structure under ``science/{LSAR|SSAR}/{RSLC|GSLC}/``. Dependencies ------...
GEOINT/grdl
grdl/IO/models/nisar.py
.py
4c46f4891a1642ff
7.42
6
"""Main py4web application entry point for SASEWaddle Manager.""" import os import sys import logging from py4web import action, request, response, abort, redirect, URL from py4web.core import _before_request, _after_request from py4web.utils.auth import Auth from py4web.utils.cors import cors # Setup logging logging...
penguintechinc/tobogganing
services/hub-api/app.py
.py
ee4f4897fc74a28f
7.42
6
""" JWT Token Management for SASEWaddle Manager Service Handles JWT token generation, validation, and refresh for nodes and clients """ import jwt import asyncio import time from datetime import datetime, timedelta, timezone from typing import Dict, Optional, Any, List from cryptography.hazmat.primitives import serial...
penguintechinc/tobogganing
services/hub-api/auth/jwt_manager.py
.py
d9d86f6959284bc0
7.42
6
""" User Management System for SASEWaddle Manager Supports role-based access control with admin and reporter roles """ import hashlib import secrets import sqlite3 import time from datetime import datetime, timedelta from typing import Optional, List, Dict, Any from dataclasses import dataclass from enum import Enum ...
penguintechinc/tobogganing
services/hub-api/auth/user_manager.py
.py
b38a6aa2857547d3
7.42
6
"""Database initialization and configuration for SASEWaddle Manager.""" import os from datetime import datetime from typing import Optional, List from pydal import DAL, Field from pydal.validators import * import logging logger = logging.getLogger(__name__) # Global database instances db: Optional[DAL] = None db_rea...
penguintechinc/tobogganing
services/hub-api/database/__init__.py
.py
75e1ffae9c8620a5
7.42
6
#!/usr/bin/env python3 """Initialize security tables and default configuration for SASEWaddle Manager.""" import os import sys import logging from datetime import datetime # Add the manager directory to the path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from database import get_db logger = logg...
penguintechinc/tobogganing
services/hub-api/init_security.py
.py
b80b12e06361ea09
7.42
6
#!/usr/bin/env python3 """Initialize security feeds and scanner for SASEWaddle Manager.""" import os import sys import asyncio import logging from datetime import datetime # Add the manager directory to the path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from database import get_db from security....
penguintechinc/tobogganing
services/hub-api/init_security_feeds.py
.py
2ec572c60e04eb0a
7.42
6
""" SASEWaddle License Management Handles license validation and feature gating """ import os import requests import json from functools import wraps from datetime import datetime, timedelta from typing import Optional, Dict, List, Any import structlog logger = structlog.get_logger() # License server configuration L...
penguintechinc/tobogganing
services/hub-api/licensing/__init__.py
.py
632c7a42cee33a54
7.42
6
import argparse import json import logging import os from pathlib import Path from .types import GofileUploaderLocalConfigOptions, GofileUploaderOptions from .utils import return_dict_without_none_value_keys logger = logging.getLogger(__name__) def load_config_file(config_file_path: Path) -> GofileUploaderLocalConf...
alexmi256/gofile-uploader
src/gofile_uploader/cli.py
.py
c71bbec826bd5412
7.5
9
from io import BufferedReader from pathlib import Path from typing import Callable, Optional from tqdm import tqdm def return_dict_without_none_value_keys(item: dict): return {k: v for k, v in item.items() if v is not None} class ProgressFileReader(BufferedReader): def __init__(self, filename: Path, read_c...
alexmi256/gofile-uploader
src/gofile_uploader/utils.py
.py
1f4f1b4b48347b09
7.5
9
import logging import sys import time from datetime import timedelta from enum import Enum from pathlib import Path from typing import Any import globus_sdk import globus_sdk.gare from globus_sdk.authorizers import GlobusAuthorizer from globus_sdk.scopes import GCSCollectionScopeBuilder, TransferScopes from typer impo...
argonne-lcf/FIRST
alcf_ai/src/alcf_ai/auth.py
.py
76ef5e833a0f057a
7.42
6
import logging import time from typing import Any from pydantic import BaseModel from .resource import ClientResource logger = logging.getLogger(__name__) class D3TritonRequest(BaseModel): model_name: str input_path: str output_path: str outputs: list[str] | None = None class SubmitTaskResponse(B...
argonne-lcf/FIRST
alcf_ai/src/alcf_ai/resources/d3_triton.py
.py
68dc0e9729a67a64
7.42
6
import logging import time from typing import Any from pydantic import BaseModel from .resource import ClientResource logger = logging.getLogger(__name__) class DINOv3Request(BaseModel): input_dir: str project: str | None = None checkpoint: str | None = None save_overlay: bool | None = None bat...
argonne-lcf/FIRST
alcf_ai/src/alcf_ai/resources/dinov3.py
.py
0efa1b4d3c4a088f
7.42
6
import base64 import gzip import logging import time from io import BytesIO from pathlib import Path from typing import Annotated, Any, Literal import numpy as np import numpy.typing as npt from pydantic import ( BaseModel, BeforeValidator, ConfigDict, ) from .resource import ClientResource NDArray = npt...
argonne-lcf/FIRST
alcf_ai/src/alcf_ai/resources/sam3.py
.py
41e97602a7b5f11c
7.42
6
import io import json import logging import tarfile from concurrent.futures import ProcessPoolExecutor, wait from io import BytesIO from math import ceil from pathlib import Path from typing import Any import numpy as np import numpy.typing as npt import smart_open import typer from PIL.Image import Image, fromarray f...
argonne-lcf/FIRST
alcf_ai/src/alcf_ai/sam3.py
.py
81def313c5b985ca
7.42
6
import json import globus_compute_sdk def chunked_vllm_inference_function(parameters): import os import re import signal import subprocess import sys import time import uuid from datetime import datetime # --------------------------- # Helper: run one chunk # ------------...
argonne-lcf/FIRST
compute-functions/vllm_batch_function.py
.py
494a1863c7cf5d22
7.42
6
""" Globus OAuth2 authentication utilities for dashboard. """ import hashlib import logging import globus_sdk from cachetools import TTLCache, cached from django.conf import settings from django.contrib.auth import get_user_model log = logging.getLogger(__name__) User = get_user_model() # User info class for dash...
argonne-lcf/FIRST
dashboard_async/globus_auth.py
.py
29ea37cc03bd2951
7.42
6
import json import logging import os from datetime import datetime, timezone from typing import Any """Inference Gateway Gunicorn ASGI server configuration.""" # Determine if we're in production or development environment = os.getenv("ENV", "production") # Localhost port to communicate between Nginx and Gunicorn bin...
argonne-lcf/FIRST
deploy/gateway_asgi.config.py
.py
72c30ce9a0a39901
7.42
6
from ema.config import directory_config, variable_config from ema.outputs import MATRIX_MARKET_HEADER import pandas as pd import numpy as np import scipy.sparse as sp from scipy.io import mmwrite def annotate(sparse_matrix, pas_ids, collist, genes, annotated_matrix=None, pasbed_dir=None, ...
BMGLab/PeakATail
ema/annotate/annotate.py
.py
8ce1637a3b031e67
7.52
10
from ema.config import directory_config import pybedtools import pandas as pd # Confidence tier constants TIER_1 = "TIER_1" # within known UTR TIER_2 = "TIER_2" # within UTR x multiplier (possible UTR extension) TIER_3 = "TIER_3" # within max_distance (possible novel distant PAS) INTERGENIC = "INTERGENIC" # beyon...
BMGLab/PeakATail
ema/annotate/find_close.py
.py
63ea018eb70aad9f
7.52
10
from collections import defaultdict from ema.config import directory_config as dc def parse_gtf_attributes(attr_string): """Parse GTF attribute column (col 8) into a key-value dict. GTF attributes are semicolon-delimited key-value pairs like: gene_id "ENSG00000223972"; gene_type "transcribed_unproces...
BMGLab/PeakATail
ema/annotate/gtftobed.py
.py
81e7b766eecfb552
7.52
10
import os import json import pandas as pd from typing import Optional def generate_report(results_df: pd.DataFrame, output_dir: str, reference_db: Optional[str] = None) -> str: """Generate a complete benchmark report directory. Args: results_df: DataFrame from run_benchmark() ...
BMGLab/PeakATail
ema/benchmark/report.py
.py
fa47bfa895d57864
7.52
10
import logging import os import time import json import pandas as pd from datetime import datetime from typing import List, Optional, Dict from ema.strategies import get_strategy, list_strategies log = logging.getLogger(__name__) def run_benchmark(bam_path: str, gtf_path: str, strategies: Optional...
BMGLab/PeakATail
ema/benchmark/runner.py
.py
080a01b4591717af
7.52
10
"""Decorator factory that applies the shared options to every subcommand. Usage: @click.command() @common_options() def my_cmd(threads, output, verbose, quiet, log_level, no_log_file, no_progress, config, **kwargs): ... """ from __future__ import annotations import logging from pathlib import Path...
BMGLab/PeakATail
ema/cli/common.py
.py
1a4b2a5f415e7a72
7.52
10
"""Single source of truth for every CLI flag's default value. All defaults are now derived from :class:`ema.cli.config_schema.RunConfig`, including switch-subcommand-only flags (``ema switch diff/length/match``). Adding a flag: * Add a dataclass field on RunConfig in ``ema/cli/config_schema.py``. ``DEFAULTS...
BMGLab/PeakATail
ema/cli/defaults.py
.py
5e9363b2805c723f
7.52
10
"""`ema run` — full pipeline subcommand. This module is intentionally thin. The pipeline body lives in ``ema.main`` and is not modified by the CLI overhaul. Click options are generated from :class:`ema.cli.config_schema.RunConfig`. The hand-rolled ``@click.option`` block was deleted in the centralisation refactor; ad...
BMGLab/PeakATail
ema/cli/run.py
.py
ba6db822650c1d9e
7.52
10
"""`ema switch diff` — differential APA test across cluster pairs.""" from __future__ import annotations import logging import click from ema.cli.common import ( apply_yaml_to_kwargs, common_options, parse_log_overrides, resolve_subcommand_output_dir, ) from ema.cli.defaults import DEFAULTS from ema....
BMGLab/PeakATail
ema/cli/switch_diff.py
.py
d5c2a217fd73a46a
7.52
10
"""`ema switch match` — cross-dataset cluster matching.""" from __future__ import annotations import logging import click from ema.cli.common import ( apply_yaml_to_kwargs, common_options, parse_log_overrides, resolve_subcommand_output_dir, ) from ema.cli.defaults import DEFAULTS from ema.progress im...
BMGLab/PeakATail
ema/cli/switch_match.py
.py
1bf1421f84931b02
7.52
10
"""`ema switch trend` — ordered-stage APA trend from a PDUI long table. Reads a per-cluster PDUI/proportion/entropy table (as produced by ``ema switch length``), treats the clusters as an ORDERED progression given by ``--stage-order``, and reports the trend (slope + Spearman monotonicity + direction) overall and per g...
BMGLab/PeakATail
ema/cli/switch_trend.py
.py
4066761965523c4f
7.52
10
"""YAML config loading + schema validation for `ema run`. Schema is a strict superset of today's main.py YAML reader: - `datasets` (required, list of {id, merge_strategy, bams}) - `gtf`, `output_dir`, `seqlen`, `cb_len`, `barcode_tag` - `min_read`, `min_cells`, `min_pas_per_cell`, `pas_gap` - `atlas`, `atlas_distance`...
BMGLab/PeakATail
ema/cli/yaml_loader.py
.py
2a5e241e16d5eb6f
7.52
10
"""Register the 3 built-in clustering strategies onto the registry. Algorithm code itself stays in ema/clustering/clustering.py. This file just thin-wraps the existing if/elif branches into registry entries. """ from __future__ import annotations from ema.clustering.registry import register_clustering_strategy @reg...
BMGLab/PeakATail
ema/clustering/_builtins.py
.py
904582e99a347d22
7.52
10
"""Cross-dataset cluster matching strategy registry. This module provides a pluggable registry for strategies that find cluster correspondences across multiple h5ad files and assign canonical cluster IDs. Each strategy implements ``ClusterMatchStrategy.match`` and is registered under a short name string. New strateg...
BMGLab/PeakATail
ema/clustering/cross_dataset/__init__.py
.py
349525b15e30f91d
7.52
10
"""Abstract base class for cross-dataset cluster matching strategies. Each strategy maps cluster labels from multiple h5ad files (each with their own independently-assigned leiden cluster labels) to a shared canonical ID space. Different datasets may label the same cell population with different integers (cluster_0 in...
BMGLab/PeakATail
ema/clustering/cross_dataset/base.py
.py
cd102e5adff1c738
7.52
10
"""Cell-set Jaccard cross-dataset cluster matching strategy. Algorithm --------- For each pair of datasets (A, B), this strategy directly computes the Jaccard similarity between cluster cell barcodes: J(A_i, B_j) = |CB(A_i) ∩ CB(B_j)| / |CB(A_i) ∪ CB(B_j)| where CB(X_k) is the set of cell barcodes in cluster k o...
BMGLab/PeakATail
ema/clustering/cross_dataset/jaccard.py
.py
44cb6e4ef661e724
7.52
10
"""Marker-overlap cross-dataset cluster matching strategy. Algorithm --------- 1. For each dataset, load the h5ad file and compute per-cluster marker PAS via Wilcoxon rank-sum (scanpy.tl.rank_genes_groups). The top-N marker PAS by score constitute the cluster's "fingerprint". 2. For every pair of datasets (dat...
BMGLab/PeakATail
ema/clustering/cross_dataset/marker_overlap.py
.py
69079c8051c03d10
7.52
10
"""Mutual Nearest Neighbor (MNN) cross-dataset cluster matching strategy. Algorithm --------- 1. Load all h5ad files and concatenate their cell × feature matrices along the obs axis into a single combined AnnData. A ``batch`` column records which dataset each cell comes from. 2. Re-embed all cells jointly usin...
BMGLab/PeakATail
ema/clustering/cross_dataset/mnn.py
.py
8b98191b8ee9424a
7.52
10
"""Round-trip the canonical cluster map back into each dataset's h5ad obs (B6). Bug B6: ``canonical_cluster_map.tsv`` was written but never read back into ``clusters.h5ad``. Cross-sample comparisons then silently compared per-sample ``leiden`` labels — which are NOT comparable across datasets (cluster 0 in sample A is...
BMGLab/PeakATail
ema/clustering/cross_dataset/roundtrip.py
.py
fc2d79e2a0ec935a
7.52
10
"""Clustering evaluation and comparison utilities. Provides functions for: - Comparing two clusterings (ARI, AMI) - Computing cluster quality metrics (silhouette score) - Finding marker peaks per cluster (Wilcoxon rank-sum) """ import numpy as np import pandas as pd import anndata as ad import scanpy as sc from sklea...
BMGLab/PeakATail
ema/clustering/evaluation.py
.py
1bba4f6e082fcb0d
7.52
10
from langchain_dartmouth.definitions import USER_AGENT from langchain_openai import OpenAIEmbeddings from openai import DefaultHttpxClient, DefaultAsyncHttpxClient import os from typing import Any, Callable, List, Optional from langchain_dartmouth.definitions import CLOUD_BASE_URL from langchain_dartmouth.model_listin...
dartmouth/langchain-dartmouth
src/langchain_dartmouth/embeddings.py
.py
f2d12dc5c08b4276
7.48
8
from langchain_core.callbacks import Callbacks from langchain_core.documents import Document, BaseDocumentCompressor from pydantic import Field import operator import os from typing import Callable, List, Optional, Sequence from langchain_dartmouth.base import AuthenticatedMixin from langchain_dartmouth.cross_encode...
dartmouth/langchain-dartmouth
src/langchain_dartmouth/retrievers/document_compressors.py
.py
a73c6dda4002d8a5
7.48
8
""" noxfile ~~~~~~~ Nox configuration script Modified from original source found in the Salt project: - https://github.com/saltstack/salt """ import datetime import os import shutil import sys from pathlib import Path # fmt: off if __name__ == "__main__": sys.stderr.write( "Do not execute this file dire...
saltstack/salt-install-guide
noxfile.py
.py
a818a029c1484943
7.45
7
import os import requests import json OPSLEVEL_API_TOKEN = os.environ["OPSLEVEL_API_TOKEN"] OPSLEVEL_ENDPOINT = "https://app.opslevel.com/graphql" LIST_CUSTOM_PROPERTIES_QUERY = """ query custom_service_properties($endCursor:String) { account { propertyDefinitions(after: $endCursor) { page...
OpsLevel/community-integrations
scripts/convert_tags_to_custom_properties/convert_tags_to_custom_properties.py
.py
fbb5937ece9f4871
7.54
11
import requests import json import os # Replace with your GraphQL endpoint and set up the API token as an env variable OPSLEVEL_API_TOKEN = os.environ["OPSLEVEL_API_TOKEN"] GRAPHQL_ENDPOINT = 'https://api.opslevel.com/graphql' HEADERS = { "Authorization": f"Bearer {API_TOKEN}", 'Content-Type': 'application/js...
OpsLevel/community-integrations
scripts/convert_teams_to_systems/migrate-teams-to-systems.py
.py
ada777d8ea3ec319
7.54
11
import os import requests OPSLEVEL_API_TOKEN = os.environ["OPSLEVEL_API_TOKEN"] OPSLEVEL_ENDPOINT = "https://app.opslevel.com/graphql" LIST_USERS_QUERY = """ query roles($endCursor: String) { account { users(filter: {key: role, arg: "user", type: equals}, after: $endCursor) { nodes { ...
OpsLevel/community-integrations
scripts/convert_user_roles/convert_user_to_team_member_roles.py
.py
85610c11f3120901
7.54
11
import os import requests OPSLEVEL_API_TOKEN = os.environ["OPSLEVEL_API_TOKEN"] OPSLEVEL_ENDPOINT = "https://app.opslevel.com/graphql" LIST_COMPONENT_TYPES_QUERY = """ query componentTypes($endCursor: String) { account { componentTypes (after: $endCursor) { nodes { id ...
OpsLevel/community-integrations
scripts/copy_componentType_custom_properties/copy_componentType_custom_properties.py
.py
0347925f04c2519e
7.54
11
import requests import json import os from collections import defaultdict # Replace these with your details GITHUB_TOKEN = os.environ["GITHUB_TOKEN"] REPO_OWNER = os.environ["REPO_OWNER"] REPO_NAME = os.environ["REPO_NAME"] OPSLEVEL_URL = "https://upload.opslevel.com/integrations/custom_event/" OPSLEVEL_ROUTING_ID = o...
OpsLevel/community-integrations
scripts/dependabot/dependabot_alerts.py
.py
eecae3b375b823a9
7.54
11
import os import csv import requests OPSLEVEL_API_TOKEN = os.environ.get("OPSLEVEL_API_TOKEN") OPSLEVEL_ENDPOINT = "https://app.opslevel.com/graphql" LIST_SYSTEMS_WITH_OWNERS_QUERY = """ query systemsWithOwners($endCursor: String) { account { systems(after: $endCursor) { nodes { ...
OpsLevel/community-integrations
scripts/export_systems_with_owners/export_systems_with_owners.py
.py
8faf3e57e7aa685e
7.54
11
import requests import argparse import sys # --- GraphQL Definitions --- # 1. Query to fetch Services, including pagination cursor GET_SERVICES_QUERY = """ query getServicesByTags ($filter: [ServiceFilterInput!], $after: String) { account { services (filter: $filter, after: $after) { nodes { id ...
OpsLevel/community-integrations
scripts/migrate_component_type/migrate_component_type.py
.py
58a45151ce836f1f
7.54
11