text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
#!/usr/bin/env python3
"""
Backfill the street_walks absolute-length columns from coverage artifacts on disk.
Background: schema v12 added `length_km`, `length_km_covered`,
`length_km_covered_any` and `median_covered_age_years` to `street_walks`,
populated by the collector at registration time. Walks cataloged before ... | jonfroehlich/streetscape-tracker | scripts/backfill_streetwalk_length.py | .py | 8aed41d4c6beabc2 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Build the boundary-review visualization (issue #91, part 2 review aid).
The frozen-rectangle boundary audit flagged cities whose search grid may be
mis-centered or mis-sized against their OSM boundary. Judging those cases from
CSV columns is impractical, so this tool renders each one on a ma... | jonfroehlich/streetscape-tracker | scripts/build_boundary_review.py | .py | 7c65df1ca8a070c7 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Cap frozen grids that are too large for a single night's collection (issue #166).
A handful of cities have frozen grids so big they are effectively uncollectable,
and because the scheduler works a stalest-first queue serially, each one eats
hours that the rest of the frame never gets back. S... | jonfroehlich/streetscape-tracker | scripts/cap_oversized_grids.py | .py | e5f166ca770b1878 | 7.24 | 2 |
"""
What capture-date formats are actually on disk, and what a strict reader cost
us (issue #226).
Reads data already collected — no network, no provider credentials, no new
requests. That makes this the smallest an experiment gets, and it is written up
anyway (docs/experiments/capture-date-precision.md), because the ... | jonfroehlich/streetscape-tracker | scripts/capture_date_precision_analyze.py | .py | 3a5dc03ef79c5afc | 7.24 | 2 |
"""
Shared distribution summaries for the docs/experiments/ studies.
Every writeup in docs/experiments/ has to quote the DISTRIBUTION it summarizes —
percentiles and n, not a headline number — because the shape is usually the
finding. That made the same linear-interpolation percentile appear three times
(`night_length... | jonfroehlich/streetscape-tracker | scripts/experiment_stats.py | .py | e0c471267a72e418 | 7.24 | 2 |
"""
Shared figure styling for the docs/experiments/ studies.
Both `grid_density_analyze.py` and `pano_spacing_analyze.py` publish figures
beside their writeups, and the two are meant to read as one system — so the
palette lives in exactly one place rather than being copied and drifting.
Kept deliberately small: only ... | jonfroehlich/streetscape-tracker | scripts/experiment_style.py | .py | 56853c5f16753ec9 | 7.24 | 2 |
"""
Shared logic for the issue #106 grid-density experiment (20 m vs 10 m vs 5 m vs
road-clipped 5 m GSV sampling).
The experiment queries ONLY a 5 m lattice per area, aligned so the production 20 m
grid is a bit-identical index subset; the coarser variants and the road-clipped
variant are derived offline from that si... | jonfroehlich/streetscape-tracker | scripts/grid_density_common.py | .py | d78ffffaf15e44bc | 7.24 | 2 |
"""
Issue #225: audit KartaView capture dates against their own upload timestamps.
python scripts/kartaview_shotdate_audit.py --docs-dir docs/experiments
WHAT THIS MEASURES. A photo cannot be captured after it was uploaded, so
`shotDate < dateAdded` is an invariant every honest record must satisfy. Sampling
Karta... | jonfroehlich/streetscape-tracker | scripts/kartaview_shotdate_audit.py | .py | f9986a3b5c922f3d | 7.24 | 2 |
#!/usr/bin/env python3
"""
Purge runs whose snapshots are tainted by transient API failures (throttling)
so they can be re-collected cleanly.
Background (2026-07-16): before client-side rate limiting, a fast host could
exceed the GSV metadata per-minute quota mid-run; the throttled responses were
written into the immu... | jonfroehlich/streetscape-tracker | scripts/purge_tainted_runs.py | .py | 8e6b1783c6201459 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Register the worldwide sampling-frame cities in the catalog, freezing each
city's grid geometry — WITHOUT downloading any imagery.
This lets the boundary-audit workflow (scripts/audit_city_boundaries.py ->
build_boundary_review.py -> apply_decisions.py) vet the grids BEFORE the first
collect... | jonfroehlich/streetscape-tracker | scripts/register_frame.py | .py | ff8dd87642840805 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Rename road-walk artifacts written before streetwalk filenames carried provider
and network-type tokens, and repoint their catalog rows.
Background: `naming.generate_streetwalk_filename` originally took no provider,
so every walk of a city at a given spacing and run date produced the SAME
na... | jonfroehlich/streetscape-tracker | scripts/repair_streetwalk_names.py | .py | 51d2caa486124334 | 7.24 | 2 |
#!/usr/bin/env python3
"""
One-time boundary re-registration (issue #91, part 2).
The frozen search grids were centered on the geocoder's reported point instead
of the midpoint of the OSM bounding box the grid dimensions are derived from
(fixed going forward in cli.py / geoutils.EnhancedLocation.bbox_center). This
lef... | jonfroehlich/streetscape-tracker | scripts/reregister_boundaries.py | .py | c23a5fd89ef0c2d9 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Manually resize a single city's frozen search grid.
Grid geometry is normally immutable so run-to-run diffs align on an identical
rectangle. This is the deliberate escape hatch (``db.update_city_geometry``)
for the case the bulk boundary re-registration (issue #91) can't fix: a town
whose OS... | jonfroehlich/streetscape-tracker | scripts/resize_city.py | .py | e92843df8e99da16 | 7.24 | 2 |
"""
Operator alerting for the scheduler (issue #92 deploy hardening).
Sends a short email when a nightly ``run-due`` finishes unhealthy (too many
failed collections, or a crash) so a deployment on makelab1 doesn't fail
silently. Deliberately transport-agnostic — the box may have a working
``mail`` relay, or need ``msm... | jonfroehlich/streetscape-tracker | streetscape_metadata_tracker/alerting.py | .py | 38f02edb1f32afb9 | 7.24 | 2 |
"""
Boundary audit logic (issue #91, step 1): compare each city's frozen search
rectangle against the OSM boundary Nominatim reports for it today.
Grid geometry is frozen at registration (see db.py), so a rectangle inferred
from a bad geocode — an administrative region, a township, a neighborhood —
is locked into ever... | jonfroehlich/streetscape-tracker | streetscape_metadata_tracker/boundary_audit.py | .py | 3a6dc8b3eacfaec8 | 7.24 | 2 |
"""
Checkpoint plumbing shared by the census providers.
A census provider's crawl is long enough that losing it to an interruption costs
real money against a per-IP budget: KartaView's radius sweep is hours (Singapore
~10.4 h), and Mapillary's tile census is tens of minutes against a 1,750/day
channel budget that a re... | jonfroehlich/streetscape-tracker | streetscape_metadata_tracker/checkpointing.py | .py | f91a084a7ed11533 | 7.24 | 2 |
"""
Resolve a city query to a catalog row, registering it (with frozen grid
geometry) the first time we see it.
This is the one place a city enters the catalog interactively. It lived inside
cli.py until issue #215 needed it from the scheduler too: the road-walk
collector requires an already-registered city (collect.p... | jonfroehlich/streetscape-tracker | streetscape_metadata_tracker/city_registration.py | .py | bb8d301bf67d292f | 7.24 | 2 |
import logging
import os
import stat
from typing import Any
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
# Standard metadata schema — the shared core written by BOTH providers.
# GSV's documented metadata endpoint returns only copyright/date/location/
# pano_id/status (audited: nothing... | jonfroehlich/streetscape-tracker | streetscape_metadata_tracker/config.py | .py | e35858a20f5f3443 | 7.24 | 2 |
"""
Run-to-run diff engine for temporal GSV tracking.
Compares two collection runs of the same city and reports what changed:
- Pano level (primary): which pano_ids were added, removed, or persisted,
and which persisted panos had their capture_date change.
- Grid-point level (only when the two runs sampled the same... | jonfroehlich/streetscape-tracker | streetscape_metadata_tracker/diff.py | .py | 6f95939f461eece6 | 7.24 | 2 |
# Copyright Amazon.com Inc. or its affiliates. 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. A copy of the
# License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanyin... | aws-controllers-k8s/networkfirewall-controller | test/e2e/__init__.py | .py | 629cbeaa37befcda | 7.5 | 0 |
# Copyright Amazon.com Inc. or its affiliates. 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. A copy of the
# License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying... | aws-controllers-k8s/networkfirewall-controller | test/e2e/tests/helper.py | .py | 6958c895637e219c | 7.5 | 0 |
import os
import openeo
import pytest
import requests
@pytest.fixture
def api_base_url():
try:
endpoint = os.environ["OPENEO_BACKEND_URL"]
except Exception:
raise RuntimeError(
"Environment variable 'OPENEO_BACKEND_URL' should be set"
" with URL pointing to OpenEO back... | Open-EO/openeo-aggregator | integration-tests/conftest.py | .py | e6d171cec951b753 | 7.65 | 1 |
import logging
import openeo
import pytest
_log = logging.getLogger(__name__)
def test_openeo_cloud_root_return_sensible_response(connection: openeo.Connection):
"""Check that ${OPENEO_BACKEND_URL}/ returns something sensible."""
path = "/"
response = connection.get(path)
_log.info("As curl:\n" + ... | Open-EO/openeo-aggregator | integration-tests/test_integration.py | .py | c83754af80addcae | 7.65 | 1 |
"""
openeo-aggregator Flask app
"""
import logging
import os
from pathlib import Path
from typing import List, Optional, Union
import flask
import openeo_driver.views
from openeo_driver.util.logging import (
LOG_HANDLER_STDERR_JSON,
LOGGING_CONTEXT_FLASK,
get_logging_config,
setup_logging,
)
from open... | Open-EO/openeo-aggregator | src/openeo_aggregator/app.py | .py | b553586bb81895fd | 7.15 | 1 |
import abc
import contextlib
import functools
import json
import logging
import time
import zlib
from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Tuple, Union
import kazoo.exceptions
import kazoo.protocol.paths
from kazoo.client import KazooClient
from openeo.util import TimingLogger
from openeo... | Open-EO/openeo-aggregator | src/openeo_aggregator/caching.py | .py | 156e54782b6e8708 | 7.15 | 1 |
import logging
import os
import re
from typing import Dict, List, Optional, Protocol, Union
import attrs
from openeo_driver.config import OpenEoBackendConfig, openeo_backend_config_class
from openeo_driver.config.load import ConfigGetter
from openeo_driver.server import build_backend_deploy_metadata
from openeo_driver... | Open-EO/openeo-aggregator | src/openeo_aggregator/config/config.py | .py | 33febba00501ed0c | 7.15 | 1 |
import concurrent.futures
import contextlib
import dataclasses
import logging
import re
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
Optional,
Set,
Tuple,
Union,
)
import flask
import requests
from openeo import Connection
from openeo.rest.auth.auth import... | Open-EO/openeo-aggregator | src/openeo_aggregator/connection.py | .py | ccc61ad9df90efd3 | 7.15 | 1 |
"""
Functionality and definitions related to
openEO Platform and its EGI Virtual Organisation
"""
import functools
import re
from collections import namedtuple
from typing import List, Union
BillingPlan = namedtuple("BillingPlan", ["name", "description", "url", "paid"])
# Regex to parse eduperson_entitlement string... | Open-EO/openeo-aggregator | src/openeo_aggregator/egi.py | .py | 5954c25b70fefaee | 7.15 | 1 |
from typing import Any, Dict, List, Type, TypeVar
import attr
from openeo_aggregator.metadata.models.cube_dimension import CubeDimension
T = TypeVar("T", bound="CubeDimensions")
@attr.s(auto_attribs=True)
class CubeDimensions:
"""Uniquely named dimensions of the data cube.
The keys of the object are the d... | Open-EO/openeo-aggregator | src/openeo_aggregator/metadata/models/cube_dimensions.py | .py | 5a5316c55e7f17e4 | 7.15 | 1 |
import functools
from typing import Any, Dict, List, Set, Type, TypeVar, Union, cast
import attr
from openeo_aggregator.metadata.models.stac_eo import EoBand
from openeo_aggregator.metadata.models.statistics import Statistics
from openeo_aggregator.metadata.utils import merge_lists_skip_duplicates
from openeo_aggrega... | Open-EO/openeo-aggregator | src/openeo_aggregator/metadata/models/stac_summaries.py | .py | d4cb69e5fed20ed0 | 7.15 | 1 |
import inspect
import logging
import textwrap
from pathlib import Path
from typing import List, Tuple
def _extract_entity_id(**kwargs) -> Tuple[List[str], dict]:
"""
Extract entity (collection/process) identifier (list of strings, like a path in a tree) from given kwargs.
"""
entity_id = []
for k ... | Open-EO/openeo-aggregator | src/openeo_aggregator/metadata/reporter.py | .py | f951a1c56b30fd51 | 7.15 | 1 |
import argparse
import logging
from typing import Dict
import requests
from openeo_aggregator.config import get_backend_config
from openeo_aggregator.metadata.merging import (
ProcessMetadataMerger,
merge_collection_metadata,
)
from openeo_aggregator.metadata.reporter import MarkDownReporter
from openeo_aggre... | Open-EO/openeo-aggregator | src/openeo_aggregator/metadata/validator.py | .py | 0d5a8b2d21bdb435 | 7.15 | 1 |
from typing import Any, Dict, NamedTuple, Optional, Sequence, Union
from openeo_driver.errors import OpenEOApiException
from openeo_aggregator.utils import FlatPG, PGWithMetadata
class PartitionedJobFailure(OpenEOApiException):
code = "PartitionedJobFailure"
class SubJob(NamedTuple):
"""A part of a partit... | Open-EO/openeo-aggregator | src/openeo_aggregator/partitionedjobs/__init__.py | .py | 6a7aa36975153e8b | 7.15 | 1 |
import abc
import copy
import math
import re
import typing
from typing import List
import pyproj
import shapely.geometry
import shapely.ops
from openeo.internal.process_graph_visitor import ProcessGraphVisitor
from openeo_driver.backend import OpenEoBackendImplementation
from openeo_driver.dry_run import DryRunDataTra... | Open-EO/openeo-aggregator | src/openeo_aggregator/partitionedjobs/splitting.py | .py | 74f9b0e52de6d51d | 7.15 | 1 |
import contextlib
import json
import logging
from typing import Dict, List, Optional
from kazoo.client import KazooClient
from kazoo.exceptions import NodeExistsError, NoNodeError
from openeo_driver.errors import JobNotFoundException
from openeo_aggregator.config import ConfigException, get_backend_config
from openeo... | Open-EO/openeo-aggregator | src/openeo_aggregator/partitionedjobs/zookeeper.py | .py | 0bb27a791acf6b33 | 7.15 | 1 |
import dataclasses
import datetime
import itertools
import json
import pathlib
from typing import Any, Dict, List, Optional, Tuple, Union
from unittest import mock
import kazoo
import kazoo.exceptions
import openeo_driver.testing
import pytest
from openeo.util import rfc3339
import openeo_aggregator.about
import open... | Open-EO/openeo-aggregator | src/openeo_aggregator/testing.py | .py | 5ce951b6a4f2396f | 7.65 | 1 |
import datetime
import functools
import itertools
import logging
import re
import time
from typing import (
Any,
Callable,
Iterable,
Iterator,
List,
NamedTuple,
Optional,
Sequence,
Set,
Union,
)
import shapely.geometry
from openeo.util import rfc3339
# Generic "sentinel object"... | Open-EO/openeo-aggregator | src/openeo_aggregator/utils.py | .py | 0c362688337b1602 | 7.15 | 1 |
import os
from pathlib import Path
from typing import Callable
import flask
import pytest
from openeo_driver.testing import ApiTester
from openeo_driver.views import OPENEO_API_VERSION_DEFAULT
from openeo_aggregator.app import create_app
from openeo_aggregator.backend import (
AggregatorBackendImplementation,
... | Open-EO/openeo-aggregator | tests/conftest.py | .py | 86845255c4663633 | 7.65 | 1 |
#!/usr/bin/env python3
"""
Base hook class for all Python hooks.
Provides common functionality: JSON parsing, error handling, logging.
"""
import json
import sys
import os
from abc import ABC, abstractmethod
from pathlib import Path
from datetime import datetime
from typing import Optional, Dict, Any
class BaseHook(A... | nicholasgriffintn/machine-setup | ai-tooling/hooks/lib/base_hook.py | .py | 54c1ded7da9f5575 | 7.24 | 2 |
#!/usr/bin/env python3
"""Configuration loader for hooks (no external dependencies)."""
import os
from typing import Dict, Any, List, Tuple
def get_allowed_git_owners() -> List[str]:
"""GitHub owners/orgs that AI-driven git access is scoped to.
Override with a comma-separated AI_GIT_ALLOWED_OWNERS env var.
... | nicholasgriffintn/machine-setup | ai-tooling/hooks/lib/config.py | .py | 6cdaa77daaa751be | 7.24 | 2 |
#!/usr/bin/env python3
"""Pattern matching utilities for hooks."""
import os
import fnmatch
from typing import List, Optional
def normalize_file_path(file_path: str) -> str:
"""Normalize file path to prevent traversal attacks."""
file_path = os.path.normpath(file_path)
# Remove leading './' but preserve l... | nicholasgriffintn/machine-setup | ai-tooling/hooks/lib/pattern_matcher.py | .py | 2da0f699caf4a71b | 7.24 | 2 |
#!/usr/bin/env python3
"""
Auto-format files after Claude edits them.
Detects file type and runs appropriate formatter.
Original Source: https://github.com/CloudAI-X/claude-workflow
"""
import sys
import os
import subprocess
import shutil
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent / ... | nicholasgriffintn/machine-setup | ai-tooling/hooks/scripts/format-on-edit.py | .py | 7e3de4579079c0b1 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Protect sensitive files from modification.
Blocks edits to production configs, lock files, and sensitive directories.
Original Source: https://github.com/CloudAI-X/claude-workflow
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent / 'lib'))
from bas... | nicholasgriffintn/machine-setup | ai-tooling/hooks/scripts/protect-files.py | .py | 764ab24c8bfe34dd | 7.24 | 2 |
#!/usr/bin/env python3
"""
PreToolUse hook (Bash matcher) that scopes both the `git` and `gh` CLIs to
an allow-list of GitHub owners/orgs (see lib/config.py: get_allowed_git_owners).
This is a defense-in-depth layer, not the only one: claude-settings.json also
sets `url.https://github.com/.insteadOf git@github.com:` (... | nicholasgriffintn/machine-setup | ai-tooling/hooks/scripts/repo-scope-guard.py | .py | b649cbc4aba73624 | 7.24 | 2 |
#!/usr/bin/env python3
"""
Pre-commit security check hook.
Blocks commits that might contain secrets or security issues.
Original Source: https://github.com/CloudAI-X/claude-workflow
"""
import sys
import re
import os
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent / 'lib'))
from base_ho... | nicholasgriffintn/machine-setup | ai-tooling/hooks/scripts/security-check.py | .py | 090fa760fb34c192 | 7.24 | 2 |
#!/usr/bin/env python3
"""
SessionStart hook - Validates environment on session startup.
Checks for required tools, configuration, and potential issues.
Source: https://github.com/CloudAI-X/claude-workflow
"""
import sys
import os
import shutil
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.par... | nicholasgriffintn/machine-setup | ai-tooling/hooks/scripts/validate-environment.py | .py | d627f939508f29d0 | 7.24 | 2 |
#!/usr/bin/env python3
"""
UserPromptSubmit hook - Validates user prompts before processing.
Can provide warnings or context to Claude based on the prompt content.
Source: https://github.com/CloudAI-X/claude-workflow
"""
import sys
import re
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent... | nicholasgriffintn/machine-setup | ai-tooling/hooks/scripts/validate-prompt.py | .py | b4a643d47687e307 | 7.24 | 2 |
#!/usr/bin/env python3
"""Ensure existing zsh installations resolve machine-setup shims first."""
import stat
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from lib.secure_io import write_text_atomic # noqa: E402
START_MARKER = '# >>> machine-setup local bin >>>'
PATH... | nicholasgriffintn/machine-setup | ai-tooling/scripts/ensure-local-bin-path.py | .py | ac155190eb39e896 | 7.24 | 2 |
#!/usr/bin/env python3
"""Run GitHub CLI with the current short-lived GitHub App token.
AI harness processes can live longer than a GitHub App installation token.
Reading GH_TOKEN only when the harness starts therefore leaves long-running
Claude and Codex sessions with an expired credential. This wrapper reloads
the t... | nicholasgriffintn/machine-setup | ai-tooling/scripts/gh_wrapper.py | .py | ba26874d8810df9b | 7.24 | 2 |
#!/usr/bin/env python3
"""
Shared write helpers for the files that carry the bot identity's live
credentials (claude-settings.local.json, ~/.claude/settings.json,
~/.codex/config.toml): write-then-rename so a reader never sees a
half-written file, and lock permissions to the owner so a live GH_TOKEN
isn't left world-re... | nicholasgriffintn/machine-setup | ai-tooling/scripts/lib/secure_io.py | .py | 8c8d1f465d4ebcca | 7.24 | 2 |
#!/usr/bin/env python3
"""
Mints a fresh GitHub App installation token and writes it into
claude-settings.json's "env" block as GH_TOKEN, syncing to Codex too.
The ~/.local/bin/gh wrapper reads the refreshed GH_TOKEN from the local
overlay for every invocation, bypassing its own stored auth entirely. This
keeps long-r... | nicholasgriffintn/machine-setup | ai-tooling/scripts/refresh-gh-token.py | .py | 58672f5c81b41b4e | 7.24 | 2 |
#!/usr/bin/env python3
"""
~/.codex/config.toml is Codex's own live app-state file (project trust
list, per-hook consent tracking) as well as user config, so it can't be
symlinked from this repo like the rest of ai-tooling -- that would mean
every project Codex trusts gets written straight into this git repo.
Instead ... | nicholasgriffintn/machine-setup | ai-tooling/scripts/sync-codex-env.py | .py | ee6223d027d69359 | 7.24 | 2 |
#!/usr/bin/env python
# helpers.py
import os
import socket
import subprocess
from pathlib import Path
from datetime import date, datetime
from typing import Optional
from PIL import Image
from rich.console import Console
from rich.panel import Panel
from rich.traceback import install
install()
console = Console()
... | nisidabay/pynuggets | helpers.py | .py | 748905d83e15b723 | 7 | 0 |
"""
CLI entry point for watching a trained SpaceInvaderAgent play, saving each episode as a gif.
Usage:
uv run python scripts/evaluate.py
uv run python scripts/evaluate.py --checkpoint scripts/output-rmsprop --episodes 3
"""
import argparse
import os
import sys
# Make the repo root (the parent of this script'... | colichar/deep-q-learning | scripts/evaluate.py | .py | 53e86dc4b002fc36 | 7 | 0 |
from torch.nn import Module, Conv2d, Linear
from torch.nn.functional import relu, huber_loss
from torch import max, argmax, save, load, device as torch_device
from torch.cuda import is_available
from torch.optim import Adam, RMSprop
import os
class CNNModelPY(Module):
"""
Implementation of a CNN model to be ... | colichar/deep-q-learning | src/models/cnn.py | .py | 43899eb83c89c417 | 7 | 0 |
from torchvision.transforms.functional import rgb_to_grayscale
from torchvision.transforms.v2 import Resize
from torch import cat, tensor, stack
from numpy import maximum, zeros
class FrameSkipStepper:
"""Advance one existing action-repeat group a raw ALE frame at a time.
This is the step-wise counterpart to... | colichar/deep-q-learning | src/utils/preprocessor.py | .py | f78c72a2b8b22394 | 7 | 0 |
import os
import numpy as np
from numpy import zeros, uint8, int64, float32, bool_, stack
from numpy.random import randint
from torch import cat, from_numpy
class ReplayMemory:
"""
Stores the experience (frames) of the agent so they can be replayed for training.
Frames are stored once each in a circular... | colichar/deep-q-learning | src/utils/replay_memory.py | .py | 1293bb30b153e430 | 7 | 0 |
from torch.utils.data import Dataset
from typing import Union
from random import sample
from numpy.random import choice as random_choice
from numpy import array as np_array
from torch import tensor, stack
import pickle
import os
class ReplayMemoryFromDisk(Dataset):
"""Stores the experience (frames) of the agent t... | colichar/deep-q-learning | src/utils/replay_memory_from_disk.py | .py | 3aa9da70872ea9c5 | 7 | 0 |
"""Shared ALE Space Invaders environment setup.
Keeping this in one place makes training, evaluation, and the playable demo use
the same Atari settings.
"""
import ale_py
import gymnasium as gym
from numpy import random
gym.register_envs(ale_py)
class NoopResetEnv(gym.Wrapper):
"""Randomize the opening with t... | colichar/deep-q-learning | src/utils/space_invaders.py | .py | 677dd02ac645cd4f | 7 | 0 |
"""
Integration tests for SpaceInvaderAgent: real gym/ALE env, real model, real filesystem.
Slower than the ReplayMemory unit tests - run with `uv run pytest -m integration`
or skip with `uv run pytest -m "not integration"`.
"""
import numpy as np
import pytest
from src.agent.agent import SpaceInvaderAgent
pytestmark... | colichar/deep-q-learning | tests/integration/test_agent.py | .py | 81864f0065ba0176 | 7.5 | 0 |
"""
Unit test for SpaceInvaderAgent.close() (issue #29 review follow-up): must close both
the vectorized training env and the standalone eval env, so AsyncVectorEnv's subprocess
workers (num_envs > 1) don't leak.
"""
from src.agent.agent import SpaceInvaderAgent
class FakeEnv:
def __init__(self):
self.clo... | colichar/deep-q-learning | tests/unit/test_agent_close.py | .py | 35a48f1efeb96a29 | 7.5 | 0 |
"""
Unit tests for SpaceInvaderAgent.train()'s end-of-run episode bookkeeping (issue #29).
The pre-vectorization single-env loop always recorded the current episode_reward once the
frame budget ran out, even mid-episode (an inner `while alive:` loop broken by the frame
budget, not by the episode actually ending, still... | colichar/deep-q-learning | tests/unit/test_agent_episode_flush.py | .py | 62123e27a6fe316f | 7.5 | 0 |
"""
Unit tests for SpaceInvaderAgent.train()'s `just_reset` handling (issue #29 review
follow-up, Part B): once a sub-env's episode ends, the *next* tick's acting state for
that sub-env must be seeded from scratch (4 copies of the new frame) instead of
shift-appending onto the state stack of the episode that just ended... | colichar/deep-q-learning | tests/unit/test_agent_just_reset.py | .py | f20a223c3f0c0ddd | 7.5 | 0 |
"""
Unit tests for SpaceInvaderAgent.update_step (see GitHub issue #1: the loss must
compare against Q(s, a_taken), not max_a Q(s, a)).
"""
import types
import torch
from src.agent.agent import SpaceInvaderAgent
class FakeReplayMemory:
def __init__(self, batch):
self._batch = batch
def get_batch(se... | colichar/deep-q-learning | tests/unit/test_agent_update_step.py | .py | 5b28697e1d02e310 | 7.5 | 0 |
"""
Unit tests for CNNModelPY's optimizer selection (adam vs rmsprop).
"""
import pytest
import torch
from torch.optim import Adam, RMSprop
from src.models.cnn import CNNModelPY
def test_default_optimizer_is_adam():
model = CNNModelPY(n_actions=6, device=torch.device("cpu"))
assert isinstance(model.optimizer... | colichar/deep-q-learning | tests/unit/test_cnn_model_optimizer.py | .py | f74929440ee04c08 | 7.5 | 0 |
"""
Unit tests for ExplorationVsExploitation's epsilon schedule (see GitHub issue
discussion: the Nature paper anneals epsilon from environment frame 0, independently
of when gradient updates/memory_warmup kick in).
"""
from src.agent.agent import ExplorationVsExploitation
def _make_schedule(**overrides):
return ... | colichar/deep-q-learning | tests/unit/test_epsilon_schedule.py | .py | 6b46caed4785e692 | 7.5 | 0 |
"""
Unit tests for SpaceInvaderAgent._freq_due (issue #29), which replaces exact-modulo
frequency gating (`frame_num % freq == 0`) now that frame_num advances by num_envs per
tick instead of 1.
"""
from src.agent.agent import SpaceInvaderAgent
def test_matches_original_modulo_check_at_num_envs_one():
freq = 10
... | colichar/deep-q-learning | tests/unit/test_freq_due.py | .py | 54e267f6f5e9d351 | 7.5 | 0 |
"""
Unit tests for agent.NoopResetEnv (issue #29 review follow-up), the OpenAI-Baselines-style
wrapper that performs a randomized no-op warmup inside reset() itself, so gymnasium's
NEXT_STEP auto-reset re-randomizes every episode's start during training, not just the
first.
"""
import gymnasium as gym
from src.agent.a... | colichar/deep-q-learning | tests/unit/test_noop_reset_env.py | .py | faf787452942b677 | 7.5 | 0 |
"""
Unit tests for Preprocessor.step_with_skip_vec (GitHub issue #27).
These run against a real gymnasium SyncVectorEnv wrapping scripted sub-envs, so the
auto-reset behaviour under test is gymnasium's actual NEXT_STEP semantics rather than
a hand-rolled imitation of them: after a sub-env reports done, its next step()... | colichar/deep-q-learning | tests/unit/test_preprocessor_vector_skip.py | .py | b79f61862b8d820b | 7.5 | 0 |
"""
Unit tests for the single-frame ring-buffer replay memory
(see plans/replay-memory-single-frame-buffer.md, plans/replay-memory-save-load.md).
"""
import numpy as np
import pytest
from src.utils.replay_memory import ReplayMemory
def _fill_with_episodes(mem, capacity, num_writes, seed=0):
"""Writes num_writes ... | colichar/deep-q-learning | tests/unit/test_replay_memory.py | .py | 4af7a412ff75cb76 | 7.5 | 0 |
"""
Unit tests for the vectorized replay memory wrapper (N independent ReplayMemory
sub-buffers, one per parallel env - see issue #26 / epic #25).
"""
import numpy as np
import pytest
from src.utils.replay_memory import VectorizedReplayMemory
def _fill_with_episodes(vmem, capacity_per_env, num_writes, seed=0):
"... | colichar/deep-q-learning | tests/unit/test_vectorized_replay_memory.py | .py | 8d456e8ddaf1e985 | 7.5 | 0 |
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../scripts')))
"""
Pytest configuration for private network tests.
Network tests (marked with @pytest.mark.network) are skipped by default.
Use --test-api to enable them.
"""
import pytest
def pytest_configure(config):
... | patello/avanza-investment-tracker | test/conftest.py | .py | 31a4c07a4b6b0c22 | 7.5 | 0 |
import pytest
import sqlite3
import csv
from database_handler import DatabaseHandler
from data_parser import DataParser, SpecialCases
@pytest.fixture
def asset_deposit_db(tmp_path):
db_base = str(tmp_path / "test_asset_deposit")
db_file = db_base + ".db"
# Create DB schema
db = DatabaseHandler(db_... | patello/avanza-investment-tracker | test/test_asset_deposit_issue.py | .py | ebbcaf65779bb1e1 | 7.5 | 0 |
"""Tests for asset-name normalization at import (issue #79)."""
import sqlite3
from database_handler import DatabaseHandler
from data_parser import DataParser
NEW_FORMAT_HEADER = (
"Datum;Konto;Typ av transaktion;Värdepapper/beskrivning;Antal;Kurs;"
"Belopp;Transaktionsvaluta;Courtage;Valutakurs;Instrumentval... | patello/avanza-investment-tracker | test/test_import_normalization.py | .py | a7cf80da4eb42adb | 7.5 | 0 |
"""Tests for deferral of unsettled (pending nota) trades at import (issue #78)."""
import logging
from database_handler import DatabaseHandler
from data_parser import DataParser
HEADER = (
"Datum;Konto;Typ av transaktion;Värdepapper/beskrivning;Antal;Kurs;"
"Belopp;Transaktionsvaluta;Courtage;Valutakurs;Instr... | patello/avanza-investment-tracker | test/test_import_unsettled.py | .py | 847a65bfaef235bc | 7.5 | 0 |
import sys
sys.path.insert(0, "..")
import pytest
from datetime import date
from database_handler import DatabaseHandler
from data_parser import DataParser
from calculate_stats import StatCalculator
@pytest.fixture
def dietz_scenario_db(tmp_path):
"""
Creates a database with a specific scenario for testing the... | patello/avanza-investment-tracker | test/test_modified_dietz.py | .py | 1adc24f4889eafe5 | 7.5 | 0 |
import pytest
from database_handler import DatabaseHandler
from data_parser import DataParser
@pytest.fixture
def database_price_updates(tmp_path):
"""
Creates a custom dataset to specifically test price updates for
Köp, Sälj, and Tillgångsinsättning transactions.
"""
db_file = tmp_path / "test_a... | patello/avanza-investment-tracker | test/test_price_updates.py | .py | 438752ac102c16ec | 7.5 | 0 |
import pytest
import math
from datetime import date
from unittest.mock import patch, MagicMock
from database_handler import DatabaseHandler
from data_parser import DataParser
from scripts.risk_calculator import RiskCalculator, generate_monthly_dates, clear_riksbanken_cache
@pytest.fixture(autouse=True)
def _clear_rat... | patello/avanza-investment-tracker | test/test_risk_metrics.py | .py | 85dba03b2b16bca2 | 7.5 | 0 |
import pytest
from database_handler import DatabaseHandler
from data_parser import DataParser
from calculate_stats import StatCalculator
@pytest.fixture
def twrr_scenario_db(tmp_path):
"""
Scenario for testing TWRR active_base reduction:
- Deposit 10000, buy asset at 100
- Asset doubles to 200
- S... | patello/avanza-investment-tracker | test/test_twrr.py | .py | 8a64dae0947d8fe3 | 7.5 | 0 |
#!/usr/bin/env python3
"""
LFS Shimmy
This is a simple API that creates pre-signed S3 URLs based on Git LFS requests,
it implements the Git LFS Batch API with the Basic transfer adapter.
MIT License
Copyright (c) 2026 Infra Bits
Permission is hereby granted, free of charge, to any person obtaining a copy
of this so... | InfraBits/lfs-shimmy | lfs_shimmy/server.py | .py | 6d7d5c98cdba25c9 | 7.24 | 2 |
"""
LFS Shimmy
This is a simple API that creates pre-signed S3 URLs based on Git LFS requests,
it implements the Git LFS Batch API with the Basic transfer adapter.
MIT License
Copyright (c) 2026 Infra Bits
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated d... | InfraBits/lfs-shimmy | lfs_shimmy/storage.py | .py | 1309f75d42e620cd | 7.24 | 2 |
"""
The fundamental unit of a linked list is a node, which is a data entity with
at least one pointer reference. The pointer reference is directed towards the
next destination one is able to move.
"""
from typing import Any
class Node:
def __init__(self, val):
self.data = val
self.next = None
c... | architgupta13/python-learning | archived/data_structures/linked_lists.py | .py | 8e3599058ca1716b | 7.15 | 1 |
from collections.abc import Callable, Iterable
from typing import TYPE_CHECKING
from ceres.__internal__.app.shared import (
Actor,
assert_found,
build_address_chain,
get_component_access,
get_components_access,
get_engine_access,
)
from ceres.__internal__.workspace_redaction import merge_redact... | OOI-RCA-APL/ceres | ceres/__internal__/app/handlers/workspaces.py | .py | f6dac73fbb5fd2a8 | 7 | 0 |
"""The engine as the native server's host.
The native server owns HTTP and answers most requests by calling one named operation
here. Each operation validates its own arguments through Pydantic and runs the engine
and query-layer code itself so filters, permissions, and wire shapes keep their exact
behavior whatever t... | OOI-RCA-APL/ceres | ceres/__internal__/app/host.py | .py | 8969346d7d421986 | 7 | 0 |
"""Password hashing and verification.
Argon2 is the native implementation's, called through `ceres.__internal__.core` rather than
reimplemented here, so a password hashed by a native command and one hashed through the
entity manager cannot drift apart. bcrypt stays on its Python library, being the
configurable alterna... | OOI-RCA-APL/ceres | ceres/__internal__/auth.py | .py | 77525976d5c60193 | 7 | 0 |
import re
from collections.abc import Iterator
from contextlib import contextmanager
# SQLite and Turso both name the constraint's columns as "table.column", listing them comma
# separated when more than one column makes up the constraint, and Turso appends its result code
# in parentheses. The first column is the one... | OOI-RCA-APL/ceres | ceres/__internal__/database/errors.py | .py | 73d95ebba28b3dfb | 7 | 0 |
from asyncio import Event as AsyncEvent
from collections import defaultdict, deque
from collections.abc import Callable, Iterable
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
from ceres.__internal__.utilities.collections import group_by
if TYPE_CHECKING:
from ceres.database import Dat... | OOI-RCA-APL/ceres | ceres/__internal__/database/writer.py | .py | 576e28d2fb692eb9 | 7 | 0 |
"""The engine host process.
The `ceres` binary owns the command line. It spawns this module to load the engine or
validate the configuration, passing one JSON payload argument in place of arguments to
parse:
- `config`: absolute path of the project configuration file.
- `addresses`: component address selector strings... | OOI-RCA-APL/ceres | ceres/__internal__/host.py | .py | 70cd3f5a551884fa | 7 | 0 |
from collections.abc import Callable, Mapping
from typing import TYPE_CHECKING, Any, ClassVar, Self
from pydantic_core.core_schema import (
no_info_plain_validator_function,
plain_serializer_function_ser_schema,
)
if TYPE_CHECKING:
from pydantic import GetCoreSchemaHandler, GetJsonSchemaHandler
from p... | OOI-RCA-APL/ceres | ceres/__internal__/interop.py | .py | 1ef45e8aec4f566f | 7 | 0 |
import importlib
import sys
from collections.abc import Callable, Iterable, Mapping, Sequence
from contextlib import contextmanager
from threading import Lock
from typing import TYPE_CHECKING, Any, Final, overload, override
if TYPE_CHECKING:
from types import ModuleType, UnionType
_UNDEFINED = object()
class La... | OOI-RCA-APL/ceres | ceres/__internal__/lazy.py | .py | d3c56ce756e570b1 | 7 | 0 |
import asyncio
from abc import abstractmethod
from asyncio import Task
from typing import TYPE_CHECKING, Any, Protocol, override
from ceres.__internal__.protocols import ComponentSource, DatabaseSource, NodeSource
from ceres.concurrency import cancel, sleep
if TYPE_CHECKING:
from ceres.component import Component,... | OOI-RCA-APL/ceres | ceres/__internal__/manager.py | .py | 418f1e0647be2e38 | 7 | 0 |
# @generated by ceres-models. Run 'make models' to update.
"""Generated models for the `alerts` table."""
from typing import TYPE_CHECKING, ClassVar, Literal
from pydantic import Field
from ceres.__internal__.record import (
BaseRecordCreate,
BaseRecordField,
BaseRecordFilter,
BaseRecordFilterArgs,
... | OOI-RCA-APL/ceres | ceres/__internal__/models/alerts.py | .py | ed9801a14f327570 | 7 | 0 |
# @generated by ceres-models. Run 'make models' to update.
"""Generated models for the `groups`, `group_memberships` tables."""
from typing import TYPE_CHECKING, ClassVar, Literal, TypedDict
from uuid import UUID
from ceres.__internal__.entity import (
BaseEntityCreate,
BaseEntityFilter,
BaseEntityFilter... | OOI-RCA-APL/ceres | ceres/__internal__/models/groups.py | .py | 1464cb8290e48358 | 7 | 0 |
# @generated by ceres-models. Run 'make models' to update.
"""Generated models for the `logs` table."""
from typing import TYPE_CHECKING, ClassVar, Literal
from ceres.__internal__.record import (
BaseRecordCreate,
BaseRecordField,
BaseRecordFilter,
BaseRecordFilterArgs,
BaseRecordOrder,
BaseR... | OOI-RCA-APL/ceres | ceres/__internal__/models/logs.py | .py | 8c3016a0fef0d886 | 7 | 0 |
# @generated by ceres-models. Run 'make models' to update.
"""Generated models for the `messages` table."""
from typing import TYPE_CHECKING, Annotated, ClassVar, Literal
from ceres.__internal__.record import (
BaseRecordCreate,
BaseRecordField,
BaseRecordFilter,
BaseRecordFilterArgs,
BaseRecordO... | OOI-RCA-APL/ceres | ceres/__internal__/models/messages.py | .py | 02306c8b50422720 | 7 | 0 |
# @generated by ceres-models. Run 'make models' to update.
"""Generated models for the `settings` table."""
from typing import TYPE_CHECKING, ClassVar, Literal, TypedDict
from uuid import UUID
from ceres.__internal__.entity import (
BaseEntityCreate,
BaseEntityFilter,
BaseEntityFilterArgs,
)
from ceres.d... | OOI-RCA-APL/ceres | ceres/__internal__/models/settings.py | .py | 39f6fe75ecff2750 | 7 | 0 |
# @generated by ceres-models. Run 'make models' to update.
"""Generated models for the `users` table."""
from typing import TYPE_CHECKING, ClassVar, Literal, TypedDict
from ceres.__internal__.entity import (
BaseUUIDEntityCreate,
BaseUUIDEntityField,
BaseUUIDEntityFilter,
BaseUUIDEntityFilterArgs,
... | OOI-RCA-APL/ceres | ceres/__internal__/models/users.py | .py | cff77d847edfb7bd | 7 | 0 |
# @generated by ceres-models. Run 'make models' to update.
"""Generated models for the `variables` table."""
from typing import TYPE_CHECKING, ClassVar, Literal, TypedDict
from ceres.__internal__.entity import (
BaseAddressEntityCreate,
BaseAddressEntityField,
BaseAddressEntityFilter,
BaseAddressEnti... | OOI-RCA-APL/ceres | ceres/__internal__/models/variables.py | .py | 5fec8d499655de80 | 7 | 0 |
# @generated by ceres-models. Run 'make models' to update.
"""Generated models for the `workspace_edits`, `workspaces` tables."""
from typing import TYPE_CHECKING, ClassVar, Literal, TypedDict
from uuid import UUID
from pydantic import Field
from ceres.__internal__.entity import (
BaseEntityCreate,
BaseEnti... | OOI-RCA-APL/ceres | ceres/__internal__/models/workspaces.py | .py | f4f59a61c75462db | 7 | 0 |
"""Derive the particle classes a component declares, for the metadata route."""
import inspect
from collections.abc import Callable
from functools import cache
from types import UnionType
from typing import TYPE_CHECKING, Union, get_args, get_origin
from ceres.config import ClassSieveConfig, MethodSieveConfig, SieveC... | OOI-RCA-APL/ceres | ceres/__internal__/particles.py | .py | 45196dbedf4faedc | 7 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.