text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
#!/usr/bin/env python
"""BasketballSerialParserCOM.py: Collects data from a Daktronics All Sport 5000 connected via port J2 to a
Daktronics All Sport CG connected to a computer on COM port (defined on line 60), then parses data to
a .csv readable by broadcasting programs. This file has only been tested using game co... | BristolTNCitySchools/DaktronicsCGSerialParser | Basketball-1101/BasketballSerialParserCOM.py | .py | 7a8835f7499a7b1b | 7.5 | 9 |
#!/usr/bin/env python
"""FootballSerialParserCOM5.py: Collects data from a Daktronics All Sport 5000 connected via port J2 to a
Daktronics All Sport CG connected to a computer on COM port (defined on line 96), then parses data to
a .csv readable by broadcasting programs. This file has only been tested using game... | BristolTNCitySchools/DaktronicsCGSerialParser | Football-6601/FootballSerialParserCOM.py | .py | 6cbf640f654acbcf | 7.5 | 9 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Classes and types for pairwise match alignment."""
import logging
from abc import ABC, abstractmethod
from typing import List, Mapping, Optional, Tuple, Union
from lingpy.align.pairwise import sw_align
from spacy.tokens import Span
from .match import Match
# Lingpy s... | direct-phonology/dphon | src/dphon/align.py | .py | ee730c0a898e4b4d | 7.63 | 17 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""dphon - a tool for old chinese phonetic analysis
Usage:
dphon -h | --help
dphon --version
dphon [-v | -vv] [options] <path>...
Global Options:
-h, --help
Show this help text and exit.
--version
Show program version and exit.
-v... | direct-phonology/dphon | src/dphon/cli.py | .py | d0ab432ebda815d5 | 7.63 | 17 |
# -*- coding: utf-8 -*-
from typing import List, Optional, Tuple
from rich.console import Console
from rich.highlighter import RegexHighlighter
from rich.theme import Theme
from spacy.tokens import Span
from .g2p import GraphemesToPhonemes
from .match import Match
# Default color scheme for highlighting matches
DEF... | direct-phonology/dphon | src/dphon/console.py | .py | fe31106e3450298e | 7.63 | 17 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Classes for loading document corpora and passing them to an NLP pipeline."""
import logging
import jsonlines
from abc import ABC, abstractmethod
from collections import OrderedDict
from glob import glob
from pathlib import Path
from typing import Any, Dict, Iterable, Tu... | direct-phonology/dphon | src/dphon/corpus.py | .py | 89d8270dc3db9672 | 7.63 | 17 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Abstract base class and implementations for extending Matches."""
import logging
from abc import ABC, abstractmethod
from typing import List
import Levenshtein as Lev
from spacy.tokens import Span
from .match import Match
from .g2p import OOV_PHONEMES
class Extender... | direct-phonology/dphon | src/dphon/extend.py | .py | 43a081a5007b32aa | 7.63 | 17 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tools for converting graphemes to phonemes."""
from importlib.resources.abc import Traversable
import json
import logging
from typing import Iterable, Iterator, Optional, Tuple, List
from spacy.language import Language
from spacy.lookups import Table
from spacy.tokens ... | direct-phonology/dphon | src/dphon/g2p.py | .py | 1966cf61cc6ad0b6 | 7.63 | 17 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The Match class for encoding text reuse relationships."""
import math
from typing import Dict, NamedTuple
import Levenshtein as Lev
from rich.console import Console, ConsoleOptions, RenderResult
from rich.table import Table
from spacy.tokens import Span
class Match(N... | direct-phonology/dphon | src/dphon/match.py | .py | 6f1a544435073d14 | 7.63 | 17 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""SpaCy pipeline component for generating Token n-grams from Docs."""
import logging
from typing import Iterator
from spacy.language import Language
from spacy.tokens import Doc, Span
class Ngrams:
"""A spaCy pipeline component for generating Token n-grams from Doc... | direct-phonology/dphon | src/dphon/ngrams.py | .py | d5ebb8686e942d4e | 7.63 | 17 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Classes for analyzing text reuse."""
from collections import defaultdict
from functools import cached_property
from itertools import combinations
from typing import Callable, Iterable, Iterator, List
from networkx import Graph, MultiGraph, connected_components, create_... | direct-phonology/dphon | src/dphon/reuse.py | .py | 38b372fd90b48dc4 | 7.63 | 17 |
# -*- coding: utf-8 -*-
"""Aligner unit tests."""
from unittest import TestCase
from pathlib import Path
import spacy
from dphon.g2p import get_sound_table_json
from dphon.match import Match
from dphon.align import SmithWatermanAligner, SmithWatermanPhoneticAligner
from lingpy.align.pairwise import _get_scorer
class... | direct-phonology/dphon | tests/unit/test_align.py | .py | f324d818f4c415b7 | 8.13 | 17 |
"""Tests for the cli module."""
import logging
import sys
from io import StringIO
from unittest import TestCase
from unittest.mock import patch
from dphon.cli import __doc__ as doc
from importlib.metadata import version as pkg_version
from dphon.cli import run
# disconnect logging for testing
logging.captureWarnings... | direct-phonology/dphon | tests/unit/test_cli.py | .py | 96566254cd129657 | 8.13 | 17 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the corpus module."""
import logging
from unittest import TestCase
from dphon.corpus import PlaintextCorpusLoader
class TestPlaintextCorpusLoader(TestCase):
"""Test the PlaintextCorpusLoader."""
def setUp(self) -> None:
"""Create a loader f... | direct-phonology/dphon | tests/unit/test_corpus.py | .py | 0c23853885fcbfd3 | 8.13 | 17 |
"""Extender unit tests."""
from unittest import TestCase
import spacy
from dphon.extend import LevenshteinExtender, extend_matches
from dphon.match import Match
class TestLevenshteinExtender(TestCase):
"""Test the LevenshteinExtender."""
def setUp(self) -> None:
"""Create a blank spaCy model and ex... | direct-phonology/dphon | tests/unit/test_extend.py | .py | 5fa382e05679738f | 7.13 | 17 |
"""Tests for the phonemes module."""
import logging
from unittest import TestCase
import spacy
from dphon.match import Match
from dphon.g2p import GraphemesToPhonemes, OOV_PHONEMES
from spacy.tokens import Doc, Span, Token
# disconnect logging for testing
logging.disable(logging.CRITICAL)
class TestG2P(TestCase):
... | direct-phonology/dphon | tests/unit/test_g2p.py | .py | 727c913864cbb08b | 8.13 | 17 |
"""Tests for the indexing module."""
import io
import logging
from unittest import TestCase
from typing import Iterator
import spacy
from spacy.tokens import Doc, Token
from dphon.console import err_console
from dphon.index import LookupsIndex, NgramPhonemesLookupsIndex
# disconnect logging and capture stderr output... | direct-phonology/dphon | tests/unit/test_index.py | .py | d36e1952698696cf | 8.13 | 17 |
from unittest import TestCase
import spacy
from dphon.match import Match
class TestMatch(TestCase):
"""Test the Match class."""
maxDiff = None # don't limit length of diff output for failures
def setUp(self) -> None:
"""Create example Docs to test with."""
self.nlp = spacy.blank("en")... | direct-phonology/dphon | tests/unit/test_match.py | .py | 33bfaffdd00d6776 | 8.13 | 17 |
"""Tests for the n-grams module."""
from dphon.ngrams import Ngrams
from unittest import TestCase
import spacy
from spacy.tokens import Doc
class TestNgrams(TestCase):
"""Test the n-grams spaCy pipeline component."""
def setUp(self) -> None:
"""create blank spaCy language for testing"""
sel... | direct-phonology/dphon | tests/unit/test_ngrams.py | .py | e78b78f47424c2bd | 8.13 | 17 |
"""Tests for the text reuse module."""
import logging
from unittest import TestCase
import spacy
from spacy.tokens import Doc
from dphon.extend import LevenshteinExtender
from dphon.match import Match
from dphon.reuse import MatchGraph
# disconnect logging for testing
logging.captureWarnings(True)
logging.disable(l... | direct-phonology/dphon | tests/unit/test_reuse.py | .py | 3de2126b0b67b9a2 | 8.13 | 17 |
from __future__ import annotations
import os
import sys
import nox
ROOT = os.path.dirname(os.path.abspath(__file__))
@nox.session
def build(session: nox.Session) -> None:
"""Build sdist and wheel dists."""
session.install("pip", "build")
session.install("setuptools")
session.run("python", "--versio... | sandpiper-toolchain/sandplover | noxfile.py | .py | 2671f8e3a4d4f24c | 7.48 | 8 |
import datetime
import time
import numpy as np
import xarray as xr
from numba import njit
from scipy import optimize
def format_number(number):
integer = int(round(number, -1))
string = f"{integer:,}"
return string
def format_table(number):
integer = round(number, 1)
string = str(integer)
r... | sandpiper-toolchain/sandplover | sandplover/utils.py | .py | 73221a89d2fc2436 | 7.48 | 8 |
#!/usr/bin/env -S python3 -B
#
# javadoc-cleanup: Github action for tidying up javadocs
#
# Copyright (c) 2020-2023 Vincent A Cicirello
# https://www.cicirello.org/
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (t... | cicirello/javadoc-cleanup | tidyjavadocs.py | .py | fd851a9d2d57be9a | 7.62 | 16 |
import threading
import time
import random
import trio
import asyncio
import contextlib
import logging
import signal
import os
import gc
import pytest
from cobald.daemon.runners.service import ServiceRunner, service
logging.getLogger().level = 10
class TerminateRunner(Exception):
pass
@contextlib.contextmana... | MatterMiners/cobald | cobald_tests/daemon/test_service.py | .py | 00398f194c918e39 | 8.04 | 11 |
import pytest
from cobald.interfaces import Controller, PoolDecorator, Partial
from ..mock.pool import FullMockPool
class MockController(Controller):
def regulate(self, interval: float):
pass
class MockDecorator(PoolDecorator):
pass
class TestPartial(object):
def test_bind(self):
"""... | MatterMiners/cobald | cobald_tests/interfaces/test_partial.py | .py | 77ba9ca5b356f287 | 8.04 | 11 |
#!/usr/bin/env python3
"""
Utility to dynamically create changelogs from fragment files
"""
import argparse
import glob
import os
import itertools
import operator
import functools
import sys
import contextlib
import datetime
from typing import NamedTuple, List, Iterable, Dict, Tuple
import yaml
TODAY = datetime.date... | MatterMiners/cobald | dev_tools/change-log.py | .py | c6418368b1729055 | 7.54 | 11 |
from typing import Callable
import weakref
import asyncio
from cobald.interfaces import Pool, CompositePool
from cobald.daemon import service
@service(flavour=asyncio)
class FactoryPool(CompositePool):
"""
Composition that adds and removes pools to satisfy demand
:param factory: a callable that produce... | MatterMiners/cobald | src/cobald/composite/factory.py | .py | 1c40c934d29b4a81 | 7.54 | 11 |
from typing import Literal
from ..interfaces import Pool, CompositePool
class WeightedComposite(CompositePool):
"""
Composition of pools weighted by their current state
The aggregation of children's :py:attr:`~.Pool.demand`,
:py:attr:`~.Pool.utilisation` and :py:attr:`~.Pool.allocation`
is weigh... | MatterMiners/cobald | src/cobald/composite/weighted.py | .py | 33ad1c21bc0f5f7e | 7.54 | 11 |
from functools import partial
from typing import Any, Callable, Optional, TypeVar, TypeAlias, overload
import asyncio
from ..interfaces import Pool, Controller, Partial
from ..daemon import service
C = TypeVar("C", bound="Controller")
#: Individual control rule for a pool on a given interval
#:
#: When a rule for a... | MatterMiners/cobald | src/cobald/controller/stepwise.py | .py | 7ed5e4ff3e4da7bd | 7.54 | 11 |
import os
from contextlib import contextmanager
from typing import Type, Tuple, Dict, Set
from yaml import SafeLoader, BaseLoader
from entrypoints import get_group_all as get_entrypoints
from toposort import toposort_flatten
from ..plugins import constraints as plugin_constraints, YAMLTagSettings
from ..config.yaml i... | MatterMiners/cobald | src/cobald/daemon/core/config.py | .py | 95e20191bb781d47 | 7.54 | 11 |
import sys
import logging
import logging.handlers
def create_handler(target: str):
"""Create a handler for logging to ``target``"""
if target == "stderr":
return logging.StreamHandler(sys.stderr)
elif target == "stdout":
return logging.StreamHandler(sys.stdout)
else:
return log... | MatterMiners/cobald | src/cobald/daemon/core/logger.py | .py | f08b5a05b0ac8a8b | 7.54 | 11 |
"""
Daemon core specific to cobald
"""
import asyncio
import sys
import logging
import platform
import cobald.__about__
from .logger import initialise_logging
from .cli import CLI
from .config import load
from .. import runtime
def run(configuration: str, level: str, target: str, short_format: bool):
"""Run th... | MatterMiners/cobald | src/cobald/daemon/core/main.py | .py | 35b7a866ec26b8fa | 7.54 | 11 |
from typing import Any
from types import ModuleType
from functools import partial, singledispatch
@singledispatch
def pretty_ref(obj: Any) -> str:
"""Pretty object reference using ``module.path:qual.name`` format"""
try:
return obj.__module__ + ":" + obj.__qualname__
except AttributeError:
... | MatterMiners/cobald | src/cobald/daemon/debug.py | .py | 410718309053ac6e | 7.54 | 11 |
"""
Show how the winner distribution and bias of a voting method changes with
varying dispersion of candidates.
"""
import random
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
from joblib import Parallel, delayed
from seaborn import histplot, kdeplot
from elsim.elections impor... | endolith/elsim | examples/distributions_by_dispersion.py | .py | ab5f997adddf3a22 | 7.48 | 8 |
"""
Show the winner distributions and bias of different voting methods.
"""
import random
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
from joblib import Parallel, delayed
from seaborn import histplot, kdeplot
from elsim.elections import normal_electorate, normed_dist_utiliti... | endolith/elsim | examples/distributions_by_method.py | .py | a50bf655e61b2dbd | 7.48 | 8 |
"""
Show how the winner distribution and bias of a voting method change with
number of candidates.
"""
import random
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
from joblib import Parallel, delayed
from seaborn import histplot, kdeplot
from elsim.elections import normal_elec... | endolith/elsim | examples/distributions_by_n_cands.py | .py | 88d669bea7c79aaa | 7.48 | 8 |
"""
Show the winner distributions and bias of different voting methods with uniform
distribution of voters and candidates.
Similar to Figure 3
The distributions of the winning position with k = 3, 4, 5 candidates and
continuous 1-Euclidean voters (both uniformly distributed) under plurality and
IRV.
from
Kiran Toml... | endolith/elsim | examples/tomlinson_2023_figure_3_updated.py | .py | e7e9e4fb9d9a1406 | 7.48 | 8 |
from django.test import TestCase
from django_trips.api.filters import TimedeltaFromDaysFilter
from django_trips.models import TripSchedule
class TimedeltaFromDaysFilterTestCase(TestCase):
"""TimedeltaFromDaysFilter converts a "days" query value to a timedelta;
an unparseable value should yield an empty query... | DestinationPak/django-trips | django_trips/api/tests/test_filters.py | .py | b555ea4d008b4c46 | 7.92 | 6 |
"""TripViewSet is the public catalog (surface B) - read-only, no exceptions.
Trip management (create/update/delete) moved out of the lib entirely; it lives in
destipak's tenancy-aware operator API, built against TripCreateSerializer imported
directly from django_trips.api.serializers. These tests lock in that the publ... | DestinationPak/django-trips | django_trips/api/tests/test_trip_write_methods_disabled.py | .py | 3affdc4c66558b04 | 7.92 | 6 |
# pylint:disable=import-error,too-many-ancestors
from django.shortcuts import get_object_or_404
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema_view
from rest_framework import filters, generics, status
from rest_framework.authentication import SessionAuthen... | DestinationPak/django-trips | django_trips/api/views/booking.py | .py | 88fbd17541e40fff | 7.42 | 6 |
# pylint:disable=import-error
from django.db.models import Count, Q
from drf_spectacular.utils import extend_schema_view
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from django_trips.api.schema_meta import categories_list_schema
from django_trips.api... | DestinationPak/django-trips | django_trips/api/views/category.py | .py | 73ab50c234f612de | 7.42 | 6 |
# pylint:disable=import-error
from django.db.models import Count, Q
from drf_spectacular.utils import extend_schema_view
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from django_trips.api.schema_meta import hosts_list_schema
from django_trips.api.seri... | DestinationPak/django-trips | django_trips/api/views/host.py | .py | 8f454124b586f767 | 7.42 | 6 |
# pylint:disable=import-error
from drf_spectacular.utils import extend_schema_view
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from django_trips.api.paginators import TripResponsePagination
from django_trips.api.schema_meta import trip_reviews_list_s... | DestinationPak/django-trips | django_trips/api/views/review.py | .py | e265c81f513e7092 | 7.42 | 6 |
# pylint:disable=import-error
from drf_spectacular.utils import extend_schema_view
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from django_trips.api.schema_meta import testimonials_list_schema
from django_trips.api.serializers import TestimonialSeria... | DestinationPak/django-trips | django_trips/api/views/testimonial.py | .py | d6b68c0d3df006b0 | 7.92 | 6 |
# pylint:disable=import-error
from django.db.models import Count, DecimalField, ExpressionWrapper, F, Min, Prefetch, Q
from django.shortcuts import get_object_or_404
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema_view
from rest_framework import status
from ... | DestinationPak/django-trips | django_trips/api/views/trip.py | .py | 0fd7155b4ee55948 | 7.42 | 6 |
# pylint:disable=import-error
from django.db.models import Count, Q
from drf_spectacular.utils import extend_schema_view
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from django_trips.api.schema_meta import trust_badges_list_schema
from django_trips.a... | DestinationPak/django-trips | django_trips/api/views/trust_badge.py | .py | 1440f835d35ce051 | 7.42 | 6 |
from django.db import models
class PackageTier(models.TextChoices):
STANDARD = "STANDARD", "Standard Package"
BUDGET = "BUDGET", "Budget Package"
PREMIUM = "PREMIUM", "Premium Package"
class FeaturedType(models.TextChoices):
BESTSELLER = "BESTSELLER", "Bestseller"
POPULAR = "POPULAR", "Popular"
... | DestinationPak/django-trips | django_trips/choices.py | .py | 19996feadd37f6ec | 7.42 | 6 |
"""
Adapter for reading Location fields, so callers work the same way
whether django_trips.Location or a swapped-in model backs the FK
(DJANGO_TRIPS_LOCATION_MODEL).
"""
from django.conf import settings
from django.utils.module_loading import import_string
from django_trips.utils import resolve_media_url
DEFAULT_LOC... | DestinationPak/django-trips | django_trips/location_adapter.py | .py | 5ae290a6f44b6959 | 7.42 | 6 |
import random
import traceback
from datetime import datetime, time, timedelta
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.db.models import Avg
from django.utils import timezone
from django.utils.text impor... | DestinationPak/django-trips | django_trips/management/commands/generate_trips.py | .py | 5bf928339e586cb9 | 7.42 | 6 |
"""Test management command"""
from datetime import timedelta
from io import StringIO
from unittest.mock import patch
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management import CommandError, call_command
from django.test import TestCase
from django.utils import ti... | DestinationPak/django-trips | django_trips/management/tests/test_generate_trips.py | .py | 6bde55a4cc42a071 | 7.92 | 6 |
# Copyright 2023 Canonical Ltd.
#
# 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 writing, s... | charmed-kubernetes/charm-kubernetes-control-plane | lib/charms/kubernetes_libs/v0/etcd.py | .py | be1c72424d70d238 | 7.64 | 18 |
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Sync AlertManager rules from an upstream repository.
This script fetches AlertManager rules definitions from a specified version
of the kube-prometheus project and adjusts them for compatibility with
COS.
"""
import logging
import os
import... | charmed-kubernetes/charm-kubernetes-control-plane | scripts/update_alert_rules.py | .py | c81f7f5f94474e3e | 7.64 | 18 |
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Sync Grafana dashboards from an upstream repository.
This script fetches Grafana dashboard definitions from a specified version
of the kube-prometheus project and adjusts them for compatibility with
COS by removing the built-in $prometheus d... | charmed-kubernetes/charm-kubernetes-control-plane | scripts/update_grafana_dashboards.py | .py | 4f4e8a9b67a12266 | 7.64 | 18 |
import contextlib
import dataclasses
import json
import logging
import os
import shlex
import shutil
import subprocess
import tempfile
from pathlib import Path
from typing import Optional
import ops
from charmhelpers.fetch.archiveurl import ArchiveUrlFetchHandler
log = logging.getLogger(__name__)
BENCH_HOME = Path("... | charmed-kubernetes/charm-kubernetes-control-plane | src/actions/cis_benchmark.py | .py | abe74b2533a5a432 | 7.64 | 18 |
#!/usr/local/sbin/charm-env python3
import os
import re
import ops
from charms import kubernetes_snaps
from auth_webhook import create_token, delete_token, get_secrets
def protect_resources(name: str, event: ops.ActionEvent) -> bool:
"""Do not allow the action to operate on names used by Charmed Kubernetes."""
... | charmed-kubernetes/charm-kubernetes-control-plane | src/actions/users.py | .py | ed53bfed1c916854 | 7.64 | 18 |
import logging
import os
import random
import re
import string
import tempfile
from base64 import b64decode, b64encode
from dataclasses import dataclass
from pathlib import Path
from subprocess import CalledProcessError, check_call, check_output
from typing import List, Mapping
import charms.contextual_status as statu... | charmed-kubernetes/charm-kubernetes-control-plane | src/auth_webhook.py | .py | 164c435cdad12f43 | 7.64 | 18 |
import json
import logging
import os
import shutil
from subprocess import CalledProcessError, check_call, check_output
import charms.contextual_status as status
import tenacity
from ops import BlockedStatus
from kubectl import ROOT_KUBECONFIG, get_service_ip, kubectl, kubectl_get
kubeconfig_dir = "/root/snap/cdk-add... | charmed-kubernetes/charm-kubernetes-control-plane | src/cdk_addons.py | .py | 2de4494321894ad8 | 7.64 | 18 |
# Copyright 2024 Canonical
# See LICENSE file for licensing details.
"""Cloud Integration for Charmed Kubernetes Control Plane."""
import logging
from typing import Optional, Union
import charms.contextual_status as status
import ops
from ops.interface_aws.requires import AWSIntegrationRequires
from ops.interface_az... | charmed-kubernetes/charm-kubernetes-control-plane | src/cloud_integration.py | .py | 3e075da0944595f8 | 7.64 | 18 |
import logging
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Sequence, Union
from ops import CharmBase
log = logging.getLogger(__name__)
OBSERVABILITY_ROLE = "system:cos"
@dataclass
class JobConfig:
"""Data class representing the configuration for a Prometheus scrape job.
... | charmed-kubernetes/charm-kubernetes-control-plane | src/cos_integration.py | .py | eb7c3f910b168801 | 7.64 | 18 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014-2015 Canonical Limited.
#
# 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
#
# Unl... | charmed-kubernetes/charm-kubernetes-control-plane | src/encryption/fstab.py | .py | 052966bbecc054db | 7.64 | 18 |
import json
import logging
import sqlite3
from functools import cached_property
from typing import Any, List, Mapping, Optional
import hvac
import ops
log = logging.getLogger(__name__)
def try_json(s: Optional[str]) -> Optional[Any]:
"""Try to load string as json, return if not possible."""
try:
ret... | charmed-kubernetes/charm-kubernetes-control-plane | src/encryption/reactive.py | .py | 0b3db80385473b22 | 7.64 | 18 |
import base64
import hashlib
import json
import logging
import socket
from functools import cached_property
from typing import List, Optional
import hvac
import ops
import requests
from encryption import reactive
log = logging.getLogger(__name__)
SECRETS_BACKEND_FORMAT = "charm-{model-uuid}-{app}"
class VaultNotRe... | charmed-kubernetes/charm-kubernetes-control-plane | src/encryption/vault_kv.py | .py | d795d03872e60465 | 7.64 | 18 |
import logging
import os
import re
import shutil
import subprocess
from pathlib import Path
from typing import Optional
from uuid import uuid4
import charms.operator_libs_linux.v0.apt as apt
import ops
from encryption.fstab import Fstab
from encryption.vault_kv import VaultKV, VaultNotReadyError
LOOP_ENVS = Path("/e... | charmed-kubernetes/charm-kubernetes-control-plane | src/encryption/vaultlocker.py | .py | 3e5f5df559061084 | 7.64 | 18 |
"""HACluster integration module."""
import logging
import subprocess
from typing import List, Optional
import ops
from cached_property import cached_property
from interface_hacluster.ops_ha_interface import HAServiceRequires
from ops.framework import Object, StoredState
from ops.model import Relation
log = logging.g... | charmed-kubernetes/charm-kubernetes-control-plane | src/hacluster.py | .py | 6d25644b45eec97f | 7.64 | 18 |
from ipaddress import ip_address
from typing import Optional
from charms import kubernetes_snaps
class K8sApiEndpoints:
"""Kubernetes API endpoints for this charm."""
def __init__(self, charm):
self.charm = charm
def from_config(self) -> Optional[str]:
"""Endpoint URL from charm configu... | charmed-kubernetes/charm-kubernetes-control-plane | src/k8s_api_endpoints.py | .py | dd499516602f127b | 7.64 | 18 |
import logging
from subprocess import CalledProcessError
from typing import List, Optional
from kubectl import kubectl_get
log = logging.getLogger(__name__)
def get_pods(namespace="default"):
try:
result = kubectl_get("po", "-n", namespace, "--request-timeout", "10s")
except CalledProcessError:
... | charmed-kubernetes/charm-kubernetes-control-plane | src/k8s_kube_system.py | .py | 8aefd88b6a8ae433 | 7.64 | 18 |
import json
import logging
from pathlib import Path
from subprocess import PIPE, CalledProcessError, check_output
import tenacity
log = logging.getLogger(__name__)
ROOT_KUBECONFIG = Path("/root/.kube/config")
def get_service_ip(name, namespace):
service = kubectl_get("svc", "-n", namespace, name)
return ser... | charmed-kubernetes/charm-kubernetes-control-plane | src/kubectl.py | .py | d403f2fecaa7643c | 7.64 | 18 |
"""NOTE: Leadership data is deprecated. This is used for legacy purposes."""
from subprocess import check_call, check_output
def set(key, value):
cmd = ["leader-set", f"{key}={value}"]
check_call(cmd)
def get(key):
cmd = ["leader-get", key]
return check_output(cmd).decode().strip()
| charmed-kubernetes/charm-kubernetes-control-plane | src/leader_data.py | .py | 8fe41fbfbc380b62 | 7.14 | 18 |
import subprocess
import unittest.mock as mock
import pytest
import tenacity
import kubectl
@pytest.fixture(params=["/root/.kube/config", "/home/ubuntu/config"])
def kubeconfig(request):
with mock.patch("pathlib.Path.exists") as exists:
exists.return_value = True
yield request.param, (request.pa... | charmed-kubernetes/charm-kubernetes-control-plane | tests/unit/test_kubectl.py | .py | a3896306debf6ffb | 8.14 | 18 |
# noqa: D104
import logging
from pywps.configuration import get_config_value
from xclim.core.indicator import registry as xclim_registry
from .ensemble_utils import uses_accepted_netcdf_variables
from .utils import get_available_variables, get_datasets_config, get_virtual_modules
from .wps_base import make_xclim_indi... | bird-house/finch | src/finch/processes/__init__.py | .py | 6eb8c71f624dfcd4 | 7.6 | 15 |
# noqa: D100
import io
import logging
from inspect import _empty as empty_default # noqa
from typing import Any
import pywps.exceptions
import xclim
from dask.diagnostics import ProgressBar
from pywps import FORMATS, ComplexInput, LiteralInput, Process
from pywps.app.Common import Metadata
from pywps.app.exceptions i... | bird-house/finch | src/finch/processes/wps_base.py | .py | 5ee1a4b3d60c7109 | 7.6 | 15 |
# noqa: D100
import logging
from anyascii import anyascii
from finch.processes.subset import finch_subset_bbox
from . import wpsio
from .ensemble_utils import ensemble_common_handler
from .utils import iter_xc_variables
from .wps_base import FinchProcess, convert_xclim_inputs_to_pywps
LOGGER = logging.getLogger("PY... | bird-house/finch | src/finch/processes/wps_ensemble_indices_bbox.py | .py | 5dcc18aa4ed77903 | 7.6 | 15 |
# noqa: D100
import logging
from anyascii import anyascii
from finch.processes.subset import finch_subset_gridpoint
from . import wpsio
from .ensemble_utils import ensemble_common_handler
from .utils import iter_xc_variables
from .wps_base import FinchProcess, convert_xclim_inputs_to_pywps
LOGGER = logging.getLogge... | bird-house/finch | src/finch/processes/wps_ensemble_indices_point.py | .py | 1033fdd451acf571 | 7.6 | 15 |
# noqa: D100
import logging
from anyascii import anyascii
from . import wpsio
from .ensemble_utils import ensemble_common_handler
from .subset import finch_subset_shape
from .utils import iter_xc_variables
from .wps_base import FinchProcess, convert_xclim_inputs_to_pywps
LOGGER = logging.getLogger("PYWPS")
class X... | bird-house/finch | src/finch/processes/wps_ensemble_indices_polygon.py | .py | a9e4d10dcb0aad0f | 7.6 | 15 |
# noqa: D100
import logging
from pathlib import Path
from urllib.parse import urlparse
import cf_xarray.geometry as cfgeo
import geopandas as gpd
import numpy as np
import xarray as xr
from pywps import FORMATS, ComplexInput, ComplexOutput, LiteralInput
from . import wpsio
from .utils import (
dataset_to_netcdf,
... | bird-house/finch | src/finch/processes/wps_geoseries_to_netcdf.py | .py | 6aa13fb23dc63f28 | 7.6 | 15 |
# noqa: D100
import json
import logging
from pathlib import Path
import xarray as xr
from pywps import FORMATS, ComplexInput, ComplexOutput
from xclim.core.options import MISSING_METHODS
from . import wpsio
from .utils import (
dataset_to_netcdf,
log_file_path,
single_input_or_none,
try_opendap,
u... | bird-house/finch | src/finch/processes/wps_hourly_to_daily.py | .py | ae6ac13dda9a492f | 7.6 | 15 |
# noqa: D100
from pathlib import Path
import lxml.etree
from pywps import get_ElementMakerForVersion
from pywps.app.basic import get_xpath_ns
from pywps.tests import WpsClient, WpsTestResponse
VERSION = "1.0.0"
WPS, OWS = get_ElementMakerForVersion(VERSION)
xpath_ns = get_xpath_ns(VERSION)
TESTS_HOME = Path(__file__... | bird-house/finch | tests/_common.py | .py | 02047de8664c0a02 | 8.1 | 15 |
import collections
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
import xarray as xr
from pywps import configuration
from scipy.stats import norm, uniform
from xarray import DataArray
from xclim.core.calendar import percentile_doy
from xclim.testing.helpers import test_timeseries as tim... | bird-house/finch | tests/conftest.py | .py | 87eb96e33e783cad | 8.1 | 15 |
import shutil
import zipfile
from pathlib import Path
from unittest import mock
import numpy as np
import pandas as pd
import pytest
import xarray as xr
from pywps import configuration
from finch.processes import ensemble_utils
from finch.processes.utils import (
drs_filename,
is_opendap_url,
netcdf_file_... | bird-house/finch | tests/test_utils.py | .py | f8d39ce967aeca65 | 7.1 | 15 |
import pywps.configuration
import finch.processes.utils
from _common import CFG_FILE, client_for
from finch.processes import get_indicators, get_processes, not_implemented
from finch.processes.utils import get_virtual_modules
from finch.wsgi import create_app
def test_wps_caps(client):
resp = client.get(service=... | bird-house/finch | tests/test_wps_caps.py | .py | 50a644f82376ffbe | 8.1 | 15 |
import geojson
import pytest
import xarray as xr
from _utils import execute_process, shapefile_zip, wps_input_file, wps_literal_input
def test_wps_averagepoly(client, netcdf_datasets):
# --- given ---
identifier = "average_polygon"
poly = {
"type": "Feature",
"id": "apolygon",
"ge... | bird-house/finch | tests/test_wps_xaverage_polygon.py | .py | edf37e52df70478e | 7.1 | 15 |
import re
from icon_validator.rules.lists.valid_data_types import ExampleOutputDataType
from icon_validator.styling import *
from icon_validator.rules.validator import KomandPluginValidator
from icon_validator.exceptions import ValidationException
from datetime import datetime
def detect_valid_datetime(list_entry: ... | rapid7/icon-integrations-validators | icon_validator/rules/plugin_validators/help_input_output_validator.py | .py | 5ef2aa7a68179252 | 7.52 | 10 |
"""
NavConfig.
Configuration management for Python projects.
"""
import sys
import logging
from typing import Any
from .project import (
project_root,
get_env_type,
get_environment
)
from .utils import install_uvloop
from .utils.settings import ensure_settings_priority
from .kardex import Kardex # noqa
fr... | phenobarbital/NavConfig | navconfig/__init__.py | .py | 2f0f72f171a0a893 | 7.65 | 19 |
"""``kardex`` -- the NavConfig command line interface.
The CLI is organised in command groups (``env``, ``vault``, ``log``), each
of them exposing its own actions::
kardex env create [--split]
kardex env new <name>
kardex vault create
kardex vault migrate
kardex vault save VARIABLE:VALUE
karde... | phenobarbital/NavConfig | navconfig/cli.py | .py | 90ce6eb6a2394f53 | 7.65 | 19 |
"""Shared helpers for the ``kardex`` sub-commands.
Nothing in this module may touch :data:`navconfig.config`: the CLI has to
run *before* a project owns an ``env/`` directory, which is exactly the
situation where building the global configuration fails.
"""
from __future__ import annotations
import sys
from pathlib i... | phenobarbital/NavConfig | navconfig/commands/common.py | .py | 7b81f448a7954b0b | 7.65 | 19 |
from typing import Any, Union
from abc import ABC, abstractmethod
import logging
import re
from pathlib import PurePath
from io import StringIO
from dotenv import dotenv_values, load_dotenv
from ..project import validate_project_environment
# Matches INI-style section headers (e.g. ``[AUTH_BACKENDS]``) on their own l... | phenobarbital/NavConfig | navconfig/loaders/abstract.py | .py | dee349a00cacb9c7 | 7.65 | 19 |
import asyncio
from pathlib import PurePath
from ..cyphers import FileCypher
# TODO: load by configuration the Cypher.
from .abstract import BaseLoader
class cryptLoader(BaseLoader):
"""cryptLoader.
Use to read configuration settings from Encrypted Files.
"""
def __init__(
self, env_path: P... | phenobarbital/NavConfig | navconfig/loaders/crypt.py | .py | b2c52cd537647277 | 7.65 | 19 |
import logging
from pathlib import PurePath
from .abstract import BaseLoader
def sort_key(path):
name = path.name
return "0" if name == ".env" else name
class fileLoader(BaseLoader):
"""fileLoader.
Use to read configuration settings from .env Files.
Loads one or multiple .env files from a dire... | phenobarbital/NavConfig | navconfig/loaders/file.py | .py | 168c9a2496dea878 | 7.65 | 19 |
import asyncio
from pathlib import PurePath
from concurrent.futures import ThreadPoolExecutor
from .parsers.toml import TOMLParser
from .abstract import BaseLoader
class pyProjectLoader(BaseLoader):
"""pyProjectLoader.
Read Configuration from a pyproject.toml (TOML syntax) file.
"""
def __init__(
... | phenobarbital/NavConfig | navconfig/loaders/pyproject.py | .py | 03dd4bf33bacb039 | 7.65 | 19 |
import asyncio
from pathlib import PurePath
from .parsers.toml import TOMLParser
from .abstract import BaseLoader
class tomlLoader(BaseLoader):
"""TomlLoader.
Used to read configuration settings from TOML files.
"""
def __init__(self, env_path: PurePath, override: bool = False, **kwargs) -> None:
... | phenobarbital/NavConfig | navconfig/loaders/toml.py | .py | a99084adb6c5df61 | 7.65 | 19 |
# navconfig/loaders/vault.py
"""
Unified Vault + File Loader - Default loader for NavConfig
This loader combines vault and file-based configuration loading:
1. Reads vault credentials from .env files
2. Connects to vault and loads environment-specific secrets
3. Supplements with .env.* files for additional configurati... | phenobarbital/NavConfig | navconfig/loaders/vault.py | .py | d6930d3be949442d | 7.65 | 19 |
import asyncio
from pathlib import PurePath
from .parsers.yaml import YAMLParser
from .abstract import BaseLoader
class yamlLoader(BaseLoader):
"""YamlLoader.
Used to read configuration settings from YAML files.
"""
def __init__(self, env_path: PurePath, override: bool = False, **kwargs) -> None:
... | phenobarbital/NavConfig | navconfig/loaders/yaml.py | .py | 35fe8d84e6a0f93b | 7.65 | 19 |
"""
Log Configuration.
Logging configuration.
Supports:
- Mail Critical Handler
- Rotating File handler
- Console (debug) Handler with Colors
- Error File Handler
TODO: add a Telegram Critical Handler.
"""
from pathlib import Path
from logging.config import dictConfig
from logging import setLogge... | phenobarbital/NavConfig | navconfig/logging/__init__.py | .py | 9f46b5bfa1ea5639 | 7.65 | 19 |
from abc import ABCMeta
class AbstractLog(metaclass=ABCMeta):
"""AbstractLog.
Abstract class for Logger Handlers.
"""
def __init__(self, config, loglevel, application: str) -> None:
self.env = config.ENV if config.ENV is not None else "production"
self.loglevel = loglevel
sel... | phenobarbital/NavConfig | navconfig/logging/handlers/abstract.py | .py | fa1caf016629d11f | 7.65 | 19 |
# basic configuration of Logstash
import socket
# Check if logstash_async is available
LOGSTASH_AVAILABLE = False
try:
import logstash_async # pylint: disable=W0611
LOGSTASH_AVAILABLE = True
except ImportError:
pass
from .abstract import AbstractLog
class LogstashHandler(AbstractLog):
"""LogstashHa... | phenobarbital/NavConfig | navconfig/logging/handlers/logstash.py | .py | 5ed75b23e32a0acb | 7.65 | 19 |
import sys
import os
import logging
from pathlib import Path, PurePath
class ProjectDetectionError(Exception):
"""Raised when project root cannot be properly detected."""
pass
def get_environment() -> str:
"""Returns the environment selected."""
return os.getenv("ENV", "")
def get_env_type() -> str:... | phenobarbital/NavConfig | navconfig/project.py | .py | 004c6cc61d49e886 | 7.65 | 19 |
# -*- coding: utf-8 -*-
"""
@author: Raluca Sandu
"""
import os
import time
import VolumeMetrics
from mpl_toolkits.mplot3d import Axes3D
import SimpleITK as sitk
import matplotlib.pyplot as plt
import numpy as np
import numpy.linalg as la
from skimage.draw import ellipsoid
def mvee(points, tol=0.001):
"""
Fin... | rmsandu/Ellipsoid-Fit | archive/ellipsoid_inner_outer.py | .py | 6fc94856c464cca4 | 7.66 | 20 |
"""Generate mockup point clouds scattered on/near an ellipse or ellipsoid.
Used to produce reproducible example data for the inner/outer ellipsoid fits
and for the README figures. Pass ``seed`` for reproducible output.
"""
import numpy as np
def sample_ellipse_points(semi_axes=(3.0, 1.5), center=(0.0, 0.0), rotatio... | rmsandu/Ellipsoid-Fit | ellipsoid_fit/sampling.py | .py | 99fe241fd6178e06 | 7.66 | 20 |
import numpy as np
import pytest
from ellipsoid_fit import inner_ellipsoid_fit, sample_ellipse_points, sample_ellipsoid_points
from ellipsoid_fit.hull import get_hull
def _assert_inside_hull(points, B, d, tol=1e-3):
A, b, _hull = get_hull(points)
# Support function of the ellipsoid {B@u + d : ||u||<=1} along... | rmsandu/Ellipsoid-Fit | tests/test_inner.py | .py | ec121d9a6de11ecb | 7.16 | 20 |
# PYTHON_ARGCOMPLETE_OK
# This file is part of python-project-template
# Made available under the terms of the MIT License, see LICENSE.txt
# Copyright 2019-2026 Kevin Locke <kevin@kevinlocke.name>
"""Command-line interface for packagename."""
import argparse
import logging
import sys
from collections.abc import Sequ... | kevinoid/python-project-template | src/packagename/cli.py | .py | 89a9266d1bb4e8ca | 7.5 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.