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
""" API support for interacting with external drivers. """ from __future__ import annotations from importlib import import_module from importlib.util import module_from_spec, spec_from_file_location from inspect import getfullargspec from pathlib import Path from traceback import format_exc from typing import TYPE_CH...
ufs-community/uwtools
src/uwtools/api/execute.py
.py
8086dc33be55b7d9
7.63
17
""" API access to ``uwtools`` Rocoto support. """ from __future__ import annotations from typing import TYPE_CHECKING from uwtools.rocoto import DEFAULT_ITERATION_RATE from uwtools.rocoto import iterate as _iterate from uwtools.rocoto import realize as _realize from uwtools.rocoto import validate_xml_file as _valida...
ufs-community/uwtools
src/uwtools/api/rocoto.py
.py
a82cb135dac02f8e
7.63
17
""" API access to ``uwtools`` templating logic. """ from __future__ import annotations import os from pathlib import Path from typing import TYPE_CHECKING from uwtools.config.atparse_to_jinja2 import convert as _convert_atparse_to_jinja2 from uwtools.config.jinja2 import render as _render from uwtools.exceptions imp...
ufs-community/uwtools
src/uwtools/api/template.py
.py
26556656a7c372ca
7.63
17
""" Convert atparse templates to Jinja2 templates. """ from __future__ import annotations import re from typing import TYPE_CHECKING from uwtools.logging import log from uwtools.utils.file import readable, writable if TYPE_CHECKING: from pathlib import Path def convert( input_file: Path | None = None, out...
ufs-community/uwtools
src/uwtools/config/atparse_to_jinja2.py
.py
67cce9634c9ef95e
7.63
17
from __future__ import annotations import difflib import re from abc import ABC, abstractmethod from collections import UserDict from copy import deepcopy from functools import reduce from io import StringIO from pathlib import Path from typing import Any, cast import yaml from f90nml import Namelist # type: ignore[...
ufs-community/uwtools
src/uwtools/config/formats/base.py
.py
ea79f09d330b6ba6
7.63
17
"""Shared fixtures for owserver tests.""" import json import os import platform import subprocess import sys import time import urllib.request from pathlib import Path import pytest PROJECT_DIR = Path(__file__).resolve().parent.parent DEV_DIR = PROJECT_DIR / "dev" TEMPLATE_PATH = PROJECT_DIR / "rootfs" / "etc" / "ow...
lrybak/hassio-owserver
tests/conftest.py
.py
ed3006bc3f25dd45
8.14
18
"""Integration tests — port of dev/test.sh.""" import re import subprocess import pytest pytestmark = pytest.mark.integration OWSERVER = "localhost:4304" @pytest.fixture(scope="module") def devices(compose_project): """Get the device list from owdir (shared across tests in this module).""" from conftest i...
lrybak/hassio-owserver
tests/test_integration.py
.py
432fa89955d6feb1
8.14
18
#!/usr/bin/env python3 # Copyright (c) 2022 Ghiggi Gionata # goes_api is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # goes_api is...
ghiggi/goes_api
goes_api/abi_area.py
.py
3de1429f7195fef9
7.5
9
#!/usr/bin/env python3 # Copyright (c) 2022 Ghiggi Gionata # goes_api is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # goes_api is...
ghiggi/goes_api
goes_api/abi_utils.py
.py
35a98c6f4c03f5a8
7.5
9
#!/usr/bin/env python3 # Copyright (c) 2022 Ghiggi Gionata # goes_api is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # goes_api is...
ghiggi/goes_api
goes_api/checks.py
.py
14c56deaf5f1f959
7.5
9
#!/usr/bin/env python3 # Copyright (c) 2022 Ghiggi Gionata # goes_api is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # goes_api is...
ghiggi/goes_api
goes_api/explore.py
.py
cb36eac45539c939
7.5
9
#!/usr/bin/env python3 # Copyright (c) 2022 Ghiggi Gionata # goes_api is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # goes_api is...
ghiggi/goes_api
goes_api/filter.py
.py
8d50b763408ad896
7.5
9
#!/usr/bin/env python3 # Copyright (c) 2022 Ghiggi Gionata # goes_api is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # goes_api is...
ghiggi/goes_api
goes_api/io.py
.py
5fc0f058e47f7d7d
7.5
9
#!/usr/bin/env python3 """ Created on Thu Mar 16 17:44:17 2023 @author: ghiggi """ import datetime from time import perf_counter def print_elapsed_time(fn): def inner(*args, **kwargs): start_time = perf_counter() results = fn(*args, **kwargs) end_time = perf_counter() execution_ti...
ghiggi/goes_api
goes_api/utils/timing.py
.py
bc52be7cedce17f2
7.5
9
"""Contains the implementation of the Date class.""" from __future__ import annotations from enum import IntEnum DEFAULT_DAY = 1 DEFAULT_MONTH = 1 DEFAULT_YEAR = 1900 DAYS_IN_FEBRUARY = 28 DAYS_IN_OTHER_MONTHS = 30 MAX_DAYS_IN_MONTH = 31 class Months(IntEnum): """Enum for months.""" JANUARY = 1 FEBRUA...
Diapolo10/5G00EV17-3001_unit-testing
src/unit_testing/date.py
.py
c288ae7dc5775104
7.92
6
"""Unit tests for the date.Date class.""" from collections.abc import Generator import pytest from unit_testing.date import ( DEFAULT_DAY, DEFAULT_MONTH, DEFAULT_YEAR, Date, Months, week_later, ) def test_date_default_attributes(default_date: Date) -> None: """Tests the default state of...
Diapolo10/5G00EV17-3001_unit-testing
tests/test_date.py
.py
a0f05f22f24cc30c
7.92
6
# marimo source for the "Exporting a bayesflow model to ONNX for HSSM" tutorial. # # Regenerate the rendered docs notebook (with outputs) after editing: # uv run marimo export ipynb notebooks/exporting_bayesflow_to_onnx.py \ # -o docs/tutorials/exporting_bayesflow_to_onnx.ipynb --include-outputs # # Edit interact...
lnccbrown/LANfactory
notebooks/exporting_bayesflow_to_onnx.py
.py
ba16b78ce4cbccef
7.62
16
# marimo source for the "Exporting an sbi model to ONNX for HSSM" tutorial. # # Regenerate the rendered docs notebook (with outputs) after editing: # uv run marimo export ipynb notebooks/exporting_sbi_to_onnx.py \ # -o docs/tutorials/exporting_sbi_to_onnx.ipynb --include-outputs # # Edit interactively with: uv r...
lnccbrown/LANfactory
notebooks/exporting_sbi_to_onnx.py
.py
4f0662f26f93938d
7.62
16
# import argparse import logging from pathlib import Path import pickle import yaml import numpy as np import lanfactory logger = logging.getLogger(__name__) # def non_negative_int(value): # """Convert string value to non-negative integer. # Args: # value: String value to convert to integer. # ...
lnccbrown/LANfactory
src/lanfactory/cli/utils.py
.py
c1784a9d7664d274
7.62
16
"""Model card utilities for HuggingFace Hub. This module reads user-provided model_card.yaml files and generates HuggingFace-compatible README.md files with proper frontmatter. """ import logging import pickle from dataclasses import dataclass, field from pathlib import Path from typing import Any import yaml from ...
lnccbrown/LANfactory
src/lanfactory/hf/model_card.py
.py
9bc1755dd1070e12
7.62
16
"""Pure computation: RT grids, LAN/KDE likelihoods, and manifold data.""" from __future__ import annotations import numpy as np import pandas as pd from numpy.typing import ArrayLike, NDArray from ssms.basic_simulators.simulator import simulator from ssms.support_utils.kde_class import LogKDE from .config import Gri...
lnccbrown/LANfactory
src/lanfactory/network_inspectors/compute.py
.py
b75835669127acfe
8.12
16
"""Config objects: model metadata and plotting/grid defaults.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from typing import Any import numpy as np from numpy.typing import NDArray from ssms.config import ModelConfigBuilder @dataclass class ModelSpe...
lnccbrown/LANfactory
src/lanfactory/network_inspectors/config.py
.py
e247db0f19e852a5
8.12
16
"""Network loaders: build LAN predictors from the LANfactory torch backend.""" from __future__ import annotations from collections.abc import Callable import os from os import PathLike from typing import Any import warnings import numpy as np from numpy.typing import NDArray LoadTorchMLPInfer: Any try: from lan...
lnccbrown/LANfactory
src/lanfactory/network_inspectors/loaders.py
.py
7917ddf51da826fa
7.12
16
"""Export jaxtrain networks to ONNX. Can be run as a script. Closes the gap that made jaxtrain a dead end for HSSM: the jax trainer saves flax parameter bytes (``*_train_state.jax``) which nothing downstream could convert — ``transform-onnx`` only reads torch state dicts, and HSSM consumes ONNX exclusively. The expor...
lnccbrown/LANfactory
src/lanfactory/onnx/jax_export.py
.py
ce6e4d3efe9a5c75
7.62
16
"""Export trained sbi estimators to ONNX for HSSM consumption. The single public entry point is :func:`transform_sbi_to_onnx`, which wraps a trained sbi density or ratio estimator and writes a single-trial ONNX graph that HSSM's ``loglik_kind="approx_differentiable"`` path can load via ``jaxonnxruntime``. This module...
lnccbrown/LANfactory
src/lanfactory/onnx/sbi.py
.py
26965866659e0d23
7.62
16
"""This module contains the function to transform Torch/Jax models to ONNX format. Can be run as a script. """ import pickle import torch import typer from lanfactory.trainers.torch_mlp import TorchMLP def transform_to_onnx( network_config_file: str, state_dict_file: str, input_shape: int, output_o...
lnccbrown/LANfactory
src/lanfactory/onnx/transform_onnx.py
.py
27f0114332624fdf
7.62
16
"""Utilities for MLflow tracking and lineage in LANfactory.""" import json import logging from pathlib import Path logger = logging.getLogger(__name__) def get_files_from_data_generation_experiment( experiment_id: str, tracking_uri: str = "sqlite:///mlflow.db" ) -> dict: """Get all files generated across al...
lnccbrown/LANfactory
src/lanfactory/utils/mlflow_utils.py
.py
d9e149d0b7ed814b
7.62
16
"""Shared helpers for the ONNX export tests.""" import onnx def max_int64_abs(onnx_model: onnx.ModelProto) -> int: """Largest absolute value stored in any int64 tensor in the graph (0 if none).""" tensors = list(onnx_model.graph.initializer) for node in onnx_model.graph.node: for attr in node.att...
lnccbrown/LANfactory
tests/_onnx_utils.py
.py
ab190bbacdaace34
7.12
16
import subprocess from pathlib import Path # AF-TODO: Add test for callable without config, # but needs to be marked as slow and skipped in CI. def test_jax_train_cli_smoke(tmp_path): """Smoke test: actually runs the CLI with real data.""" # Path to the training data directory __dir__ = Path(__file__).par...
lnccbrown/LANfactory
tests/cli/test_cli_entry_points.py
.py
9613207c0a52de25
7.12
16
"""CLI smoke tests for upload-hf and download-hf commands.""" import os import re import subprocess import yaml _ANSI_RE = re.compile(r"\x1b\[[\d;]*m") _WIDE_ENV = {**os.environ, "COLUMNS": "200"} def _strip_ansi(text: str) -> str: return _ANSI_RE.sub("", text) class TestUploadHfCliHelp: """Tests for upl...
lnccbrown/LANfactory
tests/cli/test_hf_cli.py
.py
8468892d088dc2bf
7.12
16
import logging import multiprocessing import os import random import time import uuid from copy import deepcopy import jax import lanfactory import numpy as np import pytest import ssms import torch from .constants import ( TEST_GENERATOR_CONSTANTS, TEST_NETWORK_CONSTANTS_CPN, TEST_NETWORK_CONSTANTS_LAN, ...
lnccbrown/LANfactory
tests/conftest.py
.py
77e591805ece25cb
8.12
16
"""Test configuration constants.""" from dataclasses import dataclass, field @dataclass class ModelFolderConstantsJAX: """Model folder constants.""" LAN_MODEL_FOLDER: str = "tests/test_data/jax_models/lan" CPN_MODEL_FOLDER: str = "tests/test_data/jax_models/cpn" OPN_MODEL_FOLDER: str = "tests/test_d...
lnccbrown/LANfactory
tests/constants.py
.py
0bdd2c53e4e4477b
7.12
16
"""Tests for download.py module.""" from unittest.mock import patch import pytest from lanfactory.hf.download import ( DEFAULT_REPO_ID, download_model, ) try: import huggingface_hub # noqa: F401 HAS_HF = True except ImportError: HAS_HF = False requires_hf = pytest.mark.skipif(not HAS_HF, reas...
lnccbrown/LANfactory
tests/hf/test_download.py
.py
6699916c8e611d4b
7.12
16
"""Tests for model_card.py module.""" import pickle import pytest import yaml from lanfactory.hf import DEFAULT_LICENSE from lanfactory.hf.model_card import ( ModelCardConfig, generate_readme, load_model_card_yaml, write_readme, ) class TestModelCardConfig: """Tests for ModelCardConfig dataclas...
lnccbrown/LANfactory
tests/hf/test_model_card.py
.py
a97315bef8882d68
7.12
16
"""Tests for upload.py module.""" from unittest.mock import MagicMock, patch import pytest import yaml from lanfactory.hf.upload import ( DEFAULT_INCLUDE_PATTERNS, DEFAULT_REPO_ID, _collect_files, upload_model, ) try: import huggingface_hub # noqa: F401 HAS_HF = True except ImportError: ...
lnccbrown/LANfactory
tests/hf/test_upload.py
.py
57c705c41d800ae2
7.12
16
"""Tests for the executable single-trial ONNX contract.""" import numpy as np import onnx import pytest from onnx import TensorProto, helper from lanfactory.onnx import assert_single_trial_contract def make_onnx(path, input_dims): width = input_dims[-1] if isinstance(input_dims[-1], int) else 6 # MatMul dro...
lnccbrown/LANfactory
tests/onnx/test_contract.py
.py
1337ed97d106240d
8.12
16
"""Tests for the jax -> ONNX exporter (feat/jax-onnx-export). The parity test is the load-bearing one: it guards the ecosystem's single-trial ONNX contract against silent changes in jax2onnx (0.x, pinned but moving) and in our own wrapper. """ import pickle from pathlib import Path import lanfactory import numpy as ...
lnccbrown/LANfactory
tests/onnx/test_jax_export.py
.py
36b0a774fdf6018d
8.12
16
"""End-to-end pipeline: bayesflow training → ONNX export → HSSM MCMC. Mirrors ``tests/test_sbi_hssm_integration.py`` so the bayesflow path gets the same cross-repo coverage as the sbi path. 1. Train a tiny bayesflow ``ContinuousApproximator`` (NLE) on synthetic DDM data via ssm-simulators. 2. Export via ``lanfacto...
lnccbrown/LANfactory
tests/test_bayesflow_hssm_integration.py
.py
96bdfb9fc3bd09b0
8.12
16
"""Verify ``transform_bayesflow_to_onnx`` for the NLE (ContinuousApproximator) path: tiny train, export, three-way numerical agreement, gradient agreement. Mirrors ``tests/test_sbi_nle_export.py`` so the bayesflow exporter inherits the same coverage shape as the sbi exporter. The fixture bakes in the v1 constraints (p...
lnccbrown/LANfactory
tests/test_bayesflow_nle_export.py
.py
b1a2e1e1287fef31
8.12
16
"""Verify ``transform_bayesflow_to_onnx`` for the NRE (RatioApproximator) path. NRE convention (opposite of NLE): inference_variables=θ, inference_conditions=x. The classifier logit IS log p(x|θ) - log p(x); HSSM only cares about the θ-dependent part, so the constant log p(x) is irrelevant. No Jacobian correction is n...
lnccbrown/LANfactory
tests/test_bayesflow_nre_export.py
.py
1ebda76081381bd0
8.12
16
import os import pandas as pd from sklearn import preprocessing from tensorflow.keras.preprocessing.image import ImageDataGenerator # Define constants for directories and image parameters BASE_TRAIN_DIR = "Text-Classification/train_image" # Directory for training images BASE_TEST_DIR = "Text-Classification/tes...
back-kh/GPLC-Ancient-Glyph-Palm-Leaf-Classifications
preprocessing/data_preprocessing.py
.py
e8003d9b1319f5af
7.52
10
from unittest.mock import patch import pytest @pytest.fixture(autouse=True) def auto_enable_custom_integrations(enable_custom_integrations): """Enable custom integrations in all tests.""" return # This fixture is used to prevent HomeAssistant from attempting to create and dismiss persistent # notifications...
jeyrb/hass_mikrotik_sms
conftest.py
.py
a7b81c81809a47b2
8.02
10
import logging from typing import Optional from google.cloud import logging as gcp_logging from src.utils import constants class Logger(logging.Logger): # used to avoid too much verbosity from third-party libraries DEBUG = logging.DEBUG + 1 def __init__(self, name: str) -> None: super().__init_...
hcholab/sfkit-website
src/utils/custom_logging.py
.py
4206f06158241fec
7.42
6
import googleapiclient.discovery as googleapi from src.utils import constants, custom_logging logger = custom_logging.setup_logging(__name__) class GoogleCloudIAM: """ Class to handle interactions with the Google Cloud IAM API. """ def __init__(self) -> None: self.service = googleapi.build(...
hcholab/sfkit-website
src/utils/google_cloud/google_cloud_iam.py
.py
d91d45f7dc46ab8d
7.42
6
"""Utils and helpers.""" from __future__ import annotations import re from http.cookies import SimpleCookie from typing import Any REGEXP_COOKIE_EXPIRES = re.compile("(;\\s?expires=(.*)(;|$))", re.IGNORECASE) def normalize_cookies(cookies: list[str]) -> SimpleCookie: """Normalize non RFC-compliant cookies.""" ...
Drafteed/pybravia
pybravia/util.py
.py
3187bf07a99a13b5
7.45
7
"""Pytest fixtures for pybravia tests.""" from __future__ import annotations import json from collections.abc import AsyncGenerator from pathlib import Path from typing import Any, cast import pytest from aiointercept import aiointercept from pybravia import BraviaClient TEST_HOST = "192.168.1.100" TEST_MAC = "AA:...
Drafteed/pybravia
tests/conftest.py
.py
a174efc9cc097b83
7.95
7
"""Logic for slimproto clients to discover the server on the local network.""" from __future__ import annotations import asyncio from collections import OrderedDict import logging import socket import struct LOGGER = logging.getLogger(__name__) async def start_discovery( ip_address: str, control_port: int,...
music-assistant/aioslimproto
aioslimproto/discovery.py
.py
5883ab1bd23f7f01
7.59
14
""" Manage the display of a SlimProto based player. Provides support for rendering text using local truetype fonts. Copyright 2010 Doug Winter https://github.com/winjer/squeal/blob/master/src/squeal/player/display.py """ from __future__ import annotations import asyncio import os import struct from typing import TY...
music-assistant/aioslimproto
aioslimproto/display.py
.py
895faacba396c072
7.59
14
"""Models used for the JSON-RPC API.""" from __future__ import annotations from dataclasses import dataclass, field from enum import Enum, IntEnum from typing import Any, TypedDict class EventType(Enum): """Enum with possible slim proto client events.""" PLAYER_UPDATED = "player_updated" PLAYER_HEARTBE...
music-assistant/aioslimproto
aioslimproto/models.py
.py
b4b8cce5fc0def98
7.59
14
"""Server implementation holding (and discovering) the SLIMProto players.""" from __future__ import annotations import asyncio from collections.abc import Callable import inspect import logging from types import TracebackType from typing import TYPE_CHECKING, Any, Self from .cli import SlimProtoCLI from .client impo...
music-assistant/aioslimproto
aioslimproto/server.py
.py
b6779b8e36237388
7.59
14
"""Helpers and utils.""" from __future__ import annotations import asyncio import logging import socket from typing import Any from urllib.parse import parse_qsl from .const import FALLBACK_CODECS def get_ip() -> str: """Get primary IP-address for this host.""" sock = socket.socket(socket.AF_INET, socket.S...
music-assistant/aioslimproto
aioslimproto/util.py
.py
56e8347c5179558c
7.59
14
""" Manage the sound volume of a SlimProto based player. Copyright 2010 Doug Winter https://github.com/winjer/squeal/blob/master/src/squeal/player/volume.py """ from __future__ import annotations from typing import ClassVar class SlimProtoVolume: """Represents a sound volume. This is an awful lot more complex ...
music-assistant/aioslimproto
aioslimproto/volume.py
.py
9f44163fe782fb96
7.59
14
"""Tests for the SlimProto CLI.""" import asyncio from itertools import chain import logging from types import SimpleNamespace from typing import cast from unittest.mock import AsyncMock, Mock from urllib.parse import quote import pytest from aioslimproto.cli import SlimProtoCLI from aioslimproto.client import SlimC...
music-assistant/aioslimproto
tests/cli_test.py
.py
2dc163bdafdec66f
7.09
14
"""Render `pyrefly coverage report`'s JSON as a human-readable table. Reads the JSON report from stdin (i.e. run as ``pyrefly coverage report src | python scripts/pyrefly_coverage_summary.py``) and prints one row per module -- typable symbol count, how many are untyped, and the resulting coverage percentage -- followe...
catalyst-cooperative/ferc-xbrl-extractor
scripts/pyrefly_coverage_summary.py
.py
9a2931b87ab64fd8
7.63
17
"""Abstract away interface to Arelle XBRL Library.""" import time from pathlib import Path from typing import Any, BinaryIO, Literal, cast import pydantic import stringcase from arelle import Cntlr, FileSource, ModelManager, ModelXbrl, XbrlConst from arelle.ModelDtsObject import ModelConcept from arelle.ModelObject i...
catalyst-cooperative/ferc-xbrl-extractor
src/ferc_xbrl_extractor/arelle_interface.py
.py
6581c8b2e0d78481
7.63
17
"""A command line interface (CLI) to the xbrl extractor.""" import argparse import io import json import logging import sys from itertools import chain from pathlib import Path import coloredlogs import duckdb import pandas as pd from frictionless import Package from sqlalchemy import create_engine from sqlalchemy.en...
catalyst-cooperative/ferc-xbrl-extractor
src/ferc_xbrl_extractor/cli.py
.py
9add40e0ffedad36
7.63
17
"""XBRL prototype structures.""" import io from pathlib import Path from typing import Any, BinaryIO, Literal import pydantic from arelle import XbrlConst from arelle.ModelDtsObject import ModelConcept, ModelType from pydantic import AnyHttpUrl, BaseModel from ferc_xbrl_extractor.arelle_interface import ( Metada...
catalyst-cooperative/ferc-xbrl-extractor
src/ferc_xbrl_extractor/taxonomy.py
.py
81f6bc7659d79f6d
7.63
17
"""XBRL extractor.""" import io import json import math import re import warnings from collections import defaultdict, namedtuple from collections.abc import Iterable from concurrent.futures import ProcessPoolExecutor as Executor from functools import partial from pathlib import Path from typing import BinaryIO, Typed...
catalyst-cooperative/ferc-xbrl-extractor
src/ferc_xbrl_extractor/xbrl.py
.py
dfa16362c5f88cc5
7.63
17
"""PyTest configuration module. Defines useful fixtures, command line args.""" import logging import tempfile from io import BytesIO from pathlib import Path import pytest logger = logging.getLogger(__name__) def pytest_addoption(parser): """Add package-specific command line options to pytest. This is sli...
catalyst-cooperative/ferc-xbrl-extractor
tests/conftest.py
.py
c55a05a49913995f
7.13
17
"""Test the PUDL console scripts from within PyTest.""" from importlib.metadata import entry_points import duckdb import pandas as pd import pytest # Obtain a list of all deployed entry point scripts to test: ENTRY_POINTS = [ ep.name for ep in entry_points(group="console_scripts") if ep.name.startswith("...
catalyst-cooperative/ferc-xbrl-extractor
tests/integration/console_scripts_test.py
.py
961e30217e8503a3
8.13
17
from collections import namedtuple from pathlib import Path import pytest from ferc_xbrl_extractor.xbrl import ExtractOutput, extract Dataset = namedtuple("Dataset", ["form", "year"]) DATASETS = [Dataset(form=f, year=y) for f in {1, 2, 6, 60, 714} for y in {2021, 2022}] @pytest.fixture(scope="session") def metada...
catalyst-cooperative/ferc-xbrl-extractor
tests/integration/data_quality_test.py
.py
7efc375164220941
7.13
17
"""Test datapackage descriptor from taxonomy.""" import datetime import io import zipfile from pathlib import Path from typing import BinaryIO, cast import pandas as pd import pytest from frictionless import Package from ferc_xbrl_extractor.datapackage import ( DURATION_COLUMNS, INSTANT_COLUMNS, Datapack...
catalyst-cooperative/ferc-xbrl-extractor
tests/integration/datapackage_test.py
.py
3762bf331a9a723d
8.13
17
"""Integration tests for ferc_xbrl_extractor.xbrl.""" import pytest from ferc_xbrl_extractor.xbrl import get_fact_tables def test_get_fact_tables_rejects_invalid_datapackage(data_dir, tmp_path, mocker): """get_fact_tables() raises a clear error if the generated datapackage is invalid. Forces the failure by...
catalyst-cooperative/ferc-xbrl-extractor
tests/integration/xbrl_test.py
.py
d29821664982651b
7.13
17
"""Test the internal Arelle interface helpers.""" import pytest import ferc_xbrl_extractor.arelle_interface as arelle_interface @pytest.mark.parametrize("max_retries", [0, -1]) def test_taxonomy_view_rejects_non_positive_max_retries(max_retries): """_taxonomy_view() rejects max_retries < 1 instead of looping ze...
catalyst-cooperative/ferc-xbrl-extractor
tests/unit/arelle_interface_test.py
.py
6d2b09d04cf9248d
8.13
17
"""Test the FERC XBRL extractor CLI helpers.""" import json import pytest from ferc_xbrl_extractor.cli import convert_and_validate_datapackage_sqlite_to_parquet def test_convert_and_validate_datapackage_sqlite_to_parquet_rejects_invalid( tmp_path, mocker ): """Raises a clear error if the rewritten datapack...
catalyst-cooperative/ferc-xbrl-extractor
tests/unit/cli_test.py
.py
46ed9119cbaf5d17
7.13
17
"""Test XBRL instance interface.""" import datetime import io import json import logging import zipfile from collections import Counter import pytest from lxml import etree # nosec: B410 from ferc_xbrl_extractor.instance import ( Axis, Context, DimensionType, Entity, Fact, Instance, Inst...
catalyst-cooperative/ferc-xbrl-extractor
tests/unit/instance_test.py
.py
4ef559d87b6d67f9
8.13
17
"""Test XBRL taxonomy interface.""" import pytest from ferc_xbrl_extractor.taxonomy import Concept, LinkRole @pytest.mark.parametrize( "from_list,bad_list,exception_type,match", [ ( Concept.from_list, ["not_concept", {}, {}], ValueError, "First element...
catalyst-cooperative/ferc-xbrl-extractor
tests/unit/taxonomy_test.py
.py
d1cb448499c7f66e
7.13
17
import io import zipfile import pandas as pd import pytest from lxml.etree import XMLSyntaxError # nosec: B410 from ferc_xbrl_extractor.xbrl import get_fact_tables, process_batch, process_instance def test_get_fact_tables_rejects_undated_taxonomy_filename(): """get_fact_tables() raises a clear error if a taxon...
catalyst-cooperative/ferc-xbrl-extractor
tests/unit/xbrl_test.py
.py
a23485884774b1ad
8.13
17
import os import subprocess import numpy as np from pyzdcf import pyzdcf from pypetal.utils.petalio import print_error def run_plike(dcf_fname, lag_bounds, plike_dir, verbose=False): """ Runs the PLIKE algorithm to compute the maximum likelihood peak of the ZDCF. Must have PLIKE (https://ui.adsabs.harva...
Zstone19/pypetal
src/pypetal/pyzdcf/utils.py
.py
bcbd3f810ecf2477
7.62
16
import glob import os import shutil import unittest import numpy as np import pypetal.pipeline as pl class TestWeighting(unittest.TestCase): def setUp(self): main_dir = 'examples/dat/javelin_' filenames = [main_dir + 'continuum.dat', main_dir + 'yelm.dat', main_dir + 'zing.dat'] outpu...
Zstone19/pypetal
tests/detrend_test.py
.py
06494daa00f074f9
7.12
16
from __future__ import annotations import json import re from typing import TYPE_CHECKING from django import template if TYPE_CHECKING: from admin_data_views.typing import Any, DictItems, ItemsView, NestedDict, SectionData register = template.Library() LINK_TEMPLATE = re.compile(r'<a href=".*">(?P<value>.*)</a...
MrThearMan/django-admin-data-views
admin_data_views/templatetags/admin_data_utils.py
.py
8a2ca9254fb0d1ae
7.5
9
"""Utility functions for checking types and values. Inspired from MNE.""" from __future__ import annotations import logging import operator import os from pathlib import Path from typing import TYPE_CHECKING import numpy as np if TYPE_CHECKING: from typing import Any def ensure_int(item: Any, item_name: str |...
mscheltienne/template-python
src/template/utils/_checks.py
.py
32ebc2dc31b09b3e
7.5
9
"""Temporary bug-fixes awaiting an upstream fix.""" from __future__ import annotations import sys from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Any # https://github.com/sphinx-gallery/sphinx-gallery/issues/1112 class WrapStdOut: """Dynamically wrap to sys.stdout. This makes pac...
mscheltienne/template-python
src/template/utils/_fixes.py
.py
46fa3989641fb722
7.5
9
from __future__ import annotations import platform import sys import tomllib from functools import lru_cache, partial from importlib.metadata import PackageNotFoundError, metadata, requires, version from importlib.util import find_spec from pathlib import Path from typing import TYPE_CHECKING import psutil from packa...
mscheltienne/template-python
src/template/utils/config.py
.py
abf26680c004c3c1
7.5
9
from __future__ import annotations import inspect import logging from functools import wraps from importlib import import_module from pathlib import Path from typing import TYPE_CHECKING from warnings import warn_explicit from template.utils._checks import ensure_verbose from template.utils._fixes import WrapStdOut ...
mscheltienne/template-python
src/template/utils/logs.py
.py
483618010a5d3b79
7.5
9
from __future__ import annotations import logging from pathlib import Path import numpy as np import pytest from template.utils._checks import ( check_type, check_value, ensure_int, ensure_path, ensure_verbose, ) def test_ensure_int() -> None: """Test ensure_int checker.""" # valids ...
mscheltienne/template-python
tests/utils/test_checks.py
.py
3c206b747e1516c9
8
9
from __future__ import annotations from io import StringIO import pytest from template.utils.config import _get_gpu_info, sys_info def test_sys_info() -> None: """Test info-showing utility.""" out = StringIO() sys_info(fid=out) value = out.getvalue() out.close() assert "Platform:" in value ...
mscheltienne/template-python
tests/utils/test_config.py
.py
78925df623e6fa2c
8
9
from __future__ import annotations import pytest from template.utils._docs import copy_doc from template.utils.logs import verbose def test_copy_doc_function() -> None: """Test decorator to copy docstring on functions.""" # test copy of docstring def foo(x, y) -> None: """My doc.""" @copy_...
mscheltienne/template-python
tests/utils/test_docs.py
.py
66c29d65df7b57f8
7
9
from __future__ import annotations import pytest from template.utils._imports import import_optional_dependency def test_import_optional_dependency() -> None: """Test the import of optional dependencies.""" # Test import of present package numpy = import_optional_dependency("numpy") assert isinstanc...
mscheltienne/template-python
tests/utils/test_imports.py
.py
1ead2c61eed14094
7
9
# Note: initially copied from https://github.com/florimondmanca/httpx-sse/blob/master/src/httpx_sse/_decoders.py from __future__ import annotations import json import inspect from types import TracebackType from typing import TYPE_CHECKING, Any, Generic, TypeVar, Iterator, Optional, AsyncIterator, cast from typing_ext...
Increase/increase-python
src/increase/_streaming.py
.py
14c2e06d6f1c6966
7.54
11
from __future__ import annotations from os import PathLike from typing import ( IO, TYPE_CHECKING, Any, Dict, List, Type, Tuple, Union, Mapping, TypeVar, Callable, Iterable, Iterator, Optional, Sequence, AsyncIterable, ) from typing_extensions import ( ...
Increase/increase-python
src/increase/_types.py
.py
7e283f58004cbf35
7.54
11
from __future__ import annotations from typing import Any from typing_extensions import override from ._proxy import LazyProxy class ResourcesProxy(LazyProxy[Any]): """A proxy for the `increase.resources` module. This is used so that we can lazily import `increase.resources` only when needed *and* so t...
Increase/increase-python
src/increase/_utils/_resources_proxy.py
.py
22cf42d4a19405c9
7.54
11
""" Provides functions for iterating over several simulations to compute statistical power and more. """ # Python modules import multiprocessing as mp import numpy as np import signal import time import traceback # Bioverse modules and constants from . import util # Prevents a crash due to matplotlib when multiproce...
danielapai/bioverse
bioverse/analysis.py
.py
09855dbe15dcf553
7.48
8
""" Contains class definitions. """ # System modules from copy import deepcopy import numpy as np import pickle import time # Bioverse modules and constants from .constants import DATA_DIR, OBJECTS_DIR from .constants import STR_TYPES, INT_TYPES from .constants import CONST # Imports pandas.DataFrame if installed tr...
danielapai/bioverse
bioverse/classes.py
.py
7643be9c079097c2
7.48
8
""" This module defines the Generator class and demonstrates how to create new Generators. """ # System imports from copy import deepcopy import inspect import numpy as np import traceback from warnings import warn # Bioverse modules from .classes import Object, Table, Stopwatch from .constants import ROOT_DIR from ....
danielapai/bioverse
bioverse/generator.py
.py
1cec35af0bc6bd52
7.48
8
""" This module reproduces scipy.stats.truncnorm as of SciPy v1.3.3. More recent versions of truncnorm are orders of magnitude slower as documented here and elsewhere: https://github.com/scipy/scipy/issues/12370. """ import numpy as np from scipy.stats._continuous_distns import rv_continuous, _norm_cdf, _norm_sf, _nor...
danielapai/bioverse
bioverse/truncnorm_hack.py
.py
a8227f85b99f2159
7.48
8
#!/usr/bin/env python3 """ Ensure every notebook under docs/pre_executed has metadata: "nbsphinx": {"execute": "never"} This script is safe to run as a pre-commit hook. It will modify notebooks in-place and print modified file paths. It raises exceptions on hard errors (instead of return codes). If any notebook has an...
snad-space/coniferest
.ci/pre_executed_nb.py
.py
33f20502fd09bcad
7.63
17
from numbers import Real from typing import Callable import clarabel import numpy as np from scipy import sparse from ._core import calc_paths_sum # noqa from .coniferest import Coniferest, ConiferestEvaluator from .label import Label __all__ = ["AADForest"] class AADEvaluator(ConiferestEvaluator): def __init...
snad-space/coniferest
src/coniferest/aadforest.py
.py
144d79849791fc47
7.63
17
from abc import ABC, abstractmethod from warnings import warn import numpy as np from ._core import Tree, build_trees # noqa from .evaluator import ForestEvaluator __all__ = ["Coniferest", "ConiferestEvaluator", "Tree"] class Coniferest(ABC): """ Base class for the forests in the package. It settles the b...
snad-space/coniferest
src/coniferest/coniferest.py
.py
0518cad295c5ab31
7.63
17
import math import numpy as np from scipy.sparse import csr_array from ._core import Tree, calc_apply, calc_feature_delta_sum, calc_paths_sum # noqa from .utils import average_path_length __all__ = ["ForestEvaluator"] class ForestEvaluator: def __init__(self, samples, trees, *, num_threads, sampletrees_per_ba...
snad-space/coniferest
src/coniferest/evaluator.py
.py
cf2f69a24d5fd89a
7.63
17
from .coniferest import Coniferest, ConiferestEvaluator __all__ = ["IsolationForest"] class IsolationForest(Coniferest): """ Isolation forest. This is a reimplementation of sklearn.ensemble.IsolationForest, which trains and evaluates much faster. It also supports multi-threading for evaluation (...
snad-space/coniferest
src/coniferest/isoforest.py
.py
9f2e2c7c43a9e5b3
7.63
17
import numpy as np from .coniferest import Coniferest, ConiferestEvaluator from .evaluator import ForestEvaluator from .label import Label __all__ = ["PineForest"] class PineForest(Coniferest): """ Pine Forest for active anomaly detection. Pine Forests are filtering isolation forests. That's a simple c...
snad-space/coniferest
src/coniferest/pineforest.py
.py
645879759fa31a1b
7.63
17
import webbrowser from pathlib import Path import click from coniferest.datasets import Label from coniferest.onnx.convert import save_onnx_model, to_onnx class _LabelChoice(click.Choice): """Label choice class for click Accepts (case-insensitive): * -1 / a / anomaly / yes * 1 / r / regular...
snad-space/coniferest
src/coniferest/session/callback.py
.py
85a3b6a17e51f435
7.63
17
from typing import Callable, Optional import numpy as np from coniferest.coniferest import Coniferest from coniferest.label import Label from coniferest.session import Session from coniferest.session.callback import TerminateAfter, TerminateAfterNAnomalies class OracleSession(Session): """Automated session to r...
snad-space/coniferest
src/coniferest/session/oracle.py
.py
3bea4714e0288882
7.63
17
from typing import List import numpy as np import pytest from numpy.testing import assert_equal from coniferest.coniferest import Coniferest, Tree class ConiferestImpl(Coniferest): def fit(self, data, labels=None): super().fit(data, labels) def fit_known(self, data, known_data=None, known_labels=No...
snad-space/coniferest
tests/test_coniferest.py
.py
d3cf9aad2aa71f87
8.13
17
import numpy as np import pytest from coniferest.aadforest import AADForest from coniferest.datasets import non_anomalous_outliers, ztf_m31 from coniferest.label import Label from coniferest.pineforest import PineForest from coniferest.session import Session from coniferest.session.callback import TerminateAfterNAnoma...
snad-space/coniferest
tests/test_session.py
.py
3eabb877aeed2184
8.13
17
import jax import jax.numpy as jnp import jax.scipy.fft import flt.generic @jax.jit def dct2dlt(b): """JAX implementation of dct2dlt""" def first(x, j): """compute initial row of L matrix""" even = j % 2 == 0 y = jax.lax.select(even, x * (1 - 4 / (j + 3)), x) y = jax.lax.sele...
ntessore/flt
src/flt/jax.py
.py
5efae05772c747d4
7.48
8
import webBackend.models as models import logging import sys sys.path.append("..") log = logging.getLogger(__name__) def songIdUpdater(user: str): """ Song ID Updater Helper Function Parameters: user (str): User to Scan Returns: list: List of Changed Song IDs """ history = ...
ArthurVardevanyan/Analytics-for-Spotify
monitoringBackend/scripts.py
.py
e641b73f45765c73
7.45
7
import os import sys import django import logging import requests import time # Add project root to Python path project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) sys.path.insert(0, project_root) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "AnalyticsForSpotify.settings") django.se...
ArthurVardevanyan/Analytics-for-Spotify
monitoringBackend/scripts/link_artists.py
.py
fa07c9ab749b1df8
7.45
7
import os import base64 import urllib.parse import json import tarfile import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "AnalyticsForSpotify.settings") django.setup() # https://stackoverflow.com/a/74238820 def extractNode(): """ Extracts Node Modules, only used when running outside of a contain...
ArthurVardevanyan/Analytics-for-Spotify
setup.py
.py
2ec5b65d9ccdcaa5
7.45
7