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 |
|---|---|---|---|---|---|---|
"""Observable gauges emitting Redis-derived conserver health metrics.
Two gauges are exported on every metric-export tick:
``conserver.ingress_list.length`` — one observation per
``(ingress_list, kind)`` combination, sampled via ``LLEN``. The
``ingress_list`` attribute carries the configured name (e.g.
... | vcon-dev/vcon-server | common/lib/queue_metrics.py | .py | 543635bb6bdd059f | 7.54 | 11 |
"""Legacy-field tolerance for vCons read from storage.
Older releases of vcon-mcp / vcon-lib / hand-rolled adapters wrote vCons
with field names that pre-date ``draft-ietf-vcon-vcon-core-02``. We want
links to keep processing those records, but we want every *write* to
land in spec-correct form.
This module exposes o... | vcon-dev/vcon-server | common/lib/vcon_compat.py | .py | 8a7af4450dfd2833 | 7.54 | 11 |
"""Spec→legacy vCon conversion for egress compatibility (CON-581).
This is the inverse of :func:`lib.vcon_compat.normalize_legacy_fields`.
The conserver normalizes every vCon *up* to the current spec (``vcon: "0.4.0"``)
on read and write. Downstream consumers built against an older schema (e.g.
``0.0.1``) break on th... | vcon-dev/vcon-server | common/lib/vcon_egress_compat.py | .py | 0e33b715548cf1b7 | 7.54 | 11 |
import json
from datetime import datetime
from typing import Any, Optional
from config import Configuration
from lib.logging_utils import init_logger
from lib.metrics import increment_counter
from lib.vcon_compat import normalize_legacy_fields
from redis.commands.json.path import Path
from redis_mgr import redis
from s... | vcon-dev/vcon-server | common/lib/vcon_redis.py | .py | 54f6b982f09e11de | 7.54 | 11 |
"""
Package to manage Redis connection pool and clients
Setup of redis clients cannot be done globally in each module as it will
bind to a asyncio loop which may be started and stopped. In which case
redis will be bound to an old loop which will no longer work
The redis connection pool must be shutdown and restart... | vcon-dev/vcon-server | common/redis_mgr.py | .py | a642269856cf22f9 | 7.54 | 11 |
"""
Microsoft Dataverse storage module for vcon-server
This module provides integration with Microsoft Dataverse for storing vCons. It uses
the Dataverse Web API with MSAL authentication to store vCons as entities in a
Microsoft Dataverse environment.
The module supports:
- Storing complete vCon objects as JSON in a ... | vcon-dev/vcon-server | common/storage/dataverse/__init__.py | .py | b9602826b330b54a | 7.54 | 11 |
import pytest
import json
from unittest.mock import patch, MagicMock, ANY
from lib.vcon_redis import VconRedis
from vcon import Vcon
from storage.dataverse import (
save,
get,
get_access_token,
create_dataverse_session
)
# Sample vCon for testing
@pytest.fixture
def sample_vcon():
vcon = Vcon.bui... | vcon-dev/vcon-server | common/storage/dataverse/test_dataverse.py | .py | 03fb8d7ad0fec076 | 7.04 | 11 |
from lib.logging_utils import init_logger
from lib.vcon_redis import VconRedis
from lib.vcon_egress_compat import to_configured_legacy
import logging
import elasticsearch
import json
import os
logger = init_logger(__name__)
# Disable Elastic Search API requests logs
logging.getLogger("elastic_transport.transport").se... | vcon-dev/vcon-server | common/storage/elasticsearch/__init__.py | .py | 59e9f00894a88085 | 7.54 | 11 |
"""
File Storage Module
Provides local file system storage for vCon data with support for:
- UUID-based file organization
- Optional compression (gzip)
- Date-based directory structure
- Configurable file permissions
- File size limits
"""
import os
import json
import gzip
from glob import glob
from pathlib import Pa... | vcon-dev/vcon-server | common/storage/file/__init__.py | .py | 63ec6531a834c382 | 7.54 | 11 |
"""
Tests for the file storage module.
Tests cover:
- Basic CRUD operations (save, get, delete)
- Compression support
- Date-based organization
- File size limits
- Edge cases and error handling
"""
import pytest
import json
import gzip
import os
import tempfile
from pathlib import Path
from unittest.mock import patc... | vcon-dev/vcon-server | common/storage/file/test_file_storage.py | .py | e1a518d243f496ae | 7.04 | 11 |
import pytest
from unittest.mock import patch, MagicMock, mock_open
# pymilvus/openai are optional dependencies (group: storage-milvus). storage.milvus
# imports them at module load, so skip this whole module when they aren't installed.
pytest.importorskip("pymilvus")
pytest.importorskip("openai")
from lib.vcon_redis... | vcon-dev/vcon-server | common/storage/milvus/test_milvus.py | .py | 4162b8c562853141 | 8.04 | 11 |
"""
PostgreSQL storage module for vcon-server
This module provides integration with PostgreSQL for storing vCons. It uses the peewee ORM
for database operations and stores vCons in a dedicated table with JSON support.
The module supports:
- Storing complete vCon objects as JSON
- Storing metadata fields for quick acc... | vcon-dev/vcon-server | common/storage/postgres/__init__.py | .py | a4ccb82a01270ee8 | 7.54 | 11 |
import json
from datetime import datetime
from typing import Optional
from lib.logging_utils import init_logger
from lib.vcon_redis import VconRedis
from lib.vcon_egress_compat import to_configured_legacy
import boto3
logger = init_logger(__name__)
default_options = {}
def _create_s3_client(opts: dict):
"""Cre... | vcon-dev/vcon-server | common/storage/s3/__init__.py | .py | f602e8d1dbf48bf5 | 7.54 | 11 |
import os
import paramiko
import json
from typing import Optional
from lib.logging_utils import init_logger
from datetime import datetime
from lib.vcon_redis import VconRedis
logger = init_logger(__name__)
default_options = {
"name": "sftp",
"url": "sftp://localhost",
"port": 22,
"username": "userna... | vcon-dev/vcon-server | common/storage/sftp/__init__.py | .py | 2ab33a6053deae21 | 7.54 | 11 |
import logging
import traceback
from collections.abc import Callable
from pathlib import Path
from typing import Any
logger = logging.getLogger(__name__)
BASE_PATH = str(Path(__file__).resolve().parent.parent)
class DotPathFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
... | MrThearMan/graphene-django-extensions | example_project/config/logging.py | .py | 1cc61a54a2da5d22 | 7.42 | 6 |
from __future__ import annotations
from copy import deepcopy
from typing import TYPE_CHECKING
import graphene
from django import forms # noqa: TC002
from django.db import models
from graphene.types.enum import Enum # noqa: TC002
from graphene_django.converter import (
convert_choices_to_named_enum_with_descript... | MrThearMan/graphene-django-extensions | graphene_django_extensions/converters.py | .py | 86c9c75b78000700 | 7.42 | 6 |
from __future__ import annotations
import re
from functools import wraps
from typing import TYPE_CHECKING
from django.apps import apps
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db import models
from graphene_django.settings import graphene_settings
from graphene_django.ut... | MrThearMan/graphene-django-extensions | graphene_django_extensions/errors.py | .py | a80ce1da9fc4d230 | 7.42 | 6 |
from __future__ import annotations
from typing import TYPE_CHECKING
from django import forms
from graphene.utils.str_converters import to_camel_case
if TYPE_CHECKING:
from django.db.models import Choices, Model
from graphene_django_extensions.typing import Any, FieldAliasToLookup, FieldNameStr
__all__ = [
... | MrThearMan/graphene-django-extensions | graphene_django_extensions/fields/form.py | .py | 26dc01c16c1de9a4 | 7.42 | 6 |
from __future__ import annotations
from typing import TYPE_CHECKING
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
if TYPE_CHECKING:
from django.forms import Field
from graphene_django_extensions.typing import Any, Sequence
__all__ = [
"IntChoiceFie... | MrThearMan/graphene-django-extensions | graphene_django_extensions/fields/model.py | .py | aedd81896d79d31c | 7.42 | 6 |
from __future__ import annotations
import datetime
from enum import Enum
from typing import TYPE_CHECKING
from django.core.validators import MinValueValidator
from rest_framework import serializers
from rest_framework.relations import PKOnlyObject
if TYPE_CHECKING:
from django.db.models import Model
from gr... | MrThearMan/graphene-django-extensions | graphene_django_extensions/fields/serializer.py | .py | a24d8d09b79060c7 | 7.42 | 6 |
"""
File upload handling utilities.
Compliant with the GraphQL multipart request specification:
https://github.com/jaydenseric/graphql-multipart-request-spec
"""
from __future__ import annotations
from collections import defaultdict
from typing import Any
from django.core.files import File
__all__ = [
"extract... | MrThearMan/graphene-django-extensions | graphene_django_extensions/files.py | .py | 83c11b620f6ca02a | 7.42 | 6 |
from __future__ import annotations
from typing import TYPE_CHECKING
import django_filters
from django import forms
from django.db import models
from django.db.models import Model, Q, QuerySet
from django.db.models.constants import LOOKUP_SEP
from django_filters.constants import ALL_FIELDS, EMPTY_VALUES
from django_fi... | MrThearMan/graphene-django-extensions | graphene_django_extensions/filters.py | .py | 73593d0d3e7154de | 7.42 | 6 |
from __future__ import annotations
import dataclasses
from functools import wraps
from typing import TYPE_CHECKING
from django.db import IntegrityError, models, transaction
from django.db.models import NOT_PROVIDED
from graphene_django.types import ALL_FIELDS
from rest_framework.exceptions import ValidationError
from... | MrThearMan/graphene-django-extensions | graphene_django_extensions/serializers.py | .py | f25df4e0c0456019 | 7.42 | 6 |
from __future__ import annotations
import json
import uuid
from dataclasses import dataclass, field
from enum import Enum
from itertools import chain
from django.db.models import lookups
from django.db.models.constants import LOOKUP_SEP
from graphene.utils.str_converters import to_camel_case
from graphene_django_ext... | MrThearMan/graphene-django-extensions | graphene_django_extensions/testing/builders.py | .py | 3111640385544e2c | 7.92 | 6 |
from __future__ import annotations
import re
import subprocess
from pathlib import Path
import nox
DIR = Path(__file__).parent.resolve()
REPO = "agriyakhetarpal/hugo-python-distributions"
DOCS_DIR = DIR / "docs"
nox.options.sessions = ["lint"]
nox.options.verbose = True
nox.options.default_venv_backend = "uv|virtua... | agriyakhetarpal/hugo-python-distributions | noxfile.py | .py | fd391a6e353ab229 | 7.62 | 16 |
"""
This is a thin PEP 517 wrapper around meson-python's PEP 517 support.
Its primary purpose is to set the _PYTHON_HOST_PLATFORM env var for
cross-compilation without requiring users to set it by hand, based on
requirements passed via the --cross-file=... flag in config_settings.
It looks for `--cross-file=...` in th... | agriyakhetarpal/hugo-python-distributions | scripts/hugo_meson_python_wrapper.py | .py | 2f5b9dd7cd2f7919 | 7.62 | 16 |
"""
Shared helpers for obtaining a Go toolchain on 32-bit ARM Linux
on piwheels.
The go-bin PyPI package that we use as a build-time dependency does
not publish wheels or an sdist for armv6l/armv7l (piwheels), and thus
breaks builds on that platform. On that one platform, we can bypass
and download the official go.dev... | agriyakhetarpal/hugo-python-distributions | scripts/piwheels_go_toolchain.py | .py | be62019adfdac74b | 7.62 | 16 |
"""
Copyright (c) 2023 Agriya Khetarpal. All rights reserved.
hugo: Binaries for the Hugo static site generator, installable with pip
"""
from __future__ import annotations
import json
import os
import sys
from contextlib import nullcontext
from pathlib import Path, PurePosixPath
from sys import platform as sysplatf... | agriyakhetarpal/hugo-python-distributions | src/hugo/cli.py | .py | 3fbd1603b4b79d0b | 7.62 | 16 |
# This file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2026 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
"""Dask Distributed Tools.
- pool_broadcast
"""
from __future__ import annotations
from random import randint
from typing import Any
from da... | opendatacube/odc-algo | odc/algo/_broadcast.py | .py | 0e97df8d1524d6fa | 7.54 | 11 |
# This file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2026 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
"""Generic dask helpers."""
from __future__ import annotations
import functools
from bisect import bisect_left, bisect_right
from datetime imp... | opendatacube/odc-algo | odc/algo/_dask.py | .py | f93165e16f8223f4 | 7.54 | 11 |
# This file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2026 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
"""Dask Distributed Tools.
- dask_compute_stream
"""
from __future__ import annotations
import queue
import threading
from random import rand... | opendatacube/odc-algo | odc/algo/_dask_stream.py | .py | 785f177ef5642510 | 7.54 | 11 |
# This file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2026 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
"""Misc numeric tooling."""
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
fro... | opendatacube/odc-algo | odc/algo/_numeric.py | .py | 636962ba3721ff15 | 7.54 | 11 |
# This file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2026 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
"""Helpers for dealing with RGB(A) images."""
import dask
import dask.array as da
import numpy as np
import xarray as xr
from ._dask import ra... | opendatacube/odc-algo | odc/algo/_rgba.py | .py | d5373e25343351a1 | 7.54 | 11 |
# This file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2026 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
"""Various utilities."""
ROI = slice | tuple[slice, ...]
def slice_in_out(s: slice, n: int) -> tuple[int, int]:
def fill_if_none(x: int |... | opendatacube/odc-algo | odc/algo/_tools.py | .py | a695fa8c50de539e | 7.54 | 11 |
# This file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2026 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
"""Helper methods for accessing single pixel from a rasterio file object."""
from __future__ import annotations
from typing import TYPE_CHECKI... | opendatacube/odc-algo | odc/algo/pixel.py | .py | 342e13cb698e2161 | 7.54 | 11 |
# This file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2026 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
import dask
import dask.array as da
import numpy as np
import pandas as pd
import pytest
import xarray as xr
from odc.algo._masking import (
... | opendatacube/odc-algo | tests/test_masking.py | .py | acf8231caa7300d4 | 7.04 | 11 |
# This file is part of the Open Data Cube, see https://opendatacube.org for more information
#
# Copyright (c) 2015-2026 ODC Contributors
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
from odc.algo._numeric import (
half_up,
np_slice_to_idx,
roi_shrink2,
roundup16,
shape_sh... | opendatacube/odc-algo | tests/test_numeric.py | .py | d67bc11a36856f75 | 7.04 | 11 |
# Purpose: This script downloads a list of active and outdated channels from a channel-buy from Magma.
# It writes the long-channel-IDs into a directory so charge-LND can use this as a different ruleset.
# It'll remove the channels once the channel-buy is expired, and then activate AutoFees in LNDg.
# It also enters Ma... | TrezorHannes/Lightning-Python-Tools | LNDg/amboss_pull.py | .py | e97842d3a871e328 | 7.45 | 7 |
#!/usr/bin/env python3
# This script monitors the mempool fees and adjusts the LNDg AR-Enabled setting accordingly.
# When the mempool fees are high, the script will disable AR to prevent the node from getting stuck with unconfirmed transactions.
# When the mempool fees are low, the script will enable AR to allow the ... | TrezorHannes/Lightning-Python-Tools | LNDg/mempool_rebalancer_trigger.py | .py | fe80511041c0b0b9 | 7.45 | 7 |
#!/usr/bin/env python3
"""
Rebalance Guard Script
Audits all active channels in LNDg to protect against unprofitable rebalancing feedback loops:
1. Channels offering inbound discounts (local_inbound_fee_rate < 0) are locked (ar_out_target = 100%)
to prevent LNDg from using them as outbound rebalance donors while th... | TrezorHannes/Lightning-Python-Tools | Other/rebalance_guard.py | .py | 7b2d3a4eaad36b60 | 7.45 | 7 |
'''
Overall Goal of the script: to send a specified amount of Lightning funds to a specified LN address.
The user can specify the total amount to transfer, the amount per transaction, the interval between transactions,
the maximum fee rate, and a message to include with the payments. The user can also specify a peer ... | TrezorHannes/Lightning-Python-Tools | Other/swap_wallet.py | .py | 44962b86e6d5b9d5 | 7.45 | 7 |
import sys
import os
import pytest
from unittest.mock import MagicMock
# --- FIXTURE: Mock Global Side Effects ---
@pytest.fixture(scope="module", autouse=True)
def mock_dependencies():
"""
Patcher fixture that runs BEFORE the test module logic is fully utilized.
Since 'import magma_sale_process' has side... | TrezorHannes/Lightning-Python-Tools | tests/Magma/test_magma_sale_process.py | .py | 6250e36730232712 | 7.95 | 7 |
import pytest
from rebalance_guard import audit_channel_rebalance_targets, evaluate_channel_action
def test_evaluate_channel_action_locks_discounted_channel():
"""
If a channel has a negative inbound fee and ar_out_target < 95%,
it must be flagged to be locked to 100%.
"""
channel = {
"chan... | TrezorHannes/Lightning-Python-Tools | tests/test_rebalance_guard.py | .py | 4b7ec1ce2eb2cad2 | 7.95 | 7 |
import logging
from multiprocessing import Event
from multiprocessing.pool import ThreadPool
import daisy
from daisy.cl_monitor import CLMonitor
from daisy.tcp import IOLooper
logger = logging.getLogger(__name__)
def check_task_states(task_states):
# daisy 1.x counts failed and orphaned blocks as done, so its
... | ucsdmanorlab/bootstrapper | bootstrapper/blockwise.py | .py | c521d857ed0e6bf8 | 7.52 | 10 |
import click
import toml
from . import (
prepare,
train,
predict,
segment,
evaluate,
refine,
view,
utils,
)
from .styles import cli_echo
class CommandGroup(click.Group):
def list_commands(self, ctx):
# Return the commands in the desired order
return [
... | ucsdmanorlab/bootstrapper | bootstrapper/cli.py | .py | ea08f391c7400703 | 7.52 | 10 |
import click
import numpy as np
import json
import daisy
from funlib.persistence import open_ds, prepare_ds
from functools import partial
import logging
from bootstrapper.blockwise import run_blockwise
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def quick_merge_bloc... | ucsdmanorlab/bootstrapper | bootstrapper/data/merge.py | .py | f5a4d5d161a3525a | 7.52 | 10 |
import logging
from tqdm import tqdm
import numpy as np
import networkx as nx
from funlib.evaluate import (
rand_voi,
expected_run_length,
get_skeleton_lengths,
)
from funlib.geometry import Coordinate, Roi
from funlib.persistence import open_ds
logging.basicConfig(level=logging.INFO)
logger = logging.g... | ucsdmanorlab/bootstrapper | bootstrapper/eval/compute_metrics.py | .py | 6a4e14936f79bbcc | 7.52 | 10 |
from gunpowder import BatchFilter, Array, BatchRequest, Batch, Coordinate
import logging
import numpy as np
from scipy.ndimage import binary_erosion, binary_dilation
from skimage.morphology import ball, disk
from gunpowder.nodes.add_affinities import seg_to_affgraph
logger = logging.getLogger(__name__)
class AddAf... | ucsdmanorlab/bootstrapper | bootstrapper/gp/add_aff_errors.py | .py | 97741fe833a2f62e | 7.52 | 10 |
from lsd.train import LsdExtractor
from gunpowder import BatchFilter, Array, BatchRequest, Batch
import logging
import numpy as np
from scipy.ndimage import binary_erosion, binary_dilation
from skimage.morphology import ball, disk
logger = logging.getLogger(__name__)
class AddLSDErrors(BatchFilter):
"""Compute ... | ucsdmanorlab/bootstrapper | bootstrapper/gp/add_lsd_errors.py | .py | 5a236caee8884f29 | 7.52 | 10 |
import gunpowder as gp
import numpy as np
import random
from skimage.exposure import equalize_adapthist as clahe
import itertools
class ClaheAugment(gp.BatchFilter):
"""Randomly apply CLAHE (Contrast Limited Adaptive Histogram Equalization).
Args:
array (:class`ArrayKey`):
The intensi... | ucsdmanorlab/bootstrapper | bootstrapper/gp/clahe_augment.py | .py | cc71f2ba4ff1ced4 | 7.52 | 10 |
import gunpowder as gp
import numpy as np
class CreateMask(gp.BatchFilter):
"""
A node that creates a mask array based on the input array.
Args:
in_array (str): The name of the input array.
out_array (str): The name of the output array.
"""
def __init__(self, in_array, out_array):... | ucsdmanorlab/bootstrapper | bootstrapper/gp/create_mask.py | .py | a7e16966b8bc21b7 | 7.52 | 10 |
import gunpowder as gp
import numpy as np
import random
from scipy.ndimage.morphology import binary_erosion
class CustomGrowBoundary(gp.BatchFilter):
"""Grow a boundary between regions in a label array. Does not grow at the
border of the batch or an optionally provided mask. Erodes an amount of
voxels les... | ucsdmanorlab/bootstrapper | bootstrapper/gp/custom_grow_boundary.py | .py | f681a86860e21c20 | 7.52 | 10 |
import logging
import random
import numpy as np
from scipy.ndimage import binary_dilation, label, map_coordinates
# imports for deformed slice
from skimage.draw import line
from gunpowder.batch_request import BatchRequest
from gunpowder.coordinate import Coordinate
from gunpowder import BatchFilter
logger = loggin... | ucsdmanorlab/bootstrapper | bootstrapper/gp/defect_augment.py | .py | 344927177e6ba40f | 7.52 | 10 |
# adapted from https://github.com/saalfeldlab/corditea/blob/main/src/corditea/gamma_augment.py
import itertools
import logging
from collections.abc import Iterable
import numpy as np
from gunpowder import BatchFilter
logger = logging.getLogger(__name__)
class GammaAugment(BatchFilter):
"""
An Augment to ap... | ucsdmanorlab/bootstrapper | bootstrapper/gp/gamma_augment.py | .py | 14dd5997f9e30133 | 7.52 | 10 |
import random
import gunpowder as gp
import numpy as np
import edt
from scipy.ndimage import generate_binary_structure, maximum_filter, label
from skimage.morphology import star, disk, ellipse
from skimage.segmentation import watershed
class ObfuscateLabels(gp.BatchFilter):
"""
Modifies 3D labels arrays by pe... | ucsdmanorlab/bootstrapper | bootstrapper/gp/obfuscate_labels.py | .py | 50eb9fbe8d7d82fc | 7.52 | 10 |
import gunpowder as gp
from skimage.measure import label
class Renumber(gp.BatchFilter):
"""Find connected components of the same value, and replace each component
with a new label.
Args:
labels (:class:`ArrayKey`):
The label array to modify.
"""
def __init__(self, labels):... | ucsdmanorlab/bootstrapper | bootstrapper/gp/renumber.py | .py | 9e1acb4bdd143430 | 7.52 | 10 |
import gunpowder as gp
import numpy as np
import random
from scipy.ndimage import gaussian_filter
import itertools
class SmoothAugment(gp.BatchFilter):
"""Randomly scale and shift the values of an intensity array.
Args:
array (:class:`ArrayKey`):
The intensity array to modify.
... | ucsdmanorlab/bootstrapper | bootstrapper/gp/smooth_augment.py | .py | 5ffa18a42f735757 | 7.52 | 10 |
#!/usr/bin/env python3
"""
Script to process Berkeley Earth Land_and_Ocean_LatLong1.nc data
Applies CDO to set monthly time axis from 1850 with hourly units
and adds temperature to climatology variable.
"""
import sys
import os
import argparse
import urllib.request
import urllib.error
from pathlib import Path
import x... | DestinE-Climate-DT/Climate-DT-catalog | catalogs/obs/catalog/BERKELEY-EARTH/scripts/retrieve_process.py | .py | e55f95da75ff59e5 | 7.52 | 10 |
#!/usr/bin/env python3
"""
retrieve_esacci.py + postprocessing
Downloads daily .nc files from CEDA server and optionally performs post-processing:
- yearly files of monthly averages using CDO
- NC4 format with compression
- timestamps fixed at midnight of first day of each month
Usage:
python retrieve_esacci.p... | DestinE-Climate-DT/Climate-DT-catalog | catalogs/obs/catalog/ESA-CCI-L4/scripts/retrieve_esacci.py | .py | f339789999a61a58 | 7.52 | 10 |
import math
from datetime import datetime, timezone
from django.test import TestCase
from sequencefield.functions import DateFromId, RightShift
from tests.models import (
AlphaNumericSequenceModelA,
AlphaNumericSequenceModelB,
BigIntSequenceModel,
IntSequenceModelA,
IntSequenceModelB,
)
class Se... | quertenmont/django-sequencefield | tests/test_fields.py | .py | 6c8bdf7ccd105522 | 8.04 | 11 |
import re
from django.test import TestCase
from sequencefield.metadata import (
__author__,
__copyright__,
__description__,
__email__,
__license__,
__title__,
__version__,
)
class MetadataTestCase(TestCase):
"""
This class describes a metadata test case.
"""
def test_met... | quertenmont/django-sequencefield | tests/test_metadata.py | .py | 1b53ffe4334adfa4 | 8.04 | 11 |
"""
Camera motion compensation interface.
"""
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import ClassVar, List, Optional, Tuple
import numpy as np
from motrack.library.cv.bbox import PredBBox
@dataclass(frozen=True)
class CMCContext:
"""
Per-frame tracker state made av... | Robotmurlock/Motrack | motrack/cmc/algorithms/base.py | .py | 17da7c5769923b64 | 7.64 | 18 |
"""
Camera motion compensation based on descriptor matching between two frames.
Steps:
1. Use feature detector (e.g. ORB/SIFT) to detect features in both frames.
2. [Optional] Use detections to exclude features from the estimation.
3. Match the features by descriptor, using the norm the detector declares.
4. [Optional... | Robotmurlock/Motrack | motrack/cmc/algorithms/feature_matching.py | .py | 6fbad9da3c45e895 | 7.64 | 18 |
"""
Load GMC results from file - pre-calculated.
"""
import os
from typing import ClassVar, Dict
import numpy as np
from pydantic import BaseModel, ConfigDict
from motrack.cmc.algorithms.base import CameraMotionCompensation, CMCContext
from motrack.cmc.catalog import CMC_CATALOG
from motrack.cmc.components.warp impor... | Robotmurlock/Motrack | motrack/cmc/algorithms/gmc_from_file.py | .py | 778668750e92688f | 7.64 | 18 |
"""
Identity (no-op) camera motion compensation.
"""
from typing import ClassVar
import numpy as np
from pydantic import BaseModel, ConfigDict
from motrack.cmc.algorithms.base import CameraMotionCompensation, CMCContext
from motrack.cmc.catalog import CMC_CATALOG
from motrack.cmc.components.warp import identity_warp
... | Robotmurlock/Motrack | motrack/cmc/algorithms/identity.py | .py | d274b5e0b6a23f93 | 7.64 | 18 |
"""
Camera motion compensation from Kalman filter residuals. Uses no images.
Steps:
1. Take the motion model predictions for the current frame (`tracklet_bbox_predictions`).
2. Associate them with the current detections, reusing the tracker's association algorithm.
3. Each matched pair is a correspondence: prediction ... | Robotmurlock/Motrack | motrack/cmc/algorithms/kf_residual.py | .py | 9a922abea6c4df66 | 7.64 | 18 |
"""
Camera motion compensation based on the PyLucasKanade algorithm for optical flow estimation.
Steps:
1. Use feature detector (e.g. Shi-Tomasi) to detect features to track.
2. [Optional] Use detections to exclude features from the estimation.
3. Use PyLucasKanade algorithm to estimate the optical flow for each featu... | Robotmurlock/Motrack | motrack/cmc/algorithms/pylk.py | .py | 16d5210d88964fb6 | 7.64 | 18 |
"""
Helpers shared by the correspondence based camera motion compensation algorithms.
`PyLKCMC` and `FeatureMatchingCMC` differ only in how they produce correspondences: one
tracks points with optical flow, the other matches descriptors. Everything either side of
that - excluding points that fall on detected objects, ... | Robotmurlock/Motrack | motrack/cmc/algorithms/utils.py | .py | f1a08af4e6095526 | 7.64 | 18 |
"""
Feature detector interface.
"""
from abc import ABC, abstractmethod
from typing import ClassVar, Optional
import numpy as np
# A detector declares which norm its descriptors are compared under, and the distance catalog
# is what that string selects, so the norms live there rather than being restated here.
from mo... | Robotmurlock/Motrack | motrack/cmc/components/feature_detector/algorithms/base.py | .py | b02baf1327a8017f | 7.64 | 18 |
"""
ORB feature detector.
"""
from typing import ClassVar, Optional
import cv2
import numpy as np
from pydantic import BaseModel, ConfigDict, Field
from motrack.cmc.components.feature_detector.algorithms.base import DescriptorNorm, FeatureDetector
from motrack.cmc.components.feature_detector.utils import pack_keypoin... | Robotmurlock/Motrack | motrack/cmc/components/feature_detector/algorithms/orb.py | .py | 2212e336d164500f | 7.64 | 18 |
"""
Shi-Tomasi corner detector.
"""
from typing import ClassVar, Optional
import cv2
import numpy as np
from pydantic import BaseModel, ConfigDict, Field
from motrack.cmc.components.feature_detector.algorithms.base import DescriptorNorm, FeatureDetector
from motrack.cmc.components.feature_detector.utils import empty_... | Robotmurlock/Motrack | motrack/cmc/components/feature_detector/algorithms/shi_tomasi.py | .py | 5867806268edf620 | 7.64 | 18 |
"""
SIFT feature detector.
"""
from typing import ClassVar, Optional
import cv2
import numpy as np
from pydantic import BaseModel, ConfigDict, Field
from motrack.cmc.components.feature_detector.algorithms.base import DescriptorNorm, FeatureDetector
from motrack.cmc.components.feature_detector.utils import pack_keypoi... | Robotmurlock/Motrack | motrack/cmc/components/feature_detector/algorithms/sift.py | .py | caa3f52858960c93 | 7.64 | 18 |
"""
Shared helpers for feature detectors.
"""
from typing import List, Optional
import numpy as np
def empty_points() -> np.ndarray:
"""
Creates an empty point array, returned when a detector finds nothing.
Returns:
Empty points of shape (0, 2)
"""
return np.zeros((0, 2), dtype=np.float3... | Robotmurlock/Motrack | motrack/cmc/components/feature_detector/utils.py | .py | e3274b784c94247b | 7.64 | 18 |
"""
Descriptor matching between two frames. Establishes correspondences by comparing descriptors.
Supporting module for feature based camera motion compensation.
Steps:
1. Extract descriptors from the previous and current frames.
2. Compute the distance matrix between the descriptors.
3. Apply the Lowe's ratio test t... | Robotmurlock/Motrack | motrack/cmc/components/matching.py | .py | a24cd286a4b98e51 | 7.64 | 18 |
"""
Custom implementation of the Pyramidal Lucas-Kanade optical flow algorithm.
"""
import numpy as np
import cv2
def min_eigenvalue2x2(A: np.ndarray, n_pixels: int) -> float:
"""
Computes the minimum eigenvalue of a 2x2 matrix normalized by the number of pixels and the gradient gain.
Normalization note... | Robotmurlock/Motrack | motrack/cmc/components/pylk.py | .py | 6003a8a3ed36b4cd | 7.64 | 18 |
"""
Affine warp estimation from point correspondences.
Two estimators are provided:
- `estimate_warp_lstsq`: plain least-squares fit over all given correspondences.
- `WarpRANSACEstimator`: robust fit that tolerates outlier correspondences, followed by a
final least-squares refit over the identified inliers.
Both ... | Robotmurlock/Motrack | motrack/cmc/components/ransac.py | .py | 1a295037ec8c9fb2 | 7.64 | 18 |
"""
Tracker config for tool entrypoints.
"""
import copy
import dataclasses
import json
import logging
import os
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union
from hydra.core.config_store import ConfigStore
from motrack.common import conventions, project
from motrack.uti... | Robotmurlock/Motrack | motrack/config_parser/core.py | .py | d7ead1dcddf1df26 | 7.64 | 18 |
"""
MOT Challenge Dataset support. Supports: MOT17, MOT20, DanceTrack and SportsMOT.
"""
import configparser
import copy
import logging
import os
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Tuple, List, Union, Optional
import numpy as np
import pandas as pd
from tqdm import tqdm... | Robotmurlock/Motrack | motrack/datasets/mot.py | .py | 7276919b1290432d | 7.64 | 18 |
"""
Motrack evaluation module.
Provides integrated MOT evaluation with HOTA, CLEAR, Identity, and Count
metrics. The metric implementations in this module are derived from the
TrackEval library and adapted to work within the Motrack pipeline.
Original source::
@misc{luiten2020trackeval,
author = {Jon... | Robotmurlock/Motrack | motrack/eval/__init__.py | .py | 01e0e8d6eb0c3f0e | 7.64 | 18 |
"""
MOT-format file loading for evaluation.
Reads ground-truth and tracker output files in the standard MOT Challenge
text format into per-timestep numpy arrays suitable for metric computation.
All coordinates are kept in raw pixel units (not normalized).
"""
import csv
import os
from typing import Dict, List, Tuple
... | Robotmurlock/Motrack | motrack/eval/io.py | .py | d0915357cfe98df4 | 7.64 | 18 |
"""
Evaluation metrics base class.
All metric implementations follow the same two-phase pattern:
1. ``eval_sequence`` scores a single sequence and returns a results dict.
2. ``combine_sequences`` aggregates per-sequence dicts into a dataset-level
result, typically by summing count fields and recomputing deriv... | Robotmurlock/Motrack | motrack/eval/metrics/__init__.py | .py | 0c139d0686b99aa0 | 7.64 | 18 |
"""
CLEAR MOT metrics (MOTA, MOTP, ID switches, track quality, etc.).
Frame-by-frame evaluation that matches detections with a priority for
maintaining ID continuity from the previous frame (1000x bonus in the
cost matrix), then falls back to IoU similarity.
See: https://link.springer.com/article/10.1007/s11263-007-0... | Robotmurlock/Motrack | motrack/eval/metrics/clear.py | .py | 8d4d4173c339af0c | 7.64 | 18 |
"""
Count metric — simple detection and ID tallies.
Derived from the TrackEval implementation:
https://github.com/JonathonLuiten/TrackEval
"""
from typing import Any, Dict, List
from motrack.eval.metrics import MetricBase
class Count(MetricBase):
"""
Counts detections and unique IDs per sequence.
Per... | Robotmurlock/Motrack | motrack/eval/metrics/count.py | .py | da8b9c3886be62d3 | 7.64 | 18 |
"""Config command for displaying effective configuration."""
from structkit.commands import Command
import yaml
import json
from structkit.config import get_effective_config, get_user_config_path, get_builtin_defaults
class ConfigCommand(Command):
def __init__(self, parser):
# Don't call super().__init__... | httpdss/structkit | structkit/commands/config.py | .py | 411d70667111e5d1 | 7.63 | 17 |
import os
import yaml
import asyncio
from structkit.commands import Command
# Info command class for exposing information about the structure
class InfoCommand(Command):
def __init__(self, parser):
super().__init__(parser)
parser.description = "Show information about the package or structure definit... | httpdss/structkit | structkit/commands/info.py | .py | 6419ce181a7863da | 7.63 | 17 |
import yaml
from dotenv import load_dotenv
from structkit.commands import Command
class ValidationConfigError(ValueError):
"""Expected structure validation error that should be shown without a traceback."""
load_dotenv()
# Validate command class
class ValidateCommand(Command):
def __init__(self, parser):
... | httpdss/structkit | structkit/commands/validate.py | .py | 40606bbce14e20e5 | 7.63 | 17 |
import os
class ChoicesCompleter(object):
def __init__(self, choices):
self.choices = choices
def __call__(self, **kwargs):
return self.choices
class StructuresCompleter(object):
"""Dynamic completer for available structure names."""
def __init__(self, structures_path=None):
... | httpdss/structkit | structkit/completers.py | .py | de43b35f2818de59 | 7.63 | 17 |
"""Configuration layering system for structkit.
Supports loading and merging configuration from multiple sources:
1. Built-in defaults
2. User config (~/.config/struct/config.yaml)
3. Project config (.struct.yaml or --config-file)
4. CLI arguments
Priority order: CLI args > Project config > User config > Built-in def... | httpdss/structkit | structkit/config.py | .py | 5fbf81ed0e1bfc20 | 7.63 | 17 |
# FILE: content_fetcher.py
import os
import re
import requests
import subprocess
from pathlib import Path
import hashlib
import logging
try:
import boto3
from botocore.exceptions import NoCredentialsError, ClientError
boto3_available = True
except ImportError:
boto3_available = False
try:
from google.cloud ... | httpdss/structkit | structkit/content_fetcher.py | .py | e5d823bf627ff522 | 7.63 | 17 |
import os
import re
import json
from uuid import uuid4
from datetime import datetime, timezone
from typing import Any
import yaml
from github import Github
from cachetools import TTLCache, cached
cache = TTLCache(maxsize=100, ttl=600)
def _is_git_object_id(value):
return (
isinstance(value, str)
... | httpdss/structkit | structkit/filters.py | .py | 0176d8c4433fa4a1 | 7.63 | 17 |
import argparse
import logging
import os
import shlex
from dotenv import load_dotenv
from structkit.utils import read_config_file, merge_configs
from structkit.config import load_layered_config, apply_config_to_args
from structkit.commands.generate import GenerateCommand
from structkit.commands.info import InfoCommand
... | httpdss/structkit | structkit/main.py | .py | bb046327646a0a8f | 7.63 | 17 |
import os
import logging
from dotenv import load_dotenv
from pydantic_ai import Agent
load_dotenv()
class ModelWrapper:
"""
Wraps model logic using pydantic-ai Agent, allowing use of multiple LLM providers.
"""
def __init__(self, logger=None):
self.logger = logger or logging.getLogger(__name__)
self.... | httpdss/structkit | structkit/model_wrapper.py | .py | dce85a0796d5c87a | 7.63 | 17 |
"""Utilities for managing named StructKit structure sources."""
from __future__ import annotations
import hashlib
import os
import re
import shutil
import subprocess
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Optional, Tuple
from urllib.parse import parse_qs, urlparse
import ... | httpdss/structkit | structkit/sources.py | .py | 52f676a4fc941c8a | 7.63 | 17 |
"""Resolution helpers for nested StructKit structure references."""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, Mapping, Optional, Tuple
from structkit.sources import (
SourceError,
ensure_remote_repo,
ensure_remote_source,... | httpdss/structkit | structkit/struct_refs.py | .py | 5498b19bab31d049 | 7.63 | 17 |
# FILE: template_renderer.py
import logging
import os
from jinja2 import Environment, meta
from structkit.filters import (
get_latest_release,
slugify,
get_default_branch,
gen_uuid,
now_iso,
env as env_get,
read_file,
to_yaml,
from_yaml,
to_json,
from_json,
)
from structkit.input_store import Inpu... | httpdss/structkit | structkit/template_renderer.py | .py | e2169495b028cff7 | 7.63 | 17 |
import pytest
import os
import argparse
from structkit.completers import log_level_completer, file_strategy_completer, structures_completer
def test_log_level_completer():
completer = log_level_completer()
assert 'DEBUG' in completer
assert 'INFO' in completer
assert 'WARNING' in completer
assert '... | httpdss/structkit | tests/test_completers.py | .py | ad9a06fb18c8039b | 7.13 | 17 |
"""Tests for the config command."""
import pytest
import argparse
import tempfile
import os
import yaml
import json
from unittest.mock import patch, MagicMock
from pathlib import Path
from structkit.commands.config import ConfigCommand
@pytest.fixture
def parser():
return argparse.ArgumentParser()
@pytest.fixt... | httpdss/structkit | tests/test_config_command.py | .py | 06867547852cd26b | 7.13 | 17 |
"""Tests for config layering system."""
import pytest
import os
import tempfile
import argparse
from pathlib import Path
from unittest.mock import patch, MagicMock
from structkit.config import (
get_builtin_defaults,
load_yaml_config,
merge_config_layer,
load_layered_config,
merge_cli_args,
app... | httpdss/structkit | tests/test_config_layering.py | .py | e95ccfb4044cc5f4 | 8.13 | 17 |
import pytest
from unittest.mock import patch, MagicMock
from structkit.commands.generate import GenerateCommand
import argparse
import os
class TestGlobalSystemPromptEnvVar:
"""Tests for STRUCTKIT_GLOBAL_SYSTEM_PROMPT environment variable."""
def test_env_var_used_when_no_cli_arg(self):
"""Test that... | httpdss/structkit | tests/test_env_var_cli_args.py | .py | b6c77d22355c34a2 | 7.13 | 17 |
import pytest
from unittest.mock import patch, MagicMock
from structkit.commands.generate import GenerateCommand
import argparse
import os
def test_env_var_structures_path_used_when_no_cli_arg():
"""Test that STRUCTKIT_STRUCTURES_PATH env var is used when --structures-path is not provided."""
with patch.dict(... | httpdss/structkit | tests/test_env_var_structures_path.py | .py | 3644053a6b08c109 | 7.13 | 17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.