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
"""Numerical helpers shared across the package. Two concerns live here, both cross-cutting enough that duplicating them was the direct cause of shipped bugs: * **Coercion.** :func:`as_float` and :func:`as_point` are the single place where a value coming from — or going to — a user callable is normalised. Ad-hoc `...
jeMATHfischer/TheHawkesPackage
src/hawkes_package/_numerics.py
.py
f6325c95336e929c
7.15
1
"""Hawkes process for kernels with a single interior maximum.""" from __future__ import annotations from collections.abc import Callable from typing import Any import numpy as np from ._numerics import as_float, locate_peak from .base import SeedLike, TemporalHawkesProcess __all__ = ["BellShapeHawkes"] class Bel...
jeMATHfischer/TheHawkesPackage
src/hawkes_package/bell_shape.py
.py
a3388ba7a7d0f338
7.15
1
"""Linear Hawkes process with an exponential excitation kernel.""" from __future__ import annotations from typing import Any import numpy as np from .base import SeedLike, TemporalHawkesProcess __all__ = ["ExponentialHawkes"] class ExponentialHawkes(TemporalHawkesProcess): r"""Linear Hawkes process with kern...
jeMATHfischer/TheHawkesPackage
src/hawkes_package/exponential.py
.py
cc281c43887848c0
7.15
1
"""Hawkes process with a monotone-decreasing kernel and a nonlinear intensity.""" from __future__ import annotations from collections.abc import Callable from typing import Any import numpy as np from .base import SeedLike, TemporalHawkesProcess __all__ = ["MonotoneKernelHawkes"] class MonotoneKernelHawkes(Tempo...
jeMATHfischer/TheHawkesPackage
src/hawkes_package/monotone.py
.py
eac894bf1d7e9f01
7.15
1
"""Deterministic quadrature over a rectangular spatial domain. Ogata's algorithm requires ``M >= lambda`` *pathwise*. Estimating the spatial integral by Monte Carlo breaks that in two ways at once: the bound becomes an unbiased estimate rather than an upper bound, so it sits below the truth about half the time; and th...
jeMATHfischer/TheHawkesPackage
src/hawkes_package/spatio_temporal/_integration.py
.py
5169d0ad2b6c0e50
7.15
1
"""Spatial kernel utilities for spatio-temporal Hawkes processes. Provides :func:`make_periodic`, which wraps an isotropic spatial kernel so it respects the periodic structure of a :class:`SpatialDomain` by summing the contributions of image points. """ from __future__ import annotations from collections.abc import ...
jeMATHfischer/TheHawkesPackage
src/hawkes_package/spatio_temporal/kernels.py
.py
d1bdd01f6592e7f8
7.15
1
"""Shared fixtures. All randomness flows through explicit, seeded generators passed as ``rng=``. Nothing here touches :func:`numpy.random.seed`, so ``pytest-randomly`` shuffling test order and reseeding the globals between tests actively proves that no hidden dependency on the global stream survives. """ import numpy...
jeMATHfischer/TheHawkesPackage
tests/conftest.py
.py
1418abe678db830e
7.65
1
"""The Ogata thinning invariant, checked on every process class at once. Ogata's algorithm is only correct while ``M >= lambda`` holds at every acceptance test. Two ways to get this wrong, and the assertions below catch both: * **M too tight** — the historical ``MonotoneKernelHawkes`` bug, where the bound excluded ...
jeMATHfischer/TheHawkesPackage
tests/statistical/test_thinning_invariant.py
.py
3d413992c7e301a1
7.65
1
"""Contract of the shared HawkesProcess / TemporalHawkesProcess machinery.""" import numpy as np import pytest from hawkes_package import ( BellShapeHawkes, ExponentialHawkes, HawkesProcess, MonotoneKernelHawkes, ) PARAM = np.array([1.0, 0.4, 2.0]) def _make(cls, exp_kernel, triangular_kernel, **kw...
jeMATHfischer/TheHawkesPackage
tests/test_base.py
.py
3b7cf1a9c1eb8889
7.65
1
"""Tests for BellShapeHawkes, whose kernel rises before it decays.""" import numpy as np import pytest from hawkes_package import BellShapeHawkes def test_extremum_is_a_finite_float(triangular_kernel): """`ext` must be a plain float: under NumPy 2 a shape-(1,) array here made every comparison against it ret...
jeMATHfischer/TheHawkesPackage
tests/test_bell_shape.py
.py
5644d946b8b304d7
7.65
1
"""Tests for the linear exponential-kernel Hawkes process.""" import numpy as np import pytest from hawkes_package import ExponentialHawkes def test_stability_guard_raises(): with pytest.raises(ValueError, match="alpha/beta"): ExponentialHawkes(np.array([1.0, 5.0, 1.0])) def test_stability_guard_bound...
jeMATHfischer/TheHawkesPackage
tests/test_exponential.py
.py
03523bc377aaf1f7
7.65
1
"""Tests for the frozen LegacySpatioTemporalHawkesProcess. This class is kept only so results published with it stay reproducible; it is removed in 0.4.0. These tests pin the behaviour that must not drift until then, plus the three bugs fixed in 0.2.0. """ import subprocess import sys import numpy as np import pytes...
jeMATHfischer/TheHawkesPackage
tests/test_legacy_spatio_temporal.py
.py
ede403e6a9252fba
7.65
1
"""Tests for MonotoneKernelHawkes. The historical bug this class carries scars from: the Ogata upper bound M(t) excluded the contribution of the event at ``t = Events[-1]``, making ``M(t) < lambda(t + eps)``. Every candidate was then accepted unconditionally and the output was a Poisson process, not a Hawkes one. The ...
jeMATHfischer/TheHawkesPackage
tests/test_monotone.py
.py
d02b57923eb520ef
7.65
1
from __future__ import annotations import contextlib import pathlib import re # noqa: TC003 import pydantic from pydantic_settings import BaseSettings, SettingsConfigDict class SiteGeneratorConfig(BaseSettings): """General configuration values for `weaving`, populated from CLI args.""" model_config = Sett...
Nadock/rileychase.net
weaving/config.py
.py
d89141bd1b120052
7.15
1
import contextlib from typing import Any from .db import EMOJI def to_unicode_emoji( index: str = "", shortname: str = "", alias: str = "", uc: str = "", alt: str = "", title: str = "", category: str = "", options: dict[Any, Any] | None = None, md: Any = None, ) -> str: """ ...
Nadock/rileychase.net
weaving/emoji/emoji.py
.py
31a5677178d4d293
7.15
1
import pathlib import pydantic from weaving import logging LOGGER = logging.getLogger() class WeavingError(Exception): """Base exception class for any `weaving` errors.""" class PipelineError(WeavingError): """Pipeline failure for a specific source file.""" class ValidationError(pydantic.BaseModel): ...
Nadock/rileychase.net
weaving/errors.py
.py
78ca5575c50cc211
7.15
1
import datetime import logging import pathlib import re from typing import Any, Literal from urllib import parse import pydantic from weaving import config as _config _WHITESPACE_RE = re.compile(r"\s+") PageType = Literal["default", "blog", "blog_index"] LOGGER = logging.getLogger(__name__) class OpenGraphFrontm...
Nadock/rileychase.net
weaving/frontmatter.py
.py
26229e765a0a6c02
7.15
1
from __future__ import annotations import logging import sys from typing import TYPE_CHECKING if TYPE_CHECKING: from weaving import config def configure_logging(cfg: config.SiteGeneratorConfig) -> logging.Logger: """Setup root `logging.Logger` objects to print to stderr nicely.""" root = logging.getLogg...
Nadock/rileychase.net
weaving/logging.py
.py
5ac8e09838b9863d
7.15
1
from __future__ import annotations import datetime import os import pathlib import subprocess from typing import TYPE_CHECKING import markdown import yaml from weaving import ( blog, config, emoji, errors, frontmatter, logging, pymdx_class_tags, template, ) if TYPE_CHECKING: from...
Nadock/rileychase.net
weaving/markdown.py
.py
d2be0169b6f99064
7.15
1
import datetime import functools import pathlib import re from typing import Any import jinja2 import pydantic from weaving import frontmatter, logging LOGGER = logging.getLogger() class TemplateContext(pydantic.BaseModel): """Template context for rendering `default` type pages.""" content: str """Pre...
Nadock/rileychase.net
weaving/template.py
.py
c35fb871a2eaeab9
7.15
1
from __future__ import annotations import asyncio import contextlib from typing import TYPE_CHECKING from urllib import parse import aiofile import aiohttp import aiostream import bs4 from weaving import config, errors, markdown if TYPE_CHECKING: import pathlib from collections.abc import AsyncGenerator c...
Nadock/rileychase.net
weaving/validation.py
.py
6fe29053406fed23
7.15
1
"""Bot middleware: resolve Telegram user → DB User, attach role to handler data.""" import logging from datetime import datetime, timezone from typing import Any, Awaitable, Callable from aiogram import BaseMiddleware from aiogram.types import TelegramObject, Update from sqlalchemy import select from abooker.core.con...
trapwalker/abooker
src/abooker/bot/middleware.py
.py
a23792bd45b17965
7
0
"""Logging configuration loader with local override support.""" import logging.config import os from pathlib import Path import yaml _DEFAULT_CONFIG = Path(__file__).parent.parent / "logging.yaml" _LOCAL_NAMES = ["logging.local.yaml"] def _deep_merge(base: dict, override: dict) -> dict: result = base.copy() ...
trapwalker/abooker
src/abooker/core/log.py
.py
95070417756da628
7
0
"""Small human-readable formatting helpers shared by the bot and web layers.""" def fmt_bytes(n: float) -> str: for unit in ("Б", "КБ", "МБ", "ГБ", "ТБ"): if n < 1024: return f"{n:.1f} {unit}" n /= 1024 return f"{n:.1f} ПБ" def fmt_duration(seconds: float) -> str: seconds = i...
trapwalker/abooker
src/abooker/format.py
.py
01363bc318ca4e22
7
0
"""Jackett search proxy integration.""" import asyncio import logging from typing import Any from urllib.parse import quote_plus import aiohttp from abooker.core.config import settings log = logging.getLogger(__name__) AUDIO_BOOKS_CATEGORY = 3030 # Jackett's AudioBook category ID class TorrentResult: def __...
trapwalker/abooker
src/abooker/search/jackett.py
.py
f95d53a56dd2b1c3
7
0
"""Publication creation: torrent → RSS + DB records.""" import hashlib import json import logging import re from datetime import datetime, timezone from pathlib import Path from urllib.parse import quote from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from abooker.core.config import sett...
trapwalker/abooker
src/abooker/torrent/manager.py
.py
92191bbcbab599b4
7
0
"""Interactions with Git repo.""" import os def get_commit_id(base_dir): """Return commit ID of this repo.""" git_head = os.path.join(base_dir, ".git", "HEAD") # https://stackoverflow.com/questions/14989858/get-the-current-git-hash-in-a-python-script#21901260 # Open .git\HEAD file: with open(git_...
galaxyproject/ptdk
ptdk/git.py
.py
85670bfdee302d40
7.35
4
"""Fixtures for images.""" import io import random from functools import cache from importlib.resources import files from pathlib import Path from typing import Literal import pytest from PIL import Image _COLOR_SPACE_BANDS = { "L": 1, "RGB": 3, "CMYK": 4, } # Vuforia Web Services rejects images larger ...
VWS-Python/vws-test-fixtures
src/vws_test_fixtures/images.py
.py
5f05b976b4a9191e
7.65
1
"""Test for the new fixtures.""" import base64 import io from pathlib import Path import pytest from PIL import Image, UnidentifiedImageError from PIL.GifImagePlugin import GifImageFile import vws_test_fixtures from vws_test_fixtures.images import VWS_MAX_IMAGE_FILE_SIZE _MIN_HIGH_QUALITY_DIMENSION = 100 _PNG_TOO_L...
VWS-Python/vws-test-fixtures
tests/test_fixtures.py
.py
7d5e893e734538be
7.65
1
from django.contrib.flatpages.views import flatpage from django.http import Http404, JsonResponse from django.utils.translation import get_language, get_supported_language_variant from django.views.generic.detail import BaseDetailView, SingleObjectTemplateResponseMixin def localized_flatpage(request, base_url): "...
kelvan/ausgsteckt
ausgsteckt/ausgsteckt/views.py
.py
1982a827584d742a
7.24
2
from datetime import UTC, datetime from typing import Any from xml.sax import handler, xmlreader from xml.sax.saxutils import unescape DATEFORMAT = "%Y-%m-%dT%H:%M:%SZ" class NodeCenterSaxParser(handler.ContentHandler): """Extract single point elements from nodes, ways and relations from overpass xml Needs c...
kelvan/ausgsteckt
ausgsteckt/buschenschank/management/utils/overpass_parser.py
.py
ed2e521a2fc6b5a8
7.24
2
from urllib.parse import urlparse from django import template from django.template.loader import render_to_string register = template.Library() BADGE_TAGS = ["cuisine"] LIST_TAGS = ["opening_hours"] SAFE_URL_SCHEMES = {"http", "https"} @register.simple_tag def osmtag(node, tagname): return node.tags.get(tagna...
kelvan/ausgsteckt
ausgsteckt/buschenschank/templatetags/osm_tags.py
.py
6d56434297ca2912
7.24
2
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
starlingx/root
build-tools/stx/debian_revision.py
.py
a87e6cc2721ea8a4
7.35
4
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
starlingx/root
build-tools/stx/isolated_apt.py
.py
dfe78d8e2b73acd7
7.35
4
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
starlingx/root
build-tools/stx/package_metadata.py
.py
ef5a4b529cd56e98
7.35
4
# # Copyright (c) 2026 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import logging import os import shutil import sys import constants sys.path.append('..') import repo_manage import utils DEFAULT_APT_WORKSPACE = os.path.join(constants.LOADBUILD_ROOT, 'patch_workspace') TEMP_APT_SRC_PATH = "/...
starlingx/root
build-tools/stx/patch/apt_utils.py
.py
7345faf2c79b764b
7.35
4
# # Copyright (c) 2023 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import os import logging from Cryptodome.Signature import PKCS1_v1_5 from Cryptodome.Signature import PKCS1_PSS from Cryptodome.Hash import SHA256 from Cryptodome.PublicKey import RSA from Cryptodome.Util.asn1 import DerSequence...
starlingx/root
build-tools/stx/patch/signing/patch_verify.py
.py
cdfc1563f490b63c
7.35
4
# # Copyright (c) 2026 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # """ Functions for converting an XML file to a dict and vice-versa and for processing the dict obtained from parsing an XML file """ import logging import sys from lxml import etree sys.path.append('..') import utils logger =...
starlingx/root
build-tools/stx/patch/xml_parsing.py
.py
41d097749b4bc485
7.35
4
#!/usr/bin/env python """ Render README.md -- the GitHub profile page -- from README.md.in and ../data/yaml/profiles.yaml. GitHub serves README.md straight from the default branch of this repository, so it is a committed artifact rather than throwaway build output: there is no deploy step, and a push is the publish. ...
veltzer/veltzer
scripts/gen_readme.py
.py
5148ce6df00d0360
7
0
#!/usr/bin/env python """ Refresh the sibling ../data checkout and regenerate README.md from it. README.md is generated from README.md.in plus ../data/yaml/profiles.yaml, but that generation is deliberately not part of the build: the sibling data repo is private and is not checked out in CI, and README.md is committe...
veltzer/veltzer
scripts/update_from_data.py
.py
d7398c8a525f2f21
7
0
#!/usr/bin/env python """ Install this repo into the user account using symlinks. Everything lives under "src": the .py files there are standalone scripts and the directories there are support packages they import. The scripts become commands in ~/.local/bin and the packages become importable packages in the user sit...
veltzer/utils-python
scripts/install.py
.py
9d3064aebec69889
7
0
#!/usr/bin/env python """ Script to be used to catenate many mp3 files. """ import glob import subprocess doRun = True doCheck = False # do you want to redirect standard output? doRedirect = False def unite(filenames, out): print(f"creating [{out}] out of [{filenames}]") args = [ # "ffmpeg", ...
veltzer/utils-python
src/audio_mp3_cat_regexp.py
.py
77ee7e1dd6503b89
7
0
#!/usr/bin/env python """ This script re-encodes mp3 files. The idea is that this re-encoding fixes lots of common problems with mp3 files like files which have bad length because they were catenated badly. Avconv supports many codecs. See "avconv -codecs". we will use libmp3lame. """ import os import os.path import...
veltzer/utils-python
src/audio_mp3_recode.py
.py
9030e67025695fb2
7
0
#!/usr/bin/env python """Download every chess.com game for a user into one PGN. No auth, stdlib only.""" import argparse import configparser import json import os import sys import time import urllib.error import urllib.request API = "https://api.chess.com/pub/player" CONFIG = os.path.join( os.environ.get("XDG_CON...
veltzer/utils-python
src/chesscom_dump.py
.py
9ccf556f3ea64995
7
0
#!/usr/bin/env python """ Converts a Tab-Separated Values (TSV) file to a YAML file. The first line of the TSV is treated as the header row for the field names. Any spaces in the header names will be replaced with underscores to create the YAML keys. This script performs a pre-scan of the data to: 1. Omit any column ...
veltzer/utils-python
src/convert_tsv_to_yaml.py
.py
ab6cc0f0f6feddb3
7
0
#!/usr/bin/env python """ This is a script that knows how to download eclipse. These are examples of urls to download http://kambing.ui.ac.id/eclipse/technology/epp/downloads/release/luna/SR2/eclipse-cpp-luna-SR2-linux-gtk-x86_64.tar.gz http://mirrors.hustunique.com/eclipse/technology/epp/downloads/release/luna/SR2/e...
veltzer/utils-python
src/download_eclipe.py
.py
cad1d41a5fc6119c
7
0
#!/usr/bin/env python """ This script preps eclipse for my use by installing cdt and vrapper on it TODO: - check if the features we install exist before we install them. This will save time (see my eclipse notes about how to do that) and only install the feature if it is missing. - the name "neon" is hardcoded in thi...
veltzer/utils-python
src/eclipse_prep_eclipse.py
.py
b7a8c4f8bae236c6
7
0
#!/usr/bin/env python """ this script will create a workspace where eclipse can be launched this script also maximizes the eclipse window using the technique described in: http://unix.stackexchange.com/questions/103602/how-to-maximize-a-window-programmably-in-x-window """ import os import os.path import shutil import...
veltzer/utils-python
src/eclipse_prep_workspace.py
.py
038a11942c29fae6
7
0
#!/usr/bin/env python """ this script launches eclipse this script also maximizes the eclipse window using the technique described in: http://unix.stackexchange.com/questions/103602/how-to-maximize-a-window-programmably-in-x-window this will require that the workspace created will be unique (say tmpfile or something)...
veltzer/utils-python
src/eclipse_run.py
.py
40b1390fe00c4b0e
7
0
#!/usr/bin/env python """ Simple ELF File Finder Recursively finds and prints all ELF files in a directory. """ import sys from pathlib import Path def is_elf_file(filepath): """Check if a file is an ELF binary by examining its magic number.""" try: with open(filepath, "rb") as f: magic =...
veltzer/utils-python
src/find_elf.py
.py
0d2c09f904e7806e
7
0
#!/usr/bin/env python """ Clean up GitHub deployments, releases, and workflow runs for a repository. Keeps only the last N most recent (non-failed) of each, deleting the rest. Uses the `gh` CLI for authentication and API calls. """ import json import subprocess import sys def gh_api(endpoint, method="GET", fields=...
veltzer/utils-python
src/gh_clean_all.py
.py
35de71d48faddcd6
7
0
#!/usr/bin/env python """ Delete all but the last N GitHub deployments for a repository. Uses the `gh` CLI for authentication and API calls. """ import json import subprocess import sys def gh_api(endpoint, method="GET", fields=None): """Call the GitHub API via the gh CLI.""" cmd = ["gh", "api", endpoint] ...
veltzer/utils-python
src/gh_clean_deployments.py
.py
91b3b4aa3cbb2f1f
7
0
#!/usr/bin/env python """ Keep only the latest N GitHub releases and delete all others. Uses the `gh` CLI for authentication and API calls. """ import json import subprocess import sys def gh_api(endpoint, method="GET"): """Call the GitHub API via the gh CLI.""" cmd = ["gh", "api", endpoint] if method ...
veltzer/utils-python
src/gh_clean_releases.py
.py
dcc5424d0c8b383d
7
0
#!/usr/bin/env python """ Delete all but the last N GitHub Actions workflow runs for a repository. Uses the `gh` CLI for authentication and API calls. """ import json import subprocess import sys def gh_api(endpoint, method="GET"): """Call the GitHub API via the gh CLI.""" cmd = ["gh", "api", endpoint] ...
veltzer/utils-python
src/gh_clean_workflows.py
.py
e42ef27e89e9c6d2
7
0
""" module to help with imap. Tecnically this is a wrapper object. To see the documentation of the API use: pydoc imaplib This thing started from me wanting to import my old mail to gmail and seeing this blog post: http://scott.yang.id.au/2009/01/migrate-emails-maildir-gmail.html Refrences: http://stackoverflow.com/...
veltzer/utils-python
src/imap/imap.py
.py
087c9fbeccaacecb
7
0
#!/usr/bin/env python """ marp_check_images """ import os import re import sys from pathlib import Path def find_marp_files(root_dir: str) -> list[Path]: """Find all markdown files that might be Marp presentations recursively.""" root_path = Path(root_dir) marp_files = [] for path in root_path.rglo...
veltzer/utils-python
src/marp_check_images.py
.py
f71ebe02ce0563a3
7
0
#!/usr/bin/env python """ I need a python script that accepts marp/markdown files as input and searches for mermaid inlined diagrams in them. When it finds a mermaid diagram it prompts the user with the content of the current slide and asks for the name of the diagram. When it gets the name it saves the diagrams as a ...
veltzer/utils-python
src/marp_mermaid_extract.py
.py
e144448e05164148
7
0
#!/usr/bin/env python """ This script prints repos which are not registered in mr. It will first read the projects registered in ~/.mrconfig TODO: - make this script query github and bitbucket and do the reverse check as well: that all the repos that I have there are here too. """ import os.path def add_folder(ba...
veltzer/utils-python
src/mr_diff.py
.py
61068123024991b4
7
0
#!/usr/bin/env python """ This script runs "make" (make(1)) in every project that is mine. """ import os import os.path import subprocess import sys import yaml home = os.getenv("HOME") assert home is not None, "HOME environment variable is not set" print_all = True stop_on_fail = False def run_check_string(args,...
veltzer/utils-python
src/mr_make.py
.py
fca277062fd81ef6
7
0
#!/usr/bin/env python """ This script upgrades just one pip module. It is very useful if you have a ton of repos and want to upgrade some module in all of them. """ import importlib import subprocess import sys def upgrade_module(module_name): try: importlib.import_module(module_name) # module_...
veltzer/utils-python
src/pip_upgrade.py
.py
94a147c1016e75cc
7
0
#!/usr/bin/env python """ script to convert ppt files to text """ import sys from pptx import Presentation def odp_to_text(source, target): with open(target, "w") as stream: prs = Presentation(source) for slide in prs.slides: for shape in slide.shapes: if hasattr(sha...
veltzer/utils-python
src/ppt_to_text.py
.py
9b70c838c06a3cf6
7
0
#!/usr/bin/env python """ This script checks that two screens are attached to the current machine, and then sets the two screens to the maximum resolution that the two screens support. I mainly use this script for teaching... Another way to configure this is to use the KDE -> System Settings -> Display and Monitor ->...
veltzer/utils-python
src/screen_dup.py
.py
0a078069dfad2d5e
7
0
""" This is the main code """ import json import sys from pprint import pprint def dump_print(obj): print(obj) def dump_pprint(obj): pprint(obj) def dump_obj(obj, level=0): try: for a in dir(obj): # print(a) if a.startswith("_"): continue if ...
veltzer/pyvardump
src/pyvardump/dump.py
.py
9ead128d989a3970
7
0
""" All configurations for pyunique """ import hashlib from pytconf import Config, ParamCreator class ConfigScan(Config): """ Parameters that control the scanning phase """ folder = ParamCreator.create_existing_folder( help_string="Which folder to work on?", default=".", ) class...
veltzer/pyunique
src/pyunique/configs.py
.py
79a2f9ee8475b0f1
7
0
#!/usr/bin/env python """ Web server for development purposes, light weight with some features. Mark Veltzer TODO: - call this project dws. - fix the logging of the web server to go to .dws_logs - fix it so the cwd of the web server will not change to /. - fix it so if there is a problem with the web server I wi...
veltzer/pyweblight
src/pyweblight/webserver_start.py
.py
7e9dd292c2599b0b
7.15
1
""" Build hook that supplies client_secret.json to the distribution. The credential is deliberately not in the repo: GitHub push protection rejects Google OAuth secrets, and publicly scanned ones get reported to Google and revoked. But it must ship inside the package so that a plain `pip install pytubekit` works with ...
veltzer/pytubekit
hatch_build.py
.py
4c4714b96b75b985
7.3
3
""" utils.py """ import os import subprocess from pptx import Presentation def ensure_dir(f): folder = os.path.dirname(f) if folder != "" and not os.path.isdir(folder): os.makedirs(folder) def touch(f): if os.path.isfile(f): os.utime(f, None) else: with open(f, "w"): ...
veltzer/pypptkit
src/pypptkit/utils.py
.py
c1ed1578ef789593
7
0
""" main """ import pylogconf.core from pytconf import config_arg_parse_and_launch, get_free_args, register_endpoint, register_main from pysvgview.static import APP_NAME, DESCRIPTION, VERSION_STR from pysvgview.svg_view import view_svgs @register_endpoint( allow_free_args=True, description="View svgs", ) def...
veltzer/pysvgview
src/pysvgview/main.py
.py
ea08eacbc43065a9
7
0
"""" svg_view.py """ import enum import os import sys # pylint cannot introspect the Qt compiled extension modules, so every name # imported from them reads as missing. Keep this disable above the whole Qt # import block — import sorting will not separate it from what it covers. # pylint: disable=no-name-in-module f...
veltzer/pysvgview
src/pysvgview/svg_view.py
.py
ad0017ad33b3747a
7
0
""" utils.py """ import logging import os import sys from pymakehelper.configs import ConfigSymlinkInstall, ConfigVerbose from pymakehelper.static import APP_NAME def unlink_check(filename: str): """ this is a function that removes a file and can optionally die if there is a problem """ if ConfigVer...
veltzer/pymakehelper
src/pymakehelper/utils.py
.py
3721e8b310d17a86
7
0
""" This is a script that runs pdflatex for us. Why do we need this script ? - to remove the output before we run pdflatex so that we will be sure that we start clean. if pdflatex finds a file it will * reprocess * it and we dont want that, do we ? - we need to run pdflatex twice to create indexes and more. - pdf latex...
veltzer/pymakehelper
src/pymakehelper/wrapper_pdflatex.py
.py
7f31de24c81050f4
7
0
""" auth.py """ import importlib import logging import os import pickle from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from pygooglehelper.configs import ConfigAuth, ConfigRequest from pygooglehelper.static i...
veltzer/pygooglehelper
src/pygooglehelper/auth.py
.py
1eb43201a1ebce68
7
0
""" configs.py """ from pytconf import Config, ParamCreator class ConfigAuth(Config): """ Configuration parameters for doing the authentication to google """ force = ParamCreator.create_bool( help_string="Should we force creation of a new auth token", default=False, ) host = P...
veltzer/pygooglehelper
src/pygooglehelper/configs.py
.py
09b8d1628253aca9
7
0
""" configs.py """ from pytconf import Config, ParamCreator class ConfigRepository(Config): """ Parameters to specify the repository """ folder = ParamCreator.create_existing_folder( help_string="where is the repository", default="/mnt/seagate/mark/topics_archive/audio/abooks/by_name"...
veltzer/pyfoldercheck
src/pyfoldercheck/configs.py
.py
2533f997cd4dfca9
7
0
""" main.py """ import json import os import pylogconf.core from pytconf import config_arg_parse_and_launch, register_endpoint, register_main from pyfoldercheck.configs import Authorized, ConfigNames, ConfigRepository from pyfoldercheck.static import APP_NAME, DESCRIPTION, VERSION_STR from pyfoldercheck.utils import...
veltzer/pyfoldercheck
src/pyfoldercheck/main.py
.py
80e09660e24766eb
7
0
""" All configurations """ from pytconf import Config, ParamCreator class ConfigAlgo(Config): """ Parameters for interval monitors """ interval = ParamCreator.create_int( default=60, help_string="interval to monitor", ) watermark_max = ParamCreator.create_int_or_none( ...
veltzer/pyflexebs
src/pyflexebs/configs.py
.py
f828ac2508f23dc6
7
0
""" main.py """ import os import subprocess import sys import time import bitmath import boto3 import ec2_metadata import psutil import pylogconf.core from daemon import daemon from hurry.filesize import size from pylogconf.core import create_pylogconf_file from pytconf import config_arg_parse_and_launch, register_en...
veltzer/pyflexebs
src/pyflexebs/main.py
.py
a8d3b79e08c3f8eb
7
0
""" utils.py """ import logging import os import sys from subprocess import PIPE, Popen import pypathutil.common import pyflexebs from pyflexebs.configs import ConfigProxy def run_with_logger(args, logger): """ Execute the external command and get its exitcode, stdout and stderr. """ all_args = ","...
veltzer/pyflexebs
src/pyflexebs/utils.py
.py
367ca6276ecfdc42
7
0
""" core of the package """ import datetime import json import os import os.path import subprocess from typing import Any def old_get_key(domain: str) -> str: filename = os.path.expanduser("~/.config/pyapikey.json") with open(filename) as file_handle: keys = json.load(file_handle) return keys...
veltzer/pyapikey
src/pyapikey/core.py
.py
6206daad3572ad1a
7.15
1
#!/usr/bin/env python """ This is a script that wraps the execution of "sketch". Why? - too noisy on the command line when everything is right. - does not cleanly separate warning and errors (stdout vs stderr). """ import os import subprocess import sys import tempfile # Parameters DEBUG = False REMOVE_TMP = True ...
veltzer/demos-lang-tex
scripts/wrapper_sketch.py
.py
5a4f887ed4105656
7
0
#!/usr/bin/env python """ Example that shows that we can complete any series of number with any number """ # f(1) = 1 # f(2) = 4 # f(3) = 9 # f(4) = ? def produce_number_alt_2(i): s=0 s+=(i-2)*(i-3)*(i-4)*1/(-6) s+=(i-1)*(i-3)*(i-4)*4/2 s+=(i-1)*(i-2)*(i-4)*9/-2 s+=(i-1)*(i-2)*(i-3)*1979/6 re...
veltzer/demos-lang-python-ml
src/00_algorithms/02_print_series.py
.py
202067179372d87f
7
0
#!/usr/bin/env python """Solution to exercise 20: spell checker via letter-drop index.""" from collections import defaultdict def drop_one_letter(word: str) -> list[str]: return [word[:i] + word[i + 1:] for i in range(len(word))] def build_index(words: list[str]) -> dict[str, set[str]]: idx: dict[str, set...
veltzer/demos-lang-python-ml
src/00_algorithms/04_spell_checker.py
.py
2fdd773181cea785
7
0
#!/usr/bin/env python """Solution to exercise 11: Euclidean distance and pairwise distance matrix.""" import numpy as np def euclidean(p1: np.ndarray, p2: np.ndarray) -> float: return float(np.sqrt(np.sum((p1 - p2) ** 2))) def pairwise(points: np.ndarray) -> np.ndarray: diff = points[:, None, :] - points[...
veltzer/demos-lang-python-ml
src/01_numpy/10_euclidean_distance.py
.py
7611a1f8c7a077c9
7
0
#!/usr/bin/env python """Solution to exercise 12: large-scale sensor pipeline — masking, filtering, fast expressions.""" import time import numpy as np def generate(n: int, s: int) -> tuple[np.ndarray, np.ndarray]: rng = np.random.default_rng(42) sensor = rng.integers(0, s, size=n) base = rng.uniform(1...
veltzer/demos-lang-python-ml
src/01_numpy/11_sensor_pipeline.py
.py
5a929c453db29630
7
0
#!/usr/bin/env python """Solution to exercise 14: compare vectorized vs apply vs Python-loop timings.""" import time from typing import cast import numpy as np import pandas as pd def time_it(label: str, func) -> None: t0 = time.perf_counter() func() t1 = time.perf_counter() print(f"{label}: {t1 - ...
veltzer/demos-lang-python-ml
src/02_pandas/13_vectorization_speed.py
.py
699478f9d75821ef
7
0
#!/usr/bin/env python """Show pending cluster-state tasks and long-running tasks. Two different things, both important to a DBA: GET /_cluster/pending_tasks Changes queued against the cluster STATE (mapping updates, shard allocation decisions, settings changes) that the master has not yet applied. A gro...
veltzer/demos-db-elk
exercises/dba/00_cluster_health_monitoring/08_pending_and_tasks.py
.py
d557b0af2bee9b4c
7.15
1
#!/usr/bin/env python """ Load sample log documents into the "logs_sharded" index using the bulk helper """ # Load sample log documents into the "logs_sharded" index using the bulk # helper. We generate realistic-looking log lines with the faker library so # the shards have meaningful, varied content and a non-trivial...
veltzer/demos-db-elk
exercises/dba/01_shard_management/02_load_sample_data.py
.py
f66c5aa1b1f3fd76
7.15
1
#!/usr/bin/env python """ Report shard count vs data size per index and flag suspicious shard sizing """ # Report shard count vs data size for every index and flag suspicious shard # sizing. This is the heart of the "oversharding" problem that bites real # clusters: thousands of tiny shards each carry fixed memory/ove...
veltzer/demos-db-elk
exercises/dba/01_shard_management/04_shard_sizing_report.py
.py
f9eb026e8f47c175
7.15
1
#!/usr/bin/env python """Watch an index advance through ILM phases in a short, observable session. Real retention policies use day/week/month time units, so you would never see a transition during a training session. This script instead: 1. Lowers the cluster-wide ILM poll interval so checks happen every 10s (...
veltzer/demos-db-elk
exercises/dba/02_index_lifecycle_management/08_watch_transitions.py
.py
38a677e5829c6de4
7.15
1
#!/usr/bin/env python """Automated disaster-recovery drill. A DR drill proves that a backup is actually restorable. Taking snapshots is worthless if you have never verified that a restore brings the data back intact. This script runs the full loop against a throwaway index: 1. create an index and load known data ...
veltzer/demos-db-elk
exercises/dba/03_snapshot_restore/06_dr_drill.py
.py
d7223afe29521b57
7.15
1
#!/usr/bin/env python """Zero-downtime mapping change via the classic alias-swap pattern. The problem: you cannot change the type of an existing field in place. To "change a mapping" you must build a NEW index with the new mapping and move the data across. Done naively (delete + recreate) there is a window where the i...
veltzer/demos-db-elk
exercises/dba/04_index_templates_aliases/07_zero_downtime_swap.py
.py
cd19c0a5e8cf9336
7.15
1
#!/usr/bin/env python """Create a demo index and load enough data to make the stats interesting. This gives the rest of the exercise something to measure. It creates the `perf_demo` index with a sensible mapping (a `keyword` field for safe aggregation and a `text` field for searching) and bulk-loads fake documents. It...
veltzer/demos-db-elk
exercises/dba/05_performance_tuning/01_generate_load.py
.py
4b3f67b7cfe97077
7.15
1
#!/usr/bin/env python """Report Elasticsearch cache usage and hit ratios per node. This wraps GET /_nodes/stats/indices/query_cache,request_cache,fielddata and explains the three caches a DBA tunes: * query cache (a.k.a. node query cache): caches the results of filter clauses (the non-scoring parts of a query) ...
veltzer/demos-db-elk
exercises/dba/05_performance_tuning/04_caches.py
.py
78135900f4d9495e
7.15
1
#!/usr/bin/env python """ Load sample documents into the "capacity_demo" index for the disk and capacity scripts """ # Load sample documents into the "capacity_demo" index so the later disk and # capacity scripts have a non-trivial store size to look at. We generate # realistic-looking event documents with the faker l...
veltzer/demos-db-elk
exercises/dba/06_capacity_disk_management/01_load_sample_data.py
.py
68e1bee0c4220f2f
7.15
1
#!/usr/bin/env python """Find which FIELDS consume the most disk in an index. Wraps POST /<index>/_disk_usage?run_expensive_tasks=true. This API actually reads the on-disk Lucene structures, so it is genuinely expensive (it scans segments) and must be opted into with run_expensive_tasks=true. The payoff is a precise p...
veltzer/demos-db-elk
exercises/dba/06_capacity_disk_management/06_disk_usage_analysis.py
.py
8535b6919b06baf4
7.15
1
#!/usr/bin/env python """Simple disk capacity planner / storage forecaster for a DBA. Given the current store size and document count of an index, plus an estimate of how many new documents arrive per day, this script projects: * average bytes per document (store size / doc count) * how many MB/GB the index grows...
veltzer/demos-db-elk
exercises/dba/06_capacity_disk_management/08_capacity_forecast.py
.py
26a9cc856888ff7b
7.15
1
#!/usr/bin/env python """ End-to-end zero-downtime index migration runbook using an alias swap """ # End-to-end "migrate index" runbook in one script. # # This is the pattern you reach for when a production index has the wrong # mapping and you need to fix it with zero downtime for readers. The trick # is to point app...
veltzer/demos-db-elk
exercises/dba/07_reindex_upgrade/07_migrate_index.py
.py
df714e293143cde5
7.15
1
#!/usr/bin/env python """Nagios-style threshold check for Elasticsearch. Runs the metrics collector from 01_metrics_collector.py, evaluates each metric against a configurable threshold, prints one OK/WARN/CRITICAL line per check, and exits with a Nagios-compatible code: 0 OK all checks passed 1 WARNI...
veltzer/demos-db-elk
exercises/dba/08_monitoring_alerting/02_threshold_check.py
.py
4d82fcfbb84824ff
7.15
1
#!/usr/bin/env python """Self-monitoring: index collected metrics back into Elasticsearch. Runs the collector from 01_metrics_collector.py, stamps the result with a UTC @timestamp, and bulk-indexes it as one document into the dba-metrics write alias. Storing metrics this way lets you chart cluster health over time in ...
veltzer/demos-db-elk
exercises/dba/08_monitoring_alerting/05_index_metrics.py
.py
1d6521050f3b42f0
7.15
1
#!/usr/bin/env python """Sample metrics on a fixed interval for a fixed duration. This generates a short time series of dba-metrics documents so a learner can immediately see a line chart in Kibana without waiting hours for cron to accumulate data points. Usage: ./06_sample_loop.py [interval_seconds] [duration_s...
veltzer/demos-db-elk
exercises/dba/08_monitoring_alerting/06_sample_loop.py
.py
7491816f7581eb21
7.15
1