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 |
|---|---|---|---|---|---|---|
"""Basic static custom diagram example.
Carl Zeiss GOM Metrology GmbH, 2026
This App is part of the ZEISS INSPECT Python API Examples:
https://github.com/ZEISS/zeiss-inspect-app-examples
"""
from io import StringIO
import gom
from gom import apicontribution
import gom.api.extensions.diagrams
import gom.api.extensi... | ZEISS/zeiss-inspect-app-examples | AppExamples/custom_diagrams/CustomDiagramExamples/scripts/basic_custom_diagram.py | .py | babd89073d0bfc12 | 7.42 | 6 |
"""Callback script used by custom diagram click events.
Carl Zeiss GOM Metrology GmbH, 2026
This App is part of the ZEISS INSPECT Python API Examples:
https://github.com/ZEISS/zeiss-inspect-app-examples
"""
import gom
def _safe_select_element(element_uuid):
"""Best-effort selection helper for interactive demo ... | ZEISS/zeiss-inspect-app-examples | AppExamples/custom_diagrams/CustomDiagramExamples/scripts/diagram_click_callback.py | .py | beb996c7ecda477d | 7.42 | 6 |
"""Interactive custom diagram example with element overlay.
Carl Zeiss GOM Metrology GmbH, 2026
This App is part of the ZEISS INSPECT Python API Examples:
https://github.com/ZEISS/zeiss-inspect-app-examples
"""
from io import StringIO
import gom
from gom import apicontribution
import gom.api.extensions.diagrams
im... | ZEISS/zeiss-inspect-app-examples | AppExamples/custom_diagrams/CustomDiagramExamples/scripts/element_overlay_custom_diagram.py | .py | cc3c8d6d392686f6 | 7.42 | 6 |
"""Interactive custom diagram example with point-cloud overlay.
Carl Zeiss GOM Metrology GmbH, 2026
This App is part of the ZEISS INSPECT Python API Examples:
https://github.com/ZEISS/zeiss-inspect-app-examples
"""
from io import StringIO
import gom
from gom import apicontribution
import gom.api.extensions.diagram... | ZEISS/zeiss-inspect-app-examples | AppExamples/custom_diagrams/CustomDiagramExamples/scripts/point_cloud_overlay_custom_diagram.py | .py | b6946076135c6430 | 7.42 | 6 |
"""
Integration test for the custom diagram examples.
The actual custom diagram rendering has to be verified manually, but this test ensures
that the custom diagram services can be started and that the custom circle elements can be created
and have the expected properties.
"""
import gom
import gom.api.services
SERV... | ZEISS/zeiss-inspect-app-examples | AppExamples/custom_diagrams/CustomDiagramExamples/scripts/tests/test_custom_diagrams.py | .py | e2a23c1f3a61b4e2 | 7.92 | 6 |
"""
Test for custom curve element
"""
import gom
import gom.api.services
import math
import numpy as np
from addon import ArrayDataTest
SERVICE_ENDPOINT = 'gom.api.examples.custom_curve'
SERVICE_TIMEOUT = 10000
X0 = 0.0
Y0 = 0.0
Z0 = 0.0
RADIUS = 1.0
J = 0.05
K = 0.1
T_MIN = 0.0
T_MAX = 62.840
NUM_STEPS = 1000
T_RAN... | ZEISS/zeiss-inspect-app-examples | AppExamples/custom_elements/CustomCurve/scripts/tests/test_custom_curve.py | .py | 8fbc5d0ea7e9ff48 | 7.92 | 6 |
"""
Custom nominal/actual Offset Point Element Example
Carl Zeiss GOM Metrology GmbH, 2026
This App is part of the ZEISS INSPECT Python API Examples:
https://github.com/ZEISS/zeiss-inspect-app-examples
"""
import gom
import gom.api.extensions
import gom.api.extensions.actuals
import gom.api.extensions.nominals
from... | ZEISS/zeiss-inspect-app-examples | AppExamples/custom_elements/CustomPoint/scripts/Custom_Point.py | .py | e092bd163f14af47 | 7.42 | 6 |
"""
Test for custom point cloud element
"""
import gom
import gom.api.services
import math
import numpy as np
from addon import ArrayDataTest
SERVICE_ENDPOINT = 'gom.api.examples.custom_point_cloud'
SERVICE_TIMEOUT = 10000
R = 35.0
r = 16.0
U_MIN = 0.0
U_MAX = 3.1416
U_STEPS = 600
V_MIN = 0.0
V_MAX = 3.1416
V_STEPS ... | ZEISS/zeiss-inspect-app-examples | AppExamples/custom_elements/CustomPointCloud/scripts/tests/test_custom_point_cloud.py | .py | 2170ccecfda2a470 | 7.92 | 6 |
"""
Test for custom surface element
"""
import gom
import gom.api.services
import numpy as np
from addon import ArrayDataTest
SERVICE_ENDPOINT = 'gom.api.examples.custom_surface'
SERVICE_TIMEOUT = 10000
VERTICES = {
'v0_x': 10.0, 'v0_y': -10.0, 'v0_z': -10.0,
'v1_x': 10.0, 'v1_y': 10.0, 'v1_z': -10.0,
'... | ZEISS/zeiss-inspect-app-examples | AppExamples/custom_elements/CustomSurface/scripts/tests/test_custom_surface.py | .py | 7a00c03957d91333 | 7.92 | 6 |
"""
Test for custom surface curve element
"""
import math
import gom
import gom.api.services
import numpy as np
from addon import ArrayDataTest
SERVICE_ENDPOINT = 'gom.api.examples.custom_surface_curve'
SERVICE_TIMEOUT = 10000
R = 20.0
THETA = math.pi / 6
PHI_MIN = math.pi * 0.5
PHI_MAX = math.pi * 1.5
NUM_POINTS = ... | ZEISS/zeiss-inspect-app-examples | AppExamples/custom_elements/CustomSurfaceCurve/scripts/tests/test_custom_surface_curve.py | .py | 00a078d2acf1cf88 | 7.92 | 6 |
"""
Test for custom VolumeDefects2d element
"""
import math
import gom
import gom.api.services
SERVICE_ENDPOINT = 'gom.api.examples.custom_volume_defects_2d'
SERVICE_TIMEOUT = 10000
N_DEFECTS = 3
DEFECT_RADIUS = 5.0
Z_POS = 0.0
XY_SPACING = 15.0
N_POINTS = 36
TOTAL_POINTS = N_DEFECTS * N_POINTS
def _point_coor... | ZEISS/zeiss-inspect-app-examples | AppExamples/custom_elements/CustomVolumeDefects2d/scripts/tests/test_custom_volume_defects_2d.py | .py | cedd3bf68f88f203 | 7.92 | 6 |
from cobra import Model, Reaction, Metabolite
from beartype import beartype
import os
from datetime import datetime
import pandas as pd
import re
def createToyModel():
"""Create a toy model for testing purposes.
Creates a model with 9 reactions and 5 metabolites, the biomass reaction is **r8** based on the mod... | PlanesLab/gMCSpy | gMCSpy/Utilities.py | .py | 47b232792bdabede | 7.42 | 6 |
import numpy as np
import pytest
@pytest.fixture(scope="module")
def draws():
"""Share default draw count."""
return 500
@pytest.fixture(scope="module")
def chains():
"""Share default chain count."""
return 2
@pytest.fixture(scope="module")
def eight_schools_params():
"""Share setup for eight ... | arviz-devs/arviz-base | external_tests/conftest.py | .py | 368f63e54aaba457 | 7.98 | 8 |
# pylint: disable=no-member, invalid-name, redefined-outer-name, too-many-function-args, no-self-use
import importlib
import numpy as np
import pytest
from arviz_base import from_pystan
from arviz_base.io_pystan import get_draws
from arviz_base.testing import check_multiple_attrs
from .helpers import ( # pylint: di... | arviz-devs/arviz-base | external_tests/test_pystan.py | .py | 10f58b8ea4217c63 | 7.98 | 8 |
"""ArviZ basic functions and converters."""
import datetime
import importlib
import re
import warnings
from collections.abc import Callable
from copy import deepcopy
from typing import TYPE_CHECKING, TypeVar
import numpy as np
import xarray as xr
from arviz_base._version import __version__
from arviz_base.rcparams i... | arviz-devs/arviz-base | src/arviz_base/base.py | .py | d0a3dcbe7fabd399 | 7.48 | 8 |
"""Generalistic converters.
Here "generalistic" means catch anything that can be converter into datatree and
convert it via its specific function.
"""
import numpy as np
import pandas as pd
import xarray as xr
from xarray import Dataset, DataTree, open_datatree
from arviz_base.base import dict_to_dataset
__all__ = ... | arviz-devs/arviz-base | src/arviz_base/converters.py | .py | 9bcc04aa5032dc9e | 7.48 | 8 |
"""Base IO code for all datasets. Heavily influenced by scikit-learn's implementation."""
import difflib
import hashlib
import itertools
import json
import os
import shutil
from collections import namedtuple
from urllib.request import urlretrieve
from xarray import open_datatree
from arviz_base.rcparams import rcPar... | arviz-devs/arviz-base | src/arviz_base/datasets.py | .py | d77393c97255be02 | 7.48 | 8 |
"""CmdStanPy specific conversion code."""
import logging
import re
from pathlib import Path
import numpy as np
from xarray import DataTree
from arviz_base.base import dict_to_dataset, infer_stan_dtypes, requires
from arviz_base.rcparams import rcParams
_log = logging.getLogger(__name__)
class CmdStanPyConverter:
... | arviz-devs/arviz-base | src/arviz_base/io_cmdstanpy.py | .py | 3aabfc89cd671dfb | 7.48 | 8 |
"""emcee-specific conversion code."""
import warnings
import numpy as np
from xarray import DataTree
from arviz_base.base import dict_to_dataset
from arviz_base.rcparams import rc_context
def _verify_names(sampler, var_names, arg_names, slices):
"""Make sure var_names and arg_names are assigned reasonably.
... | arviz-devs/arviz-base | src/arviz_base/io_emcee.py | .py | 48581f137fef3a2d | 7.48 | 8 |
"""ArviZ testing utilities."""
import numpy as np
from arviz_base.io_dict import from_dict
def generate_base_data(seed=31):
"""Generate a base dataset for testing."""
from scipy.stats import halfnorm, norm
rng = np.random.default_rng(seed)
mu = rng.normal(loc=1, size=(4, 100))
tau = np.exp(rng.... | arviz-devs/arviz-base | src/arviz_base/testing.py | .py | e273eb4f61ca10a7 | 7.98 | 8 |
"""General utilities."""
import re
import warnings
import numpy as np
def _check_tilde_start(x):
"""Check whether an item starts with the negation prefix.
Parameters
----------
x : any
Object to inspect.
Returns
-------
bool
True when ``x`` is a string that starts with ... | arviz-devs/arviz-base | src/arviz_base/utils.py | .py | fc2a0ad624cdb272 | 7.48 | 8 |
"""ArviZ input validation utilities."""
import typing
import warnings
from arviz_base.rcparams import defaultParams, rcParams
def validate_sample_dims(sample_dims, data=None):
"""Validate `sample_dims` argument in ArviZ functions.
Parameters
----------
sample_dims : str or sequence of str or None
... | arviz-devs/arviz-base | src/arviz_base/validate.py | .py | d9fed149cfef8299 | 7.48 | 8 |
# pylint: disable=redefined-outer-name
"""Test configuration and global fixtures."""
import numpy as np
import pytest
from arviz_base import from_dict
@pytest.fixture(scope="module")
def draws():
"""Share default draw count."""
return 10
@pytest.fixture(scope="module")
def chains():
"""Share default c... | arviz-devs/arviz-base | tests/conftest.py | .py | 3f97504b34902e26 | 7.98 | 8 |
"""API-Hilfsfunktionen für die Schulferien-Integration.
Zentrale Funktionen:
- fetch_data: HTTP-Abfrage der OpenHolidaysAPI mit Fallback-Logik
- parse_daten: Konvertierung der API-JSON-Response in interne Datenstruktur
- load_bridge_days: Laden der Brückentage aus bridge_days.yaml
- compute_region_slug: Normalisierung... | Chiralistic/home-assistant-schulferien | custom_components/schulferien/api_utils.py | .py | 3571ef7ce270df46 | 7.56 | 12 |
"""Binärsensoren für Schulferien und Feiertage.
Binärsensoren ergänzen die Sensors um einfache ON/OFF-Zustände,
die sich ideal für Automatisierungen in Home Assistant eignen.
Anstatt dass der Nutzer den Sensor-Wert ("ferientag" / "kein_ferientag")
prüfen muss, liefert ein BinarySensor direkt True/False.
Warum 6 Binär... | Chiralistic/home-assistant-schulferien | custom_components/schulferien/binary_sensor.py | .py | 162f578e99a47a26 | 7.56 | 12 |
"""Modul für die Verwaltung und den Abruf von Feiertagen.
Zwei Sensor-Klassen:
1. FeiertagSensor — Hauptsensor mit API-Abfrage
2. FeiertagMorgenSensor — Spiegel-Sensor für morgen (liest vom Hauptsensor)
Warum Ostersonntag-Ergaenzung? Die OpenHolidaysAPI liefert Ostermontag,
aber nicht immer Ostersonntag. Da Ostersonn... | Chiralistic/home-assistant-schulferien | custom_components/schulferien/feiertag_sensor.py | .py | 76ea216a6bddd999 | 7.56 | 12 |
"""Modul für die Verwaltung und den Abruf von Schulferien.
Zwei Sensor-Klassen:
1. SchulferienSensor — Hauptsensor mit API-Abfrage und Brückentag-Logik
2. SchulferienMorgenSensor — Spiegel-Sensor für morgen (liest vom Hauptsensor)
Warum zwei Klassen statt einer? Der Hauptsensor muss die API aufrufen,
Daten parsen und... | Chiralistic/home-assistant-schulferien | custom_components/schulferien/schulferien_sensor.py | .py | f2227bca3c977201 | 7.56 | 12 |
"""Modul zum Setup der Sensoren für Schulferien und Feiertage."""
import logging
from .schulferien_sensor import SchulferienSensor, SchulferienMorgenSensor
from .feiertag_sensor import FeiertagSensor, FeiertagMorgenSensor
from .api_utils import load_bridge_days, compute_region_slug
_LOGGER = logging.getLogger(__name... | Chiralistic/home-assistant-schulferien | custom_components/schulferien/sensor.py | .py | ab76ac0161eb2fd1 | 7.56 | 12 |
import random
import string
import timeit
from mappingtools.operators import combine, merge
from mappingtools.resolvers import Resolver
# --- Setup Small Data ---
base_tree_small = {
"system": {
"metadata": {"version": "1.0.0", "env": "prod"},
"networking": {
"ports": [80, 443, 8080],
... | erivlis/mappingtools | benchmarks/bench_merge_vs_combine.py | .py | 8e3110d1c2c1e28c | 7.48 | 8 |
import random
import timeit
from mappingtools.operators import KeyFormat, flatten
# --- Data Generation Functions ---
# 1. Small, balanced tree
NESTED_DATA_SMALL = {
"a": 1, "b": {"c": 2, "d": [3, 4, {"e": 5}]}, "f": "a_string",
"g": [{"h": 6, "i": [7, 8]}, {"j": 9}], "k": None,
}
# 2. Wide tree (high bread... | erivlis/mappingtools | benchmarks/benchmark_flatten.py | .py | d1519817a4c59cd3 | 7.48 | 8 |
"""
Recipe 01: Deep JSON Patching (Immutability & Optics)
This recipe demonstrates how to use the `Lens` optic and the `merge` function
to immutably update a deeply nested section of a large JSON-like dictionary.
Instead of writing brittle traversal logic (e.g., `data.get("a", {}).get("b", {})...`),
we compose a Lens... | erivlis/mappingtools | recipes/recipe_01_deep_json_patching.py | .py | 6dabbb9020d3b66e | 7.48 | 8 |
"""
Recipe 02: Reshaping Tabular Data (ETL / Pandas / CSV)
This recipe demonstrates how to convert a flat, tabular stream of data
(like rows from a CSV or a database cursor) into a deeply nested dictionary (tensor).
Instead of writing recursive `defaultdict` loops, we use `reshape` to group by keys
and `Aggregation` ... | erivlis/mappingtools | recipes/recipe_02_etl_reshape.py | .py | e9563d8b39965e6d | 7.48 | 8 |
"""
Recipe 03: Configuration Management (Monoids & Reduce)
This recipe demonstrates how to load multiple configuration layers
(e.g., default.json -> dev.json -> local.json) and cleanly merge them
into a single, unified state object.
Instead of writing a custom `ConfigurationManager` class, we use the `merge`
function... | erivlis/mappingtools | recipes/recipe_03_config_management.py | .py | 9383a0ed58689a8d | 7.48 | 8 |
"""
Recipe 04: Deep JSON Diffing
This recipe demonstrates how to use the `flatten()` operator to collapse
deeply nested JSON structures into single-layer dictionaries with tuple paths as keys.
Once flattened, comparing two nested structures to find additions,
removals, or changes becomes a trivial set operation on th... | erivlis/mappingtools | recipes/recipe_04_deep_json_diffing.py | .py | 393fd5436c51bc19 | 7.48 | 8 |
"""
Recipe 05: Profiling Config Access (MeteredDict)
This recipe demonstrates how to use `MeteredDict` to track how
many times your application reads or writes specific keys.
This is incredibly useful for finding "hot keys" in a config file
that might be better served by being cached locally rather than
repeatedly fe... | erivlis/mappingtools | recipes/recipe_05_slow_config_profiling.py | .py | af2028772b0670ba | 7.48 | 8 |
"""
Recipe 06: Quick Serialization (ETL / simplify / Dictifier)
This recipe demonstrates how to convert complex Python objects (like
dataclasses, datetime objects, and custom class instances) into
pure, JSON-serializable dictionaries using `strictify`.
Instead of writing custom `to_dict` methods or configuring standa... | erivlis/mappingtools | recipes/recipe_06_serialization_pipeline.py | .py | c7733281e4b20e52 | 7.48 | 8 |
"""
Recipe 07: Multi-Dimensional Counting (CategoryCounter)
This recipe demonstrates how to use `CategoryCounter` to aggregate
data into multiple distinct categories simultaneously with a single pass.
We will traverse a filesystem directory and count files by extension,
by size category (Small, Medium, Large), and by... | erivlis/mappingtools | recipes/recipe_07_filesystem_categorization.py | .py | ebbf6c57e66c809c | 7.48 | 8 |
"""
Recipe 08: The Inverted Configuration Index (Explorer Mode)
What happens when we combine `flatten` with `MappingCollector` and `Aggregation.ALL`?
We discover a powerful auditing tool: The Inverted Index.
Imagine a massive, deeply nested configuration file. You want to know:
"Are we hardcoding the same IP address,... | erivlis/mappingtools | recipes/recipe_08_inverted_config_index.py | .py | 19f794eea31408fa | 7.48 | 8 |
"""
Recipe 09: Cartesian Grid Search (itertools.product + merge)
When performing hyperparameter tuning or parameterized testing, you often
need to generate a vast matrix of configuration objects from a base template.
By combining `itertools.product` to generate combinations of values,
and our `merge` Monoid to immuta... | erivlis/mappingtools | recipes/recipe_09_hyperparameter_grid_search.py | .py | c45f0b2db35c300c | 7.48 | 8 |
"""
Recipe 10: Cryptographic Secret Redaction (flatten + Lenses + reduce)
In modern systems, logging deeply nested JSON payloads (like API requests)
is risky because they might contain hardcoded secrets, PII, or tokens.
This recipe demonstrates how to build an immutable "Redaction Pipeline".
We combine `flatten` to s... | erivlis/mappingtools | recipes/recipe_10_cryptographic_redaction.py | .py | 03409f4a247f4707 | 7.48 | 8 |
"""
Recipe 11: Microservice Dependency Graph (inverse + AutoMapper)
In large-scale Microservice architectures, you often define a "forward"
dependency graph in your infrastructure as code:
"Service A depends on [Service B, Service C]".
However, during an incident (e.g., Service C goes down), you need the
"reverse" gr... | erivlis/mappingtools | recipes/recipe_11_microservice_dependency_graph.py | .py | 697e57ca9705ba5b | 7.48 | 8 |
"""
Recipe 12: Schema-Guided Payload Correction (flatten + Lenses + merge)
When APIs evolve, incoming JSON payloads often contain deprecated keys,
wrong data types, or missing required fields.
This recipe demonstrates how to build an "Auto-Corrector" pipeline.
We use a lightweight, evolving schema specification to gu... | erivlis/mappingtools | recipes/recipe_12_schema_guided_correction.py | .py | 5b656360a424a15a | 7.48 | 8 |
"""
Recipe 13: Broadcasting Method Calls (Dictifier)
When you manage a collection of identical objects (like a pool of database
connections, a roster of users, or a fleet of sensors) indexed in a dictionary,
you often have to write boilerplate `for key, obj in collection.items(): obj.do_work()` loops.
The `Dictifier`... | erivlis/mappingtools | recipes/recipe_13_dictifier_broadcasting.py | .py | a7896ba8cd51bf9f | 7.48 | 8 |
"""
Recipe 14: Dynamic Object Minification (minify vs simplify)
When exporting massive JSON datasets for front-end clients or network transmission,
long string keys ("customer_identifier_uuid", "transaction_timestamp_utc") waste bandwidth.
The `mappingtools` library provides `minify` to instantly solve this.
However,... | erivlis/mappingtools | recipes/recipe_14_auto_minification.py | .py | 981ed56ac8a6541b | 7.48 | 8 |
"""
Recipe 15: Pivot Tensors (reshape + Aggregation.ALL)
When dealing with analytics, you often receive rows of data that need to be
grouped by multiple intersecting axes (e.g., Year -> Quarter -> Category -> Value).
This recipe combines the powerful `reshape` function with `Aggregation.ALL` to group
a flat stream of... | erivlis/mappingtools | recipes/recipe_15_data_pivot_tensor.py | .py | 26087a7478fd364e | 7.48 | 8 |
"""
Recipe 16: Time-Series Smoothing (MappingCollector + Aggregation.EMA)
When processing noisy time-series data (like IoT sensor readings, stock prices,
or server CPU metrics), raw values can fluctuate wildly.
This recipe demonstrates how to use `MappingCollector` with the `Aggregation.EMA`
(Exponential Moving Avera... | erivlis/mappingtools | recipes/recipe_16_time_series_ema.py | .py | 6f8254f7b81972ea | 7.48 | 8 |
"""
Recipe 17: Data Governance & Role-Based Access Control (RBAC) (rename + Lens)
In large organizations, returning JSON data to an API client often requires
"shaping" the response based on the user's role (e.g., an Admin sees everything,
a standard User sees limited fields, an External client sees sanitized data).
T... | erivlis/mappingtools | recipes/recipe_17_data_governance_masking.py | .py | 0b25e5acf853afd5 | 7.48 | 8 |
"""
Recipe 18: Bi-directional State Sync (inverse + rekey)
In modern frontend-backend synchronizations (like React/Vue communicating with a Python API),
the frontend might use camelCase keys (`userId`, `createdAt`) while the Python backend
strictly uses snake_case (`user_id`, `created_at`).
This recipe demonstrates h... | erivlis/mappingtools | recipes/recipe_18_bidirectional_state_sync.py | .py | 13d2fab54d2d0ab0 | 7.48 | 8 |
"""
Recipe 19: Feature Flag Rollout State (native python + distinct)
In continuous deployment, you often use complex Feature Flags
(e.g., A/B testing, beta rings). When calculating the effective
state for a user, you may need to resolve multiple overlapping flag
evaluations from different tiers (Global -> Region -> Us... | erivlis/mappingtools | recipes/recipe_19_feature_flag_rollout.py | .py | 965d4212bbc6d8ab | 7.48 | 8 |
"""
Recipe 20: Telemetry Aggregation (MeteredDict + Dictifier + combine)
In a distributed or multi-threaded system, you might have multiple workers
or sub-systems, each managing their own `MeteredDict` to profile performance
and access patterns.
Eventually, you need to aggregate all these isolated telemetry summaries... | erivlis/mappingtools | recipes/recipe_20_telemetry_aggregation.py | .py | f4dd9c79c4b81c2c | 7.48 | 8 |
"""
Recipe 21: Algorithmic Music Transposition (reshape + Lens)
In algorithmic composition or MIDI processing, a song is often represented
as a flat stream of note events. To manipulate the song (like transposing
a specific instrument or extracting a sheet music view), we need to pivot
the flat stream into a structure... | erivlis/mappingtools | recipes/recipe_21_algorithmic_music_transposition.py | .py | 9a741986ea2c89d0 | 7.48 | 8 |
"""
Recipe 22: Image Bounding Box Filter (reshape + Lenses)
In image processing, an image might be represented as a flat stream of pixels
(e.g., from a sensor or linear array) with x, y coordinates and RGB values.
This recipe uses `reshape` to convert a flat array of pixels into a 2D spatial
tensor (Y -> X -> RGB). T... | erivlis/mappingtools | recipes/recipe_22_image_bounding_box_filter.py | .py | add279fbaae3121d | 7.48 | 8 |
"""
Recipe 23: Graph Theory Connectivity (flatten)
In Graph Theory, determining connectivity components (which nodes can reach which other nodes)
is a classic algorithm. If a graph is represented as a dictionary of Adjacency Lists
(Node -> [Connected Nodes]), we can use `mappingtools` primitives to find all uniquely r... | erivlis/mappingtools | recipes/recipe_23_graph_theory_connectivity.py | .py | fa1fb1f626ea679a | 7.48 | 8 |
"""
Recipe 24: Real-Time Anomaly Detection (MappingCollector + Aggregation.EMA)
In cybersecurity, system monitoring, or algorithmic trading, detecting anomalies
(spikes or crashes) in real-time is critical.
Instead of keeping a massive array of historical data to calculate moving averages,
we can use `MappingCollecto... | erivlis/mappingtools | recipes/recipe_24_anomaly_detection.py | .py | 6b1709d01e1d5c61 | 7.48 | 8 |
"""
Recipe 25: Markov Chain Text Generation (MappingCollector + Aggregation.COUNT)
Before Large Language Models (LLMs) like GPT, there were Markov Chains.
A Markov Chain generates text by predicting the next word based purely on the
current word, using probabilities derived from a training corpus.
Mathematically, a M... | erivlis/mappingtools | recipes/recipe_25_markov_chain_text_generator.py | .py | 9241513df8f0e07b | 7.48 | 8 |
"""
Recipe 28: Combine with Conflict Resolution
The standard `merge` operator is a "last-wins" monoid, which is perfect for
layering configurations. However, sometimes you need more control when two
trees have conflicting values at the same leaf path.
This recipe introduces the `combine` operator, a generalization of... | erivlis/mappingtools | recipes/recipe_28_conflict_resolution.py | .py | a84a3ce5ace84772 | 7.48 | 8 |
"""
Recipe #29: Cleaning Up API Payloads
Problem: You receive a complex, nested data structure from an external API and
need to clean it up before processing. This includes normalizing keys and trimming
whitespace from string values.
Solution: Use the `modify` transformer to apply multiple cleaning functions in a
sin... | erivlis/mappingtools | recipes/recipe_29_payload_cleanup.py | .py | c8c781b03e045ab0 | 7.48 | 8 |
"""
Recipe #30: Traversal Mode Overrides
Problem: In a fraud-monitoring ingestion pipeline, partners send payloads that
mix nested dicts, binary signatures, and iterable domain wrappers. Blind
protocol detection can flatten or merge these fields incorrectly.
Solution: Use `TraversalModeRegistry` + `traversal_mode(...... | erivlis/mappingtools | recipes/recipe_30_traversal_mode_overrides.py | .py | 9142609fca5b9690 | 7.48 | 8 |
from collections import Counter
from collections.abc import Callable, Iterable, MutableMapping, Sequence
from dataclasses import dataclass
from enum import Enum
from typing import Any
def all_aggregator(mapping: MutableMapping, key: Any, values: Iterable[Any]):
"""Extends the list at mapping[key] with values."""
... | erivlis/mappingtools | src/mappingtools/aggregations.py | .py | 998d01008e8aaa2d | 7.48 | 8 |
import string
from collections import defaultdict
from collections.abc import Callable, Mapping
from mappingtools._tools import unique_strings
class AutoMapper(Mapping):
"""
A Mapping that automatically generates and assigns unique, minified strings
for any new keys accessed. The minified keys are genera... | erivlis/mappingtools | src/mappingtools/collectors/_collectors.py | .py | 9073145983b83b06 | 7.48 | 8 |
from collections import defaultdict
from collections.abc import Callable, Iterable, MutableMapping
from typing import Any, Generic, cast
from mappingtools.aggregations import Aggregation
from mappingtools.typing import KT, VT, Category, VT_co
# Alias for backward compatibility
MappingCollectorMode = Aggregation
cla... | erivlis/mappingtools | src/mappingtools/collectors/mapping_collector.py | .py | e10e31103dbbf420 | 7.48 | 8 |
# -*- coding: utf-8 -*-
"""Task-balancing losses for multi-task learning.
Several classic balancing strategies are bundled here so the trainer can switch
between them:
* ``AutomaticWeightedLoss`` (AWL) — Kendall et al., "Multi-Task Learning Using
Uncertainty to Weigh Losses" (CVPR 2018). Learns a per-task uncertain... | jzhoujg/WiADN | AutomaticWeightedLoss.py | .py | 7b63d2590511ef5f | 7.42 | 6 |
# -*- coding: utf-8 -*-
"""Train WiADN (Asymmetrical Dual-Task Attention Network) for WiFi sensing.
Jointly recognizes the user's **activity** (high-level task) and **location**
(low-level task) from WiFi CSI. The asymmetrical architecture cascades attention
modules that transfer prior knowledge from the low-level tas... | jzhoujg/WiADN | train.py | .py | 128a9e01fb6c0294 | 7.42 | 6 |
"""Adapters for Waveshare boards."""
from typing import ClassVar
from gpiozero import Factory
from app.adapters.base import RelayBoardAdapter
from app.adapters.gpio_devices import Relay
class WaveshareRpiRelayBoardAdapter(RelayBoardAdapter):
"""Adapter for RPi Relay Board from Waveshare.
The Board carries... | max-pfeiffer/irrigation-pi | backend/app/adapters/waveshare.py | .py | bd9b79632b194e40 | 7.42 | 6 |
"""API endpoints for Relay objects."""
from fastapi import APIRouter
from app.api.v1.models import Relay, RelayUpdate
from app.config import relayBoardAdapter
from app.services.relay import (
service_get_relay,
service_get_relays,
service_update_relay,
)
router = APIRouter()
@router.get("/")
def get_re... | max-pfeiffer/irrigation-pi | backend/app/api/v1/endpoints/relay.py | .py | 9d4fee58e0a51263 | 7.42 | 6 |
"""API endpoints for Schedule objects."""
from fastapi import APIRouter, Depends, Request
from sqlmodel import Session
from app.api.v1.models import ScheduleCreate, ScheduleResponse, ScheduleUpdate
from app.database.config import get_session
from app.services.schedule import (
service_create_schedule,
service... | max-pfeiffer/irrigation-pi | backend/app/api/v1/endpoints/schedule.py | .py | 8557ced769c2d96b | 7.42 | 6 |
"""API endpoints for system date and time."""
from fastapi import APIRouter, Request
from app.api.v1.models import SystemDateTime
from app.services.system_date_time import (
service_get_system_date_time,
service_set_system_date_time,
)
router = APIRouter()
@router.get("/")
def get_system_date_time() -> Sys... | max-pfeiffer/irrigation-pi | backend/app/api/v1/endpoints/system_date_time.py | .py | 743af85e1a2da916 | 7.42 | 6 |
"""API models."""
from datetime import time
from pydantic import AwareDatetime, BaseModel, Field, PositiveInt
from app.scheduling import Repeat
class ScheduleResponse(BaseModel):
"""Response schema for schedule."""
id: PositiveInt = Field(description="Primary key")
start_time: time = Field(description... | max-pfeiffer/irrigation-pi | backend/app/api/v1/models.py | .py | 4d260b9e1158e1d3 | 7.42 | 6 |
"""Application configuration."""
from pathlib import Path
from socket import AddressFamily, gethostname
from typing import Any
import semver
import toml
from gpiozero.pins.mock import MockFactory
from gpiozero.pins.native import NativeFactory
from psutil import net_if_addrs
from pydantic import computed_field
from py... | max-pfeiffer/irrigation-pi | backend/app/config.py | .py | 8a0723c022d7cd07 | 7.42 | 6 |
"""Database models."""
from datetime import time
from pydantic import PositiveInt
from sqlmodel import Field, SQLModel
from app.scheduling import Repeat
class BaseModel(SQLModel):
"""Base model."""
id: int | None = Field(default=None, primary_key=True)
class Schedule(BaseModel, table=True):
"""Sched... | max-pfeiffer/irrigation-pi | backend/app/database/models.py | .py | c8fb05e20084de8b | 7.42 | 6 |
"""FastAPI application."""
from contextlib import asynccontextmanager
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from fastapi import FastAPI, Request, status
from fastapi.concurrency import run_in_threadpool
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResp... | max-pfeiffer/irrigation-pi | backend/app/main.py | .py | 78a8ffc8a9af1e1d | 7.42 | 6 |
"""Repositories for data persistence."""
from datetime import time
from apscheduler.job import Job
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from sqlmodel import Session, select
from app.database.models import Schedule
from app.scheduling import Rep... | max-pfeiffer/irrigation-pi | backend/app/repositories.py | .py | f95c2dfa0c0e6f27 | 7.42 | 6 |
"""Scheduling for relay switches."""
from datetime import datetime
from enum import StrEnum
from app.config import relayBoardAdapter
from app.services.relay import service_update_relay
class Repeat(StrEnum):
"""Enumeration for repeat values."""
every_day = "every_day"
weekdays = "weekdays"
weekends... | max-pfeiffer/irrigation-pi | backend/app/scheduling.py | .py | e7262c52e8a5bbfa | 7.42 | 6 |
"""Services for relay switching."""
from app.adapters.base import RelayBoardAdapter
from app.adapters.gpio_devices import Relay
def service_get_relay(adapter: RelayBoardAdapter, relay_position: int) -> dict:
"""Get relay data.
:param adapter:
:param relay_position:
:return:
"""
relay: Relay ... | max-pfeiffer/irrigation-pi | backend/app/services/relay.py | .py | 1ae616e298584a48 | 7.42 | 6 |
"""Services for handling persistence of Schedule objects."""
from datetime import UTC, date, datetime, time, timedelta, tzinfo
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from sqlalchemy.sql.expression import select
from sqlmodel import Session
from app.database.models import Schedule
from app.except... | max-pfeiffer/irrigation-pi | backend/app/services/schedule.py | .py | 120a9a13a7a139b7 | 7.42 | 6 |
"""Services for system date and time."""
import subprocess
from datetime import datetime
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from app.exceptions import SystemDateTimeError
SUBPROCESS_TIMEOUT: int = 10
def service_get_system_date_time() -> datetime:
"""Service for reading system date an... | max-pfeiffer/irrigation-pi | backend/app/services/system_date_time.py | .py | 8fd10c77e028c94b | 7.42 | 6 |
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
from sqlmodel import SQLModel
from app.config import ApplicationSettings
from app.database.models import *
# this is the Alembic Config object, which provides
# access to the values within the .ini file ... | max-pfeiffer/irrigation-pi | backend/migrations/env.py | .py | 008654ddf15b29d7 | 7.42 | 6 |
"""Initial Migrations
Revision ID: 51b99b73e5b2
Revises:
Create Date: 2024-02-02 00:25:17.824043
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
import sqlmodel
# revision identifiers, used by Alembic.
revision: str = '51b99b73e5b2'
down_revision: Union[str, None] = None
bran... | max-pfeiffer/irrigation-pi | backend/migrations/versions/51b99b73e5b2_initial_migrations.py | .py | 160f1525c62d7e99 | 7.42 | 6 |
"""Classes for fake objects to stub out dependencies."""
class FakeRelay:
"""Class for faking a relay."""
def __init__(self):
"""Initialize object."""
self._value: int = None
def on(self) -> None:
"""Switches relay on.
:return:
"""
self._value = 1
de... | max-pfeiffer/irrigation-pi | backend/tests/fake_objects.py | .py | 9b1e99bca7d51b4f | 7.92 | 6 |
"""Tests for schedule service package."""
from datetime import datetime, time
from app.services.schedule import (
calculate_stop_time,
set_system_timezone,
)
def test_set_system_timezone() -> None:
"""Test setting the system timezone to a time object.
:return:
"""
naive_time: time = time(ho... | max-pfeiffer/irrigation-pi | backend/tests/unit/test_service_schedule.py | .py | c4655f5efab2d491 | 7.92 | 6 |
"""Test utilities."""
from dataclasses import dataclass
from gpiozero import Device
from gpiozero.exc import BadPinFactory
from app.database.models import Schedule
from app.scheduling import Repeat
def is_raspberry_pi() -> bool:
"""Return true if the function is run on a Raspberry Pi.
:return:
"""
... | max-pfeiffer/irrigation-pi | backend/tests/utils.py | .py | 679ee63bdfaafccf | 7.92 | 6 |
"""
Obsidian-style global attachment lookup for MkDocs.
Resolves bare / wrong-relative image paths by filename anywhere under docs/
(unique basename match), similar to Obsidian's attachment resolution.
Handles:
 → 
![[netconfig.webp]] → ![netconfig.we... | canwdev/canwdev.github.io | hooks/obsidian_attachments.py | .py | 531c7fe759cddfcc | 7.42 | 6 |
"""
Sentry Integration Demo for ModelQ
This example demonstrates how to integrate Sentry error tracking with ModelQ,
similar to how Sentry works with Celery.
Installation:
pip install modelq[sentry]
# or
pip install modelq sentry-sdk
Setup:
1. Create a Sentry account at https://sentry.io
2. Creat... | ModelsLab/modelq | examples/sentry_demo.py | .py | 5bc4a84e45c0cb0f | 7.66 | 20 |
class Middleware:
def __init__(self) -> None:
pass
def execute(self, event, *args, **kwargs):
if event == "before_worker_boot":
self.before_worker_boot()
elif event == "after_worker_boot":
self.after_worker_boot()
elif event == "before_worker_shutdown":
... | ModelsLab/modelq | modelq/app/middleware/base.py | .py | 1abdc587992bfd11 | 7.66 | 20 |
import random
import time
import redis
from redis.exceptions import ConnectionError, TimeoutError
import logging
logger = logging.getLogger(__name__)
class _RedisWithRetry:
"""Lightweight proxy that wraps a redis.Redis instance.
Any callable attribute (e.g. get, set, blpop, xadd …) is executed with a
ret... | ModelsLab/modelq | modelq/app/redis_retry.py | .py | 5e4036c7eaa607ad | 7.66 | 20 |
"""
Optional Sentry integration for ModelQ.
This module provides Sentry error tracking integration for ModelQ,
similar to how Sentry integrates with Celery.
Usage:
from modelq import ModelQ
mq = ModelQ(
host="localhost",
sentry_dsn="https://your-sentry-dsn@sentry.io/project-id",
sentr... | ModelsLab/modelq | modelq/app/sentry.py | .py | 12bf4be29ee3d697 | 7.66 | 20 |
class TaskTimeoutError(Exception):
"""Custom exception to indicate task timeout."""
def __init__(self, task_id: str) -> None:
super().__init__(f"Task {task_id} timed out waiting for result.")
self.task_id = task_id
class TaskProcessingError(Exception):
"""Custom exception to indicate an e... | ModelsLab/modelq | modelq/exceptions.py | .py | c8cdbaf1eaa77b60 | 7.66 | 20 |
"""
Tests for claiming a task on Redis versions without BLMOVE.
BLMOVE needs Redis >= 6.2. Every GPU worker container in production was still on
Redis 6.0.16, where the command does not exist. Upgrading such a worker to a
ModelQ that calls BLMOVE unconditionally produced:
ERROR - Worker 0 crashed with error: unkn... | ModelsLab/modelq | tests/test_blmove_fallback.py | .py | f0924e6f3fbf4d7c | 7.16 | 20 |
"""Tests for the reconnect delay in _RedisWithRetry.
Recovery from a dead Redis connection costs socket_timeout (to detect) plus
RETRY_DELAY (to wait), so RETRY_DELAY is the tail of every stall. It also has
to spread a synchronised herd: on 2026-08-15 every worker on a node logged the
same connection failure in the sa... | ModelsLab/modelq | tests/test_redis_retry_delay.py | .py | a21f347e8aa793e0 | 8.16 | 20 |
"""Regression tests for the RetryTaskException retry budget.
A RetryTaskException used to be re-queued unconditionally, with no attempt
counter. Any task whose failure was permanent -- an expired or deleted source
URL, for example -- looped forever, re-entering the queue every delay_seconds
and consuming worker capaci... | ModelsLab/modelq | tests/test_retry_budget.py | .py | 7412119ac397a003 | 8.16 | 20 |
"""
Tests for the queue/run split a producer sees after blocking on a result.
Motivated by a production report where a generation API answered in ~37s while
the only timer it exposed read 5.55s. That timer started after the task was
enqueued, so everything before it -- and the queue wait itself -- was invisible,
and t... | ModelsLab/modelq | tests/test_stage_timings.py | .py | c4ff21ccbe2c0003 | 7.16 | 20 |
"""USD Addon for AYON."""
import os
from ayon_core.addon import AYONAddon, IPluginPaths, ITrayAddon
from .version import __version__
USD_ADDON_DIR = os.path.dirname(os.path.abspath(__file__))
class USDAddon(AYONAddon, ITrayAddon, IPluginPaths):
"""Addon to add USD Support to AYON.
Addon can also skip dis... | ynput/ayon-usd | client/ayon_usd/addon.py | .py | 719187ec54052510 | 7.56 | 12 |
import platform
from ayon_usd.ayon_bin_client.ayon_bin_distro.lakectlpy import wrapper
from ayon_core.settings import get_studio_settings
class _LocalCache:
lake_instance = None
CACHED_ITEMS = []
def get_global_lake_instance(settings=None):
"""Create lakefs connection.
Warning:
This returns s... | ynput/ayon-usd | client/ayon_usd/config.py | .py | daf105e32fb61112 | 7.56 | 12 |
"""Add the AYON USD startup script to Maya's Python path."""
import os
from ayon_applications import LaunchTypes, PreLaunchHook
MAYA_STARTUP_DIR = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"startup",
"maya",
)
class SetupAssetResolver(PreLaunchHook):
"""Configure t... | ynput/ayon-usd | client/ayon_usd/hooks/pre_maya_launch.py | .py | 8004ae95146b86b9 | 7.56 | 12 |
"""Pre-launch hook to initialize asset resolver for the application."""
import json
import os
from typing import Optional
from ayon_applications import LaunchTypes, PreLaunchHook
from ayon_usd import config, utils
from ayon_usd.utils import ADDON_DATA_JSON_PATH
class InitializeAssetResolver(PreLaunchHook):
"""I... | ynput/ayon-usd | client/ayon_usd/hooks/pre_resolver_init.py | .py | 3fa0bcce23f5a602 | 7.56 | 12 |
"""Pre-launch hook to set USD pinning related environment variable."""
from ayon_applications import LaunchTypes, PreLaunchHook
class UsdPinningRoot(PreLaunchHook):
"""Pre-launch hook to set USD_ROOT environment variable."""
app_groups = {"maya", "houdini", "blender", "unreal"}
# this should be set to fa... | ynput/ayon-usd | client/ayon_usd/hooks/usd_pinning_root.py | .py | c89c14fc7ff2d108 | 7.56 | 12 |
import logging
import json
import os
import sys
import re
from typing import Dict, List, Optional, Set
from pxr import UsdShade, Ar, Sdf
from urllib.parse import urlparse
log = logging.getLogger(__name__)
def is_uri(path: str) -> bool:
parsed = urlparse(path)
return bool(parsed.scheme)
def _normalize_path(... | ynput/ayon-usd | client/ayon_usd/standalone/usd/pinning/_pinning_file_generation_funcs.py | .py | 0dd491d4c2fdb8d9 | 7.56 | 12 |
#!/usr/bin/env python
"""Prepares server package from addon repo to upload to server.
Requires Python 3.9. (Or at least 3.8+).
This script should be called from cloned addon repo.
It will produce 'package' subdirectory which could be pasted into server
addon directory directly (eg. into `ayon-backend/addons`).
For... | ynput/ayon-usd | create_package.py | .py | 3a3ba78cea8db67b | 7.56 | 12 |
"""USD Addon for AYON - server part."""
import os
from pathlib import Path
from typing import Any
from fastapi import Depends # noqa: F401
from ayon_server.addons import BaseServerAddon
from .settings import USDSettings, convert_settings_overrides
PRIVATE_DIR = Path(os.path.dirname(os.path.abspath(__file__))).pa... | ynput/ayon-usd | server/__init__.py | .py | 47b10e694a48dd0d | 7.56 | 12 |
"""The conftest module for the ayon_usd addon.
This is setting up fixtures for installing and testing addon on the
server. Currently, it provides fixtures for installing the addon through
REST API, waiting for the installation event to finish, restarting,
and checking the addon is installed.
This could be speed up by... | ynput/ayon-usd | tests/client/ayon_usd/conftest.py | .py | c22acbb559c03d65 | 8.06 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.