text
string
repo
string
path
string
language
string
hash
string
score
float64
stars
int64
"""Preprocessing helpers: clonotype grouping and clone sizes. Deliberately light on imports — this module is loaded by ``import tcri``, so an eager ``import umap`` here cost ~2.9 s of every import (umap → pynndescent → numba/llvmlite) for a dependency this file never used. """ import numpy as np from .._state import ...
nceglia/tcri
tcri/preprocessing/_preprocessing.py
.py
398db6210df3a27d
7.5
9
"""``tl.delta_*`` — the paired (``cov_from`` -> ``cov_to``) forms of the two entropies. **Why only two.** A cross-covariate comparison belongs in the API when producing it requires applying a metric at a level the public surface does not expose — the scope principle in the API contract. The entropies reduce to an item...
nceglia/tcri
tcri/tools/_delta.py
.py
9f89919842f2a34d
7.5
9
"""``tl.clonotypic_entropy`` and ``tl.phenotypic_entropy`` — normalized Shannon entropies in **bits** (§7.2/§7.3), engine-backed. - ``clonotypic_entropy``: per phenotype φ, H[P(c|φ)] over the **supported** clones (spread of a phenotype across clones). Absent/zero-support clones are excluded before normalizing (no ...
nceglia/tcri
tcri/tools/_entropy.py
.py
cd6b730c1cd1ed03
7.5
9
"""``tl.mutual_information`` — clone↔phenotype coupling I(c;φ|m) in **bits** (§7.4). Default ``normalize_mode="min"`` — the coefficient of constraint, I/min(H_c,H_p). The ``"average"`` denominator (classical NMI) scales with log2(C) and is not comparable across groups with different clone counts, which is why it is no...
nceglia/tcri
tcri/tools/_mutual_information.py
.py
9f6acd4878cb9bf8
7.5
9
from lxml import etree from caselawclient.xml_helpers import DEFAULT_NAMESPACES from ..models.documents import Document from ..models.judgments import Judgment from ..models.parser_logs import ParserLog from ..models.press_summaries import PressSummary class CannotDetermineDocumentType(Exception): pass def ge...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/client_helpers/__init__.py
.py
b695d68f0040a8e7
7.52
10
""" The content hash is the SHA256 hash of the judgment text with all whitespace removed. This is intended to confirm that various processing has not changed the content of the judgment, whilst allowing variations in the XML which might not allow for preservation of whitespace. The canonical version of this hashing fu...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/content_hash.py
.py
d1c3c2e0ea0006ad
7.52
10
import json from typing import NamedTuple from caselawclient.models.identifiers import Identifier from caselawclient.models.identifiers.unpacker import IDENTIFIER_NAMESPACE_MAP from caselawclient.types import DocumentIdentifierSlug, DocumentIdentifierValue from caselawclient.xquery_type_dicts import MarkLogicDocumentU...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/identifier_resolution.py
.py
925e0c8dc4ced0b2
7.52
10
from caselawclient.managers.merge import checks from caselawclient.models.documents import Document from caselawclient.types import SuccessFailureMessageTuple def _combine_list_of_successfailure_results( validations: list[SuccessFailureMessageTuple], ) -> SuccessFailureMessageTuple: """Given a list of Success...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/managers/merge/__init__.py
.py
64e57e94b6178c20
7.52
10
import datetime import os import warnings from functools import cached_property from ds_caselaw_utils.types import CourtCode from saxonche import PySaxonProcessor from typing_extensions import deprecated from caselawclient.models.documents.metadata.types.date import date_as_string_from_value from caselawclient.models...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/documents/body.py
.py
fc1569a225539372
7.52
10
from typing import TypedDict import caselawclient.models.documents class AttributeComparison(TypedDict): """Results from a comparison of one attribute across two documents""" label: str this_value: str that_value: str match: bool class Comparison(dict[str, AttributeComparison]): def __init...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/documents/comparison.py
.py
22b12b78f527a6cc
7.52
10
from abc import ABC, abstractmethod from collections.abc import Iterable from typing import TYPE_CHECKING, ClassVar, Generic, TypeVar from caselawclient.models.documents.metadata.fields.field import ( MetadataCategoryValue, MetadataField, MetadataFieldValue, ) from caselawclient.models.documents.metadata.f...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/documents/metadata/base.py
.py
9de4187c91ed9989
7.52
10
from lxml import etree from caselawclient.models.documents.metadata.fields.exceptions import ( MetadataFieldRemovalNotAllowedException, ) from caselawclient.models.documents.metadata.fields.field import MetadataField, MetadataFieldValue from caselawclient.models.documents.metadata.fields.resolution import Resolved...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/documents/metadata/fields/collection.py
.py
94cfb44b7512ce02
7.52
10
class InvalidMetadataFieldXMLRepresentationException(Exception): """Raised when a metadata field cannot be unpacked from XML.""" class MetadataFieldRemovalNotAllowedException(Exception): """Raised when attempting to hard-remove a non-editor metadata claim.""" class MetadataFieldValidationException(Exception...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/documents/metadata/fields/exceptions.py
.py
32b101d1392014d4
7.02
10
from dataclasses import dataclass from datetime import UTC, datetime from typing import Union from uuid import uuid4 from lxml import etree from caselawclient.models.documents.metadata.fields.source import MetadataSource from caselawclient.xml_helpers import Element MetadataFieldValue = Union[str, "MetadataCategoryV...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/documents/metadata/fields/field.py
.py
0acb9728e5c936ef
7.52
10
from caselawclient.models.documents.metadata.fields.field import MetadataField, MetadataFieldValue from caselawclient.models.documents.metadata.fields.source import MetadataSource def _claim_sort_key(claim: MetadataField) -> tuple[int, float, str]: """Order by source precedence, then first-seen time, then id. ...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/documents/metadata/fields/resolution.py
.py
65052599d91343fd
7.52
10
from enum import Enum class MetadataSource(str, Enum): """Origin of a metadata claim, ordered from lowest to highest precedence.""" DOCUMENT = "document" EXTERNAL = "external" EDITOR = "editor" @property def precedence(self) -> int: """Higher numbers outrank lower ones when resolving...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/documents/metadata/fields/source.py
.py
9d165c256be5a86e
7.02
10
"""Import-time metadata materialisation version derived from per-field LOGIC_VERSION.""" from __future__ import annotations import hashlib import json from typing import TYPE_CHECKING from caselawclient.models.documents.metadata.types.case_number import CaseNumberMetadata from caselawclient.models.documents.metadata...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/documents/metadata/materialisation.py
.py
2c29f116dbf2d574
7.52
10
from caselawclient.models.documents.metadata.base import MultipleMetadata from caselawclient.models.documents.metadata.fields.exceptions import MetadataFieldRemovalNotAllowedException from caselawclient.models.documents.metadata.fields.field import MetadataField, MetadataFieldValue from caselawclient.models.documents.m...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/documents/metadata/types/judges.py
.py
48bc27289f0b0ebc
7.52
10
import json from enum import Enum from typing import Any, TypedDict from typing_extensions import NotRequired class AnnotationDataDict(TypedDict): type: str calling_function: str calling_agent: str message: NotRequired[str] payload: NotRequired[dict[str, Any]] automated: bool class VersionT...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/documents/versions.py
.py
7c439fbc3c99d962
7.52
10
import os from lxml import etree from caselawclient.xml_helpers import ( DEFAULT_NAMESPACES, Element, get_xpath_match_string, get_xpath_match_strings, get_xpath_nodes, ) def _xslt_path(xslt_file_name: str) -> str: from caselawclient.Client import ROOT_DIR return os.path.join(ROOT_DIR, "...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/documents/xml.py
.py
1536fd2e636d15d0
7.52
10
from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any from uuid import uuid4 from lxml import etree from caselawclient.types import DocumentIdentifierSlug, DocumentIdentifierValue, SuccessFailureMessageTuple from caselawclient.xml_helpers import Element from .exceptions import IdentifierValidatio...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/identifiers/__init__.py
.py
a75bbafe202dd165
7.52
10
from typing import TYPE_CHECKING from lxml import etree from caselawclient.types import SuccessFailureMessageTuple from caselawclient.xml_helpers import Element from . import Identifier, IdentifierSchema from .fclid import FindCaseLawIdentifier from .neutral_citation import NeutralCitationNumber from .press_summary_...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/identifiers/collection.py
.py
595c931897e7cf34
7.52
10
import re from typing import TYPE_CHECKING from sqids import Sqids from caselawclient.types import DocumentIdentifierSlug from . import Identifier, IdentifierSchema if TYPE_CHECKING: from caselawclient.Client import MarklogicApiClient VALID_FCLID_PATTERN = re.compile(r"^[bcdfghjkmnpqrstvwxyz23456789]{4,}$") ...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/identifiers/fclid.py
.py
863f33f9585716b5
7.52
10
import re from ds_caselaw_utils import neutral_url from ds_caselaw_utils.types import NeutralCitationString from caselawclient.types import DocumentIdentifierSlug from . import Identifier, IdentifierSchema from .exceptions import IdentifierValidationException VALID_NCN_PATTERN = re.compile(r"(^\[([0-9]{4})\] ([a-zA...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/identifiers/neutral_citation.py
.py
6d801e5c7566fe5b
7.52
10
from caselawclient.types import DocumentIdentifierSlug from .neutral_citation import NeutralCitationNumber, NeutralCitationNumberSchema class PressSummaryRelatedNCNIdentifierSchema(NeutralCitationNumberSchema): """ Identifier schema for relating a Press Summary to a Judgment with a given NCN """ nam...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/identifiers/press_summary_ncn.py
.py
b7ec7a3ec11edadc
7.52
10
from warnings import warn from caselawclient.xml_helpers import Element from . import IDENTIFIER_UNPACKABLE_ATTRIBUTES, Identifier from .collection import SUPPORTED_IDENTIFIER_TYPES, IdentifiersCollection from .exceptions import InvalidIdentifierXMLRepresentationException IDENTIFIER_NAMESPACE_MAP: dict[str, type[Ide...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/identifiers/unpacker.py
.py
823be2778c60ce5b
7.52
10
import importlib from functools import cached_property from typing import TYPE_CHECKING, Any, Optional from ds_caselaw_utils.types import NeutralCitationString from caselawclient.errors import DocumentNotFoundError from caselawclient.identifier_resolution import IdentifierResolutions from caselawclient.models.neutral...
nationalarchives/ds-caselaw-custom-api-client
src/caselawclient/models/judgments.py
.py
9c31fe4896ec45a9
7.52
10
"""Library for reading the terraform database.""" import pathlib import re import yaml import yaml.parser from .exceptions import HostDbException from .manifest import SERVICE_MATCH, Machine, Manifest from .validation import validate_manifest from .yaml_loaders import yaml_decode class HostDb: """Library for m...
allenporter/hostdb
hostdb/hostdb.py
.py
4c2d7c07a29d26aa
7.5
9
"""An ansible inventory module based on hostdb backed by hostdb. This has some custom helpers for building etcd inventory. """ import dataclasses import logging import os import pathlib from ansible.errors import AnsibleParserError from ansible.plugins.inventory import BaseInventoryPlugin from . import exceptions, ...
allenporter/hostdb
hostdb/inventory.py
.py
5f886423aab24a7e
7.5
9
"""Manifest definitions for the hostdb package. This file contains all of the dataclass definitions for the hostdb package. """ from dataclasses import dataclass, field # "sto01" becomes ("sto", "01") SERVICE_MATCH = r"([a-z|_|-]+)(\d+)" @dataclass class Network: """Network configuration.""" subnet: str ...
allenporter/hostdb
hostdb/manifest.py
.py
3fa9da9d94807d25
7.5
9
"""Functions for generating hostnames.""" import random from importlib.resources import files PACKAGE = "hostdb.resources" WORDLIST = "wordlist" def _build_hostname_set() -> dict[str, str]: """Return the hostname set from the wordlist.""" words: dict[str, str] = {} text = files(PACKAGE).joinpath(WORDLIS...
allenporter/hostdb
hostdb/naming.py
.py
f34ae542212485f9
7.5
9
#!/usr/bin/env python # # Tool for allocating a hostname from a list of words and set of existing # hosts. The tool prints out a new hostname that should be added to the # database. import logging import pathlib import sys import traceback from argparse import ( ArgumentParser, ) from argparse import ( _SubPa...
allenporter/hostdb
hostdb/tool/main.py
.py
cc627f705436e94b
7.5
9
"""Initialize the yaml_loaders extensions.""" from pathlib import Path from typing import Any, TypeVar import yaml from mashumaro.codecs.yaml import YAMLDecoder T = TypeVar("T") _DEFAULT_LOADER = getattr(yaml, "CSafeLoader", yaml.SafeLoader) class FastSafeLoader(_DEFAULT_LOADER): """The fastest available safe...
allenporter/hostdb
hostdb/yaml_loaders/__init__.py
.py
b58ec4face2ee467
7.5
9
"""Tests for hostdb.""" import pathlib import pytest from hostdb.exceptions import HostDbException from hostdb.hostdb import HostDb from hostdb.manifest import Machine, Manifest EXAMPLES = pathlib.Path.cwd() / pathlib.Path("examples") EXAMPLE_CONFIG = EXAMPLES / "manifest.yaml" TESTDATA = pathlib.Path.cwd() / pathl...
allenporter/hostdb
tests/test_hostdb.py
.py
ab8eb738ae0d9891
8
9
"""Tests for the hostname allocation logic.""" import random import pytest from hostdb.naming import allocate_hostnames @pytest.mark.parametrize( ("allocated", "expected"), [ ({}, ["exile", "friend", "falcon", "lagoon", "earth"]), ({"linear"}, ["exile", "friend", "falcon", "lagoon", "earth"...
allenporter/hostdb
tests/test_naming.py
.py
241ad7b3fd74fb7f
7
9
"""Formatting helpers for Streamlit metrics and tables.""" from __future__ import annotations import math import pandas as pd from strava_data.strava_api.visualisation.interactive_utils import ( format_pace as format_interactive_pace, ) def format_duration(seconds: float | int) -> str: """Format seconds a...
c-wilkinson/StravaDataAnalysis
src/dashboard/formatting.py
.py
205f25187d54504f
7.66
20
""" Handles Strava OAuth token retrieval and refresh logic. """ import json import time import requests from strava_data.config import get_client_id, get_client_secret from strava_data.db.dao import read_tokens, store_tokens from utils.logger import get_logger LOGGER = get_logger() def get_or_refresh_tokens() -> No...
c-wilkinson/StravaDataAnalysis
src/strava_data/auth.py
.py
108b697235d827c4
7.66
20
""" Global configuration and environment variable handling for Strava secrets and optional encryption. """ import os CONFIG_FILE = "config.txt" # pylint: disable=C0103 # Attempt to read password / buffer size from local config file if os.path.isfile(CONFIG_FILE): with open(CONFIG_FILE, "r", encoding="utf-8") as ...
c-wilkinson/StravaDataAnalysis
src/strava_data/config.py
.py
afa4a5154b418fab
7.66
20
""" Data Access Object (DAO) layer for reading/writing tokens and activity data. Uses pyAesCrypt to decrypt/encrypt the SQLite database file, but only once at program start/end. """ import os import sqlite3 from os import stat from typing import Any, Dict, Optional from datetime import datetime import pandas as pd im...
c-wilkinson/StravaDataAnalysis
src/strava_data/db/dao.py
.py
338644650b816edc
7.66
20
""" Data classes or schemas representing Strava data in Python. """ from dataclasses import dataclass from typing import Optional @dataclass class Activity: # pylint: disable=too-many-instance-attributes """ Represents a single Strava activity row. """ activity_id: int name: str activity...
c-wilkinson/StravaDataAnalysis
src/strava_data/db/models.py
.py
8f91e33e247e2303
7.66
20
""" Machine learning to forecast pace """ from pathlib import Path import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import Ridge from sklearn.model_selection import TimeSeriesSplit, cross_val_score from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from...
c-wilkinson/StravaDataAnalysis
src/strava_data/ml/pace_forecast.py
.py
1284a6d7db6c9651
7.66
20
""" Machine learning to classify run types (e.g. Easy, Tempo, Intervals, Long) """ from pathlib import Path import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler from sklearn.metrics import silhouette_score from st...
c-wilkinson/StravaDataAnalysis
src/strava_data/ml/run_type_classifier.py
.py
a490821da644cc15
7.66
20
""" Generates a weekly training recommendation chart based on recent Strava activity. - Analyses the past 6 months to determine usual running days. - Reviews the last 8 weeks of runs to identify missing session types. - Uses historical pace data to tailor pace suggestions. - Assigns recommended runs to the days you ty...
c-wilkinson/StravaDataAnalysis
src/strava_data/ml/training_advisor.py
.py
c581a965d1984f9b
7.66
20
""" Data transformation utilities for activities and splits. """ import pandas as pd import numpy as np def transform_activities(activities_df: pd.DataFrame) -> pd.DataFrame: """ Cleans and enriches raw Strava activities. :param activities_df: Raw DataFrame from Strava's /activities endpoint. :retur...
c-wilkinson/StravaDataAnalysis
src/strava_data/strava_api/processing/transform.py
.py
d29f93f4da567293
7.66
20
"""Shared helpers for Plotly versions of the existing Strava charts.""" from __future__ import annotations import math import numpy as np import pandas as pd import plotly.graph_objects as go def format_pace(seconds_per_km: float | int) -> str: """Format seconds per kilometre as minutes and seconds.""" if ...
c-wilkinson/StravaDataAnalysis
src/strava_data/strava_api/visualisation/interactive_utils.py
.py
acb32d6b641062c1
7.66
20
""" Render Strava-style summary cards (weekly / monthly / yearly) as PNG images. Public entrypoint: - render_week_month_year_cards(activities_df, splits_df, output_dir) This module follows the existing visualisation style: - accepts DataFrames - does prep + computation internally - writes PNGs to disk """ from __fut...
c-wilkinson/StravaDataAnalysis
src/strava_data/strava_api/visualisation/summary_cards.py
.py
63dbe0eb98a521f0
7.66
20
""" Utilities for chart styling or other shared visualisation helpers. """ import calendar from dataclasses import dataclass import datetime from typing import Callable, Optional, Tuple, List import matplotlib.pyplot as plt from matplotlib.patches import FancyBboxPatch from matplotlib.text import Text import numpy as...
c-wilkinson/StravaDataAnalysis
src/strava_data/strava_api/visualisation/utils.py
.py
883755965d847f1c
7.66
20
"""Architecture tests for the standalone dashboard data boundary.""" import ast from pathlib import Path DASHBOARD_DIRECTORY = Path(__file__).resolve().parents[1] / "dashboard" def test_dashboard_package_has_no_database_imports(): """The Streamlit layer must consume Parquet rather than the SQLite DAO.""" f...
c-wilkinson/StravaDataAnalysis
src/tests/test_dashboard_boundary.py
.py
cad05c313bf7dd28
7.16
20
"""Tests for database fields required by the Parquet dashboard export.""" import sqlite3 from strava_data.db import dao def test_init_database_migrates_existing_activity_table(tmp_path, monkeypatch): """An existing encrypted-database schema gains dashboard activity fields.""" database_path = tmp_path / "str...
c-wilkinson/StravaDataAnalysis
src/tests/test_dashboard_database_fields.py
.py
f4a5a8528ef4c1bd
7.16
20
"""Tests for dashboard-only formatting helpers.""" import pandas as pd from dashboard.formatting import rounded_numeric def test_rounded_numeric_handles_nat_and_zero_values(): """Nullable display columns do not call ``round`` on ``NaT`` objects.""" values = pd.Series([171.234, pd.NaT, 0], dtype="object") ...
c-wilkinson/StravaDataAnalysis
src/tests/test_dashboard_formatting.py
.py
d7c53a15b0a9dcd5
7.16
20
""" Markata Plugin: Chart.js Renderer This plugin converts Chart.js code blocks in Markdown files into rendered Chart.js charts. # Installation Ensure Chart.js is available in your site. If serving locally, add the script to your template: ```html <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <scrip...
WaylonWalker/waylonwalker.com
plugins/chartjs.py
.py
105d3f44cc9bffa4
7.6
15
""" CSV Fence to Table Plugin Converts fenced code blocks with ```csv into rendered HTML tables. # Installation ```toml [markata] hooks = ["markata.plugins.csv_fence_table"] ``` # Configuration None required. # Usage Use markdown fences like this: ```csv name,age,city Alice,30,New York Bob,25,San Francisco Char...
WaylonWalker/waylonwalker.com
plugins/csv_fence.py
.py
5e24d8cef72106b6
7.6
15
""" Dropper Media Wrapper Plugin Wraps images and videos served from Dropper in links to their original source and optionally adds a `?width=` query parameter when none is present. # Installation ```toml hooks = [ "markata.plugins.load", "plugins.dropper", # or the path where you place this file ] ``` # Config...
WaylonWalker/waylonwalker.com
plugins/dropper_resize.py
.py
826b1852ccfd2d5f
7.6
15
""" Meta Ampersand Fix Stopgap plugin: in rendered HTML stored in `post.html` (a dict[str, str]), find all `<meta ...>` tags and replace `&amp;` with `&` **only inside those meta tags**. This is useful when upstream templating/rendering double-escapes ampersands in meta tag attribute values (e.g. `content="a&amp;b"`)...
WaylonWalker/waylonwalker.com
plugins/fix_og_encoding.py
.py
8c1010ab2943b6bb
7.6
15
import typer from markata.hookspec import hook_impl from more_itertools import flatten, unique_everseen from rich import console console = console.Console() IGNORE_TAGS = [ "rss", "", ] def check_feed_conflicts(tag, existing_feeds): """Check for conflicts between a tag and existing feeds.""" conflic...
WaylonWalker/waylonwalker.com
plugins/generate_feed_conf.py
.py
76efc95ee73edd1a
7.6
15
""" glossary - inline glossary definitions # Installation ```toml hooks = [ "markata.plugins.glossary", ] ``` # Configuration ```toml [markata.glossary] filter = 'post.templateKey == "glossary"' # filter to find glossary posts template = "{{ term }}" # jinja2 template used to inject definit...
WaylonWalker/waylonwalker.com
plugins/glossary.py
.py
acaceaac052ba71e
7.6
15
""" Link Collector Plugin Collects all hyperlinks from posts and stores them in markata.links. # Installation Add to your `markata.toml`: ```toml [markata] hooks = ["markata.plugins.link_collector"] ``` # Usage This plugin gathers link information in the `post_render` phase and makes it available as a list of dic...
WaylonWalker/waylonwalker.com
plugins/link_collector.py
.py
31d074eeca066c1f
7.6
15
"""md_video plugin""" from markata.hookspec import hook_impl import pydantic import re from typing import TYPE_CHECKING if TYPE_CHECKING: from markata import Markata MARKATA_PLUGIN_NAME = "md_video" MARKATA_PLUGIN_PACKAGE_NAME = "md-video" class MdVideoConfig(pydantic.BaseModel): video_extensions: list[str...
WaylonWalker/waylonwalker.com
plugins/md_video.py
.py
aebfbae340d88290
7.6
15
""" Markata Plugin: Mermaid Diagram Renderer This plugin converts Mermaid code blocks in Markdown files into rendered Mermaid diagrams. # Installation Ensure Mermaid.js is available in your site. If serving locally, add the script to your template: ```html <script type="module"> import mermaid from 'https://cdn.j...
WaylonWalker/waylonwalker.com
plugins/mermaid.py
.py
eb017d727e87a5c1
7.6
15
from lxml import html from markata.hookspec import hook_impl def permalink_aria(doc): for a_tag in doc.xpath("//a[@class='header-anchor'][@href]"): a_tag.attrib["aria-label"] = ( f"Permalink to Heading {a_tag.getparent().text_content()}" ) return doc def process_html_content(html...
WaylonWalker/waylonwalker.com
plugins/permalink_aria.py
.py
95429cb2cb8e2a9d
7.6
15
""" QRCode Plugin Generates QR codes for selected posts and saves them to `markout/<slug>/qr.svg`. # Installation ```toml [tool.markata] hooks = ["markata.plugins.qrcode"] ``` Install dependencies: ```bash pip install pyqrcode ``` # Configuration ```toml [markata.qrcode] filter = "True" # Python...
WaylonWalker/waylonwalker.com
plugins/qrcode.py
.py
3d8028c21d79e56b
7.6
15
"""manifest plugin""" from pathlib import Path from typing import List, TYPE_CHECKING from bs4 import BeautifulSoup from markata import Markata, __version__ from markata.hookspec import hook_impl if TYPE_CHECKING: import frontmatter from bs4.element import Tag import json from urllib import request as ulreq...
WaylonWalker/waylonwalker.com
plugins/seo_amp.py
.py
2c4fabcc380fc638
7.6
15
"""Tag Aggregator Plugin with Reporting""" from datetime import datetime import json from markata.hookspec import hook_impl, register_attr import pydantic from typing import Dict, List, Set class TagAggregatorConfig(pydantic.BaseModel): synonyms: Dict[str, List[str]] = {} additional: Dict[str, List[str]] = {...
WaylonWalker/waylonwalker.com
plugins/tag_aggregator.py
.py
6f448d41fcdca6f7
7.6
15
""" Improved Markata plugin for wikilink hover previews using HTMX + Tippy.js Fixes HTMX swap errors by deferring hx-get trigger until tooltip is visible and ensures proper initialization order. """ from typing import TYPE_CHECKING from lxml import html from markata.hookspec import hook_impl if TYPE_CHECKING: pas...
WaylonWalker/waylonwalker.com
plugins/tippy_wikilink_hover.py
.py
9650a275c81610d3
7.6
15
""" Webmentions for Markata (webmention.io + Bridgy) Adds a "Webmentions" section to each post by querying webmention.io’s API. Works great with Bridgy: point your site's <link rel="webmention"> to webmention.io and let Bridgy send mentions there; this plugin renders them. # Installation - `pip install requests` - A...
WaylonWalker/waylonwalker.com
plugins/webmention.py
.py
ac7d076c739e3ff6
7.6
15
from typing import TYPE_CHECKING from lxml import html from markata.hookspec import hook_impl if TYPE_CHECKING: pass external_svg = """ <svg xmlns="https://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="h-4 w-4 inline align-middle"> <path stroke-linecap="ro...
WaylonWalker/waylonwalker.com
plugins/wikilink_hover.py
.py
06252f6942d4ac46
7.6
15
from functools import lru_cache from string import Template from typing import TYPE_CHECKING from markata.hookspec import hook_impl if TYPE_CHECKING: from bs4.element import Tag from bs4 import BeautifulSoup # Cache the template to avoid repeated string creation YOUTUBE_TEMPLATE = Template(""" <div class="r...
WaylonWalker/waylonwalker.com
plugins/youtube.py
.py
3c01ab88ae6aebf2
7.6
15
import threading from django.db import transaction from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from usage_costs.models import ModelCategory from .models import AIModelSpec, ModelProvider @receiver(pre_save, sender=AIModelSpec) def detect_fal_model_id_change(instanc...
GooeyAI/gooey-server
ai_models/signals.py
.py
a5975283b17a3838
7.65
19
import typing from django.db import models from django.utils import timezone from daras_ai_v2.crypto import PBKDF2PasswordHasher, get_random_api_key, safe_preview if typing.TYPE_CHECKING: from workspaces.models import Workspace class ApiKeyQueySet(models.QuerySet): def create_api_key(self, workspace: "Work...
GooeyAI/gooey-server
api_keys/models.py
.py
8804837620af908e
7.65
19
#!/usr/bin/env python3 # Copyright 2026 Canonical Ltd. # See LICENSE file for licensing details. """Interface library for configuring a kratos login webhook. The provider side is responsible for providing the configuration that kratos will use to call this webhook. The requirer side (kratos) takes the configuration ...
canonical/kratos-operator
lib/charms/kratos/v0/kratos_login_webhook.py
.py
582871a15dd7e3b4
7.57
13
#!/usr/bin/env python3 # Copyright 2026 Canonical Ltd. # See LICENSE file for licensing details. """Interface library for configuring a kratos registration webhook. The provider side is responsible for providing the configuration that kratos will use to call this webhook. The requirer side (kratos) takes the configu...
canonical/kratos-operator
lib/charms/kratos/v0/kratos_registration_webhook.py
.py
e35cb0cc8b20dd24
7.57
13
# Copyright 2025 Canonical Ltd. # Licensed under the Apache2.0. See LICENSE file in charm source for details. """Library to manage the integration with the SMTP Integrator charm. This library contains the Requires and Provides classes for handling the integration between an application and a charm providing the `smtp...
canonical/kratos-operator
lib/charms/smtp_integrator/v0/smtp.py
.py
30892017118dd907
7.57
13
#!/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/kratos-operator
lib/charms/traefik_k8s/v0/traefik_route.py
.py
b4ffe628787e2098
7.57
13
# Copyright 2025 Canonical Ltd. # See LICENSE file for licensing details. import logging import re from typing import Optional from ops import Container from ops.pebble import Error, ExecError from exceptions import MigrationError logger = logging.getLogger(__name__) VERSION_REGEX = re.compile(r"Version:\s+(?P<ver...
canonical/kratos-operator
src/cli.py
.py
7c3a2244aeca6f0f
7.57
13
# Copyright 2025 Canonical Ltd. # See LICENSE file for licensing details. from typing import Mapping, Protocol, TypeAlias, Union EnvVars: TypeAlias = Mapping[str, Union[str, bool]] DEFAULT_CONTAINER_ENV = { "LOG_FORMAT": "json", "SERVE_PUBLIC_CORS_ENABLED": "true", } class EnvVarConvertible(Protocol): ...
canonical/kratos-operator
src/env_vars.py
.py
fa58538eee8f5b1f
7.07
13
# Copyright 2025 Canonical Ltd. # See LICENSE file for licensing details. import logging from collections import ChainMap from typing import Optional from ops import Container, ModelError, Unit from ops.pebble import CheckStatus, Layer, LayerDict, ServiceInfo, ServiceStatus from cli import CommandLine from configs i...
canonical/kratos-operator
src/services.py
.py
3e85ba333f7aa56e
7.57
13
# Copyright 2025 Canonical Ltd. # See LICENSE file for licensing details. from functools import wraps from typing import TYPE_CHECKING, Any, Callable, Dict, List, Literal, Optional, TypeVar from ops import CharmBase from constants import ( DATABASE_INTEGRATION_NAME, KRATOS_EXTERNAL_IDP_INTEGRATOR_INTEGRATION...
canonical/kratos-operator
src/utils.py
.py
175a6a143c5a13c9
7.57
13
# Copyright 2025 Canonical Ltd. # See LICENSE file for licensing details. import logging from contextlib import contextmanager from typing import Callable, Iterator import jubilant import yaml from integration.constants import KRATOS_APP from tenacity import retry, stop_after_attempt, wait_exponential StatusPredicat...
canonical/kratos-operator
tests/integration/utils.py
.py
32f19b2a30a6af3c
8.07
13
""" Example of the basis rotation circuit with H3+ molecule. Starts with the guess wave function from the core Hamiltonian, and runs the VQE to obtain the HF energy. """ import numpy as np from qibo.models import VQE from qibochem.ansatz import circuit_ansatz, hf_circuit from qibochem.driver import Molecule def gue...
qiboteam/qibochem
examples/br_example.py
.py
b318bf14731bb4f3
7.54
11
""" Sample script for using the physics-constrained hardware-efficient ansatz. Helper functions help set the circuit parameters and calculate the energy expectation value Reference: https://pubs.acs.org/doi/10.1021/acs.jctc.3c00966 """ import numpy as np from qibo.optimizers import optimize from qibochem.ansatz impo...
qiboteam/qibochem
examples/physics_constrained_hea.py
.py
2dc03a421e3ca6a3
7.54
11
""" Sample script of how to build and run the UCCSD ansatz with HF embedding for LiH """ import numpy as np from qibo.optimizers import optimize from qibochem.ansatz import circuit_ansatz from qibochem.ansatz.utils import generate_excitations from qibochem.driver import Molecule def electronic_energy(parameters, ha...
qiboteam/qibochem
examples/ucc_example1.py
.py
08dd53ec639844d9
7.54
11
"""Helper functions for the `ansatz` module""" from collections.abc import Sequence from math import factorial import numpy as np from qibo import Circuit, gates from qibo.gates import Gate from scipy.linalg import expm from qibochem.ansatz.utils import generate_excitations def _bk_matrix_power2(dims: int) -> np.n...
qiboteam/qibochem
src/qibochem/ansatz/_ansatz.py
.py
bac48ee8ea5bdb99
7.54
11
""" Qibochem also has a few utility functions to assist with the construction of circuit ansatzes. """ from collections.abc import Sequence import numpy as np from qibo.config import raise_error def generate_excitations( order: int, excite_from: Sequence[int], excite_to: Sequence[int], conserve_spin: bool = Tru...
qiboteam/qibochem
src/qibochem/ansatz/utils.py
.py
5010faa7631f5855
7.54
11
""" Helper functions for obtaining and transforming the molecular Hamiltonian """ from functools import reduce import openfermion from qibo import symbols from qibo.hamiltonians import SymbolicHamiltonian def _fermionic_hamiltonian(oei, tei, constant): """ Build molecular Hamiltonian as an InteractionOperat...
qiboteam/qibochem
src/qibochem/driver/hamiltonian.py
.py
d8d2a8826a855793
7.54
11
""" Functions for optimising the measurement cost of obtaining the expectation value """ from math import prod import numpy as np from qibo import Circuit, gates, symbols from qibo.gates import Gate from qibo.hamiltonians import SymbolicHamiltonian from qibo.symbols import X, Y, Z from sympy.core.expr import Expr fro...
qiboteam/qibochem
src/qibochem/measurement/optimization.py
.py
50e0c3bc2daf0e2d
7.54
11
""" Functions for obtaining the expectation value for some given circuit and Hamiltonian, either from a state vector simulation, or from sample measurements """ from collections import Counter from functools import reduce from qibo import Circuit from qibo.gates import Gate from qibo.hamiltonians import SymbolicHamil...
qiboteam/qibochem
src/qibochem/measurement/result.py
.py
9aa21f8c66d559e7
7.54
11
""" Functions for allocating shots to the Hamiltonian terms """ import numpy as np from sympy.core.numbers import One def coefficients_sum(expression): """Sum up the absolute value of the coefficients for all non-constant terms in a sympy.Expr""" return sum(abs(coeff) for term, coeff in expression.as_coeffic...
qiboteam/qibochem
src/qibochem/measurement/shot_allocation.py
.py
2060c367bedebc61
7.54
11
""" Utility functions for optimising measurements and calculation of expectation value """ import networkx as nx import numpy as np from qibo import gates # Mapping of Pauli operators to a symplectic (binary) representation, folowing the convention of (X|Z) PAULI_BINARY = {"I": (0, 0), "X": (1, 0), "Y": (1, 1), "Z": ...
qiboteam/qibochem
src/qibochem/measurement/util.py
.py
65e104b2fed60bae
7.54
11
""" Tests for ansatz utility functions (util.py) """ from math import prod import numpy as np import pytest from qibo import Circuit, gates, symbols from qibo.hamiltonians import SymbolicHamiltonian from qibo.models.encodings import hamming_weight_encoder from qibochem.ansatz._ansatz import ( _a_gate, _a_gat...
qiboteam/qibochem
tests/test_ansatz.py
.py
74c3268f331971e2
7.04
11
""" Test functionality to reduce the measurement cost of running VQE """ import numpy as np import pytest from qibo.hamiltonians import SymbolicHamiltonian from qibo.symbols import X, Y, Z from qibochem.measurement.optimization import ( _gc_measurement_mapping, _measurement_basis_rotations, ) from qibochem.me...
qiboteam/qibochem
tests/test_measurement_optimisation.py
.py
5299d0451f3f5ad8
8.04
11
""" Test functionality to reduce the measurement cost of running VQE """ import numpy as np import pytest from qibochem.measurement.util import ( _binary_gaussian_elimination, _binary_nullspace, _check_terms_commutativity, _col_reduce_x_matrix, _get_sigma_terms, _group_commuting_terms, _la...
qiboteam/qibochem
tests/test_measurement_util.py
.py
a8eaa2dee9dc7972
7.04
11
""" Test Molecule class functions """ from pathlib import Path import numpy as np import openfermion import pytest from qibo import gates, models from qibo.hamiltonians import SymbolicHamiltonian from qibo.symbols import X, Z from qibochem.driver import Molecule @pytest.mark.parametrize( "xyz_file,expected", ...
qiboteam/qibochem
tests/test_molecule.py
.py
33ae70816ab8a2ba
8.04
11
""" Enhanced MRZ detection: document edge detection + perspective transformation (Dynamsoft Capture Vision) followed by face-orientation correction (RetinaFace). Usage: python combine.py passport_180.jpg """ import argparse import sys import cv2 import numpy as np from dynamsoft_capture_vision_bundle import * i...
yushulx/python-mrz-scanner-sdk
examples/enhanced/combine.py
.py
b8f78543b5362da7
7.45
7
"""Construct design matrices for hierarch from Wilkinson formulas. The :func:`design_matrix` helper translates a long-format DataFrame with named columns into the positional numeric layout that :func:`hierarch.stats.hypothesis_test` and friends expect, using a Wilkinson formula to describe the nesting structure of the...
rishi-kulkarni/hierarch
hierarch/design.py
.py
1cdf7297ecf66925
7.48
8
import numpy as np def nb_unique(input_data, axis=0): """2D np.unique(a, return_index=True, return_counts=True). Parameters ---------- input_data : 2D numeric array axis : int, optional axis along which to identify unique slices, by default 0 Returns ------- 2D array ...
rishi-kulkarni/hierarch
hierarch/internal_functions.py
.py
937defdb1bf66205
7.48
8
from dataclasses import dataclass from typing import Iterable, Tuple, Union import numpy as np from hierarch.internal_functions import ( id_cluster_counts, msp, ) BOOTSTRAP_KINDS = ("weights", "indexes", "bayesian") @dataclass(frozen=True) class BootstrapPlan: """Precomputed cluster geometry for neste...
rishi-kulkarni/hierarch
hierarch/resampling.py
.py
e6c797b777b9e8a5
7.48
8
import numpy as np import pytest from tests._reference import make_design def pytest_configure(config): config.addinivalue_line( "markers", "slow: statistical calibration tests (run with `pytest -m slow`)" ) def pytest_collection_modifyitems(config, items): if config.getoption("markexpr"): ...
rishi-kulkarni/hierarch
tests/conftest.py
.py
b8d90e1eefefd99e
7.98
8
"""Contract of GroupbyMean and of aggregating a bootstrapped sample. On raw data GroupbyMean is a plain successive groupby-mean (== pandas). On a weight- or index-bootstrapped sample, aggregating up to the level the bootstrap started from must yield the nested *multiplicity*-weighted mean of the resample ("mean of clu...
rishi-kulkarni/hierarch
tests/test_aggregation_contract.py
.py
4264b9683512a77a
7.98
8
"""Contract of the nested bootstrap, independent of implementation. Weights are non-negative (integer for Efron, continuous for Bayesian), mass is redistributed only *within* the clusters at the level the bootstrap starts from, resampling is nested (a zero-weight parent zeroes its descendants), skipped levels inherit ...
rishi-kulkarni/hierarch
tests/test_bootstrapper_contract.py
.py
04afb13587668a36
7.98
8
"""confidence_interval contract. The interval contains the slope point estimate, widens with the confidence level, is equivariant under affine transforms of y and scaling of x, shifts with an added slope, agrees between compare='means' and 'corr' for two groups, and warns when the refinement fails to converge. """ im...
rishi-kulkarni/hierarch
tests/test_confidence_interval_contract.py
.py
cbd3fdadb6bb748d
7.98
8