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
""" Obsidian Python Bridge Script: CSV -> Markdown Table (data-wrangling flex) POC: Python's batteries make tabular data trivial. Paste or select raw CSV (commas, semicolons, tabs — auto-sniffed), run the script, get a properly aligned Markdown table with pipes escaped, inserted right where your selection was. Priori...
mathe00/my-obsidian-python-scripts
csv-to-markdown-table.py
.py
908bc22c03f5629f
7.52
10
""" Obsidian Python Bridge Script: Concise English Word Definition Select an English word in the active note, run the script, and get its definition from the free dictionaryapi.dev API inside an Obsidian notification. Kept intentionally small (it is the repo's "minimal example"), but now follows the recommended bridg...
mathe00/my-obsidian-python-scripts
define_word_en_concise.py
.py
4f2087cd11d9479e
7.52
10
""" Obsidian Python Bridge Script: Executable Code Blocks (Jupyter-lite POC) Turn the active note into a lightweight notebook: any fenced Python block tagged with ``#run`` is executed, its stdout captured and injected right after the fence as an Obsidian callout: ```python #run print(2 ** 10) ``` <!--...
mathe00/my-obsidian-python-scripts
executable-code-blocks.py
.py
f543a0b4c8e00a4e
7.52
10
""" Obsidian Python Bridge Script: ISBN -> Book Card (API mashup POC) Select an ISBN (10 or 13 digits, hyphens tolerated), run the script and get a full book card inserted in place of the selection: - checksum **validation implemented by hand** (the classic weighted-sum algorithms — pure Python elegance), - metadat...
mathe00/my-obsidian-python-scripts
isbn-book-card.py
.py
a78d29ff18c3f17b
7.52
10
""" Obsidian Python Bridge Script: PDF -> Markdown Note (optional-dep showcase) Finds PDF links in the active note (``[[doc.pdf]]`` or ``[doc](doc.pdf)``), extracts their text with **pypdf** and creates a sibling markdown note: Doc.pdf → Doc (Extracted).md with one section per page plus a light heading heurist...
mathe00/my-obsidian-python-scripts
pdf-to-note.py
.py
479d0a780c9ac8b7
7.52
10
""" Obsidian Python Bridge Script: QR Code Generator (optional-dep showcase) Turn selected text (or a modal prompt) into a QR code PNG dropped into your attachments folder and embedded into the note — `qrcode` is an OPTIONAL dependency: without it you get a friendly install hint instead of a crash. Also shows off the...
mathe00/my-obsidian-python-scripts
qr-code-generator.py
.py
46fcb57cf390084e
7.52
10
""" Obsidian Python Bridge Script: Auto Linker (V2.4 - Robust Matching) This script automatically creates links in the currently active note. It searches for text matching the titles (case-insensitive, accent-insensitive) of other notes in the vault and converts them into one of three types based on settings: - Wikili...
mathe00/my-obsidian-python-scripts
script-auto-linker.py
.py
8ec9a312511eba18
7.52
10
"""Integration tests running the scripts against the REAL current OPB library. These tests locate the local Obsidian Python Bridge dev clone, point ``PYTHONPATH`` at it and execute the scripts in subprocesses: * **Event guard** — with ``OBSIDIAN_EVENT_NAME`` set, every script must exit 0 immediately (before any cli...
mathe00/my-obsidian-python-scripts
tests/test_bridge_integration.py
.py
2dd91ebdc9894519
7.02
10
import logging from utils.django import django_setup_full from .copy_utils import dump_and_restore_db logger = logging.getLogger(__name__) EXPOSURE_TABLE_MAPPINGS = { "exposure_sample_displayedacteur": "qfdmo_displayedacteur", "exposure_sample_displayedpropositionservice": "qfdmo_displayedpropositionservic...
incubateur-ademe/quefairedemesobjets
data-platform/dags/acteurs/tasks/business_logic/copy_displayed_data_from_warehouse_task.py
.py
d6d7933400c1a44f
7.56
12
import logging import subprocess from typing import Optional import psycopg2 logger = logging.getLogger(__name__) def drop_tables(dsn: str, tables: list[str]) -> None: """Drop tables in the destination DB before restoring.""" conn = psycopg2.connect(dsn) conn.autocommit = True with conn.cursor() as ...
incubateur-ademe/quefairedemesobjets
data-platform/dags/acteurs/tasks/business_logic/copy_utils.py
.py
84de71ab6b8e16d2
7.56
12
"""Configuration model for the clone DAG""" import re from pathlib import Path from typing import Literal from clone.tasks.business_logic.fix_corrupted_utf8 import validate_sed_substitutions from pydantic import AnyUrl, BaseModel, computed_field, model_validator DIR_CURRENT = Path(__file__).resolve() DIR_SQL_CREATIO...
incubateur-ademe/quefairedemesobjets
data-platform/dags/clone/config/models.py
.py
de5d21c54b0d8232
7.56
12
"""Creates the actual tables replicating AE in our DB""" import logging import tempfile from pathlib import Path from clone.tasks.business_logic.fix_corrupted_utf8 import fix_corrupted_utf8_file from pydantic import AnyUrl from shared.config.airflow import TMP_FOLDER from utils import logging_utils as log from utils....
incubateur-ademe/quefairedemesobjets
data-platform/dags/clone/tasks/business_logic/clone_table_create.py
.py
68122d89e85274cd
7.56
12
#!/usr/bin/env python3 """ General CLI utilities for catocli This module contains general-purpose utility functions used across the catocli package, including settings loading and configuration management. """ import os import json # Import for resource handling try: # Python 3.9+ from importlib.resources i...
catonetworks/cato-cli
catocli/Utils/cliutils.py
.py
a6d1fb463d1866cd
7.59
14
#!/usr/bin/env python3 """ App Stats Timeseries Formatter for Cato CLI This module provides functions to format appStatsTimeSeries API responses into JSON and CSV formats, with special handling for timeseries data and unit conversions. """ import csv import io import json import re from datetime import datetime from ...
catonetworks/cato-cli
catocli/Utils/formatter_app_stats_timeseries.py
.py
1309ea986196b004
7.59
14
#!/usr/bin/env python3 """ Events TimeSeries Formatter for Cato CLI This module provides functions to format eventsTimeSeries API responses into JSON and CSV formats, with special handling for granularity multiplication when sum aggregation is used on appropriate fields. Key functionality: - Handles granularity multi...
catonetworks/cato-cli
catocli/Utils/formatter_events_timeseries.py
.py
25c04dd58814f462
7.59
14
#!/usr/bin/env python3 """ Licensing Formatter for Cato CLI Formats licensing API responses into JSON and CSV formats """ import csv import io import json from datetime import datetime from typing import Dict, List, Any, Optional def format_licensing(response_data: Dict[str, Any], output_format: str = 'json') -> st...
catonetworks/cato-cli
catocli/Utils/formatter_licensing.py
.py
a55beaa0a80521ba
7.59
14
#!/usr/bin/env python3 """ PoP Locations Formatter for Cato CLI Formats popLocations API responses into JSON and CSV formats """ import csv import io import json from typing import Dict, List, Any def format_pop_locations(response_data: Dict[str, Any], output_format: str = 'json') -> str: """ Convert popLoc...
catonetworks/cato-cli
catocli/Utils/formatter_pop_locations.py
.py
628c717593ef666a
7.59
14
#!/usr/bin/env python3 """ Socket Port Metrics Timeseries Formatter for Cato CLI This module provides functions to format socketPortMetricsTimeSeries API responses into JSON and CSV formats, with special handling for timeseries data and unit conversions. """ import csv import io import json from datetime import datet...
catonetworks/cato-cli
catocli/Utils/formatter_socket_port_metrics_timeseries.py
.py
97514893ed20b223
7.59
14
#!/usr/bin/env python3 """ Version checking utility for Cato CLI Checks for newer versions available on GitHub releases and PyPI """ import json import urllib.request import urllib.error import ssl import os import time from .. import __version__ # Cache settings CACHE_FILE = os.path.expanduser("~/.catocli_version_ca...
catonetworks/cato-cli
catocli/Utils/version_checker.py
.py
b42b6c0a7ef1c4c2
7.59
14
#!/usr/bin/env python3 """ Configure command parser for Cato CLI Handles profile creation, listing, and switching """ import argparse from .configure import ( configure_profile, list_profiles, set_profile, delete_profile, show_profile ) from ...Utils.cliutils import load_private_settings from ...Ut...
catonetworks/cato-cli
catocli/parsers/configure/__init__.py
.py
9a9d7841e880b5ea
7.59
14
#!/usr/bin/env python3 """ Configure command implementation for Cato CLI Implements profile creation, listing, switching, and management """ import getpass import sys import json from graphql_client import Configuration from graphql_client.api_client import ApiException from graphql_client.api.call_api import ApiClien...
catonetworks/cato-cli
catocli/parsers/configure/configure.py
.py
1874ed32e7675017
7.59
14
from ...customParserApiClient import createRequest, get_help from ..eventsFeedEnhanced import enhanced_events_feed_handler def query_eventsFeed_parse(query_subparsers): query_eventsFeed_parser = query_subparsers.add_parser('eventsFeed', help='Enhanced eventsFeed() query operation with advanced feature...
catonetworks/cato-cli
catocli/parsers/custom/query_eventsFeed/__init__.py
.py
65fc5cae84fb0113
7.59
14
#!/usr/bin/env python3 """ Private commands parser for custom GraphQL payloads Dynamically loads commands from ~/.cato/settings.json """ import argparse from ..customParserApiClient import createPrivateRequest, get_private_help from ...Utils.cliutils import load_private_settings class PrivateCommandHelpFormatter(arg...
catonetworks/cato-cli
catocli/parsers/custom_private/__init__.py
.py
332e0e58ba9827ac
7.59
14
import time import socket import boto3 import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) ELB = boto3.client('elbv2') def handler(event: dict, context: dict) -> None: ''' Args: event (dict): The event object containing the RDS proxy endpoint, the NLB target...
opensupplyhub/open-supply-hub
deployment/terraform/database-private-link-provider/lambda-nlb-registrar/register_nlb_targets.py
.py
638d27ea879e2e2e
7.66
20
"""Stage a contributor upload as ``{list_id}.xlsx`` for ContriBot.""" from __future__ import annotations import shutil from pathlib import Path from typing import Union import pandas as pd PathLike = Union[str, Path] class ContribotWorkbook: """Convert or copy an uploaded facility list into a ContriBot workbo...
opensupplyhub/open-supply-hub
src/contribot/lib/contribot_workbook.py
.py
a9094575d959bd32
7.66
20
"""Google Drive client for uploading ContriBot validation reports.""" from __future__ import annotations import json import logging import mimetypes import os from typing import Any, Optional import boto3 from google.oauth2 import service_account from googleapiclient.discovery import build from googleapiclient.http ...
opensupplyhub/open-supply-hub
src/contribot/lib/google_drive.py
.py
797a9c635b049b6f
7.66
20
"""DynamoDB persistence for ContriBot facility-list processing state.""" from __future__ import annotations import logging import os from datetime import datetime, timezone from decimal import Decimal from typing import Any, Optional import boto3 from botocore.exceptions import ClientError logger = logging.getLogge...
opensupplyhub/open-supply-hub
src/contribot/lib/lists_repository.py
.py
f64d20a26c409212
7.66
20
"""Monday.com GraphQL client for ContriBot approval-queue items.""" from __future__ import annotations import json import os from typing import Any, Optional from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen import boto3 # Title aliases on the Contributor List Approval Queue (...
opensupplyhub/open-supply-hub
src/contribot/lib/monday.py
.py
b68076a070b36383
7.66
20
"""S3 helpers for downloading facility-list uploads.""" from __future__ import annotations import os from typing import Any, Optional import boto3 class S3Storage: """Download objects from the facility-list files bucket.""" def __init__( self, bucket_name: Optional[str] = None, s3_...
opensupplyhub/open-supply-hub
src/contribot/lib/s3_storage.py
.py
cb2173889871974f
7.66
20
"""Slack incoming-webhook client for ContriBot moderator notifications.""" from __future__ import annotations import json import os from typing import Any, Optional from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen import boto3 class SlackWebhook: """Post messages to a Sl...
opensupplyhub/open-supply-hub
src/contribot/lib/slack_webhook.py
.py
c695c017fbed529d
7.66
20
#!/usr/bin/env python3 """ Debug CSV Processing Script This script investigates the "Unconsumed column names" error by examining how the CSV data is being processed and identifying potential issues. """ import pandas as pd import logging import re # Setup logging logging.basicConfig(level=logging.INFO) logger = logg...
tracebloc/data-ingestors
debug_csv_processing.py
.py
d209be78051494b4
7.45
7
"""Pytest config for the end-to-end ingestion suite. These tests run the REAL ``tracebloc-ingest`` engine against the bundled ``templates/`` datasets, into a REAL MySQL, with an in-process mock backend (``CLIENT_ENV=local`` pins the APIClient at ``http://localhost:8000``). They are skipped unless a MySQL is reachable ...
tracebloc/data-ingestors
e2e/conftest.py
.py
a040630060cfd5b8
7.95
7
"""End-to-end DATABASE behaviour against a real MySQL. The unit suite (``tests/test_database.py``) mocks the SQLAlchemy engine, so no SQL is ever executed despite 100% line coverage: ``CREATE TABLE``, the ``ON DUPLICATE KEY UPDATE`` upsert, the bulk-insert -> per-row fallback, type mapping and charset round-tripping a...
tracebloc/data-ingestors
e2e/test_database_e2e.py
.py
436713239d70a4ae
7.95
7
"""backend#1706 — the ingestor→trainer IMAGE-lookup contract, end to end. Sibling of ``test_semseg_client_contract_e2e.py``, which pins the same kind of boundary for ``mask_id``. Here the subject is the image itself, and the bug it guards against already shipped: tracebloc-engine#615, where keypoint and semantic-segme...
tracebloc/data-ingestors
e2e/test_image_lookup_contract_e2e.py
.py
5cd7bf0f13bb6510
7.95
7
"""End-to-end ingestion equivalence: every modality's bundled template ingests. For each modality we build an ``ingest.yaml`` matched to the bundled ``templates/`` dataset, run the real engine into MySQL, and assert it succeeds with rows. Modalities with known engine/template gaps are ``xfail``'d against their trackin...
tracebloc/data-ingestors
e2e/test_ingest_e2e.py
.py
3fa442be3192cfe1
7.95
7
"""backend#816 — the semseg ingestor→client mask_id contract, end-to-end. Ingests a real ``semantic_segmentation`` dataset into a real MySQL (the e2e harness DB) and asserts the ingestor produces EXACTLY what the training client resolves masks from — checked against the CLIENT'S OWN derivation rule. This is the bounda...
tracebloc/data-ingestors
e2e/test_semseg_client_contract_e2e.py
.py
5faee499799d474d
7.95
7
from setuptools import setup, find_packages import re # read the contents of your README file from pathlib import Path this_directory = Path(__file__).parent long_description = (this_directory / "Readme.md").read_text() def _read_version(): """Single-source the version from tracebloc_ingestor/__init__.py. ...
tracebloc/data-ingestors
setup.py
.py
baa0adbd74592599
7.45
7
"""Shared fixtures for the test suite. Validators and ingestors snapshot ``config = Config()`` at import time but read ``os.environ`` lazily on each property access, so tests set env vars via ``monkeypatch.setenv`` and the module-level config picks them up. The ``clean_env`` fixture strips the env vars these tests tou...
tracebloc/data-ingestors
tests/conftest.py
.py
8b22c6a5550286f6
7.95
7
"""Congruence tests across the per-category dispatch sites. A category accepted by the schema enum flows through four dispatch sites, each of which silently no-ops on a category it doesn't know: 1. ``conventions._data_format_for`` (raises — the only loud one) 2. ``utils.validators_mapping.map_validator...
tracebloc/data-ingestors
tests/test_category_congruence.py
.py
bb1a6d7670dc5a22
7.95
7
"""Cross-layer coercion consistency — the validator gate and the ingest paths must reach the SAME verdict on the same value (#236, #237). This is the regression net for the whole bug class: the three layers (DataValidator gate, CSVIngestor cast, JSONIngestor per-record check) used to decide independently what a type p...
tracebloc/data-ingestors
tests/test_coercion_consistency.py
.py
e1f0e5b0751411d6
7.95
7
"""Cross-repo column-identifier contract (ISSUE #382). This pins the canonical column-name grammar that BOTH the ingestor (here) and the trainer (``tracebloc-engine`` core/utils/database.py) must agree on. The trainer mirrors ``tracebloc_ingestor.identifiers`` verbatim and has its own copy of this table plus a pin tes...
tracebloc/data-ingestors
tests/test_column_identifier_contract.py
.py
9e8889ad7a2f7815
7.95
7
"""Tests for the shared column-name resolution rule (#340). ``resolve_column`` is the single source of truth for matching a declared column name to the actual header, used by BOTH the validators (``BaseValidator._match_column`` delegates here) and the ingest read path (``BaseIngestor._resolve_label_column``). The two ...
tracebloc/data-ingestors
tests/test_columns.py
.py
2dd52503d6a4f628
7.95
7
"""Lock in ``Config``'s lazy-property contract. The bug this protects against (see #97): validators import ``config = Config()`` at module top-level. When ``Config`` was a ``@dataclass`` with ``os.getenv`` defaults, those fields were frozen at class-definition time, long before the declarative entrypoint set ``SRC_PAT...
tracebloc/data-ingestors
tests/test_config_lazy.py
.py
aa391b5d1e595d5f
7.95
7
"""Tests for ContrastivePairsValidator — the structural check that each ``embeddings`` ``.txt`` is a tab-separated pair (``anchor\\tpositive``) or triplet (``anchor\\tpositive\\tnegative``). FileTypeValidator only checks the extension and TextContentValidator only checks UTF-8 decodability — neither sees this structure...
tracebloc/data-ingestors
tests/test_contrastive_pairs_validator.py
.py
b81f3825a92a947d
7.95
7
from typing import Any, Literal from aidial_client._compatibility.pydantic_v1 import ( BaseModel, Extra, Field, root_validator, ) class JsonRpcError(BaseModel): code: int message: str data: Any | None = None class Config: extra = Extra.allow class JsonRpcRequest(BaseModel):...
epam/ai-dial-client-python
aidial_client/_internal_types/_json_rpc.py
.py
edfa92664340006e
7.45
7
""" Just copy of alias generators from pydantic V2: https://github.com/pydantic/pydantic/blob/c772b43edb952c5fe54bb28da5124b10d5470caf/pydantic/alias_generators.py So we can use library with pydantic < 2.0 version """ import re def to_pascal(snake: str) -> str: """Convert a snake_case string to PascalCase. ...
epam/ai-dial-client-python
aidial_client/_utils/_alias.py
.py
c821ae8ffd0fc0df
7.45
7
from pathlib import PurePosixPath from typing import Literal, cast, get_args from urllib.parse import quote, unquote, urljoin, urlparse, urlsplit from aidial_client._compatibility.pydantic_v1 import BaseModel from aidial_client._constants import API_PREFIX from aidial_client._exception import InvalidDialURLError, NotD...
epam/ai-dial-client-python
aidial_client/helpers/storage_resource.py
.py
99f8578be27f8488
7.45
7
from collections.abc import Sequence from http import HTTPStatus from typing import Any import httpx from aidial_client._compatibility.pydantic_v1 import ValidationError from aidial_client._exception import ( DialException, InvalidRequestError, ParsingDataError, ) from aidial_client._http_client._sse impo...
epam/ai-dial-client-python
aidial_client/resources/client_channel.py
.py
3e3c6b639d58ec1d
7.45
7
from typing import Optional from dataclasses import dataclass import globber import requests import os BUILDKITE_API_ACCESS_TOKEN = os.environ["BUILDKITE_API_ACCESS_TOKEN"] HEADERS = {'Authorization': f'Bearer {BUILDKITE_API_ACCESS_TOKEN}'} @dataclass class ListArtifactsRequestURLBuilder: org: str pipeline...
elastic/oblt-actions
buildkite/download-artifact/download_artifacts.py
.py
bb7c2e1ffd93c158
7.42
6
"""Regression test that check if security statements run without error""" import os import sys import json import subprocess from pathlib import Path from typing import Dict, Union, List, cast FILE_PATH = Path(__file__) STATEMENTS_PATH = FILE_PATH.parent / "statements" GITHUB_SUMMARY = os.environ.get('GITHUB_STEP_SU...
testofthings/toolsaf
regression_tests/run_statements.py
.py
00a2bbdacfc5dca9
7.92
6
"""Test setup documentation reader""" import pathlib from toolsaf.common.address import DNSName, EntityTag, IPAddress from toolsaf.adapters.batch_import import BatchImporter from tests.test_model import Setup class Setup_1(Setup): """Setup for tests here""" def __init__(self): super().__init__() ...
testofthings/toolsaf
tests/adapters/test_setup_reader.py
.py
873b155a33dbc1ea
7.92
6
"""Test broadcast matching""" from toolsaf.builder_backend import SystemBackend from toolsaf.common.address import IPAddress from toolsaf.common.basics import Status from toolsaf.common.traffic import IPFlow from toolsaf.core.matcher import SystemMatcher from toolsaf.main import ARP, UDP def test_broadcast_matching_w...
testofthings/toolsaf
tests/matcher/test_matching_problems.py
.py
5e02136d41f4b898
7.92
6
from toolsaf.common.basics import ExternalActivity, Status from toolsaf.builder_backend import ConnectionBackend, SystemBackend from toolsaf.core.model import Service from toolsaf.core.services import NameEvent import test_model from toolsaf.common.address import DNSName, EndpointAddress, EntityTag, HWAddress, Protocol...
testofthings/toolsaf
tests/test_inspector.py
.py
25196ba51e7235b8
7.92
6
from toolsaf.common.address import DNSName, EntityTag, HWAddress, IPAddress from toolsaf.common.basics import ExternalActivity, Status from toolsaf.main import SSH from toolsaf.core.services import NameEvent from toolsaf.common.traffic import NO_EVIDENCE, IPFlow from toolsaf.common.verdict import Verdict from tests.tes...
testofthings/toolsaf
tests/test_model_new.py
.py
d494ed70ac492ac3
7.92
6
"""Zino API authentication mechanisms. This only implements the authentication scheme of the legacy server protocol. """ import io import secrets from hashlib import sha1 from pathlib import Path from typing import Optional, Union def authenticate( user: str, response: str, challenge: Optional[str] = None, secr...
Uninett/zino
src/zino/api/auth.py
.py
d633f2f211d92fe8
7.45
7
"""Notification channel implementation for Zino 2.0. Notification channels are currently part of the legacy API from the Tcl-based Zino 1.0. They are a simple text-based, line-oriented protocol. Clients are not expected to send any data to a notification channel, only receive data from the server. """ import asynci...
Uninett/zino
src/zino/api/notify.py
.py
7a58ce9743a70630
7.45
7
import logging from asyncio import AbstractEventLoop from typing import Optional from zino.api.legacy import Zino1ServerProtocol from zino.api.notify import Zino1NotificationProtocol from zino.config.models import Configuration, PollDevice from zino.state import ZinoState from zino.statemodels import Event _logger = ...
Uninett/zino
src/zino/api/server.py
.py
d767af374eebd0eb
7.45
7
import re from difflib import get_close_matches from typing import Optional try: from tomllib import TOMLDecodeError, load except ImportError: from tomli import TOMLDecodeError, load from pydantic import BaseModel, ValidationError from .models import Configuration class InvalidConfigurationError(Exception)...
Uninett/zino
src/zino/config/__init__.py
.py
530ae817d55282b5
7.45
7
"""Zino configuration models""" from ipaddress import IPv4Address, IPv6Address from os import R_OK, access from os.path import isfile from typing import Any, Literal, Optional, Union from pydantic import BaseModel, ConfigDict from pydantic.functional_validators import AfterValidator from typing_extensions import Anno...
Uninett/zino
src/zino/config/models.py
.py
c8bd9942d5cb29e9
7.45
7
"""Functionality to parse and validate the legacy polldevs.cf config file""" from typing import Iterator, TextIO, Tuple from pydantic import ValidationError from zino.config.models import PollDevice def read_polldevs(filename: str) -> Tuple[dict[str, PollDevice], dict[str, str]]: """ Reads and parses the l...
Uninett/zino
src/zino/config/polldevs.py
.py
9fa2d23a717d4ebe
7.45
7
"""Debugging utilities for analyzing errors and stack traces in Zino.""" import inspect import logging from typing import Any, Dict, List, Optional, Type _log = logging.getLogger(__name__) def debug_log_timeout_error(device_name: str, task_class: Type, logger: Optional[logging.Logger] = None) -> None: """Debug ...
Uninett/zino
src/zino/debug.py
.py
4566bfd5835a6e80
7.45
7
import logging from datetime import timedelta from typing import Dict, NamedTuple, Optional, Protocol, Type, Union from pydantic.main import BaseModel from zino.statemodels import ( AlarmEvent, BFDEvent, BGPEvent, Event, EventState, EventType, PortStateEvent, ReachabilityEvent, Sub...
Uninett/zino
src/zino/events.py
.py
54881a543eca4798
7.45
7
"""Implements data models and algorithms for tracking interface flapping. Flapping is normally only tracked/updated based on incoming link traps. """ from __future__ import annotations import logging from datetime import datetime, timedelta from typing import TYPE_CHECKING, List, Optional, Tuple from pydantic impor...
Uninett/zino
src/zino/flaps.py
.py
c3e03b744566d25e
7.45
7
"""Track running jobs in APScheduler for monitoring purposes.""" import asyncio import logging import signal from datetime import datetime from typing import Optional from apscheduler.events import ( EVENT_JOB_ERROR, EVENT_JOB_EXECUTED, EVENT_JOB_MAX_INSTANCES, EVENT_JOB_MISSED, EVENT_JOB_SUBMITTE...
Uninett/zino
src/zino/job_tracker.py
.py
b22cef458381312b
7.45
7
"""OID manipulation""" SEPARATOR = "." SEPARATOR_B = b"." class OID(tuple): """Object IDentifier represented in tuple form. Example usages: >>> ifXTable = OID('.1.3.6.1.2.1.31.1.1') >>> ifXTable OID('.1.3.6.1.2.1.31.1.1') >>> ifName = ifXTable + '1.1' >>> ifName OID('.1....
Uninett/zino
src/zino/oid.py
.py
62c669ab74450635
7.45
7
import logging from datetime import datetime, timedelta, timezone from typing import TYPE_CHECKING, Dict, Optional, Protocol, Union from pydantic.main import BaseModel from zino.statemodels import ( DeviceMaintenance, Event, EventState, MatchType, PlannedMaintenance, PortStateMaintenance, ) fr...
Uninett/zino
src/zino/planned_maintenance.py
.py
756f65549cd19d4b
7.45
7
#!/usr/bin/env python3 """Test SNMP polling using the PySNMP high-level API directly""" import argparse import asyncio import logging from pysnmp.hlapi.asyncio import ( CommunityData, ContextData, ObjectIdentity, ObjectType, SnmpEngine, UdpTransportTarget, bulkCmd, isEndOfMib, ) _log ...
Uninett/zino
src/zino/polltest.py
.py
1af26c3e9ca454c9
7.95
7
import asyncio import logging import operator import pathlib from datetime import datetime, timedelta from typing import Sequence, Set, Tuple from apscheduler.executors.asyncio import AsyncIOExecutor from apscheduler.jobstores.base import JobLookupError from apscheduler.schedulers.asyncio import AsyncIOScheduler from...
Uninett/zino
src/zino/scheduler.py
.py
35c112a61c7f5bc5
7.45
7
"""Zino SNMP back-ends""" import importlib import logging import os.path from types import ModuleType from typing import TYPE_CHECKING from weakref import WeakValueDictionary from zino.config.models import PollDevice from zino.snmp.base import SNMPBackendNotLoaded if TYPE_CHECKING: from zino.snmp.pysnmp_backend ...
Uninett/zino
src/zino/snmp/__init__.py
.py
b3aac075fc951d63
7.45
7
"""SNMP agent for Zino that responds to uptime queries. This module implements an SNMP agent that listens on a configurable port and responds to queries for ZINO-MIB::zinoUpTime, which is used by clients for failover detection. The agent is built on PySNMP, since the netsnmpy library does not yet provide support for ...
Uninett/zino
src/zino/snmp/agent.py
.py
d060a50555070eb2
7.45
7
import os import re import shutil from fetcher.scroller import Scroller from fetcher.source import DocumentsSource, SourceType, get_documents_sources from utils.logging import get_logger from utils.utils import download_repo logger = get_logger(__name__) def _empty_dir(path: str) -> None: """Remove everything ...
kyma-project/kyma-companion
doc_indexer/src/fetcher/fetcher.py
.py
f808acb18015125f
7.42
6
import fnmatch import os import shutil from fetcher.source import DocumentsSource from utils.logging import get_logger logger = get_logger(__name__) class Scroller: """Scroller class to scroll through the files and save the required files.""" dir_path: str output_dir: str source: DocumentsSource ...
kyma-project/kyma-companion
doc_indexer/src/fetcher/scroller.py
.py
129e19591e959f54
7.42
6
import json from enum import StrEnum from pydantic import BaseModel from utils.logging import get_logger logger = get_logger(__name__) class SourceType(StrEnum): """Enum for the documents source type.""" GITHUB = "Github" class DocumentsSource(BaseModel): """Model for the documents source.""" n...
kyma-project/kyma-companion
doc_indexer/src/fetcher/source.py
.py
25be5a070510dbde
7.42
6
import json import re import time import uuid from collections.abc import Generator import tiktoken from hdbcli import dbapi from indexing.constants import HEADER1, HEADER2, HEADER3 from langchain_core.documents import Document from langchain_core.embeddings import Embeddings from langchain_hana import HanaDB from lan...
kyma-project/kyma-companion
doc_indexer/src/indexing/adaptive_indexer.py
.py
10f1666f4e7290ab
7.42
6
import time from typing import Protocol from hdbcli import dbapi from indexing.constants import HEADER1 from langchain_community.document_loaders import DirectoryLoader from langchain_community.document_loaders.text import TextLoader from langchain_core.documents import Document from langchain_core.embeddings import E...
kyma-project/kyma-companion
doc_indexer/src/indexing/indexer.py
.py
5520c36b7d6b7b3c
7.42
6
from hdbcli import dbapi from utils.logging import get_logger logger = get_logger(__name__) _ERR_SQL_INV_TABLE = 259 # HANA error code for invalid/missing table name def create_hana_connection(url: str, port: int, user: str, password: str) -> dbapi.Connection | None: """Create a connection to the Hana Cloud D...
kyma-project/kyma-companion
doc_indexer/src/utils/hana.py
.py
53558447742ab3da
7.42
6
import time from collections.abc import Callable from typing import cast from gen_ai_hub.proxy.core.proxy_clients import get_proxy_client from gen_ai_hub.proxy.langchain import OpenAIEmbeddings from langchain_core.embeddings import Embeddings from utils.logging import get_logger from utils.settings import get_embeddi...
kyma-project/kyma-companion
doc_indexer/src/utils/models.py
.py
295e25e6a717fb05
7.42
6
import json import logging import os import sys from pathlib import Path from decouple import config from utils.model_config import ModelConfig project_root = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../") MODELS_CONFIGS_KEY = "MODELS_CONFIGS" def load_env_from_json() -> None: """Load the co...
kyma-project/kyma-companion
doc_indexer/src/utils/settings.py
.py
701d273f46f86575
7.42
6
import os import re import shutil import tarfile import tempfile import urllib.error import urllib.request from urllib.parse import urlparse from utils.logging import get_logger logger = get_logger(__name__) # Only GitHub is supported as a document source (see fetcher.source.SourceType). # codeload serves a gzipped ...
kyma-project/kyma-companion
doc_indexer/src/utils/utils.py
.py
98b94e7741972e81
7.42
6
import os import uuid import pytest from utils.hana import create_hana_connection from utils.settings import ( DATABASE_PASSWORD, DATABASE_PORT, DATABASE_URL, DATABASE_USER, EMBEDDING_MODEL_NAME, get_embedding_model_config, ) from utils.utils import sanitize_table_name @pytest.fixture(scope=...
kyma-project/kyma-companion
doc_indexer/tests/integration/conftest.py
.py
c79db254232663a5
7.92
6
import os.path import random import shutil import string from pathlib import Path import pytest from fetcher.fetcher import DocumentsFetcher current_dir = Path(__file__).parent def get_random_string(length) -> str: return "".join(random.choice(string.ascii_lowercase) for i in range(length)) @pytest.fixture de...
kyma-project/kyma-companion
doc_indexer/tests/integration/fetcher/test_fetcher.py
.py
6eaea3dbb661f8bf
7.92
6
"""Integration tests for main.py entry points. These tests exercise the exact code paths used in production to catch wiring bugs (e.g. passing deployment_id instead of model name). """ import logging from pathlib import Path import pytest from langchain_core.embeddings import Embeddings from utils.models import cre...
kyma-project/kyma-companion
doc_indexer/tests/integration/test_main.py
.py
e2b040e5b92f437a
7.92
6
"""Integration tests for embedding model functionality. These tests make real API calls to the embedding service. """ import math import pytest from langchain_core.embeddings import Embeddings from utils.models import create_embedding_factory, openai_embedding_creator from utils.settings import EMBEDDING_MODEL_NAME...
kyma-project/kyma-companion
doc_indexer/tests/integration/utils/test_embeddings.py
.py
a4830f9f5ec367fd
7.92
6
import os import pytest from fetcher.source import get_documents_sources pytestmark = pytest.mark.unit @pytest.fixture def docs_sources_file_path(root_tests_path): """Return the path to the documents sources file.""" return os.path.join(root_tests_path, "..", "docs_sources.json") def test_get_documents_so...
kyma-project/kyma-companion
doc_indexer/tests/unit/fetcher/test_source.py
.py
da365626a188ffe9
7.92
6
from typing import Any from unittest.mock import Mock, call, patch import pytest from indexing.indexer import MarkdownIndexer, create_chunks from langchain_core.documents import Document pytestmark = pytest.mark.unit SINGLE_BATCH_DOCS = [Document(page_content="# My Header 1\nContent")] TABLE_NAME = "test_table" BACK...
kyma-project/kyma-companion
doc_indexer/tests/unit/indexing/test_indexer.py
.py
f4c34bbf8cab653f
7.92
6
import io import os import tarfile from unittest.mock import patch import pytest from utils.utils import _parse_github_repo, download_repo pytestmark = pytest.mark.unit @pytest.mark.parametrize( "given_url, expected", [ ("https://github.com/kyma-project/eventing-manager.git", ("kyma-project", "even...
kyma-project/kyma-companion
doc_indexer/tests/unit/utils/test_utils.py
.py
c34d518a4e7575bf
7.92
6
#!/usr/bin/env python3 """ Encrypt K8s headers via ECDH + AES-256-GCM and print the 4 encrypted values. Usage: python3 scripts/python/encrypt_k8s_headers.py Required environment variables: TEST_CLUSTER_URL TEST_CLUSTER_CERTIFICATE_AUTHORITY_DATA TEST_CLUSTER_TOKEN COMPANION_API_URL COMPANION_T...
kyma-project/kyma-companion
scripts/python/encrypt_k8s_headers.py
.py
4e70674e89da6f57
7.42
6
from math import ceil from typing import Any, Protocol from langchain_core.documents import Document from langchain_core.embeddings import Embeddings from langchain_core.prompts import PromptTemplate from langchain_core.runnables.config import RunnableConfig from agents.common.prompts import CHUNK_SUMMARIZER_PROMPT f...
kyma-project/kyma-companion
src/agents/common/chunk_summarizer.py
.py
f12c2260de6a4331
7.42
6
"""Summarize older conversation history to keep prompt token usage bounded.""" from typing import Protocol from langchain_core.embeddings import Embeddings from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage from langchain_core.prompts import PromptTemplate from langchain_core.runn...
kyma-project/kyma-companion
src/agents/common/conversation_summarizer.py
.py
51eaf1fd4b451d43
7.42
6
from pydantic import BaseModel from agents.common.constants import CLUSTER from services.k8s_resource_discovery import K8sResourceDiscovery, ResourceKind class Message(BaseModel): """ Message data model. Because of Pydantic version conflict between AICore and LangGraph, we keep this model as a duplicate ...
kyma-project/kyma-companion
src/agents/common/data.py
.py
528c12b99dba107d
7.42
6
""" Tests for grid-square getters in getters/load_geodata.py. Genuine missing grid-square files on S3 (due to true absence of data e.g. sea-only squares with no road layer) raise pyogrio DataSourceError and must be skipped, while any other read failure must still raise. """ import geopandas as gpd import pytest from ...
nestauk/asf_heat_pump_suitability
asf_heat_pump_suitability/getters/tests/test_load_geodata.py
.py
386879127528d09f
7.1
15
def assign_bool_domestic_status(b_id: str, non_domestic: list) -> bool: """ Returns False for specified non-domestic codes. Args: b_id (str): test building ID, e.g. 'B01', or 'b03_cluster1' where 'b03' is the ID prefix and 'cluster1' is the descriptor non_domestic (list): list of test build...
nestauk/asf_heat_pump_suitability
asf_heat_pump_suitability/pipeline/cluster/tests/utils.py
.py
726ee22c01911fe6
7.1
15
""" Functions to generate features for random forest binary classifier model which classifies buildings into blocks of flats or not. Features are generated per building from building footprint and UPRN geodata. """ import polars as pl import geopandas as gpd def generate_df_features( buildings_gdf: gpd.GeoDataFr...
nestauk/asf_heat_pump_suitability
asf_heat_pump_suitability/pipeline/model/block_of_flats/feature_engineering.py
.py
2db289a360a00680
7.6
15
""" Functions to train and apply a random forest binary classifier model. Contains script to train a random forest classifier to identify buildings as blocks of flats or not, given features derived from building footprint and UPRN geospatial information. To run the script: asf_heat_pump_suitability/pipeline/model/blo...
nestauk/asf_heat_pump_suitability
asf_heat_pump_suitability/pipeline/model/block_of_flats/train_model.py
.py
c528f8d4a7308dfe
7.6
15
""" Script to compute contextual information for clusters including: - Proportion of attachment types, tenure types, EPC ratings of properties within clusters - Median outdoor space of properties within clusters - Whether any properties within clusters are in HN zones, city centres, protected areas, off-gas, within 150...
nestauk/asf_heat_pump_suitability
asf_heat_pump_suitability/pipeline/run/compute_contextual_features.py
.py
0e47b7cae5b57f81
7.6
15
""" Script to optimise input datasets for speed and memory gains during pipeline runs. Converts heavy file types into more efficient parquet files and, where possible, partitions geospatial data by grid square. To run (all grid squares): python asf_heat_pump_suitability/pipeline/run/optimise_inputs.py To run for ...
nestauk/asf_heat_pump_suitability
asf_heat_pump_suitability/pipeline/run/optimise_inputs.py
.py
2013902f9e755637
7.6
15
import geopandas as gpd import shapely from pygeotile import tile import pyproj import warnings from convertbng.util import convert_bng import numpy as np from asf_heat_pump_suitability.getters import load_data from asf_heat_pump_suitability.utils import geo_utils def transform_df_uk_dataset_links() -> gpd.GeoDataFra...
nestauk/asf_heat_pump_suitability
asf_heat_pump_suitability/pipeline/transform/building_footprint.py
.py
4dd91a25a4c77530
7.6
15
""" Functions to label UPRNs within city centre areas. """ import geopandas as gpd import polars as pl from asf_heat_pump_suitability import config CITY_CENTRE_TYPES = [ # TODO: confirm types with scaling "Hyper concentrated urbanity", "Concentrated urbanity", "Metropolitan urbanity", "Regional urba...
nestauk/asf_heat_pump_suitability
asf_heat_pump_suitability/pipeline/transform/city_centres.py
.py
1ca0d4e5957fa1c7
7.6
15
""" This can be run as a standalone script to calculate grid capacity per LSOA/DataZone in England, Scotland, and Wales. Outputs will be saved to `outputs/reports/grid_capacity.csv` unless otherwise specified. """ import re from typing import Any import logging import argparse import numpy as np import pandas as pd i...
nestauk/asf_heat_pump_suitability
asf_heat_pump_suitability/pipeline/transform/grid_capacity.py
.py
d907fa7ce71fa16b
7.6
15
""" Functions to label UPRNs within official existing, potential or planned heat network zones. """ import geopandas as gpd import polars as pl from asf_heat_pump_suitability import config def extend_df_heat_network_zone_bool( uprns_df: pl.DataFrame, uprns_gdf: gpd.GeoDataFrame, hn_zone_gdf: gpd.GeoDataFrame ) ...
nestauk/asf_heat_pump_suitability
asf_heat_pump_suitability/pipeline/transform/heat_network_zones.py
.py
6c3c0f80653f9166
7.6
15