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
""" Abstract base class for news sources with Pydantic models. """ from abc import ABC, abstractmethod from typing import List, Optional import requests from bs4 import BeautifulSoup import logging import html from pydantic import BaseModel, Field logger = logging.getLogger(__name__) class Article(BaseModel): ""...
thegauravgiri/newsapi
news_source.py
.py
2216dddb0f052a37
7.15
1
""" Template for creating a new news source scraper. To add a new news source: 1. Copy this file to sources/your_source_name.py 2. Rename the class to YourSourceName (use PascalCase) 3. Update source_name and language properties 4. Implement the scrape() method with your scraping logic 5. Add the import to sources/__i...
thegauravgiri/newsapi
sources/_template.py
.py
d5d654f948caedbc
7.15
1
#!/bin/env python3 # This script takes the space delimited file master_configuration_set and the # tsrc manifest, and joins them based on the scm_group column. You could think # of it as an sql join where scm_group = tsrc group. # # it outputs a yaml structure for every site/line in master_configuration set. # # cus...
VEuPathDB/websiteconf
make_yaml.py
.py
9acd66ad2316fb4e
7
0
"""Self-signed TLS certificate generation. The certificate is only *used* when a client negotiates TLS via ``AUTH TLS``; pyftpdlib merely advertises the capability unless enforcement is enabled (``--tls-control-required`` / ``--tls-data-required``). A self-signed certificate provides encryption but no authentication —...
janLo/ftp2ocr
src/ftp2ocr/certs.py
.py
b4b9fd0d0cb75f7c
7.15
1
"""OCR and PDF processing primitives. The heavy lifting is delegated to :mod:`ocrmypdf` (Python API, not a subprocess) and :mod:`pikepdf`. Duplex reordering interleaves the two halves of a scan so that a scanner that emits odd pages front-to-back and even pages back-to-front ends up in reading order. """ from __futur...
janLo/ftp2ocr
src/ftp2ocr/ocr.py
.py
1377ba922bf2787f
7.15
1
"""Data directory layout. Each FTP user gets a home directory below the configured base directory. The subdirectory a PDF is uploaded into decides what happens with it: - ``new_simplex``: run OCR on single-sided scans - ``new_duplex``: re-order interleaved duplex scans, then run OCR - ``new_raw``: copy through w...
janLo/ftp2ocr
src/ftp2ocr/paths.py
.py
2e6958916a0de6a6
7.15
1
"""The processing pipeline. An uploaded PDF is routed by the directory it landed in. Each file is handled by a single, self-contained worker task so the whole pipeline for that file (reorder → OCR → publish → backup) is atomic and easy to reason about, unlike the previous chain of ``apply_async`` callbacks. """ from ...
janLo/ftp2ocr
src/ftp2ocr/pipeline.py
.py
9f6f4348c64a40cc
7.15
1
"""Helper to wait until a file is completely written. The filesystem observer fires as soon as a file appears, which can be mid-transfer. Before processing a file from the ``observed`` directory we wait until its size stays constant between two probes. """ from __future__ import annotations import logging import tim...
janLo/ftp2ocr
src/ftp2ocr/stability.py
.py
7c41083d1e3d98d7
7.15
1
"""Shared test fixtures.""" from pathlib import Path import pikepdf import pytest def make_pdf(path: Path, pages: int) -> Path: """Create a minimal PDF where page *i* carries a ``/Marker`` of ``/P<i>``.""" pdf = pikepdf.Pdf.new() for i in range(pages): page = pikepdf.Dictionary( Type...
janLo/ftp2ocr
tests/conftest.py
.py
e57d9152f5d4fd56
7.65
1
"""Tests for TLS certificate generation.""" from pathlib import Path from cryptography import x509 from ftp2ocr.certs import ensure_cert, generate_selfsigned_cert def test_generate_selfsigned_cert_parses() -> None: cert_pem, key_pem = generate_selfsigned_cert("scanner.example.com", ["192.168.1.5"]) assert...
janLo/ftp2ocr
tests/test_certs.py
.py
1275466fe8d3a476
7.65
1
"""CLI smoke tests.""" from pathlib import Path from click.testing import CliRunner from ftp2ocr import __version__ from ftp2ocr.cli import main from ftp2ocr.users import verify_password def test_version() -> None: result = CliRunner().invoke(main, ["--version"]) assert result.exit_code == 0 assert __v...
janLo/ftp2ocr
tests/test_cli.py
.py
e7c234877e4eeeb0
7.65
1
# /// script # requires-python = ">=3.11,<3.15" # dependencies = [] # [tool.uv] # exclude-newer = "P7D" # /// """Propose or explicitly pin a reviewed APM release from GitHub.""" from __future__ import annotations import argparse import datetime as dt import json import re import urllib.request from pathlib import Pat...
aoirint/ffmpeg-docker
.agents/skills/apm-workflow/scripts/propose_bootstrap_update.py
.py
878feade115442de
7
0
"""Faithful interval-prevalence primitives from Alexe and Hammer (2006).""" from __future__ import annotations from collections.abc import Iterator, Sequence import numpy as np def upper_prevalence( distribution: np.ndarray, axes: Sequence[int] | None = None, ) -> np.ndarray: """Construct the paper's i...
GregoryMorse/LADClassifier
lad/_intervals.py
.py
5ad0c8f2e7212c1b
7
0
"""Prime-pattern generation from Chambon et al. (2019), PPC2. The paper builds the non-dominated solutions of a constraint matrix for each positive observation, then transforms every solution into a prime pattern. This implementation keeps that construction explicit and degree bounded. """ from __future__ import anno...
GregoryMorse/LADClassifier
lad/_prime_patterns.py
.py
325e1345f2c6c686
7
0
"""Degree-bound computations from Gardy, Lardeux, and Saubion (2022).""" from __future__ import annotations from dataclasses import dataclass from math import comb, log @dataclass(frozen=True) class DegreeProbability: degree: int log_probability: float def _alpha(projection_values: int, observations: int,...
GregoryMorse/LADClassifier
lad/_probabilistic.py
.py
2f8082d2e74e155e
7
0
""" ffmachine - shared ForgeFIRM hardware-machine glue for the Glowforge web-service clients: the gfhome one-shot homing runner and the gfcloud full-cloud daemon both drive the same hardware Machine with captures routed through forgectrl, honor the same shared-config identity overrides, and log the same way: through sy...
ScottW514/python3-gfhardware
forgefirm-app/ffmachine.py
.py
18441cc1fdfee9ce
7.3
3
""" (C) Copyright 2020 Scott Wiederhold, s.e.wiederhold@gmail.com https://community.openglow.org SPDX-License-Identifier: MIT """ import importlib.machinery import importlib.util import os import sysconfig from collections import namedtuple from enum import Enum, IntEnum from typing import Union # System Wide Value...
ScottW514/python3-gfhardware
gfhardware/_common.py
.py
2460856dacb7b9a3
7.3
3
""" (C) Copyright 2020 Scott Wiederhold, s.e.wiederhold@gmail.com https://community.openglow.org SPDX-License-Identifier: MIT """ import logging import os from typing import Union from gfhardware._common import * logger = logging.getLogger(LOGGER_NAME) class _CNC(object): # Externally-held exclusive /dev/glo...
ScottW514/python3-gfhardware
gfhardware/cnc.py
.py
069303fa633d6670
7.3
3
""" (C) Copyright 2020 Scott Wiederhold, s.e.wiederhold@gmail.com https://community.openglow.org SPDX-License-Identifier: MIT Based on python-evdev Copyright (c) 2012-2016 Georgi Valkov. All rights reserved. """ import logging import os import select from threading import Thread from typing import Callable from g...
ScottW514/python3-gfhardware
gfhardware/switches.py
.py
198af584bbaf6ccb
7.3
3
"""The per-job limits the cloud client hands the cooling engine: what a pulse header's envelope tags become as /cool/state parameters, what a sentinel or an absurd value becomes (nothing), and that the limits ride every report while a job is loaded and leave with it. """ import os import sys import types import unittes...
ScottW514/python3-gfhardware
tests/test_limits.py
.py
af73d5676ff423a6
7.8
3
""" Create and update sqlite databases with daily open source project stats """ import datetime import dateutil.parser import json import os import os.path import requests import sqlite3 def config_dir(): return os.environ.get( "PRISMS_CODE_STATS_DIR", os.path.join(os.environ["HOME"], ".prisms_code_stats...
prisms-center/code_stats
code_stats.py
.py
c2b2495ef5e8ea01
7
0
import code_stats as cs import datetime import numpy as np import pandas import pandas.plotting pandas.plotting.register_matplotlib_converters() def fromisoformat(d): if hasattr(datetime.date, "fromisoformat"): return datetime.date.fromisoformat(d) sd = datetime.datetime.strptime(d, "%Y-%m-%d") ...
prisms-center/code_stats
code_stats_data.py
.py
ddbea625c3224287
7
0
import copy from typing import TYPE_CHECKING from apps.bot.consts import PlatformEnum, RoleEnum from apps.bot.core.messages.attachments.attachment import Attachment from apps.bot.core.messages.attachments.audio import AudioAttachment from apps.bot.core.messages.attachments.document import DocumentAttachment from apps....
Xoma163/petrovich
apps/bot/core/event/event.py
.py
410742b0846dcb25
7.39
5
import base64 import copy from io import BytesIO from pathlib import Path from typing import TYPE_CHECKING from urllib3.exceptions import SSLError from apps.shared.decorators import retry from apps.shared.utils.downloader import Downloader if TYPE_CHECKING: from apps.bot.core.chat_actions import ChatActionEnum ...
Xoma163/petrovich
apps/bot/core/messages/attachments/attachment.py
.py
50ae4581e5e06905
7.39
5
import io from PIL import Image from apps.bot.core.messages.attachments.photo import PhotoAttachment class ThumbnailMixin: def __init__(self, **kwargs): super().__init__(**kwargs) self.thumbnail: PhotoAttachment | None = None self.thumbnail_url: str | None = None self.thumbnail_b...
Xoma163/petrovich
apps/bot/core/messages/attachments/mixins/thumbnail_mixin.py
.py
a9417f7651d4ba07
7.39
5
import re class Message: COMMAND_SYMBOLS = ["/"] SHORT_KEYS_SYMBOLS = ["-"] KEYS_SYMBOLS = ["—", "--"] SPACE_REGEX = r" |\n" def __init__(self, raw_str=None, _id=None): self._init(raw_str, _id) def _init(self, raw_str=None, _id=None): """ raw - исходная строка ...
Xoma163/petrovich
apps/bot/core/messages/message.py
.py
01e198275ca94d90
7.39
5
from apps.bot.core.messages.message import Message from petrovich.settings import env class TgMessage(Message): MENTION = env.str("TG_BOT_LOGIN") def __init__(self, raw_str=None, _id=None, entities=None, quote=None): self._mention_entities = [] self.has_mention = False self.entities =...
Xoma163/petrovich
apps/bot/core/messages/telegram/message.py
.py
28f5c1e14daaf3e9
7.39
5
from dataclasses import dataclass import discord from discord import app_commands from discord.ext import commands from dictator.settings import config from dictator.utilities import ( already_has_role, assign_role, get_playtime_hours, ) @dataclass class Role: """A structured object to hold role dat...
twohoursonelife/dictator
dictator/cogs/roles.py
.py
05ae4d2d756b2b28
7.3
3
import socket from datetime import date import discord import inflect from discord import app_commands from discord.ext import commands, tasks from dictator.settings import config from dictator.logger_config import logger from dictator.open_collective import ForecastOpenCollective class Stats(commands.Cog): def...
twohoursonelife/dictator
dictator/cogs/stats.py
.py
78b86747a18f177c
7.3
3
from html.parser import HTMLParser from urllib import parse class LinkFinder(HTMLParser): """Collects absolute href targets from <a> tags in one HTML page.""" def __init__(self, base_url, page_url): super().__init__() self.base_url = base_url self.page_url = page_url self.link...
joelstephen97/Crawler
link_finder.py
.py
3ad0cd91a7ac0488
7
0
import threading from urllib.request import urlopen, Request from link_finder import LinkFinder from domain import get_domain_name from general import create_project_dir, create_data_files, file_to_set, set_to_file class Spider: """Shared crawl state. All worker threads read and write the class attributes.""" ...
joelstephen97/Crawler
spider.py
.py
ffb86d9936cbf160
7
0
"""Configures the available backends.""" from __future__ import annotations import os import sys import warnings from concurrent.futures import Executor from concurrent.futures import Future from concurrent.futures import ProcessPoolExecutor from concurrent.futures import ThreadPoolExecutor from enum import Enum from...
pytask-dev/pytask-parallel
src/pytask_parallel/backends.py
.py
235071594177bb54
7.39
5
"""Configure pytask.""" from __future__ import annotations import os from typing import Any from pytask import hookimpl from pytask_parallel import execute from pytask_parallel import logging from pytask_parallel.backends import ParallelBackend @hookimpl def pytask_parse_config(config: dict[str, Any]) -> None: ...
pytask-dev/pytask-parallel
src/pytask_parallel/config.py
.py
5ac759b16bc2163e
7.39
5
"""Contains nodes for pytask-parallel.""" from __future__ import annotations import tempfile from pathlib import Path from typing import Any from _pytask.node_protocols import PNode from _pytask.node_protocols import PPathNode from attrs import define from pytask_parallel.typing import is_local_path @define(kw_on...
pytask-dev/pytask-parallel
src/pytask_parallel/nodes.py
.py
f3f8d70957b4333a
7.39
5
"""Contains functions related to typing.""" from pathlib import PosixPath from pathlib import WindowsPath from typing import Any from typing import NamedTuple from pytask import PTask from upath.implementations.local import FilePath __all__ = ["is_coiled_function", "is_local_path"] def is_coiled_function(task: PTa...
pytask-dev/pytask-parallel
src/pytask_parallel/typing.py
.py
fee5cea199f1e50c
7.39
5
"""Contains utility functions.""" from __future__ import annotations import importlib.util import inspect from functools import partial from pathlib import Path from typing import TYPE_CHECKING from typing import Any from typing import cast from pytask import NodeLoadError from pytask import PNode from pytask import...
pytask-dev/pytask-parallel
src/pytask_parallel/utils.py
.py
23cbc14d320cf0cf
7.39
5
from __future__ import annotations import sys from contextlib import contextmanager from typing import TYPE_CHECKING import pytest from click.testing import CliRunner from nbmake.pytest_items import NotebookItem from pytask import storage if TYPE_CHECKING: from collections.abc import Callable class SysPathsSna...
pytask-dev/pytask-parallel
tests/conftest.py
.py
ed49cf322334005c
7.89
5
"""Provides the means to compile a LaTeX document to a desired location. The function is mainly used in testing to validate the provided examples, but can also be used by users to compile their documents. """ from __future__ import annotations import os import shutil import subprocess from pathlib import Path from ...
pytask-dev/latex-dependency-scanner
src/latex_dependency_scanner/compile.py
.py
386299691ba12dd8
7.35
4
""" * Nome: Exemplos de Interface Grafica * Descrição: Ao final da aula, os alunos serão capazes de usar Interface Grafica. * Autor: Douglas Baptista de Godoy * Data de Criação: 2024-10-10 * Versão: 1.0 * * Dependências: * - Python 3.12.6 """ # Programa 13.1: Um primeiro programa com tkinter import tkinter a...
douglasbgodoy/Python
CODE/8-InterfaceGrafica/1-Exemplo_pratico.py
.py
22ed7f1220cb1e68
7.15
1
import numpy as np from ... import Globals from .ReadData import ReadData import os import RecarrayTools as RT def _DateStrToDateUT(s): ''' convert date on the format YYYY-MM-DDThh:mm:ss.sss to an integer date and a floating point time. ''' Y = np.array([np.int32(x[0:4]) for x in s]) M = np.array([np.int32(x[5:7...
mattkjames7/PyMess
PyMess/FIPS/ANN/ConvertData.py
.py
00f457a120fb405a
7.39
5
import numpy as np from .ReadData import ReadData from .. import Globals import DateTimeTools as TT def _AppendTimeFields(data,FileDate): """Add calendar fields and ensure that Unix time is current.""" fields = data.dtype.names or () missing = [name for name in ('Date','ut','unix') if name not in fields] if ('Da...
mattkjames7/PyMess
PyMess/FIPS/GetData.py
.py
fba4c0e0f3fcada5
7.39
5
import numpy as np from ..Tools.Gamma.Gamma import Gamma k_B = 1.38064852e-23 def KappaDist(v,n,T,K,m): ''' This function outputs the phase space density (PSD) of a Kappa distribution function given a temperature, density and velocity array. Inputs: v: Particle velocity array (m/s). n: Density (m^-3). T:...
mattkjames7/PyMess
PyMess/FIPS/KappaDist.py
.py
11196a8a3f2d0d9a
7.39
5
import numpy as np k_B = 1.38064852e-23 e = 1.6022e-19 def MaxwellBoltzmannDist(v,n,T,m): ''' This function outputs the phase space density (PSD) of a Maxwell- Boltzmann function given a temperature, density and velocity array. Inputs: v: Particle velocity array (m/s). n: Density (m^-3). T: Temperature (...
mattkjames7/PyMess
PyMess/FIPS/MaxwellBoltzmannDist.py
.py
0fd651eda3d86b29
7.39
5
from concurrent.futures import ProcessPoolExecutor, as_completed import multiprocessing import os import numpy as np from .FindPDSFiles import FindPDSFiles from ...Tools.ReadPDSFile import ReadPDSFile from .ReadPDS4 import ReadPDS4 import RecarrayTools as RT from ... import Globals from ...Tools.PDSFMTtodtype import P...
mattkjames7/PyMess
PyMess/FIPS/PDS/ConvertToBinary.py
.py
3eb880e3f5b4e2e5
7.39
5
import numpy as np from .FindPDSFiles import FindPDSFiles from .ReadPDSMAG import ReadPDSMAG from ... import Globals import RecarrayTools as RT import DateTimeTools as TT from scipy.interpolate import InterpolatedUnivariateSpline,interp1d import os from .. import MagGlobals from ...Pos.GetRegion import GetRegion def _...
mattkjames7/PyMess
PyMess/MAG/PDS/ConvertPDStoBinary.py
.py
910f1a334d102a33
7.39
5
"""Global pytest configuration for non‑E2E tests. Intentional separation: - Docker-dependent fixtures and the auto e2e marker live under `tests/e2e/conftest.py` on purpose to keep unit/integration runs lightweight and free from Docker imports. - Do not move that file here unless you also change its path-based scop...
hironow/dotfiles
emulator/tests/conftest.py
.py
52cb8dbe92bb298d
7.5
0
"""Bigtable CLI CRUD E2E. Flow - init instance/cluster (idempotent) - create table - put cell - get cell - list tables - delete table """ import pytest def _rand(n: int = 6) -> str: import random as _r import string as _s return "".join(_r.choices(_s.ascii_lowercase + _s.digits, k=n)) @pytest.mark.e2...
hironow/dotfiles
emulator/tests/e2e/test_bigtable_cli_crud_e2e.py
.py
7b5b0de0200577ec
7.5
0
"""CRUD happy‑path E2E for each CLI. Purpose - Exercise end‑to‑end create/read flows with minimal complexity. - Keep scenarios fast and deterministic; include cleanup after assertions. Scope - pgAdapter: CREATE → INSERT → SELECT → DROP - Neo4j: CREATE node → MATCH → DELETE - Elasticsearch: CREATE index → INDEX doc → ...
hironow/dotfiles
emulator/tests/e2e/test_cli_crud_e2e.py
.py
cdc25e1f263b1768
7.5
0
"""Feature‑focused E2E for each CLI. Purpose - Validate more advanced capabilities beyond CRUD: aggregates, relationships, filtered vector search, etc. Scope - pgAdapter: aggregation + ORDER BY - Neo4j: relationships + counting - Elasticsearch: aggregations - Qdrant: payload filter + vector search """ import pytes...
hironow/dotfiles
emulator/tests/e2e/test_cli_features_e2e.py
.py
78d647ad95af2c9d
7.5
0
"""Guardrail E2E tests (no CLI changes required). Goals - Catch regressions in constraint/mode enforcement and type handling. - Keep flows independent and self‑cleaning. """ import textwrap import pytest @pytest.mark.e2e def test_pgadapter_read_only_mode_or_skip( ensure_network, require_services, build_image, r...
hironow/dotfiles
emulator/tests/e2e/test_cli_guardrails_e2e.py
.py
1480b7070d76086b
7.5
0
"""Transactional / atomic flows E2E. Focus - pgAdapter: explicit BEGIN/ROLLBACK/COMMIT semantics - Neo4j: attempt explicit BEGIN/ROLLBACK/COMMIT (skip if unsupported by driver path) - Elasticsearch: index with refresh=wait_for to emulate commit‑like visibility - Qdrant: upsert then delete to validate atomic cleanup ""...
hironow/dotfiles
emulator/tests/e2e/test_cli_transactions_e2e.py
.py
e27f5648ae67364b
7.5
0
"""pgAdapter concurrent update conflict (best‑effort) E2E. We attempt to orchestrate two concurrent sessions that update the same row. This relies on `pg_sleep()` to hold a transaction open. If `pg_sleep` is not available in the pgAdapter build, the test skips. """ import textwrap import time import pytest def _env...
hironow/dotfiles
emulator/tests/e2e/test_pgadapter_tx_concurrency_e2e.py
.py
59a1a80d719676f3
7.5
0
"""E2E smoke for the PostgreSQL 18 CLI. Verifies the CLI starts, connects over the Docker network, responds to help, and can run simple SQL including uuidv7() and a generated column. """ import pytest @pytest.mark.e2e def test_postgres_cli_help_and_exit( ensure_network, require_services, build_image, run_shell ...
hironow/dotfiles
emulator/tests/e2e/test_postgres_cli_e2e.py
.py
6d9bfedf89dbcac1
7.5
0
"""E2E for PostgreSQL 18 extensions via the Go CLI. These tests try pgvector and PostGIS through the interactive CLI. If the extensions are not available in the image, they skip gracefully. """ import re import pytest def _should_skip_for_missing_extension(out: str, name: str) -> bool: s = out.lower() name ...
hironow/dotfiles
emulator/tests/e2e/test_postgres_cli_extensions_e2e.py
.py
d0d4116781f16fe1
7.5
0
import pytest import docker from tests.utils.helpers import skip_unless_container_running @pytest.fixture(autouse=True) def _require_bigtable(): skip_unless_container_running("bigtable-emulator") def test_bigtable_container_starts(): """Test that the Bigtable emulator container starts and is healthy.""" ...
hironow/dotfiles
emulator/tests/test_bigtable_emulator.py
.py
d37a6eae0e272cc3
7.5
0
"""Helper functions for tests using the Result type.""" import asyncio import socket import time import docker from aiohttp import ClientSession from docker.errors import NotFound from docker.models.containers import Container from tests.utils.result import Error, Ok, Result def get_container(client: docker.Dock...
hironow/dotfiles
emulator/tests/utils/helpers.py
.py
6b6d4df913cb26d0
7.5
0
"""Module containing definitions for the result type. It works like Rust's Result type. """ from dataclasses import dataclass from typing import Generic, TypeVar _T = TypeVar("_T") _E = TypeVar("_E") @dataclass(frozen=True) class Ok(Generic[_T]): # noqa: UP046 value: _T def __repr__(self): return...
hironow/dotfiles
emulator/tests/utils/result.py
.py
4e27bf9873879e0c
7.5
0
#!/usr/bin/env python3 """Scan deployed agent-home instruction files for dead file references. Verification gate for the distributed agent instruction set: after `just sync-agents`, every file reference inside the deployed base/overlay/ spokes must resolve. Per agent home this checks that: 1. absolute `/Users/...`, `...
hironow/dotfiles
scripts/check_agent_home_refs.py
.py
7a49ce8a6f0bb291
7
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ module name: event_manager Author: CJ Lin Command line wrapper of event-manager. """ import os import pathlib import subprocess import sys import click from . import event_manager CONF_PATH = pathlib.Path(sys.prefix, "etc", "event-manager.yml") CONF_PATH.parent.mk...
cj-lin/event-manager
event_manager/__init__.py
.py
2d6cf614e2ccea28
7.15
1
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Filename: cron Author: CJ Lin """ import asyncio import datetime import dateutil.rrule import sortedcontainers class DefaultSortedDict(sortedcontainers.SortedDict): def __missing__(self, key): self[key] = [] return self[key] class crule: d...
cj-lin/event-manager
event_manager/cron.py
.py
d2b4e3d44420b6a2
7.15
1
#!/usr/bin/env python # __main__.py import click from multitool import APP, MULTITOOL_LOG_FILE, MULTITOOL_PLUGINS_DIRECTORY from multitool import __version__ as version from multitool.bootstrap.commands import bootstrap from multitool.cls import AliasedGroup from multitool.exceptions import wrap_with_exception_handli...
mdelotavo/multitool
multitool/__main__.py
.py
cfe3c8fd359f5be0
7.3
3
from selenium import webdriver from selenium.webdriver.chrome.options import Options from . import Base class Chrome(Base): def get_options(self): return Options() def boot_driver(self): self.log.debug("chrome: %s", self.browser_args) return webdriver.Chrome(**self.browser_args) ...
wtnb75/selenible
selenible/drivers/chrome.py
.py
470c4a18d6278300
7.3
3
from selenium import webdriver from selenium.webdriver.firefox.options import Options from . import Base class Firefox(Base): def get_options(self): return Options() def boot_driver(self): return webdriver.Firefox(**self.browser_args) def do_install_addon(self, params): """ ...
wtnb75/selenible
selenible/drivers/firefox.py
.py
a766232ed3af6434
7.3
3
import math import time import urllib.parse import yaml from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.alert import Alert from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.select import Select from selenium.webdriver.support.ui i...
wtnb75/selenible
selenible/modules/browser.py
.py
df6f58768a2d23e3
7.3
3
import re import yaml update_style_schema = yaml.safe_load(""" allOf: - type: object - "$ref": "#/definitions/common/locator" """) def Base_update_style(self, param): """ - name: red background update_style: id: element1 "background-color": red - name: dismiss heading upd...
wtnb75/selenible
selenible/modules/content.py
.py
5f9440204b7183b5
7.3
3
import json import logging.config import tempfile import time import urllib.parse from contextlib import ExitStack from subprocess import DEVNULL import requests import toml import yaml from lxml import etree progn_schema = yaml.safe_load(""" type: array items: {type: object} """) def Base_progn(self, param): "...
wtnb75/selenible
selenible/modules/ctrl.py
.py
4a95e21bd573b6d2
7.3
3
import math import os import tarfile import time import zipfile import yaml from PIL import ( Image, ImageChops, ImageColor, ImageDraw, ImageEnhance, ImageFilter, ImageFont, ImageOps, ) def inout_fname(param): input_filename = param.get("input") output_filename = param.get("ou...
wtnb75/selenible
selenible/modules/imageproc.py
.py
9d843d0baa86d1d4
7.3
3
import logging from pathlib import Path ######################### # CORE CONFIGURATION ######################### FINAL_MARKING = False # final marking, no more resubmissions PROJECT_NO = 3 TOTAL_POINTS = 25 # as per spec weighting of points (sum of all question points, Q1+...+Qn) NO_COMMITS_EXPECTED = 11 # very ...
ssardina-teaching/git-teaching-tools
feedback_p3.py
.py
e9f569dda7810052
7.15
1
#!/usr/bin/env python3 """ Generate a PDF of attendance codes for printing and cutting. Reads a text file with one code per line and produces a PDF where each code is displayed in a box, laid out in 3 columns × 18 rows per page. Print the PDF and cut out each box to hand to students. This can be used with EdStem Atte...
ssardina-teaching/git-teaching-tools
gen_code_page.py
.py
9b0590aa65e2de05
7.15
1
#!/usr/bin/env python3 """ Script to generate a markdown table with student answers for each question. Takes a CSV file and a student number as input. Usage: python generate_student_answers.py <csv_file> <student_number> """ import csv from pathlib import Path import sys import argparse import regex as re try: im...
ssardina-teaching/git-teaching-tools
generate-report-answers/generate_student_report.py
.py
e16edfde81a92d38
7.15
1
""" Download files from Google drive folder using the Google Drive API: https://developers.google.com/drive/api/guides/about-sdk Uses PyDrive2 for high-level access to the drive: https://docs.iterative.ai/PyDrive2/ To change credentials: - Go to the Google API Access Pane (https://console.developers.google.com/ap...
ssardina-teaching/git-teaching-tools
gg_drive_download.py
.py
bdd220774c2a43bf
7.15
1
""" Get or update the list of issue labels in a repository * Uses PyGithub (https://github.com/PyGithub/PyGithub) as API to GitHub: * PyGithub documentation: https://pygithub.readthedocs.io/en/latest/introduction.html * GitHub REST API: https://docs.github.com/en/rest * GitHub GraphQL API: https://docs.github.com/en/g...
ssardina-teaching/git-teaching-tools
gh_issue_labels.py
.py
32b2c6821a4ff5fd
7.15
1
import csv import json import os import shutil import git # get the TIMEZONE to be used - ZoneInfo requires Python 3.9+ from datetime import datetime, timezone from zoneinfo import ZoneInfo TIMEZONE_STR = "Australia/Melbourne" # https://en.wikipedia.org/wiki/List_of_tz_database_time_zones DATE_FORMAT = "%-d/%-m/%Y %...
ssardina-teaching/git-teaching-tools
util.py
.py
d0185f969a722c57
7.15
1
""" Sensor module """ import datetime import json import logging from statistics import median from time import sleep from bme280 import BME280 from enviroplus import gas from paho.mqtt.client import Client as MqttClient from pms5003 import PMS5003, ReadTimeoutError try: from smbus2 import SMBus except ImportErro...
hellqvio86/enviroplus-sensors-to-mqtt
src/enviroplussensorstomqtt/sensor.py
.py
d136cff98aa6c75d
7
0
import os import re import subprocess import sys import logging import yaml import pwd from jinja2 import FileSystemLoader, Environment, TemplateNotFound _VAR_RE = r"\$\{(\w+)\}" def expand_env(config): """Expand ${VAR} references in every string value of the parsed config. Expansion runs after YAML parsin...
alekc/samba-docker
rootfs/etc/config-gen/config.py
.py
b530689c53f77b69
7
0
"""Tests for ${VAR} expansion in the config generator. Runnable either with pytest or directly: python3 tests/test_expand_env.py """ import importlib.util import os import pathlib import sys import yaml _SRC = pathlib.Path(__file__).resolve().parents[1] / "rootfs/etc/config-gen/config.py" _spec = importlib.util.spec...
alekc/samba-docker
tests/test_expand_env.py
.py
e3e2a813b26e27bf
7.5
0
from .utils import str_to_quoted from .validator import validate_uri import base64 def encoding_convert(source, params: str) -> str: """ Encodes the property :param source: The source :type source: str :param params: The parameters :type params: str """ if "...
brookite/pyvcard
pyvcard/converters.py
.py
232dfb386ac6b636
7.24
2
import enum class _STATE(enum.Enum): BEGIN = 0 END = 1 class VERSION(enum.Enum): """Enum of vCard versions. Supported 2.1-4.0 versions""" @staticmethod def get(version): """ Returns version enum """ if version == "2.1": return VERSION.V2_1 elif...
brookite/pyvcard
pyvcard/enums.py
.py
9e2699b2e4edeb6b
7.24
2
def get_string(obj) -> str: """ Gets the string from file or str. Utility method """ if isinstance(obj, str): return obj elif hasattr(obj, "close"): if not obj.closed: s = obj.read() obj.close() obj = s return obj else: ...
brookite/pyvcard
pyvcard/parsers.py
.py
311ae8df78320aa3
7.24
2
import io from csv import DictWriter, DictReader import pyvcard.vobject from pyvcard.converters import AbstractConverter from pyvcard.parsers import AbstractParser, get_string import pyvcard class csv_Converter(AbstractConverter): """ This class describes a vCard object to CSV converter. """ def __i...
brookite/pyvcard
pyvcard/sources/csv_source.py
.py
0fae97106b221f36
7.24
2
import json import pyvcard.vobject from pyvcard.converters import AbstractConverter, determine_type, encoding_convert from pyvcard.parsers import AbstractParser class jCard_Parser(AbstractParser): """ This class describes a JSON to vCard object parser jCard (RFC 7095) """ class jCard_ValidationEr...
brookite/pyvcard
pyvcard/sources/jcard.py
.py
fae66fe0adfa9794
7.24
2
import base64 import quopri import re import warnings from typing import Union, List, Optional from .exceptions import vCardFormatError quopri_warning = True def escape(string: str, characters: List[str] = (";", ",", "\n", "\r", ":")) -> str: """ Escapes listed characters with a character \\ :param ...
brookite/pyvcard
pyvcard/utils.py
.py
ddc4157f5917741f
7.24
2
import os from pyvcard.migrator import _VersionMigrator from pyvcard.vobject import parse """ Used official vCard standards RFC 2426 - vCard 3.0 RFC 6350 - vCard 4.0 RFC 6351 - xCard RFC 7095 - jCard http://microformats.org/wiki/hcard - hCard """ def openfile(file: os.PathLike, mode="r", encoding=None, buffering=-...
brookite/pyvcard
pyvcard/vcard.py
.py
898aab714381e087
7.24
2
from typing import Union from pyvcard.parsers import AbstractParser from pyvcard.vobject.tools import vCard_Converter, _vCard_Builder from pyvcard.vobject.parsing import vCard_Parser from pyvcard.vobject.structures import vCard, vCard_entry, is_vcard, is_vcard_property, \ parse_name_property, validate_vcards from ...
brookite/pyvcard
pyvcard/vobject/__init__.py
.py
7394085c0e9a201c
7.24
2
import re from typing import Optional from pyvcard.regex import VCARD_BORDERS, CONTENTLINE, PARAM, PARAM_21, CONTENTLINE_21 from pyvcard.utils import split_noescape, unescape, _unfold_lines, remove_junk_symbols from pyvcard.enums import _STATE from pyvcard.exceptions import vCardFormatError, vCardValidationError impo...
brookite/pyvcard
pyvcard/vobject/parsing.py
.py
2e43e326051b9f17
7.24
2
from typing import Union, List, Dict, Optional import pyvcard.vobject.structures as structures import pyvcard.vobject.containers as containers import pyvcard.sources.jcard import pyvcard.sources.xcard import pyvcard.sources.csv_source import pyvcard.sources.hcard class vCard_Converter: """ This class descri...
brookite/pyvcard
pyvcard/vobject/tools.py
.py
622ed2b1bc1ac435
7.24
2
#!/usr/bin/env python3 """ Fetch GitHub contribution data from the public contributions page. No API token required - scrapes the public HTML. """ import json from datetime import datetime, timedelta from pathlib import Path import requests from bs4 import BeautifulSoup USERNAME = "Zerofour04" def fetch_contributi...
Zerofour04/Zerofour04
scripts/fetch_contributions.py
.py
a536fbd87c653500
7.24
2
#!/usr/bin/env python3 """ Generate macOS terminal-style ASCII portrait SVG with typing animation. Based on avivashishta's design. """ from pathlib import Path from PIL import Image, ImageEnhance # ASCII density ramp: bright (sparse) -> dark (dense) RAMP = " .`:-=+*cs#%@" # Grid dimensions COLS = 100 ROWS = 53 # SV...
Zerofour04/Zerofour04
scripts/make_ascii_svg.py
.py
964b6e7cd5020009
7.24
2
#!/usr/bin/env python3 """ Generate macOS terminal-style neofetch info card SVG. Based on avivashishta's design. """ from pathlib import Path import requests # User info - customize these! USERNAME = "zerofour04" GITHUB_USERNAME = "Zerofour04" def fetch_github_stats() -> dict: """Fetch stars and followers from ...
Zerofour04/Zerofour04
scripts/make_info_card.py
.py
f6ce524a81f5cade
7.24
2
#!/usr/bin/env python3 """ Render the contribution heatmap as an animated SVG. Uses a diagonal reveal animation that plays once. """ import json from datetime import datetime from pathlib import Path # GitHub-style color palette (5 levels) PALETTE = [ "#161b22", # Level 0 - no contributions "#0e4429", # Lev...
Zerofour04/Zerofour04
scripts/render_heatmap_svg.py
.py
722b3dcd384cd15a
7.24
2
import socket import sys import time import cv2 import matplotlib.patheffects as path_effects import matplotlib.pyplot as plt from matplotlib.widgets import Button import numpy as np import serial import serial.tools.list_ports # --- Configuration --- BAUD_RATE = 115200 ROWS, COLS = 8, 8 NUM_PIXELS = ROWS * COLS BEGI...
araobp/arduino-infrared-array-sensor
python/earth_gesture_controller.py
.py
ad950aa5e551b3e2
7.39
5
from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.contrib.auth.models import AbstractUser from django.utils.translation import gettext_lazy as _ from django.utils import timezone # Create your mode...
panda-zxs/hula
hula/account/models.py
.py
c9309e303e3e132e
7.15
1
# Copyright © Michal Čihař <michal@weblate.org> # # SPDX-License-Identifier: MIT """Schema loading helpers.""" import json from pathlib import Path SCHEMA_BASE = Path(__file__).resolve().parent.joinpath("schemas") SCHEMA_CACHE: dict[str, dict] = {} def get_path(name: str) -> Path: """Build filename for a sche...
WeblateOrg/weblate_schemas
weblate_schemas/loader.py
.py
d4d76e945d6f8876
7.24
2
# Copyright © Michal Čihař <michal@weblate.org> # # SPDX-License-Identifier: MIT """Message class implementation for Weblate Fedora Messaging.""" from __future__ import annotations from typing import TYPE_CHECKING from fedora_messaging import message from . import load_schema if TYPE_CHECKING: from datetime i...
WeblateOrg/weblate_schemas
weblate_schemas/messages.py
.py
22bcdfd5431ee1a7
7.24
2
# Copyright © Michal Čihař <michal@weblate.org> # # SPDX-License-Identifier: MIT """Test schemas loader.""" from weblate_schemas import get_path, load_schema def test_filename() -> None: """Test filename calculation.""" filename = get_path("weblate-memory.schema.json") assert "weblate-memory.schema.json...
WeblateOrg/weblate_schemas
weblate_schemas/tests/test_loader.py
.py
ba9d153dfe94084f
7.24
2
# Copyright © Michal Čihař <michal@weblate.org> # # SPDX-License-Identifier: MIT """Test the Message classes.""" from weblate_schemas.messages import WeblateV1Message from weblate_schemas.tests.test_valid import ( body_with_context, merge_body, new_string_body, new_translation_body, ) def test_base_...
WeblateOrg/weblate_schemas
weblate_schemas/tests/test_message.py
.py
d38b636504d5ce6e
7.74
2
#!/usr/bin/env python3 """Release Iosevka COPR packages: update version, commit, push, and submit builds.""" import argparse import re import subprocess from datetime import date, datetime from pathlib import Path from copr.v3 import Client from copr.v3.exceptions import CoprRequestException AUTHOR = "Peter Wu" ...
peterwu/copr-iosevka
build.py
.py
77b70d5e805ddeff
7.35
4
from pathlib import Path import json from amcli.utils.models import collect_models from amcli.utils.dependencies import ( collect_dependencies, collect_all_dependencies, build_reverse_dependencies, ) from amcli.utils.categories import collect_field_categories from amcli.utils.nested import collect_nested ...
ono-kojiro/learning_python
amcli/src/amcli/commands/generate_schema/run.py
.py
7ad4f2b7aefa6f6e
7
0
# file: src/amcli/commands/generate_testscript/main.py import os import json from .add import run_add from .get import run_get from .update import run_update from .delete import run_delete def load_schema(schema_path): with open(schema_path, "r", encoding="utf-8") as f: return json.load(f) def load_ref_...
ono-kojiro/learning_python
amcli/src/amcli/commands/generate_testscript/main.py
.py
eeac31c9149178e6
7.5
0
from pathlib import Path import yaml import sys import argparse from amcli.utils.settings_editor import ( replace_installed_apps, extract_installed_apps_list, ) def export_installed_apps(settings_path: Path, out_yaml: Path): """settings.py の INSTALLED_APPS を YAML に書き出す""" apps = extract_installed_apps_...
ono-kojiro/learning_python
amcli/src/amcli/commands/installapp.py
.py
211c4aa58338919b
7
0