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 |
|---|---|---|---|---|---|---|
from __future__ import annotations
import argparse
import shutil
from pathlib import Path
import nox
DIR = Path(__file__).parent.resolve()
nox.needs_version = ">=2024.3.2"
nox.options.sessions = ["lint", "pylint", "tests"]
nox.options.default_venv_backend = "uv|virtualenv"
@nox.session
def lint(session: nox.Sessi... | LPC-HH/boostedhh | noxfile.py | .py | c314d683016a98fa | 7.15 | 1 |
from __future__ import annotations
import argparse
import uproot
def inspect_root_file(file_path):
"""Inspect the contents of a ROOT file."""
try:
# Open the ROOT file using uproot
with uproot.open(file_path) as file:
print(f"\nInspecting ROOT file: {file_path}\n")
#... | LPC-HH/boostedhh | src/boostedhh/inspect_root.py | .py | b6a186f3d131e56d | 7.65 | 1 |
"""
Skimmer Base Class - common functions for all skimmers.
Author(s): Raghav Kansal
"""
from __future__ import annotations
import logging
from abc import abstractmethod
from pathlib import Path
import numpy as np
import pandas as pd
from coffea import processor
from boostedhh.hh_vars import LUMI
from . import co... | LPC-HH/boostedhh | src/boostedhh/processors/SkimmerABC.py | .py | e7fffc7ed0334f1e | 7.15 | 1 |
"""
Collection of utilities for corrections and systematics in processors.
Loosely based on https://github.com/jennetd/hbb-coffea/blob/master/boostedhiggs/corrections.py
Most corrections retrieved from the cms-nanoAOD repo:
See https://cms-nanoaod-integration.web.cern.ch/commonJSONSFs/
Authors: Raghav Kansal, Cristi... | LPC-HH/boostedhh | src/boostedhh/processors/corrections.py | .py | bf2182f889fa3bd3 | 7.15 | 1 |
"""
Common functions for processors.
Author(s): Raghav Kansal
"""
from __future__ import annotations
import awkward as ak
import numpy as np
from coffea.analysis_tools import PackedSelection
P4 = {
"eta": "Eta",
"phi": "Phi",
"mass": "Mass",
"pt": "Pt",
}
PAD_VAL = -99999
GEN_FLAGS = ["fromHardPr... | LPC-HH/boostedhh | src/boostedhh/processors/utils.py | .py | fff558c0c99cda32 | 7.15 | 1 |
# from distributed.diagnostics.plugin import WorkerPlugin
from __future__ import annotations
import json
import os
import pickle
from pathlib import Path
import numpy as np
import uproot
from coffea import nanoevents, processor
from . import utils
def add_mixins(nanoevents):
# for running on condor
nanoeve... | LPC-HH/boostedhh | src/boostedhh/run_utils.py | .py | 11f42d07ccedd616 | 7.15 | 1 |
"""
Splits the total fileset and creates condor job submission files for the specified run script.
Author(s): Cristina Mantilla Suarez, Raghav Kansal
"""
from __future__ import annotations
import os
import subprocess
import sys
import warnings
from math import ceil
from pathlib import Path
from string import Templat... | LPC-HH/boostedhh | src/boostedhh/submit_utils.py | .py | 6fd5a64cc5472ec5 | 7.15 | 1 |
#!/usr/bin/env python3
"""
PyInstaller build script for the Script-to-Speech GUI backend.
This script creates a standalone executable that can be bundled with the Tauri app
for self-contained distribution without requiring Python/uv to be installed.
The executable is renamed with a platform-specific target triple suf... | trentw/script-to-speech | build_backend.py | .py | c10512b53aed6be3 | 7.15 | 1 |
"""
This script will create a new report file that will get published to Github
pages, that ties together all the various graphs that have been downloaded.
"""
import datetime
import logging
import logging.config
import os
import config
import image_download_config
import pytz
log_config_path = os.path.join(os.path.d... | bcgov/nr-rfc-reanalysis | python/src/create_report.py | .py | 13e704725641cf6d | 7.15 | 1 |
import re
from consts import ValueType
def normalize_multi(val: str) -> str:
"""Normalize user-entered separators to `; ` for multi-value tags."""
return "; ".join(part for part in (raw_part.strip() for raw_part in re.split(r"\s*[/;,]\s*", val)) if part)
def parse_date(val: str) -> str:
"""Parse a user-... | xulbux/python | apps/src/film_credits_tagger/helpers.py | .py | c0cd93c73327afff | 7.3 | 3 |
import re
_TIME_RE = re.compile(r"^\s*(?:(\d+):)?(?:(\d{1,2}):)?(\d+(?:\.\d+)?)\s*$")
def parse_time(val: str) -> float | None:
"""Parse `HH:MM:SS(.ms)`, `MM:SS(.ms)`, or `SS(.ms)` into seconds.<br>
Returns `None` if the input cannot be parsed."""
if not val.strip():
return None
if not (match... | xulbux/python | apps/src/video_trimmer/helpers.py | .py | 7717a01ade48824b | 7.3 | 3 |
#!/usr/bin/env python3
# x-cmds:file[update]
"""Quickly convert a HEX value to a percentage."""
from xulbux import ArgumentParser, S, StyledText, console
def hex_to_percent(hex_val: str | None) -> float:
"""Convert a hex value to a percentage."""
if not hex_val:
return 0.0
elif hex_val.startswi... | xulbux/python | commands/hex-percent.py | .py | 7f369f6ee285d99f | 7.3 | 3 |
#!/usr/bin/env python3
# x-cmds:file[update]
"""Displays an animated, random text character mess.
The mess can be made faster and displayed in color."""
import random as rnd
import time
import xulbux as xx
from xulbux import ArgumentParser
from xulbux.ansi import AnyStyle, S, StyledText
digits: list[str] = ["0", "1"... | xulbux/python | commands/mess.py | .py | 48108197e462a2ed | 7.3 | 3 |
#!/usr/bin/env python3
# x-cmds:file[update]
"""Generate a truly random number with a specific number of digits or within a range.
Provide either the number of digits or a min and max range."""
import secrets
import sys
import xulbux as xx
from xulbux import ArgumentParser, FormatCodes, ProgressBar, S
sys.set_int_ma... | xulbux/python | commands/rand.py | .py | 74bf54747bfdae37 | 7.3 | 3 |
#!/usr/bin/env python3
# x-cmds:file[update]
"""Show a sine wave animation inside the terminal."""
import math
import time
import xulbux as xx
from xulbux import ArgumentParser, S
def show_wave(width: int, speed: tuple[float, float] = (5, 1)) -> None:
t = 0
half_w = width // 2
prev_x: int | None = None
... | xulbux/python | commands/sine.py | .py | c8b464027f7afdb5 | 7.3 | 3 |
#!/usr/bin/env python3
# x-cmds:file[update]
"""Force delete files or directories, even if they are locked by processes."""
import contextlib
import os
import platform
import shutil
import subprocess
import sys
import time
from pathlib import Path
import psutil
import xulbux as xx
from xulbux import ArgumentParser, F... | xulbux/python | commands/x-rm.py | .py | 3ac65ea32be61f14 | 7.3 | 3 |
from typing import Any
from django.views.generic import TemplateView
class HomeView(TemplateView):
"""Website home view (index)."""
template_name = "core/pages/home/index.html"
def get_context_data(self, **kwargs) -> dict[str, Any]: # noqa: D102
context = super().get_context_data(**kwargs)
... | MHLut/django-local-test | src/mysite/core/views.py | .py | faf7c4f43f0e4ea7 | 7.15 | 1 |
"""Version-compatible symptom-pattern classifier."""
from __future__ import annotations
import re
from collections.abc import Iterable
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
TARGET_COLUMN = "p... | younesgu/Medical_Diagnosis_V2 | src/medical_diagnosis/predictor.py | .py | 2bc2d077fdf402b6 | 7.15 | 1 |
"""
Глобальний кулдаун участі в групових іграх (pograb, skarb, тощо).
Одна людина може виграти приз раз на GAME_COOLDOWN_HOURS годин.
Кулдаун встановлюється після виграшу і блокує вхід у будь-яку гру.
"""
import aiosqlite
import logging
from datetime import datetime, timedelta, timezone
from .core import DB_PATH
GAM... | Yuriy-vasylevsky/TgBot | db/game_cooldown.py | .py | a9be58b02c877fce | 7.15 | 1 |
"""Client-side access to the Maude worker: errors and executor.
Runs in the MCP server process. Never imports the `maude` SWIG bindings — the
interpreter lives in a dedicated worker process (see `harold_mcp.maude.worker`).
"""
import multiprocessing
import threading
from collections.abc import Callable
from concurren... | demiourgoi/Harold | harold-mcp/src/harold_mcp/maude/executor.py | .py | 5bb07a5c4e580aa6 | 7 | 0 |
"""Interpreter side of the Maude worker: runs only in the worker process.
This module is pickled/spawn-imported by the worker process. The `maude` SWIG
bindings are imported **lazily** (inside functions), so importing this module
in the MCP server process never touches them.
Gotcha: the lazy `import maude` below is a... | demiourgoi/Harold | harold-mcp/src/harold_mcp/maude/worker.py | .py | 559db1b2744cdbc0 | 7 | 0 |
"""Harold MCP server: the FastMCP instance and its lifecycle.
Importing this module builds the `mcp` instance but does **not** initialize
Maude: the interpreter lives in a worker process managed by the server
lifespan (see `harold_mcp.maude`).
"""
import os
import signal
from collections.abc import AsyncGenerator
fro... | demiourgoi/Harold | harold-mcp/src/harold_mcp/server/server.py | .py | 2adbcccd8f14e223 | 7 | 0 |
"""Diagnostics tools for Maude programs.
The `maude_program_diagnostics` tool loads a Maude source file into the
interpreter (running in the dedicated worker process) and reports every
problem it finds, including warnings the interpreter can recover from.
"""
import os
from pathlib import Path
from typing import Lite... | demiourgoi/Harold | harold-mcp/src/harold_mcp/server/tools/diagnostics.py | .py | 8df9c43cd186d2c5 | 7 | 0 |
"""Application configuration, read from `HAROLD_*` environment variables."""
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""Harold configuration (flat for now; `maude_`-prefixed fields group by purpose).
- `HAROLD_MAUDE_WORKERS`: nu... | demiourgoi/Harold | harold-mcp/src/harold_mcp/settings.py | .py | f2b64b0a04b33567 | 7 | 0 |
"""Integration tests for `MaudeExecutor` against the real interpreter."""
import time
from collections.abc import Iterator
from concurrent.futures.process import BrokenProcessPool
from pathlib import Path
import pytest
from harold_mcp.maude import MaudeExecutor, MaudeWorkerCrashedError, worker
from harold_mcp.maude.... | demiourgoi/Harold | harold-mcp/tests/integration/test_maude_executor_integration.py | .py | 6641e4c999cccffd | 7.5 | 0 |
"""Integration tests for `harold_mcp.maude.worker` against the real interpreter.
The worker functions run in a spawned process (the real MCP server layout);
these tests validate the spawn/pickling story and the fd-2 capture on the
repo fixtures.
"""
import multiprocessing
from collections.abc import Iterator
from con... | demiourgoi/Harold | harold-mcp/tests/integration/test_maude_worker_integration.py | .py | 39b480b4a6e4f9e1 | 7.5 | 0 |
"""Unit tests for the Maude warning parser (no interpreter involved)."""
from harold_mcp.maude.worker import _parse_warnings
def test_quoted_file_format() -> None:
text = 'Warning: "hello.maude", line 3: skipped unexpected token: f'
assert _parse_warnings(text) == [{"line": 3, "message": "skipped unexpected ... | demiourgoi/Harold | harold-mcp/tests/unit/test_maude_worker.py | .py | de44e1e8e553e9fa | 7.5 | 0 |
"""
This module provides very simple dbus notifications.
"""
import os
import dbusnotify
from dotenv import dotenv_values
class NotifySender:
"""
This class represents a sender of dbus notifications. It can post individual messages, or you can initialise it
with a dictionary of messages. If the dictionar... | adambmarsh/dbus-notifier | dbus_notifier/notifysender.py | .py | a11c1be271293ce5 | 7 | 0 |
"""
Configuration Manager for Calcium Transient Analysis
Handles loading and saving analysis configuration to/from JSON files.
Author: hjoca
Date: 2026-02-09
"""
import json
from pathlib import Path
from typing import Optional, Dict, Any
from dataclasses import asdict
from ca_analyzer import AnalysisConfig
class ... | humbertojoca/CaTanalysis | config_manager.py | .py | 2d9a316362abe75e | 7 | 0 |
"""
Main script for calcium transient analysis.
This script provides a simple interface to analyze calcium transients
from linescan microscopy images.
Author: hjoca
Date: 2026-01-13
"""
import os
# Suppress Java native access warnings from JPype/Bioformats
os.environ['JAVA_TOOL_OPTIONS'] = '--enable-native-access=AL... | humbertojoca/CaTanalysis | main.py | .py | ca694814ad9869ac | 7 | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Modern Plot Styling for Calcium Transient Analysis
This module provides publication-quality plot styling using Seaborn
and matplotlib, replacing the legacy pp_style module.
Author: hjoca
Created: 2026-01-13
"""
import matplotlib.pyplot as plt
import seaborn as sns
... | humbertojoca/CaTanalysis | plot_style.py | .py | 858db6bf51feb314 | 7 | 0 |
import numpy as np
import pandas as pd
from scipy.stats import rankdata
import pdb
import copy
import sys
def tv_matrix_distance(P, Q):
return np.mean([0.5 * np.sum(np.abs(P[i] - Q[i])) for i in range(P.shape[0])])
def evaluate_estimate(T, T_hat, Y=None, Y_anchor_=None, Yt=None, K=None, epsilon0=0, verbose=False)... | tbortolotti/marginal-noise-adaptive-conformal | cln/T_estimation.py | .py | 32d47f336bd02ea4 | 7.15 | 1 |
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import pandas as pd
import pdb
from functools import lru_cache
import sys
from cln.utils_ecdf import EmpiricalCDF2DGrid
def construct_grid(num_steps, grid_type='uniform'):
if grid_type == 'uniform':
grid = np.linspace(0, 1, num_step... | tbortolotti/marginal-noise-adaptive-conformal | cln/asymptotic.py | .py | d45f261460bf4db6 | 7.15 | 1 |
import numpy as np
class EmpiricalCDF2DGrid:
def __init__(self, X, Y):
"""
Initialize the 2D empirical CDF by sorting the (X, Y) pairs together.
Parameters:
X (np.array): 1D array of observed values for the first random variable
Y (np.array): 1D array of observed values for... | tbortolotti/marginal-noise-adaptive-conformal | cln/utils_ecdf.py | .py | 133bc033d56ded35 | 7.15 | 1 |
"""Contains the raw dataset parsing and repackaging code for the BigEarthNet(-S2) dataset."""
import argparse
import dataclasses
import datetime
import json
import logging
import os
import pathlib
import pprint
import re
import typing
import cv2 as cv
import hub
import numpy as np
import pandas as pd
import tqdm
fro... | tbortolotti/marginal-noise-adaptive-conformal | third_party/bigearthnet/data/scripts/data_parser.py | .py | df666d2513f84762 | 7.15 | 1 |
"""Generate a mini dataset from the original BigEarth data.
This script assumes the original data was already downloaded and extracted.
It will then fetch the train, val and test splits from an external source, and
sample at random from that data to create a small debugging dataset. The debug
dataset can be used to wo... | tbortolotti/marginal-noise-adaptive-conformal | third_party/bigearthnet/data/scripts/prepare_dataset_subset.py | .py | faf226568e787e8a | 7.15 | 1 |
import json
import pprint
import numpy as np
import torch
from tqdm import tqdm
def compute_class_counts(onehot_labels: np.ndarray) -> np.ndarray:
"""Given a collection of onehot labels, compute the number of positives for each class."""
num_classes = len(
onehot_labels[0]
) # use first instance... | tbortolotti/marginal-noise-adaptive-conformal | third_party/bigearthnet/data/stats.py | .py | 5e847f7747d026df | 7.15 | 1 |
import logging
import os
import pathlib
import tarfile
import typing
import gdown
import hub
import numpy as np
import random
import torch
import pytorch_lightning as pl
import torch.utils.data.dataloader
import torch.utils.data.dataset
from torch.utils.data import SequentialSampler, SubsetRandomSampler
logger = logg... | tbortolotti/marginal-noise-adaptive-conformal | third_party/bigearthnet/datamodules/bigearthnet_datamodule.py | .py | d620d72e62a3c9c9 | 7.15 | 1 |
import importlib.resources
import json
import logging
import os
import typing
import numpy as np
import copy
import timm
import torch
import torch.nn as nn
from torchgeo.models import ResNet18_Weights, get_model
import pytorch_lightning as pl
import torch
from hydra.utils import instantiate
from omegaconf import Dict... | tbortolotti/marginal-noise-adaptive-conformal | third_party/bigearthnet/models/bigearthnet_module.py | .py | 8d2f7a70ea8f6da6 | 7.15 | 1 |
import logging
import torch
import torch.nn as nn
log = logging.getLogger(__name__)
class Baseline(torch.nn.Module): # pragma: no cover
"""Baseline Model Class.
Inherits from the given framework's model class. This is a simple MLP model.
"""
def __init__(
self,
num_classes: int,
... | tbortolotti/marginal-noise-adaptive-conformal | third_party/bigearthnet/models/nets/baseline.py | .py | d57637600981a045 | 7.15 | 1 |
import math
import warnings
from typing import List
from torch.optim import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
class WarmupCosineLR(_LRScheduler):
"""
Sets the learning rate of each parameter group to follow a linear warmup schedule
between warmup_start_lr and base_lr followed by... | tbortolotti/marginal-noise-adaptive-conformal | third_party/pytorch-cifar10/schduler.py | .py | ffcf33a7b468bb13 | 7.15 | 1 |
"""Discovery endpoint for the first governed API contract."""
from flask import current_app, jsonify
from flask_restx import Namespace, Resource
from .versioning import CURRENT_API_BASE_PATH, CURRENT_API_VERSION, IMPLEMENTATION_VERSION
api = Namespace(
"api-v1",
description="Metadata and discovery links for... | CCMMMA/it.uniparthenope.meteo.api | apis/namespace_api_v1.py | .py | 40c334f76b8b89f4 | 7.15 | 1 |
"""Administrative reporting resources for the governed API."""
from flask import current_app, jsonify, request
from flask_restx import Namespace, Resource
from apis.authentication import require_api_key
from core.RuntimeServices import RUNTIME_SERVICES_EXTENSION
api = Namespace("api-v1-admin", description="Protecte... | CCMMMA/it.uniparthenope.meteo.api | apis/namespace_api_v1_admin.py | .py | 518545dbfaf58896 | 7.15 | 1 |
"""Version 1 product discovery and metadata resources."""
from flask import current_app, jsonify
from flask_restx import Namespace, Resource
from core.GetParams import get_params
from core.RuntimeServices import RUNTIME_SERVICES_EXTENSION
from apis.authentication import require_api_key
from apis.namespace_products im... | CCMMMA/it.uniparthenope.meteo.api | apis/namespace_api_v1_products.py | .py | 560045fa746cfda7 | 7.15 | 1 |
"""Application-facing endpoints for tiled payload services."""
import json
from flask import current_app, jsonify, request
from flask_restx import Namespace, Resource
from core.GetParams import get_params
from core.MemcachedMethodHandlers import get_resource, set_resource
from core.RuntimeServices import RUNTIME_SER... | CCMMMA/it.uniparthenope.meteo.api | apis/namespace_apps.py | .py | 38eb86c3b89ebbe9 | 7.15 | 1 |
"""RESTX namespace for box-oriented place summaries."""
from flask_restx import Namespace, Resource
from core.Box import Box
from flask import jsonify
from core.GetParams import get_params
api = Namespace('box', description='Box-oriented content endpoints.')
# TESTED AND WORKING -- NO CACHE USE
@api.route('/today/<... | CCMMMA/it.uniparthenope.meteo.api | apis/namespace_box.py | .py | 6f45bb90fcdc5320 | 7.15 | 1 |
"""RESTX namespace exposing legal and privacy content."""
from flask_restx import Namespace, Resource
from flask import current_app, jsonify
from core.GetParams import get_params
from core.RuntimeServices import RUNTIME_SERVICES_EXTENSION
api = Namespace('legal', description='Legal and compliance content endpoints.'... | CCMMMA/it.uniparthenope.meteo.api | apis/namespace_legal.py | .py | fb0bd87c1faec522 | 7.15 | 1 |
"""RESTX namespace exposing API version metadata."""
from flask_restx import Namespace, Resource
from flask import current_app, jsonify
from .versioning import IMPLEMENTATION_VERSION
api = Namespace('version', description='Service version and runtime environment metadata.')
# TESTED AND WORKING -- NO CACHE USE
@ap... | CCMMMA/it.uniparthenope.meteo.api | apis/namespace_version.py | .py | fb2b48abdcdc53fe | 7.15 | 1 |
"""RESTX namespace serving the latest webcam imagery."""
import os
from flask_restx import Namespace, Resource
from flask import current_app, send_file
api = Namespace('webcam', description='Latest webcam image retrieval endpoints.')
# TESTED AND WORKING -- NO CACHE USE
# I DON'T HAVE WEBCAM DIRECTORY
@api.route("... | CCMMMA/it.uniparthenope.meteo.api | apis/namespace_webcam.py | .py | a389f773d9f321cb | 7.15 | 1 |
"""Shared metadata and response handling for governed API versions."""
from __future__ import annotations
from flask import Flask, request
CURRENT_API_VERSION = "1"
CURRENT_API_BASE_PATH = f"/api/v{CURRENT_API_VERSION}"
IMPLEMENTATION_VERSION = "4.01"
def _legacy_successor(path):
"""Return a successor URI only... | CCMMMA/it.uniparthenope.meteo.api | apis/versioning.py | .py | 451d977cc7765716 | 7.15 | 1 |
"""Application bootstrap for the meteorological API service."""
import os
from flask import Flask
from flask_cors import CORS
from apis import api
from apis.versioning import register_version_response_headers
from apis.authentication import register_api_key_observation
from pymemcache.client.base import Client
from c... | CCMMMA/it.uniparthenope.meteo.api | app.py | .py | dc1e752067f8ea35 | 7.15 | 1 |
"""Persistent domain models for API-key requests, credentials, and audit events."""
from __future__ import annotations
from datetime import datetime, timezone
from uuid import uuid4
from core.Models import db
def utcnow():
"""Return a timezone-independent UTC value suitable for current SQL columns."""
retu... | CCMMMA/it.uniparthenope.meteo.api | core/ApiKeyModels.py | .py | b7352568def5398d | 7.15 | 1 |
"""Helpers for retrieving box-oriented place content."""
class Box(object):
"""Service or helper that encapsulates box behavior."""
def get_today(self, params):
"""Return today."""
result = {
"placeLabel": "Provincia di NAPOLI",
"placeUrl": "http:\/\/ccmmma.uniparthenop... | CCMMMA/it.uniparthenope.meteo.api | core/Box.py | .py | 1e110a3451526ab6 | 7.15 | 1 |
"""Helpers for reading query parameters from Flask requests."""
from flask import request
def get_param(name):
"""Return a single request parameter with optional fallback handling."""
value = None
try:
value = request.args.get(name, None)
except:
pass
if value is None:
try... | CCMMMA/it.uniparthenope.meteo.api | core/GetParams.py | .py | df7577dcb6a40d76 | 7.15 | 1 |
"""Database models used by the meteorological API."""
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Instrument(db.Model):
"""Service or helper that encapsulates instrument behavior."""
__tablename__ = 'instruments'
id = db.Column(db.String(50), primary_key=True, unique=True, nullable=F... | CCMMMA/it.uniparthenope.meteo.api | core/Models.py | .py | 90567b4a102f2523 | 7.15 | 1 |
"""Place lookup services used by the public API endpoints."""
import json
import os
import netCDF4
import numpy as np
from math import radians, cos, sin, asin, sqrt
from datetime import datetime
from core.MongoDbHandlers import MongoDBHandlers
from core.Logger import logger
try:
from numpy.compat import basestrin... | CCMMMA/it.uniparthenope.meteo.api | core/Places.py | .py | 6e6566a5bec04e4c | 7.15 | 1 |
"""High-throughput request popularity tracking for cache-aware product routes."""
from __future__ import annotations
import json
import threading
import time
from pathlib import Path
class RequestPopularityTracker:
"""Track and persist the most frequently requested forecast and time-series signatures."""
d... | CCMMMA/it.uniparthenope.meteo.api | core/RequestPopularityTracker.py | .py | e38b11c5df61471e | 7.15 | 1 |
"""Services for exposing Slurm-related operational data."""
# import subprocess
from fabric import Connection
from paramiko.ssh_exception import NoValidConnectionsError, SSHException
# import ConfigParser
class SlurmServices(object):
"""Service or helper that encapsulates slurm services behavior."""
cfg = {}... | CCMMMA/it.uniparthenope.meteo.api | core/SlurmServices.py | .py | 2017a0cf1c8727bf | 7.15 | 1 |
"""Tile-generation helpers for application-facing geospatial endpoints."""
import math
import datetime
from concurrent.futures import ThreadPoolExecutor
from functools import partial
from geojson import Feature, FeatureCollection, Point
from core.Places import Places
class Tiles(object):
"""Service or helper tha... | CCMMMA/it.uniparthenope.meteo.api | core/Tiles.py | .py | 36588f6c2d2f56b6 | 7.15 | 1 |
"""Shared cache-key construction utilities.
Keeping key generation in one module prevents the memory and disk cache layers
from silently drifting apart when their implementations change.
"""
from __future__ import annotations
import hashlib
from typing import Any
def resolve_cache_key_source(request: Any = None, o... | CCMMMA/it.uniparthenope.meteo.api | core/cache_keys.py | .py | c7e5e42a25185b0f | 7.15 | 1 |
"""Pytest fixtures for isolated API endpoint tests."""
from __future__ import annotations
import importlib
import json
import os
import sys
from dataclasses import dataclass
from pathlib import Path
import pytest
REPO_ROOT = Path(__file__).resolve().parents[1]
VARS_CONTROL_DIR = REPO_ROOT / "vars-control-file"
STA... | CCMMMA/it.uniparthenope.meteo.api | tests/conftest.py | .py | 82aebceee3308fb2 | 7.65 | 1 |
"""Tests for the shared memory and disk cache infrastructure."""
from __future__ import annotations
import hashlib
import json
import os
import time
from types import SimpleNamespace
import pytest
from core.cache_keys import make_cache_key
from core.ManageDiskCache import ManageDiskCache
from core.MemcachedMethodHa... | CCMMMA/it.uniparthenope.meteo.api | tests/test_cache_infrastructure.py | .py | ea2de5bd105419fa | 7.65 | 1 |
"""Shared plumbing for command implementations."""
import pygit2
import typer
from ..gitio import RepositoryNotFound, checkout_branch, open_repository
from ..store import GitRefStore
def require_repo() -> pygit2.Repository:
"""Open the repository from cwd or exit with an error."""
try:
return open_r... | isselab/feature-oriented-git | git_feature/commands/common.py | .py | 954032a4a10e7225 | 7.3 | 3 |
"""`git feature init` — initialize the feature store, hooks, change-id backfill, and model.cfr."""
import json
from importlib import metadata
from pathlib import Path
import pygit2
import typer
from ..gitio import RepositoryNotFound, open_repository
from ..gitio.hooks import install_hooks
from ..identity import Chan... | isselab/feature-oriented-git | git_feature/commands/init.py | .py | 7b8a5ffe548c91c3 | 7.3 | 3 |
"""Hunk capture: anchor a commit's hunks and write feature annotations."""
from dataclasses import dataclass, field
from datetime import UTC, datetime
from fnmatch import fnmatch
import pygit2
from ...gitio import Hunk, commit_diff, patch_id, resolve_commit
from ...identity import ChangeIdMap, anchor_from_hunk
from ... | isselab/feature-oriented-git | git_feature/domain/annotate/capture.py | .py | e29099006f8e0983 | 7.3 | 3 |
"""Variant derivation stages 3–4: materialize the reduced tree and verify it."""
import pygit2
from ...gitio import blob_data, rewrite_tree
from ...identity import ChangeIdMap, original_added_lines
from ...store.base import Store
from ...store.types import RegionDecision
from .pipeline import Conflict, Projection
d... | isselab/feature-oriented-git | git_feature/domain/derivation/materialize.py | .py | d900ebe6b15a22de | 7.3 | 3 |
"""Putback: remap view-space edits through a derivation manifest onto the source tree."""
from dataclasses import dataclass, field
from ...gitio import FileDiff, Hunk
from ...store.types import DerivationManifest
from .pipeline import Conflict
@dataclass(frozen=True)
class MappedEdit:
"""One hunk translated fro... | isselab/feature-oriented-git | git_feature/domain/derivation/putback.py | .py | 13a27f3cfe361316 | 7.3 | 3 |
"""Variant materialization driver shared by checkout, view, and putback."""
from dataclasses import dataclass
import pygit2
from ...gitio import compare_and_swap_ref, create_commit, read_ref
from ...store.base import Store
from ...store.types import DerivationManifest
from .materialize import materialize_tree, verif... | isselab/feature-oriented-git | git_feature/domain/derivation/service.py | .py | f12551b171e24e08 | 7.3 | 3 |
"""Catalog and annotation lookups shared by the query commands."""
import re
from collections.abc import Iterator
from ...store.base import Store
from ...store.types import Annotation
_IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_-]*")
def presence_features(presence: str) -> set[str]:
"""Feature names referenced b... | isselab/feature-oriented-git | git_feature/domain/query/catalog.py | .py | 73c4262fdf829497 | 7.3 | 3 |
"""Well-formedness checks for a parsed feature model."""
from .ast import Module, referenced_features, render
from .evaluator import Evaluator
def model_feature_names(module: Module) -> set[str]:
"""Names annotations may reference: every clafer that is not an instance."""
evaluator = Evaluator(module)
re... | isselab/feature-oriented-git | git_feature/domain/variability/lint.py | .py | c0332769a1de78a2 | 7.3 | 3 |
"""Presence-condition algebra: `name`, `!`, `&`, `|`, parentheses."""
import re
from collections.abc import Iterable, Mapping
from itertools import product
from .ast import And, Expr, Not, Or, Ref, referenced_features
_TOKEN = re.compile(r"\s*([A-Za-z_][A-Za-z0-9_-]*|&&|\|\||[!&|()])")
_MAX_SAT_FEATURES = 16
clas... | isselab/feature-oriented-git | git_feature/domain/variability/presence.py | .py | 3edd6b4925f7fefb | 7.3 | 3 |
"""Blame and tree-content access used by the region resolver."""
from collections.abc import Iterator
import pygit2
from .diff import resolve_commit
def line_origins(repo: pygit2.Repository, rev: str | pygit2.Commit, path: str) -> list[str] | None:
"""Per-line origin commit sha of a file at a revision, or None... | isselab/feature-oriented-git | git_feature/gitio/blame.py | .py | 4bec8a73a2fd620c | 7.3 | 3 |
"""Commit diffs exposed as plain data (no pygit2 types leak upward)."""
from dataclasses import dataclass
import pygit2
@dataclass(frozen=True)
class Hunk:
"""One contiguous change: spans are (start_line, line_count), 1-based."""
old_span: tuple[int, int]
new_span: tuple[int, int]
header: str
a... | isselab/feature-oriented-git | git_feature/gitio/diff.py | .py | acaa1c225799d1ab | 7.3 | 3 |
"""Revision-walk helpers."""
from collections.abc import Iterator
import pygit2
from .diff import resolve_commit
def iter_commits(
repo: pygit2.Repository,
rev: str | None = None,
exclude: list[str] | None = None,
) -> Iterator[pygit2.Commit]:
"""Yield commits reachable from `rev` (default HEAD), n... | isselab/feature-oriented-git | git_feature/gitio/history.py | .py | 7059a776a455fcf8 | 7.3 | 3 |
"""Chained git hook installation: a dispatcher per hook plus a hook.d directory."""
import shlex
import shutil
from pathlib import Path
import pygit2
HOOK_NAMES = ("post-commit", "post-rewrite")
_DISPATCHER_MARKER = "# git-feature chained hook dispatcher"
_HOOK_SCRIPT_MARKER = "# installed by git-feature"
_DISPATCH... | isselab/feature-oriented-git | git_feature/gitio/hooks.py | .py | 5f510685429fbd1b | 7.3 | 3 |
"""Stable patch-id: hash of a commit's diff with offsets and whitespace normalized."""
import hashlib
import pygit2
from .diff import commit_diff
def patch_id(repo: pygit2.Repository, rev: str | pygit2.Commit) -> str:
"""Return a hex id identifying a commit's diff regardless of position or whitespace."""
d... | isselab/feature-oriented-git | git_feature/gitio/patchid.py | .py | 680fb748da7802b3 | 7.3 | 3 |
"""Reference reading and guarded writing."""
import pygit2
class RefUpdateConflict(Exception):
"""Raised when a guarded ref update finds an unexpected current target."""
def read_ref(repo: pygit2.Repository, name: str) -> str | None:
"""Return the commit sha a ref points to, or None if the ref doesn't exis... | isselab/feature-oriented-git | git_feature/gitio/refio.py | .py | 86306d3924beb8e5 | 7.3 | 3 |
"""Repository discovery and access."""
import os
from pathlib import Path
import pygit2
class RepositoryNotFound(Exception):
"""Raised when no git repository can be discovered from the given path."""
def open_repository(path: str | Path | None = None) -> pygit2.Repository:
"""Open the repository containin... | isselab/feature-oriented-git | git_feature/gitio/repo.py | .py | 8c77f2f4fb1d67a8 | 7.3 | 3 |
"""Tree rewriting and commit creation for derived variants."""
import pygit2
from .diff import resolve_commit
def blob_data(repo: pygit2.Repository, rev: str | pygit2.Commit, path: str) -> bytes | None:
"""Raw bytes of a file at a revision, or None if absent or not a blob."""
commit = resolve_commit(repo, r... | isselab/feature-oriented-git | git_feature/gitio/tree.py | .py | 9261f786ef1a50d7 | 7.3 | 3 |
"""
Advent Calendar Core Engine and Unlock Logic.
This module provides the backend logic for storing, unlocking, and serving
daily Advent content for December 1-24. It includes server-authoritative
unlock logic and admin override support.
"""
import copy
import json
import os
from dataclasses import dataclass, field
... | WxboySuper/Santa_Tracker | archive/flask-legacy/utils/advent.py | .py | 9cfdcabd0871e4d3 | 7.15 | 1 |
from typing import List
from src.utils.locations import Location
class Tracker:
"""Tracks Santa's journey through various locations."""
def __init__(self) -> None:
self._locations: List[Location] = []
self._status: str = "Waiting for Santa's arrival"
def update_location(self, location: ... | WxboySuper/Santa_Tracker | archive/flask-legacy/utils/tracker.py | .py | d1ec30b95b7cab23 | 7.15 | 1 |
import pygame
import sys
# Konstanten
FIELD_SIZE = 20 # Größe eines Felds in Pixeln
GRID_SIZE = 1000 # Anzahl der Felder pro Seite
SCREEN_SIZE = FIELD_SIZE * 50 # Sichtbarer Bereich in Pixeln
class Game:
def __init__(self):
pygame.init()
self.screen = pygame.display.set_mode((SCREEN_SIZE, SCREE... | YemotaY/C1M1lidar | SIMU.py | .py | cb0a2bc9b0f7d2ff | 7 | 0 |
import matplotlib.pyplot as plt
import matplotlib
import time
import json
import numpy as np
import ast
from matplotlib.backend_bases import MouseEvent
import tkinter as tk
from tkinter import messagebox
import math
matplotlib.use('TkAgg')
class SimpleSLAM:
def __init__(self):
"""
Initialisiert d... | YemotaY/C1M1lidar | SimpleSLAM.py | .py | 864600bd7dab9642 | 7 | 0 |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
from sklearn.neighbors import NearestNeighbors
import pandas as pd
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
def wraptopi(phi):
return np.mod(phi + np.pi, 2*np.pi) - np.pi
def best_fit_transform(A, B):
'''
Ca... | YemotaY/C1M1lidar | slam/icp.py | .py | 1595784530b78573 | 7 | 0 |
# Utility file with functions for handling rotations
#
# Author: Trevor Ablett
# University of Toronto Institute for Aerospace Studies
import numpy as np
def skew_symmetric(v):
""" Skew symmetric operator for a 3x1 vector. """
return np.array(
[[0, -v[2], v[1]],
[v[2], 0, -v[0]],
[-v... | YemotaY/C1M1lidar | slam/rotations.py | .py | 7e63577bb9a5c028 | 7 | 0 |
import matplotlib.pyplot as plt
import matplotlib
import json
import numpy as np
from matplotlib.backend_bases import MouseEvent
import tkinter as tk
from tkinter import messagebox
import math
import sys
matplotlib.use('TkAgg')
class SimpleSLAM:
def __init__(self):
"""
Initialisiert den LiDAR-Pl... | YemotaY/C1M1lidar | wallPlot.py | .py | d9e95be945440ace | 7 | 0 |
import json
import os
import yaml
from collections import Counter
from pathlib import Path
from PIL import Image
CLASS_NAMES = {
0: "Arthropod",
} # as they appear in YOLO
# shift by one. YOLO starts at 0 but some COCO formats ignore 0
CLASS_NAMES_COCO = {i + 1: name for i, name in CLASS_NAMES.items()}
def get_... | EcdysisFoundation/ultralytics | dataset_generation/eval_test_dataset.py | .py | 02a538157bb03f13 | 7.5 | 0 |
import os
import random
import logging
import numpy as np
import pandas as pd
import shutil
from sklearn.model_selection import train_test_split
from pathlib import Path
from tqdm import tqdm
from .utils import save_yaml_file, check_minimum_length, VALID_IMG_EXTENSIONS
SEED = 42
logger = logging.getLogger(__name__)
... | EcdysisFoundation/ultralytics | dataset_generation/split.py | .py | 973d6b4c6a720567 | 7 | 0 |
import json
import os
import numpy as np
from pathlib import Path
import threading
from concurrent.futures import ThreadPoolExecutor
from sahi.predict import get_sliced_prediction
from .sahi_segmentation import DETECTION_MODEL
FILE_LOCK = threading.Lock()
TEMP_RESULTS_PREFIX = 'temp_results_'
class NumpyEncoder(j... | EcdysisFoundation/ultralytics | inference/sahi_segmentation_eval.py | .py | 5e133afd3b3e5f57 | 7 | 0 |
import os
import json
from sahi.predict import get_sliced_prediction
from sahi import AutoDetectionModel
# SAHI INFERENCE FOR OBJECT DETECTION
# Saving as label studio formatted prediction
MODEL_PATH = 'runs/detect/train6/weights/best.pt'
detection_model = AutoDetectionModel.from_pretrained(
model_type='ultra... | EcdysisFoundation/ultralytics | inference/sahi_stitched.py | .py | 050085dbe6ea3026 | 7 | 0 |
import cv2
from math import sqrt
import numpy as np
from sahi.prediction import ObjectPrediction
from skimage.morphology import remove_small_objects
from skimage.measure import label
def save_labeling_img(path, full_img_save_path):
"""
Resizes for labeling app, below Decompression Bomb threshold.
Saves t... | EcdysisFoundation/ultralytics | inference/utils.py | .py | 6a7c42ba55a8bdcc | 7 | 0 |
#!/usr/bin/env python3
"""Build script for portable NetConnect executables using PyInstaller."""
import sys
import os
import subprocess
import platform
import shutil
from pathlib import Path
# Force UTF-8 output on Windows (cp1252 can't encode checkmarks)
if sys.platform == "win32":
sys.stdout.reconfigure(encodin... | DavoudTeimouri/NetConnect-Tool | scripts/build_portable.py | .py | a8c4d4bad8e174f1 | 7.15 | 1 |
"""Configuration management for NetConnect."""
import os
import sys
import yaml
from dataclasses import dataclass, field, asdict
from typing import Optional
from pathlib import Path
@dataclass
class NetConnectConfig:
"""NetConnect configuration."""
defaults: dict = field(default_factory=lambda: {
"du... | DavoudTeimouri/NetConnect-Tool | src/netconnect/config.py | .py | b7d38ca38ae473c8 | 7.15 | 1 |
"""Core connection testing logic for NetConnect."""
import socket
import ipaddress
import time
import ssl
from dataclasses import dataclass
from typing import List, Optional
from enum import Enum
class Protocol(Enum):
TCP = "tcp"
UDP = "udp"
BOTH = "both"
@dataclass
class ConnectionResult:
"""Resul... | DavoudTeimouri/NetConnect-Tool | src/netconnect/core.py | .py | 0dc124f336b11b1f | 7.15 | 1 |
"""Tests for NetConnect core functionality."""
import pytest
from netconnect.core import (
parse_ip_range,
parse_port_range,
banner_text,
Protocol,
create_tcp_listener,
create_udp_listener,
create_listeners,
close_listeners,
)
def test_parse_ip_range_single():
"""Test parsing sing... | DavoudTeimouri/NetConnect-Tool | tests/test_core.py | .py | 8d1cab61a50becb5 | 7.65 | 1 |
"""Common testing fixtures."""
import ipaddress
import json
import os
import pathlib
import re
import subprocess
import tempfile
from collections import Counter
from collections.abc import Callable, Generator
from contextlib import contextmanager
from typing import Any, cast
import google.auth
import googleapiclient.... | memes/terraform-google-restricted-apis-dns | tests/conftest.py | .py | fb8fa927d031ab4f | 7.5 | 0 |
"""Test fixture for Restricted APIs DNS module with custom IPv4 addresses."""
import pathlib
from collections.abc import Callable, Generator
from typing import Any
import pytest
from .conftest import EXPECTED_DNS_ZONES, run_tofu_in_workspace
FIXTURE_NAME = "custom-ipv4"
FIXTURE_LABELS = {
"fixture": FIXTURE_NAM... | memes/terraform-google-restricted-apis-dns | tests/test_custom_ipv4.py | .py | a418917c3dca7fff | 7.5 | 0 |
"""Test fixture for Restricted APIs DNS module with custom IPv4 addresses."""
import pathlib
from collections.abc import Callable, Generator
from typing import Any
import pytest
from .conftest import EXPECTED_DNS_ZONES, run_tofu_in_workspace
FIXTURE_NAME = "custom-ipv4"
FIXTURE_LABELS = {
"fixture": FIXTURE_NAM... | memes/terraform-google-restricted-apis-dns | tests/test_custom_ipv4_ipv6.py | .py | 381686840d0085ce | 7.5 | 0 |
"""Test fixture for Restricted APIs DNS module with custom IPv4 addresses."""
import pathlib
from collections.abc import Callable, Generator
from typing import Any
import pytest
from .conftest import EXPECTED_DNS_ZONES, run_tofu_in_workspace
FIXTURE_NAME = "custom-ipv4"
FIXTURE_LABELS = {
"fixture": FIXTURE_NAM... | memes/terraform-google-restricted-apis-dns | tests/test_custom_ipv6.py | .py | 9dc011a5f245a4af | 7.5 | 0 |
"""Test fixture for Restricted APIs DNS module with explicit description."""
import pathlib
from collections.abc import Callable, Generator
from typing import Any
import pytest
from .conftest import EXPECTED_DNS_ZONES, EXPECTED_RESTRICTED_A_RRS, EXPECTED_RESTRICTED_AAAA_RRS, run_tofu_in_workspace
FIXTURE_NAME = "de... | memes/terraform-google-restricted-apis-dns | tests/test_description.py | .py | be9499d9e32f1b7e | 7.5 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.