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 |
|---|---|---|---|---|---|---|
#!/usr/bin/env python3
"""
Submit a SLURM array job to add environment data and count offline beta monitor rates for many run_ids.
Usage:
sbatch_count_offline_mon_rates.py -rids 1748 1749 ... -aid 13
"""
import subprocess as sp
import argparse
from typing import List
from pathlib import Path
def main():
par ... | Helium6CRES/rocks_analysis_pipeline | sbatch_count_offline_mon_rates.py | .py | eaf79a3b39f9664e | 7.15 | 1 |
#!/usr/bin/env /data/raid2/eliza4/he6_cres/rocks_analysis_pipeline/.venv/bin/python3
"""
CLI entry point for submitting katydid runs via sbatch.
"""
import argparse
from pathlib import Path
from rocks_utility import sbatch_job
def main() -> None:
par = argparse.ArgumentParser()
arg = par.add_argument
ar... | Helium6CRES/rocks_analysis_pipeline | sbatch_katydid.py | .py | 26dc4003a794ca29 | 7.15 | 1 |
#!/usr/bin/env python3
import subprocess as sp
import argparse
from pathlib import Path
def main():
"""
DOCUMENT
"""
umask = sp.run(["umask u=rwx,g=rwx,o=rx"], executable="/bin/bash", shell=True)
# Parse command line arguments.
par = argparse.ArgumentParser()
arg = par.add_argument
#... | Helium6CRES/rocks_analysis_pipeline | sbatch_post_processing.py | .py | a1a5e067416b1d58 | 7.15 | 1 |
#!/usr/bin/env python3
import subprocess as sp
import argparse
from typing import List
from pathlib import Path
import re
def main():
"""
Slurm submission script for spec-sims Katydid analysis.
"""
par = argparse.ArgumentParser()
arg, st = par.add_argument, "store_true"
arg("-t", "--tlim", nar... | Helium6CRES/rocks_analysis_pipeline | sbatch_ssa_katydid.py | .py | fd2336f784b47379 | 7.15 | 1 |
#!/usr/bin/env python3
import subprocess as sp
import argparse
from pathlib import Path
def main():
"""
DOCUMENT
"""
umask = sp.run(["umask u=rwx,g=rwx,o=rx"], executable="/bin/bash", shell=True)
# Parse command line arguments.
par = argparse.ArgumentParser()
arg = par.add_argument
#... | Helium6CRES/rocks_analysis_pipeline | sbatch_ssa_post_processing.py | .py | fc3fd0499fc5121a | 7.15 | 1 |
#!/usr/bin/env python3
import argparse
import logging
import pathlib
import sys
from collections import Counter
import pandas as pd
import finalgrade
from finalgrade.audit import build_log, late_detail, student_frame
from finalgrade.errors import FinalgradeError, PolicyError
logger = logging.getLogger('finalgrade')... | matthigger/finalgrade | finalgrade/__main__.py | .py | e564299599114353 | 7 | 0 |
""" grades in the shape banner will import
Banner matches a row to a student by three fields at once -- CRN, term code
and a 9 digit student id -- and silently ignores any row where all three
don't line up. So the whole job here is producing those three columns
exactly, from a gradebook that has none of them.
Two of... | matthigger/finalgrade | finalgrade/banner.py | .py | 9811a16d3fe4ecd1 | 7 | 0 |
""" what a policy would do to a gradebook, without computing any grades
The policy's hardest question is which assignments a category catches:
categories match by substring, so `hw: 50` quietly takes in `hw1` and also
`review_hw` -- and you only found out by running the thing and reading the
warnings that scrolled pas... | matthigger/finalgrade | finalgrade/check.py | .py | 63e8b34dc786de58 | 7 | 0 |
"""Exceptions raised by finalgrade.
All inherit ValueError so that existing callers catching ValueError keep
working, while the CLI can catch FinalgradeError specifically and print
a single actionable line rather than a traceback.
"""
class FinalgradeError(ValueError):
""" base for every error this package raise... | matthigger/finalgrade | finalgrade/errors.py | .py | 6b27aa95b550b8cb | 7 | 0 |
""" which of a student's scores count in a category, and their mean
drop_low discards a student's worst few; keep_high counts only their best
few. A category takes one or the other, never both: which of a student's
scores count is one question with one answer.
They differ on an assignment with no score at all -- nan... | matthigger/finalgrade | finalgrade/get_mean_drop_low.py | .py | 8323e46561e35bc2 | 7 | 0 |
""" a score that is not in the grade cannot be late
One rule across waive, drop_low and keep_high: an assignment that is not
part of a student's category mean charges no late days, and is not one of
the assignments a late day is a fraction of. Being late on work that does
not count costs nothing, because there is not... | matthigger/finalgrade | test/test_late_counted.py | .py | 6a6c33d5b4a630ed | 7.5 | 0 |
import pathlib
import tempfile
import numpy as np
import pytest
import finalgrade
from finalgrade.policy import *
test_folder = pathlib.Path(finalgrade.__file__).parents[1] / 'test'
class TestConfig:
def test_default_config(self):
"""Default policy (no categories) should process without error"""
... | matthigger/finalgrade | test/test_policy.py | .py | 234b5056daa32e12 | 7.5 | 0 |
#!/usr/bin/env python3
""" assembles the static site into _site/
The page is plain html, css and js -- there is no bundler and nothing to
compile. The only build step is that the browser needs a wheel of this
package to install, and needs to be told its filename (which carries a
version). So: build a wheel, copy the... | matthigger/finalgrade | web/build.py | .py | 5a44fa70094076b1 | 7 | 0 |
#!/usr/bin/env python3
""" writes the example gradebooks the page's "try an example" loads
A demo gradebook is only worth anything if it exercises the awkward cases,
so this one is built around students who each break something: nobody who
submitted nothing, somebody who stopped halfway, a retake sitting in a second
c... | matthigger/finalgrade | web/make_example.py | .py | 63d56a30d8c9dc73 | 7 | 0 |
"""Flask application settings loaded from environment variables."""
import os
from datetime import timedelta
GAMES_PER_PAGE = 12
# Environment variables the app cannot safely start without. Without this
# check, a missing FLASK_AUTH_SECRET only surfaces on the first session write
# (deep inside Flask), and missing P... | Club-JDR/questmaster | config/settings.py | .py | 28d7c76b637d7056 | 7.24 | 2 |
from __future__ import with_statement
import logging
from logging.config import fileConfig
from flask import current_app
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python... | Club-JDR/questmaster | migrations/env.py | .py | 5875bc23daa3a0c9 | 7.24 | 2 |
"""Set discord_message.sent_at server-side default
Revision ID: 2e25be8292ad
Revises: bcc54b903cb3
Create Date: 2026-08-13 15:05:00.000000
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "2e25be8292ad"
down_revision = "bcc54b903cb3"
branch_labels = None
depends... | Club-JDR/questmaster | migrations/versions/2e25be8292ad_discord_message_sent_at_server_default.py | .py | 6ec802c005e73091 | 7.24 | 2 |
"""Add user name
Revision ID: 2ec87b2c0974
Revises: ac8986dff4d9
Create Date: 2025-07-15 16:11:45.462774
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "2ec87b2c0974"
down_revision = "ac8986dff4d9"
branch_labels = Non... | Club-JDR/questmaster | migrations/versions/2ec87b2c0974_add_user_name.py | .py | 91aa29c5f26e1446 | 7.24 | 2 |
"""Add special events for games
Revision ID: 3a278ccd9bda
Revises: d93dbbe1bddb
Create Date: 2025-10-04 10:10:37.933192
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "3a278ccd9bda"
down_revision = "d93dbbe1bddb"
branch_labels = None
depends_on = None
def up... | Club-JDR/questmaster | migrations/versions/3a278ccd9bda_add_special_events_for_games.py | .py | a9dbccbed2abd50e | 7.74 | 2 |
"""add game trophies_awarded
Revision ID: 83cc6fb5964d
Revises: 2e25be8292ad
Create Date: 2026-08-13 17:44:04.157401
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "83cc6fb5964d"
down_revision = "2e25be8292ad"
branch_labels = None
depends_on = None
def upgra... | Club-JDR/questmaster | migrations/versions/83cc6fb5964d_add_game_trophies_awarded.py | .py | ac8c74214eef1908 | 7.24 | 2 |
"""Add impersonator_id/impersonator_username to app_log
While an admin is impersonating another user (admin "view-as"), the app
behaves exactly as it would for the target — so ``user_id``/``username``
on the log record are the *impersonated* user's. These two new columns
carry the real admin's identity in that case, s... | Club-JDR/questmaster | migrations/versions/9c1d2e3f4a5b_add_impersonator_to_app_log.py | .py | 7965cd751e7e9f3a | 7.24 | 2 |
"""Add not_player_as_of to user
Revision ID: a1b2c3d4e5f6
Revises: 3a278ccd9bda
Create Date: 2026-02-17 00:00:00.000000
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "a1b2c3d4e5f6"
down_revision = "3a278ccd9bda"
branch_labels = None
depends_on = None
def up... | Club-JDR/questmaster | migrations/versions/a1b2c3d4e5f6_add_not_player_as_of_to_user.py | .py | b04628afa18be48c | 7.24 | 2 |
"""Add can_post_games to user
Adds a boolean flag letting admins prevent a specific user from creating or
publishing games without deleting or disabling the account. Defaults to True
so existing users are unaffected.
Revision ID: a8b9c0d1e2f3
Revises: f7a8b9c0d1e2
Create Date: 2026-07-18 00:00:00.000000
"""
import ... | Club-JDR/questmaster | migrations/versions/a8b9c0d1e2f3_add_can_post_games_to_user.py | .py | 2036ad4d9e15885c | 7.24 | 2 |
"""Add system description/reference_url and user_system_interest table
Gives each System a public page that doubles as passive matchmaking:
``description``/``reference_url`` let a system carry its own blurb or a
link to an external reference page, and ``user_system_interest`` records a
user's declared interest in play... | Club-JDR/questmaster | migrations/versions/b1c2d3e4f5a6_add_system_matchmaking.py | .py | 1f9833fd60954ef6 | 7.24 | 2 |
"""Add user_id to game_event
Revision ID: b7f8a9c0d1e2
Revises: a1b2c3d4e5f6
Create Date: 2026-02-17 12:00:00.000000
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "b7f8a9c0d1e2"
down_revision = "a1b2c3d4e5f6"
branch_labels = None
depends_on = None
def upgra... | Club-JDR/questmaster | migrations/versions/b7f8a9c0d1e2_add_user_id_to_game_event.py | .py | a74f52c2c3437b2e | 7.24 | 2 |
"""Add the infraction table for in-app moderation infractions
Tracks moderation events in QuestMaster (replacing Mee6 ``!warn`` /
``!infractions``), preserving the historical warning format. Severity is an
integer so new levels can be inserted between existing ones without an enum
migration.
Revision ID: b9c0d1e2f3a4... | Club-JDR/questmaster | migrations/versions/b9c0d1e2f3a4_add_infraction.py | .py | 6546f4dc33ee2e46 | 7.24 | 2 |
"""Add game_defaults to user
Stores per-user default values for the game creation form (e.g. description,
complement) as JSONB, rather than a dedicated column per possible field. Only
a whitelisted subset of keys is ever read back (see
website.utils.game_form_defaults); the column is nullable so existing users
are una... | Club-JDR/questmaster | migrations/versions/bcc54b903cb3_add_game_defaults_to_user.py | .py | 51bc70683530c231 | 7.24 | 2 |
"""Add game open_to_viewers and game_viewer table
Lets a GM signal that spectators (people who don't want to play but want to
watch, in person or via the VTT) are welcome, and lets those viewers follow
the game so it shows up in their personal agenda. ``game_viewer`` is purely a
personal-agenda signal (not a registrat... | Club-JDR/questmaster | migrations/versions/c1d2e3f4a5b6_add_game_open_to_viewers.py | .py | e46562d3346bf27f | 7.24 | 2 |
"""Add username to user
Revision ID: c3d4e5f6a7b8
Revises: b7f8a9c0d1e2
Create Date: 2026-02-17 14:00:00.000000
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "c3d4e5f6a7b8"
down_revision = "b7f8a9c0d1e2"
branch_labels = None
depends_on = None
def upgrade():... | Club-JDR/questmaster | migrations/versions/c3d4e5f6a7b8_add_username_to_user.py | .py | cd6d8e5e0025c162 | 7.24 | 2 |
"""Add indexes backing the dashboard per-user stats queries
Indexes the foreign keys the dashboard aggregates filter/join on, which
PostgreSQL does not create automatically:
* ``game.gm_id`` — "games as GM" lookups.
* ``game_players.player_id``— "games as player" join (composite PK leads with
``game_id``... | Club-JDR/questmaster | migrations/versions/c4d5e6f7a8b9_add_dashboard_stats_indexes.py | .py | 82afaf981f29fd17 | 7.24 | 2 |
"""Add permission_grant table for granular admin permissions (RBAC)
Stores one row per (capability, subject) grant. A subject is either a Discord
role or an individual user; the capability key references the code-defined
catalog (not a DB foreign key). A unique constraint keeps grants idempotent.
Revision ID: d5e6f7a... | Club-JDR/questmaster | migrations/versions/d5e6f7a8b9c0_add_permission_grant.py | .py | b7cdb2aa482c1340 | 7.24 | 2 |
"""Add app_setting table for runtime config overrides
Revision ID: e1f2a3b4c5d6
Revises: c3d4e5f6a7b8
Create Date: 2026-06-15 10:00:00.000000
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "e1f2a3b4c5d6"
down_revision = "c3d4e5f6a7b8"
branch_labels = None
depe... | Club-JDR/questmaster | migrations/versions/e1f2a3b4c5d6_add_app_setting.py | .py | 040b5bad2da5f05d | 7.24 | 2 |
"""Multi-embed and link-button support for discord_message
Replaces the per-embed scalar columns (title, description, color, footer,
image_url) with a single ``embeds`` JSON list, and adds a ``buttons`` JSON list.
Drops the ``type`` discriminator: a message is now simply the combination of
content, embeds and buttons ... | Club-JDR/questmaster | migrations/versions/e6f7a8b9c0d1_add_buttons_to_discord_message.py | .py | 90e59824254265fa | 7.24 | 2 |
"""Make Game.date and GameSession.start/end timezone-aware
Game.date / GameSession.start / GameSession.end were naive
TIMESTAMP columns, but "now" was computed three different ways across the
codebase (naive container-local, aware UTC, and Europe/Paris wall time
entered by users) with nothing to keep them consistent —... | Club-JDR/questmaster | migrations/versions/f0453966f7c6_game_dates_timezone_aware.py | .py | 98b5e185391ab752 | 7.24 | 2 |
"""Add discord_message table for admin-sent Discord messages
Revision ID: f2a3b4c5d6e7
Revises: e1f2a3b4c5d6
Create Date: 2026-06-17 09:00:00.000000
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "f2a3b4c5d6e7"
down_revision = "e1f2a3b4c5d6"
branch_labels = No... | Club-JDR/questmaster | migrations/versions/f2a3b4c5d6e7_add_discord_message.py | .py | 47d0a6549210a109 | 7.24 | 2 |
"""Add the app_log table for persisted application logs
Application log records at ``QM_DB_LOG_LEVEL`` and above are written here by
``DatabaseLogHandler`` so the admin "Journaux applicatifs" page can filter
them with plain SQL. ``user_id`` is intentionally not a foreign key: log
writes must stay decoupled from the re... | Club-JDR/questmaster | migrations/versions/f7a8b9c0d1e2_add_app_log.py | .py | 54b824a35e3a3fb9 | 7.24 | 2 |
"""API test fixtures.
Provides JWT token helpers, pre-authenticated API clients, and
session-based test clients for cookie-auth fallback tests.
"""
from datetime import datetime, timezone
import jwt
import pytest
from tests.constants import TEST_ADMIN_USER_ID, TEST_GM_USER_ID, TEST_REGULAR_USER_ID
def make_jwt_to... | Club-JDR/questmaster | tests/api/conftest.py | .py | cda4e250ff054ecd | 7.74 | 2 |
"""Tests for the API auth endpoints and JWT decorators."""
from datetime import datetime, timedelta, timezone
from unittest.mock import patch
import pytest
from tests.api.conftest import make_jwt_token
from tests.constants import TEST_REGULAR_USER_ID
class TestExchangeToken:
"""Tests for POST /api/v1/auth/toke... | Club-JDR/questmaster | tests/api/test_auth.py | .py | 6610d2323e8f3700 | 7.74 | 2 |
"""Tests for API JSON error handlers."""
class TestJsonErrorHandlers:
"""Tests for JSON error responses on API routes."""
def test_404_returns_json(self, api_client):
"""Non-existent API route returns JSON 404."""
response = api_client.get("/api/v1/nonexistent")
assert response.status... | Club-JDR/questmaster | tests/api/test_errors.py | .py | 900ab9437b7167b6 | 7.74 | 2 |
"""Tests for the API health endpoint."""
from unittest.mock import patch
from website.extensions import cache, db
def test_health_returns_ok(api_client):
"""GET /api/v1/health returns 200 with expected JSON fields."""
response = api_client.get("/api/v1/health")
assert response.status_code == 200
as... | Club-JDR/questmaster | tests/api/test_health.py | .py | 67cd9a6fd30166e2 | 7.74 | 2 |
"""Tests for the leaderboard API endpoint."""
from unittest.mock import MagicMock, patch
class TestGetLeaderboards:
"""Tests for GET /api/v1/leaderboards/."""
def test_requires_auth(self, api_client):
"""Endpoint requires authentication."""
response = api_client.get("/api/v1/leaderboards/")
... | Club-JDR/questmaster | tests/api/test_leaderboards.py | .py | 67bbfb566f358e6c | 7.74 | 2 |
"""Tests for pagination utilities."""
from config.constants import API_DEFAULT_PAGE, API_DEFAULT_PER_PAGE, API_MAX_PER_PAGE
from website.api.pagination import paginated_response, parse_pagination_args
class TestParsePaginationArgs:
"""Tests for parse_pagination_args."""
def test_defaults(self, test_app):
... | Club-JDR/questmaster | tests/api/test_pagination.py | .py | 6711e334d44bf3cc | 7.74 | 2 |
"""Tests for session-cookie auth fallback and api_login_optional.
Verifies that the API accepts Flask session cookies as an alternative
to JWT Bearer tokens, and that ``api_login_optional`` allows anonymous
access where appropriate.
"""
from datetime import datetime
from unittest.mock import MagicMock, patch
from te... | Club-JDR/questmaster | tests/api/test_session_auth.py | .py | c11cbedc555ae170 | 7.74 | 2 |
"""Tests for the stats and calendar API endpoints."""
from datetime import datetime
from unittest.mock import MagicMock, patch
class TestGetStats:
"""Tests for GET /api/v1/stats/."""
def test_requires_auth(self, api_client):
"""Endpoint requires authentication."""
response = api_client.get("... | Club-JDR/questmaster | tests/api/test_stats.py | .py | 3e02c429d7da6cfb | 7.74 | 2 |
"""Tests for the user API endpoints."""
from unittest.mock import MagicMock, patch
from tests.constants import TEST_REGULAR_USER_ID
from website.exceptions import NotFoundError
class TestGetCurrentUser:
"""Tests for GET /api/v1/users/me/."""
def test_requires_auth(self, api_client):
"""Endpoint req... | Club-JDR/questmaster | tests/api/test_users.py | .py | 00acd40b2f96cb04 | 7.74 | 2 |
"""Root test configuration.
Provides the Flask test app, transactional database sessions with
automatic rollback, and seeded reference data fixtures.
"""
from dotenv import load_dotenv
# Load env BEFORE importing app
config = load_dotenv()
import os
import pytest
from tests.constants import (
TEST_ADMIN_USER_... | Club-JDR/questmaster | tests/conftest.py | .py | cc245359a3e36a83 | 7.74 | 2 |
"""
Read an array layout from file.
Layouts are ECSV tables -- plain text with a small YAML header naming each
column and its unit. Carrying the units in the file removes the ambiguity that
plain columns of numbers leave behind: a camera radius may be quoted as a length
or as an angle on the sky, and the two look iden... | cta-observatory/divtel | divtel/layout.py | .py | 5e35a0acfc0ab5e8 | 7 | 0 |
"""
Functions to define telescopes pointings
We use the same reference frame as simtel_array:
X is pointing North
Y is pointing West
Z is pointing upward
Az is taken clock-wise from X (towards Y) and between -180 and 180 degrees
Alt is taken from ground (towards Z) and between -90 and 90 degrees
"""
import numpy as np... | cta-observatory/divtel | divtel/pointing.py | .py | 891560528590d934 | 7 | 0 |
import astropy.units as u
import numpy as np
import pytest
from divtel.telescope import Array, Telescope
@pytest.fixture
def square_array():
"""Four telescopes on a 100 m square."""
return Array(
[
Telescope(100 * u.m, 0 * u.m, 0 * u.m, 20 * u.m, 1 * u.m),
Telescope(0 * u.m, 1... | cta-observatory/divtel | divtel/tests/test_divergent_pointing.py | .py | ae7e08d376875f67 | 7.5 | 0 |
import astropy.units as u
import pytest
from divtel.telescope import Array, Telescope
@pytest.fixture
def square_array():
"""Four telescopes on a 100 m square."""
return Array(
[
Telescope(100 * u.m, 0 * u.m, 0 * u.m, 20 * u.m, 1 * u.m),
Telescope(0 * u.m, 100 * u.m, 0 * u.m, ... | cta-observatory/divtel | divtel/tests/test_export_cfg.py | .py | b9030b6229d136c8 | 7.5 | 0 |
"""Layouts are read from ECSV files that carry their own units."""
from importlib.resources import files
import astropy.units as u
import pytest
from divtel.layout import camera_radius_in_metres, load_array, load_table
DATA = files("divtel") / "data"
HEADER = """# %ECSV 1.0
# ---
# datatype:
# - {{name: x, datatyp... | cta-observatory/divtel | divtel/tests/test_layout.py | .py | 51af9b4b6eb80406 | 7.5 | 0 |
import marimo
__generated_with = "0.24.0"
app = marimo.App(width="full")
@app.cell(hide_code=True)
async def _():
import sys
# In the WASM build there is no site-packages: Python is Pyodide, and
# divtel has to be fetched as a wheel published next to this page. The
# released sdist on PyPI cannot be... | cta-observatory/divtel | examples/marimo/interactive_display.py | .py | bec3d5d7101b87db | 7 | 0 |
import json
from biothings.web.auth.authn import BioThingsAuthenticationProviderInterface
class UserCookieAuthProvider(BioThingsAuthenticationProviderInterface):
"""Retrieve the current user from a secure cookie."""
WWW_AUTHENTICATE_HEADER = "None"
def __init__(self, handler, cookie_name="user"):
... | NIAID-Data-Ecosystem/nde-discovery-api | nde-web/authn/authn_provider.py | .py | 7562652829e68905 | 7.15 | 1 |
"""Sync per-repo metadata JSON files from curated sources.
Each repo (a NDE data source such as ``ndex``, ``immport``, ``mwccs``) is
represented by a JSON file under ``nde-web/repo_metadata/<key>.json``. The
files are the single source of truth at runtime (loaded by
``NDESourceHandler``). This script regenerates / upd... | NIAID-Data-Ecosystem/nde-discovery-api | nde-web/scripts/sync_repo_metadata.py | .py | 4624918c2a42a9b9 | 7.15 | 1 |
#!/usr/bin/env python3
"""Validate repo-level metadata files and generated caches.
This intentionally avoids third-party dependencies so it can run in any
checkout. It checks the project-specific invariants that matter for the
``NDESourceHandler`` metadata path:
* curated source JSON files parse and include required ... | NIAID-Data-Ecosystem/nde-discovery-api | nde-web/scripts/validate_repo_metadata.py | .py | 1b8fc652d816c839 | 7.15 | 1 |
"""Tool identity & CLI framing: one house style for banners, --help, examples.
Every tool presents the same first impression — an identity line
(``{icon} name vX.Y.Z — tagline``), a ``-v/--version`` flag, and an aligned
``Examples:`` epilog — by building its parser through :func:`make_parser`.
The same identity is reu... | pokanop/scripts | scriptkit/app.py | .py | c0a52a366708bfe7 | 7.15 | 1 |
"""Managed text blocks — insert, replace, or remove a marked region in a file.
A *managed block* is a span of lines fenced by a ``begin``/``end`` marker pair
(e.g. the ``# >>> … >>>`` / ``# <<< … <<<`` stanzas shells use). The point of
this module is that the block is **reversible and idempotent**: writing the same
bo... | pokanop/scripts | scriptkit/blocks.py | .py | 17b2f092e74fdc27 | 7.15 | 1 |
"""CLI plumbing: the user-facing error type and a uniform run/dispatch flow.
The whole app lifecycle is centralized here so tools don't re-roll it:
- :func:`run` wraps ``main`` with one error + interrupt + exit policy.
- :func:`parse_args` parses argv, optionally injecting a *default subcommand*
(so bare ``netsy`` ... | pokanop/scripts | scriptkit/cli.py | .py | 77bf78938be0018a | 7.15 | 1 |
"""Three-tier configuration: defaults < saved file < environment overrides.
Synthesized from aikit/medcat. Supports deep-merging nested dicts, dot-path
get/set, and a ``PREFIX_A__B=value`` environment convention that maps onto
``a.b``. ``save()`` writes pretty JSON with ``0600`` permissions.
"""
from __future__ impor... | pokanop/scripts | scriptkit/config.py | .py | 0a07368682749852 | 7.15 | 1 |
"""Subprocess helpers with a uniform result and graceful failure modes.
``run()`` never raises for a non-zero exit (unless ``check=True``); it always
returns a :class:`Result`, folding timeouts / missing binaries into a code and
an ``err`` string. This is the shape every tool's CLI-coordination code wants.
"""
from _... | pokanop/scripts | scriptkit/proc.py | .py | 3e3d258af0b497c1 | 7.15 | 1 |
"""Progress indicators: bars, spinners/status, tracked iteration, parallel map.
Built on ``rich`` when present, with graceful no-rich fallbacks so the tools
keep working in minimal environments. ``bar()`` is a pure-string renderer for
inline ``\\r`` progress with no dependency at all.
"""
from __future__ import annot... | pokanop/scripts | scriptkit/progress.py | .py | 9ea0786043a58063 | 7.15 | 1 |
"""Table rendering: a thin, declarative wrapper over ``rich.table.Table``.
Columns are described as dicts so callers stay declarative; falls back to an
aligned plain-text grid when ``rich`` is unavailable.
"""
from __future__ import annotations
from . import style
from .console import HAS_RICH, console
def table(c... | pokanop/scripts | scriptkit/tables.py | .py | 9288efd7e86b73a7 | 7.15 | 1 |
"""Human-friendly formatting helpers: sizes, durations, counts, truncation."""
from __future__ import annotations
def human_size(num_bytes: float, *, binary: bool = True) -> str:
"""Format a byte count as a human string (``1.5 MB``).
``binary`` uses 1024 steps (the default, matching disk/file tooling);
... | pokanop/scripts | scriptkit/text.py | .py | 4f8388a09a65d7f8 | 7.15 | 1 |
"""Shared pytest fixtures for the scriptkit + tools test suite."""
from __future__ import annotations
import importlib.machinery
import importlib.util
import sys
from pathlib import Path
import pytest
REPO_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(REPO_ROOT))
@pytest.fixture(autouse=Tru... | pokanop/scripts | tests/conftest.py | .py | 87830b0d317dee89 | 7.65 | 1 |
"""Interrupt / subprocess-lifecycle tests for aikit's ``run`` (POK-85).
``aikit update`` couldn't be aborted cleanly with Ctrl-C: the update command is
run through ``run()``, and the previous implementation only killed the immediate
shell, orphaning the real installer tree it spawned. ``run()`` now isolates
captured c... | pokanop/scripts | tests/test_aikit_interrupt.py | .py | b6051eb305b3b71e | 7.65 | 1 |
"""Smoke test for the new-tool scaffold so it never rots."""
import os
import subprocess
import sys
from pathlib import Path
import pytest
REPO_ROOT = Path(__file__).resolve().parent.parent
TEMPLATE = REPO_ROOT / "templates" / "tool_template.py"
@pytest.mark.parametrize(
"argv,needle",
[
(["--versi... | pokanop/scripts | tests/test_template.py | .py | 7d43a2f65e66a1e3 | 7.65 | 1 |
# Copyright 2022 Canonical Ltd.
# See LICENSE file for licensing details.
"""## Overview.
This document explains how to use the `JujuTopology` class to
create and consume topology information from Juju in a consistent manner.
The goal of the Juju topology is to uniquely identify a piece
of software running across any... | canonical/cos-configuration-k8s-operator | lib/charms/observability_libs/v0/juju_topology.py | .py | 4172f1ccbb77c462 | 7.39 | 5 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""A Juju secrets getter for sensitive data."""
import logging
from typing import Optional
from urllib.parse import urlparse
from ops.model import (
ActiveStatus,
BlockedStatus,
Model,
ModelError,
Sec... | canonical/cos-configuration-k8s-operator | src/secrets_helper.py | .py | 51f05e6c4bb9e964 | 7.39 | 5 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Sloth SLO Provider wrapper for cos-configuration-k8s-operator.
This module provides a file-based interface for the Sloth charm library.
Unlike alert rules and dashboards (which are typically shipped with the charm),
SL... | canonical/cos-configuration-k8s-operator | src/sloth.py | .py | b7a7f39ce7cdcaf9 | 7.39 | 5 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Pure helper utilities for cos-configuration-k8s (no ops dependency)."""
import re
from typing import Optional
def extract_remote(repo_url: str) -> Optional[str]:
"""Extract the SSH remote hostname from a git repo... | canonical/cos-configuration-k8s-operator | src/utils.py | .py | 3eeb90e05faeb20f | 7.39 | 5 |
#!/usr/bin/env python3
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
import functools
import logging
import os
from collections import defaultdict
from datetime import datetime
from pathlib import Path
import pytest
from pytest_operator.plugin import OpsTest
logger = logging.getLogger(__n... | canonical/cos-configuration-k8s-operator | tests/integration/conftest.py | .py | ebc2ed5758604577 | 7.89 | 5 |
#!/usr/bin/env python3
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
#
# Learn more at: https://juju.is/docs/sdk
"""Helper for interacting with Loki throughout the charm's lifecycle."""
import logging
from typing import Optional
import aiohttp
import requests
import yaml
from yaml.scanner... | canonical/cos-configuration-k8s-operator | tests/integration/loki_workload.py | .py | f1f938b53b82e2a2 | 7.89 | 5 |
#!/usr/bin/env python3
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
import logging
import os
import random
import unittest
from typing import List, Tuple
from unittest.mock import patch
import hypothesis.strategies as st
from helpers import FakeProcessVersionCheck
from hypothesis import g... | canonical/cos-configuration-k8s-operator | tests/unit/charm/test_status_vs_config.py | .py | 29c1ac44e2cfc02b | 7.89 | 5 |
#!/usr/bin/env python3
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
import unittest
from unittest.mock import patch
from ops.testing import Harness
from charm import COSConfigCharm
class TestWorkloadVersion(unittest.TestCase):
"""Workload version should be set correctly in juju."""... | canonical/cos-configuration-k8s-operator | tests/unit/charm/test_workload_version.py | .py | e5d0d1671bc083fc | 7.89 | 5 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
import logging
from unittest.mock import PropertyMock, patch
import pytest
from ops.testing import (
Container,
Context,
Exec,
PeerRelation,
Secret,
State,
Storage,
)
from src.charm import COS... | canonical/cos-configuration-k8s-operator | tests/unit/scenario/conftest.py | .py | 41a2d356fb16cfa6 | 7.89 | 5 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Scenario tests for SLO provider functionality."""
import dataclasses
import logging
from scenario import Relation
from src.sloth import SlothSloProvider
logger = logging.getLogger(__name__)
def test_sloth_relation... | canonical/cos-configuration-k8s-operator | tests/unit/scenario/test_slo_provider.py | .py | e106f74722420503 | 7.89 | 5 |
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
"""Charm for providing services catalogues to bundles or sets of charms.
This charm library contains two classes (CatalogueProvider and CatalogueConsumer) that handle
both sides of the `catalogue` relation interface.
### CatalogueConsumer
The... | canonical/parca-k8s-operator | lib/charms/catalogue_k8s/v1/catalogue.py | .py | cd74ad11472db412 | 7.3 | 3 |
"""# Overview.
This document explains how to integrate with the Parca charm where you wish to use Parca
as a store for profiles that are sent from a Parca Agent.
## Requirer Library usage
In this mode, your charm will be an application that needs to receive store configuration over the
relation in order that the wor... | canonical/parca-k8s-operator | lib/charms/parca_k8s/v0/parca_store.py | .py | d96ff15bdf2826db | 7.3 | 3 |
#!/usr/bin/env python3
# Copyright 2022 Canonical Ltd.
# See LICENSE file for licensing details.
r"""# Interface Library for traefik_route.
This library wraps relation endpoints for traefik_route. The requirer of this
relation is the traefik-route-k8s charm, or any charm capable of providing
Traefik configuration fil... | canonical/parca-k8s-operator | lib/charms/traefik_k8s/v0/traefik_route.py | .py | c727ee26196f9604 | 7.3 | 3 |
#!/usr/bin/env python3
# Copyright 2025 Canonical
# See LICENSE file for licensing details.
"""Traefik-route ingress configuration."""
import enum
import socket
from collections import namedtuple
from enum import Enum
from typing import Dict, Optional, Sequence
from charms.traefik_k8s.v0.traefik_route import Traefik... | canonical/parca-k8s-operator | src/ingress_configuration.py | .py | 4e99ca0831726770 | 7.3 | 3 |
# Copyright 2024 Canonical
# See LICENSE file for licensing details.
"""TLS Config class."""
import dataclasses
from typing import List, Optional
import pydantic
from charms.tls_certificates_interface.v4.tls_certificates import (
CertificateRequestAttributes,
PrivateKey,
ProviderCertificate,
)
# FIXME:... | canonical/parca-k8s-operator | src/models.py | .py | 49fe230f784e2041 | 7.3 | 3 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Nginx workload."""
import dataclasses
import logging
from pathlib import Path
from typing import Dict, List, Optional, Set
from charmlibs.nginx_k8s import NginxConfig, NginxLocationConfig, NginxUpstream
from ops import... | canonical/parca-k8s-operator | src/nginx.py | .py | 79c1e19466bb6e18 | 7.3 | 3 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Nginx prometheus exporter workload."""
from ops import Container, pebble
NGINX_PROMETHEUS_EXPORTER_PORT = 9113
_NGINX_PROM_EXPORTER_DIR = "/etc/nginx"
KEY_PATH = f"{_NGINX_PROM_EXPORTER_DIR}/certs/server.key"
CERT_PAT... | canonical/parca-k8s-operator | src/nginx_prometheus_exporter.py | .py | 2d28e203cd238ac0 | 7.3 | 3 |
# Copyright 2025 Canonical
# See LICENSE file for licensing details.
"""Control Parca running in a container under Pebble. Provides a Parca class."""
import logging
import re
import typing
from typing import Dict, List, Literal, Optional, Sequence, TypedDict, Union
import ops.pebble
import yaml
from ops import Conta... | canonical/parca-k8s-operator | src/parca.py | .py | a09154b05e75b412 | 7.3 | 3 |
# Copyright 2021 Canonical Ltd.
# See LICENSE file for licensing details.
import logging
import os
from pathlib import Path
from helpers import get_resources, pack
from pytest import fixture
logger= logging.getLogger("conftest")
@fixture(scope="module")
def parca_charm():
"""Parca charm used for integration tes... | canonical/parca-k8s-operator | tests/integration/conftest.py | .py | e04c688b2ebfd985 | 7.8 | 3 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
import json
import logging
import shlex
import subprocess
from pathlib import Path
from subprocess import getoutput, getstatusoutput
from typing import List, Tuple
import yaml
from jubilant import Juju
from nginx import CA_CERT_PATH, Nginx
PAR... | canonical/parca-k8s-operator | tests/integration/helpers.py | .py | cb75ee1c57838500 | 7.8 | 3 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Generic COS integration test.
Tests integrations with:
- loki
- prom
- catalog
- grafana
"""
import json
import jubilant
import pytest
import requests
from jubilant import Juju
from tenacity import retry, stop_after_d... | canonical/parca-k8s-operator | tests/integration/test_core_cos_integrations.py | .py | e3862d01b3b4b0e1 | 7.8 | 3 |
#!/usr/bin/env python3
# Copyright 2022 Canonical Ltd.
# See LICENSE file for licensing details.
"""Integration testing for the following endpoints.
- external-parca-store-endpoint # push profiles to other parca
- parca-store-endpoint # receive profiles from other parca
- profiling-endpoint # receive profiles
- self... | canonical/parca-k8s-operator | tests/integration/test_profiling_integrations.py | .py | b15a0eb8fb5fac15 | 7.8 | 3 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
import json
import logging
import re
import shlex
from subprocess import check_call, check_output
import jubilant
import pytest
from jubilant import Juju
from minio import Minio
from tenacity import retry
from tenacity.st... | canonical/parca-k8s-operator | tests/integration/test_s3_integration.py | .py | af4524220fb0c6f9 | 7.8 | 3 |
from typing import List, Set, cast
import jubilant
import pytest
import requests
from jubilant import Juju
from tenacity import retry, stop_after_attempt, wait_fixed
from tests.integration.helpers import (
INTEGRATION_TESTERS_CHANNEL,
PARCA,
S3_APP,
get_app_ip_address,
)
TEMPO = "tempo"
TEMPO_WORKER ... | canonical/parca-k8s-operator | tests/integration/test_tracing_integrations.py | .py | d4befa956000a3f2 | 7.8 | 3 |
import jubilant
import pytest
from jubilant import Juju
from tests.integration.helpers import (
PARCA,
)
# Cross-base upgrades (e.g. 24.04 -> 26.04) are not supported via juju refresh.
# The charmhub charm is built for 24.04 (Python 3.12), while the local charm
# targets 26.04 (Python 3.14). Juju refresh only rep... | canonical/parca-k8s-operator | tests/integration/test_upgrade.py | .py | f66a04ffbe705588 | 7.8 | 3 |
from pathlib import Path
import yaml
from scenario import Context, State
from parca import DEFAULT_CONFIG_PATH
def assert_parca_command_equals(state: State, expected_command):
"""Assert that the command line for the parca service in the parca container matches."""
container = state.get_container("parca")
... | canonical/parca-k8s-operator | tests/unit/test_charm/container_utils.py | .py | 91e98f0ddcf21e1c | 7.8 | 3 |
"""
Generating a candidate set for a held dataset, with its provenance.
This is the seam between the detector (`interpretation.anomaly_candidates`,
unchanged) and the stored, inspectable candidate set the API serves. It decides
one thing the detector deliberately does not: whether candidate generation is
possible for ... | eeb03/den-repo | api/candidates.py | .py | 4dcd14547d2fff1f | 7 | 0 |
import os
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from database.session import init_db
from auth.mailer import configure_from_environment
from jobs.runner import mark_o... | eeb03/den-repo | api/main.py | .py | 0d58cd04933d4157 | 7 | 0 |
"""
Assembling the honest description of one survey line's radargram.
This adds no new representation of the trace grid and no second candidate
model. It answers three questions the existing `trace_grid` response left to the
caller's judgement, each of which is a scientific claim rather than a formatting
choice:
* ... | eeb03/den-repo | api/radargram.py | .py | adda7d607d89d662 | 7 | 0 |
"""
Assembling a `DatasetReport` from what the platform has stored.
THE SPLIT. `schemas/dataset_report.py` decides what a report MEANS -- what
counts as ready, what counts as missing, what may never be claimed. This module
only fetches: records, frames, labels, the dataset row. Keeping the judgement
out of the I/O is ... | eeb03/den-repo | api/reports.py | .py | 8c215444823fa24d | 7 | 0 |
"""
Candidate intelligence API.
A thin surface over `api.candidates` and `database.candidates_store`. The route
layer adds no semantics: what a candidate may and may not claim is enforced on
the models in `interpretation.candidate_intelligence`, so it holds equally for
the API, a script and the report.
EVERY RESPONSE... | eeb03/den-repo | api/routes/candidates.py | .py | a7b884b1ea7d3404 | 7 | 0 |
"""
Export API.
Every response carries the payload AND a report naming what was written, what
was skipped and why. A format that cannot honestly represent the data refuses
with a reason rather than emitting a placeholder.
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.responses import Pl... | eeb03/den-repo | api/routes/exports.py | .py | 1c2a5ab2698cfb4f | 7 | 0 |
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from auth.dependencies import get_current_user, visible_dataset_ids
from database.models import User
from database.session import get_db
from database.models import Dataset, FusionSample as Fusi... | eeb03/den-repo | api/routes/fusion.py | .py | 83f1b3702fd24d12 | 7 | 0 |
"""
Dataset import: upload now, process in the background, report truthfully.
The existing `POST /api/datasets/ingest` still exists and is unchanged. It runs
the whole pipeline inside the request, which is fine for a small CSV and
unusable for a 112 MB SEG-Y -- the connection is held for the duration and the
client le... | eeb03/den-repo | api/routes/imports.py | .py | ee347b62c2eec756 | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.