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 |
|---|---|---|---|---|---|---|
"""Tests for QuickSourceReader"""
import pytest
from stream2py.source_reader import QuickSourceReader
class SimpleQuickReader(QuickSourceReader):
"""A simple QuickSourceReader that reads from a list"""
def __init__(self, data):
self.data = iter(data)
def read(self):
try:
retu... | i2mint/stream2py | stream2py/tests/test_quick_source_reader.py | .py | b223027c5545ab7c | 7.85 | 4 |
"""Tests for using readers without context manager (Issue #18)"""
import pytest
from stream2py import StreamBuffer
from stream2py.tests.utils_for_testing import SimpleSourceReader
from stream2py.exceptions import StreamNotStartedError
def test_mk_reader_requires_started_buffer():
"""Test that mk_reader() raises c... | i2mint/stream2py | stream2py/tests/test_reader_without_context.py | .py | cb28ad8218b7cab6 | 7.85 | 4 |
"""Sorted Deque that handles Reader-Writer Priority"""
from contextlib import contextmanager
from typing import Generator
from stream2py.utility.reader_writer_lock import RWLock
from stream2py.utility.sorted_deque import SortedDeque
class RWLockSortedDeque(RWLock):
"""
>>> import operator
>>> locked_deq... | i2mint/stream2py | stream2py/utility/locked_sorted_deque.py | .py | 5b9765a7e7c4c5ba | 7.35 | 4 |
"""READER-WRITER LOCK WITH PRIORITY FOR WRITERS"""
# From: http://code.activestate.com/recipes/577803-reader-writer-lock-with-priority-for-writers/
# Created by Mateusz Kobos on Fri, 22 Jul 2011
# Licensed under the MIT License
import threading
__author__ = "Mateusz Kobos"
class RWLock:
"""Synchronization objec... | i2mint/stream2py | stream2py/utility/reader_writer_lock.py | .py | 51db74ce34029e87 | 7.35 | 4 |
"""Sequence sorted by a key function."""
# Take from: https://code.activestate.com/recipes/577197-sortedcollection/
# Found from: https://docs.python.org/3.7/library/bisect.html
# Created by Raymond Hettinger on Fri, 16 Apr 2010
# Licensed under the MIT License
from bisect import bisect_left, bisect_right
class Sort... | i2mint/stream2py | stream2py/utility/sorted_collection.py | .py | 4888e6021b07f0f8 | 7.35 | 4 |
"""Deque sorted by a key function."""
from bisect import bisect_left, bisect_right
from collections import deque
from itertools import islice
from stream2py.utility.sorted_collection import SortedCollection
class SortedDeque(SortedCollection):
"""Deque sorted by a key function.
Intent of SortedDeque is to ... | i2mint/stream2py | stream2py/utility/sorted_deque.py | .py | 4ea11b5e6de9df9d | 7.35 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# 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 ... | Ensembl/ensembl-genes | pipelines/gene_symbol_classifier/filter_assignments.py | .py | b27c279a6592a6d8 | 7.35 | 4 |
#!/usr/bin/env python3
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# 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
#
# htt... | Ensembl/ensembl-genes | src/python/ensembl/genes/content/main_static_content.py | .py | f8425a360e31a4e8 | 7.35 | 4 |
#!/usr/bin/env python3
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# 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
#
# htt... | Ensembl/ensembl-genes | src/python/ensembl/genes/content/main_static_murine_content.py | .py | 4abcc907ec9cbad5 | 7.35 | 4 |
#!/usr/bin/env python3
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# 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
#
# htt... | Ensembl/ensembl-genes | src/python/ensembl/genes/info_from_registry/assign_species_prefix.py | .py | 128cbeb3a76eb122 | 7.85 | 4 |
#!/usr/bin/env python3
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# 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
#
# htt... | Ensembl/ensembl-genes | src/python/ensembl/genes/info_from_registry/assign_stable_space.py | .py | fb9ee222c8d9cc13 | 7.35 | 4 |
#!/usr/bin/env python3
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# 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
#
# htt... | Ensembl/ensembl-genes | src/python/ensembl/genes/info_from_registry/create_config.py | .py | 2ecc783c2c6d93e0 | 7.35 | 4 |
#!/usr/bin/env python3
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# 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
#
# htt... | Ensembl/ensembl-genes | src/python/ensembl/genes/info_from_registry/create_pipe_reg.py | .py | 85a617448d80428b | 7.35 | 4 |
#!/usr/bin/env python3
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# 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
#
# htt... | Ensembl/ensembl-genes | src/python/ensembl/genes/info_from_registry/genebuild_start_pipeline.py | .py | eaa668aeef771f12 | 7.35 | 4 |
#!/usr/bin/env python3
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# 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
#
# htt... | Ensembl/ensembl-genes | src/python/ensembl/genes/info_from_registry/seed_nonvert.py | .py | 86d8e56c876532c8 | 7.35 | 4 |
#!/usr/bin/env python3
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# 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
#
# htt... | Ensembl/ensembl-genes | src/python/ensembl/genes/info_from_registry/write_metrics_to_registry.py | .py | 432906d21348c7f1 | 7.35 | 4 |
#!/usr/bin/env python3
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# 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
#
# htt... | Ensembl/ensembl-genes | src/python/ensembl/genes/metadata/bioproject_from_registry.py | .py | 462e879711cc4c23 | 7.35 | 4 |
#!/usr/bin/env python3
# pylint: disable=missing-module-docstring
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may ... | Ensembl/ensembl-genes | src/python/ensembl/genes/metrics/busco_lineage_selector.py | .py | 2f978b8b69fd4d5b | 7.35 | 4 |
#!/usr/bin/env python3
# pylint: disable=missing-module-docstring
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may ... | Ensembl/ensembl-genes | src/python/ensembl/genes/metrics/busco_metakeys_patch.py | .py | 4e556b07a2218e06 | 7.35 | 4 |
#!/usr/bin/env python3
# pylint: disable=missing-module-docstring
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may ... | Ensembl/ensembl-genes | src/python/ensembl/genes/metrics/check_busco_score.py | .py | d7704a30726dc9d8 | 7.35 | 4 |
"""
Changelog comparison logic for project YAML files.
Compares a newly generated YAML against a previous version and reports
added, removed, and modified entries in a human-readable format.
"""
import re
from typing import Any, Dict, List, Optional, Tuple
import yaml
# Fields that are internal / audit-only and sho... | Ensembl/ensembl-genes | src/python/ensembl/genes/projects/changelog.py | .py | 5ee4b972a95a9178 | 7.35 | 4 |
"""
Project configuration mappings determining data fetch behavior and YAML schema rules.
"""
from dataclasses import dataclass
from typing import List, Optional
@dataclass
class ProjectConfig: # pylint: disable=too-many-instance-attributes
"""
Directs the pipeline on what data sources are allowed and how t... | Ensembl/ensembl-genes | src/python/ensembl/genes/projects/config.py | .py | 4b547cd135b4a1ac | 7.35 | 4 |
"""FTP/HTTP helpers for checking Ensembl/EBI file and beta-page availability."""
import socket
import sys
import time
from ftplib import FTP, error_perm, error_temp
from typing import Any, Optional
import requests
class EnsemblFTP:
"""
Robust FTP client for Ensembl/EBI with reconnect + tolerant shutdown.
... | Ensembl/ensembl-genes | src/python/ensembl/genes/projects/ftp_client.py | .py | ea3d5a3a7ea15876 | 7.35 | 4 |
#!/usr/bin/env python3
"""
Main entry point for generating project-specific genome metadata YAML files.
Usage:
python -m ensembl.genes.projects.generate_project_yaml input_guuids.txt \
--project vgp --output species.yaml --audit-file audit.tsv
"""
import argparse
import json
import logging
import sys
from collec... | Ensembl/ensembl-genes | src/python/ensembl/genes/projects/generate_project_yaml.py | .py | 90780956c8f093f2 | 7.35 | 4 |
"""
Data fetcher for the Ensembl Metadata database.
"""
import logging
from typing import Dict, List, Optional
import pymysql
from ensembl.genes.projects.models import GenomeMetadata
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class MetadataDbClient:
"""Queries the Ensembl Met... | Ensembl/ensembl-genes | src/python/ensembl/genes/projects/registry/metadata_db.py | .py | aeeb223443c79f20 | 7.35 | 4 |
"""
Data fetcher for NCBI via Entrez HTTP endpoints.
Performs web scraping for submitters and HPRC population data.
"""
import logging
import re
from typing import Optional
import requests
from ensembl.genes.projects.models import GenomeMetadata
from ensembl.genes.projects.config import ProjectConfig
logger = loggi... | Ensembl/ensembl-genes | src/python/ensembl/genes/projects/registry/ncbi_entrez.py | .py | 65ab4cd883f737d4 | 7.35 | 4 |
"""
Read helpers built on Maya API 2.0 (maya.api.OpenMaya).
Everything here only reads the scene; state changes stay in maya.cmds so they remain undoable.
The readers report the same vocabulary as maya.cmds (getAttr -type names, getAttr values), so the
rest of the package relies on one set of type names. Rare attribut... | dLantee/pop | python/pop/mapiutils.py | .py | af814c904d0f48b7 | 7 | 0 |
"""Every copy of the version number must agree with pop.__version__."""
import re
import unittest
from pathlib import Path
import pop
ROOT = Path(__file__).resolve().parents[1]
def read(name):
return (ROOT / name).read_text(encoding='utf-8')
class VersionTest(unittest.TestCase):
def test_changelog_newest... | dLantee/pop | tests/test_version.py | .py | 86b35d0c666c3ca2 | 7.5 | 0 |
from city_furniture.enums import CityFurnitureClassType, CityFurnitureFunctionType
from city_furniture.models import FurnitureSignpostPlan, FurnitureSignpostReal
from city_furniture.models.common import CityFurnitureDeviceType
from traffic_control.management.commands.base_create_dummy_device_type import (
BaseCreat... | City-of-Helsinki/city-infrastructure-platform | city_furniture/management/commands/create_dummy_city_furniture_device_type.py | .py | cddff12044f47716 | 7.39 | 5 |
# Generated by Django 4.2.26 on 2025-12-15 11:10
from django.db import migrations
def set_dummy_device_type_for_null_values(apps, schema_editor):
"""
Create or get the DummyDT device type and set it for all devices with null device_type.
This must be done before making the field non-nullable.
"""
... | City-of-Helsinki/city-infrastructure-platform | city_furniture/migrations/0026_set_device_type_non_nullable.py | .py | 7ebf3510c43e0f65 | 7.39 | 5 |
#! python3 # noqa: E265
from PyQt6.QtWidgets import (
QAbstractItemView,
QTableWidget,
QTableWidgetItem,
QVBoxLayout,
QWidget,
)
from dicogis.utils.texts import TextsManager
class ScrollableTable(QWidget):
"""
A scrollable table with two columns in read-only mode.
Attributes:
... | Guts/DicoGIS | dicogis/ui/scrollable_table.py | .py | 1a2670ec0caf20dc | 7.39 | 5 |
import os
import argparse
from astropy.io import fits
import numpy as np
def validate_files(filenames, check_is_file=True):
try:
validated = os.path.expanduser(filenames)
if check_is_file and not os.path.isfile(validated):
raise IOError('%s does not exist' % validated)
except Attri... | folguinch/go-continuum | argparse_actions.py | .py | b8ad2ab90d3aa19b | 7.3 | 3 |
"""Data structures to manage information."""
from typing import Optional
from dataclasses import dataclass, asdict, InitVar
from pathlib import Path
@dataclass
class Environ():
"""Structures the go-continuum environment."""
basedir: Path = Path('./')
"""Base directory."""
uvdata: Optional[Path] = None
... | folguinch/go-continuum | go_continuum/environment.py | .py | 47ccc4f45762338e | 7.3 | 3 |
"""Argparse parent parsers commonly used."""
from typing import Callable, Optional, Union
import argparse
import pathlib
import warnings
from casatasks import casalog
#from .functions import positions_to_pixels
from .argparse_actions import StartLogger, ReadQuantity, MakePath
def source_position(
required: bool ... | folguinch/go-continuum | go_continuum/moved_helpers/argparse_parents.py | .py | 7fa646875e9cd96f | 7.3 | 3 |
"""Utilities for working with CASA."""
from typing import (Optional, Sequence, List, TypeVar, Callable, Mapping, Any,
Tuple, Dict)
from inspect import signature
from collections import OrderedDict
import astropy.units as u
import numpy.typling as npt
from casatasks import vishead
from .common_type... | folguinch/go-continuum | go_continuum/moved_helpers/utils.py | .py | f852f55cf920a8dc | 7.3 | 3 |
"""Tools for processing argument parser inputs."""
from typing import TypeVar
from pathlib import Path
import configparser as cparser
import casa_utils as utils
# Types
NameSpace = TypeVar('NameSpace')
def set_config(args: NameSpace):
"""Setup the `config` value in `args`.
It assumes:
- A `configfile` ... | folguinch/go-continuum | go_continuum/old/args_proc.py | .py | 07b41d93d5bd9243 | 7.3 | 3 |
"""Setup the logging system for CASA scripts."""
from typing import TypeVar
import argparse
from casatasks import casalog
# Types
NameSpace = TypeVar('NameSpace')
def logging_parent() -> argparse.ArgumentParser:
"""Get `argparse` parent for logging file name."""
parser = argparse.ArgumentParser(add_help=Fals... | folguinch/go-continuum | go_continuum/old/casa_logging.py | .py | 4a9abce3d98290c2 | 7.3 | 3 |
from configparser import ConfigParser
from pathlib import Path
from typing import Sequence
import argparse
import sys
from casatasks import tclean, exportfits
# Local utils
#aux = os.path.dirname(sys.argv[2])
#sys.path.insert(0, aux)
import casa_logging
import casa_utils as utils
def run_tclean(log, **kwargs):
"... | folguinch/go-continuum | go_continuum/old/run_clean.py | .py | 73802b2acbf3e03c | 7.3 | 3 |
"""
Sphinx Auto-SaltSLS top-level extension
"""
import os
from jinja2 import Environment, FileSystemLoader
from sphinx.errors import ExtensionError
from sphinx.util import logging
# noinspection PyUnresolvedReferences
from sphinx.util.console import darkgreen, bold
from .mapper import AutoSaltSLSMapper
__author__ =... | Tanoti/sphinxcontrib-autosaltsls | sphinxcontrib/autosaltsls/__init__.py | .py | 7c0008a8e502bc50 | 7.15 | 1 |
"""
AutoSaltSLS mapper class
"""
import os
import pathlib
from jinja2 import Environment, FileSystemLoader
from sphinx.errors import ExtensionError
from sphinx.util import logging, status_iterator
# noinspection PyUnresolvedReferences
from sphinx.util.console import darkgreen, bold
from .objects import AutoSaltSLS
... | Tanoti/sphinxcontrib-autosaltsls | sphinxcontrib/autosaltsls/mapper.py | .py | 30cf148c1f2bf3ee | 7.15 | 1 |
# pylint: disable=W0621
"""Asynchronous Python client for BSBLan.
This example demonstrates the optimized hot water functionality:
- HotWaterState: Essential parameters for frequent polling (5 fields)
- HotWaterConfig: Configuration parameters checked less frequently (16 fields)
- HotWaterSchedule: Time program schedu... | liudger/python-bsblan | examples/control.py | .py | d35621a3c0af0b91 | 7.39 | 5 |
"""Discovery utility for finding BSB-LAN devices on the network.
Uses mDNS/Zeroconf to discover BSB-LAN devices without needing hardcoded IPs.
Usage:
from discovery import discover_bsblan, get_bsblan_host
# Get host (from env or mDNS discovery)
host, port = await get_bsblan_host()
# Or discover all ... | liudger/python-bsblan | examples/discovery.py | .py | 340f49f68924ac85 | 7.39 | 5 |
"""Fetch BSB-LAN parameters and print the raw API response.
Uses BSB-LAN's URL commands (https://docs.bsb-lan.de/using.html):
- ``/JQ`` (default): query current parameter values.
- ``/JC`` (``--structure``): dump the parameter structure, including data
type, read/write flag, unit, and enum ``possibleValues``. Usefu... | liudger/python-bsblan | examples/fetch_param.py | .py | 3a54c4577978fe89 | 7.39 | 5 |
"""Profile BSBLAN initialization to identify performance bottlenecks.
This script profiles the initialization process of the BSBLAN library
to help identify slow operations that affect Home Assistant startup time.
Usage:
# Basic profiling with auto-discovery or BSBLAN_HOST env var
uv run python examples/profi... | liudger/python-bsblan | examples/profile_init.py | .py | 1b6706b7e58861d5 | 7.39 | 5 |
"""Hot water domain logic for BSB-LAN."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, TypeVar
from .constants import ErrorMsg, HotWaterParams
from .exceptions import BSBLANError, BSBLANUnsupportedFeatureError
from .models import (
HotWaterConfig,
HotWaterSchedule,
HotWaterSt... | liudger/python-bsblan | src/bsblan/_hot_water.py | .py | 3df623f187fa198a | 7.39 | 5 |
"""Low-level parameter lookup and read helpers for BSB-LAN."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, cast
from .constants import ErrorMsg
from .exceptions import BSBLANError
from .models import EntityInfo
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable
... | liudger/python-bsblan | src/bsblan/_parameters.py | .py | a13d739be1d43faa | 7.39 | 5 |
"""Heating and hot water schedule domain logic for BSB-LAN."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from .constants import ErrorMsg, HeatingScheduleParams, HotWaterParams
from .exceptions import BSBLANError, BSBLANUnsupportedFeatureError
from .models import HeatingTimeSwitchProgra... | liudger/python-bsblan | src/bsblan/_schedules.py | .py | 3dbd13ae1a193375 | 7.39 | 5 |
"""Temperature range, unit, and bounds management for the BSBLAN client.
Owns the per-circuit temperature range cache, the set of circuits whose range
has been initialized, and the active temperature unit. Ranges are lazily
fetched from the device static values and target temperatures are validated
against the heating... | liudger/python-bsblan | src/bsblan/_temperature.py | .py | 0ecc4577a7f510c6 | 7.39 | 5 |
"""Thermostat write preparation for BSB-LAN."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from .constants import CircuitConfig, Validation
from .exceptions import BSBLANInvalidParameterError
if TYPE_CHECKING:
from collections.abc import Callable
from ._temperature import Temp... | liudger/python-bsblan | src/bsblan/_thermostat.py | .py | fc382fb758952c62 | 7.39 | 5 |
"""HTTP transport layer for the BSBLAN client.
Owns the low-level concerns of talking to a BSB-LAN device: URL building,
authentication, headers, request execution with exponential-backoff retries,
and firmware-specific response post-processing. The owning client keeps a
stable ``_request`` facade that delegates here.... | liudger/python-bsblan | src/bsblan/_transport.py | .py | a8db55ffcb89adf6 | 7.39 | 5 |
"""Lazy section/group validation for the BSBLAN client.
Owns the on-demand validation of API sections and hot water parameter groups,
including the per-key locks that serialize concurrent first-time validation,
the set of already-validated hot water groups, and the hot water parameter
cache. The owning client keeps th... | liudger/python-bsblan | src/bsblan/_validation.py | .py | 2575d1468f7993dc | 7.39 | 5 |
"""API capability resolution for the BSBLAN client.
Owns the policy that maps a device's reported BSB-LAN JSON-API version (from
``/JV``) to a supported API configuration. The JSON-API version is the
documented, firmware-independent compatibility signal and is the sole input for
selecting the configuration. The adapte... | liudger/python-bsblan | src/bsblan/_version.py | .py | 86978883d254b301 | 7.39 | 5 |
"""Utility functions for BSB-LAN integration."""
from __future__ import annotations
import logging
import re
from dataclasses import dataclass, field
from typing import Any
from .constants import CircuitConfig
logger = logging.getLogger(__name__)
def validate_time_format(
time_value: str,
min_year: int,
... | liudger/python-bsblan | src/bsblan/utility.py | .py | e680f77fce247bfa | 7.39 | 5 |
"""Tests for BSBLAN authentication."""
# file deepcode ignore W0212: this is a testfile
# pylint: disable=protected-access
from aiohttp.helpers import BasicAuth
from bsblan import BSBLAN
from bsblan.bsblan import BSBLANConfig
from bsblan.exceptions import BSBLANAuthError
def test_get_auth_without_credentials() -> ... | liudger/python-bsblan | tests/test_auth.py | .py | e7e52e167bd0d320 | 7.89 | 5 |
"""Test edge cases in bsblan.py for 100% coverage."""
from __future__ import annotations
from typing import Any
from unittest.mock import AsyncMock, MagicMock
import aiohttp
import pytest
from bsblan import BSBLAN, BSBLANConfig
from bsblan.exceptions import (
BSBLANConnectionError,
BSBLANError,
BSBLANMa... | liudger/python-bsblan | tests/test_bsblan_edge_cases.py | .py | fd7c99939372f610 | 7.89 | 5 |
"""Tests for BSBLAN configuration methods."""
# file deepcode ignore W0212: this is a testfile
# pylint: disable=protected-access
import pytest
from bsblan import BSBLAN
from bsblan.bsblan import BSBLANConfig
from bsblan.constants import ErrorMsg
from bsblan.exceptions import BSBLANError
def test_build_url() -> No... | liudger/python-bsblan | tests/test_configuration.py | .py | aec192e8656a6738 | 7.89 | 5 |
"""Tests for retrieving hotwater information from the BSBLAN device."""
# pylint: disable=duplicate-code
# pylint: disable=protected-access
# file deepcode ignore W0212: this is a testfile
import json
from typing import Any
from unittest.mock import AsyncMock
import aiohttp
import pytest
from bsblan import BSBLAN, ... | liudger/python-bsblan | tests/test_hotwater_state.py | .py | 4015e9149ea288dc | 7.89 | 5 |
"""Test cases for schedule models (TimeSlot, DaySchedule, DHWSchedule)."""
from __future__ import annotations
from datetime import time
import pytest
from bsblan.models import DaySchedule, DHWSchedule, HeatingSchedule, TimeSlot
class TestTimeSlot:
"""Test cases for TimeSlot dataclass."""
def test_valid_t... | liudger/python-bsblan | tests/test_schedule_models.py | .py | 7acbe0e704197671 | 7.89 | 5 |
#!/usr/bin/env python3
"""
把 Hexo/NoteBook 源目录里的图片拷到 Chirpy 的 assets/img/posts/<slug>/,
并修正 _posts 里已经写坏的路径(Windows 反斜杠、残留的 uploads 前缀)。
用法:
python tools/sync_post_images.py <hexo文章目录>
"""
import re
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from hexo_to_jekyll im... | MillerWu2014/MillerWu2014.github.io | tools/sync_post_images.py | .py | 307e0123dbde4bab | 7.15 | 1 |
import io
import pandas as pd
class DataHandler:
"""
Handles conversion of data series.
Parameters
----------
series : pandas.Series
Data as series.
"""
def __init__(self, series):
if not isinstance(series, pd.Series):
raise ValueError()
if not series... | 4Subsea/drio-python | datareservoirio/_utils.py | .py | b1351bfff22cf56a | 7.24 | 2 |
import json
import logging
import os
from abc import ABCMeta, abstractmethod
from oauthlib.oauth2 import (
BackendApplicationClient,
InvalidGrantError,
MissingTokenError,
WebApplicationClient,
)
from requests.adapters import HTTPAdapter
from requests_oauthlib import OAuth2Session
from urllib3 import Re... | 4Subsea/drio-python | datareservoirio/authenticate.py | .py | 0acc6b3045bc43db | 7.24 | 2 |
import io
import logging
import os
from collections import OrderedDict
import pandas as pd
from ..appdirs import WINDOWS, _win_path
log = logging.getLogger(__name__)
_BYTES_PER_ROW = 128 // 8
class CacheIO:
"""
Basic cache related disk operations.
"""
@staticmethod
def... | 4Subsea/drio-python | datareservoirio/storage/cache_engine.py | .py | c46fc88708f1bd8d | 7.24 | 2 |
import base64
import io
import logging
import os
import re
import shutil
import timeit
from threading import RLock as Lock
import pandas as pd
import requests
from ..appdirs import user_cache_dir
from .cache_engine import CacheIO, _CacheIndex
log = logging.getLogger(__name__)
_BLOBSTORAGE_SESSION =... | 4Subsea/drio-python | datareservoirio/storage/storage.py | .py | 7702f6cbfc2dd669 | 7.24 | 2 |
import datetime
from random import uniform
NORMAL_HOURS_KEY = 'n'
PEAK_HOURS_KEY = 'p'
NORMAL_MAX_PERIOD_MINUTES = 60
NORMAL_MIN_PERIOD_MINUTES = 20
NORMAL_DEFAULT_PERIOD_MINUTES = 40
NORMAL_MAX_DELAY_MINUTES = 20
PEAK_MAX_PERIOD_MINUTES = 35
PEAK_MIN_PERIOD_MINUTES = 15
PEAK_DEFAULT_PERIOD_MINUTES = 25
PEAK_MAX_DEL... | rrryanc/WebScraping | schedule.py | .py | 5ae595b2debdb940 | 7 | 0 |
import logging
LOGGER = logging.getLogger(__name__)
ADDED_MAP_KEY = 'added_map'
REMOVED_MAP_KEY = 'removed_map'
DEFAULT_LINK_FORMATTER = lambda _id,_name: str(_name)
#add a method to convert all to string
#todo return a list rather than string for easier unit tests
def format_notification_message(results_dictionary,... | rrryanc/WebScraping | utils/message_formatter.py | .py | 33c5aa70ac4523e1 | 7 | 0 |
import datetime
from random import uniform
def to_minutes(hours, minutes):
"""Return input in minutes.
hours -- current hours to be converted
minutes -- currents minutes added to converted hours
"""
return hours * 60 + minutes
def get_current_day_hour_minute():
"""Return the current day, ho... | rrryanc/WebScraping | utils/schedule_utils.py | .py | aa18f1f5be5971f9 | 7 | 0 |
import logging
from pathlib import Path
import settings
from scheduler.condor import CondorScheduler
from scheduler.scheduler import EScheduler
from scheduler.slurm import SlurmScheduler
logger = logging.getLogger(__name__)
def working_directory(details, *args, **kwargs):
if isinstance(details, dict) and "job_i... | gravitationalwavedc/gwcloud_bilby | bundle/core/misc.py | .py | 765b92f321688889 | 7 | 0 |
import logging
from pathlib import Path
import _bundledb
import settings
from scheduler.scheduler import EScheduler
from scheduler.status import JobStatus
from core.misc import get_scheduler
logger = logging.getLogger(__name__)
def get_submit_status(job):
"""
Gets the status of the job submission step for ... | gravitationalwavedc/gwcloud_bilby | bundle/core/status.py | .py | 1f1cb3c91370cecf | 7 | 0 |
import logging
from pathlib import Path
import htcondor
from .scheduler import Scheduler
from .status import JobStatus
logger = logging.getLogger(__name__)
class CondorScheduler(Scheduler):
"""
Condor scheduler
"""
def submit(self, script, working_directory):
"""
Submits a script u... | gravitationalwavedc/gwcloud_bilby | bundle/scheduler/condor.py | .py | 49b246544c9c097d | 7 | 0 |
import logging
import subprocess
from typing import ClassVar
from .scheduler import Scheduler
from .status import JobStatus
logger = logging.getLogger(__name__)
class SlurmScheduler(Scheduler):
"""
Slurm scheduler
"""
SLURM_STATUS: ClassVar[dict[str, str]] = {
"BOOT_FAIL": "Job terminated d... | gravitationalwavedc/gwcloud_bilby | bundle/scheduler/slurm.py | .py | e75f36007918aa0a | 7 | 0 |
import contextlib
import os
from pathlib import Path
from tempfile import NamedTemporaryFile
from bilby_pipe.parser import create_parser
def args_to_bilby_ini(args):
"""
Generates an ini string from the provided args
:param args: The args to add to the ini string
:return: A string containing the ini... | gravitationalwavedc/gwcloud_bilby | bundle/tests/utils.py | .py | db7897d5d676f5c1 | 7.5 | 0 |
import fcntl
import logging
import os
import re
import sqlite3
import sys
from datetime import datetime
from pathlib import Path
from tempfile import NamedTemporaryFile
import h5py
import requests
from gwcloud_python import GWCloud
from gwdc_python.exceptions import GWDCUnknownException
logger = logging.getLogger("gw... | gravitationalwavedc/gwcloud_bilby | gwosc_cron/gwosc_ingest.py | .py | 526e5773b837388c | 7 | 0 |
from hashlib import sha256
from typing import Iterable, Optional
from django.conf import settings
from django.core.validators import RegexValidator
from django.db import models, transaction
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from hels... | City-of-Helsinki/kukkuu | children/models.py | .py | ceb606ed029da8a7 | 7 | 0 |
import logging
from functools import wraps
from threading import Thread
from typing import Optional
logger = logging.getLogger(__name__)
def execute_in_background(
thread_name: Optional[str] = None, daemonic: Optional[bool] = None
):
"""A decorator to execute a function in a new thread in background.
Ar... | City-of-Helsinki/kukkuu | common/decorators.py | .py | 3f5199d7d25ecf55 | 7 | 0 |
from enum import Enum
from io import BytesIO
import qrcode
import qrcode.image.pil
import qrcode.image.svg
class QRCodeFileFormatEnum(Enum):
"""
ENUM to hold the allowed values for QRCode fileformat
"""
SVG: str = "svg"
PNG: str = "png"
FACTORIES = {
QRCodeFileFormatEnum.SVG.value: qrcode.... | City-of-Helsinki/kukkuu | common/qrcode_service.py | .py | b1818326e92ad22f | 7 | 0 |
import graphene
from django.conf import settings
from django.core.exceptions import PermissionDenied
from graphene_django import DjangoConnectionField
from graphene_django.filter import DjangoFilterConnectionField
from common.utils import get_node_id_from_global_id, get_obj_from_global_id
from kukkuu.exceptions import... | City-of-Helsinki/kukkuu | common/schema.py | .py | 63900825fe813a35 | 7 | 0 |
"""
Get RSS feed
"""
import re
import pathlib
import feedparser
root = pathlib.Path(__file__).parent.parent.resolve()
def replace_chunk(content, marker, chunk):
""" Swap out placeholders """
replacer = re.compile(
r"<!\-\- {} starts \-\->.*<!\-\- {} ends \-\->".format(marker, marker),
re.DOTAL... | thechelsuk/thechelsuk | python/get_blog_posts.py | .py | 404908d00d64c97a | 7.3 | 3 |
#!/usr/bin/env python3
"""
Add subtitles to all blog posts that don't have them.
This script processes both English and Portuguese posts systematically.
"""
import os
import re
import yaml
from pathlib import Path
def extract_frontmatter_and_content(file_path):
"""Extract YAML frontmatter and content from a markd... | helmedeiros/blog | scripts/add_all_subtitles.py | .py | ee89802dc18a17fd | 7 | 0 |
#!/usr/bin/env python3
"""
Add subtitles to blog posts that don't have them.
Keeps English and Portuguese versions in sync.
"""
import os
import re
import yaml
from pathlib import Path
# Subtitle mappings for posts based on their titles and content
SUBTITLES = {
# Hello World and Early Posts
"2008-05-12-hello... | helmedeiros/blog | scripts/add_subtitles.py | .py | a640a92b4ca55c37 | 7 | 0 |
#!/usr/bin/env python3
"""
Blog Translation Script with Backup and Batch Control
This script provides options to:
1. Backup existing English posts
2. Process posts in batches
3. Resume from where you left off
4. Selective translation
"""
import os
import shutil
import argparse
from datetime import datetime
from pathl... | helmedeiros/blog | scripts/backup_and_translate.py | .py | 635eb73280d623f6 | 7 | 0 |
#!/usr/bin/env python3
"""
Clean up leftover date fragments in English translation files
"""
import re
from pathlib import Path
def clean_date_fragments(content):
"""Remove leftover date fragments from frontmatter"""
lines = content.split('\n')
cleaned_lines = []
in_frontmatter = False
for line ... | helmedeiros/blog | scripts/clean_leftover_date_fragments.py | .py | 13269f5f776c2c07 | 7 | 0 |
#!/usr/bin/env python3
"""
Clean up already translated markdown files by removing unwanted prefixes
"""
import re
from pathlib import Path
def clean_translation_prefixes(content):
"""Remove translation prefixes from content"""
prefixes_to_remove = [
"Here is the translation of the text from Brazilian ... | helmedeiros/blog | scripts/clean_translated_files.py | .py | cc84a3cc435190a7 | 7 | 0 |
#!/usr/bin/env python3
"""
Clean up translated posts by fixing YAML frontmatter and removing LLM artifacts
"""
import os
import re
from pathlib import Path
def clean_frontmatter_title(content):
"""Clean up title field in YAML frontmatter"""
lines = content.split('\n')
cleaned_lines = []
in_frontmatter... | helmedeiros/blog | scripts/cleanup_translated_posts.py | .py | d318ad7d7e7cf2f4 | 7 | 0 |
#!/usr/bin/env python3
"""
Copy correct date fields from Portuguese files to English files
"""
import re
from pathlib import Path
def extract_date_from_file(file_path):
"""Extract the date field from a markdown file"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read... | helmedeiros/blog | scripts/copy_dates_from_portuguese.py | .py | d56c5e9a55481241 | 7 | 0 |
#!/usr/bin/env python3
import os
import re
import glob
# Mapping of filenames to appropriate titles
TITLE_MAPPINGS = {
"2013-06-26-agile-unlocking-our-human-potential-patrick-kua.md": "Agile: Unlocking Our Human Potential - Patrick Kua",
"2012-08-24-1a-semana-de-lightningtalks-e-fishbowls-no-tecnopuc.md": "Fir... | helmedeiros/blog | scripts/fix_all_titles.py | .py | 3f5bf96006688fb2 | 7 | 0 |
#!/usr/bin/env python3
"""
Fix all YAML frontmatter issues in English translation files
"""
import re
from pathlib import Path
def fix_yaml_frontmatter(content, file_path):
"""Fix YAML frontmatter issues"""
if not content.startswith('---'):
return content
# Split content into frontmatter and bod... | helmedeiros/blog | scripts/fix_all_yaml_issues.py | .py | 17d4d5e3a76433bf | 7 | 0 |
#!/usr/bin/env python3
"""Fix the WordPress migration `[<img.../>][N]` markup that Hugo renders broken.
The legacy WordPress markup wraps an HTML `<img>` tag inside a markdown
reference-link `[link-text][N]`. Hugo's markdown engine doesn't render this
correctly — the `[` and `]` leak through as visible characters.
Tw... | helmedeiros/blog | scripts/fix_broken_wp_images.py | .py | 05592c084d0ebf51 | 7 | 0 |
#!/usr/bin/env python3
import os
import re
import glob
def extract_title_from_filename(filename):
"""Extract a meaningful title from the filename"""
# Remove path and extension
basename = os.path.basename(filename)
name_without_ext = os.path.splitext(basename)[0]
# Remove date prefix (YYYY-MM-DD-)... | helmedeiros/blog | scripts/fix_empty_titles.py | .py | b66b0d0173a40a7e | 7 | 0 |
#!/usr/bin/env python3
"""
Fix corrupted line breaks in English translation files
The English files have been corrupted and lost their line breaks,
making them single-line files. This script restores proper formatting.
"""
import re
from pathlib import Path
def fix_line_breaks(content):
"""Restore proper line br... | helmedeiros/blog | scripts/fix_line_breaks.py | .py | dd4ca67895c10028 | 7 | 0 |
#!/usr/bin/env python3
"""
Fix remaining issues in English translations:
1. Replace remaining placeholders with appropriate content
2. Fix mixed language issues
3. Clean up specific problematic patterns
"""
import os
import re
from pathlib import Path
def fix_placeholders_in_content(content, file_path):
"""Replac... | helmedeiros/blog | scripts/fix_remaining_issues.py | .py | 285d8806bf83a757 | 7 | 0 |
#!/usr/bin/env python3
"""
Fix translation linking issues by removing conflicting URL parameters.
This script removes 'url' parameters from post front matter that prevent
Hugo from properly detecting translations between EN and PT versions.
"""
import os
import re
from pathlib import Path
def process_markdown_file(f... | helmedeiros/blog | scripts/fix_translation_links.py | .py | 8ec6c507e55f500a | 7 | 0 |
#!/usr/bin/env python3
"""
Fix broken title quotes in YAML frontmatter
"""
import re
from pathlib import Path
def fix_yaml_title(content):
"""Fix broken title quotes in YAML frontmatter"""
lines = content.split('\n')
fixed_lines = []
in_frontmatter = False
for line in lines:
if line.stri... | helmedeiros/blog | scripts/fix_yaml_titles.py | .py | e053e4bd733a0791 | 7 | 0 |
#!/usr/bin/env python3
"""Check whether the GA4 instrumentation is measuring what we think it is.
Run this before and after each rollout phase. It reports the handful of
numbers that reveal whether tracking is sound, with an explicit verdict
per check, so "did that change work?" has an answer instead of a vibe.
Usage... | helmedeiros/blog | scripts/ga_health_check.py | .py | 869e3b08e75a674f | 7 | 0 |
#!/usr/bin/env python3
"""
Convert translated markdown files to Hugo content structure
This script takes our translated English markdown files and creates proper
Hugo content files that can be used to regenerate the HTML blog structure.
"""
import os
import re
from pathlib import Path
import shutil
def parse_frontma... | helmedeiros/blog | scripts/markdown_to_hugo.py | .py | 715b3de2b310f863 | 7 | 0 |
#!/usr/bin/env python3
"""
Comprehensive review and cleanup of English translations
This script identifies and fixes common issues in the translated posts:
1. LLM artifacts and instructions
2. Placeholder text that wasn't replaced
3. Broken links and references
4. Mixed language content
5. Formatting issues
6. YAML fr... | helmedeiros/blog | scripts/review_and_cleanup_english.py | .py | 99adfccec4f4bf8d | 7 | 0 |
#!/usr/bin/env python3
"""
Strip the legacy "Series Navigation" trailing block from migrated posts.
Posts have already been migrated to the front-matter `series:` convention,
so the new card widget renders from layouts. This script removes the
hand-written markdown block that the WordPress migration left behind.
Bloc... | helmedeiros/blog | scripts/strip_old_series_widget.py | .py | 781841949f6c3de1 | 7 | 0 |
#!/usr/bin/env python3
"""Strip leftover manual series navigation from EN/PT posts.
Two patterns are handled, both conservative:
1. Top-of-post blockquote banner (one line + the blank after):
> **Series: X** | **Part N of M** > _description_
> **Série: X** | **Parte N de M** > _description_
> **Series: X*... | helmedeiros/blog | scripts/strip_top_series_banner.py | .py | 9d751ebf79a798b0 | 7 | 0 |
#!/usr/bin/env python3
"""Copy Hugo `series:` taxonomy from EN posts to their PT counterparts.
For each PT post that:
- lacks a `series:` field in its frontmatter, AND
- has an EN counterpart at content/en/posts/<same-filename> with `series:` set
…copy the `series:` block and the `series_order:` line from EN to P... | helmedeiros/blog | scripts/sync_pt_series_taxonomy.py | .py | 3ec37392983c4b5a | 7 | 0 |
#!/usr/bin/env python3
"""
Test script to translate a single blog post
"""
import os
import re
import json
import subprocess
from pathlib import Path
from bs4 import BeautifulSoup
def extract_content_from_html(html_file_path):
"""Extract title and content from HTML file"""
with open(html_file_path, 'r', encod... | helmedeiros/blog | scripts/test_single_translation.py | .py | 1d169298f90dd648 | 7.5 | 0 |
#!/usr/bin/env python3
"""
Translate all remaining markdown files with automatic cleanup
This script translates files and automatically runs cleanup after each batch
to ensure no prefixes slip through.
"""
import subprocess
import time
from pathlib import Path
def run_cleanup():
"""Run the cleanup script"""
... | helmedeiros/blog | scripts/translate_all_with_cleanup.py | .py | 50a0493eac7bd901 | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.