text
stringlengths
185
73.3k
repo
stringlengths
7
100
path
stringlengths
4
146
language
stringclasses
7 values
hash
stringlengths
16
16
score
float64
7
8.5
stars
int64
0
237k
#!/usr/bin/env python3 """ run_STAR.py This script processes short-read RNA-seq data by mapping them to a reference genome using STAR. Features: - Handles both Single-End (SE) and Paired-End (PE) data - Supports multiple samples/replicates via a sample sheet - Auto-detects and building of STAR genome index i...
ConesaLab/SQANTI-single-cell
scripts/run_STAR.py
.py
881e07ad5ef81ad7
7.48
8
import os import sys import pandas as pd import numpy as np import scanpy as sc def prepare_anndata(args, row): """ Load classification file and create an AnnData object. Aggregates counts by cell barcode (CB) and associated_gene. """ file_acc = row['file_acc'] sampleID = row['sampl...
ConesaLab/SQANTI-single-cell
src/sc_clustering.py
.py
9d270f133faf2476
7.48
8
#!/usr/bin/env python3 """Normalize weekly Markdown files and sync the latest report into README.md.""" from __future__ import annotations import json import re from pathlib import Path README = Path("README.md") WEEKLY_DIR = Path("weekly") START = "<!-- WEEKLY_CHINESE_LLM_UPDATE:START -->" END = "<!-- WEEKLY_CHINESE...
PristineStream/ChatGPT-Chinese-Tutorial
scripts/sync_latest_weekly_to_readme.py
.py
f3d0fa163e6b2e28
8.1
15
import ast import pathlib import re import sys CODE_ROOT = pathlib.Path(__file__).resolve().parent.parent EXECUTION_MODULES_PATH = CODE_ROOT / "src" / "saltext" / "kubernetes" / "modules" def check_cli_examples(files): """ Check that every function on every execution module provides a CLI example """ ...
salt-extensions/saltext-kubernetes
.pre-commit-hooks/check-cli-examples.py
.py
10b64b5e87f52d65
7.5
9
import datetime import json import os import platform import shutil import sys import tempfile from importlib import metadata from pathlib import Path import nox from nox.command import CommandFailed from nox.virtualenv import VirtualEnv # Nox options # Reuse existing virtualenvs nox.options.reuse_existing_virtualen...
salt-extensions/saltext-kubernetes
noxfile.py
.py
306a4cc712a2f03b
7.5
9
""" Per-resource log fetch for Kubernetes pods. .. versionadded:: 2.1.0 Dormant on stock Salt — see ``saltext.kubernetes.resources.kubernetes``. """ # pylint: disable=undefined-variable from saltext.kubernetes.utils._kuberesource import require_kind from saltext.kubernetes.utils._kuberesource import resource_identi...
salt-extensions/saltext-kubernetes
src/saltext/kubernetes/modules/kuberesource_logs.py
.py
043fcd7955924645
7.5
9
""" Per-resource state apply. .. versionadded:: 2.1.0 Forwards a manifest through ``kubernetes.apply`` while leaving the resource identity available to the manifest's Jinja templates via ``template_context`` (so a single manifest can be customised per resource at dispatch time). Dormant on stock Salt — see ``saltext...
salt-extensions/saltext-kubernetes
src/saltext/kubernetes/modules/kuberesource_state.py
.py
4d74d9ff0162ff09
7.5
9
""" Internal connection helpers for the saltext-kubernetes extension. This module owns the auth-resolution logic for the extension. The publicly-exposed seam is :py:func:`_setup_conn`, which is re-exported through :py:mod:`saltext.kubernetes.modules.kubernetesmod` for backwards compatibility — its signature, kwargs ha...
salt-extensions/saltext-kubernetes
src/saltext/kubernetes/utils/_connection.py
.py
d9300cf05851d695
7.5
9
""" Shared helpers for the ``kuberesource_*`` companion execution modules. Each ``kuberesource_*`` module is a thin wrapper that pulls resource identity from ``__resource__["id"]`` (set by Salt's resources-layer dispatcher) and forwards to the existing ``kubernetes.*`` execution module functions. The shared logic live...
salt-extensions/saltext-kubernetes
src/saltext/kubernetes/utils/_kuberesource.py
.py
6a24408930f21013
7.5
9
import logging import os import subprocess import pytest from pytest_kind import KindCluster from saltfactories.utils import random_string from saltext.kubernetes import PACKAGE_ROOT # Reset the root logger to its default level(because salt changed it) logging.root.setLevel(logging.WARNING) log = logging.getLogger(...
salt-extensions/saltext-kubernetes
tests/conftest.py
.py
50fedaf309505ebb
8
9
""" Deep coverage for the drift-suppression kwargs on ``kubernetes.apply``. The shallow file (``test_kubernetesmod_drift_suppression.py``) covers one test per ignore_* kwarg; this file exercises: * Multiple ignore_* kwargs combined in a single apply * Nested ignore_fields paths (image, env) * Re-apply after kub...
salt-extensions/saltext-kubernetes
tests/functional/modules/test_kubernetesmod_drift_deep.py
.py
de5428a9a45dcc7b
8
9
""" Functional tests for the drift-suppression kwargs on ``kubernetes.apply``. Each test: 1. Applies a manifest. 2. Mutates the live object out-of-band (simulating a foreign controller or operator). 3. Re-applies the original manifest with a matching ``ignore_*``. 4. Asserts the foreign mutation is prese...
salt-extensions/saltext-kubernetes
tests/functional/modules/test_kubernetesmod_drift_suppression.py
.py
2022deab1acc8747
8
9
""" Functional tests for exec-plugin auth against a real kind cluster. Uses a hermetic mock exec plugin (a shell script that prints a valid ``ExecCredential`` JSON with the kind cluster's service-account token). This proves the exec-auth wiring works end-to-end without depending on external auth tools like aws-iam-aut...
salt-extensions/saltext-kubernetes
tests/functional/modules/test_kubernetesmod_exec_auth.py
.py
cb996ca755c1c28a
8
9
""" Deep coverage for exec-plugin auth against a real kind cluster. The shallow file (``test_kubernetesmod_exec_auth.py``) demonstrates the happy path. This file targets: * Malformed plugin output → meaningful error * Plugin non-zero exit → install_hint surfaced * Plugin with multi-arg ``args:`` actually receiv...
salt-extensions/saltext-kubernetes
tests/functional/modules/test_kubernetesmod_exec_auth_deep.py
.py
14aac2e41081893c
8
9
""" Functional tests for the multi-cluster routing layer. The existing functional suite spins up a single kind cluster via the ``kind_cluster`` fixture. To test multi-cluster routing without doubling the runtime cost of every CI run, we exercise the alias plumbing against the same physical cluster reached through two ...
salt-extensions/saltext-kubernetes
tests/functional/modules/test_kubernetesmod_multi_cluster.py
.py
df051c032c490efa
8
9
""" Real-isolation multi-cluster tests using two distinct kind clusters. Gated by ``RUN_MULTI_CLUSTER_TESTS=1`` because materialising a second kind cluster on every CI run is wasteful. When enabled, these tests verify that the alias-routing code truly targets independent clusters — an object on cluster A is not visibl...
salt-extensions/saltext-kubernetes
tests/functional/modules/test_kubernetesmod_multi_cluster_real.py
.py
0ded6bf4733f794c
8
9
""" Functional tests for ``kubernetes.wait_for`` against a real kind cluster. Covers the user-driven wait surface added in 2.1.0: * ``condition=`` waits on ``status.conditions[*].type`` * ``jsonpath=`` waits on an arbitrary kubectl-style path * Timeout error path is exercised against a never-satisfied predicate...
salt-extensions/saltext-kubernetes
tests/functional/modules/test_kubernetesmod_wait_conditions.py
.py
bdb47a2a6b75fd88
8
9
""" Deep coverage for ``kubernetes.wait_for`` against a real kind cluster. The shallow test file (``test_kubernetesmod_wait_conditions.py``) covers the happy paths; this file targets edge cases: * ``status=False`` matching against a deliberately-failing pod * Nested jsonpath resolution * Cluster-scoped kinds (n...
salt-extensions/saltext-kubernetes
tests/functional/modules/test_kubernetesmod_wait_conditions_deep.py
.py
fc4ac58a69333a1d
8
9
import pytest from aws_cdk import App from infrastructure.build import build def test_cdk_app_can_synth(): """Test that the CDK app can be synthesized without errors.""" app = App() app.node.set_context('branch', 'test-branch') app.node.set_context('config-name', 'demo') build(app) # If we ge...
IGVF-DACC/igvf-catalog
cdk_swagger/tests/unit/test_basic.py
.py
9567a7bbf8fd2c82
7.92
6
import csv import gzip import json from math import log10 from typing import Optional import os from adapters.base import BaseAdapter from adapters.helpers import build_variant_id, build_regulatory_region_id, get_file_fileset_by_accession_in_arangodb from adapters.writer import Writer # Example row from sorted.dist.h...
IGVF-DACC/igvf-catalog
data/adapters/AFGR_caqtl_adapter.py
.py
5841fbe013c285aa
7.42
6
import csv import gzip import hashlib import json from typing import Optional import os from adapters.base import BaseAdapter from adapters.helpers import build_variant_id, get_file_fileset_by_accession_in_arangodb from adapters.writer import Writer from adapters.gene_validator import GeneValidator # Example row from ...
IGVF-DACC/igvf-catalog
data/adapters/AFGR_eqtl_adapter.py
.py
f203a5561567565f
7.42
6
import csv import gzip import hashlib import json import pickle from math import log10 from typing import Optional import os from adapters.base import BaseAdapter from adapters.helpers import build_variant_id, get_file_fileset_by_accession_in_arangodb from adapters.writer import Writer from adapters.gene_validator impo...
IGVF-DACC/igvf-catalog
data/adapters/AFGR_sqtl_adapter.py
.py
fa77dd896c7d9266
7.42
6
import csv import gzip import json from math import log10 from typing import Optional from adapters.base import BaseAdapter from adapters.helpers import build_regulatory_region_id, get_file_fileset_by_accession_in_arangodb from adapters.writer import Writer # Element-level CRISPR element-to-phenotype screens (Gersbac...
IGVF-DACC/igvf-catalog
data/adapters/CRISPR_element_phenotype_adapter.py
.py
bc6a60c1733101d6
7.42
6
import gzip import json import csv import os import re from typing import Optional from adapters.base import BaseAdapter from adapters.helpers import convert_aa_letter_code_and_Met1, convert_aa_to_three_letter, split_spdi, build_variant_coding_variant_key, get_file_fileset_by_accession_in_arangodb from adapters.writer...
IGVF-DACC/igvf-catalog
data/adapters/Mutpred2_coding_variants_adapter.py
.py
fe21d7f1315b2ae4
7.42
6
import csv import gzip import hashlib import json from typing import Optional from biocommons.seqrepo import SeqRepo from ga4gh.vrs.dataproxy import SeqRepoDataProxy from ga4gh.vrs.extras.translator import AlleleTranslator from adapters.base import BaseAdapter from adapters.helpers import bulk_check_variants_in_arang...
IGVF-DACC/igvf-catalog
data/adapters/STARR_seq_adapter.py
.py
02e17396167f20c0
7.42
6
import csv import json import os import gzip import re from typing import Optional from adapters.base import BaseAdapter from adapters.helpers import bulk_query_coding_variants_in_arangodb, bulk_query_coding_variants_from_hgvsc_in_arangodb, bulk_query_coding_variants_Met1_in_arangodb, get_file_fileset_by_accession_in_...
IGVF-DACC/igvf-catalog
data/adapters/VAMP_coding_variant_scores_adapter.py
.py
f3d06977bbb29331
7.42
6
import gzip import os import re import shutil import stat import tarfile import tempfile import zipfile from pathlib import Path from typing import Iterator FILE_ACCESSION_PATTERN = re.compile(r'(?:IGVFFI|ENCFF)[A-Z0-9]+') def get_file_accession(filepath: str) -> str: """Derive the file accession from the input...
IGVF-DACC/igvf-catalog
data/adapters/archive_utils.py
.py
14985847ef196740
7.42
6
""" Base adapter class for all IGVF Catalog data adapters. This module provides a base class that consolidates common functionality across all data adapters, including: - Schema loading and validation - Writer management - Common configuration - Standard error handling """ from abc import ABC, abstractmethod from typ...
IGVF-DACC/igvf-catalog
data/adapters/base/base_adapter.py
.py
0c8932caac8ad5b7
7.42
6
import csv import json import hashlib import obonet import pickle from typing import Optional import os from adapters.base import BaseAdapter from adapters.writer import Writer from adapters.helpers import get_file_fileset_by_accession_in_arangodb # Example lines in merged_PPI.UniProt.csv (and merged_PPI_mouse.UniPro...
IGVF-DACC/igvf-catalog
data/adapters/biogrid_gene_gene_adapter.py
.py
74e2b9139ca0dd1a
7.42
6
"""Cisco CatalystCenter Authentication API wrapper. Copyright (c) 2026 Cisco Systems. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights ...
cisco-en-programmability/catalystcentersdk
catalystcentersdk/api/authentication.py
.py
70dce9a540767a58
7.56
12
"""Cisco CatalystCenter CustomCaller Copyright (c) 2026 Cisco Systems. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, m...
cisco-en-programmability/catalystcentersdk
catalystcentersdk/api/custom_caller.py
.py
c59f078f26d3e3d7
7.56
12
"""Cisco Catalyst Center Applications API wrapper. Copyright (c) 2026 Cisco Systems. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights t...
cisco-en-programmability/catalystcentersdk
catalystcentersdk/api/v2_3_7_6_1/applications.py
.py
21589e4a9b78e452
7.56
12
"""Cisco Catalyst Center Cisco Trusted Certificates API wrapper. Copyright (c) 2026 Cisco Systems. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitatio...
cisco-en-programmability/catalystcentersdk
catalystcentersdk/api/v2_3_7_6_1/cisco_trusted_certificates.py
.py
b3d7adf846e4713b
7.56
12
"""Cisco Catalyst Center Command Runner API wrapper. Copyright (c) 2026 Cisco Systems. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights...
cisco-en-programmability/catalystcentersdk
catalystcentersdk/api/v2_3_7_6_1/command_runner.py
.py
de7e0efd86e935d9
7.56
12
"""Cisco Catalyst Center Configuration Archive API wrapper. Copyright (c) 2026 Cisco Systems. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the...
cisco-en-programmability/catalystcentersdk
catalystcentersdk/api/v2_3_7_6_1/configuration_archive.py
.py
9c2de8bbc5b96e8d
7.56
12
"""Cisco Catalyst Center Users API wrapper. Copyright (c) 2026 Cisco Systems. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, ...
cisco-en-programmability/catalystcentersdk
catalystcentersdk/api/v2_3_7_6_1/users.py
.py
079d6c1a3e928b05
7.56
12
# Copyright 2022-2025 Joe Block <jpb@unixorn.net> # License: Apache 2.0 import json import logging from typing import Optional, TypedDict from ha_mqtt_discoverable import Discoverable, __version__ from ha_mqtt_discoverable.utils import clean_string from ha_mqtt_discoverable_cli.utils import valid_configuration_key ...
unixorn/ha-mqtt-discoverable-cli
ha_mqtt_discoverable_cli/device.py
.py
8b46ab61dc2374e9
7.45
7
# # device_driver.py # # Copyright 2022-2023, Joe Block <jpb@unixorn.net> """ Code to support the hmd-create-device script """ import json import logging import sys from ha_mqtt_discoverable_cli.cli import create_base_parser from ha_mqtt_discoverable_cli.device import Device from ha_mqtt_discoverable_cli.settings i...
unixorn/ha-mqtt-discoverable-cli
ha_mqtt_discoverable_cli/device_driver.py
.py
5ffd6cfcfe7f10fe
7.45
7
# # Gives us a git-style main command that calls subcommands. # # Copyright 2023-2024: Joe Block <jpb@unixorn.net> # License: Apache 2.0 import os import subprocess import sys from gitlike_commands import find_subcommand def hmd_usage(): """ They called hdm with no subcommands, or we couldn't find a subcom...
unixorn/ha-mqtt-discoverable-cli
ha_mqtt_discoverable_cli/hmd.py
.py
da98e3ec926095de
7.45
7
# # sensor_driver.py # # Copyright 2022-2023, Joe Block <jpb@unixorn.net> """ Code to support the hmd-create-binary-sensor script """ import logging import sys from ha_mqtt_discoverable import Settings from ha_mqtt_discoverable_cli.cli import create_base_parser from ha_mqtt_discoverable.sensors import BinarySensor,...
unixorn/ha-mqtt-discoverable-cli
ha_mqtt_discoverable_cli/sensor_driver.py
.py
d0f3ada270a32953
7.45
7
# # Copyright 2022-2024 Joe Block <jpb@unixorn.net> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
unixorn/ha-mqtt-discoverable-cli
ha_mqtt_discoverable_cli/settings.py
.py
348c9b723fa00a06
7.45
7
''' LEARNED: - No key related eventFilter on the app(QApplication) otherwise: keyRelease --> multiple trigger - Not every event filter keys trigger action with both: full / non full screen video Below how the event filter was used in an early stage of the project This script is no...
K4KarolE/QTea_Media_Player
docs/learning/event_filter.py
.py
db714b5825e21f65
7.45
7
''' The below is not used in this project - saving for later Layout <- QGraphicsView <- QGraphicsScene <- QGraphicsVideoItem ''' from PyQt6.QtMultimedia import QAudioOutput, QMediaPlayer from PyQt6.QtMultimediaWidgets import QGraphicsVideoItem from PyQt6.QtWidgets import QWidget, QGraphicsScene, QGraphicsView class...
K4KarolE/QTea_Media_Player
docs/learning/graphics_scene_compiling.py
.py
5310f70685950a6e
7.45
7
""" Switching there and back between the two media >> can increase the memory usage It is the memory leak of the "QMediaPlayer().setSource()" function Was trying to create a new AVPlayer class instance for every media play and remove the previous instance >> The memory leak issue is still in place For testing, do not...
K4KarolE/QTea_Media_Player
docs/learning/player_basic_memory_leak_fix_try.py
.py
3e24a0e11e433227
7.45
7
''' Slider jumps to the position of the mouse click Cheers mate! https://python-forum.io/thread-10564.html ''' from PyQt6.QtWidgets import QSlider, QApplication, QMainWindow, QStyle from PyQt6.QtCore import Qt import sys app = QApplication(sys.argv) window = QMainWindow() window.resize(400, 350) window.setWindowTi...
K4KarolE/QTea_Media_Player
docs/learning/slider_jump_to_mouse_click.py
.py
287335b5ba0cf390
7.45
7
""" Cheers all! https://www.geeksforgeeks.org/python/pyqt5-qtablewidget/ https://www.qtcentre.org/threads/25952-Select-entire-row-in-QTableWidget-programmatically Please note, the QTableWidget is not used in the app. If you want to save some headache and workarounds, use the QTableWidget instead of ...
K4KarolE/QTea_Media_Player
docs/learning/table_widget.py
.py
3fbec8b4ef015bf8
7.45
7
""" Cheers! https://www.geeksforgeeks.org/prevent-freezing-in-python-pyqt-guis-with-qthread/ """ from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel from PyQt6.QtCore import Qt, QThread, pyqtSignal import sys import time QApplication.setDesktopSettingsAware(False) # avoid OS auto color...
K4KarolE/QTea_Media_Player
docs/learning/thumbnail_view/multithreading.py
.py
2e68a9cd422aadf3
7.45
7
import sys from PyQt6.QtCore import QEvent from PyQt6.QtWidgets import QApplication from .class_data import cv from .class_bridge import br from .logger import * """ To avoid system theme >> qt app theme https://doc.qt.io/qt-6/qguiapplication.html#setDesktopSettingsAware windll - myappid: To get the packaged applic...
K4KarolE/QTea_Media_Player
src/application.py
.py
c0a725fbafe749e7
7.45
7
""" Used to display the logo image when the video area is not active: - playing music - player is in stopped state """ from pathlib import Path from PyQt6.QtCore import Qt from PyQt6.QtGui import QPixmap from PyQt6.QtWidgets import QLabel from .class_data import cv from .logger import logger_runtime @logger_runtime...
K4KarolE/QTea_Media_Player
src/images.py
.py
e1c4ab4ec820c46c
7.45
7
''' Used to measure the time of - application launch: main.py - add directory: src / buttons.py / button_add_dir_clicked() LEARNED: The function with the @logger_runtime decorator need to be called with lambda: - button_add_dir.clicked.connect(lambda: button_add_dir.button_add_dir_clic...
K4KarolE/QTea_Media_Player
src/logger.py
.py
a928130427fe6a7f
7.45
7
''' THIS FILE CAN BE REACHED OUTSIDE THE APP ONLY It contains supporting functions only, which can be actioned in this file for: - Verify the tables available in the DB - Creating new DB - Remove a table from the DB ''' import sqlite3 from pathlib import Path from json import load, dump def open_json(): ...
K4KarolE/QTea_Media_Player
src/tables_and_playlists_guide.py
.py
f8aa190bf331a067
7.45
7
from PyQt6.QtCore import QThread, pyqtSignal from .class_data import cv, save_thumbnail_history_json from .func_coll import set_thumbnail_generation_needed_to from .func_thumbnail import create_thumbnails_and_update_widgets class ThreadThumbnail(QThread): result_ready = pyqtSignal(int, str) def __init__(sel...
K4KarolE/QTea_Media_Player
src/thread_thumbnail.py
.py
f0ac0c61a2728d67
7.45
7
from PyQt6.QtCore import QEvent, Qt from PyQt6.QtGui import QAction, QPixmap from PyQt6.QtWidgets import ( QLabel, QMenu, QVBoxLayout, QWidget ) from .class_data import cv from .class_bridge import br from .class_skins import sk from .func_coll import ( active_track_font_style, clear_queue_...
K4KarolE/QTea_Media_Player
src/thumbnail_widget.py
.py
4bd64c9f5ef8f06a
7.45
7
""" ThumbnailMainWindow(QScrollArea) << WidgetsWindow(QWidget) - Window holding the thumbnail widgets Used in the src / playlists / playlists_creation() """ from PyQt6.QtCore import Qt, QTimer from PyQt6.QtWidgets import ( QWidget, QScrollArea, QScrollBar ) from .class_bridge import br from ...
K4KarolE/QTea_Media_Player
src/thumbnail_window.py
.py
b4aaf423f4e40cd0
7.45
7
""" Collect interpreter information, also run as the subprocess interrogation script (stdlib only). Executed by the interpreter being probed. Collection supports Python 3.6+, but the file must parse on 2.7 so the version gate below can report older interpreters instead of dying with a ``SyntaxError``: no f-strings, no...
tox-dev/python-discovery
src/python_discovery/_py_info_collect.py
.py
62117953e90a7303
7.57
13
"""A Python specification is an abstract requirement definition of an interpreter.""" from __future__ import annotations import contextlib import pathlib import re from typing import Final from ._py_info import normalize_isa from ._specifier import SimpleSpecifier, SimpleSpecifierSet, SimpleVersion PATTERN = re.com...
tox-dev/python-discovery
src/python_discovery/_py_spec.py
.py
3b544c0bd250ee6e
8.07
13
"""Version specifier support using only standard library (PEP 440 compatible).""" from __future__ import annotations import contextlib import operator import re import sys from dataclasses import dataclass from typing import TYPE_CHECKING, Final DC_KW: Final[dict[str, bool]] = ( {"frozen": True, "kw_only": True,...
tox-dev/python-discovery
src/python_discovery/_specifier.py
.py
a3b3076f4cff9854
8.07
13
"""odsbox - Toolbox for accessing ASAM ODS servers using the HTTP API This package provides convenient access to ASAM ODS servers with lazy loading for better performance. Example:: from odsbox import ConI with ConI(url="http://localhost:8087/api", auth=("sa", "sa")) as con_i: units = con_i.query_da...
peak-solution/odsbox
src/odsbox/__init__.py
.py
d188a00b18854a69
7.57
13
"""datetime is represented as string in ASAM ODS formatted using YYYYMMDDHHMMSSFFF. Here you find some helpers.""" from __future__ import annotations from typing import cast import pandas as pd def __normalize_datetime_string(asam_time: str) -> str: asam_time_len = len(asam_time) if asam_time_len < 8: ...
peak-solution/odsbox
src/odsbox/asam_time.py
.py
9d1ace0196332910
7.57
13
"""JAQueL conversion result types.""" from __future__ import annotations from dataclasses import dataclass import odsbox.proto.ods_pb2 as ods @dataclass(slots=True, frozen=True, unsafe_hash=False) class JaquelConversionResult: """ Result of a JAQueL to ODS conversion. Contains the target entity, the g...
peak-solution/odsbox
src/odsbox/jaquel_conversion_result.py
.py
884b82a513c52c3a
7.57
13
"""ASAM ODS Protocol Buffer interfaces This module provides convenient access to ASAM ODS protobuf definitions with lazy loading for better performance. Example:: from odsbox.proto import ods, ods_security # Create a model instance model = ods.Model() """ from __future__ import annotations from typin...
peak-solution/odsbox
src/odsbox/proto/__init__.py
.py
b04e211194489948
7.57
13
""" Helper for handling transactions Example:: from odsbox.con_i import ConI with ConI( url="http://localhost:8087/api", auth=("sa", "sa") ) as con_i: with con_i.transaction() as transaction: # do some work transaction.commit() """ from _...
peak-solution/odsbox
src/odsbox/transaction.py
.py
1886745d473d3fe5
7.57
13
"""Helper class for Units in ASAM ODS""" from __future__ import annotations import logging from typing import TYPE_CHECKING if TYPE_CHECKING: from .con_i import ConI import odsbox.proto.ods_pb2 as ods class UnitCatalog: """ This class caches the units stored in the ASAM ODS server. ...
peak-solution/odsbox
src/odsbox/unit_catalog.py
.py
06c7b4c9d9d06f57
7.57
13
"""Utility functions for context handling.""" from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from ..proto import ods def from_context_variables(context_variables: "ods.ContextVariables") -> dict[str, Any]: """ Convert ContextVariables to a dictionary. Args: context_var...
peak-solution/odsbox
src/odsbox/utils/context.py
.py
1c8f651b3602306d
7.57
13
"""Tests for chunked download functionality in file_access_download""" from __future__ import annotations import os import tempfile from unittest import mock import pytest from odsbox.con_i import ConI from odsbox.proto.ods_pb2 import FileIdentifier @pytest.fixture def con_i(): return ConI("https://docker.pea...
peak-solution/odsbox
tests/test_con_i_chunked_download.py
.py
f3a63ea3faeadd2d
7.07
13
"""Mock tests for ConI with resource logout behavior""" from __future__ import annotations import logging from unittest import mock import pytest import requests import odsbox.proto.ods_pb2 as ods from odsbox.con_i import ConI class TestConIWithResourceLogout: """Test class for ConI with resource context mana...
peak-solution/odsbox
tests/test_con_i_with_resource_logout.py
.py
0842e601e008d63f
7.07
13
"""Tests for the is_null_to_nan parameter in datamatrices_to_pandas.py""" from __future__ import annotations import numpy as np import pandas as pd import odsbox.proto.ods_pb2 as ods from odsbox.datamatrices_to_pandas import to_pandas class TestIsNullToNan: """Test suite for is_null_to_nan functionality""" ...
peak-solution/odsbox
tests/test_is_null_to_nan.py
.py
c962812a35da2a78
8.07
13
"""Test ModelCache functionality.""" from __future__ import annotations import os from pathlib import Path import pytest from google.protobuf.json_format import Parse from odsbox.model_cache import ModelCache from odsbox.proto.ods_pb2 import Model def __get_model(model_file_name): model_file = os.path.join(os...
peak-solution/odsbox
tests/test_model_cache.py
.py
7243897f95108f7c
7.07
13
"""Test ModelSuggestions class functionality.""" from __future__ import annotations import os from pathlib import Path from unittest.mock import Mock from google.protobuf.json_format import Parse from odsbox.model_suggestions import ModelSuggestions from odsbox.proto.ods_pb2 import Model def _get_model(model_file...
peak-solution/odsbox
tests/test_model_suggestions.py
.py
f8d534b634be17e7
7.07
13
"""Tests for odsbox.__init__ lazy loading functionality""" from __future__ import annotations import sys import pytest def test_odsbox_lazy_import_coni(): """Test that ConI is lazily imported""" from odsbox import ConI # Should be the actual ConI class assert ConI.__name__ == "ConI" assert has...
peak-solution/odsbox
tests/test_odsbox_init.py
.py
63bd50c7757754f1
8.07
13
"""Tests for odsbox.proto lazy loading functionality""" from __future__ import annotations import sys import pytest def test_proto_lazy_import_ods(): """Test that ods module is lazily imported""" # Remove from cache if already imported if "odsbox.proto" in sys.modules: del sys.modules["odsbox.p...
peak-solution/odsbox
tests/test_proto_init.py
.py
6913b7331bc54474
7.07
13
"""Nox sessions.""" import os import shlex import shutil import sys from pathlib import Path from textwrap import dedent import nox # Use standard nox session type Session = nox.Session session = nox.session package = "py21cmemu" python_versions = ["3.14", "3.13", "3.12", "3.11", "3.10"] nox.needs_version = ">= 20...
21cmfast/21cmEMU
noxfile.py
.py
c58cffccc7a90192
7.45
7
"""User-facing configuration for py21cmEMU.""" from __future__ import annotations import logging from collections.abc import Generator from contextlib import contextmanager from pathlib import Path from typing import Any import toml from appdirs import AppDirs log = logging.getLogger(__name__) APPDIR = AppDirs("py...
21cmfast/21cmEMU
src/py21cmemu/config.py
.py
200897202507dd41
7.45
7
import torch from torch.utils.data import Dataset from . import sde as sde_lib def get_model_fn(model, train=False): """Create a function to give the output of the score-based model. Args: model: The score model. train: `True` for training and `False` for evaluation. Returns: A model ...
21cmfast/21cmEMU
src/py21cmemu/model_utils.py
.py
6d93ab55497daf12
7.45
7
"""PyTorch implementation of the v1 21cmEMU default emulator. This module provides the PyTorch model class for the v1 emulator, originally implemented in TensorFlow/Keras. The model was converted using the convert_v1_to_pytorch.py script. Usage ----- from py21cmemu.models.ACG.v1_pytorch import load_converted_mode...
21cmfast/21cmEMU
src/py21cmemu/models/acg/v1_pytorch.py
.py
a1095689726b3f12
7.45
7
""" Neural-network modules for the 21cm MH emulator (v3). This module defines the HybridEmulator architecture used for inference. Architecture matches the production_ema training checkpoint. """ import torch import torch.nn as nn class _LSTMHead(nn.Module): """Single LSTM head producing a 1-D sequence. Pro...
21cmfast/21cmEMU
src/py21cmemu/models/mcg/lstm_model.py
.py
d56eec287b2a500f
7.45
7
import logging from pathlib import Path import torch device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") def extract(a, t, x_shape): batch_size = t.shape[0] out = a.cpu().gather(-1, t.cpu()) return out.reshape(batch_size, *((1,) * (len(x_shape) - 1))).to(t.device) def t...
21cmfast/21cmEMU
src/py21cmemu/utils.py
.py
37f2fe28eaf796c0
7.45
7
"""Tests for emulator download / data initialisation (get_emulator.py). These tests require network access and modify the on-disk emulator cache. They are excluded from the standard fast test run with: -k "not test_config and not test_get_emulator" """ from __future__ import annotations import shutil from pathlib ...
21cmfast/21cmEMU
tests/test_get_emulator.py
.py
5eb5aa99b2fb1d14
7.95
7
"""Get current fuel prices and station detail for a specific GasBuddy station.""" import argparse import asyncio import logging from py_gasbuddy import GasBuddy from py_gasbuddy.exceptions import APIError, LibraryError FUEL_LABELS = { "regular_gas": "Regular", "midgrade_gas": "Midgrade", "premium_gas": "...
firstof9/py-gasbuddy
examples/price-lookup.py
.py
abb435e7b107fe14
7.63
17
"""Cache functions for py-gasbuddy.""" import asyncio import json import logging import os import uuid from pathlib import Path from typing import Any import aiofiles import aiofiles.os _LOGGER = logging.getLogger(__name__) class GasBuddyCache: """Class for GasBuddy file cache.""" def __init__(self, cache...
firstof9/py-gasbuddy
py_gasbuddy/cache.py
.py
e81151ca403886ba
7.63
17
"""Exceptions for library.""" class MissingSearchData(Exception): """Exception for missing search data variable.""" class LibraryError(Exception): """Exception for a general library failure.""" class CloudflareBlocked(LibraryError): """Cloudflare blocked the CSRF/token-fetch round-trip. Subclass ...
firstof9/py-gasbuddy
py_gasbuddy/exceptions.py
.py
1ee71c22c61a0e3c
7.63
17
"""Type definitions for py-gasbuddy.""" from typing import Any, Required, TypedDict class Address(TypedDict, total=False): """Station address.""" line1: Required[str] line2: str | None locality: str region: str postalCode: str country: str class Brand(TypedDict): """Station brand i...
firstof9/py-gasbuddy
py_gasbuddy/models.py
.py
966b3f9a3df99ba7
7.63
17
"""Provide common pytest fixtures.""" import json import os import shutil import tempfile from collections import defaultdict from collections.abc import Callable, Generator from pathlib import Path from typing import Any from unittest.mock import patch import aiohttp import pytest from multidict import CIMultiDict, ...
firstof9/py-gasbuddy
tests/conftest.py
.py
3f57665aec37bc05
8.13
17
#!/usr/bin/env python3 """ Resource consumption test script for testing resource monitoring tools. Consumes various amounts of VSS, RSS, and CPU over configurable time periods. """ import argparse import json import mmap import multiprocessing import os import time from typing import Any, Dict class ResourceConsumer...
con/duct
demo/resource_consumer.py
.py
da4805aae513c8fd
7.56
12
"""Summary formatter with custom conversions for con-duct output.""" from __future__ import annotations from datetime import datetime import logging import string from typing import Any lgr = logging.getLogger("con-duct") # Decimal (SI) byte units shared by SummaryFormatter.naturalsize (run # summary) and the plot ...
con/duct
src/con_duct/_formatter.py
.py
b290322471e88b0e
7.56
12
"""Signal handlers for con-duct.""" from __future__ import annotations import logging import os import signal from types import FrameType from typing import Optional lgr = logging.getLogger("con-duct") class SigIntHandler: """ Handler of SIGINT signals received by the process running duct. """ def ...
con/duct
src/con_duct/_signals.py
.py
0455397f117846e9
7.56
12
"""Process tracking and reporting for con-duct.""" from __future__ import annotations from dataclasses import asdict from importlib.metadata import version import json import logging import math import os import platform import shutil import socket import subprocess import threading import time from typing import Any,...
con/duct
src/con_duct/_tracker.py
.py
4e4d501d458876c9
7.56
12
"""Utility functions for con-duct.""" from typing import Any def assert_num(*values: Any) -> None: for value in values: assert isinstance(value, (float, int)) # TODO: consider asking ps for `etimes` (seconds) directly via # `-o etimes` instead of parsing `etime`. Even if we switch, this # parser is wor...
con/duct
src/con_duct/_utils.py
.py
3167909e07206ac9
7.56
12
"""Centralized JSON file type detection and loading for duct.""" from __future__ import annotations import json from typing import Any from con_duct._constants import SUFFIXES # Suffixes that use JSON Lines format JSONL_SUFFIXES = (SUFFIXES["usage"], SUFFIXES["usage_legacy"]) def is_jsonl_file(path: str) -> bool: ...
con/duct
src/con_duct/json_utils.py
.py
61d37821ff8df3cc
7.56
12
"""Resource-usage plotting for con-duct. Renders a per-pid CPU / rss cloud overlaid by envelopes: max-across-pids as a lower bound, and either ``totals.*`` from the record (RSS, and CPU in ``ps-pcpu`` mode) or sum-across-pids of the derived values (CPU in ``ps-cpu-timepoint`` mode) as the upper bound. CPU lives on the...
con/duct
src/con_duct/plot.py
.py
575ae9a782e890b8
7.56
12
import argparse import json import logging from pprint import pprint from typing import Any from con_duct._formatter import SummaryFormatter from con_duct.json_utils import is_jsonl_file, load_info_file, load_usage_file lgr = logging.getLogger(__name__) def get_field_conversion_mapping() -> dict[str, str]: """ ...
con/duct
src/con_duct/pprint_json.py
.py
fc48a25def3c22c3
7.56
12
import logging import os from pathlib import Path from typing import Generator import pytest @pytest.fixture(scope="session", autouse=True) def set_test_config() -> Generator: # set DUCT_SAMPLE_INTERVAL and DUCT_REPORT_INTERVAL to small values # to speed up testing etc. Those could be overridden by a specific...
con/duct
test/conftest.py
.py
7d71cc964af2656d
8.06
12
#!/usr/bin/env python3 from __future__ import annotations import argparse import sys import time def consume_cpu(duration: int, load: int) -> None: """Function to consume CPU proportional to 'load' for 'duration' seconds""" end_time = time.time() + duration while time.time() < end_time: for _ in r...
con/duct
test/data/test_script.py
.py
a3470177635137ba
8.06
12
"""Tests for utility functions in _duct_main.py""" import pytest from con_duct._utils import ( assert_num, etime_to_etimes, is_same_pid, pdcpu_from_pcpu, ) @pytest.mark.parametrize("input_value", [0, 1, 2, -1, 100, 0.001, -1.68]) def test_assert_num_green(input_value: int) -> None: assert_num(inp...
con/duct
test/duct_main/test_duct_utils.py
.py
3f429009bc4c67c6
8.06
12
from __future__ import annotations import json import os from pathlib import Path import platform import subprocess import time import pytest from con_duct._constants import SUFFIXES SYSTEM = platform.system() TEST_SCRIPT_DIR = Path(__file__).parent.parent / "data" # Allow overriding the duct executable for testing ex...
con/duct
test/duct_main/test_e2e.py
.py
0a74d949458622c5
8.06
12
from __future__ import annotations import json import logging import multiprocessing import os from pathlib import Path import signal import subprocess import sys from time import sleep, time import pytest from utils import assert_files, run_duct_command from con_duct import _duct_main from con_duct._constants import S...
con/duct
test/duct_main/test_execution.py
.py
b85dd0c3295302a9
7.06
12
import argparse import os import platform import re import subprocess from typing import Any, Optional import unittest from unittest import mock from unittest.mock import MagicMock, patch import pytest from con_duct import cli from con_duct.cli import _create_run_parser SYSTEM = platform.system() class TestSuiteHelp...
con/duct
test/test_cli.py
.py
613cf081abf9e8a3
8.06
12
from __future__ import annotations import logging import os from pathlib import Path import sys from unittest.mock import patch import pytest from con_duct import cli @pytest.fixture def temp_env_files(tmp_path: Path) -> dict[str, Path]: """Create temporary .env files for testing.""" # System-level config ...
con/duct
test/test_env_files.py
.py
ab435dc28a38b00c
7.06
12
import os from unittest import mock import pytest from con_duct._formatter import SummaryFormatter from con_duct._tracker import Report GREEN_START = SummaryFormatter.COLOR_SEQ % SummaryFormatter.GREEN RED_START = SummaryFormatter.COLOR_SEQ % SummaryFormatter.RED @mock.patch("con_duct._duct_main.LogPaths") @mock.pat...
con/duct
test/test_formatter.py
.py
e070c72914dd838e
7.06
12
import argparse import contextlib from io import StringIO import json import logging import os import tempfile from typing import Any, Dict, Optional import unittest from unittest.mock import mock_open, patch import pytest from con_duct._constants import __schema_version__ from con_duct._formatter import SummaryFormatt...
con/duct
test/test_ls.py
.py
becf7a18c6ed9094
8.06
12