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 |
|---|---|---|---|---|---|---|
"""Jinja2 filters for miscelleaneous use."""
from __future__ import annotations
from functools import reduce
from typing import TYPE_CHECKING
from typing import Any
from typing import TypeVar
from jinja2 import Undefined
from jinja2 import UndefinedError
from jinja2 import pass_environment
from jinja2.filters import... | copier-org/jinja2-copier-extension | src/jinja2_copier_extension/_filters/utils.py | .py | 8267e7a9f855fdb9 | 7.42 | 6 |
"""Tests for Base64 encoding/decoding filters."""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from tests.utils import render
if TYPE_CHECKING:
from jinja2 import Environment
@pytest.mark.parametrize(
"filter_call",
[
"b64decode",
"b64decode('utf-8... | copier-org/jinja2-copier-extension | tests/filters/test_base64.py | .py | 43a212eefa9dc0a2 | 7.92 | 6 |
"""Tests for date/time filters."""
from __future__ import annotations
import platform
from datetime import datetime
from typing import TYPE_CHECKING
from zoneinfo import ZoneInfo
import pytest
from time_machine import travel
from tests.utils import render
if TYPE_CHECKING:
from jinja2 import Environment
@tra... | copier-org/jinja2-copier-extension | tests/filters/test_datetime.py | .py | e6b2188902edd0dc | 7.92 | 6 |
"""Tests for JSON (de)serialization filters."""
from __future__ import annotations
from typing import TYPE_CHECKING
from tests.utils import render
if TYPE_CHECKING:
from jinja2 import Environment
def test_from_json(env: Environment) -> None:
"""Test the `from_json` filter with default settings."""
ass... | copier-org/jinja2-copier-extension | tests/filters/test_json.py | .py | 1873b3dad2760ca6 | 7.92 | 6 |
"""Tests for filesystem path filters."""
from __future__ import annotations
import platform
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from pychoir import MatchesRegex
from tests.utils import build_file_tree
from tests.utils import cd
from tests.utils import render
if TYPE_CHECKING:
... | copier-org/jinja2-copier-extension | tests/filters/test_path.py | .py | 14318c2f413f4b4f | 7.92 | 6 |
"""Tests for random functions filters."""
from __future__ import annotations
import re
from typing import TYPE_CHECKING
import pytest
from tests.utils import render
if TYPE_CHECKING:
from jinja2 import Environment
def test_shuffle(env: Environment) -> None:
"""Test shuffling a sequence of elements."""
... | copier-org/jinja2-copier-extension | tests/filters/test_random.py | .py | de039c0fa24b54f0 | 7.92 | 6 |
"""Tests for regular expression filters."""
from __future__ import annotations
import re
from typing import TYPE_CHECKING
from typing import Literal
import pytest
from tests.utils import render
if TYPE_CHECKING:
from jinja2 import Environment
def test_regex_escape(env: Environment) -> None:
"""Test escap... | copier-org/jinja2-copier-extension | tests/filters/test_regex.py | .py | 9b043677a180f675 | 7.92 | 6 |
"""Tests for miscelleaneous filters."""
from __future__ import annotations
import re
from typing import TYPE_CHECKING
from typing import Any
import pytest
from jinja2 import UndefinedError
from tests.utils import render
if TYPE_CHECKING:
from collections.abc import Sequence
from jinja2 import Environment
... | copier-org/jinja2-copier-extension | tests/filters/test_utils.py | .py | fc469d5c60adf4e4 | 7.92 | 6 |
"""Tests for YAML (de)serialization filters."""
from __future__ import annotations
from typing import TYPE_CHECKING
from tests.utils import render
if TYPE_CHECKING:
from jinja2 import Environment
def test_from_yaml(env: Environment) -> None:
"""Test the `from_yaml` filter with default settings."""
res... | copier-org/jinja2-copier-extension | tests/filters/test_yaml.py | .py | e9e78b7c0c6c8407 | 7.92 | 6 |
from __future__ import annotations
import os
from contextlib import contextmanager
from pathlib import Path
from textwrap import dedent
from typing import TYPE_CHECKING
from typing import Any
if TYPE_CHECKING:
from collections.abc import Iterator
from collections.abc import Mapping
from jinja2 import Env... | copier-org/jinja2-copier-extension | tests/utils.py | .py | 47d21f9e80fc628c | 7.92 | 6 |
"""
title: Llama Index Ollama Pipeline
author: Alexander Wolff
date: 2024-08-30
version: 0.1
license: MIT
description: A pipeline for retrieving relevant information from a knowledge base using the Llama Index library with Ollama embeddings.
requirements: llama-index-core, llama-index-embeddings-ollama, llama-index-llm... | wolffaxn/ollama-docker | src/rag/ollama-llamaindex-pipeline.py | .py | 194c65f922d23c14 | 7.52 | 10 |
"""Timeweb Cloud DNS Authenticator for Certbot."""
from __future__ import annotations
import collections
import functools
import logging
from collections.abc import Callable
from certbot import errors
from certbot.plugins import dns_common
from certbot_dns_timeweb.client import TimewebClient
logger = logging.getLo... | artrey/certbot-dns-timeweb | certbot_dns_timeweb/authenticator.py | .py | 2799668ad96c432b | 7.66 | 20 |
"""Tests for the DNS-01 challenge handling."""
from unittest import mock
import pytest
from certbot import errors
from certbot_dns_timeweb.authenticator import DEFAULT_PROPAGATION_SECONDS, Authenticator
def test_more_info_is_a_string(authenticator):
assert isinstance(authenticator.more_info(), str)
def test_... | artrey/certbot-dns-timeweb | tests/test_authenticator.py | .py | e1c7f12b2193236f | 8.16 | 20 |
import os
import tempfile
import GeoAnalyze
import matplotlib.pyplot
import pytest
@pytest.fixture(scope='class')
def visual():
yield GeoAnalyze.Visual()
@pytest.fixture
def message():
output = {
'error_figure': 'Input figure file extension is not supported.'
}
return output
def test_fu... | debpal/GeoAnalyze | tests/test_visual.py | .py | 31d320d2625f277f | 7.14 | 18 |
"""End-to-end smoke test for the LoRiS Streamlit app.
The app reads several required environment variables (BACKEND_URL, PAGE_ICON, …)
with no defaults and, on a full run, calls a backend and loads remote QALD data.
We therefore exercise the built-in DRY_RUN path: it executes the whole startup
sequence (imports, confi... | WSE-research/LoRiS-LLM-generated-Representations-of-SPARQL-queries | tests/e2e/test_app_boots.py | .py | 4f429752ba80c96f | 7.98 | 8 |
from PIL import Image
import requests
import logging
import os
import re
import base64
from io import BytesIO
import markdown
import random
def include_css(st, filenames):
content = ""
for filename in filenames:
with open(filename) as f:
content += f.read()
st.markdown(f"<style>{content... | WSE-research/LoRiS-LLM-generated-Representations-of-SPARQL-queries | util.py | .py | d2fe5f1d38b2d99c | 7.48 | 8 |
import json5
import tkinter as tk
from tkinter import filedialog
def _stages(item_name: str, full_name: str):
stage1 = {
"name": f"{full_name} stage1",
"inherit_codes": True,
"img": f"/images/items/{item_name}.png",
# "img_mods": "",
# "disabled_img": "",
# "disable... | StripesOO7/poptracker-pack-builder | pythonProject/item_json.py | .py | 861b7cd08f97b1eb | 7.62 | 16 |
import json5
import random
import tkinter as tk
from tkinter import filedialog
from item_json import _item_consumable_preset
def _maps_json(map_name: str):
"""
returns a JSON-compatible dict containing the basic option for a single map definition in poptracker
:param str map_name: Name of the Region to cr... | StripesOO7/poptracker-pack-builder | pythonProject/location_json.py | .py | 32816f4ccb64ba71 | 7.62 | 16 |
# coding=utf-8
import sys, os
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class AppDpiHelper:
"""
Dpi辅助类
在Qt之中,必须在QApplication(sys.argv)之前就设置Dpi,否则不会生效,
但是要获得准确的DpiScale,又需要用到QApplication,因此需要重启一次程序才能让
指定的DpiScale生效,至于为何不采用Qt.AA_EnableHighDpiScaling来实现高Dpi支持呢,
这是因为引入了它,会导致非常多额外处理... | InterwovenCode/ScreenPinKit | src/base/app_dpi_helper.py | .py | 5d5dc1825df793dd | 7.45 | 7 |
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class MouseThroughWindow(QWidget):
"""支持鼠标穿透窗口类"""
def __init__(self, parent: QWidget = None):
super().__init__(parent)
def setVisible(self, visible: bool) -> None:
# [Qt之使用setWindowFlags方法遇到的问题](https://b... | InterwovenCode/ScreenPinKit | src/base/mouse_through_window.py | .py | 171e2649307e9ac7 | 7.45 | 7 |
# coding=utf-8
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtGui import QShowEvent
from PyQt5.QtWidgets import *
from .mouse_through_window import *
class ShadowWindow(MouseThroughWindow):
def __init__(self, roundRadius: int, shadowWidth: float, parent: QWidget):
super().__in... | InterwovenCode/ScreenPinKit | src/base/shadow_window.py | .py | df0e35d089c3d20f | 7.45 | 7 |
# coding=utf-8
from canvas_item.canvas_util import CanvasROIManager
from .canvas_scene import CanvasScene, DrawActionEnum
from .canvas_view import CanvasView
from .canvas_commands import *
class CanvasEditor(QWidget):
"""
Canvas编辑层
sceneBrush == None时,则说明是桌面绘图,
在截图绘图里,其橡皮擦原理是基于sceneBrush来实现的
"""
... | InterwovenCode/ScreenPinKit | src/canvas_editor/canvas_editor.py | .py | ba123b05bf339c32 | 7.45 | 7 |
# coding=utf-8
from canvas_item.canvas_util import *
class CanvasView(QGraphicsView):
"""
注意,不应该对Scene进行缩放,否则你的橡皮擦实现需要改变思路,
通过新建一个橡皮层来实现,因为一旦缩放之后,Sene同背景就会不匹配了
"""
def __init__(self, scene: QGraphicsScene, parent=None):
super().__init__(scene, parent)
self.initUI()
def initUI... | InterwovenCode/ScreenPinKit | src/canvas_editor/canvas_view.py | .py | 79d042e2c4504078 | 7.45 | 7 |
# coding=utf-8
from enum import Enum
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import cv2
import numpy as np
from qt_image_util import ndarray_to_qpixmap, qpixmap_to_ndarray
class AfterEffectType(Enum):
"""
图像后处理效果类型
"""
Unknown = "Unknown"
Blur = "Blur"
... | InterwovenCode/ScreenPinKit | src/canvas_item/after_effect_util.py | .py | ff1a8b57a1b150df | 7.45 | 7 |
# coding=utf-8
from .canvas_util import *
class CanvasArrowItem(CanvasCommonPathItem):
"""
绘图工具-箭头
@note 滚轮可以控制箭头大小
"""
def __init__(self, parent: QWidget = None) -> None:
super().__init__(parent)
self.__initEditMode()
self.__initStyle()
self.zoomComponent = ZoomC... | InterwovenCode/ScreenPinKit | src/canvas_item/canvas_arrow_item.py | .py | 722dbffc2be7c36c | 7.45 | 7 |
# coding=utf-8
from .canvas_util import *
from .canvas_text_item import CanvasTextItem
class BubbleDirectionEnum(Enum):
Null = ""
TopLeft = "⇖"
TopRight = "⇗"
BottomLeft = "⇙"
BottomRight = "⇘"
Left = "⇐"
Right = "⇒"
class CanvasBubbleTextItem(CanvasTextItem):
"""
绘图工具-文本框
@not... | InterwovenCode/ScreenPinKit | src/canvas_item/canvas_bubble_text_item.py | .py | a7f0944cdddbc392 | 7.45 | 7 |
# coding=utf-8
from .canvas_util import *
from .after_effect_util import *
from base import *
class CanvasEffectRectItem(CanvasCommonPathItem):
"""
绘图工具-特效图元
"""
def __init__(self, sourcePixmap: QPixmap, parent: QWidget = None) -> None:
super().__init__(parent, False)
self.... | InterwovenCode/ScreenPinKit | src/canvas_item/canvas_effect_item.py | .py | 90bbfb575e0d4e8e | 7.45 | 7 |
# coding=utf-8
from .canvas_util import *
class CanvasLineStripItem(CanvasCommonPathItem):
"""
绘图工具-折线
Note:
对于一个非封闭的PathItem而言,为了让它的HitTest行为约束在线段内,将其
shape()里的shapePath由相邻两点加上线条宽度构成的连续矩形合并;
另一方面,最终显示出来的线条则是QPen直接绘制原始PathItem所得
"""
def __init__(self, parent: QWidget = None) -> None:... | InterwovenCode/ScreenPinKit | src/canvas_item/canvas_line_strip_item.py | .py | b9acf26d5ad8e0d9 | 7.45 | 7 |
# coding=utf-8
from .canvas_line_strip_item import CanvasLineStripItem
from .canvas_util import *
class CanvasMarkerPen(CanvasLineStripItem):
"""
绘图工具-记号笔
@note 滚轮可以控制笔触大小
"""
def __init__(self, parent: QWidget = None) -> None:
super().__init__(parent)
self.__initEditMode()
d... | InterwovenCode/ScreenPinKit | src/canvas_item/canvas_marker_pen.py | .py | 9fa69fe840193999 | 7.45 | 7 |
# coding=utf-8
from .canvas_util import *
class CanvasPasteImageItem(CanvasCommonPathItem):
"""
绘图工具-图片粘贴图元
"""
def __init__(self, bgBrush: QBrush, parent: QWidget = None) -> None:
super().__init__(parent, False)
self.__initEditMode()
self.radius = 5
self.bgBrush = bgB... | InterwovenCode/ScreenPinKit | src/canvas_item/canvas_paste_image_item.py | .py | 97488fd6c8c2f695 | 7.45 | 7 |
# coding=utf-8
from .canvas_util import *
class CanvasPenItem(CanvasCommonPathItem):
"""
绘图工具-画笔
"""
def __init__(self, isSmoothCurve: bool = True, parent: QWidget = None) -> None:
super().__init__(parent, False)
self.__initEditMode()
self.__initStyle()
self.isSmoothCu... | InterwovenCode/ScreenPinKit | src/canvas_item/canvas_pen_item.py | .py | a6b2d13c4da8cbb8 | 7.45 | 7 |
# coding=utf-8
from .canvas_util import *
class CanvasShapeEnum(Enum):
Ellipse = "Ellipse"
Triangle = "Triangle"
Rectangle = "Rectangle"
Star = "Star"
# NPolygon = "N边形"
class CanvasShapeItem(CanvasCommonPathItem):
"""
绘图工具-闭合形状
@note 滚轮可以控制描边宽度
"""
def __init__(
sel... | InterwovenCode/ScreenPinKit | src/canvas_item/canvas_shape_item.py | .py | 6f9aa99ceb57bac7 | 7.45 | 7 |
# coding=utf-8
from .canvas_util import *
class CanvasStarItem(CanvasCommonPathItem):
"""
绘图工具-五芒星
"""
def __init__(self, parent: QWidget = None) -> None:
super().__init__(parent)
self.__initEditMode()
self.__initStyle()
self.zoomComponent = ZoomComponent()
se... | InterwovenCode/ScreenPinKit | src/canvas_item/canvas_star_item.py | .py | 660184b64e35c3eb | 7.45 | 7 |
# coding=utf-8
# 参考资料
# - https://svgco.de/
# - https://editor.method.ac/
# - https://svgedit.netlify.app/editor/index.html
# - https://yqnn.github.io/svg-path-editor/
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtSvg import QSvgWidget, QSvgRenderer
from .canvas_uti... | InterwovenCode/ScreenPinKit | src/canvas_item/canvas_svg_item.py | .py | a50ad79d5a412fa4 | 7.45 | 7 |
# coding=utf-8
from .canvas_util import *
class CanvasTextItem(QGraphicsTextItem):
"""
绘图工具-文本框
@note 滚轮可以控制字体大小
"""
def __init__(self, parent: QWidget = None) -> None:
super().__init__(parent)
self.__initStyle()
self.transformComponent = TransformComponent()
self... | InterwovenCode/ScreenPinKit | src/canvas_item/canvas_text_item.py | .py | dbcc87f96f0233d2 | 7.45 | 7 |
# coding=utf-8
import sys, os
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from canvas_item import *
class DrawingScene(QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent)
... | InterwovenCode/ScreenPinKit | src/canvas_item/demos/canvas_line_strip_demo.py | .py | d8095e8f012d6658 | 7.45 | 7 |
# coding=utf-8
import sys, os
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from canvas_item import *
class DrawingScene(QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent)
... | InterwovenCode/ScreenPinKit | src/canvas_item/demos/canvas_shape_demo.py | .py | 301a6c289ab8deb0 | 7.45 | 7 |
# coding=utf-8
import sys, os
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from canvas_item import *
class DrawingScene(QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent)
... | InterwovenCode/ScreenPinKit | src/canvas_item/demos/canvas_text_demo.py | .py | e0c808694014f787 | 7.45 | 7 |
"""Arena level logic — collective points unlock more weekly issues.
The arena's level is a pure function of the sum of every player's
``total_points`` in ``scores.json``. Each level above 0 adds a bonus
to the per-category issue limits. Thresholds and bonuses live in
``config/arena_levels.json`` so Python (issue selec... | claudiotancredi/weekly-issue-arena | scripts/arena_level.py | .py | ac99ed175c41eb0b | 7.52 | 10 |
#!/usr/bin/env python3
"""Fetch open issues from configured repos and update the README tables.
Usage::
python scripts/fetch_issues.py
Environment variables:
GITHUB_TOKEN — required for higher rate limits (5 000 req/hr vs 60).
"""
import argparse
import json
import logging
import random
import re
from date... | claudiotancredi/weekly-issue-arena | scripts/fetch_issues.py | .py | 4a161bf7452ff616 | 7.52 | 10 |
"""Opt-in preferences for arena participation.
The arena is consent-first: a contributor exists in the arena only after
they submit the *Join the Arena* issue form. This module owns
``.arena_state/preferences.json``, the single source of truth for who
opted in and what they agreed to.
Schema::
{
"version":... | claudiotancredi/weekly-issue-arena | scripts/preferences.py | .py | 3387335eaeab202a | 7.52 | 10 |
"""Shared utilities for Weekly Issue Arena scripts."""
import json
import logging
import os
import re
import tempfile
from datetime import datetime, timedelta, timezone
from pathlib import Path
import requests
log = logging.getLogger(__name__)
GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")
HEADERS = {
"Accept": ... | claudiotancredi/weekly-issue-arena | scripts/utils.py | .py | 5321728ae0adb90b | 7.52 | 10 |
"""Tests for the arena_level helper module."""
import json
import sys
import pytest
sys.path.insert(0, "scripts")
import arena_level # noqa: E402, I001
def _bonus(n: int) -> dict:
return {"gfi": n, "bug": n, "hard": n}
@pytest.fixture
def sample_config():
"""Synthetic levels config covering edge cases.... | claudiotancredi/weekly-issue-arena | tests/test_arena_level.py | .py | 327c29b283fbeeab | 8.02 | 10 |
__all__ = (
"ConfigFileExtensionError",
"ConfigNotFoundError",
)
class ConfigFileExtensionError(ValueError):
"""Raised when a configuration file uses an unsupported extension."""
class ConfigNotFoundError(RuntimeError):
def __init__(self, config_dir, dagfile):
super().__init__(f"Could not fi... | airflow-laminar/airflow-config | airflow_config/exceptions.py | .py | 861825613d7750cd | 7.13 | 17 |
from __future__ import annotations
import os
from pathlib import Path
from typing import ClassVar
from airflow.plugins_manager import AirflowPlugin
__all__ = (
"AirflowConfigViewerPlugin",
"AirflowConfigViewerPluginView",
)
try:
from airflow.api_fastapi.auth.managers.models.resource_details import Acces... | airflow-laminar/airflow-config | airflow_config/ui/airflow.py | .py | 3128b70956f23ef2 | 7.63 | 17 |
# /// script
# requires-python = ">=3.11,<3.15"
# dependencies = []
# [tool.uv]
# exclude-newer = "P7D"
# ///
"""Safely inspect wheel and sdist archive paths, types, modes, size, and SHA-256."""
from __future__ import annotations
import argparse
import hashlib
import json
import stat
import sys
import tarfile
import ... | aoirint/sd_scripts_docker | .agents/skills/python-quality-check/scripts/inspect_distribution.py | .py | 86cc60199cf85c6e | 7.92 | 6 |
"""Create a ``__repr__`` for your python classes.
A Python script that takes a file name as a command-line argument,
imports the specified module, and then prints a ``__repr__`` method
for each class defined in the module.
It uses the definition found in the ``__init__`` method of the class.
"""
import difflib
impor... | cleder/crepr | crepr/crepr.py | .py | 9f9fe68e7d1de678 | 7.45 | 7 |
"""Test class with positional args."""
from typing import Self
class PosArgs:
"""Positional args cannot be processed."""
def __init__(self: Self, x: int, *args: int) -> None:
"""Initialize the class.
Args:
----
x (int): The value of x.
*args (int): Additional... | cleder/crepr | tests/classes/class_pos_args_test.py | .py | 9b9758e81200835b | 7.45 | 7 |
"""Module containing class definitions for testing purposes.
This module defines a class with a `__repr__` method.
"""
from typing import Self
class MyClassWithRepr:
"""A class with a `__repr__` method."""
def __init__(self: Self, value: str) -> None:
"""Initialize the class with the given value.""... | cleder/crepr | tests/classes/class_with_repr_test.py | .py | 69fb5478cb36cb06 | 7.95 | 7 |
"""Module containing class definitions for testing purposes.
This module defines a class without a `__repr__` method.
"""
from typing import Self
class MyClassWithoutRepr:
"""A class without a `__repr__` method."""
def __init__(self: Self, value: str) -> None:
"""Initialize the class with the given... | cleder/crepr | tests/classes/class_without_repr.py | .py | 9f7b73577a945bce | 7.45 | 7 |
"""Test a class with keyword arguments and **kwargs."""
from typing import Self
class SplatKwargs:
"""The happy path class."""
def __init__(self: Self, name: str, **kwargs: int) -> None:
"""Initialize the class."""
self.name = name # pragma: no cover
self.kwargs = kwargs # pragma: ... | cleder/crepr | tests/classes/splat_kwargs_test.py | .py | 59f04bb721925dc1 | 7.45 | 7 |
"""Test class for kw only arguments."""
from typing import Self
class KwOnly:
"""The happy path class."""
def __init__(self: Self, name: str, *, age: int) -> None:
"""Initialize the class."""
self.name = name # pragma: no cover
self.age = age # pragma: no cover
def __repr__(se... | cleder/crepr | tests/remove/kw_only_test.py | .py | 01479a11eaf27d1d | 7.95 | 7 |
"""Test a class with keyword arguments and **kwargs."""
from typing import Self
class SplatKwargs:
"""The happy path class."""
def __init__(self: Self, name: str, **kwargs: int) -> None:
"""Initialize the class."""
self.name = name # pragma: no cover
self.kwargs = kwargs # pragma: ... | cleder/crepr | tests/remove/splat_kwargs_test.py | .py | 44ab3f57b7a3ca89 | 7.95 | 7 |
from pydantic import BaseModel
from typing import Optional, Dict
class BSLObjectStorage(BaseModel):
"""Definisce la configurazione per l'Object Storage"""
bucket: str
prefix: Optional[str] = None
caCert: Optional[str] = None
class Config:
extra = "allow"
class BSLCredential(BaseModel):
... | seriohub/vui-api | src/models/k8s/bsl.py | .py | d992ba5126a8bd08 | 7.56 | 12 |
from pydantic import BaseModel
from typing import Optional, Dict, List
# from datetime import datetime
class BackupRepositoryMetadata(BaseModel):
"""Represents the metadata section of a BackupRepository."""
name: str
generateName: Optional[str] = None
namespace: str
uid: str
resourceVersion: O... | seriohub/vui-api | src/models/k8s/repo.py | .py | d16d7fc3a3a34084 | 7.56 | 12 |
import json
import logging
import shutil
from pathlib import Path
from f.common_logic.data_conversion import to_geojson
from f.common_logic.db_operations import postgresql
from f.common_logic.file_operations import (
list_to_csv_string,
read_csv_to_list,
save_uploaded_file_to_temp,
)
from f.connectors.csv.... | ConservationMetrics/gc-scripts-hub | f/apps/gc_dataset_importer.app/4_apply_transformation_and_write_to_database.inline_script.py | .py | 013b7f6721d94474 | 7.54 | 11 |
import base64
import csv
import json
import logging
import tempfile
import zipfile
from io import StringIO
from pathlib import Path
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def read_csv_to_list(csv_path):
"""
Read CSV file and return as list of dictionaries.
Parameter... | ConservationMetrics/gc-scripts-hub | f/common_logic/file_operations.py | .py | fbaac97b61afa619 | 7.54 | 11 |
import json
import re
import unicodedata
def _reverse_parts(k, sep="/"):
"""Reverse the parts of a string separated by a given separator.
Parameters
----------
k : str
The string to be reversed.
sep : str, optional
The separator used to split and join the string parts, by default ... | ConservationMetrics/gc-scripts-hub | f/common_logic/identifier_utils.py | .py | 8d1f151c1819bb63 | 7.54 | 11 |
from pathlib import Path
import pandas as pd
from f.common_logic.data_conversion import detect_structured_data_type
_CYBERTRACKER_FIXTURE = (
Path(__file__).resolve().parent.parent.parent
/ "connectors/cybertracker/tests/assets/0.json"
)
def test_structured_data_type__gpx_format(tmp_path: Path):
file_p... | ConservationMetrics/gc-scripts-hub | f/common_logic/tests/data_format_detection_test.py | .py | a72fea291b98084f | 7.04 | 11 |
from datetime import datetime
from unittest.mock import patch
from f.common_logic.date_utils import calculate_cutoff_date
@patch("f.common_logic.date_utils.datetime")
def test_calculate_cutoff_date_with_lookback(mock_datetime):
"""Test calculate_cutoff_date with a lookback period"""
# Mock current date to Oc... | ConservationMetrics/gc-scripts-hub | f/common_logic/tests/date_utils_test.py | .py | 74ffd9e3ecad7b67 | 8.04 | 11 |
from pytest import raises as pytest_raises
from f.common_logic.identifier_utils import (
camel_to_snake,
normalize_and_snakecase_keys,
normalize_identifier,
sanitize_sql_message,
slugify,
validate_identifier,
)
def test_sanitize_sql_message():
message = {
"col.1": 1,
"col?... | ConservationMetrics/gc-scripts-hub | f/common_logic/tests/identifier_utils_test.py | .py | bfa69ace4d3e6f77 | 8.04 | 11 |
# twilio~=9.4
# requests~=2.32.3
import json
import logging
from typing import TypedDict
from twilio.rest import Client as TwilioClient
# https://hub.windmill.dev/resource_types/274/twilio_message_template
class twilio_message_template(TypedDict):
account_sid: str
auth_token: str
origin_number: str
... | ConservationMetrics/gc-scripts-hub | f/connectors/alerts/alerts_twilio.py | .py | 50856291ea0c1cab | 7.54 | 11 |
import os
import pytest
import testing.postgresql
from google.auth.credentials import AnonymousCredentials
from google.cloud import storage
@pytest.fixture
def pg_database():
"""A dsn that may be used to connect to a live (local for test) postgresql server"""
db = testing.postgresql.Postgresql(port=7654)
... | ConservationMetrics/gc-scripts-hub | f/connectors/alerts/tests/conftest.py | .py | 815795f3aeaef0be | 8.04 | 11 |
# requirements:
# filetype~=1.2
# fiona~=1.10
# openpyxl~=3.1
# pandas~=2.2
# pyproj~=3.7
# psycopg[binary]
# requests~=2.32
from __future__ import annotations
import json
import logging
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional
import pandas as pd
import requests
from pyproj im... | ConservationMetrics/gc-scripts-hub | f/connectors/arcgis/arcgis_download_feature_layer_anonymously.py | .py | bb6209c8a3515167 | 7.54 | 11 |
# requirements:
# psycopg[binary]
# requests~=2.32
import logging
import os
from pathlib import Path
from typing import TypedDict
import requests
from f.common_logic.db_operations import postgresql
from f.common_logic.file_operations import save_data_to_file
from f.connectors.geojson.geojson_to_postgres import main ... | ConservationMetrics/gc-scripts-hub | f/connectors/arcgis/arcgis_feature_layer.py | .py | a1f425fa95373f4f | 7.54 | 11 |
import json
import logging
from pyproj import Transformer
from f.connectors.arcgis.arcgis_download_feature_layer_anonymously import (
build_geojson,
fetch_features,
fetch_layer_data,
get_layer_metadata,
main,
transform_record_geometry,
)
logger = logging.getLogger(__name__)
def test_script_... | ConservationMetrics/gc-scripts-hub | f/connectors/arcgis/tests/arcgis_download_feature_layer_anonymously_test.py | .py | d3704e3026954b81 | 7.04 | 11 |
"""Demo script for did:webvh generation and updating."""
import argparse
import asyncio
import json
from datetime import datetime
from pathlib import Path
from time import perf_counter
import aries_askar
from did_webvh.askar import AskarSigningKey
from did_webvh.const import ASKAR_STORE_FILENAME, HISTORY_FILENAME, W... | decentralized-identity/didwebvh-py | demo.py | .py | 7ee251ce6f95c33c | 7.5 | 9 |
"""Askar key store support for signing proofs."""
from typing import Optional
from aries_askar import Key, KeyAlg
from aries_askar.error import AskarError
from .core.multi_key import MultiKey
from .core.types import SigningKey, VerifyingKey
# Supported multicodec names mapped to key algorithms
ALG_SUPPORTED = {"ed2... | decentralized-identity/didwebvh-py | did_webvh/askar.py | .py | 32df26974606f12a | 7.5 | 9 |
"""Date-time handling utilities."""
from datetime import datetime, timedelta, timezone
from typing import Union
MAX_FUTURE_SKEW = timedelta(minutes=5)
def iso_format_datetime(dt: datetime) -> str:
"""Convert a datetime to a string in ISO format."""
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezo... | decentralized-identity/didwebvh-py | did_webvh/core/date_utils.py | .py | d482d309312992ec | 7.5 | 9 |
"""DID URL format handling."""
import re
from dataclasses import dataclass
from typing import ClassVar
from urllib.parse import parse_qs
@dataclass
class DIDUrl:
"""A DID URL as defined by Decentralized Identifiers 1.0."""
PATTERN: ClassVar[re.Pattern] = re.compile(
r"^did:([a-z0-9]+):((?:[a-zA-Z0-9... | decentralized-identity/didwebvh-py | did_webvh/core/did_url.py | .py | a6ed255051f7cbd6 | 7.5 | 9 |
"""File access helpers."""
import os
import re
from asyncio import get_running_loop
from codecs import getincrementaldecoder
from collections.abc import AsyncGenerator, AsyncIterator
from contextlib import asynccontextmanager
from io import FileIO, StringIO
from pathlib import Path
from typing import TypeAlias
import... | decentralized-identity/didwebvh-py | did_webvh/core/file_utils.py | .py | e00c7b6f80f47611 | 7.5 | 9 |
"""Hashing utilities and metadata."""
from collections.abc import Callable
from dataclasses import dataclass
from hashlib import sha256
from typing import TypeAlias
import base58
from multiformats import multihash
HashFn: TypeAlias = Callable[[bytes], bytes]
DEFAULT_HASH = "sha2-256"
HASH_FN_MAP: dict[str, HashFn]... | decentralized-identity/didwebvh-py | did_webvh/core/hash_utils.py | .py | 3bf130adb36d6077 | 7.5 | 9 |
"""MultiKey format handling."""
from typing import ClassVar
from multiformats import multibase, multicodec
class MultiKey(str):
"""MultiKey string representation."""
BASE: ClassVar[str] = "base58btc"
@classmethod
def from_public_key(cls, codec: str, pk: bytes) -> "MultiKey":
"""Encode publ... | decentralized-identity/didwebvh-py | did_webvh/core/multi_key.py | .py | 07a34814524fada6 | 7.5 | 9 |
"""Support for IETF problem details."""
from dataclasses import dataclass
from typing import Any
@dataclass
class ProblemDetails:
"""RFC 9457 problem details instance."""
type: str
title: str | None = None
detail: str | None = None
status: int | None = None
exts: dict[str, Any] | None = None... | decentralized-identity/didwebvh-py | did_webvh/core/problem_details.py | .py | 88169688e6b55b74 | 7.5 | 9 |
"""Document proof generation and verification."""
from copy import deepcopy
from datetime import datetime
from hashlib import sha256, sha384
from typing import Optional
import jcs
from multiformats import multibase
from ..askar import AskarVerifyingKey
from .date_utils import make_timestamp
from .types import Signin... | decentralized-identity/didwebvh-py | did_webvh/core/proof.py | .py | 1a199c91a0e81b65 | 7.5 | 9 |
import json
from copy import deepcopy
import pytest
from did_webvh.core.file_utils import AsyncTextGenerator, AsyncTextReadError, read_str
from did_webvh.core.resolver import (
DereferencingResult,
DidResolver,
HistoryResolver,
HistoryVerifier,
ResolutionResult,
dereference_fragment,
norma... | decentralized-identity/didwebvh-py | did_webvh/core/tests/test_core_resolver.py | .py | 545f836fcf895ef4 | 7 | 9 |
"""Abstract data types."""
from abc import ABC, abstractmethod
from typing import Optional
from .multi_key import MultiKey
class VerifyingKey(ABC):
"""A public key used for verifying proofs."""
@property
@abstractmethod
def kid(self) -> Optional[str]:
"""Access the key identifier."""
@... | decentralized-identity/didwebvh-py | did_webvh/core/types.py | .py | 7b0598fd60615d94 | 7.5 | 9 |
"""Domain and path handling for did:webvh identifiers."""
import urllib
from dataclasses import dataclass, field
from typing import Optional
from .const import SCID_PLACEHOLDER
@dataclass
class DomainPath:
"""Domain and path (and port) compatible with a did:webvh identifier."""
scid: str
domain: str
... | decentralized-identity/didwebvh-py | did_webvh/domain_path.py | .py | df2febb8bae5e95c | 7.5 | 9 |
"""History file management."""
from datetime import datetime
from pathlib import Path
from .const import HISTORY_FILENAME, METHOD_NAME, WITNESS_FILENAME
from .core.did_url import DIDUrl
from .core.file_utils import AsyncTextGenerator, read_url
from .core.resolver import DidResolver, HistoryResolver, LocalHistoryResol... | decentralized-identity/didwebvh-py | did_webvh/history.py | .py | 8afe17b804df1295 | 7.5 | 9 |
"""Provisioning of new did:webvh DIDs."""
import argparse
import asyncio
import base64
import json
import re
from copy import deepcopy
from datetime import datetime
from hashlib import sha256
from pathlib import Path
from typing import Optional, Union
import aries_askar
import jcs
from .askar import AskarSigningKey
... | decentralized-identity/didwebvh-py | did_webvh/provision.py | .py | 1103c1c500088ecf | 7.5 | 9 |
"""Resolution of did:webvh DIDs."""
import argparse
import asyncio
import json
import urllib.parse
from datetime import datetime
from pathlib import Path
from .core.did_url import DIDUrl
from .core.file_utils import AsyncTextReadError, read_url
from .core.problem_details import ProblemDetails
from .core.resolver impo... | decentralized-identity/didwebvh-py | did_webvh/resolver.py | .py | a85bcd7770d46b5c | 7.5 | 9 |
import pytest
from did_webvh.verify import _check_document_id_format
VALID_DID = [
"did:webvh:0000000000000000000000000000:mydomain.com",
"did:webvh:0000000000000000000000000000:mydomain.com%3A500",
"did:webvh:0000000000000000000000000000:mydomain.com%3A500:path",
"did:webvh:00000000000000000000000000... | decentralized-identity/didwebvh-py | did_webvh/tests/test_verify.py | .py | 142bea6747878cd8 | 7 | 9 |
"""High-level document state verification."""
from collections.abc import Awaitable
from .const import METHOD_NAME, METHOD_VERSION
from .core.did_url import DIDUrl
from .core.problem_details import ProblemDetails
from .core.resolver import HistoryVerifier
from .core.state import DocumentState, InvalidDocumentState
fr... | decentralized-identity/didwebvh-py | did_webvh/verify.py | .py | d0aef7c753a55406 | 7.5 | 9 |
from functools import lru_cache
from os import environ, name
from pathlib import Path
from shutil import which
from subprocess import Popen
from sys import argv, exit, stderr, stdout
from time import sleep
from typing import List
@lru_cache(maxsize=1)
def _get_perl() -> str:
perl_exe = which("perl")
if not pe... | dau-dev/verilator-python | verilator/cli.py | .py | fa9c9bcd0a6a494c | 7.48 | 8 |
from collections.abc import Callable
from datetime import UTC, datetime, time, timedelta
from logging import getLogger
from airflow_pydantic import fail, pass_
from airflow_pydantic.airflow import BranchPythonOperator, Param, PythonOperator, PythonSensor, TriggerDagRunOperator
from .common import (
Action,
Ch... | airflow-laminar/airflow-ha | airflow_ha/operator.py | .py | 3c3f9b5152b316f6 | 7.54 | 11 |
from airflow_pydantic import ImportPath, PythonSensorArgs, Task
from pydantic import Field, field_validator
from .common import (
Endtime,
FailTriggerKwargs,
MaxRetrigger,
PassTriggerKwargs,
ReferenceDate,
Runtime,
)
from .operator import HighAvailabilityOperator
__all__ = (
"HighAvailabil... | airflow-laminar/airflow-ha | airflow_ha/task.py | .py | dbb521b01d962412 | 7.54 | 11 |
import pytest
from airflow_pydantic.migration import _airflow_3
from pytest import fixture
from airflow_ha import Action, HighAvailabilityOperator, Result
def _choose(**kwargs):
"""
Example callable for HighAvailabilityOperator.
Returns a tuple of Result and Action.
"""
return (Result.PASS, Actio... | airflow-laminar/airflow-ha | airflow_ha/tests/conftest.py | .py | b3f23a48b99608fb | 8.04 | 11 |
from typing import Literal
from airflow_pydantic import BashTask, BashTaskArgs, CallablePath, SSHTask, SSHTaskArgs
from airflow_pydantic.airflow import BashOperator, SSHOperator
from pydantic import Field, field_validator
__all__ = (
"Lunchy",
"LunchyAction",
"LunchyOperator",
"LunchyOperatorArgs",
... | airflow-laminar/airflow-common | airflow_common/infra/launchctl.py | .py | 7e3d898d296bdf7f | 7.42 | 6 |
from airflow_pydantic import BashTask, BashTaskArgs, CallablePath, SSHTask, SSHTaskArgs
from airflow_pydantic.airflow import BashOperator, SSHOperator
from pydantic import Field, field_validator
__all__ = (
"Reboot",
"RebootOperator",
"RebootOperatorArgs",
"RebootSSH",
"RebootSSHOperator",
"Reb... | airflow-laminar/airflow-common | airflow_common/infra/reboot.py | .py | c764ceb211168494 | 7.42 | 6 |
from airflow_pydantic import BashTask, BashTaskArgs, ImportPath, SSHTask, SSHTaskArgs
from airflow_pydantic.airflow import PythonOperator
from pydantic import Field, field_validator
from .model import CondaLibrary, GitRepo, LibraryList, PipLibrary
__all__ = (
"InstallLibraryOperator",
"InstallLibrarySSHOperat... | airflow-laminar/airflow-common | airflow_common/library/task.py | .py | 92bfd859d10f972c | 7.42 | 6 |
"""Tests for infrastructure tasks: Systemctl, Reboot, and Lunchy."""
import pytest
from airflow_common.infra.journalctl import (
clean_journalctl,
)
from airflow_common.infra.launchctl import (
Lunchy,
LunchySSH,
LunchySSHTask,
LunchySSHTaskArgs,
LunchyTask,
LunchyTaskArgs,
lunchy_comm... | airflow-laminar/airflow-common | airflow_common/tests/test_infra.py | .py | d0a1a71f8dc2c45d | 7.92 | 6 |
from logging import getLogger
from typing import TYPE_CHECKING
from airflow_pydantic import Pool, fail, skip
from supervisor_pydantic.client import SupervisorRemoteXMLRPCClient
from supervisor_pydantic.convenience import (
SupervisorTaskStep,
check_programs,
kill_supervisor,
remove_supervisor_config,
... | airflow-laminar/airflow-supervisor | airflow_supervisor/airflow/local.py | .py | a94ebd0bec09f898 | 7.62 | 16 |
"""Tests for SupervisorTask and SupervisorTaskArgs configurations."""
from unittest.mock import patch
import pytest
from airflow_pydantic.migration import _airflow_3
from airflow_supervisor import ProgramConfiguration, SupervisorAirflowConfiguration
from airflow_supervisor.config import SupervisorOperator, Superviso... | airflow-laminar/airflow-supervisor | airflow_supervisor/tests/config/test_task.py | .py | ea7a0201844597a8 | 7.12 | 16 |
"""Tests for SupervisorSSHTask and SupervisorSSHTaskArgs configurations."""
from unittest.mock import patch
import pytest
from airflow_pydantic import Host, Port, SSHOperatorArgs
from airflow_supervisor import ProgramConfiguration
from airflow_supervisor.config import (
SupervisorSSHAirflowConfiguration,
Sup... | airflow-laminar/airflow-supervisor | airflow_supervisor/tests/config/test_task_ssh.py | .py | fbe9fb2828778582 | 8.12 | 16 |
"""Extended tests for SupervisorSSH operator."""
from unittest.mock import patch
import pytest
from airflow_pydantic.migration import _airflow_3
@pytest.fixture
def ssh_configuration():
"""Create an SSH Supervisor configuration fixture."""
try:
from airflow.providers.ssh.hooks.ssh import SSHHook
... | airflow-laminar/airflow-supervisor | airflow_supervisor/tests/test_ssh_extended.py | .py | 3560c48a57f49660 | 8.12 | 16 |
__version__ = "0.1.5"
from collections.abc import Callable
from enum import Enum
from typing import TypeVar
from .builtins import (
_createObservedDict,
_createObservedList,
_createObservedSet,
_ObservedDict,
_ObservedList,
_ObservedSet,
)
from .generic import _install_watcher_object
try:
... | 1kbgz/bigbrother | bigbrother/__init__.py | .py | a3d6ce714dda36ff | 7.5 | 9 |
"""Observe plain objects (e.g. dataclasses) that keep their state in ``__dict__``.
``object.__setattr__`` writes to the instance dict at the C level, *bypassing* a dict subclass's
``__setitem__`` — so the ``__dict__``-swap trick used for pydantic (whose ``__setattr__`` does a
Python-level ``dict[name] = value``) does ... | 1kbgz/bigbrother | bigbrother/generic.py | .py | 6724807dd40a2885 | 7.5 | 9 |
from enum import Enum
from dataclasses import dataclass
from typing import Any
class ResultType(Enum):
'''
Тип результата выполнения узла
NONE - ничего не возвращает
STR_VALUE - строковое значение
NUMBER_VALUE - числовое значение
IMAGE_CV2 - изображение в формате OpenCV
IMAGE_BASE64 ... | EgorPlehanov/node_data_editor | units/calculation_functions/calculation_functions_typing.py | .py | 2ede282338a306a0 | 7.42 | 6 |
from ..calculation_functions_typing import *
from ...data_types import File
from ..input.read import read_file
import cv2
import numpy as np
import matplotlib.pyplot as plt
def fourier_2d_to_show(image_path, is_gamma_transform=False):
"""
Применить прямое 2-D преобразование Фурье
"""
image = cv2.imr... | EgorPlehanov/node_data_editor | units/calculation_functions/edit/fourier.py | .py | 18c2befdb8d792a8 | 7.42 | 6 |
from ..calculation_functions_typing import *
from ...data_types import File
from ..input.read import read_file
from .filters import apply_grayscale_scaling
import cv2
import numpy as np
import matplotlib.pyplot as plt
def calculate_derivative(image):
"""
Рассчитываем производные строки изображения
"""
... | EgorPlehanov/node_data_editor | units/calculation_functions/edit/xray_artifact.py | .py | 8faba835b414b3d8 | 7.42 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.