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 |
|---|---|---|---|---|---|---|
"""Tests for the banlist, focused on the Quarry remote-fetch layer.
The committed ``dpla-id-banlist.txt`` is the floor; the Quarry feed can only
add IDs on top of it. These tests pin that invariant and the fail-safe
behavior (network error / empty run / garbage never shrinks the banlist).
"""
from pathlib import Path... | dpla/ingest-wikimedia | tests/test_banlist.py | .py | 5a4b18191ebd10c9 | 7.5 | 0 |
"""Tests for ingest_wikimedia.categories.
Focus is on the two pieces of new state/behaviour we rely on for the post-
upload touch flow:
* ``CategoryEnsurer.newly_created`` populates only when ``ensure()`` actually
writes new P8464 infrastructure — not on any of the three fast-paths.
* ``touch_institution_files()`` ... | dpla/ingest-wikimedia | tests/test_categories.py | .py | 1fcaf09308403781 | 7.5 | 0 |
"""Tests for the shared CSRF-recovery primitives in
``ingest_wikimedia.csrf``.
Motivated by the Toledo Lucas 2026-06-25 SDC-sync run: 68,411 identical
``KeyError("Invalid token 'csrf' ...")`` failures bucketed as
"SDC sync failed; skipping ordinal" over ~5.5 days. PR #350 had already
solved the same class of bug for :... | dpla/ingest-wikimedia | tests/test_csrf.py | .py | 728649467cb2f49d | 7.5 | 0 |
"""Tests for the SDC log scanner in tools.get_ids_retry.
The upload and download scanners are exercised indirectly by integration
tests on the retry pipeline; this file focuses on parse_sdc_log because
its classification rules are dense (every transient pattern is one
substring match) and the scanner is the only point... | dpla/ingest-wikimedia | tests/test_get_ids_retry.py | .py | 9d3b6bfcb01df3ac | 7.5 | 0 |
#!/usr/bin/env python3
"""Regenerate the "What I'm Shipping Lately" README section.
Pulls recent public GitHub activity, summarises what's been shipped, and injects
it between the AI-SUMMARY markers. The section is always regenerated from real
activity; whether a model writes the prose depends on configuration.
NOTE:... | santoshshinde2012/santoshshinde2012 | scripts/ai_summary.py | .py | 2a910cb4546c2b7a | 7.3 | 3 |
"""Meetup's public per-group ICS export — the no-auth path.
``https://www.meetup.com/<slug>/events/ical/`` still returns a real VCALENDAR
of a group's upcoming events with no API key, no OAuth, and no token refresh.
Verified 2026-08-16: 200 + VEVENTs with ``UID``, ``DTSTART;TZID=...``,
``DTEND``, ``SUMMARY``, ``DESCRI... | davidawad/meetup_ical_export | meetup_ics.py | .py | 9e881fad0f744cec | 7.39 | 5 |
"""One full pass through the whole flow against a fake Meetup.
Nothing here talks to the real service — `responses` stands in for both
`secure.meetup.com` (OAuth2) and `api.meetup.com/gql-ext` (GraphQL). It exists
because the individual units can all pass while the wiring between them is
wrong, and there are no live c... | davidawad/meetup_ical_export | tests/test_end_to_end.py | .py | df4ca99accf61553 | 7.89 | 5 |
"""One full pass through the ics (no-auth) flow against a fake Meetup.
Mirrors what test_end_to_end.py covers for the graphql/OAuth path — merging
multiple groups, surviving a dead group, DEBUG-mode group limiting — but
driven through the actual Flask app for MEETUP_EVENT_SOURCE=ics, the mode
that needs zero credentia... | davidawad/meetup_ical_export | tests/test_end_to_end_ics.py | .py | 1cf45da0d9f08a5b | 7.89 | 5 |
"""Opt-in smoke tests against the real Meetup service.
Skipped by default (and always in CI, which never sets the env var below) —
everything else in this suite runs offline against fixtures. This file is the
one place that actually calls meetup.com, to catch Meetup changing the public
ICS export's shape or URL out fr... | davidawad/meetup_ical_export | tests/test_live_smoke.py | .py | 18fac8151094d4c7 | 7.89 | 5 |
import base64
from gitpy.service.urls import generate_url, REPOSITORY_URLS
from gitpy.service.utils import FILLER as F
class Repository:
'''https://docs.github.com/en/rest/repos/repos?apiVersion=2022-11-28'''
def __init__(self, authenticated_obj):
self.gitpy_obj = authenticated_obj
self.netwo... | akk29/gitpy | gitpy/core/repos.py | .py | 246bba8ead422a38 | 7 | 0 |
import traceback
from gitpy.service.loggerService import Logger
from requests.status_codes import codes
def process_exception(self):
tb = traceback.extract_stack()[:-1] # Exclude current frame
last_frame = tb[-4]
if(hasattr(self,"warning_error")):
last_frame = tb[-4]
file_name = last_f... | akk29/gitpy | gitpy/exceptions.py | .py | 974054e797e2179e | 7 | 0 |
"""Install a Copilot skill that teaches the pipelign golden path."""
from __future__ import annotations
import argparse
import os
import sys
from dataclasses import dataclass
from pathlib import Path
SKILL_NAME = "pipelign"
SKILL_FILENAME = "SKILL.md"
_COPILOT_HOME_ENV = "PIPELIGN_COPILOT_HOME"
SKILL_CONTENT = """... | sdwfrost/pipelign | pipelign/skill.py | .py | fc40b1bb2fb253a1 | 7.24 | 2 |
"""The Discord client and its lifecycle."""
from __future__ import annotations
import discord
import structlog
from discord.ext import commands
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from .config import Settings
from .db.session import create_engine, create_session_factory
from .registra... | mting314/bruinwatch | src/bruinwatch/bot.py | .py | 7a5e90f0663b892a | 7 | 0 |
"""Typed configuration, loaded from the environment or a local ``.env``."""
from __future__ import annotations
from pydantic import Field, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_prefix="BRUINWATCH_",
... | mting314/bruinwatch | src/bruinwatch/config.py | .py | f9d6bcb71b234baf | 7 | 0 |
"""Widen sections.units.
Real catalog data exceeds the original 16 characters: variable-unit courses
carry strings like ``"4.0/6.0 Alternate"`` (17) alongside ``"2.0-4.0 Variable"``
(exactly 16). A backfill of Fall 2023 aborted on the first one.
A survey of ~280 courses across two terms put every other bounded string... | mting314/bruinwatch | src/bruinwatch/db/migrations/versions/0002_widen_section_units.py | .py | d620ec2129b5064d | 7 | 0 |
"""SQLAlchemy models.
Schema shape follows hotseat.io's: a normalized catalog
(``subject_areas -> courses -> sections``) plus an append-only
``enrollment_data`` time series keyed on ``(section_id, created_at)``.
Two tables carry most of the design weight:
``subscriptions``
Many users to many sections. The poller... | mting314/bruinwatch | src/bruinwatch/db/models.py | .py | 5c304d36ac47348e | 7 | 0 |
"""Async engine and session factory."""
from __future__ import annotations
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from sqlalchemy.ext.asyncio import (
AsyncEngine,
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.pool import Static... | mting314/bruinwatch | src/bruinwatch/db/session.py | .py | efcd9f19bfee1f05 | 7 | 0 |
"""Health endpoint.
Replaces the old bare ``socket.bind`` that existed only to satisfy Heroku's port
check and answered nothing. This reports whether the bot is connected and
whether the scraper's circuit breaker has tripped, so a platform health check
means something.
The routes mount onto a shared aiohttp app along... | mting314/bruinwatch | src/bruinwatch/health.py | .py | e0d05c5511a8885b | 7 | 0 |
"""A single, polite HTTP client for the UCLA Schedule of Classes.
Every request in the process goes through one ``httpx.AsyncClient`` so that
connections are pooled and a global semaphore can cap how hard we lean on
sa.ucla.edu. The previous implementation issued bare, unbounded, *synchronous*
``requests.get`` calls f... | mting314/bruinwatch | src/bruinwatch/registrar/client.py | .py | 0f0156d90ca0f7cb | 7 | 0 |
"""Deterministic construction of the registrar's ``model`` query parameter.
The Schedule of Classes drives its AJAX endpoints with an opaque-looking JSON
``model`` blob plus a base64 ``Token``. The obvious way to get one is to scrape
the ``Iwe_ClassSearch_SearchResults.AddToCourseData({...})`` script tag off a
search-... | mting314/bruinwatch | src/bruinwatch/registrar/model.py | .py | 7755d0aa25434191 | 7 | 0 |
"""Fetch-and-parse routines: the only place client and parsers meet.
Each function mirrors one of hotseat.io's ``fetch-*`` lambdas, but they run as
coroutines inside the bot process rather than as separately scheduled functions.
"""
from __future__ import annotations
import asyncio
import structlog
from .client im... | mting314/bruinwatch | src/bruinwatch/registrar/scrapers.py | .py | ba2ac0ddb473845a | 7 | 0 |
"""Value types for the UCLA Schedule of Classes.
Everything here is a plain frozen dataclass with no I/O, no ORM and no Discord
imports, so the whole scraping layer can be unit tested against saved HTML.
"""
from __future__ import annotations
import datetime as dt
import re
from dataclasses import dataclass, field
f... | mting314/bruinwatch | src/bruinwatch/registrar/types.py | .py | 001cb2d1c215698d | 7 | 0 |
"""Backfill the catalog for past terms.
The registrar serves any term code you ask for, back to Fall 1999 -- far beyond
the eight terms its dropdown advertises. This walks those terms and records what
was offered, by whom, at what capacity, and how full each section ended up.
**It cannot recover enrollment history.**... | mting314/bruinwatch | src/bruinwatch/services/backfill.py | .py | f25f95c6766cd4a7 | 7 | 0 |
"""The change-detection rules, as pure functions.
Deliberately separated from :mod:`bruinwatch.services.sync`, which owns the SQL.
These rules are the part worth reasoning about carefully -- whether a scrape
result is worth a database row, a DM, or nothing at all -- so they are kept
free of any I/O and tested directly... | mting314/bruinwatch | src/bruinwatch/services/changes.py | .py | b342960f627e0f45 | 7 | 0 |
"""Delivers queued change notifications as Discord DMs.
Runs as its own loop, independent of scraping. Change events are already durably
recorded in ``notification_outbox``, so this can crash, restart, or fall behind
without losing or duplicating a message: a row is only stamped ``sent_at`` after
Discord accepts it.
... | mting314/bruinwatch | src/bruinwatch/services/notifier.py | .py | a8fa018ccb94e2ad | 7 | 0 |
"""Interactive components.
These replace the old emoji-reaction flows, which needed `bot.wait_for` with no
timeout inside `while True` loops, re-added reactions on every pass, and had no
way to tell one user's menu from another's.
Every view here is owned by a single user, expires on its own, and disables its
own com... | mting314/bruinwatch | src/bruinwatch/ui/views.py | .py | 435fbd04f85754b0 | 7 | 0 |
from __future__ import annotations
import asyncio
import os
import pathlib
from collections.abc import AsyncIterator, Iterator
import pytest
import pytest_asyncio
from sqlalchemy import text
from sqlalchemy.ext.asyncio import (
AsyncEngine,
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from... | mting314/bruinwatch | tests/conftest.py | .py | df08119bc93245e5 | 7.5 | 0 |
"""Getting a real PostgreSQL to test against, without Docker.
The schema leans on PostgreSQL-only features -- ``TEXT[]`` columns,
``INSERT ... ON CONFLICT ... RETURNING``, a partial index -- so the change
detection tests need a genuine engine, not SQLite pretending.
Two sources, in order:
1. ``BRUINWATCH_TEST_DATABA... | mting314/bruinwatch | tests/postgres.py | .py | 214b9525dc840930 | 7.5 | 0 |
"""Shared algorithm run setup."""
import numpy as np
from potion.evaluation.loggers import EpisodicOnlineLogger
def initialize_run(seed, logger):
"""Return independent training/evaluation RNGs and a fresh default logger."""
training_seed, evaluation_seed = np.random.SeedSequence(seed).spawn(2)
training_... | T3p/potion | potion/algorithms/_common.py | .py | 798ce02eb256fb9c | 7.24 | 2 |
"""Reusable helpers for plotting learning curves."""
from pathlib import Path
import matplot2tikz
import numpy as np
DEFAULT_CONFIDENCE = 0.95
DEFAULT_BOOTSTRAP_SAMPLES = 10_000
DEFAULT_BOOTSTRAP_SEED = 42
def bootstrap_mean_confidence_interval(
performance,
confidence=DEFAULT_CONFIDENCE,
n_bootstrap=... | T3p/potion | potion/visualization/plot_utils.py | .py | f6f75d20d44b39ee | 7.24 | 2 |
# Copyright 2020 Anver Housseini
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | autopkg/ahousseini-recipes | Aircall/AircallURLProvider.py | .py | 6081dfd05afc3a20 | 7.3 | 3 |
# Copyright 2020 Anver Housseini
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | autopkg/ahousseini-recipes | Archi/ArchiLatestGitHubTagProvider.py | .py | fc59716364ae50b9 | 7.8 | 3 |
# Copyright 2020 Anver Housseini
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | autopkg/ahousseini-recipes | Callbar/CallbarVersionProvider.py | .py | cdc85055198162c2 | 7.3 | 3 |
# Copyright 2023 Anver Housseini
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | autopkg/ahousseini-recipes | InstaShare/InstaShareURLProvider.py | .py | d69a71777b23cb44 | 7.3 | 3 |
# Copyright 2021 Anver Housseini
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | autopkg/ahousseini-recipes | Lens/LensVersionProvider.py | .py | 655c2e02280c7a4f | 7.3 | 3 |
# Copyright 2023 Anver Housseini
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | autopkg/ahousseini-recipes | SharedProcessors/HomebrewCaskURL.py | .py | d10f23ff34d2e86d | 7.3 | 3 |
# Copyright 2021 Anver Housseini
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | autopkg/ahousseini-recipes | SilhouetteStudio/SilhouetteStudioURLProvider.py | .py | 6248e34f4f4e166b | 7.8 | 3 |
import jsbeautifier
import json
import pathlib
import re
class CustomJSONEncoder(json.JSONEncoder):
""" Hacked JSONEncoder to output pretty float reprs. """
@staticmethod
def pretty_float_repr(x):
r1 = f"{x:g}"
r2 = f"{x:.16g}"
r = r1 if float(r1) == x else r2
r = r.replace... | polyfem/polyfem-data | contact/clean_example_jsons.py | .py | 95fdc5958d11bb72 | 7.39 | 5 |
"""Benchmark linear solvers."""
import pathlib
import argparse
import subprocess
import json
from datetime import datetime
import pandas
def get_time_stamp():
"""Get formated timestamp."""
return datetime.now().strftime("%Y-%b-%d-%H-%M-%S")
current_parents = pathlib.Path(__file__).resolve().parents
# Fin... | polyfem/polyfem-data | contact/compare_solvers.py | .py | 1e7ea43f61407372 | 7.39 | 5 |
import os
from contextlib import asynccontextmanager
from pathlib import Path
from connexion import AsyncApp
from connexion.resolver import RestyResolver
from connexion.options import SwaggerUIOptions
from rfidsecuritysvc.db.dbms import init_db, close_db
from rfidsecuritysvc.model.authorized import ensure_api_key
from ... | bcurnow/rfid-security-svc | rfidsecuritysvc/__init__.py | .py | 95cd0390c8448744 | 7 | 0 |
from connexion.context import request
from rfidsecuritysvc.model import sound as model
def get(name: str) -> dict | tuple[str, int, dict]:
m = model.get_by_name(name)
if m:
# IOS (and maybe others) require that the server support Range requests
# and the Content-Range header in order to play ... | bcurnow/rfid-security-svc | rfidsecuritysvc/api/player.py | .py | 3febeb278ef1b538 | 7 | 0 |
from functools import wraps
from typing import Any, Callable
import sys
import os
import sqlite3
from pathlib import Path
# Global database connection (thread-safe by check_same_thread=False)
_db_connection: sqlite3.Connection | None = None
def get_database_path() -> str:
"""Get the database path from environme... | bcurnow/rfid-security-svc | rfidsecuritysvc/db/dbms.py | .py | 4933e569c4ebb16a | 7 | 0 |
import base64
from datetime import datetime, timezone
from .base_model import BaseModel
from rfidsecuritysvc.db import sound as table
from typing import Self
import sqlite3
class Sound(BaseModel):
def __init__(self: Self, id: int, name: str, last_update_timestamp: str, content: str = None) -> None:
self.id... | bcurnow/rfid-security-svc | rfidsecuritysvc/model/sound.py | .py | a92b7e06426c36bc | 7 | 0 |
#!/usr/bin/env python3
"""
PreToolUse hook: deny shell commands listed in block-commands.txt
See block-commands.txt for the list of rejected commands
"""
import json
import shlex
import sys
from pathlib import Path
CONFIG_PATH = Path(__file__).with_name("block-commands.txt")
DENY_MESSAGE = "This command is on the de... | aobolensk/dotfiles | dotfiles/.claude/hooks/block-commands.py | .py | c281362ad9662558 | 7.24 | 2 |
#!/usr/bin/env python3
"""
PreToolUse hook: deny reading files whose name/path matches block-reads.txt
Covers the Read tool (file_path) and common shell read commands (cat, less,
head, tail, ...) passed to Bash. See block-reads.txt for the patterns.
"""
import fnmatch
import json
import shlex
import sys
from pathlib ... | aobolensk/dotfiles | dotfiles/.claude/hooks/block-reads.py | .py | 71620e464cec49de | 7.24 | 2 |
#!/usr/bin/env python3
"""
PostToolUse hook: run clang-format -i on edited C-family files.
Only formats when the extension is C-family and a .clang-format config governs
the file, so repos without config keep their style. Reads edited paths from
Claude (tool_input.file_path) or Codex (apply_patch command). Always exit... | aobolensk/dotfiles | dotfiles/.claude/hooks/clang-format.py | .py | d800f7524666727a | 7.24 | 2 |
from alembic import context
from logging.config import fileConfig
import json
from sqlalchemy import engine_from_config, pool
from sqlalchemy.engine.url import URL
from wts.models import db
from wts.utils import get_config_var
# this is the Alembic Config object, which provides
# access to the values within the .ini... | uc-cdis/workspace-token-service | migrations/env.py | .py | 29b9442503b8d38f | 7.35 | 4 |
"""Add IDP
Revision ID: 27833deaf81f
Revises: a38a346e6ded
Create Date: 2020-03-15 19:38:26.321139
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "27833deaf81f"
down_revision = "a38a346e6ded"
branch_labels = None
depends_on = None
def upgrade():
op.add_c... | uc-cdis/workspace-token-service | migrations/versions/27833deaf81f_add_idp.py | .py | ae8add71e3e96ad5 | 7.35 | 4 |
"""Encrypt refresh tokens
Revision ID: 3417aec47fe2
Revises: 27833deaf81f
Create Date: 2022-02-16 16:30:05.188696
"""
from alembic import op
from cryptography.fernet import Fernet
from wts.utils import get_config_var
# revision identifiers, used by Alembic.
revision = "3417aec47fe2"
down_revision = "27833deaf81f"
... | uc-cdis/workspace-token-service | migrations/versions/3417aec47fe2_encrypt_refresh_tokens.py | .py | c6959945eaff0b65 | 7.35 | 4 |
"""Create refresh_token table
Revision ID: a38a346e6ded
Revises:
Create Date: 2020-03-15 19:26:18.544300
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "a38a346e6ded"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# check whe... | uc-cdis/workspace-token-service | migrations/versions/a38a346e6ded_create_refresh_token_table.py | .py | 44f88aaef3d7ce6d | 7.35 | 4 |
from authlib.integrations.requests_client.oauth2_session import OAuth2Session
from authlib.common.urls import add_params_to_uri
from cryptography.fernet import Fernet
import flask
from flask import Flask
from importlib import metadata
import json
from urllib.parse import urlparse, urljoin
from cdislogging import get_lo... | uc-cdis/workspace-token-service | wts/api.py | .py | a90d70c816cf21ed | 7.35 | 4 |
import flask
from authutils.user import current_user
from wts.utils import get_oauth_client
class User(object):
def __init__(self, userid, username=None):
self.userid = userid
self.username = username
class AccessTokenPlugin(object):
def __init__(self):
pass
def find_user(self... | uc-cdis/workspace-token-service | wts/auth_plugins/base.py | .py | fac5e582fb84855b | 7.35 | 4 |
import flask
import time
from authutils.user import current_user
from ..models import db, RefreshToken
from ..utils import get_config_var, get_oauth_client
blueprint = flask.Blueprint("external_oidc", __name__)
blueprint.route("")
external_oidc_cache = {}
# this is called every 10 sec by the Gen3Fuse sidecar
@b... | uc-cdis/workspace-token-service | wts/blueprints/external_oidc.py | .py | e7836a8032b46012 | 7.35 | 4 |
import flask
from authlib.common.security import generate_token
from urllib.parse import urljoin
from authutils.user import current_user
from cdiserrors import APIError, UserError, AuthNError, AuthZError
from ..resources import oauth2
from ..utils import get_oauth_client
blueprint = flask.Blueprint("oauth2", __nam... | uc-cdis/workspace-token-service | wts/blueprints/oauth2.py | .py | 71c5e70af718cb4c | 7.35 | 4 |
from authlib.common.errors import AuthlibBaseError
from datetime import datetime
import flask
from jose import jwt
import uuid
from authutils.user import current_user
from cdiserrors import AuthError
from ..models import RefreshToken, db
from ..utils import get_oauth_client
def client_do_authorize():
requested_... | uc-cdis/workspace-token-service | wts/resources/oauth2.py | .py | fd127f4a3e986d18 | 7.35 | 4 |
import flask
import json
import os
from cdiserrors import UserError
def get_config_var(variable, default=None, secret_config={}):
"""
get a secret from env var or mounted secret dir,
raise exception if it doesn't exist
"""
path = os.environ.get("SECRET_CONFIG")
if not secret_config and path:
... | uc-cdis/workspace-token-service | wts/utils.py | .py | 19981df0b6adbd94 | 7.35 | 4 |
# -*- coding: utf-8 -*-
"""
Defines functionality to check case existence in dbGaP.
"""
import httpx
import re
import xmltodict
from cdislogging import get_logger
from xml.parsers.expat import ExpatError
from cdiserrors import InternalError, UserError
try:
from datamodelutils import models
except ModuleNotFoundE... | uc-cdis/authutils | src/authutils/dbgap.py | .py | 7b6cb8ffbee46d45 | 7 | 0 |
"""
Provide a basic set of endpoints for an application to implement OAuth client
functionality.
These endpoints assume that the ``current_app`` has already been configured
with an OAuth client instance from the ``authlib`` package as follows:
.. code-block:: python
from authutils.oauth2.client import OAuthClien... | uc-cdis/authutils | src/authutils/oauth2/client/blueprint.py | .py | 9b14c555e6ca3aad | 7 | 0 |
import httpx
import jwt
from ..errors import (
JWTAudienceError,
JWTExpiredError,
JWTPurposeError,
JWTScopeError,
JWTError,
)
def get_keys_url(issuer, force_issuer=None):
"""
Prefer OIDC discovery doc, but fall back on Fence-specific /jwt/keys for backwards compatibility (or if `force_iss... | uc-cdis/authutils | src/authutils/token/core.py | .py | b33d5bf9887159fd | 7 | 0 |
from asyncio import Future, get_event_loop
from collections import OrderedDict
import httpx
from fastapi import Security, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from starlette.status import HTTP_403_FORBIDDEN
from . import core
from .keys import get_pem_key
from ..errors i... | uc-cdis/authutils | src/authutils/token/fastapi.py | .py | 69aa175719726091 | 7 | 0 |
"""
Define functions for updating the public keys associated with certain token
issuers and retrieving the public key which can be used to verify a given JWT.
The public keys should be stored on the flask app in a `jwt_public_keys`
attribute, which will be a dictionary mapping issuer URLs (`iss` in a JWT) to
ordered d... | uc-cdis/authutils | src/authutils/token/keys.py | .py | 692b9d8dc0a00533 | 7 | 0 |
# pylint: disable=protected-access
"""
Define functions for validating a JWT and tracking the current token and claims
from a request.
"""
import flask
import functools
from cdislogging import get_logger
from werkzeug.local import LocalProxy
from . import core
from .keys import get_public_key_for_token
from ..errors ... | uc-cdis/authutils | src/authutils/token/validate.py | .py | 28e83231ba8d558c | 7 | 0 |
import functools
import json
from cached_property import cached_property
from cdiserrors import AuthZError
import flask
from werkzeug.local import LocalProxy
from authutils.errors import AuthError
from authutils.token.validate import set_current_token, validate_request
DEFAULT_TOKEN_AUDIENCE = "gen3"
def set_curre... | uc-cdis/authutils | src/authutils/user.py | .py | f81aa9eb647ec778 | 7 | 0 |
# level2-2
'''
from itertools import combinations
def solution(numbers, target):
answer = 0
# nC0, nC1, nC2, nC3, nC4, nCn-1\
n = len(numbers)
cnt = 0
s = sum(numbers)
for i in range(n):
for j in combinations([_ for _ in range(n)], i):
t = s
for k in j:
... | fabichoi/1d1p | 2020/src_43rd_week.py | .py | 4e78a00142bb9d83 | 7 | 0 |
# 50th week
# boj1173
'''
if __name__ == "__main__":
n, m, M, T, R = map(int, input().split(' '))
cnt = 0
now = m
if m + T > M:
print(-1)
else:
while n > 0:
if now + T <= M:
now += T
n -= 1
else:
if now - R >= ... | fabichoi/1d1p | 2020/src_50th_week.py | .py | dc2212435ff77a6c | 7 | 0 |
"""Change table names from plural to singular
Revision ID: fb5ed49d63d5
Revises: 7ea34679824b
Create Date: 2025-06-20 18:24:49.260276+00:00
"""
from collections.abc import Sequence
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "fb5ed49d63d5"
down_revision: str | None = "7ea34679824... | lsst-sqre/ook | alembic/versions/20250620_1824_fb5ed49d63d5_change_table_names_from_plural_to_.py | .py | 9531d89cb2a05519 | 7.15 | 1 |
"""Add affiliation metadata
Revision ID: 176f421b2597
Revises: fb5ed49d63d5
Create Date: 2025-07-07 17:30:56.922656+00:00
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "176f421b2597"
down_revision: str | None = "fb5e... | lsst-sqre/ook | alembic/versions/20250707_1730_176f421b2597_add_affiliation_metadata.py | .py | 9759c43e3786ad40 | 7.15 | 1 |
"""Add pg_trgm extension and search_vector for fuzzy author search
Revision ID: c03d146610d8
Revises: 1ad667eab84e
Create Date: 2025-07-30 20:10:18.783706+00:00
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "c03d1466... | lsst-sqre/ook | alembic/versions/20250730_2010_c03d146610d8_add_pg_trgm_extension_and_search_vector_.py | .py | ec89ca4d2f0c2857 | 7.15 | 1 |
"""Add address_country_code column
Revision ID: 8e529b9177a0
Revises: c03d146610d8
Create Date: 2025-08-05 15:42:15.097883+00:00
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "8e529b9177a0"
down_revision: str | None ... | lsst-sqre/ook | alembic/versions/20250805_1542_8e529b9177a0_add_address_country_code_column.py | .py | 4507a3a91a106aa5 | 7.15 | 1 |
"""Add author_alias table
Revision ID: 34ea7479b953
Revises: 8e529b9177a0
Create Date: 2026-06-10 19:08:15.259400+00:00
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "34ea7479b953"
down_revision: str | None = "8e529b... | lsst-sqre/ook | alembic/versions/20260610_1908_34ea7479b953_add_author_alias_table.py | .py | 8ed0c4fd9edcf24f | 7.15 | 1 |
"""Add origin_paths to linkcheck_check_url
Revision ID: e3224f7fa2cb
Revises: 97e2df2ad883
Create Date: 2026-07-07 20:14:25.536129+00:00
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "e3224f7fa2cb"
down_revision: str... | lsst-sqre/ook | alembic/versions/20260707_2014_e3224f7fa2cb_add_origin_paths_to_linkcheck_check_url.py | .py | bcfcfebc2e29df59 | 7.15 | 1 |
"""Drop linkcheck_check id autoincrement
Revision ID: a62deab01a9b
Revises: e3224f7fa2cb
Create Date: 2026-07-08 15:29:52.734130+00:00
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "a62deab01a9b"
down_revision: str |... | lsst-sqre/ook | alembic/versions/20260708_1529_a62deab01a9b_drop_linkcheck_check_id_autoincrement.py | .py | aa8e62d56016bb0f | 7.15 | 1 |
"""Re-mint resource IDs in date_created order
Revision ID: cf936213314d
Revises: a62deab01a9b
Create Date: 2026-07-08 16:00:00.000000+00:00
This is a one-time, deliberate resource-ID break (PRD ook#238, decision D1). It
re-mints every ``resource.id`` as a time-ordered Crockford Base32 identifier
derived from the row'... | lsst-sqre/ook | alembic/versions/20260708_1600_cf936213314d_remint_resource_ids_time_ordered.py | .py | 49ee9e3a34bc684c | 7.15 | 1 |
"""Add external_reference url index and dedup key constraint
Revision ID: 20144e072aa7
Revises: 3b66bd60b53f
Create Date: 2026-07-08 20:48:54.283338+00:00
The ``_upsert_external_reference`` upsert path (PRD ook#238, issue 1.3)
resolves DOI-less references with ``ON CONFLICT (url)``, but no unique index
backed the ``u... | lsst-sqre/ook | alembic/versions/20260708_2048_20144e072aa7_add_external_reference_url_index_and_.py | .py | 6575317d35d085db | 7.15 | 1 |
"""Add intersphinx inventory table
Revision ID: c2a2c14c0e60
Revises: 818fdc36974d
Create Date: 2026-07-09 21:15:57.408740+00:00
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "c2a2c14c0e60"
down_revision: str | None ... | lsst-sqre/ook | alembic/versions/20260709_2115_c2a2c14c0e60_add_intersphinx_inventory_table.py | .py | d9b46967f345e8c2 | 7.15 | 1 |
"""Add consecutive_blocked_count to checked_url
Revision ID: 818fdc36974d
Revises: 20144e072aa7
Create Date: 2026-07-10 20:34:16.073658+00:00
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "818fdc36974d"
down_revision... | lsst-sqre/ook | alembic/versions/20260710_2034_818fdc36974d_add_consecutive_blocked_count_to_.py | .py | aef7dd62424cda26 | 7.15 | 1 |
"""Add resolved redirect columns to intersphinx_inventory
Revision ID: 4acb43afff3d
Revises: c2a2c14c0e60
Create Date: 2026-08-13 22:45:00.271202+00:00
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "4acb43afff3d"
dow... | lsst-sqre/ook | alembic/versions/20260813_2245_4acb43afff3d_add_resolved_redirect_columns_to_.py | .py | 95846abef521d028 | 7.15 | 1 |
"""Add refresh failure backoff to intersphinx_inventory
Revision ID: 6f68334c9c9b
Revises: 4acb43afff3d
Create Date: 2026-08-14 01:39:58.422768+00:00
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "6f68334c9c9b"
down_... | lsst-sqre/ook | alembic/versions/20260814_0139_6f68334c9c9b_add_refresh_failure_backoff_to_.py | .py | 9fbdd17f07d38d1e | 7.15 | 1 |
"""Add linkcheck contributions and result source
Revision ID: 0bfe17a5f990
Revises: 6f68334c9c9b
Create Date: 2026-08-20 19:14:43.491407+00:00
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "0bfe17a5f990"
down_revisio... | lsst-sqre/ook | alembic/versions/20260820_1914_0bfe17a5f990_add_linkcheck_contributions_and_result_.py | .py | aac42c5f27e24b3a | 7.15 | 1 |
"""Rename linkcheck datetime columns to the date_ prefix
Revision ID: f43554a10acb
Revises: 0bfe17a5f990
Create Date: 2026-08-21 15:03:00.000000+00:00
"""
from collections.abc import Sequence
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "f43554a10acb"
down_revision: str | None = "... | lsst-sqre/ook | alembic/versions/20260821_1503_f43554a10acb_rename_linkcheck_datetime_columns_to_.py | .py | 335504e84dc5fd4c | 7.15 | 1 |
"""Administrative command-line interface."""
from __future__ import annotations
import asyncio
import re
import subprocess
from dataclasses import dataclass
from datetime import timedelta
from itertools import batched
from pathlib import Path
from typing import Any
import click
import structlog
from algoliasearch.se... | lsst-sqre/ook | src/ook/cli.py | .py | 15817ef47a52fba4 | 7.15 | 1 |
"""Database models for the Observatory glossary."""
from __future__ import annotations
from datetime import datetime
from typing import Any
from sqlalchemy import (
Boolean,
Column,
DateTime,
ForeignKey,
Integer,
Table,
UnicodeText,
UniqueConstraint,
)
from sqlalchemy.dialects.postgre... | lsst-sqre/ook | src/ook/dbschema/glossary.py | .py | af23f4e4991cb6cd | 7.15 | 1 |
"""Dependency for managing an Algolia search index."""
from __future__ import annotations
from algoliasearch.search_client import SearchClient
from ..config import config
class AlgoliaSearchDependency:
"""Provides an Algolia SearchClient as a FastAPI dependency."""
def __init__(self) -> None:
self... | lsst-sqre/ook | src/ook/dependencies/algoliasearch.py | .py | 552e0814c47f31c7 | 7.15 | 1 |
"""A dependency for providing context to consumers."""
from dataclasses import dataclass
from typing import Annotated, Any
from aiokafka import ConsumerRecord
from fastapi import Depends
from faststream.kafka import KafkaMessage as _KafkaMessage
from faststream_fastapi import Context
from safir.dependencies.db_sessio... | lsst-sqre/ook | src/ook/dependencies/consumercontext.py | .py | 17af90a197c93013 | 7.15 | 1 |
"""Request context dependency for FastAPI.
This dependency gathers a variety of information into a single object for the
convenience of writing request handlers. It also provides a place to store a
`structlog.BoundLogger` that can gather additional context during processing,
including from dependencies.
"""
from dat... | lsst-sqre/ook | src/ook/dependencies/context.py | .py | 942114061648bf08 | 7.15 | 1 |
"""Domain models for Algolia records."""
from __future__ import annotations
import uuid
from base64 import b64encode
from datetime import UTC, datetime
from enum import StrEnum
from typing import Any, Self
from pydantic import BaseModel, ConfigDict, Field, HttpUrl
__all__ = ["DocumentRecord", "DocumentSourceType", ... | lsst-sqre/ook | src/ook/domain/algoliarecord.py | .py | 5927feae1d964321 | 7.15 | 1 |
"""Country code normalization utilities for author affiliations."""
from __future__ import annotations
from functools import lru_cache
import pycountry
__all__ = ["get_country_name", "normalize_country_code"]
# Custom mapping for known non-standard country codes and names
# All keys are stored in uppercase for cas... | lsst-sqre/ook | src/ook/domain/authors/_countries.py | .py | 8ebd98d288d11306 | 7.15 | 1 |
"""Domain model for authors and affiliations."""
from __future__ import annotations
from i18naddress import format_address
from pydantic import BaseModel, Field
from ._countries import get_country_name
__all__ = ["Address", "Affiliation", "Author", "AuthorSearchResult"]
class Address(BaseModel):
"""An address... | lsst-sqre/ook | src/ook/domain/authors/_models.py | .py | a1234684ba4dc98c | 7.15 | 1 |
"""Name parsing utilities for author search functionality."""
from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from typing import ClassVar
class NameFormat(Enum):
"""Enum representing different name formats that can be parsed."""
FIRST_LAST = "first_last" # "Jonat... | lsst-sqre/ook | src/ook/domain/authors/_nameparser.py | .py | 23fc7b8631a1cfbf | 7.15 | 1 |
"""Normalization and validation of ORCID identifiers."""
from __future__ import annotations
import re
from typing import Annotated
from pydantic import BeforeValidator
__all__ = ["Orcid", "normalize_orcid"]
_ORCID_URL_PREFIX_PATTERN = re.compile(
r"^(?:https?://)?(?:www\.)?orcid\.org/", re.IGNORECASE | re.ASCI... | lsst-sqre/ook | src/ook/domain/authors/_orcid.py | .py | 119346a4440207e7 | 7.15 | 1 |
from scipy.stats import norm
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.linear_model import BayesianRidge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer
class GenericRegressor(BaseEstimator, RegressorMixin):
r"""
Uses a linear regressi... | mghasemi/nonlinear-regression | GeneralRegression/GeneralRegression.py | .py | 7c5080779577e738 | 7.15 | 1 |
"""
Time Series Tools
========================
"""
from abc import ABCMeta
from sklearn.model_selection import BaseCrossValidator
class TimeSeriesCV(BaseCrossValidator, metaclass=ABCMeta):
"""
This is a very naive cross validator for time series. It simply sorts the given index (default 0)
and splits the... | mghasemi/nonlinear-regression | GeneralRegression/ModelSelection.py | .py | ba4e297d31380fd8 | 7.15 | 1 |
from pathlib import Path
from typing import Annotated
import typer
from . import preparator
from .plotter import BLUE, DARK_GRAY, generate_skill_picture
from .preparator import DEFAULT_SKILL_FILE_NAME
from .utils import PictureTypes, StyleTypes, failure_print, version_callback
app = typer.Typer()
_SKILL_GROUP_ARG ... | AndreWohnsland/skillplotter | skill_plotter/main.py | .py | 534e2e947841fbb7 | 7.39 | 5 |
import matplotlib.pyplot as plt
from matplotlib import patheffects
from matplotlib.axes import Axes
from matplotlib.patches import FancyBboxPatch
from .preparator import split_dict_evenly
from .utils import StyleTypes
DARK_GRAY = "#404040"
BLUE = "#367DA2"
WHITE = "#ffffff"
_COLOR = str | tuple[float, float, float]
... | AndreWohnsland/skillplotter | skill_plotter/plotter.py | .py | 996c8352b5bd5d09 | 7.39 | 5 |
import json
from pathlib import Path
from typing import Any
import jsonschema
import typer
from .utils import failure_print, info_print, success_print
_APP_NAME = "skill-plotter"
_app_dir = Path(typer.get_app_dir(_APP_NAME))
DEFAULT_SKILL_FILE_NAME = "skills"
_DEFAULT_CATEGORY = "default"
# Validate the data again... | AndreWohnsland/skillplotter | skill_plotter/preparator.py | .py | 710e9ff8cffc283b | 7.39 | 5 |
"""Module for utility functions and constants."""
from enum import StrEnum
import typer
from . import __version__
class PictureTypes(StrEnum):
"""Save file types."""
SVG = "svg"
PNG = "png"
JPG = "jpg"
PDF = "pdf"
class StyleTypes(StrEnum):
"""Different types of styling for the plot."""
... | AndreWohnsland/skillplotter | skill_plotter/utils.py | .py | f8681d803ed1fb1b | 7.39 | 5 |
from django.core.exceptions import ValidationError
from django.db import transaction
from django.forms import BaseInlineFormSet, CharField, DateInput, Textarea
from django_tomselect.forms import TomSelectConfig, TomSelectModelChoiceField
from utils.forms import (
MARKDOWN_HELP_TEXT,
ModalModelFormMixin,
Si... | lueho/BRIT | bibliography/forms.py | .py | 335cae809d0e7c48 | 7.24 | 2 |
from extra_views import InlineFormSetFactory
from .models import SourceAuthor
class SourceAuthorInline(InlineFormSetFactory):
model = SourceAuthor
fields = ("author",)
factory_kwargs = {
"extra": 0,
"min_num": 0, # Allow Sources without authors (was 1)
"can_delete": True,
}
... | lueho/BRIT | bibliography/inlines.py | .py | ab9e60bf51eab364 | 7.24 | 2 |
import string
import celery
from django.db import models, transaction
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from utils.object_management.models import (
NamedUserCreatedObject,
UserCreatedObject,
UserCreatedObjectManager,
)
class Author(UserCrea... | lueho/BRIT | bibliography/models.py | .py | cf6845ac74d676e3 | 7.24 | 2 |
import itertools
import math
import time
from functools import lru_cache
from typing import List
from typing import Sequence
from typing import Union
from nmd.emd_1d import emd_1d_dp
from nmd.emd_1d import emd_1d_hybrid
from nmd.emd_1d import emd_1d_old as emd_1d_fast_original
# Assume emd_1d_slow and potentially ot... | averykhoo/ngram-movers-distance | experiments/correctness-test.py | .py | 493b3e71b6fe3255 | 7.5 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.