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 |
|---|---|---|---|---|---|---|
"""
Base classes for event sinks
"""
import csv
import datetime
import io
import logging
from collections import namedtuple
import requests
from django.conf import settings
from django.core.paginator import Paginator
from edx_toggles.toggles import WaffleFlag
from platform_plugin_aspects.utils import get_model
from ... | openedx/platform-plugin-aspects | platform_plugin_aspects/sinks/base_sink.py | .py | 859db5a6c9e65f38 | 7.92 | 6 |
"""User profile sink"""
from platform_plugin_aspects.sinks.base_sink import ModelBaseSink
from platform_plugin_aspects.sinks.serializers import CourseEnrollmentSerializer
class CourseEnrollmentSink(ModelBaseSink): # pylint: disable=abstract-method
"""
Sink for user CourseEnrollment model
"""
model ... | openedx/platform-plugin-aspects | platform_plugin_aspects/sinks/course_enrollment_sink.py | .py | 006b85120ef01257 | 7.92 | 6 |
"""
Handler for the CMS COURSE_PUBLISHED event
Does the following:
- Pulls the course structure from modulestore
- Serialize the xblocks
- Sends them to ClickHouse in CSV format
Note that the serialization format does not include all fields as there may be things like
LTI passwords and other secrets. We just take the... | openedx/platform-plugin-aspects | platform_plugin_aspects/sinks/course_overview_sink.py | .py | 3b617a372e76f619 | 7.92 | 6 |
"""User profile sink"""
from platform_plugin_aspects.sinks.base_sink import ModelBaseSink
from platform_plugin_aspects.sinks.serializers import UserExternalIDSerializer
class ExternalIdSink(ModelBaseSink): # pylint: disable=abstract-method
"""
Sink for user external ID serializer
"""
model = "exter... | openedx/platform-plugin-aspects | platform_plugin_aspects/sinks/external_id_sink.py | .py | 5f92fd055b63f6d1 | 7.92 | 6 |
"""Tag sink"""
from platform_plugin_aspects.sinks.base_sink import ModelBaseSink
from platform_plugin_aspects.sinks.serializers import (
ObjectTagSerializer,
TagSerializer,
TaxonomySerializer,
)
class TagSink(ModelBaseSink): # pylint: disable=abstract-method
"""
Sink for content tags
"""
... | openedx/platform-plugin-aspects | platform_plugin_aspects/sinks/tag_sink.py | .py | f2576cbafb428446 | 7.92 | 6 |
import json
from datetime import datetime
from unittest.mock import Mock, patch
from django.test import TestCase
from platform_plugin_aspects.sinks.serializers import (
BaseSinkSerializer,
CourseOverviewSerializer,
DateTimeJSONEncoder,
)
from test_utils.helpers import course_key_factory
class TestBaseSi... | openedx/platform-plugin-aspects | platform_plugin_aspects/sinks/tests/test_serializers.py | .py | ae819fe4e79c4042 | 7.92 | 6 |
"""User profile sink"""
from platform_plugin_aspects.sinks.base_sink import ModelBaseSink
from platform_plugin_aspects.sinks.serializers import UserProfileSerializer
class UserProfileSink(ModelBaseSink): # pylint: disable=abstract-method
"""
Sink for user profile events
"""
model = "user_profile"
... | openedx/platform-plugin-aspects | platform_plugin_aspects/sinks/user_profile_sink.py | .py | 28e0afdacabf4fae | 7.92 | 6 |
"""User retirement sink"""
import requests
from django.conf import settings
from platform_plugin_aspects.sinks.base_sink import ModelBaseSink
from platform_plugin_aspects.sinks.serializers import UserRetirementSerializer
class UserRetirementSink(ModelBaseSink): # pylint: disable=abstract-method
"""
Sink fo... | openedx/platform-plugin-aspects | platform_plugin_aspects/sinks/user_retire_sink.py | .py | c108453f42105f9e | 7.92 | 6 |
"""
This file contains a management command for exporting course modulestore data to ClickHouse.
"""
import logging
from importlib import import_module
from celery import shared_task
from edx_django_utils.monitoring import set_code_owner_attribute
from opaque_keys.edx.keys import CourseKey
from platform_plugin_aspec... | openedx/platform-plugin-aspects | platform_plugin_aspects/tasks.py | .py | 58404449677250c9 | 7.92 | 6 |
"""
Tests for the load_test_tracking_events management command.
"""
from collections import namedtuple
from unittest.mock import DEFAULT, Mock, patch
import pytest
from django.core.management import call_command
CommandOptions = namedtuple("TestCommandOptions", ["options", "expected_logs"])
def load_test_command_b... | openedx/platform-plugin-aspects | platform_plugin_aspects/tests/commands/test_load_test_tracking_events.py | .py | a1a33c2c8384a663 | 7.92 | 6 |
"""
Tests for signal handlers.
"""
from unittest.mock import Mock, patch
from django.test import TestCase
from platform_plugin_aspects.signals import (
on_externalid_saved_txn,
on_user_retirement,
receive_course_publish,
)
from platform_plugin_aspects.sinks.user_retire_sink import UserRetirementSink
cl... | openedx/platform-plugin-aspects | platform_plugin_aspects/tests/test_signals.py | .py | 922a453d9dc44ac4 | 7.92 | 6 |
#!/usr/bin/env python
"""
Test basic SupersetXBlock display function
"""
import json
from unittest import TestCase
from unittest.mock import Mock, patch
from django.core.exceptions import ImproperlyConfigured
from opaque_keys.edx.locator import CourseLocator
from webob import Request
from xblock.field_data import Dic... | openedx/platform-plugin-aspects | platform_plugin_aspects/tests/test_xblock.py | .py | 202bec7bf5ee28fa | 7.92 | 6 |
"""
Utilities for the Aspects app.
"""
from __future__ import annotations
import copy
import logging
import os
import uuid
from importlib import import_module
from urllib.parse import urljoin
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.urls import reverse
from... | openedx/platform-plugin-aspects | platform_plugin_aspects/utils.py | .py | 23c518372496fa3c | 7.92 | 6 |
from typing import Optional
from opperai import fn
from pydantic import BaseModel, Field
from .actions import Action, Trajectory
class Evaluation(BaseModel):
"""
Evaluation of the action an agent is going to take given its trajectory.
"""
observations: str = Field(
...,
description... | opper-ai/delvin | delvin/agent/functions.py | .py | 18382f7e0cc11b1a | 7.65 | 19 |
import os
from .actions import (
ViewFile,
)
def view_file_outline(file_path: str) -> str:
"""
Given a python file, return a formatted string that includes the total line count on top,
followed by an outline of functions or classes in the file with their line numbers,
accounting for possible inde... | opper-ai/delvin | delvin/agent/view.py | .py | 76036ea3e1572ce7 | 7.65 | 19 |
import asyncio
import os
import subprocess
async def clone_or_reset_repo(
repo_url: str, commit_hash: str, destination: str
) -> None:
await clone_repo_at_commit(repo_url, commit_hash, destination)
print("Successfully reset the repository to the latest commit.")
async def clone_repo(repo_url: str, dest... | opper-ai/delvin | delvin/github.py | .py | 28d2d939a1ccbe72 | 7.65 | 19 |
import time
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from hs2p import TilingResult
from .tile_store import TarTileReader
class TileIndexDataset(torch.utils.data.Dataset):
def __init__(self, tile_indices):
self.tile_indices = np.asarray(tile_indices, dtype=np.int64)... | clemsgrs/slide2vec | slide2vec/data/dataset.py | .py | df89e513f7b15706 | 7.62 | 16 |
import os
import torch
_RANK = -1
_WORLD_SIZE = -1
_LOCAL_RANK = -1
_LOCAL_WORLD_SIZE = -1
def is_enabled() -> bool:
"""
Returns:
True if distributed mode has been enabled (the process topology is known).
"""
return _RANK >= 0
def get_global_size() -> int:
"""
Returns:
The ... | clemsgrs/slide2vec | slide2vec/distributed/__init__.py | .py | 4af6b4dc557e580f | 7.62 | 16 |
"""torchrun entry point for distributed dense-over-images extraction (issue #235).
One of these runs per GPU under ``torch.distributed.run``. Like its two siblings it is near
logic-free: the rank, the model and the progress wiring come from
:mod:`slide2vec.distributed.worker_entry`; what is left here is this path's ow... | clemsgrs/slide2vec | slide2vec/distributed/dense_image_worker.py | .py | 8ed7e0be72eccff1 | 7.62 | 16 |
"""torchrun entry point for distributed dense feature extraction (issue #217).
One of these runs per GPU under ``torch.distributed.run``. It is deliberately near
logic-free (D10): the rank, the model and the progress wiring all come from
:mod:`slide2vec.distributed.worker_entry`; what is left here is dense-specific — ... | clemsgrs/slide2vec | slide2vec/distributed/dense_worker.py | .py | 8dda280667afff42 | 7.62 | 16 |
"""torchrun entry point for distributed given-image feature extraction (issue #234).
One of these runs per GPU under ``torch.distributed.run``. Like its dense sibling it is
near logic-free: the rank, the model and the progress wiring come from
:mod:`slide2vec.distributed.worker_entry`; what is left here is Given-speci... | clemsgrs/slide2vec | slide2vec/distributed/image_worker.py | .py | 7045a60930c8353d | 7.62 | 16 |
"""What every torchrun worker does before it starts encoding.
A slide2vec worker module is deliberately near logic-free — read the rank torchrun handed
it, rebuild the model the parent named, wire progress back to the parent, encode its shard.
Only the last step differs between the dense and given-image workers, so th... | clemsgrs/slide2vec | slide2vec/distributed/worker_entry.py | .py | 8cd7acefed606720 | 7.62 | 16 |
"""CONCH and CONCH v1.5 encoder implementations.
CONCH requires the ``conch`` package (pip install conch).
CONCH v1.5 requires ``transformers`` and uses the TITAN model to extract
the CONCH v1.5 backbone.
"""
from typing import Callable
import torch
from torch import Tensor
from torchvision.transforms import v2
fro... | clemsgrs/slide2vec | slide2vec/encoders/models/conch.py | .py | 9a26af86bcfaf2e1 | 7.62 | 16 |
"""GenBio-PathFM tile encoder.
GenBio-PathFM (GenBio AI, 2024; ``genbio-ai/genbio-pathfm``) is a 1.1B-param ViT
histopathology tile encoder (JEDI = JEPA + DINO training on public data). It is
loaded via HF ``AutoModel(trust_remote_code=True)`` (auto_map ->
``GenBioPathFMModel``), so it is a custom :class:`TileEncoder`... | clemsgrs/slide2vec | slide2vec/encoders/models/genbio.py | .py | ad62002dee567b58 | 7.62 | 16 |
"""Prov-GigaPath encoder implementation."""
from typing import Callable
import torch
from torchvision.transforms import v2
from slide2vec.encoders.base import (
SlideEncoder,
TimmTileEncoder,
preferred_default_device,
resolve_requested_output_variant,
)
from slide2vec.encoders.registry import registe... | clemsgrs/slide2vec | slide2vec/encoders/models/gigapath.py | .py | 8431f0831fc75896 | 7.62 | 16 |
"""Hibou-B and Hibou-L encoder implementations.
Requires the ``transformers`` package.
"""
from typing import Callable
import torch
from torch import Tensor
from torchvision.transforms import v2
from transformers import AutoModel
from slide2vec.encoders.base import (
TileEncoder,
attentions_tuple_to_grids,
... | clemsgrs/slide2vec | slide2vec/encoders/models/hibou.py | .py | 6e8abc14d7167feb | 7.62 | 16 |
"""Midnight encoder implementation.
Requires the ``transformers`` package.
"""
from typing import Callable
import torch
from torch import Tensor
from torchvision.transforms import v2
from transformers import AutoModel
from slide2vec.encoders.base import (
TileEncoder,
attentions_tuple_to_grids,
hf_eage... | clemsgrs/slide2vec | slide2vec/encoders/models/midnight.py | .py | 36e1b23856a4af5f | 7.62 | 16 |
"""mSTAR tile encoder implementation.
mSTAR (Wang et al., 2024; ``Innse/mSTAR``) is released as a ``ViT-L/16`` patch
encoder, not a slide aggregator: the published checkpoint is a per-tile feature
extractor and slide2vec handles WSI -> coordinates -> per-tile features itself.
We therefore register it as a **tile** enc... | clemsgrs/slide2vec | slide2vec/encoders/models/mstar.py | .py | 99bbfae154808a94 | 7.62 | 16 |
"""MUSK encoder implementation.
Requires the ``musk`` package:
pip install git+https://github.com/lilab-stanford/MUSK.git
"""
from typing import Callable
import torch
from torch import Tensor
from torchvision.transforms import v2
from timm.models import create_model
from slide2vec.encoders.base import (
Til... | clemsgrs/slide2vec | slide2vec/encoders/models/musk.py | .py | 826b86260557f095 | 7.62 | 16 |
"""Phikon and Phikon-v2 encoder implementations.
Both require the ``transformers`` package.
"""
from typing import Callable
import torch
from torch import Tensor
from transformers import AutoImageProcessor, AutoModel
from slide2vec.encoders.base import (
TileEncoder,
attentions_tuple_to_grids,
hf_eager_... | clemsgrs/slide2vec | slide2vec/encoders/models/phikon.py | .py | db13486f5ec77d63 | 7.62 | 16 |
"""PRISM2 slide encoder implementation."""
import torch
from transformers import AutoModel, AutoProcessor
from slide2vec.encoders.base import (
SlideEncoder,
preferred_default_device,
resolve_requested_output_variant,
)
from slide2vec.encoders.registry import register_encoder
PRISM2_MODEL_ID = "paige-ai/... | clemsgrs/slide2vec | slide2vec/encoders/models/prism2.py | .py | 3593480a490cf4a1 | 7.62 | 16 |
import argparse
import json
from pathlib import Path
from neo4j import GraphDatabase
import sys
try:
from src.utils import get_env_variable
except ModuleNotFoundError: # pragma: no cover - fallback for direct execution
from utils import get_env_variable
def _sort_schema(d: dict[str, dict[str, str]]) -> dict[... | nickzren/text-to-cypher | src/export_neo4j_schema.py | .py | 2ee9483b809d6e68 | 7.65 | 19 |
import logging
import os
from pathlib import Path
from dotenv import load_dotenv
logger = logging.getLogger(__name__)
load_dotenv()
def get_project_root() -> Path:
current_path = Path(__file__).resolve()
for parent in current_path.parents:
if (parent / ".env").exists():
return parent
... | nickzren/text-to-cypher | src/utils.py | .py | e225962349e62019 | 7.65 | 19 |
"""The client for handling DRM-protected content on www.passes.com."""
import asyncio
import logging
import os
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Optional
import aiohttp
import xmltodict
from async_lru import alru_cache
from pywidevine import PSSH, Cdm, Device, Ke... | Xewdy444/PassesDL | utils/passes/drm/client.py | .py | 01082e0eff8de1a7 | 7.64 | 18 |
"""Utility classes for the Passes DRM client."""
from enum import Enum
from pywidevine import PSSH
class SecurityLevel(Enum):
"""Content decryption module security levels."""
SW_SECURE_CRYPTO = "8fd9a7ea-73de-49bc-8b9e-ec1e73d325d3"
SW_SECURE_DECODE = "d597b3c2-7827-4047-9ee4-c10e49f7bc14"
HW_SECUR... | Xewdy444/PassesDL | utils/passes/drm/utils.py | .py | 428d5a9f0bd9809f | 7.64 | 18 |
"""Utility classes for the Passes client."""
from __future__ import annotations
import json
from datetime import datetime
from enum import Enum, auto
from http.client import responses
from typing import Annotated, Any, Dict, List, Optional
import annotated_types
from patchright.async_api import Response
from pydanti... | Xewdy444/PassesDL | utils/passes/utils.py | .py | c03d59a32902b0c7 | 7.64 | 18 |
"""Utility classes."""
from __future__ import annotations
import argparse
from datetime import datetime
from pathlib import Path
from typing import Any, List, Optional, Tuple, Type, Union
from pydantic import BaseModel, FilePath, HttpUrl, PositiveInt
from pydantic_settings import BaseSettings, TomlConfigSettingsSour... | Xewdy444/PassesDL | utils/utils.py | .py | 1a4602d39038e6d2 | 7.64 | 18 |
"""Common domain objects."""
from collections.abc import MutableMapping
from charms.data_platform_libs.v0.data_interfaces import Data
from ops import Application, Relation, Unit
class RelationState:
"""Relation state object."""
def __init__(
self, relation: Relation | None, data_interface: Data, co... | canonical/kyuubi-k8s-operator | src/common/relation/domain.py | .py | 1b53a1f5feb6361e | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""Common classes/functions for K8s implementations."""
import logging
import uuid
from abc import ABC
from collections.abc import Iterator
from contextlib import contextmanager
from ops import Container
from ops.pebb... | canonical/kyuubi-k8s-operator | src/common/workload/k8s.py | .py | 9b24d96cd20260eb | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Limited
# See LICENSE file for licensing details.
"""Kyuubi environment variables."""
from core.domain import SparkServiceAccountInfo, TLSInfo
from utils.logging import WithLogging
class KyuubiEnvironConfig(WithLogging):
"""Kyuubi Environment Variables."""
... | canonical/kyuubi-k8s-operator | src/config/env.py | .py | 2f8e1bc95aa328bd | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""Hive related configurations."""
from typing import Optional
from xml.etree import ElementTree
from constants import (
METASTORE_DATABASE_NAME,
)
from core.domain import DatabaseConnectionInfo
from utils.loggin... | canonical/kyuubi-k8s-operator | src/config/hive.py | .py | 28cf9dbf67b094d5 | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""Kyuubi workload configurations."""
from constants import AUTHENTICATION_TABLE_NAME
from core.config import CharmConfig
from core.domain import DatabaseConnectionInfo, LDAPInfo, TLSInfo, ZookeeperInfo
from utils.log... | canonical/kyuubi-k8s-operator | src/config/kyuubi.py | .py | 88458724c4c7b3e1 | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""Spark related configurations."""
from lightkube import Client
from constants import GPU_JOB_OCI_IMAGE, JOB_OCI_IMAGE, SPARK_DEFAULT_CATALOG_NAME
from core.config import CharmConfig
from core.domain import Database... | canonical/kyuubi-k8s-operator | src/config/spark.py | .py | dd5122a9f228cd71 | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.
"""Structured configuration for the Kyuubi charm."""
import logging
import re
from typing import Literal
from charms.data_platform_libs.v0.data_models import BaseConfigModel
from pydantic import Field, NonNegativeInt, P... | canonical/kyuubi-k8s-operator | src/core/config.py | .py | 59dfdb91b8842d42 | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""Charm Context definition and parsing logic."""
from ipaddress import IPv4Address, IPv6Address
from charms.data_platform_libs.v0.data_interfaces import (
DatabaseRequirerData,
DataPeerData,
DataPeerUnitD... | canonical/kyuubi-k8s-operator | src/core/context.py | .py | 6fe2554f9d290563 | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""Implementation and blue-print for Kyuubi workloads."""
from abc import abstractmethod
from pathlib import Path
from ops import Container
from common.workload import AbstractWorkload
class KyuubiPaths:
"""Obj... | canonical/kyuubi-k8s-operator | src/core/workload/__init__.py | .py | 4fc3d1ad3b3afddd | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""Module containing all business logic related to the workload."""
import re
import secrets
import string
import httpx
import ops.pebble
from ops.model import Container
from common.workload.k8s import K8sWorkload
fr... | canonical/kyuubi-k8s-operator | src/core/workload/kyuubi.py | .py | 28f6a87928eee7c1 | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Limited
# See LICENSE file for licensing details.
"""JDBC Authentication related event handlers."""
from __future__ import annotations
from typing import TYPE_CHECKING
from charms.data_platform_libs.v0.data_interfaces import (
DatabaseCreatedEvent,
DatabaseR... | canonical/kyuubi-k8s-operator | src/events/auth/jdbc.py | .py | 447d97ecaea64c43 | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Limited
# See LICENSE file for licensing details.
"""LDAP authentication event handlers for Kyuubi charm."""
from __future__ import annotations
from typing import TYPE_CHECKING
from charms.glauth_k8s.v0.ldap import (
LdapReadyEvent,
LdapUnavailableEvent,
)
... | canonical/kyuubi-k8s-operator | src/events/auth/ldap.py | .py | 878f67b59704228e | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2026 Canonical Ltd.
# See LICENSE file for licensing details.
"""Event handler for related applications on the `certificates` relation interface."""
from __future__ import annotations
from typing import TYPE_CHECKING, cast
from charms.certificate_transfer_interface.v0.certificate_... | canonical/kyuubi-k8s-operator | src/events/certificate_transfer.py | .py | 3a051393d4a71ddb | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""Integration Hub related event handlers."""
from __future__ import annotations
from typing import TYPE_CHECKING
from charms.spark_integration_hub_k8s.v0.spark_service_account import (
ServiceAccountGoneEvent,
... | canonical/kyuubi-k8s-operator | src/events/integration_hub.py | .py | 1e9f81be69a6ffaf | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""Kyuubi related event handlers."""
from __future__ import annotations
from typing import TYPE_CHECKING, cast
import ops
from cryptography import x509
from ops import SecretChangedEvent
from constants import (
... | canonical/kyuubi-k8s-operator | src/events/kyuubi.py | .py | cee1fb098865f3c8 | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""Metastore database related event handlers."""
from __future__ import annotations
from typing import TYPE_CHECKING
from charms.data_platform_libs.v0.data_interfaces import (
DatabaseCreatedEvent,
DatabaseRe... | canonical/kyuubi-k8s-operator | src/events/metastore.py | .py | 25cd1c2fd29e3e54 | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Limited
# See LICENSE file for licensing details.
"""Refresh related event handlers."""
from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import TYPE_CHECKING
import charm_refresh
if TYPE_CHECKING:
from charm import... | canonical/kyuubi-k8s-operator | src/events/refresh.py | .py | 033dd5aa40f167aa | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.
"""Event handler for related applications on the `certificates` relation interface."""
from __future__ import annotations
from typing import TYPE_CHECKING
from charms.tls_certificates_interface.v4.tls_certificates impor... | canonical/kyuubi-k8s-operator | src/events/tls.py | .py | fe4eb687f9d711ba | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""Zookeeper related event handlers."""
from __future__ import annotations
from typing import TYPE_CHECKING
from charms.data_platform_libs.v0.data_interfaces import DatabaseRequirerEventHandlers
from ops.charm import... | canonical/kyuubi-k8s-operator | src/events/zookeeper.py | .py | faa91775172ebd12 | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""Authentication manager."""
import secrets
import string
from constants import AUTHENTICATION_TABLE_NAME, DEFAULT_ADMIN_USERNAME
from core.domain import DatabaseConnectionInfo
from managers.database import Database... | canonical/kyuubi-k8s-operator | src/managers/auth/jdbc.py | .py | 97e3873a012a6e20 | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""Database connection manager."""
import psycopg2
from constants import (
POSTGRESQL_DEFAULT_DATABASE,
)
from core.domain import DatabaseConnectionInfo
from utils.logging import WithLogging
class DatabaseManag... | canonical/kyuubi-k8s-operator | src/managers/database.py | .py | e6642c8174f6fd86 | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Limited
# See LICENSE file for licensing details.
"""Hive metastore schema manager."""
import logging
import ops
from core.workload import KyuubiWorkloadBase
from utils.logging import WithLogging
logger = logging.getLogger(__name__)
class HiveMetastoreManager(Wi... | canonical/kyuubi-k8s-operator | src/managers/hive_metastore.py | .py | 55e31d24b6eb98c7 | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""Integration Hub manager."""
import re
from core.domain import SparkServiceAccountInfo
from utils.logging import WithLogging
class IntegrationHubManager(WithLogging):
"""Class that encapsulates various utilit... | canonical/kyuubi-k8s-operator | src/managers/integration_hub.py | .py | 074d37f7817452ff | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""K8s manager."""
from lightkube import Client
from lightkube.core.exceptions import ApiError
from lightkube.resources.core_v1 import Namespace, Node, ServiceAccount
from core.domain import SparkServiceAccountInfo
f... | canonical/kyuubi-k8s-operator | src/managers/k8s.py | .py | d9be524bc153eca7 | 7.42 | 6 |
#!/usr/bin/env python3
# Copyright 2024 Canonical Limited
# See LICENSE file for licensing details.
"""Kyuubi manager."""
from __future__ import annotations
from typing import TYPE_CHECKING
from config.env import KyuubiEnvironConfig
from config.hive import HiveConfig
from config.kyuubi import KyuubiConfig
from conf... | canonical/kyuubi-k8s-operator | src/managers/kyuubi.py | .py | e6d95b9cc51eb783 | 7.42 | 6 |
"""Utility module containing logic of creation and deletion of managed Kyuubi K8s service."""
import enum
import functools
import json
import socket
from dataclasses import dataclass
import lightkube
from lightkube.core.exceptions import ApiError
from lightkube.models.core_v1 import (
LoadBalancerIngress,
Loa... | canonical/kyuubi-k8s-operator | src/managers/service.py | .py | c9afd53a65f35995 | 7.42 | 6 |
"""Configurator class for Tesla Smart Charger."""
import json
from pathlib import Path
from tesla_smart_charger import constants
class ChargerConfig:
"""
Configurator class for Tesla Smart Charger.
Attributes
----------
config_file (str): Path to the configuration file.
config (dict... | codesquadnest/tesla-smart-charger | tesla_smart_charger/charger_config.py | .py | 85b89c803f00279c | 7.42 | 6 |
"""
Database Controller.
This controller is responsible for interacting with the database to store and
retrieve data.
The controller is implemented as an abstract class that defines the interface
for the controller. This allows for different implementations of the controller
to be used.
"""
from abc import ABC, abst... | codesquadnest/tesla-smart-charger | tesla_smart_charger/controllers/db_controller.py | .py | ef279923faef0876 | 7.42 | 6 |
"""
Energy Monitor Controller.
This controller is responsible for monitoring the energy usage of the house
to determine if the power limit can be increased or decreased.
The controller is implemented as an abstract class that defines the interface
for the controller. This allows for different implementations of the c... | codesquadnest/tesla-smart-charger | tesla_smart_charger/controllers/em_controller.py | .py | a9028b7b8f6116e7 | 7.42 | 6 |
"""
Shelly EM Controller Implementation.
This controller monitors and manages the power consumption of the Shelly EM device.
"""
import requests
from retrying import retry
from tesla_smart_charger import constants
from tesla_smart_charger.controllers.em_controller import EnergyMonitorController
class ShellyEMContr... | codesquadnest/tesla-smart-charger | tesla_smart_charger/controllers/shelly_em_controller.py | .py | 7a994659c34abb1b | 7.42 | 6 |
"""Energy-monitor polling cron — triggers overload handling when needed."""
import threading
from retrying import retry
from tesla_smart_charger import constants, logger
from tesla_smart_charger.app_config import AppConfig
from tesla_smart_charger.controllers import em_controller as _em_controller
from tesla_smart_c... | codesquadnest/tesla-smart-charger | tesla_smart_charger/cron/em_cron.py | .py | 9a38fa20f11dd7d7 | 7.42 | 6 |
"""Token refresh cron — refreshes OAuth tokens for every configured vehicle."""
import threading
from tesla_smart_charger import logger
from tesla_smart_charger.app_config import AppConfig
from tesla_smart_charger.tesla_api import TeslaAPI
tsc_logger = logger.get_logger()
REFRESH_OK_INTERVAL = 10800 # 3 hours
REFR... | codesquadnest/tesla-smart-charger | tesla_smart_charger/cron/token_cron.py | .py | 7be3b1c365a528aa | 7.42 | 6 |
"""
Vehicle command endpoints — /api/v1/vehicles/{id}/...
Commands that change vehicle state invalidate the telemetry cache so the
dashboard refetches instead of showing pre-command values for up to the
cache TTL.
Every route here has physical-world effects, so the whole router sits behind
``security.require_auth`` —... | codesquadnest/tesla-smart-charger | tesla_smart_charger/routes/command_routes.py | .py | ee9acf45db92feb1 | 7.42 | 6 |
"""GET /api/v1/config and POST /api/v1/config — system configuration."""
import ipaddress
from typing import Any
import requests
from fastapi import APIRouter, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from tesla_smart_charger import logger
from tesla_smart_charger.app... | codesquadnest/tesla-smart-charger | tesla_smart_charger/routes/config_routes.py | .py | 3b084b1a9c42169d | 7.42 | 6 |
"""GET /api/v1/history — paginated, filterable overload event history."""
import sqlite3
from typing import Annotated
from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import JSONResponse
from tesla_smart_charger import constants, logger
from tesla_smart_charger.controllers import db_control... | codesquadnest/tesla-smart-charger | tesla_smart_charger/routes/history_routes.py | .py | 9187b309f6cff8be | 7.42 | 6 |
"""GET /api/v1/status — overall system health and live state."""
from collections.abc import Callable
from fastapi import APIRouter
from fastapi.responses import JSONResponse
from tesla_smart_charger import logger, security, telemetry_cache
from tesla_smart_charger.app_config import AppConfig
from tesla_smart_charge... | codesquadnest/tesla-smart-charger | tesla_smart_charger/routes/status_routes.py | .py | 123d99ca190c197f | 7.42 | 6 |
"""Vehicle CRUD endpoints — /api/v1/vehicles."""
from typing import Any
from fastapi import APIRouter, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from tesla_smart_charger import logger, telemetry_cache
from tesla_smart_charger.app_config import AppConfig
from tesla_smart_... | codesquadnest/tesla-smart-charger | tesla_smart_charger/routes/vehicle_routes.py | .py | d6609b54aa324cb9 | 7.42 | 6 |
"""
Password hashing and the HTTP Basic Auth guard for vehicle command endpoints.
Commands with physical-world effects (waking a car, changing its charge limit)
are gated behind ``require_auth``. The guard **fails closed**: when Basic Auth
has not been configured the commands are refused outright rather than left ope... | codesquadnest/tesla-smart-charger | tesla_smart_charger/security.py | .py | fb576bcaef9153c5 | 7.42 | 6 |
"""
Per-vehicle telemetry cache.
Shared by the status route (which reads it) and the command routes (which
invalidate it after a command changes vehicle state). Reads never block on
the network: cached data is served immediately — fresh or stale — while a
background thread refreshes expired entries.
"""
import threa... | codesquadnest/tesla-smart-charger | tesla_smart_charger/telemetry_cache.py | .py | fb50f281b9d410e0 | 7.42 | 6 |
"""
Tests for the main convert function and type mapping.
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from syno2bw import convert, SECURE_NOTE_TYPE, LOGIN_TYPE, CARD_TYPE
class TestConvert:
"""Tests for convert function."""
def test_convert_login... | HyperNylium/SynologyC2Password-to-Bitwarden | tests/test_converter.py | .py | aaf50b22b9024422 | 7.14 | 18 |
"""
Integration tests for the full conversion pipeline.
"""
import json
import os
import sys
import tempfile
import contextlib
import io
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from syno2bw import main, convert, save
class TestIntegration:
"""End-to-end tests for the conv... | HyperNylium/SynologyC2Password-to-Bitwarden | tests/test_integration.py | .py | e753ddd1a39f9007 | 8.14 | 18 |
"""
Tests for CSV parsing functions.
"""
import os
import pytest
import sys
# Add parent directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from syno2bw import read_csv, validate_input_file, clean_path
class TestCleanPath:
"""Tests for clean_path functi... | HyperNylium/SynologyC2Password-to-Bitwarden | tests/test_parser.py | .py | 1aded60f408694d7 | 8.14 | 18 |
"""Benchmark items."""
import os
import httpx2 as httpx
import pytest
host = os.environ.get("HOST", "0.0.0.0")
port = os.environ.get("PORT", "8081")
tiles = [
{"tile": "0/0/0", "zoom": 0, "assets": 15}, # 15 Assets
{"tile": "1/1/1", "zoom": 1, "assets": 6}, # 6 Assets
{"tile": "2/2/1", "zoom": 2, "ass... | developmentseed/titiler-stacapi | benchmark/benchmarks.py | .py | 235fbee09d35961b | 7.6 | 15 |
"""titiler.stacapi tests configuration."""
import os
from typing import Any
import pytest
import rasterio
from fastapi.testclient import TestClient
from rasterio.io import MemoryFile
DATA_DIR = os.path.join(os.path.dirname(__file__), "fixtures")
def parse_img(content: bytes) -> dict[Any, Any]:
"""Read tile ima... | developmentseed/titiler-stacapi | tests/conftest.py | .py | 26331791bf46614e | 8.1 | 15 |
"""Test Advanced PySTAC client."""
import json
import os
from unittest.mock import MagicMock, patch
import pytest
from titiler.stacapi.pystac import Client
catalog_json = os.path.join(os.path.dirname(__file__), "fixtures", "catalog.json")
@pytest.fixture
def mock_stac_io():
"""STAC IO mock"""
return Magic... | developmentseed/titiler-stacapi | tests/test_advanced_pystac_client.py | .py | f30b0a490bbd17e9 | 8.1 | 15 |
"""test titiler-stacapi app."""
def test_landing(app):
"""Test / endpoint."""
name = "TiTiler-STACAPI"
response = app.get("/")
assert response.status_code == 200
assert response.headers["content-type"] == "application/json"
body = response.json()
assert body["title"] == name
assert bo... | developmentseed/titiler-stacapi | tests/test_app.py | .py | 6a77aac324ad25a6 | 7.1 | 15 |
"""Test titiler.stacapi WMS endpoints."""
import json
import os
from unittest.mock import patch
import pystac
import rasterio
from owslib.wms import WebMapService
from .conftest import parse_img
item_json = os.path.join(
os.path.dirname(__file__), "fixtures", "46_033111301201_1040010082988200.json"
)
catalog_js... | developmentseed/titiler-stacapi | tests/test_wms.py | .py | d43d6d3991d7cf26 | 7.1 | 15 |
"""titiler-stacapi custom Mosaic Backend and Custom STACReader."""
import json
from threading import Lock
from typing import Any, cast
import attr
import pystac
from cachetools import TTLCache, cached
from cachetools.keys import hashkey
from geojson_pydantic import Point, Polygon
from geojson_pydantic.geometries impo... | developmentseed/titiler-stacapi | titiler/stacapi/backend.py | .py | 9ed0100b08f9f3a0 | 7.6 | 15 |
"""titiler.stacapi ogcapi pydantic models.
This might be moved in an external python module
see: https://github.com/developmentseed/ogcapi-pydantic
"""
from typing import TypedDict, Union
from geojson_pydantic import Feature, Point
from pydantic import BaseModel
from titiler.core.utils import TMSLimits
class Pr... | developmentseed/titiler-stacapi | titiler/stacapi/models.py | .py | c26038a721bc3297 | 7.6 | 15 |
"""
This module provides an advanced client for interacting with STAC (SpatioTemporal Asset Catalog) APIs.
The `Client` class extends the basic functionality of the `pystac.Client` to include
methods for retrieving and aggregating data from STAC collections.
"""
import warnings
from typing import Dict, List, Optional... | developmentseed/titiler-stacapi | titiler/stacapi/pystac/advanced_client.py | .py | 2656cd8debcadb30 | 7.6 | 15 |
"""Custom STAC reader."""
import sys
from typing import Any, Sequence, Type
import attr
import pystac
import rasterio
from morecantile import TileMatrixSet
from rio_tiler.constants import WEB_MERCATOR_TMS, WGS84_CRS
from rio_tiler.errors import InvalidAssetName, MissingAssets
from rio_tiler.io import BaseReader, Mult... | developmentseed/titiler-stacapi | titiler/stacapi/reader.py | .py | 655d3d13978335b6 | 7.6 | 15 |
#!/usr/bin/env python3
"""
Git Commit Analyzer
Analyzes commit quality, format compliance, and suggests improvements
"""
import argparse
import re
import subprocess
import sys
from typing import Dict, List, Tuple
# Color constants
RED = "\033[0;31m"
GREEN = "\033[0;32m"
YELLOW = "\033[1;33m"
BLUE = "\... | woonstadrotterdam/woningwaardering | .cursor/skills/managing-commits/scripts/commit-analyzer.py | .py | 21b3291ba0deb995 | 7.48 | 8 |
#!/usr/bin/env python3
"""
Conventional Commits Helper
Generates and validates conventional commit messages
"""
import argparse
import subprocess
import sys
VALID_TYPES = [
"feat",
"fix",
"docs",
"style",
"refactor",
"perf",
"test",
"chore",
"ci",
"build",
... | woonstadrotterdam/woningwaardering | .cursor/skills/managing-commits/scripts/conventional-commits.py | .py | bd272405afd1a753 | 7.48 | 8 |
#!/usr/bin/env python3
"""
Intelligent File Grouping for Commits
Groups modified files by scope, type, and logical relationships
"""
import argparse
import json
import re
import subprocess
import sys
from collections import defaultdict
from pathlib import Path
from typing import Dict, List
# Color cons... | woonstadrotterdam/woningwaardering | .cursor/skills/managing-commits/scripts/group-files.py | .py | f31b20b3f6b7ee57 | 7.48 | 8 |
# -*- coding: utf-8 -*-
# Copyright 2025 Red Hat, Inc.
# Apache License 2.0 (see LICENSE or http://www.apache.org/licenses/LICENSE-2.0)
from typing import Dict, Tuple, Optional
from ansible_collections.kubernetes.core.plugins.module_utils.k8s import service
# Copied from
# https://github.com/ansible-collections/kub... | kubevirt/kubevirt.core | plugins/module_utils/diff.py | .py | a6accce84383c31e | 7.66 | 20 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2023 Red Hat, Inc.
# Based on the kubernetes.core.k8s_info module
# Apache License 2.0 (see LICENSE or http://www.apache.org/licenses/LICENSE-2.0)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = """
module: ku... | kubevirt/kubevirt.core | plugins/modules/kubevirt_vm_info.py | .py | 1ff6ffe375ff3095 | 7.66 | 20 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2023 Red Hat, Inc.
# Based on the kubernetes.core.k8s_info module
# Apache License 2.0 (see LICENSE or http://www.apache.org/licenses/LICENSE-2.0)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = """
module: ku... | kubevirt/kubevirt.core | plugins/modules/kubevirt_vmi_info.py | .py | b0759195eb8a642a | 7.66 | 20 |
# -*- coding: utf-8 -*-
# Copyright 2024 Red Hat, Inc.
# Apache License 2.0 (see LICENSE or http://www.apache.org/licenses/LICENSE-2.0)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from json import dumps
import pytest
from kubernetes.dynamic.exceptions import DynamicApiErro... | kubevirt/kubevirt.core | tests/unit/plugins/inventory/test_kubevirt_format_dynamic_api_exc.py | .py | de995d8bc4dce1fb | 7.16 | 20 |
# -*- coding: utf-8 -*-
# Copyright 2024 Red Hat, Inc.
# Apache License 2.0 (see LICENSE or http://www.apache.org/licenses/LICENSE-2.0)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import pytest
from ansible_collections.kubevirt.core.plugins.inventory.kubevirt import (
I... | kubevirt/kubevirt.core | tests/unit/plugins/inventory/test_kubevirt_populate_inventory_from_namespace.py | .py | 535cb7004a99323a | 7.16 | 20 |
# -*- coding: utf-8 -*-
# Copyright 2024 Red Hat, Inc.
# Apache License 2.0 (see LICENSE or http://www.apache.org/licenses/LICENSE-2.0)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import pytest
@pytest.mark.parametrize(
"file_name,expected",
[
("inventory.k... | kubevirt/kubevirt.core | tests/unit/plugins/inventory/test_kubevirt_verify_file.py | .py | f69eb995fae11a99 | 7.16 | 20 |
# -*- coding: utf-8 -*-
# Copyright 2024 Red Hat, Inc.
# Apache License 2.0 (see LICENSE or http://www.apache.org/licenses/LICENSE-2.0)
# This file allows to run modules in unit tests.
# It was taken from:
# https://docs.ansible.com/ansible/latest/dev_guide/testing_units_modules.html#module-argument-processing
from _... | kubevirt/kubevirt.core | tests/unit/utils/ansible_module_mock.py | .py | 447e60681a452f62 | 8.16 | 20 |
from __future__ import annotations
import dataclasses
from enum import Enum
import re
import textwrap
import typing
import parsley
@dataclasses.dataclass
class Term:
pass
class FilterOn(Enum):
name = "name"
summary = "summary"
name_or_summary = "name_or_summary"
depends = "depends"
depends... | simple-repository/simple-repository-browser | simple_repository_browser/_search.py | .py | 46c50f993814a92e | 7.63 | 17 |
import dataclasses
import logging
from packaging.utils import InvalidWheelFilename, parse_wheel_filename
from packaging.version import InvalidVersion, Version
from simple_repository import model
logger = logging.getLogger(__name__)
@dataclasses.dataclass(frozen=True)
class CompatibilityMatrixModel:
matrix: dict... | simple-repository/simple-repository-browser | simple_repository_browser/compatibility_matrix.py | .py | 0d2b9736f8e7f84b | 7.63 | 17 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.