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 |
|---|---|---|---|---|---|---|
import os
import pytest
from leverage.modules.tfrunner import TFRunner
from leverage._utils import ExitError
@pytest.fixture
def mock_tofu_binary(mocker):
"""Mock tofu binary availability and version check"""
mocker.patch("shutil.which", return_value="/usr/bin/tofu")
mock_subprocess = mocker.patch("subp... | binbashar/leverage | tests/test_modules/test_tfrunner.py | .py | 4e9f6a76a54cef3e | 7.16 | 20 |
from pathlib import Path
from unittest.mock import patch
import pytest
from leverage import path as lepath
from leverage._utils import ExitError
from leverage.path import (
get_home_path,
PathsHandler,
get_working_path,
get_account_config_path,
get_global_config_path,
get_build_script_path,
... | binbashar/leverage | tests/test_path.py | .py | 316f14f7c0b69d2e | 8.16 | 20 |
from subprocess import CalledProcessError
from unittest.mock import patch, MagicMock
import pytest
from leverage.path import get_root_path, NotARepositoryError
class TestGetRootPath:
@pytest.fixture(autouse=True)
def setup_method(self):
"""Setup common test resources and mock patches."""
sel... | binbashar/leverage | tests/test_root_path.py | .py | 0d0502fe6be044d1 | 8.16 | 20 |
"""
Download-and-cache the open_dvm example dataset (raw or processed) from OSF.
Mirrors MNE-Python's own dataset-fetching convention (``mne.datasets.sample``),
using ``pooch`` under the hood -- ``pooch`` is already a transitive dependency
via ``mne``, so no new dependency is introduced.
Two independent datasets are ... | dvanmoorselaar/open_dvm | open_dvm/support/datasets.py | .py | 8df3baad847de614 | 7.64 | 18 |
"""
Eye tracking utility functions for the DvM Toolbox.
This module provides standalone utility functions for eye tracking
data processing that are used across multiple analysis modules.
Functions
--------------
exclude_eye : Trial exclusion based on eye movements
Filters trials with fixation breaks using either ... | dvanmoorselaar/open_dvm | open_dvm/support/eye_utils.py | .py | e1ceaefddf93b560 | 7.64 | 18 |
"""
Support functions for plotting
Created by Dirk van Moorselaar on 30-03-2016.
Copyright (c) 2016 DvM. All rights reserved.
"""
from typing import List, Optional, Tuple, Union
import matplotlib
import matplotlib.colors as mcolors
import numpy as np
def shifted_color_map(cmap, min_val, max_val, name):
"""Func... | dvanmoorselaar/open_dvm | open_dvm/visualization/plot_utils.py | .py | a0f5ddaa6004eb86 | 7.64 | 18 |
"""
Pytest configuration and shared fixtures for open_dvm tests.
This file defines pytest fixtures and configuration used across all tests.
"""
import tempfile
import numpy as np
import pytest
from tests.fixtures.sample_data import (
create_biosemi64_evoked_pair,
create_lateralization_test_data,
create_... | dvanmoorselaar/open_dvm | tests/conftest.py | .py | da47cb2c3f8c6e8e | 8.14 | 18 |
"""
Sample data fixtures for testing open_dvm.analysis.BDM functionality.
"""
import mne
import numpy as np
import pandas as pd
def make_separable_epochs(
n_trials: int = 80,
n_ch: int = 4,
n_samples: int = 50,
sfreq: float = 100,
seed: int = 0,
separable_from_sample=None,
label_column: s... | dvanmoorselaar/open_dvm | tests/fixtures/bdm_sample_data.py | .py | 1c3e79d59795ffcc | 8.14 | 18 |
"""
Sample data builders for testing open_dvm.analysis.CTF.
These construct synthetic mne.EpochsArray + behavioral DataFrame pairs
with a genuine, decodable spatial signal (channel i biased when the
trial's position bin == i), so that CTF/IEM reconstruction has a real,
checkable pattern to recover rather than pure noi... | dvanmoorselaar/open_dvm | tests/fixtures/ctf_sample_data.py | .py | 3deda025d03e9500 | 8.14 | 18 |
"""
Sample data fixtures for testing open_dvm.analysis.EEG functionality.
"""
import os
import mne
import numpy as np
import pandas as pd
from open_dvm.analysis.EEG import RAW, Epochs
def make_synthetic_raw(
ch_names: list,
ch_types,
data: np.ndarray = None,
sfreq: float = 250,
n_samples: int =... | dvanmoorselaar/open_dvm | tests/fixtures/eeg_sample_data.py | .py | 88b0433a0031d266 | 8.14 | 18 |
"""
Sample raw eye-tracker file builders for testing
open_dvm.support.eye_readers.
These construct synthetic .asc (EyeLink EDF-derived ASCII) and .tsv
(EyeTribe) file content matching the real formats closely enough to
exercise the parsers, without needing real recorded data.
"""
def _asc_event(prefix9, *fields):
... | dvanmoorselaar/open_dvm | tests/fixtures/eye_readers_sample_data.py | .py | 038ef1333201699e | 8.14 | 18 |
"""
Sample data builders for testing open_dvm.analysis.EYE (EYE and
SaccadeDetector classes).
Two kinds of builders are provided:
- Trial-dict builders (`make_trial`) for unit-testing methods that
operate directly on the parsed trial-dict contract (interp_trial,
get_xy, ...), without needing real files on disk.
- ... | dvanmoorselaar/open_dvm | tests/fixtures/eye_sample_data.py | .py | 80d4edc795e09048 | 8.14 | 18 |
"""
Sample data fixtures for testing open_dvm.support.FolderStructure.
All writer functions take an explicit `root` directory and write into
the standard DvM folder convention (eeg/processed, behavioral/raw,
erp/evoked, tfr/<method>, bdm/<path>, ctf/<path>) beneath it. Callers
are expected to have already chdir'd (or ... | dvanmoorselaar/open_dvm | tests/fixtures/folder_structure_sample_data.py | .py | 6899b1ec0a0b9941 | 8.14 | 18 |
"""
Sample data fixtures for testing open_dvm.visualization.plot functionality.
"""
import mne
import numpy as np
def make_condition_evokeds(
amplitudes: dict,
ch_names=("C3", "C5", "C4", "C6"),
n_subjects: int = 5,
sfreq: float = 200,
tmin: float = -0.1,
n_samples: int = 60,
noise_sd: fl... | dvanmoorselaar/open_dvm | tests/fixtures/plot_sample_data.py | .py | 1e6784c53e1e2f1a | 8.14 | 18 |
"""
Sample data fixtures for testing open_dvm functionality.
This module provides utilities for generating synthetic EEG data suitable
for testing ERP analysis functions.
"""
from typing import Dict, Tuple
import mne
import numpy as np
import pandas as pd
from mne import EpochsArray, create_info
def create_sample_... | dvanmoorselaar/open_dvm | tests/fixtures/sample_data.py | .py | b90fadcec05c21b5 | 8.14 | 18 |
"""
Sample data fixtures for testing open_dvm.analysis.TFR functionality.
"""
import mne
import numpy as np
import pandas as pd
def make_epochs(
ch_names=("C3", "C4"),
n_trials=10,
n_samples=100,
sfreq=200.0,
tmin=-0.2,
seed=0,
):
"""Plain noise epochs with no particular oscillatory conte... | dvanmoorselaar/open_dvm | tests/fixtures/tfr_sample_data.py | .py | b285dc4ca5cad55d | 8.14 | 18 |
"""
Test suite for open_dvm.support.datasets.
Organization
------------
- TestGetCacheDir: cache-directory resolution (path arg > env var > default)
- TestFetchArchive: pooch.create()/fetch() called with the right arguments
- TestFetchRawData / TestFetchProcessedData: correct archive dict used
"""
from pathlib import... | dvanmoorselaar/open_dvm | tests/test_support/test_datasets.py | .py | aee3fbf73649f857 | 7.14 | 18 |
"""
Test suite for open_dvm.support.eye_utils.
Organization
------------
- TestExcludeEye: exclude_eye trial-exclusion behavior
"""
import mne
import numpy as np
import pandas as pd
from open_dvm.support.eye_utils import exclude_eye
def _make_epochs_and_df(n_trials=5, n_times=50, sfreq=250, ch_names=("Fz", "Cz")):... | dvanmoorselaar/open_dvm | tests/test_support/test_eye_utils.py | .py | 37d6b7363c75ec52 | 8.14 | 18 |
"""
The doctor module provides functionality to check the health of the `exasol_integration_test_docker_environment`
package and also provide help to find potential fixes.
"""
import sys
from collections.abc import (
Callable,
Iterable,
)
from enum import Enum
import docker
from docker.errors import DockerExc... | exasol/integration-test-docker-environment | exasol_integration_test_docker_environment/doctor.py | .py | 900ca31c1be0fcca | 7.92 | 6 |
import hashlib
import json
import logging
import shutil
from collections.abc import Generator
from pathlib import Path
from typing import (
Any,
TypeVar,
)
import luigi
from luigi import (
Task,
util,
)
from luigi.parameter import ParameterVisibility
from luigi.task import TASK_ID_TRUNCATE_HASH
from e... | exasol/integration-test-docker-environment | exasol_integration_test_docker_environment/lib/base/base_task.py | .py | de44893ff9d3f75f | 7.92 | 6 |
import time
from abc import abstractmethod
from typing import (
Protocol,
runtime_checkable,
)
import fabric
from docker import DockerClient
from docker.models.containers import (
Container,
ExecResult,
)
from paramiko.ssh_exception import NoValidConnectionsError
from exasol_integration_test_docker_en... | exasol/integration-test-docker-environment | exasol_integration_test_docker_environment/lib/base/db_os_executor.py | .py | 2d34045edac76c57 | 7.92 | 6 |
import logging
from docker.models.containers import Container
from exasol_integration_test_docker_environment.lib.docker import ContextDockerClient
def remove_docker_container(containers: list[str]):
"""
Removes the given container using docker API.
"""
with ContextDockerClient() as docker_client:
... | exasol/integration-test-docker-environment | exasol_integration_test_docker_environment/lib/docker/container/utils.py | .py | 5b5d9e01de33d7a0 | 7.92 | 6 |
# pynot-instrument-module
"""
Instrument definitions for NOT/ALFOSC
"""
import numpy as np
import os
import datetime
from os.path import dirname, abspath
from astropy.io import fits
from astropy.table import Table
name = 'alfosc'
# absolute path from code directory [DO NOT CHANGE]
path = dirname(abspath(__file__))
#... | jkrogager/PyNOT | pynot/alfosc.py | .py | e1960a59d7050cca | 7.45 | 7 |
# -*- coding: UTF-8 -*-
"""
Input / Output functions for the DataSet class.
"""
from astropy.io import fits
import numpy as np
import warnings
from pynot.data.organizer import TagDatabase
from pynot import instrument
veclen = np.vectorize(len)
# Function to save dataset: data/io.py
def get_header_info(fname):
... | jkrogager/PyNOT | pynot/data/io.py | .py | caffe586d8f50c8e | 7.45 | 7 |
from collections import defaultdict
import numpy as np
import os
import warnings
from pynot.data import io
from pynot.data import organizer as do
output_base_phot = 'imaging'
output_base_spec = 'spectra'
class OBDatabase:
def __init__(self, fname):
if os.path.exists(fname):
with warnings.cat... | jkrogager/PyNOT | pynot/data/obs.py | .py | 5458171432145695 | 7.45 | 7 |
import astropy.units as u
import numpy as np
import yaml
import os
import glob
import warnings
from pynot import instrument
path = os.path.dirname(os.path.abspath(__file__))
# --- Data taken from: ftp://ftp.stsci.edu/cdbs/current_calspec/
_standard_star_files = glob.glob(path + '/calib/std/*.dat')
_standard_star_file... | jkrogager/PyNOT | pynot/functions.py | .py | d2a21286762bfda1 | 7.45 | 7 |
"""
Write calibration reports for:
BIAS frames
FLAT frames
ARC frames
RESPONSE functions
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends import backend_pdf
from astropy.io import fits
import os
from pynot import instrument
report_dir = 'reports'
plt.rcParams['font.fami... | jkrogager/PyNOT | pynot/reports.py | .py | 51bfdb12b3209cb1 | 7.45 | 7 |
# -*- coding: utf-8 -*-
"""A PNG writer in forty lines, so the examples need nothing installed.
Pillow would do this better and handle a hundred cases this does not. The point
of the examples is to show what the capture API gives you, and an example whose
first line is `pip install Pillow` teaches the reader about Pil... | Hellikandra/pyDXGID3D | examples/_png.py | .py | fa57840523c1ff47 | 7.5 | 9 |
# -*- coding: utf-8 -*-
"""Shared fixtures and tier gating.
Tier 0 static checks - any OS, no comtypes, no GPU
Tier 1 binding checks - Windows + comtypes; WARP suffices, no GPU
Tier 2 capture checks - real GPU and an interactive desktop session
Tier 3 performance - as tier 2, plus a quiet machine
Tiers 1 ... | Hellikandra/pyDXGID3D | tests/conftest.py | .py | fd2cabd80835c6d1 | 8 | 9 |
# 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 applicable law or agreed to in writing, software
# d... | openstack/ovn-octavia-provider | ovn_octavia_provider/cmd/octavia_ovn_db_sync_util.py | .py | d9182cfc874295de | 7.52 | 10 |
# 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 applicable law or agreed to in writing, software
# d... | openstack/ovn-octavia-provider | ovn_octavia_provider/common/utils.py | .py | 7f8c3a82a31e5ced | 7.52 | 10 |
# Copyright 2026 Red Hat, Inc. All rights reserved.
#
# 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 b... | openstack/ovn-octavia-provider | ovn_octavia_provider/ovn/db_sync.py | .py | feabe453c7a8287f | 7.52 | 10 |
# Copyright 2020 Red Hat, Inc.
#
# 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 applicable law or agre... | openstack/ovn-octavia-provider | ovn_octavia_provider/ovsdb/ovsdb_monitor.py | .py | c1adef0f2784c3d6 | 7.52 | 10 |
#
# 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 applicable law or agreed to in writing, software
# ... | openstack/ovn-octavia-provider | ovn_octavia_provider/tests/unit/base.py | .py | 301131b54e14c9ca | 7.02 | 10 |
# Copyright 2022 Red Hat, Inc.
# All Rights Reserved.
#
# 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... | openstack/ovn-octavia-provider | ovn_octavia_provider/tests/unit/common/test_utils.py | .py | f90191c35252af2a | 7.02 | 10 |
# Copyright 2015
#
# 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 applicable law or agreed to in wr... | openstack/ovn-octavia-provider | ovn_octavia_provider/tests/unit/hacking/test_checks.py | .py | 45bf805f19caff05 | 7.02 | 10 |
# Copyright 2026 Red Hat, Inc. All rights reserved.
#
# 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 b... | openstack/ovn-octavia-provider | ovn_octavia_provider/tests/unit/ovn/test_db_sync.py | .py | 0803fb2ef32dc0b5 | 8.02 | 10 |
#
# 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 applicable law or agreed to in writing, software
# ... | openstack/ovn-octavia-provider | ovn_octavia_provider/tests/unit/ovsdb/test_ovsdb_monitor.py | .py | c077d8cc80bba553 | 7.02 | 10 |
from __future__ import annotations
from typing import TYPE_CHECKING, List, Optional
if TYPE_CHECKING:
from autocti.clocker.abstract import AbstractClocker
import autofit as af
class AggBase(af.AggBase):
def __init__(
self,
aggregator: af.Aggregator,
use_dataset_full: boo... | PyAutoLabs/PyAutoCTI | autocti/aggregator/abstract.py | .py | 48da905e40d597fb | 7.42 | 6 |
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Optional, Union
from autocti.aggregator.abstract import AggBase
if TYPE_CHECKING:
from autocti.model.model_util import CTI1D
from autocti.model.model_util import CTI2D
import autofit as af
logger = logging.getLog... | PyAutoLabs/PyAutoCTI | autocti/aggregator/cti.py | .py | cb9f41b0b75ed056 | 7.42 | 6 |
from __future__ import annotations
from typing import TYPE_CHECKING, List, Optional
from autocti.aggregator.abstract import AggBase
if TYPE_CHECKING:
from autocti.clocker.abstract import AbstractClocker
from autocti.dataset_1d.fit import FitDataset1D
import autofit as af
from autocti.aggregator.dataset_1d i... | PyAutoLabs/PyAutoCTI | autocti/aggregator/fit_dataset_1d.py | .py | c3f147c21d9bbc25 | 7.42 | 6 |
from __future__ import annotations
from typing import TYPE_CHECKING, List, Optional, Union
if TYPE_CHECKING:
from autocti.clocker.abstract import AbstractClocker
from autocti.model.model_util import CTI1D
from autocti.model.model_util import CTI2D
from autocti.charge_injection.fit import FitImagingCI
... | PyAutoLabs/PyAutoCTI | autocti/aggregator/fit_imaging_ci.py | .py | 0b3de74542f94486 | 7.42 | 6 |
import copy
from typing import Dict, Optional
import autoarray as aa
from autocti.preloads import Preloads
from autocti.charge_injection.imaging.imaging import ImagingCI
class FitImagingCI(aa.FitImaging):
def __init__(
self,
dataset: ImagingCI,
post_cti_data: aa.Array2D,
... | PyAutoLabs/PyAutoCTI | autocti/charge_injection/fit.py | .py | 52dbf24bc96ffa9c | 7.42 | 6 |
from typing import Optional
class HyperCINoiseScalar(float):
def __new__(cls, scale_factor=0.0):
return super().__new__(cls, scale_factor)
def __init__(self, scale_factor=0.0):
"""
The hyper_ci-parameter factor by which the noises is scaled when included in the model-fitting ... | PyAutoLabs/PyAutoCTI | autocti/charge_injection/hyper.py | .py | 972d53019412dfab | 7.42 | 6 |
import copy
import autoarray as aa
from typing import Tuple
class SettingsImagingCI:
def __init__(
self,
parallel_pixels: Tuple[int, int] = None,
serial_pixels: Tuple[int, int] = None,
):
super().__init__()
self.parallel_pixels = parallel_pixels
... | PyAutoLabs/PyAutoCTI | autocti/charge_injection/imaging/settings.py | .py | e92f2daad9d525fa | 7.42 | 6 |
from autofit import mock
from autofit.non_linear.result import ResultsCollection
class MockResult(mock.MockResult):
def __init__(
self,
samples=None,
instance=None,
model=None,
analysis=None,
search=None,
mask=None,
model_image=None,
... | PyAutoLabs/PyAutoCTI | autocti/charge_injection/mock/mock_result.py | .py | 5ad00a67e175e031 | 7.42 | 6 |
import math
import numpy as np
from typing import List, Union
from arcticpy import CCDPhase
from arcticpy import TrapInstantCapture
from autocti.instruments.euclid import euclid_util
from autoarray.layout import layout_util
from autoarray.structures.arrays.uniform_2d import Array2D
from autocti.clocker.two_d import... | PyAutoLabs/PyAutoCTI | autocti/charge_injection/ou_sim_ci.py | .py | 6ec3bdf8e6a13ac5 | 7.42 | 6 |
from arcticpy import CCD
from arcticpy import CCDPhase
from autonerves.dictable import from_json, output_to_json
class AbstractClocker:
def __init__(self, iterations: int = 1, verbosity: int = 0):
"""
An abstract clocker, which wraps the c++ arctic CTI clocking algorithm in **PyAutoCTI**... | PyAutoLabs/PyAutoCTI | autocti/clocker/abstract.py | .py | bd72df9a55864498 | 7.42 | 6 |
import astropy.io.fits as pyfits
import numpy as np
from os import path
from scipy.interpolate import interp1d
from typing import Tuple
import autoarray as aa
class SimulatorCosmicRayMap:
def __init__(
self,
shape_native: Tuple[int, int],
lengths: np.ndarray,
distances: np.ndarray... | PyAutoLabs/PyAutoCTI | autocti/cosmics/cosmics.py | .py | 299ed6431a6e9331 | 7.42 | 6 |
import autoarray as aa
from autocti.dataset_1d.dataset_1d.dataset_1d import Dataset1D
class FitDataset1D(aa.FitDataset):
def __init__(self, dataset: Dataset1D, post_cti_data):
"""
Fit a 1D CTI dataset with model cti data.
Parameters
----------
dataset
... | PyAutoLabs/PyAutoCTI | autocti/dataset_1d/fit.py | .py | 22bf8a39262c72a1 | 7.42 | 6 |
"""Nox sessions."""
import platform
from nox_poetry import Session, session
python_versions = ["3.10", "3.11", "3.12"]
@session(python=python_versions)
def tests(session: Session) -> None:
"""Run the test suite."""
session.install(
"invoke",
"pytest",
"xdoctest",
"coverage[t... | fedejaure/mdns-beacon | noxfile.py | .py | 60564a9655678926 | 7.65 | 19 |
"""Base mDNS Beacon module."""
import asyncio
import logging
from abc import ABC, abstractmethod
from typing import Optional
from zeroconf import IPVersion, Zeroconf
logger = logging.getLogger(__name__)
class BaseBeacon(ABC):
"""mDNS Beacon base class.
Note:
Derived beacons must override the `_exe... | fedejaure/mdns-beacon | src/mdns_beacon/base.py | .py | cdb3b0c580595186 | 7.65 | 19 |
"""Beacon module."""
import logging
import time
from ipaddress import IPv4Address, IPv6Address, ip_address
from typing import Any, Dict, List, Optional, Union
from slugify import slugify
from typing_extensions import Literal
from zeroconf import IPVersion, ServiceInfo
from .base import BaseBeacon
logger = logging.g... | fedejaure/mdns-beacon | src/mdns_beacon/beacon.py | .py | 0d54d1cbbf397eff | 7.65 | 19 |
"""Console layout for mdns-beacon."""
from abc import ABC, abstractmethod
from typing import Any, ClassVar, Dict, List, Optional, Tuple, Union
from rich.console import RenderableType
from rich.live import Live
from rich.spinner import Spinner
from rich.table import Table
from rich.text import Text
from zeroconf impor... | fedejaure/mdns-beacon | src/mdns_beacon/cli/layouts.py | .py | 3a2ba0a32fc1f5af | 7.65 | 19 |
"""Param types for mdns-beacon."""
from ipaddress import IPv4Address, IPv6Address, ip_address
from typing import AnyStr, Optional, Union
import click
class IpAddress(click.ParamType):
"""An IPv4Address or IPv6Address parsed via ipaddress.ip_address.
Example:
>>> ptype = IpAddress()
>>> ptyp... | fedejaure/mdns-beacon | src/mdns_beacon/cli/types.py | .py | 6a8c1f2bd62bd7ae | 7.65 | 19 |
"""mDNS listener module."""
import logging
from typing import Callable, ClassVar, List, Optional, Set, Union
from zeroconf import IPVersion, ServiceBrowser, ServiceListener, ZeroconfServiceTypes
from .base import BaseBeacon
logger = logging.getLogger(__name__)
class BeaconListener(BaseBeacon):
"""mDNS Beacon ... | fedejaure/mdns-beacon | src/mdns_beacon/listener.py | .py | 14bae3cfd004bb29 | 7.65 | 19 |
"""Tasks for maintaining the project.
Execute 'invoke --list' for guidance on using Invoke
"""
import platform
import webbrowser
from pathlib import Path
from typing import Optional
from invoke import call, task
from invoke.context import Context
from invoke.runners import Result
ROOT_DIR = Path(__file__).parent
DO... | fedejaure/mdns-beacon | tasks.py | .py | 3fae03e8ea97884f | 7.65 | 19 |
"""Context Managers utils tests module."""
import contextlib
import os
import signal
import threading
import time
from typing import Generator
@contextlib.contextmanager
def raise_keyboard_interrupt(*, timeout: float) -> Generator[None, None, None]:
"""Start a thread that raise a KeyboardInterrupt in `timeout`."... | fedejaure/mdns-beacon | tests/helpers/contextmanager.py | .py | 932bbc01a7d633ca | 8.15 | 19 |
"""Tests for `base` module."""
from asyncio import AbstractEventLoop
from typing import Optional
import pytest
from zeroconf import IPVersion
from mdns_beacon.base import BaseBeacon
from .helpers.contextmanager import raise_keyboard_interrupt
class DummyBeacon(BaseBeacon):
"""Dummy Beacon for testing purpose.... | fedejaure/mdns-beacon | tests/test_base.py | .py | fe1434d579c19335 | 8.15 | 19 |
"""Tests for `beacon` module."""
from asyncio import AbstractEventLoop
from typing import Any, Dict, Set
from uuid import uuid4
import pytest
from zeroconf import IPVersion
from mdns_beacon.beacon import Beacon
from .helpers.contextmanager import raise_keyboard_interrupt
@pytest.mark.slow
@pytest.mark.parametrize... | fedejaure/mdns-beacon | tests/test_beacon.py | .py | fcf083699b0a1bbe | 7.15 | 19 |
"""Tests for `mdns_beacon.cli.layouts` module."""
from contextlib import ExitStack
from io import StringIO
from typing import ContextManager, Optional, Tuple, Type
import pytest
from pytest_mock import MockerFixture
from rich.console import Console, RenderableType
from rich.live import Live
from rich.spinner import S... | fedejaure/mdns-beacon | tests/test_cli/test_layouts.py | .py | 17f5414a25795c37 | 8.15 | 19 |
"""Tests for `mdns_beacon.cli.main` module."""
from asyncio import AbstractEventLoop
from typing import List
from uuid import uuid4
import pytest
from click.testing import CliRunner
from pytest_mock import MockerFixture
import mdns_beacon
from mdns_beacon.cli.main import main
from ..helpers.contextmanager import ra... | fedejaure/mdns-beacon | tests/test_cli/test_main.py | .py | 28a40c95d212ee10 | 8.15 | 19 |
"""Tests for `mdns_beacon.cli.types` module."""
from contextlib import ExitStack
from ipaddress import IPv4Address, IPv6Address
from typing import ContextManager, Optional, Union
import pytest
from click.exceptions import BadParameter
from mdns_beacon.cli.types import IpAddress
@pytest.mark.parametrize(
"addre... | fedejaure/mdns-beacon | tests/test_cli/test_types.py | .py | 22a11b61a35dc46f | 7.15 | 19 |
"""Tests for `listener` module."""
from asyncio import AbstractEventLoop
from typing import Any, Dict, Set
import pytest
from zeroconf import IPVersion
from mdns_beacon.listener import BeaconListener
from .helpers.contextmanager import raise_keyboard_interrupt
@pytest.mark.slow
@pytest.mark.parametrize(
"beac... | fedejaure/mdns-beacon | tests/test_listener.py | .py | 09c86aceee1fdb32 | 7.15 | 19 |
from pathlib import Path
from alfasim_sdk._internal.alfacase import case_description
def generate_alfacase_file(
alfacase_description: case_description.CaseDescription, alfacase_file: Path
) -> None:
"""
Dump the case_description to the given alfacase_file, using YAML format.
PvtModels that are of m... | ESSS/alfasim-sdk | src/alfasim_sdk/_internal/alfacase/alfacase.py | .py | 4d845def399e4dbf | 7.66 | 20 |
import inspect
import operator
import sys
from collections import deque
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from enum import EnumMeta
from pathlib import Path
from typing import Any
import attr
import typing_inspect
from barril.curve.curve import Curve
from barril.units... | ESSS/alfasim-sdk | src/alfasim_sdk/_internal/alfacase/generate_schema.py | .py | a9343ca2ef94e0c8 | 7.66 | 20 |
from typing import Any
from strictyaml import YAML
from strictyaml.parser import generic_load
from alfasim_sdk._internal.alfacase.case_description_attributes import DescriptionError
def migrate_alfacase_yaml_to_latest(yaml_contents: str) -> str:
"""
Migrates the given YAML contents of an alfacase file to th... | ESSS/alfasim-sdk | src/alfasim_sdk/_internal/alfacase/migration.py | .py | b2a1d2abe26b4712 | 7.66 | 20 |
import itertools
from collections.abc import Callable, Sequence
from functools import partial
from pathlib import Path, PurePosixPath
from types import ModuleType
from typing import Any, TypeGuard
import attr
from barril.units import Array, Scalar
from alfasim_sdk._internal.alfacase.alfacase_to_case import (
Desc... | ESSS/alfasim-sdk | src/alfasim_sdk/_internal/alfacase/plugin_alfacase_to_case.py | .py | 04b7b6fa1f817679 | 7.66 | 20 |
import attr
from alfasim_sdk._internal.types import BaseField, Group, Tab, Tabs
def _is_tab(value: BaseField) -> bool:
"""
Return either the given value is a Tab/Tabs or not
"""
return isinstance(value, type) and issubclass(value, (Tab, Tabs))
def _is_group(value: BaseField) -> bool:
"""
Re... | ESSS/alfasim-sdk | src/alfasim_sdk/_internal/alfacase/plugin_introspection.py | .py | 663b3de5ec77f031 | 8.16 | 20 |
from functools import lru_cache
@lru_cache
def register_units() -> None:
"""
Register new categories for Barril and limit the number of units shown to users.
Note: we try to add all combinations of units we find useful, but given that POSC doesn't have all
possible combinations we remove the ones whi... | ESSS/alfasim-sdk | src/alfasim_sdk/_internal/units.py | .py | c80cdada66ebff0b | 7.66 | 20 |
from typing import Any
from attr import Attribute
from attr.validators import deep_iterable, instance_of
def non_empty_str(self: Any, attribute: Attribute, value: Any) -> None:
"""
A validator that raises a ValueError if the initializer is called with a empty string '' or ' '
"""
if not isinstance(v... | ESSS/alfasim-sdk | src/alfasim_sdk/_internal/validators.py | .py | 9270da93a63a5967 | 7.66 | 20 |
from enum import Enum
import attr
from attr import attrib
from attr.validators import instance_of, optional
from barril.units import UnitDatabase
from alfasim_sdk._internal.validators import non_empty_str, valid_unit
class Visibility(Enum):
"""
Controls the visibility of the variable.
- ``Internal``... | ESSS/alfasim-sdk | src/alfasim_sdk/_internal/variables.py | .py | 17991c1c47b22de9 | 7.66 | 20 |
import os
import subprocess
import tempfile
import textwrap
import uuid
from collections.abc import Iterator
from pathlib import Path
from subprocess import CalledProcessError
import pytest
import strictyaml
from _pytest.compat import assert_never
from _pytest.monkeypatch import MonkeyPatch
from alfasim_sdk import co... | ESSS/alfasim-sdk | src/alfasim_sdk/testing/fixtures.py | .py | 58331eae8881804a | 8.16 | 20 |
from pathlib import Path
import invoke
@invoke.task
def build(ctx):
"""
An umbrella task, currently only calls the cog
"""
cog(ctx)
def schema_file_path() -> Path:
return Path(__file__).parent / "src/alfasim_sdk/_internal/alfacase/schema.py"
def case_description_source_file_path() -> Path:
... | ESSS/alfasim-sdk | tasks.py | .py | 0fa9077708a0a3c7 | 7.66 | 20 |
from textwrap import dedent
import numpy as np
from alfasim_sdk import (
Numpy1DArray,
PvtModelPtTableParametersDescription,
convert_alfacase_to_description,
generate_alfacase_file,
generate_alfatable_file,
)
def test_alfatable_has_flow_style_for_numpy_array(tmp_path):
description = PvtModel... | ESSS/alfasim-sdk | tests/alfacase/test_alfatable.py | .py | 6f6f8842202a6187 | 8.16 | 20 |
from pathlib import Path
from barril.units import Scalar
from alfasim_sdk import (
EmulsionDropletSizeModelType,
EmulsionInversionPointModelType,
EmulsionRelativeViscosityModelType,
)
from alfasim_sdk._internal.alfacase.alfacase_to_case import (
DescriptionDocument,
load_case_description,
)
def ... | ESSS/alfasim-sdk | tests/alfacase/test_migration.py | .py | 42179abfcbcf4b22 | 8.16 | 20 |
"""Nox sessions for linting, docs, and testing."""
from __future__ import annotations
import argparse
import shutil
from pathlib import Path
import nox
DIR = Path(__file__).parent.resolve()
nox.options.sessions = ["lint", "tests"]
@nox.session
def lint(session: nox.Session) -> None:
"""Run the linter.
I... | frank1010111/petrelpy | noxfile.py | .py | 33cf23f4c0705ce6 | 7.63 | 17 |
"""Command line tool for working with Petrel input and output formats."""
from __future__ import annotations
import sys
from pathlib import Path
from zipfile import ZipFile
import click
import pandas as pd
from trogon import tui
from petrelpy.gslib import load_from_petrel
from petrelpy.petrel import (
export_pe... | frank1010111/petrelpy | src/petrelpy/cli.py | .py | ca406ef0014c3828 | 7.63 | 17 |
"""Work with gslib geomodel format."""
from __future__ import annotations
import logging
from pathlib import Path
import dask.dataframe as dd
import fastparquet
import numpy as np
import pandas as pd
from scipy.spatial import cKDTree
def load_from_petrel(fin: Path | str, npartitions=60) -> dd.DataFrame:
"""Loa... | frank1010111/petrelpy | src/petrelpy/gslib.py | .py | 708d8c56c908fdea | 7.63 | 17 |
"""Convert between Petrel and various other formats."""
from __future__ import annotations
from pathlib import Path
import pandas as pd
def write_header(df, fname, fill_na=-999):
"""Write header information to a Petrel-readable header file.
Args:
df (DataFrame): header information for wells (does ... | frank1010111/petrelpy | src/petrelpy/petrel.py | .py | 4bc19032f439ab9f | 7.63 | 17 |
"""Work with Eclipse well connection files.
These are a handy export from Petrel that can get you well-specific properties.
"""
from __future__ import annotations
import io
from collections.abc import Iterator
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
COL_NAMES_TRAJECTO... | frank1010111/petrelpy | src/petrelpy/wellconnection.py | .py | 140bc57856b88a86 | 7.63 | 17 |
from typing import Any
import click
import requests
def ensure_status_code(response: requests.Response) -> None:
"""
Ensure that the response status code is 2xx
"""
if not response.ok:
raise requests.HTTPError(
f"Request failed with status code {response.status_code}\n"
... | bo4e/BO4E-python | bo4e_schemas_create_release.py | .py | a51821fdebe53687 | 7.65 | 19 |
"""
This script is run with the 'json_schemas' dependency group (`uv run --group json_schemas ...`).
"""
import importlib
import inspect
import json
import logging
import pkgutil
import re
import sys
from collections.abc import Iterator
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
f... | bo4e/BO4E-python | generate_or_validate_json_schemas.py | .py | 54c1c9807769333b | 7.65 | 19 |
"""Generate documentation assets that Sphinx consumes:
- ``docs/_static/images/bo4e/<pkg>/<Class>.svg`` (per-class diagrams)
- ``docs/_static/tables/compatibility_matrix.csv``
- ``docs/_static/tables/changes_table.csv``
- ``docs/_static/tables/changes/<old>_to_<new>.json``
Prereqs:
- ``bo4e`` binary on PATH (see... | bo4e/BO4E-python | scripts/generate_docs_assets.py | .py | e2c6fc992ae84879 | 7.65 | 19 |
#!/usr/bin/env python
import os
from glob import glob
from setuptools import Extension, setup # type: ignore[import]
def module_name_from_src_path(path: str) -> str:
"""Derive a fully-qualified module name from a file path under ./src.
Cython's default path-to-module logic relies on finding __init__.py fi... | akornatskyy/wheezy.captcha | setup.py | .py | 7dfb925b8e479369 | 7.52 | 10 |
tsequence = tuple([t / 20.0 for t in range(21)])
beziers = {}
def pascal_row(n):
"""Returns n-th row of Pascal's triangle"""
result = [1]
x, numerator = 1, n
for denominator in range(1, n // 2 + 1):
x *= numerator
x /= denominator
result.append(x)
numerator -= 1
if ... | akornatskyy/wheezy.captcha | src/wheezy/captcha/bezier.py | .py | 9178988fa4bbc849 | 7.52 | 10 |
import pandas as pd
from pathlib import Path
""" This module contains functions to access training, validation and testing data
for the river flow (discharge) of the Dranse river in Bioge, France.
Hourly values for the years 2016, 2017, 2018, and 2019.
"""
def get_yearly_flow(year=2016):
""" Re... | maxnolte/river_forecast | river_forecast/training_data_access.py | .py | f96c8115a7495ef9 | 7.42 | 6 |
"""
Utilities for formatting, normalizing and standardizing file and directory paths.
"""
from pathlib import Path
from .._cache import _format_display_path, _get_relative_path, _normalize_path, _normalize_token
def normalize_path(path, sep="/", as_str=True, prepend_dot=False):
# noinspection PyShadowingNames
... | mikeqfu/pyhelpers | pyhelpers/dirs/formatting.py | .py | cc4438d06f4a0f0f | 7.6 | 15 |
"""
Utilities for file system discovery, resource management and directory operations.
"""
import collections.abc
import os
import shutil
from .._cache import _confirmed, _format_display_path, _get_relative_path, _normalize_path, \
_print_failure_message
def _delete_dir(dir_path, confirmation_required=True, ver... | mikeqfu/pyhelpers | pyhelpers/dirs/management.py | .py | e5083c94787ce0a3 | 7.6 | 15 |
"""
Utilities for directory navigation, context-switching and path resolution.
"""
import importlib.resources
import os
from pathlib import Path
from .._cache import _find_file_path, _normalize_path
def cd(*subdir, mkdir=False, cwd=None, back_check=False, as_str=False, normalized=True, **kwargs):
# noinspection... | mikeqfu/pyhelpers | pyhelpers/dirs/navigation.py | .py | 6b7105fd2bcb8ce5 | 7.6 | 15 |
"""
Utilities for validating paths, confirming file existence and sanitizing inputs.
"""
import errno
import os
import re
from .management import get_file_paths
def is_dir_path(dir_path):
"""
Check whether a string is formatted as a directory path.
This function performs a syntax-only check: it does no... | mikeqfu/pyhelpers | pyhelpers/dirs/validation.py | .py | 7b02c6fd86577219 | 7.6 | 15 |
"""
Basic computation/conversion.
"""
import copy
import datetime
import math
import os
import re
import sys
import numpy as np
import pandas as pd
import requests
from .web import fake_requests_headers
from .._cache import _print_failure_message
def get_utc_tai_offset(verbose=False, raise_error=False, url=None):
... | mikeqfu/pyhelpers | pyhelpers/ops/computation.py | .py | 1793deb23dded816 | 7.6 | 15 |
"""
Utilities for Internet-related tasks and data manipulation from online sources.
"""
import html.parser
import importlib.resources
import json
import logging
import pathlib
import random
import re
import secrets
import socket
import sys
import urllib.parse
import requests
from .._cache import _init_requests_sessi... | mikeqfu/pyhelpers | pyhelpers/ops/web.py | .py | fa6cdf250f3197fd | 7.6 | 15 |
"""
Utilities for measuring similarity between textual data.
"""
import re
import numpy as np
from .._cache import _check_dependencies, _remove_punctuation, _vectorize_text
def euclidean_distance_between_texts(txt1, txt2):
# noinspection PyShadowingNames
"""
Computes the Euclidean distance between two ... | mikeqfu/pyhelpers | pyhelpers/text/similarity.py | .py | 9a69ebba07c2cab7 | 7.6 | 15 |
"""
General color utility functions for visualization.
"""
import numpy as np
from .._cache import _check_dependencies
def cmap_discretization(cmap, n_colors):
# noinspection PyShadowingNames
"""
Creates a discrete colormap based on the input.
:param cmap: A colormap instance, e.g. built-in `colorm... | mikeqfu/pyhelpers | pyhelpers/viz/color_utils.py | .py | 96cc6fe62e8391a6 | 7.6 | 15 |
"""
Mapping and geographic data plotting.
This submodule provides high-level wrappers for creating interactive maps using
`Folium <https://python-visualization.github.io/folium/>`_. It includes functions
for calculating optimal map centers and initializing base maps directly from
`GeoPandas <https://geopandas.org/>`_ ... | mikeqfu/pyhelpers | pyhelpers/viz/maps.py | .py | 9e982eca3116aeb2 | 7.6 | 15 |
"""
Global pytest configuration and shared test fixtures.
"""
import pathlib
import pytest
@pytest.fixture(scope='session')
def dat_dir():
"""
Return the absolute path to the test data assets directory.
:return: Path object pointing to ``tests/data/``.
:rtype: pathlib.Path
**Examples**::
... | mikeqfu/pyhelpers | tests/conftest.py | .py | ac53f91695722dfb | 7.1 | 15 |
"""
Test the module ``_cache.py``
"""
import os
import sys
from pathlib import Path
import numpy as np
import pytest
import requests
import shapely.geometry
from pyhelpers._cache import _check_dependencies, _check_url_scheme, _confirmed, _find_file_path, \
_format_display_path, _format_exception_message, _get_an... | mikeqfu/pyhelpers | tests/test__cache.py | .py | d06dbedb8b0b5641 | 8.1 | 15 |
"""
Tests the :mod:`~pyhelpers.dirs.formatting` submodule.
"""
import os
from pathlib import Path
import pytest
from pyhelpers.dirs import format_display_path, get_relative_path, normalize_path, standardize_path
def test_normalize_path():
pathname = normalize_path("tests\\data\\dat.csv")
assert pathname ==... | mikeqfu/pyhelpers | tests/test_dirs/test_formatting.py | .py | f7454d0483a6431d | 8.1 | 15 |
"""
Tests the :mod:`~pyhelpers.dirs.management` submodule.
"""
import os
import pytest
from pyhelpers.dirs import cd, delete_dir, format_display_path, get_file_paths
def test_delete_dir(tmp_path, capfd):
"""Test :func:`~pyhelpers.dirs.delete_dir`."""
# import tempfile, pathlib; tmp_path = pathlib.Path(tem... | mikeqfu/pyhelpers | tests/test_dirs/test_management.py | .py | 81b4da8757cf2085 | 8.1 | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.