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
"""Tests for variant name generation in CuBIDS. This module tests the assign_variants function which is responsible for generating variant names when files differ from the dominant group. The tests cover: 1. Basic variant name generation 2. Handling of cluster values (e.g., from parameter clustering) 3. Special param...
PennLINC/CuBIDS
cubids/tests/test_variants.py
.py
b9e875804d768e84
8.25
31
"""Utility functions for CuBIDS' tests.""" import hashlib import importlib.resources import json import os import shutil from contextlib import contextmanager from pathlib import Path import nibabel as nb import numpy as np import pandas as pd TEST_DATA = importlib.resources.files("cubids") / "tests/data" def get_...
PennLINC/CuBIDS
cubids/tests/utils.py
.py
444fbe9c720dca3e
8.25
31
"""Methods for validating BIDS datasets. This module provides functions for validating BIDS datasets, including building subprocess commands for the BIDS validator and handling validation results. """ import glob import json import logging import os import pathlib import re import subprocess import warnings import p...
PennLINC/CuBIDS
cubids/validator.py
.py
3022a3fea0075da7
7.75
31
""" Benchmark different detector models. Compares speed and optionally accuracy across different backends and model sizes. """ import argparse import time from typing import Dict import numpy as np import yaml from tello_vision.detectors.base_detector import BaseDetector def benchmark_detector( detector: BaseD...
dronefreak/dji-tello-object-detection-segmentation
examples/benchmark.py
.py
4d5c0e9f784f9091
7.92
69
""" Example: Object tracking and following with Tello. Demonstrates autonomous behavior - drone follows a detected person. This is a starting point for self-driving car concepts applied to drones: - Object detection - Target tracking - Reactive control based on object position """ import time from collections import...
dronefreak/dji-tello-object-detection-segmentation
examples/object_follower.py
.py
f2c64740e86a1bf7
7.92
69
""" Example: Basic detection without drone (using webcam or video file). Useful for testing detector models without needing the actual drone. """ import argparse import time import cv2 import yaml from tello_vision.detectors.base_detector import BaseDetector from tello_vision.visualizer import Visualizer def main(...
dronefreak/dji-tello-object-detection-segmentation
examples/test_detector.py
.py
cd1731f1476fc77e
7.42
69
""" Main application for Tello Vision. Integrates drone control, detection, and visualization. """ import argparse import time from pathlib import Path from typing import Optional import cv2 import numpy as np import yaml from .config_validator import ConfigError, validate_config from .detectors.base_detector impor...
dronefreak/dji-tello-object-detection-segmentation
tello_vision/app.py
.py
28d1aecd12a4d764
7.92
69
""" Configuration validation utilities. Provides a small, dependency-free schema check for ``config.yaml`` so that missing or malformed configuration surfaces as an actionable error message at startup instead of a raw ``KeyError`` deep inside the application (e.g. while initializing the detector or drone controller). ...
dronefreak/dji-tello-object-detection-segmentation
tello_vision/config_validator.py
.py
b8beb515872e3506
7.92
69
""" Abstract base class for object detection/segmentation models. Allows easy swapping between different backends (YOLOv8, Detectron2, custom). """ from abc import ABC, abstractmethod from dataclasses import dataclass from typing import List, Optional, Tuple import numpy as np @dataclass class Detection: """Si...
dronefreak/dji-tello-object-detection-segmentation
tello_vision/detectors/base_detector.py
.py
4645637ab65527cc
7.92
69
""" Detectron2 detector implementation. Higher quality but slower than YOLO. Good for precision applications. """ import time from typing import Any, Optional import numpy as np from .base_detector import BaseDetector, Detection, DetectionResult class Detectron2Detector(BaseDetector): """Detectron2 Mask R-CNN...
dronefreak/dji-tello-object-detection-segmentation
tello_vision/detectors/detectron2_detector.py
.py
d3d4205695406493
7.92
69
""" YOLOv8 detector implementation using Ultralytics. Fast, real-time capable, and easy to use. """ import time from typing import TYPE_CHECKING, Optional import cv2 import numpy as np from .base_detector import BaseDetector, Detection, DetectionResult if TYPE_CHECKING: # Only needed for type-checking: ultraly...
dronefreak/dji-tello-object-detection-segmentation
tello_vision/detectors/yolo_detector.py
.py
782b73d5e5879fea
7.92
69
""" Asynchronous inference worker. Decouples frame capture/display from model inference by running detection on a dedicated background thread. The main loop can keep grabbing and displaying frames at full speed while inference proceeds independently; if inference is slower than capture, older un- processed frames are ...
dronefreak/dji-tello-object-detection-segmentation
tello_vision/inference_worker.py
.py
141bf0daa4c147f4
7.92
69
"""Pytest configuration and shared fixtures.""" import numpy as np import pytest # Markers that identify a test as *not* a plain fast unit test. Any test # collected without one of these already applied is auto-marked "unit" so # CI's `-m "unit and not slow"` selection actually picks up the test suite # instead of si...
dronefreak/dji-tello-object-detection-segmentation
tests/conftest.py
.py
93bfcb52c76795aa
8.42
69
"""Tests for main application.""" from unittest.mock import Mock, patch from tello_vision.app import TelloVisionApp class TestTelloVisionApp: """Tests for TelloVisionApp class.""" @patch("tello_vision.app.TelloController") @patch("tello_vision.app.BaseDetector") @patch("tello_vision.app.Visualizer"...
dronefreak/dji-tello-object-detection-segmentation
tests/test_app.py
.py
2fc0b9a7253f7010
7.42
69
"""Tests for base detector functionality.""" import pytest from tello_vision.detectors.base_detector import ( BaseDetector, Detection, DetectionResult, ) class TestDetection: """Tests for Detection class.""" def test_detection_creation(self): """Test creating a detection.""" det ...
dronefreak/dji-tello-object-detection-segmentation
tests/test_detectors.py
.py
c2f014baed5ee644
8.42
69
"""Tests for the asynchronous inference worker.""" import time from unittest.mock import Mock import numpy as np from tello_vision.detectors.base_detector import DetectionResult from tello_vision.inference_worker import AsyncInferenceWorker def _make_result(count: int = 0) -> DetectionResult: return DetectionRe...
dronefreak/dji-tello-object-detection-segmentation
tests/test_inference_worker.py
.py
abd75e76d4c817b3
7.42
69
"""Tests for Tello controller functionality.""" import sys from unittest.mock import MagicMock, Mock, patch import numpy as np import pytest from tello_vision.tello_controller import TelloController # TelloController imports pynput.keyboard lazily inside # setup_keyboard_controls() because pynput's top-level package...
dronefreak/dji-tello-object-detection-segmentation
tests/test_tello_controller.py
.py
5bfabe35ea5e6dc0
7.42
69
"""Tests for visualization functionality.""" import numpy as np from tello_vision.detectors.base_detector import Detection from tello_vision.visualizer import Visualizer class TestVisualizer: """Tests for Visualizer class.""" def test_visualizer_creation(self, sample_config): """Test creating a visu...
dronefreak/dji-tello-object-detection-segmentation
tests/test_visualizer.py
.py
1a02b37745128da7
7.42
69
# do not pre-load from typing import Any, Dict, Mapping, Optional from .api_utils import generate_interview_from_bytes from .docassemble_compat import background_context as bg_context, get_worker_app workerapp = get_worker_app() @workerapp.task def weaver_generate_task( filename: str, mimetype: Optional[st...
SuffolkLITLab/docassemble-ALWeaver
docassemble/ALWeaver/api_weaver_worker.py
.py
20d82167dd494670
7.72
26
from typing import Any, Dict, List, Optional, Union import ruamel.yaml as yaml from docassemble.base.util import log, DADict, DAList, DAStore, path_and_mimetype from packaging.version import Version from more_itertools import unique_everseen __all__ = [ "get_possible_deps_as_choices", "get_pypi_deps_from_choi...
SuffolkLITLab/docassemble-ALWeaver
docassemble/ALWeaver/custom_values.py
.py
a0928ebc2ffd5af8
7.72
26
from typing import Dict, List, Tuple from bs4 import BeautifulSoup from bs4.element import Tag import copy import json """ Data flow: 1. Initial screen load: PY make_it_draggable (a). outputs a draggable_table for screen display (b). outputs the original table order as a list to be used later ...
SuffolkLITLab/docassemble-ALWeaver
docassemble/ALWeaver/draggable_table.py
.py
a94d3766538bfa8d
7.72
26
"""Session, candidate and event records for the Weaver editing agent. Nothing in this module talks to Flask, Docassemble or a model provider. It owns the shapes that the orchestration loop, the tool registry and the REST layer all agree on, plus the owner-scoped Redis persistence that keeps an agent conversation alive...
SuffolkLITLab/docassemble-ALWeaver
docassemble/ALWeaver/editor_agent_models.py
.py
3d16b281643cb57e
7.72
26
"""Deterministic repair of the blocking problems that are purely mechanical. Two DAYamlChecker errors dominate real interviews: a question block with no ``id``, and two blocks sharing one. Both are genuine problems and both have a single obvious fix, so refusing to start the assistant over them just makes a developer ...
SuffolkLITLab/docassemble-ALWeaver
docassemble/ALWeaver/editor_agent_repair.py
.py
ce7d222abe2d2d79
7.72
26
from __future__ import annotations import json import re import textwrap from typing import Any, Dict, Iterable, List, Optional, Tuple DEFAULT_FIELD_TYPES: List[str] = [ "text", "yesno", "yesnomaybe", "radio", "checkboxes", "combobox", "multiselect", "dropdown", "currency", "n...
SuffolkLITLab/docassemble-ALWeaver
docassemble/ALWeaver/editor_ai_utils.py
.py
c9ee0c602d080297
7.72
26
"""Deterministic literal search and replacement helpers for editor projects. The browser never sends replacement text as an instruction to interpret. It sends exact source spans from a search response, and these helpers verify that the spans are still matches before producing a new source buffer. """ from __future__...
SuffolkLITLab/docassemble-ALWeaver
docassemble/ALWeaver/editor_project_search.py
.py
4fb2e59a95da870d
7.72
26
import pandas as pd from typing import List, Dict, Optional from docassemble.base.util import log __all__ = ["get_LIST_codes"] def get_LIST_codes( file_path: str, custom_order: Optional[List[str]] = None ) -> List[Optional[Dict[str, str]]]: """ Reads a CSV file and creates a list of dictionaries structur...
SuffolkLITLab/docassemble-ALWeaver
docassemble/ALWeaver/list_taxonomy.py
.py
a35393ee83a335aa
7.72
26
"""Build the model behind a generated interview's review screen. The Weaver used to emit one review "Edit" entry per parent collection, which meant one entry per variable for the many interviews whose fields are mostly loose primitives. ALDashboard's review screen generator groups by the question screen instead, which...
SuffolkLITLab/docassemble-ALWeaver
docassemble/ALWeaver/review_screen.py
.py
581415d317ff087a
7.72
26
# do not pre-load """End-to-end checks on the attachment blocks the Weaver writes for addenda. An addendum only works if three separate parts of the generated YAML agree: the ALDocument has to be created with `has_addendum=True`, the PDF field has to be filled from `safe_value()` rather than the variable itself, and a...
SuffolkLITLab/docassemble-ALWeaver
docassemble/ALWeaver/test_addendum_attachment.py
.py
342543cf6e290fe1
8.22
26
# do not pre-load import unittest import yaml from docassemble.ALWeaver.assemblyline_settings import ( MANAGED_BLOCK_ID, METADATA_DOCUMENT_ID, SETTINGS_SCHEMA, read_settings, update_settings, ) SOURCE = """# keep header metadata: title: Original description: | Existing description auth...
SuffolkLITLab/docassemble-ALWeaver
docassemble/ALWeaver/test_assemblyline_settings.py
.py
04f03aef635d8fb8
8.22
26
# # Copyright (c) 2020 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # """ Oslo Logging configuration """ from oslo_config import cfg from oslo_log import log as logging from controllerconfig.common import constants def setup_logger(): """ Setup a logger """ # set in cfg what the valid ...
starlingx/config
controllerconfig/controllerconfig/controllerconfig/common/oslolog.py
.py
de728f5557a14070
7.71
25
# # Copyright (c) 2026 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # """Unit tests for controllerconfig.common.exceptions module.""" import unittest from controllerconfig.common.exceptions import ConfigError from controllerconfig.common.exceptions import KeystoneFail from controllerconfig.common....
starlingx/config
controllerconfig/controllerconfig/controllerconfig/tests/test_config_exceptions.py
.py
0527203d111cc8b4
8.21
25
# # Copyright (c) 2026 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # """Unit tests for controllerconfig.common.log module.""" import logging import unittest from unittest import mock from controllerconfig.common import log class TestGetLogger(unittest.TestCase): """Tests for get_logger func...
starlingx/config
controllerconfig/controllerconfig/controllerconfig/tests/test_config_log.py
.py
8459f5a32f79c57c
8.21
25
# # Copyright (c) 2026 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # """Unit tests for controllerconfig.config_management module.""" import unittest from unittest import mock import netaddr from controllerconfig import config_management class TestIsValidManagementAddress(unittest.TestCase): ...
starlingx/config
controllerconfig/controllerconfig/controllerconfig/tests/test_config_management.py
.py
a41c043f3110cce6
7.21
25
# # Copyright (c) 2026 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # """Unit tests for controllerconfig.common.rest_api_utils module.""" import json import unittest from unittest import mock from controllerconfig.common.exceptions import KeystoneFail from controllerconfig.common import rest_api_u...
starlingx/config
controllerconfig/controllerconfig/controllerconfig/tests/test_config_rest_api.py
.py
7a4581b54f4fcd7e
7.21
25
# # Copyright (c) 2026 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # """Extended coverage tests for rest_api_utils module.""" import unittest from unittest import mock from controllerconfig.common import rest_api_utils class TestRestApiExtended(unittest.TestCase): """Extended tests for rest...
starlingx/config
controllerconfig/controllerconfig/controllerconfig/tests/test_config_rest_api_auth.py
.py
b036398a5f3121a0
8.21
25
#!/usr/bin/python # Copyright (c) 2017 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # # Sample upgrade migration script. Important notes: # - The script should exit 0 on success and exit non-0 on fail. Note that # failing will result in the upgrade of controller-1 failing, so don't fail # unless...
starlingx/config
controllerconfig/controllerconfig/scripts/00-sample-migration.py
.py
2ba00e695e5caf80
7.71
25
# Copyright 2013 Wind River, Inc. # Copyright 2012 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LI...
starlingx/config
sysinv/cgts-client/cgts-client/cgtsclient/common/base.py
.py
efa6dfd0771fc020
7.71
25
# # Copyright (c) 2013-2016 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # """ The sole purpose of this module is to manage access to the _no_wrap variable used by the wrapping_formatters module """ _no_wrap = [False] def is_nowrap_set(no_wrap=None): """ returns True if no wrapping de...
starlingx/config
sysinv/cgts-client/cgts-client/cgtsclient/common/cli_no_wrap.py
.py
281d48233aab8556
7.71
25
# Copyright (c) 2026 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import json import os import sys from cgtsclient.common import utils from cgtsclient.tests import utils as test_utils from six.moves import cStringIO as StringIO from unittest import mock class TruncateJsonTest(test_utils.BaseTe...
starlingx/config
sysinv/cgts-client/cgts-client/cgtsclient/tests/test_ptp_json_output.py
.py
23faf902c2e86658
8.21
25
#!/usr/bin/env python3 from __future__ import annotations import argparse import json import logging from typing import TYPE_CHECKING import requests if TYPE_CHECKING: from typing import Any # Init logging config logging.basicConfig(format="%(message)s") logger = logging.getLogger(__name__) def parse_args() ...
digitalfabrik/integreat-cms
.circleci/scripts/get_contributors.py
.py
4bce945b509d132e
7.9
63
""" This module includes functions that are used as decorators in the API endpoints. """ from __future__ import annotations import json import logging import random import re import threading import time from functools import wraps from typing import TYPE_CHECKING from urllib import error, parse, request from django...
digitalfabrik/integreat-cms
integreat_cms/api/decorators.py
.py
3da361004ebc4d68
7.9
63
""" This module includes functions that extend the functionality of the Django Debug Toolbar to non HTML responses. """ from __future__ import annotations import json from typing import TYPE_CHECKING from django.http import HttpResponse if TYPE_CHECKING: from collections.abc import Callable from typing impo...
digitalfabrik/integreat-cms
integreat_cms/api/middleware/json_debug_toolbar_middleware.py
.py
c0026ae6a89136e6
7.9
63
""" This module provides the API endpoints for the public chat API """ from __future__ import annotations import json import logging import random from typing import TYPE_CHECKING import requests from django.conf import settings from django.core.cache import cache from django.http import HttpResponse, JsonResponse f...
digitalfabrik/integreat-cms
integreat_cms/api/v3/chat/user_chat.py
.py
7c9b7e49602c3346
7.9
63
""" This module includes functions related to the event API endpoint. """ from __future__ import annotations from datetime import datetime, timedelta from typing import TYPE_CHECKING from django.conf import settings from django.http import JsonResponse from django.utils import timezone from django.utils.html import ...
digitalfabrik/integreat-cms
integreat_cms/api/v3/events.py
.py
c15e7ee7906b62de
7.9
63
""" APIv3 endpoint for feedback about the imprint """ from __future__ import annotations import logging from typing import TYPE_CHECKING from django.http import Http404, JsonResponse from ....cms.models.feedback.imprint_page_feedback import ImprintPageFeedback from ...decorators import feedback_handler, json_respon...
digitalfabrik/integreat-cms
integreat_cms/api/v3/feedback/imprint_page_feedback.py
.py
189915943d872069
7.9
63
""" APIv3 endpoint for feedback bout single pages """ from __future__ import annotations import logging from typing import TYPE_CHECKING from django.http import Http404, JsonResponse from ....cms.models import PageFeedback from ...decorators import feedback_handler, json_response if TYPE_CHECKING: from ....cms...
digitalfabrik/integreat-cms
integreat_cms/api/v3/feedback/page_feedback.py
.py
3604c303538a31a5
7.9
63
""" This module includes functions related to the imprint API endpoint. """ from __future__ import annotations import logging from typing import TYPE_CHECKING from django.conf import settings from django.http import JsonResponse from django.utils import timezone from django.utils.html import strip_tags if TYPE_CHEC...
digitalfabrik/integreat-cms
integreat_cms/api/v3/imprint.py
.py
7a5d327ea3b25c47
7.9
63
""" This module includes functions related to the languages API endpoint. """ from __future__ import annotations from typing import TYPE_CHECKING from django.http import Http404, JsonResponse from ...cms.constants import region_status from ..decorators import json_response if TYPE_CHECKING: from typing import ...
digitalfabrik/integreat-cms
integreat_cms/api/v3/languages.py
.py
bc1b286c615c102d
7.9
63
""" This module includes the POI category API endpoint. """ from __future__ import annotations from typing import TYPE_CHECKING from django.conf import settings from django.http import JsonResponse from django.templatetags.static import static if TYPE_CHECKING: from typing import Any from django.http impor...
digitalfabrik/integreat-cms
integreat_cms/api/v3/location_categories.py
.py
3c2f772a8887a14a
7.9
63
""" This module includes functions related to the locations/POIs API endpoint. """ from __future__ import annotations from typing import TYPE_CHECKING from django.conf import settings from django.db.models import Prefetch from django.http import JsonResponse from django.utils import timezone from django.utils.html i...
digitalfabrik/integreat-cms
integreat_cms/api/v3/locations.py
.py
132a6987ca5070e2
7.9
63
""" This module contains API views for news endpoints — the per-source push-notification feed and the combined feed across all news sources. """ from __future__ import annotations import logging from typing import TYPE_CHECKING from django.core.paginator import Paginator from django.http import Http404, JsonResponse...
digitalfabrik/integreat-cms
integreat_cms/api/v3/news.py
.py
d6523cb3c62d36ac
7.9
63
""" This module includes functions related to the offers API endpoint. """ from __future__ import annotations from typing import TYPE_CHECKING from django.http import JsonResponse from ...cms.constants import postal_code from ..decorators import json_response if TYPE_CHECKING: from typing import Any from ...
digitalfabrik/integreat-cms
integreat_cms/api/v3/offers.py
.py
7c8938d6b0ea93c3
7.9
63
""" This module includes functions related to the pages API endpoint. """ from __future__ import annotations import json import logging from collections import defaultdict from typing import TYPE_CHECKING from django.conf import settings from django.core.exceptions import MultipleObjectsReturned from django.db.model...
digitalfabrik/integreat-cms
integreat_cms/api/v3/pages.py
.py
61033d28326ca2c9
7.9
63
""" This module includes the endpoint to read and write the settings of a single region. The endpoint is generic on purpose — it is not scoped to a specific consumer — but it only exposes the settings which an external system is allowed to manage (see :mod:`~integreat_cms.cms.constants.region_api_settings`). Core fiel...
digitalfabrik/integreat-cms
integreat_cms/api/v3/region_settings.py
.py
9cc9954fe7734b28
7.9
63
""" This module includes functions related to the regions API endpoint. """ from __future__ import annotations from typing import TYPE_CHECKING from django.http import Http404, JsonResponse if TYPE_CHECKING: from typing import Any from django.http import HttpRequest from ...cms.constants import region_sta...
digitalfabrik/integreat-cms
integreat_cms/api/v3/regions.py
.py
73b6a8111f7d327d
7.9
63
from __future__ import annotations import logging from typing import TYPE_CHECKING from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ if TYPE_CHECKING: from typing import Final from django.db.models import Model from django.utils.functional import Promise from l...
digitalfabrik/integreat-cms
integreat_cms/cms/apps.py
.py
8aeebc664779c6ad
7.9
63
from django.contrib.auth.hashers import BCryptSHA256PasswordHasher class WPBCryptPasswordHasher(BCryptSHA256PasswordHasher): """ A PHP (and WordPress) compatible BCrypt password hasher that supports hashes with ``$2y$10$``. See https://www.php.net/manual/en/function.password-hash.php. For PHP style ha...
digitalfabrik/integreat-cms
integreat_cms/cms/auth.py
.py
df9a24cc584984dd
7.9
63
"""Anesthetic: nested sampling post-processing.""" import anesthetic.samples import anesthetic.plot import anesthetic.read.chain import anesthetic.read.hdf import pandas import pandas.plotting._core import pandas.plotting._misc from anesthetic._format import _DataFrameFormatter from anesthetic._version import __versio...
handley-lab/anesthetic
anesthetic/__init__.py
.py
7d140c4c55cf4631
7.93
73
"""Utility functions for nested sampling examples.""" import numpy as np from scipy.stats import special_ortho_group from scipy.special import gamma, gammaln def random_ellipsoid(mean, cov, size=None): """Draw a point uniformly in an ellipsoid. This is defined so that the volume of the ellipsoid is ``sqr...
handley-lab/anesthetic
anesthetic/examples/utils.py
.py
62952c89a06eee92
7.93
73
"""Read MCMCSamples from Cobaya chains.""" import os import re import numpy as np from anesthetic.samples import MCMCSamples from pandas import concat def read_paramnames(root): """Read header of ``<root>.1.txt`` to infer the paramnames. This is the data file of the first chain. It should have as many co...
handley-lab/anesthetic
anesthetic/read/cobaya.py
.py
8263d41e9014723c
7.93
73
"""Anesthetic testing utilities.""" import pandas.testing import numpy.testing def assert_frame_equal(left, right, *args, **kwargs): """Assert frames are equal, including metadata.""" check_metadata = kwargs.pop('check_metadata', True) pandas.testing.assert_frame_equal(left, right, *args, **kwargs) nu...
handley-lab/anesthetic
anesthetic/testing.py
.py
4b4b56d6cdec6f8c
7.43
73
from packaging import version import subprocess def run(*args): """Run a bash command and return the output in Python.""" return subprocess.run(args, text=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout de...
handley-lab/anesthetic
bin/utils.py
.py
7c52f346c4d6b5c8
7.93
73
import base64 import json def define_env(env): """ Define macros for MkDocs """ @env.macro def tos_gated_downloads(section_id, files, tos_url="https://www.dasharo.com/pages/terms/", prose_section_id=None): """Render a ToS checkbox that reveals base64-encoded download l...
Dasharo/docs
main.py
.py
3db1f6597e63b7b7
7.88
56
""" Prepare tables and data for other examples """ import datetime import decimal import pprint import random import string import examples._config as config import pyexasol from pyexasol import ExaTimeDelta bool_values = [True, False] user_statuses = ["ACTIVE", "PENDING", "SUSPENDED", "DISABLED"] def users_genera...
exasol/pyexasol
examples/a00_prepare.py
.py
e7d6c1a4addfc03c
7.96
81
""" Abort long-running query from another thread """ import pprint import threading import time import examples._config as config import pyexasol printer = pprint.PrettyPrinter(indent=4, width=140) class QueryThread(threading.Thread): def __init__(self, connection): self.connection = connection ...
exasol/pyexasol
examples/a09_abort_query.py
.py
e36d6a2af3a6815f
7.96
81
""" Parallel HTTP transport EXPORT into multiple independent processes running in parallel """ import multiprocessing import pprint import examples._config as config import pyexasol import pyexasol.callback as cb printer = pprint.PrettyPrinter(indent=4, width=140) class ExportProc(multiprocessing.Process): de...
exasol/pyexasol
examples/b03_parallel_export.py
.py
e6d1b3eb14d33e2b
7.96
81
""" Parallel HTTP transport IMPORT from multiple independent processes running in parallel """ import multiprocessing import pprint import pandas import examples._config as config import pyexasol import pyexasol.callback as cb printer = pprint.PrettyPrinter(indent=4, width=140) class ImportProc(multiprocessing.P...
exasol/pyexasol
examples/b04_parallel_import.py
.py
feeee1a7d393e340
7.96
81
""" Parallel HTTP transport EXPORT data, process it and IMPORT back to Exasol Do it in multiple independent processes running in parallel Compression and encryption are enabled in this example """ import multiprocessing import pprint import examples._config as config import pyexasol import pyexasol.callback as cb ...
exasol/pyexasol
examples/b05_parallel_export_import.py
.py
7cb2d7de05162fe0
7.96
81
""" Attempt to access connection object from multiple threads simultaneously """ import pprint import threading import time import examples._config as config import pyexasol printer = pprint.PrettyPrinter(indent=4, width=140) class QueryThread(threading.Thread): def __init__(self, connection): self.con...
exasol/pyexasol
examples/c12_thread_safety.py
.py
0265b9ecf808d8d9
7.96
81
""" Stress Test 1 DO NOT RUN ON PRODUCTION (!) Apply this command if you have fork-related issues in MacOS: export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES Pushing Exasol server with 100+ sessions running in parallel """ import multiprocessing import pprint import time import examples._config as config import pyexas...
exasol/pyexasol
examples/z01_many_sessions.py
.py
accf367cf6dff64a
7.96
81
""" This module provides `PEP-249`_ DBAPI compliant connection implementation. (see also `PEP-249-connection`_) .. _PEP-249-connection: https://peps.python.org/pep-0249/#connection-objects """ import ssl from functools import wraps import pyexasol from exasol.driver.websocket._cursor import Cursor as DefaultCursor f...
exasol/pyexasol
exasol/driver/websocket/_connection.py
.py
6e8b700027f72b4b
7.96
81
""" E2E test configuration and documentation generation fixtures. Usage in tests: def test_something(page, document): with document.step("Page aufrufen"): page.goto("/") with document.step("Formular ausfüllen"): page.fill("#field", "value") After the test, a markdown file ...
digitalfabrik/lunes-cms
e2e-tests/conftest.py
.py
40701768e7adfd35
8.21
25
""" E2E test: Beruf archivieren und wiederherstellen — generates user_docs/archive_job.md Covers issue #890: a content manager archives a job so it disappears from the default job list (and the API), finds it again via the archive filter, and restores it. """ from typing import Callable import pytest from conftest i...
digitalfabrik/lunes-cms
e2e-tests/test_archive_job.py
.py
5d8998440e2d6cc9
8.21
25
""" E2E test: Login-Flow — generates user_docs/login.md """ from __future__ import annotations from typing import Generator import pytest from conftest import DocPage from playwright.sync_api import Browser, BrowserContext, expect, Page @pytest.fixture def context(browser: Browser) -> Generator[BrowserContext, Non...
digitalfabrik/lunes-cms
e2e-tests/test_login.py
.py
28e030a08abf9538
8.21
25
from __future__ import annotations from typing import Any from django.db.models import QuerySet from rest_framework import mixins, status, viewsets from rest_framework.request import Request from rest_framework.response import Response from rest_framework.throttling import ScopedRateThrottle, SimpleRateThrottle from ...
digitalfabrik/lunes-cms
lunes_cms/analytics/api/views.py
.py
c3371f841a82b2ef
7.71
25
from __future__ import annotations import logging from datetime import date, datetime, timezone import requests from django.conf import settings logger = logging.getLogger(__name__) def _escape_field_string(value: str) -> str: """Escape special characters in InfluxDB line protocol string field values.""" r...
digitalfabrik/lunes-cms
lunes_cms/analytics/influx.py
.py
d300cdfe2f858d5d
7.71
25
from django.db import models class AnalyticsEvent(models.Model): """ Analytics event """ class ExerciseType(models.TextChoices): """ Exercise types matching the app's ExerciseKeys. """ WORD_LIST = "word_list", "Word List" WORD_CHOICE = "word_choice", "Word Cho...
digitalfabrik/lunes-cms
lunes_cms/analytics/models/analytics_event.py
.py
83ea6d5bfba583e7
7.71
25
"""This runs at the init of the doctest pytest session Launch or connect to a persistent local DPF service to be shared in pytest as a session fixture """ import doctest from doctest import DocTestRunner from unittest import mock import pytest from ansys.dpf import core from ansys.dpf.core.misc import module_exists...
ansys/pydpf-core
conftest.py
.py
03c6462b5929a4b9
8.48
91
""" acme-cert-updater update the certificate using ACME and Route 53 """ import os import os.path import pathlib import json import string import tempfile import traceback import urllib.request from datetime import datetime from typing import Dict, Union, List from unittest import mock import logging import boto3 fr...
shogo82148/acme-cert-updater
updater/app.py
.py
5cd061735adf1a81
7.67
21
import csv import re from collections import defaultdict from drgpy._resources import open_text #dx_pttrn = "[A-TV-Z][0-9][0-9AB][0-9A-TV-Z]{0,4}" dx_pttrn = "[A-Z][0-9][0-9AB][0-9A-TV-Z]{0,4}" # NOTE: COVID-19 starts with "U" pr_pttrn = "[A-HJ-NP-Z0-9]{7}" _code_line_re = re.compile( r"(?:[A-HJ-NP-Z0-9]{7}|[A-Z]...
yubin-park/drgpy
drgpy/_mdcsrdr.py
.py
db42b903f19f7851
7.91
65
import os import yaml from logging.config import fileConfig from sqlalchemy import engine_from_config from sqlalchemy import pool from alembic import context # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file fo...
Blockstream/satellite-api
server/alembic/env.py
.py
6346b4f99fda5f14
7.8
38
"""Add tx_retries table Revision ID: 0704901102eb Revises: 5cebc0f48f6e Create Date: 2021-08-02 21:46:46.095406 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '0704901102eb' down_revision = '5cebc0f48f6e' branch_labels = None depends_on = None def upgrade(): ...
Blockstream/satellite-api
server/alembic/versions/0704901102eb_add_tx_retries_table.py
.py
0b9b0b02bd0873a5
7.8
38
"""Add channel to order table Revision ID: 3ec897840ea4 Revises: 0704901102eb Create Date: 2022-04-05 21:57:27.398804 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '3ec897840ea4' down_revision = '0704901102eb' branch_labels = None depends_on = None def upgra...
Blockstream/satellite-api
server/alembic/versions/3ec897840ea4_add_channel_to_order_table.py
.py
5c401adf229bf96d
7.3
38
"""Add regions to orders table Revision ID: 5cebc0f48f6e Revises: c7b63286fd71 Create Date: 2021-07-26 22:38:41.193023 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '5cebc0f48f6e' down_revision = 'c7b63286fd71' branch_labels = None depends_on = None def upgr...
Blockstream/satellite-api
server/alembic/versions/5cebc0f48f6e_add_regions_to_orders_table.py
.py
d03126bb1725589b
7.3
38
from math import ceil from constants import MIN_BID, MIN_PER_BYTE_BID ETH_MTU = 1500 UDP_IP_HEADER = 20 + 8 BLOCKSAT_HEADER = 8 MPE_HEADER = 16 MAX_BLOCKSAT_PAYLOAD = ETH_MTU - (UDP_IP_HEADER + BLOCKSAT_HEADER) def calc_ota_msg_len(msg_len): """Compute the number of bytes sent over-the-air (OTA) for an API messa...
Blockstream/satellite-api
server/bidding.py
.py
7f3cf06dc2f7d6af
7.8
38
import json import logging from datetime import datetime from flask import current_app from sqlalchemy import and_ import constants import order_helpers from database import db from models import Order, TxRetry from regions import region_code_to_number_list from schemas import order_schema def assign_tx_seq_num(ord...
Blockstream/satellite-api
server/transmitter.py
.py
11f2c1c7328bc80b
7.8
38
import json from web3 import Web3, HTTPProvider # import RPi.GPIO as GPIO # for real rasp-pi # from RPiSim.GPIO import GPIO from flask import Flask, render_template # Pin mapping pin_mapping = { 'fourteen': 14, 'fifteen': 15, 'eighteen': 18, 'twentythree': 23, 'twentyfour': 24, 'twentyfive': 25...
Salmandabbakuti/IOT-Blockchain
app.test.py
.py
7f6dc290ebd094aa
7.36
51
from functools import wraps # from flask import current_app from inspect import signature from app import signer_notification from app.encryption import SignedNotification, SignedNotifications def unsign_params(func): """ A decorator that verifies the SignedNotification|SignedNotifications typed argumen...
cds-snc/notification-api
app/annotations.py
.py
daaa4372828d3025
7.89
59
from datetime import datetime, timezone from typing import Tuple from uuid import UUID from flask import current_app from notifications_utils.clients.redis.annual_limit import ( TOTAL_EMAIL_FISCAL_YEAR_TO_YESTERDAY, TOTAL_SMS_BILLABLE_UNITS_FISCAL_YEAR_TO_YESTERDAY, TOTAL_SMS_FISCAL_YEAR_TO_YESTERDAY, ...
cds-snc/notification-api
app/annual_limit_utils.py
.py
53511f41f30674e9
7.89
59
from datetime import datetime import werkzeug from flask import Blueprint, current_app, jsonify, request from app import DATETIME_FORMAT from app.dao.api_key_dao import ( expire_api_key, get_api_key_by_secret, update_compromised_api_key_info, ) from app.dao.fact_notification_status_dao import ( get_ap...
cds-snc/notification-api
app/api_key/rest.py
.py
2c8f622fa3c25a51
7.89
59
import uuid from datetime import datetime, timedelta from io import BytesIO from typing import List import botocore import pytz from boto3 import client, resource from boto3.s3.transfer import TransferConfig from flask import current_app from notifications_utils.s3 import s3upload as utils_s3upload from app.models im...
cds-snc/notification-api
app/aws/s3.py
.py
d463fdbc60bc3cd1
7.89
59
import logging from aws_xray_sdk.core.context import Context from aws_xray_sdk.core.exceptions.exceptions import SegmentNotFoundException log = logging.getLogger(__name__) MISSING_SEGMENT_MSG = "cannot find the current segment/subsegment, please make sure you have a segment open" SUPPORTED_CONTEXT_MISSING = ("RUNTIM...
cds-snc/notification-api
app/aws/xray/context.py
.py
5325bb7279734242
7.89
59
import logging import time from environs import Env from flask import current_app from app.celery.error_registry import classify_error from celery import Celery, Task, signals from celery.signals import worker_process_shutdown # Fallback logger for Celery signal handlers that fire outside of any Flask app # context ...
cds-snc/notification-api
app/celery/celery.py
.py
91e53775d623fcd6
7.89
59
""" Celery error classification for CloudWatch alarm differentiation. Known/expected errors are tagged with a category marker in the logs so that the log filters can distinguish them from truly unexpected errors. """ from enum import Enum from typing import Optional, Tuple # The categories themselves are defined he...
cds-snc/notification-api
app/celery/error_registry.py
.py
1518a05440c869e3
7.89
59
from datetime import datetime from typing import Union from flask import current_app, json from notifications_utils.statsd_decorators import statsd from sqlalchemy.orm.exc import NoResultFound from app import annual_limit_client, notify_celery, statsd_client from app.annual_limit_utils import get_annual_limit_notific...
cds-snc/notification-api
app/celery/process_pinpoint_receipts_tasks.py
.py
6b365ed2c2f576ec
7.89
59
import json from datetime import datetime from typing import Any, Dict, List, Optional, Tuple, TypedDict, cast from flask import current_app from notifications_utils.statsd_decorators import statsd from sqlalchemy.orm.exc import NoResultFound from app import annual_limit_client, bounce_rate_client, notify_celery, sta...
cds-snc/notification-api
app/celery/process_ses_receipts_tasks.py
.py
f7e96ce05a90bf34
7.89
59
from typing import Optional from flask import current_app from notifications_utils.recipients import InvalidEmailError from notifications_utils.statsd_decorators import statsd from sqlalchemy.orm.exc import NoResultFound from app import notify_celery from app.celery.utils import CeleryParams from app.config import Co...
cds-snc/notification-api
app/celery/provider_tasks.py
.py
53acdd0b133c0803
7.89
59
from datetime import datetime, timedelta, timezone from itertools import islice from flask import current_app from notifications_utils.statsd_decorators import statsd from notifications_utils.timezones import convert_utc_to_local_timezone from sqlalchemy import func from sqlalchemy.dialects.postgresql import insert f...
cds-snc/notification-api
app/celery/reporting_tasks.py
.py
a11bf9c93adb5613
7.89
59
from datetime import datetime, timedelta from typing import List, cast from flask import current_app from notifications_utils.statsd_decorators import statsd from sqlalchemy import and_ from sqlalchemy.exc import SQLAlchemyError from app import ( email_bulk, email_normal, email_priority, notify_celery...
cds-snc/notification-api
app/celery/scheduled_tasks.py
.py
ac56b694093642fb
7.89
59
from typing import Any, Dict, Optional from flask import current_app from app import config, models # Default retry periods for sending notifications. RETRY_DEFAULT = 300 RETRY_HIGH = 25 class CeleryParams(object): # Important to load from the object and not the module to avoid # circular imports, back and...
cds-snc/notification-api
app/celery/utils.py
.py
c1557235f2e9deea
7.89
59