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 |
|---|---|---|---|---|---|---|
# pyright: reportPrivateUsage=false
# pylint: disable=protected-access,super-init-not-called
# ruff: noqa: ANN401, SLF001
"""Tests for finding VuMark target links."""
from typing import Any
import pytest
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElem... | VWS-Python/vws-web-tools | tests/test_vumark_target_link.py | .py | d4600fc2268bd869 | 7.5 | 0 |
"""
Configurations for the application.
"""
import logging
import os
import sys
from typing import Dict, List, Optional
import yaml
from aiu import __meta__
AIU_PACKAGE_DIR = os.path.abspath(os.path.dirname(__file__))
AIU_ROOT_DIR = os.path.dirname(AIU_PACKAGE_DIR)
AIU_CONFIG_DIR = os.path.join(AIU_ROOT_DIR, "confi... | fmigneault/aiu | aiu/config.py | .py | 2a67af878aab2313 | 7.3 | 3 |
"""
Audio field and container type definitions.
"""
import datetime
import logging
import os
import shutil
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterable,
List,
Optional,
Tuple,
Type,
Union,
)
from typing_extensions import TypeAlias
import eyed3
from eyed3.id3.tag import T... | fmigneault/aiu | aiu/typedefs.py | .py | 5d27decadf3b344c | 7.3 | 3 |
"""
Generic utilities used across the project.
"""
import os
import re
import shutil
from functools import wraps
from typing import (
Callable,
Iterable,
List,
Optional,
Union,
)
from aiu.config import LOGGER
from aiu.typedefs import LoggerType
FILENAME_ILLEGAL_CHARS = ["\\", "/", ":", "*", "?", "... | fmigneault/aiu | aiu/utils.py | .py | 5771a1a477a77f25 | 7.3 | 3 |
from .form import *
from .util import *
from .align import *
# tuned for 300 dpi grayscale text
BLACK_LEVEL = 0.5 * 255 # 255 is pure white
CHECK_THR = 0.05 # threshold for checked box
EMPTY_THR = 0.02 # threshold for empty box
RADIO_THR = 0.01 # threhold for picking radio button
def calc_checkbox_score(image, res... | sdrp/digitize-mtc | backend/scripts/omr.py | .py | 200a04ea7640ee18 | 7 | 0 |
from app import *
from flask import request, render_template, jsonify, Response
import argparse
import json
import os
from scripts import *
import time
import cv2
import webbrowser
import platform
import webbrowser
from math import inf
@app.route('/')
def home():
vs.stop()
return render_template('home.html')
# To D... | sdrp/digitize-mtc | backend/server.py | .py | a8543d83a514bd1c | 7 | 0 |
import os
from os import listdir
import argparse
import csv
import sys
from collections import namedtuple
import pdb
from math import inf
sys.path.append("..") # Adds higher directory to python modules path so we can import
from scripts import util, AlignmentError, align, compute_blurriness, omr, Form
from server impo... | sdrp/digitize-mtc | backend/tests/test_end_to_end.py | .py | 01812ca74026b8ed | 7.5 | 0 |
'''
A Python script that generates a JSON template for a form
based on an SVG with tagged rectangles
Eventually we will have a front-end interface that will allow users
to generate this template by uploading a form image and annotating it
themselves using a GUI.
'''
from form import *
import json
from pathlib import P... | sdrp/digitize-mtc | scratch/misc/convert_svg_to_json_no_translation.py | .py | 746b5b9a1fb21361 | 7 | 0 |
from PIL import Image
import pytesseract
def ocr_core(filename):
"""
This function will handle the core OCR processing of images.
"""
text = pytesseract.image_to_string(Image.open(filename), config="-c tessedit_char_whitelist=0123456789") # We'll use Pillow's Image class to open the image and pytesser... | sdrp/digitize-mtc | scratch/misc/ocr_test.py | .py | 7d96fea540a96d9f | 7.5 | 0 |
"""Ordered calibration-epoch registries backed by immutable snapshots.
The registry deliberately stores only snapshot identities. Shot/date validity
remains in each snapshot's existing ``[validity]`` table, so there is one
authority for epoch boundaries rather than two hand-edited copies.
"""
from __future__ import ... | queezz/echelle_spectra | src/echelle_spectra/calibration_registry.py | .py | aa35f8a03f584e11 | 7.5 | 0 |
"""Portable per-drive cube catalogs and merged all-years indexes."""
from __future__ import annotations
import json
import os
import threading
import uuid
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from .campaign_run import (
GATE_UNRECORDED,
RunReceipt,
read_... | queezz/echelle_spectra | src/echelle_spectra/catalog.py | .py | e976f95a6df0cec0 | 7.5 | 0 |
"""What is on this campaign drive: logbooks, day folders, calibrations, space.
The first question asked of a drive that arrives in a box is not a scientific
one. It is *which drive is this* -- how many observing days, which shot
numbers, whether the curator's logbook agrees, and whether there is room to
write cubes b... | queezz/echelle_spectra | src/echelle_spectra/drive_inventory.py | .py | b540e2dbe3c9ce51 | 7.5 | 0 |
"""The one folder dialog both GUIs open, and the two habits it has.
The viewer and the calibration bench each ask the same question — *which
folder?* — and each used to ask it with its own hand-built
:class:`QtWidgets.QFileDialog`. They drifted, as a pair kept in two places
does: the bench learned to show a folder's ... | queezz/echelle_spectra | src/echelle_spectra/folder_picker.py | .py | ea6f073359d52927 | 7.5 | 0 |
"""Thin immutable manifests over historical calibration filenames.
A binder states what a past calibration actually used: the artifact filenames as
they were named at the time, and — where the file travels with this package —
its recorded size and SHA-256. Artifacts too large to package, such as a
campaign folder's s... | queezz/echelle_spectra | src/echelle_spectra/historical.py | .py | 5371b4d3111b9b5f | 7.5 | 0 |
"""LHD text export against a frozen header.
The LHD-side text header is a contract with the machine's data system, so it
stays at the byte shape it had before the Harbor unification (owner ruling,
2026-08-14). Two legacy dialects survive, and both are rendered here from
templates recovered verbatim from the pre-train... | queezz/echelle_spectra | src/echelle_spectra/lhd_text.py | .py | 3591fc5daaada281 | 7.5 | 0 |
"""Where does this drive's light sit, against which era's order pattern?
Two field questions turned out to be one measurement. The first is a diary:
sample a campaign through time, read one plasma-bright frame per sampled day,
and record where its order bands sit against each candidate era pattern -- the
geometry bet... | queezz/echelle_spectra | src/echelle_spectra/pattern_survey.py | .py | 8cc0d51c088ae465 | 7.5 | 0 |
"""Display levels for the raw 2-D detector frame.
An echelle calibration frame is not a picture, and the level rule that suits a
picture ruins it. Measured on the owner's 20250926 pair
(``local/20250926_calib/Ne-0.02s-x3-bright-lines.sif`` and
``Ne-0.1s-x3-dimm-lines.sif``, both 2560x2160): the frame is one enormous
... | queezz/echelle_spectra | src/echelle_spectra/tools/detector_display.py | .py | 4636b78bfe63c183 | 7.5 | 0 |
import numpy as np
from lmfit.lineshapes import gaussian
def baseline_als(y, lam, p, niter=10):
"""Asymmetric Least Squares Smoothing" by P. Eilers and H. Boelens
y - signal, lam - parameter (float or array), p - weight (float, array?)
"""
from scipy.sparse import csc_matrix, spdiags
from scipy.sp... | queezz/echelle_spectra | src/echelle_spectra/tools/emissionbands.py | .py | 414165a6509367d8 | 7.5 | 0 |
"""Shared, provenance-carrying spectral line tables.
The catalog is calibration-facing. It provides line positions and lightweight
identification metadata without importing downstream molecular fitting logic.
"""
from __future__ import annotations
from dataclasses import dataclass, replace
from functools import lru... | queezz/echelle_spectra | src/echelle_spectra/tools/line_catalog.py | .py | b1ce2297e20d9b64 | 7.5 | 0 |
"""Range-aware pyqtgraph overlays backed by the shared line catalog."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Mapping, Sequence
import numpy as np
import pyqtgraph as pg
from .line_catalog import (
LAMP_LINE_FAMILIES,
LINE_FAMILIES,
SpectralLine,
loa... | queezz/echelle_spectra | src/echelle_spectra/tools/line_overlay.py | .py | 5107738ea80e1306 | 7.5 | 0 |
"""Known-line wavelength validation helpers.
This module is intentionally narrow: it validates measured peak positions
against supplied line wavelengths. Molecular modeling and intensity analysis
belong in downstream packages such as ``fulcher_analyzer``.
"""
from __future__ import annotations
from dataclasses impor... | queezz/echelle_spectra | src/echelle_spectra/tools/line_validation.py | .py | a372bf852d4c309b | 7.5 | 0 |
"""Helpers for loading SIF files into Spectrum objects without the GUI.
This module exists so the CLI and tests can load and extract spectra without
importing any Qt/GUI machinery. The loading logic mirrors what the GUI does
in ``LoadCalibrationsThread`` + ``LoadImageThread``.
"""
from __future__ import annotations
... | queezz/echelle_spectra | src/echelle_spectra/tools/loader.py | .py | 3e4e063c35efda81 | 7.5 | 0 |
"""Re-extract the packaged NIST ASD line caches from physics.nist.gov.
The caches under ``src/echelle_spectra/resources/nist_asd_cache`` were first
produced by hand from the NIST ASD "Lines" web form, and nothing in the tree
recorded which query produced them. That is how they came to span only
580--638 nm -- the Ful... | queezz/echelle_spectra | src/echelle_spectra/tools/nist_cache_refresh.py | .py | e14401e4b4695115 | 7.5 | 0 |
"""NIST ASD helpers for lamp-based wavelength calibration review.
This module deliberately works with cached NIST ASD exports. Network fetching
belongs in notebooks or one-off local scripts so calibration runs stay
reproducible.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from ... | queezz/echelle_spectra | src/echelle_spectra/tools/nist_lamp_calibration.py | .py | cbf3a98acdb52bf0 | 7.5 | 0 |
"""Tests for seasonal decomposition.
The schema tests carry the most weight. The previous implementation returned
``derivative_value`` from one code path and ``trend_derivative_value`` from
another, so what a caller had to index depended on whether seasonality happened
to be detected. Several tests below exist purely ... | finite-sample/incline | tests/test_seasonal.py | .py | 86e480bd60fb28b3 | 7.74 | 2 |
"""
Tests for issue #3 - Fix hardcoded MongoDB credentials exposed in source code
"""
import os
import sys
import unittest
from unittest.mock import MagicMock, patch
class TestMongoURIConfig(unittest.TestCase):
"""Tests that MONGO_URI env var is used and fallback default is correct."""
def _reload_app_modul... | DewaldOosthuizen/python-rest-tutorial | tests/test_app_config.py | .py | 0625e92842c7adbc | 7.89 | 5 |
"""
Tests for issue #17: Replace deprecated PyMongo collection.insert() and collection.update() calls.
Verifies that web/app.py uses the modern insert_one and update_one PyMongo 4.x API.
"""
import os
APP_PATH = os.path.join(os.path.dirname(__file__), "..", "web", "app.py")
REQUIREMENTS_PATH = os.path.join(os.path.di... | DewaldOosthuizen/python-rest-tutorial | tests/test_issue_17_pymongo_api.py | .py | a689ba369168d3bb | 7.89 | 5 |
# import functools
import datetime
import os
import re
from datetime import timezone
from functools import wraps
import bcrypt
import jwt
from flask import Flask, jsonify, request
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_restful import Api, Resource
from pymongo im... | DewaldOosthuizen/python-rest-tutorial | web/app.py | .py | 0e2253373637ddff | 7.39 | 5 |
import os
class Path(str):
"""A class that represents a path. It is a subclass of str, so it can be used as a string.
Attributes:
path (str): The path as a string.
abs (str): The absolute path as a string.
basename (str): The basename of the path.
ext (str): The extension of t... | kyan001/PyConsoleCMDTools | consolecmdtools/path.py | .py | 64b0065132970fc6 | 7.24 | 2 |
# -*- coding: utf-8 -*-
import queue
class FakeErr:
'''
用于重定向 sys.stderr
系统默认调用 sys.stderr.write()
'''
def __init__(self):
self.q = queue.LifoQueue() # (stack)
self.buffer = ""
def write(self, words):
self.buffer += words
if words == '\n': # print会自动单独write一个... | kyan001/PyConsoleCMDTools | tests/FakeErr.py | .py | 7adc4d1638a9cdc5 | 7.74 | 2 |
# -*- coding: utf-8 -*-
import queue
class FakeIn:
'''
用于重定向 sys.stdin
系统默认调用 sys.stdin.readline()[:-1]
'''
def __init__(self):
self.q = queue.LifoQueue() # (stack)
def readline(self):
if self.q.empty():
return '\n'
else:
return self.q.get()
... | kyan001/PyConsoleCMDTools | tests/FakeIn.py | .py | b133577f55ec0626 | 7.74 | 2 |
# -*- coding: utf-8 -*-
import queue
class FakeOs:
'''用于重定向 os.system'''
def __init__(self):
self.call_q = queue.LifoQueue() # (stack)
def system(self, cmd):
self.call_q.put(cmd)
return 0
def readline(self):
if self.call_q.empty():
return None
els... | kyan001/PyConsoleCMDTools | tests/FakeOs.py | .py | eaee36ff5c3b9853 | 7.24 | 2 |
# -*- coding: utf-8 -*-
import queue
class FakeOut:
'''
用于重定向 sys.stdout
系统默认调用 sys.stdout.write()
'''
def __init__(self):
self.q = queue.LifoQueue() # (stack)
self.buffer = ""
def write(self, words):
self.buffer += words
if words == '\n': # print会自动单独write一个... | kyan001/PyConsoleCMDTools | tests/FakeOut.py | .py | 573a2b11466a8874 | 7.74 | 2 |
# Copyright 2020 Michael Still
import json
import logging
import sys
import click
try:
from importlib.metadata import entry_points
except ImportError:
from importlib_metadata import entry_points
from shakenfist_utilities import logs
from shakenfist_client import apiclient
from shakenfist_client.commandline im... | shakenfist/client-python | shakenfist_client/main.py | .py | 4917c3cf4aa6edc0 | 7.15 | 1 |
import io
import logging
from unittest import mock
import testtools
from click.testing import CliRunner
from shakenfist_client import main
# A structurally valid JWT: three base64url segments, the header being
# base64url('{"alg":"none"}'). The redaction has to key off the shape of
# the string rather than where it... | shakenfist/client-python | shakenfist_client/tests/test_client_main.py | .py | ef35704888d36642 | 7.65 | 1 |
from datetime import datetime
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired
from wtforms import (
BooleanField,
DateField,
HiddenField,
IntegerField,
PasswordField,
RadioField,
SelectField,
SelectMultipleField,
StringField,
SubmitField,
T... | gfitzp/fitzflix | app/main/forms.py | .py | 54a026eb13e28a81 | 7.15 | 1 |
#!/usr/bin/env python3
"""Backup retention pruning for /backup/picasa_db_YYYY-MM-DD.tar.zst files.
Three tiers, applied in order:
- Daily: keep every backup from the last DAILY_RETENTION_DAYS days.
- Weekly: for backups older than that but within WEEKLY_RETENTION_DAYS,
keep one per ISO week (the ea... | benjaminlewis-1000/django_picasa | dockerize/prune_backups.py | .py | 2bae42d7bae6d6be | 7 | 0 |
"""Runtime configuration for Mr. Ajeeb.
Every value can be overridden with an ``AJEEB_*`` environment variable, so the
same code runs in a terminal, in Streamlit, or in CI without edits.
"""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from datetime import date
from pathlib i... | KanishKumar11/ajeebpy | ajeeb/config.py | .py | 0469e23d82b53c0c | 7 | 0 |
"""A tiny intent registry: the modern replacement for a long ``if/elif`` chain.
Each skill declares the phrasings it answers to as regular expressions. The
registry picks the highest-priority pattern that matches and hands the regex
``Match`` to the handler, so skills receive parsed arguments instead of
re-slicing the... | KanishKumar11/ajeebpy | ajeeb/registry.py | .py | 0ac4aa4a7782b8c5 | 7 | 0 |
"""Small JSON-backed store so notes survive between sessions.
Deliberately boring: one file, atomic writes, and every failure degrades to an
empty list rather than taking the assistant down with it.
"""
from __future__ import annotations
import json
import logging
import os
from dataclasses import asdict, dataclass
... | KanishKumar11/ajeebpy | ajeeb/storage.py | .py | 9db1583db9637068 | 7 | 0 |
"""Speech to text.
Two entry points, both built on SpeechRecognition:
* :func:`listen` grabs a phrase from a live microphone (terminal front-end).
* :func:`transcribe` turns recorded audio bytes into text (browser front-end,
where the microphone belongs to the browser and PyAudio is not needed).
Every failure come... | KanishKumar11/ajeebpy | ajeeb/stt.py | .py | 0fd89125576cb808 | 7 | 0 |
"""Text to speech, with graceful fallbacks.
The 2020 version hard-coded ``voices[2].id``, which raises ``IndexError`` on any
machine with fewer than three installed voices. Here the backend is chosen at
runtime, the voice is looked up by name, and if nothing is available the
assistant simply stops speaking instead of ... | KanishKumar11/ajeebpy | ajeeb/tts.py | .py | 39224931e04b745f | 7 | 0 |
# Copyright 2018-2026 Simon Brunning
import dataclasses
import logging
import re
from collections import OrderedDict
from collections.abc import Iterable, Iterator, Mapping, Sequence
from typing import Any
logger = logging.getLogger(__name__)
class RowWrapper:
"""
Build lightweight row dataclasses for DB API... | brunns/brunns-row | src/brunns/row/rowwrapper.py | .py | 2e4b918c716ab9dc | 7.24 | 2 |
# crossword.adapters.ccxml_export_adapter
import re
import xml.etree.ElementTree as ET
from datetime import date
from crossword import Puzzle, Word
from crossword.ports.export_port import ExportError
class CcxmlExportAdapter:
"""
Exports a puzzle to Crossword Compiler XML format.
"""
def __init__(se... | philhanna/crossword | crossword/adapters/ccxml_export_adapter.py | .py | 7c8fbd80b4aef8a4 | 7.24 | 2 |
"""
Adapter that fetches word definitions from the free dictionaryapi.dev REST API.
API reference: https://dictionaryapi.dev/
The API returns a JSON array of entry objects for a given word. Each entry
may contain multiple "meanings", each of which groups a list of definitions
under a part-of-speech label. Because a... | philhanna/crossword | crossword/adapters/dictionary_api_definition_adapter.py | .py | 84efed4cce763dcf | 7.24 | 2 |
"""
FlatFileWordListAdapter - Flat-file word list implementation of the Word List Port
Loads an ASCII dictionary file into memory and provides word matching via regex
patterns. Words are bucketed by length so that callers who know the target
length avoid scanning the full dictionary.
"""
import re
from crossword.por... | philhanna/crossword | crossword/adapters/flat_file_word_list_adapter.py | .py | 4458c147664923b3 | 7.24 | 2 |
# crossword.adapters.puz_import_adapter
import puz
from crossword import Grid, Puzzle
from crossword.domain.word import Word
from crossword.ports.import_port import ImportPort, PuzzleImportError
class PuzImportAdapter(ImportPort):
"""
Imports a puzzle from AcrossLite binary format (.puz).
Uses the puzpy... | philhanna/crossword | crossword/adapters/puz_import_adapter.py | .py | 259a7b4697b88019 | 7.24 | 2 |
"""
Adapter that fetches word definitions from the Wikimedia REST API's
"definition" endpoint, which serves parsed Wiktionary content.
API reference: https://en.wiktionary.org/api/rest_v1/#/Page%20content/get_page_definition__title_
The API returns a JSON object keyed by language code (e.g. "en" for
English). Each va... | philhanna/crossword | crossword/adapters/wiktionary_api_definition_adapter.py | .py | 7a2fb82b6c570fb3 | 7.24 | 2 |
from datetime import date
from io import StringIO
from crossword import Puzzle
from crossword.ports.export_port import ExportError
class XdExportAdapter:
"""
Exports a puzzle to the .xd crossword format.
Format spec: https://github.com/century-arcade/xd/blob/master/doc/xd-format.md
Sections are sepa... | philhanna/crossword | crossword/adapters/xd_export_adapter.py | .py | 8e3a6b1ba9a011b5 | 7.24 | 2 |
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
class PartOfSpeech(Enum):
NOUN = "noun"
VERB = "verb"
ADJECTIVE = "adjective"
ADVERB = "adverb"
OTHER = "other"
@dataclass(frozen=True)
class Definition:
text: str
example: Optional[str] = None
@... | philhanna/crossword | crossword/domain/definition.py | .py | 73a5670d53de7a23 | 7.24 | 2 |
from collections import deque
from dataclasses import dataclass
@dataclass(frozen=True)
class FillPriorityItem:
"""Snapshot of one unfilled puzzle slot and its fill urgency metrics.
Attributes:
seq: The word's sequence number within its direction group.
direction: "across" or "down".
... | philhanna/crossword | crossword/domain/fill_priority.py | .py | 28a07827a14ddf4d | 7.24 | 2 |
from __future__ import annotations
import random
from collections import deque
from dataclasses import dataclass, field
from typing import List, Optional, Sequence, Tuple
from .grid import Grid
@dataclass
class GeneratorSettings:
# User-facing (Could be overridden from YAML)
BLACK_CELL_PERCENT_MIN: float = 0... | philhanna/crossword | crossword/domain/grid_generator.py | .py | 3375ef894e29c18d | 7.24 | 2 |
import string
ALPHABET = string.ascii_uppercase
def regexp(letters):
""" Forms a regular expression from a list of letters """
# Make a list of the integer indices of the letters
# pointing to the ALPHABET
iset = set()
for ch in letters:
x = ALPHABET.find(ch)
if x > -1:
... | philhanna/crossword | crossword/domain/letter_list.py | .py | 6c63f7f0d0c6a822 | 7.24 | 2 |
import re
import xml.etree.ElementTree as ET
from .grid import Grid
from .puzzle import Puzzle
class ToSVG:
""" Abstract base class for grid and puzzle to svg """
BOXSIZE = 32
def __init__(self, n, *args, **kwargs):
self.n = n
self.id = f"svg{n}x{n}"
self.boxsize = ToSVG.BOXSIZE... | philhanna/crossword | crossword/domain/to_svg.py | .py | 2a873aae9afc6626 | 7.24 | 2 |
from enum import Enum
from .numbered_cell import NumberedCell
class Word:
""" Abstract base class for Across and Down words """
# Enumerated values of word direction.
# Safer to use these, like Word.ACROSS and Word.DOWN, instead of string values
ACROSS = "A"
DOWN = "D"
def __init__(self, p... | philhanna/crossword | crossword/domain/word.py | .py | 8e384f47092ec4e4 | 7.24 | 2 |
def find_duplicate(candidate: str, existing_words) -> str | None:
"""Return the first word in existing_words that candidate duplicates
or is a near-duplicate of, or None if there's no conflict."""
for w in existing_words:
if is_near_duplicate(candidate, w):
return w
return None
def... | philhanna/crossword | crossword/domain/word_similarity.py | .py | dd1f4b1012380ef2 | 7.24 | 2 |
"""
HTTP Server main entry point - registers all routes and starts the server.
"""
import logging
from crossword.http_server.server import create_server, start_server
from crossword.wiring import make_app
# Import all handlers
from crossword.http_server.static_handlers import handle_get_index, handle_get_static, han... | philhanna/crossword | crossword/http_server/main.py | .py | 6e6a94b4144a3899 | 7.24 | 2 |
"""
HTTP Server - custom request handler with regex-based router.
"""
import logging
import re
import json
from http.server import BaseHTTPRequestHandler
from urllib.parse import parse_qs, unquote, urlparse
from io import BytesIO
CURRENT_USER = {"id": 1}
logger = logging.getLogger(__name__)
class Route:
"""Sing... | philhanna/crossword | crossword/http_server/server.py | .py | 02308520def175a8 | 7.24 | 2 |
"""
Definition Provider Port — dictionary/thesaurus lookup.
Implementations may query a local database, a third-party API (e.g. Merriam-Webster),
or any other source. The port is technology-agnostic.
"""
from abc import ABC, abstractmethod
from crossword.domain.definition import WordResult
class DefinitionNotFound... | philhanna/crossword | crossword/ports/definition_port.py | .py | fc2d9bd4bd401e37 | 7.24 | 2 |
# crossword.ports.grid_generator_port
from abc import ABC, abstractmethod
from crossword.domain.grid import Grid
class GridGeneratorPort(ABC):
@abstractmethod
def generate(self, n: int, spec: list[int] | None = None) -> Grid:
"""
Return a valid crossword grid of size n×n.
spec: optio... | philhanna/crossword | crossword/ports/grid_generator_port.py | .py | ae62363fc5917cf0 | 7.24 | 2 |
# crossword.ports.import_port
from abc import ABC, abstractmethod
from crossword import Puzzle
class PuzzleImportError(Exception):
"""Raised when a puzzle file cannot be parsed or is invalid."""
pass
class ImportPort(ABC):
"""Abstract interface for importing puzzles from external formats."""
@abstr... | philhanna/crossword | crossword/ports/import_port.py | .py | b6bca555cc436ea4 | 7.24 | 2 |
"""
Word List Port - Word dictionary lookup
This port defines the contract for word list operations.
Implementations may load the word list into memory, query a database, or fetch from an API.
"""
from abc import ABC, abstractmethod
class WordListPort(ABC):
"""
Abstract interface for word list operations (d... | philhanna/crossword | crossword/ports/word_list_port.py | .py | d34823f378db4a8c | 7.24 | 2 |
"""Per-exchange tracking, interval metrics, and time-bucket aggregation."""
from __future__ import annotations
from collections.abc import Callable, Iterable, Sequence
from dataclasses import dataclass
from decimal import Decimal
from statistics import median
from .depletion import (
DEFAULT_SPECS,
BandSpec,... | carlosplanchon/measurevolume | measurevolume/analyzer.py | .py | 63f7123121197cb2 | 7.39 | 5 |
"""Order book data model.
All prices and quantities are `Decimal`. The bundled dataset mixes two
encodings (one exchange serializes numbers as JSON strings, the other as
JSON numbers); parsing goes through ``json.loads(..., parse_float=Decimal)``
plus a defensive per-value conversion, so no binary float is ever
materi... | carlosplanchon/measurevolume | measurevolume/models.py | .py | 8bc994d65be8dd15 | 7.39 | 5 |
"""Streaming reader for order-book snapshot logs.
Accepts plain ``.csv`` (JSON Lines, one snapshot per line), ``.csv.xz`` and
``.csv.tar.xz``, decompressing on the fly with the standard library only;
the 545 MB bundled dataset never needs to be extracted to disk. Progress is
tracked by compressed bytes consumed, so it... | carlosplanchon/measurevolume | measurevolume/reader.py | .py | 9949005cf85fe6ce | 7.39 | 5 |
# -*- coding: utf-8 -*-
"""python -m flask_frame sync_apifox --token xxx --project-id xxx"""
import argparse
import importlib
import sys
def _create_app_by_convention():
"""
按约定自动创建 Flask 应用并生成 swagger spec。
检测顺序:
1. config 模块 → create_app(config)
2. module 包 → module.init_app(app)(如果存在)
3. c... | bistro-x/flask_frame | src/flask_frame/__main__.py | .py | 28194917e9d5dfab | 7.35 | 4 |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# 文本算法相关工具
import difflib
def compute_edit_distance(base_text: str, text: str) -> int:
"""
计算编辑距离(Levenshtein距离),用于衡量两个字符串的差异。
:param base_text: 原始文本
:param text: 比较文本
:return: 编辑距离
"""
leven_cost = 0
s = difflib.SequenceMatcher(None, base_... | bistro-x/flask_frame | src/flask_frame/algorithm/text.py | .py | 671e98f3d3dbb62a | 7.35 | 4 |
"""
装饰器模块。
提供两种装饰器:
- deprecated: 标记已废弃的函数,调用时发出 DeprecationWarning
- profile: 性能分析装饰器,超过阈值时生成调用报告文件
"""
import warnings
import functools
from pyinstrument import Profiler
__all__ = ["deprecated", "profile"]
def deprecated(func):
"""
标记函数已废弃的装饰器。调用时会发出 DeprecationWarning 提醒迁移。
Args:
func... | bistro-x/flask_frame | src/flask_frame/annotation/__init__.py | .py | c14b746b65c032ad | 7.35 | 4 |
"""
请求参数提取和代理转发模块。
get_request_param(): 统一合并 JSON、form、files、URL 参数。
proxy(): 代理请求到远程服务,支持 PostgREST 风格的 schema 前缀。
"""
from typing import Any
import flask
from flask import request
import requests
from .response import Response
def get_request_param() -> tuple[dict[str, Any], list[Any] | None]:
"""
提取当前请求的... | bistro-x/flask_frame | src/flask_frame/api/request.py | .py | 785b78eb3503e53c | 7.35 | 4 |
"""
响应封装模块。
提供统一的 API 响应结构:{result, code, message, data, create_time}。
Response.make_flask_response() 是标准的响应生成方法。
JsonResult 及相关函数已废弃,请使用 Response 类替代。
"""
import decimal
from datetime import date, time
from datetime import datetime as cdatetime
from http import HTTPStatus
from typing import Any
import flask
from flas... | bistro-x/flask_frame | src/flask_frame/api/response.py | .py | c1f88cb377934bcb | 7.35 | 4 |
"""
Flask 应用工厂模块。
create_app(config) 是框架的入口函数,负责:
- 创建 Flask 应用实例
- 加载配置
- 初始化插件
- 注册全局钩子(teardown_request、errorhandler)
- 添加默认路由(健康检查、日志下载、性能分析)
"""
import os
from http import HTTPStatus
from typing import Any
import flask
from flask import Flask, g, make_response, send_file
from flask import request
from p... | bistro-x/flask_frame | src/flask_frame/app.py | .py | bd1d0d56cc39f8af | 7.35 | 4 |
# -*- coding:utf-8 -*-
"""
API 请求日志插件。
通过 after_request 钩子记录非 GET 请求的调用信息。
提供 Celery 定时任务 api_log_clean 清理过期日志。
"""
from typing import TYPE_CHECKING
__all__ = ["init_app"]
if TYPE_CHECKING:
from flask import Flask
flask_app: Flask
else:
flask_app = None
def init_app(app: "Flask") -> None:
"""
初始... | bistro-x/flask_frame | src/flask_frame/extension/api_log/__init__.py | .py | 39ba93e4249e3bff | 7.35 | 4 |
"""
Celery 异步任务插件。
使用 REDIS_URL 同时作为 broker 和 backend(无需单独配置 CELERY_BROKER_URL)。
支持 Redis Sentinel 模式和 redbeat 定时任务调度。
提供 BaseTask 基类,自动管理数据库事务(成功提交、失败回滚)。
"""
from urllib.parse import urlparse
from typing import TYPE_CHECKING
from sqlalchemy.exc import InvalidRequestError, OperationalError
from celery import Celery,... | bistro-x/flask_frame | src/flask_frame/extension/celery.py | .py | e6d9d89420d10c74 | 7.35 | 4 |
"""
数据库插件(SQLAlchemy + 自动迁移)。
核心功能:
- 自动 URL 编码密码中的特殊字符
- 支持 GaussDB 版本兼容
- 启动时自动执行 SQL 迁移脚本(版本号通过文件名管理)
- 自动 reflect 数据库表结构到 db.Model
- 支持多 schema(逗号分隔)
"""
import json
import os
import random
import time
from itertools import zip_longest
import functools
from typing import TYPE_CHECKING
import sqlalchemy
f... | bistro-x/flask_frame | src/flask_frame/extension/database/__init__.py | .py | 2c8f483c207f582e | 7.35 | 4 |
"""
分布式锁插件:优先使用 Redis 分布式锁,未配置 Redis 时自动降级为本地文件锁。
降级策略:lock 模块独立初始化 Redis 客户端(与 redis 插件解耦),避免循环依赖。
使用方式:get_lock(name, timeout) 根据当前锁类型自动返回对应的锁实例。
"""
import os
import time
import platform
from typing import TYPE_CHECKING
from urllib.parse import urlparse
import redis
from redis.sentinel import Sentinel
from ..util.... | bistro-x/flask_frame | src/flask_frame/extension/lock.py | .py | c37f46b8abd47e66 | 7.35 | 4 |
# -*- coding: utf-8 -*-
"""
Loguru 日志系统插件。
将 Flask/Celery/Gunicorn 的日志统一重定向到 Loguru。
特性:
- 自动拦截标准 logging 并转发到 Loguru
- 支持文件日志轮转和保留策略
- 使用文件锁替代 enqueue 模式(兼容 gevent)
"""
import logging
import os
import sys
from loguru import logger
__all__ = ["init_app", "configure_celery_logging"]
def configure_celery_loggin... | bistro-x/flask_frame | src/flask_frame/extension/loguru/__init__.py | .py | fa8b88e2dc7d6a87 | 7.35 | 4 |
"""
MinIO 文件存储插件。
提供文件上传、下载、删除、存在性检查等功能。
支持两种上传方式:
- upload_file_to_minio: 从本地文件上传
- upload_bytes_to_minio: 从内存字节流上传
"""
import os
from io import BytesIO
from typing import TYPE_CHECKING
from urllib.parse import urljoin, urlparse
from minio import Minio
__all__ = [
"init_app",
"upload_file_to_minio",
... | bistro-x/flask_frame | src/flask_frame/extension/minio.py | .py | cd9077d2c6215cfd | 7.35 | 4 |
"""
权限校验插件。
通过 before_request 钩子在每次请求前执行鉴权流程:
1. 从 Authorization 头获取 token
2. 检查是否为 ADMIN_TOKEN(跳过校验)
3. 调用用户认证服务获取用户信息(依赖 USER_AUTH_URL 配置)
4. 校验用户是否有当前接口的访问权限
权限判定规则(按优先级):
- CHECK_API=False 时跳过所有权限校验
- 静态文件(/static/)不校验
- admin 用户拥有全部权限
- 客户端模式(有 client_id 无 id)通过
- 在 no_permissions 列表中的接口拒绝访问
-... | bistro-x/flask_frame | src/flask_frame/extension/permission.py | .py | a54082c46827c603 | 7.35 | 4 |
"""
PostgREST 代理插件。
将未匹配路由的请求转发到 PostgREST 服务(远程或本地数据库)。
支持三种模式:
- PROXY_LOCAL=True: 本地模式,直接查询数据库(绕过 PostgREST)
- PROXY_CUSTOM=True: 自定义模式,不自动拦截请求
- 默认: 远程模式,转发到 PROXY_SERVICE_URL
"""
import os
from typing import Any, TYPE_CHECKING
import requests
from flask import request
from ...api.response import Response
f... | bistro-x/flask_frame | src/flask_frame/extension/postgrest/__init__.py | .py | 4e85cb42cacbb0ab | 7.35 | 4 |
# url 转 sql 生成器,postgrest 格式
def generate_sql(
method: str, path: str, args: dict = None, data: dict = None, headers: dict = {}
):
"""http数据转换成SQL语句
Args:
method (str): http方法
path (str): 访问路径
args (dict, optional): url参数. Defaults to None.
data (dict, optional): body数据. D... | bistro-x/flask_frame | src/flask_frame/extension/postgrest/sql_generator.py | .py | 9b97e7c346e5e017 | 7.35 | 4 |
# -*- coding: utf-8 -*-
"""
OpenAPI 文档生成与 Apifox 同步工具。
两种模式:
1. 直接解析模式:从 Flask url_map + docstring 生成 OpenAPI 3.0(无需 flasgger)
2. Flasgger 模式:传入 flasgger 的 swagger_spec,提取完整元数据(参数类型、definitions)
使用示例:
from flask_frame.openapi import generate_openapi, sync_to_apifox
# 直接解析(无需 flasgger)
spec = generate_ope... | bistro-x/flask_frame | src/flask_frame/openapi.py | .py | 14214ca50cba929e | 7.35 | 4 |
"""
数据模型 Schema 模块。
BaseSchema: 基础 Schema,自动剔除空值字段并包含未知字段。
DateTimeField: 支持 datetime 对象直接反序列化的时间字段。
注意:BaseSchema 在 pre_load 阶段会自动剔除 None、''、[]、{} 值的字段,
这意味着这些值不会参与校验和反序列化。如果需要保留空值,请直接使用 marshmallow.Schema。
"""
from flask_marshmallow import Schema
from marshmallow import INCLUDE, fields, pre_load, post_load
from date... | bistro-x/flask_frame | src/flask_frame/schema/__init__.py | .py | e549224a65f7b927 | 7.35 | 4 |
# python 线程池 用于异步数据处理和批量的i/o操作
# python中批量的计算操作不适合用多线程
from concurrent.futures import ThreadPoolExecutor
class dk_thread_pool(object):
'工作线程池'
executor = ThreadPoolExecutor(max_workers=5) # 最大线程数设置为5
# func 线程执行的函数 ,*args 是func函数的接口, call_back是回调函数
def submit(self, func, call_back, *args):
#... | bistro-x/flask_frame | src/flask_frame/thread/dk_thread_pool.py | .py | 23ff6672b062db53 | 7.35 | 4 |
# 导入装饰器工具和线程锁
from functools import wraps
from threading import Lock
# 默认锁对象
default_lock = Lock()
# 锁对象字典,支持多对象锁
lock_list = {'default': Lock()}
def synchronized(func=None, obj=None):
"""
线程同步装饰器:可用于函数或对象方法的线程安全保护。
用法:
@synchronized
def foo():
...
@synchronized(obj=... | bistro-x/flask_frame | src/flask_frame/thread/my_synchronized.py | .py | 580d2b0c13106e1d | 7.35 | 4 |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import base64
import datetime
import hashlib
import os
import time
import zipfile
# 常用函数,时间格式,文件读写等。
from shutil import move, rmtree
# 获取当前日期,格式%Y-%m-%d %H:%M:%S
def get_curr_date():
# 返回当前时间的字符串表示
curr_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") #... | bistro-x/flask_frame | src/flask_frame/util/com_tool.py | .py | 4fc4e03e0c433580 | 7.35 | 4 |
from functools import wraps
def get_enum_values(enum):
"""
获取枚举类型的所有值
该函数接收一个枚举类型(例如Python的Enum类),并返回其所有成员的值列表。
适用于将枚举类型转换为前端可以使用的选项列表。
Args:
enum: 枚举类,例如通过enum.Enum定义的类
Returns:
list: 包含所有枚举值的列表
Example:
>>> from enum import Enum
>>> class Color(Enum):
... | bistro-x/flask_frame | src/flask_frame/util/db.py | .py | 9471ed64ab641470 | 7.35 | 4 |
from cryptography.fernet import Fernet
import base64
import hashlib
def _get_fernet_key(key: str = None) -> str:
"""
获取用于Fernet加解密的密钥
优先使用参数key,其次ENCRYPTION_KEY,最后PPRODUCT_KEY
自动将普通字符串转换为合法Fernet密钥
"""
from flask import current_app
if key is not None:
raw_key = key
else:
... | bistro-x/flask_frame | src/flask_frame/util/fernet_tool.py | .py | fb07abbed80d489c | 7.35 | 4 |
# -*- coding: utf-8 -*-
import os
import shutil
import time
import urllib
from contextlib import closing
from tenacity import retry, stop_after_attempt
from requests.utils import requote_uri
from flask import has_request_context, request
from flask_frame.annotation import deprecated
import base64
def retry_warning... | bistro-x/flask_frame | src/flask_frame/util/file.py | .py | ad0ee25a5bd5142b | 7.35 | 4 |
# -*- coding: UTF-8 -*-
import json
import uuid
from datetime import date, datetime
from decimal import Decimal
# 自定义JSON编码器,支持datetime、date、UUID、Decimal类型的序列化
class AppEncoder(json.JSONEncoder):
def default(self, obj):
"""
重写default方法,处理特殊类型的序列化
"""
if isinstance(obj, datetime):... | bistro-x/flask_frame | src/flask_frame/util/json.py | .py | 49e464118fe740cf | 7.35 | 4 |
"""
文件锁实现(跨平台),用于多进程/多线程场景下的互斥控制。
锁机制说明:
**Linux/macOS (POSIX 系统):**
使用 fcntl.flock() 系统调用,这是内核级的文件锁:
- LOCK_EX: 排他锁,同一时间只有一个进程能持有
- 锁绑定到文件描述符,进程退出时内核自动释放(防止死锁)
- 多进程安全:不同进程竞争同一锁文件时,内核保证只有一个成功
**Windows 系统:**
通过文件存在性模拟锁(非原子操作,存在短暂竞争窗口):
- acquire(): 创建锁文件表示持有锁
- release(): 删除锁文件表示释放锁
... | bistro-x/flask_frame | src/flask_frame/util/lock.py | .py | 1ead6df9d4a90a59 | 7.35 | 4 |
from sqlalchemy import inspect
def get_all_column_list(model):
"""
获取 SQLAlchemy 模型的所有字段列表
:param model: SQLAlchemy 模型类
:return: 字段对象列表
"""
return model.__table__.columns._all_columns
def add_filter(model, query, args):
"""
根据参数字典为 SQLAlchemy 查询对象添加过滤条件
:param model: SQLAlchemy 模... | bistro-x/flask_frame | src/flask_frame/util/model.py | .py | 9f9747faf082dfd9 | 7.35 | 4 |
import os
from rsa import common, transform, core, PrivateKey, PublicKey
from ..api.exception import ResourceError
# 加载公钥和私钥,异常时抛出业务错误
try:
current_path = os.path.abspath(__file__)
grader_father = os.path.abspath(os.path.dirname(current_path) + os.path.sep + "..")
# 加载公钥文件
pubkey = PublicKey.load_pkc... | bistro-x/flask_frame | src/flask_frame/util/rsa_tool.py | .py | c02e68a3f366eb8f | 7.35 | 4 |
# 原生sql分页查询
def mysql_page(db, sql, offset, limit, sort=None, db_schema=None):
"""
使用原生SQL进行分页查询。
:param db: 数据库连接对象
:param sql: 查询SQL语句(不带分页)
:param offset: 偏移量
:param limit: 每页数量
:param sort: 排序字段,'-'开头表示降序
:param db_schema: 可选,指定schema
:return: (查询结果, 总数)
"""
if not sort:
... | bistro-x/flask_frame | src/flask_frame/util/sql_tool.py | .py | c58f468129394517 | 7.35 | 4 |
"""Regenerate the recent-releases section of README.md."""
import json
import os
import pathlib
import re
from python_graphql_client import GraphqlClient
ROOT = pathlib.Path(__file__).parent.resolve()
CLIENT = GraphqlClient(endpoint="https://api.github.com/graphql")
TOKEN = os.environ.get("SOURCE_PUSH_TOKEN", "")
... | credfeto/credfeto | build_readme.py | .py | c1c8b93cd8e832fb | 7.24 | 2 |
from __future__ import annotations
import asyncio
import contextlib
import time
from typing import TYPE_CHECKING, TypeVar
from typing_extensions import Self
from .constants import ALL_SPECIES_AND_COLORS
from .errors import InvalidPairBytes
from .http import HTTPClient
__all__: tuple[str, ...] = ("ValidField",)
if ... | rneopets/dti.py | dti/state.py | .py | e3e4c33a5b1a4b05 | 7 | 0 |
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from urllib.parse import quote, urlencode, urljoin, urlparse
from dti.enums import LayerImageSize
if TYPE_CHECKING:
from .enums import PetPose
__all__: tuple[str, ...] = (
"build_layers_url",
"outfit_image_url",
"url_sanitizer"... | rneopets/dti.py | dti/utils.py | .py | 0a66cab921f1698a | 7 | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""":Mod: export
:Synopsis:
:Author:
servilla
costa
ide
:Created:
6/12/18
"""
import daiquiri
from metapype.model.node import Node
from xml.sax.saxutils import escape, unescape
logger = daiquiri.getLogger("export: " + __name__)
space = " "
def to_... | PASTAplus/metapype-eml | src/metapype/eml/export.py | .py | ae44e44acb1ea5c9 | 7.39 | 5 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:Mod: references
:Synopsis:
:Author:
servilla
:Created:
2/23/21
"""
import daiquiri
import metapype.eml.names as names
from metapype.model.node import Node
logger = daiquiri.getLogger(__name__)
def _register_ids(node: Node) -> dict:
id_register = di... | PASTAplus/metapype-eml | src/metapype/eml/references.py | .py | 908107a3d8dc1cd4 | 7.39 | 5 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""":Mod: validate
:Synopsis:
:Author:
servilla
costa
ide
:Created:
7/10/18
"""
import daiquiri
from metapype.eml import rule
from metapype.eml.exceptions import MetapypeRuleError, UnknownNodeError, ChildNotAllowedError
from metapype.eml.validation_error... | PASTAplus/metapype-eml | src/metapype/eml/validate.py | .py | d02a5505471b4cb1 | 7.39 | 5 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:Mod: metapype_io
:Synopsis:
Metapype import and export utilities
:Author:
servilla
:Created:
12/30/20
"""
import json
import re
import daiquiri
from lxml import etree
from xml.sax.saxutils import escape
from metapype.model.node import Node
logger = ... | PASTAplus/metapype-eml | src/metapype/model/metapype_io.py | .py | c5b95bc20ff53027 | 7.39 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.