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
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :Mod: test_node_store_scope :Synopsis: Tests context isolation of node store. Tests both: Isolation: two concurrent “requests” (threads) don’t see each other’s nodes when each uses its own store scope. Cleanup: the store is cleared even if an e...
PASTAplus/metapype-eml
tests/test_node_store_scope.py
.py
8898ca21073e8622
7.89
5
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :Mod: test_normalize :Synopsis: :Author: servilla :Created: 2/17/24 """ import daiquiri from metapype.model.normalize import normalize logger = daiquiri.getLogger(__name__) def test_normalize_xml(): test_xml = "<?xml version=\"1.0\"?><test a=\" t...
PASTAplus/metapype-eml
tests/test_normalize.py
.py
5fe8a995bc93d1d3
7.89
5
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :Mod: convert :Synopsis: :Author: servilla :Created: 2/9/21 """ from datetime import date import json import logging import os from pathlib import Path import click import daiquiri cwd = os.path.dirname(os.path.realpath(__file__)) logfile = cwd + "/conver...
PASTAplus/metapype-eml
utils/convert.py
.py
1d6c252435dcebf0
7.39
5
"""``logging`` propagation: a record climbs the logger hierarchy. A child logger with no handlers still gets its records delivered -- they propagate up the chain until some ancestor's handler takes them. """ from __future__ import annotations import logging def chain_delivery(sink: list[str]) -> None: """Log o...
SuperElectron/python-design-patterns
patterns/behavioral/chain_of_responsibility/real_world.py
.py
be68db5f7765c9bc
7.15
1
"""The Gang of Four Command: interface, concrete commands, invoker with undo. A text editor whose operations are objects. The invoker keeps history, so undo is popping the stack and asking the command to reverse itself. """ from __future__ import annotations from abc import ABC, abstractmethod class Document: ...
SuperElectron/python-design-patterns
patterns/behavioral/command/naive.py
.py
1d88728fc565785f
7.15
1
"""Commands as callables. For plain deferral, ``functools.partial`` packages the call and its arguments. For undo, a command is a (do, undo) pair -- here a small frozen dataclass of two callables, still no interface or hierarchy. """ from __future__ import annotations from collections.abc import Callable from datacl...
SuperElectron/python-design-patterns
patterns/behavioral/command/pythonic.py
.py
65c03113fcb0d4c1
7.15
1
"""Callbacks in the stdlib are the Command pattern. ``sched.scheduler`` queues (time, priority, action, arguments) records -- commands with metadata -- and its run loop is the invoker. """ from __future__ import annotations import sched class FakeClock: """A clock the scheduler advances by 'sleeping' -- tests ...
SuperElectron/python-design-patterns
patterns/behavioral/command/real_world.py
.py
01babfd978f04619
7.15
1
"""The same grammar as data: nested tuples, one recursive evaluator. Extending the language is a dict entry, not a class. """ from __future__ import annotations import operator from collections.abc import Callable Expr = int | tuple[str, "Expr", "Expr"] OPS: dict[str, Callable[[int, int], int]] = { "+": operat...
SuperElectron/python-design-patterns
patterns/behavioral/interpreter/pythonic.py
.py
97449c787fc49d9a
7.15
1
"""Interpreting with Python's own parser: a safe arithmetic evaluator. ``ast.parse`` builds the tree; a restricted walk evaluates only the node types we allow. User input never reaches eval(). """ from __future__ import annotations import ast import operator from collections.abc import Callable _BINOPS: dict[type[a...
SuperElectron/python-design-patterns
patterns/behavioral/interpreter/real_world.py
.py
4e47aac108c983a9
7.15
1
"""The iterator protocol implemented by hand. The guide's three rules: 1. the iterable's ``__iter__`` returns a new iterator; 2. the iterator's ``__next__`` returns items and raises ``StopIteration``; 3. the iterator's ``__iter__`` returns itself. """ from __future__ import annotations class OddNumbers: """An i...
SuperElectron/python-design-patterns
patterns/behavioral/iterator/naive.py
.py
63818fd0707a5e6e
7.15
1
"""Generators: the iterator pattern as a language feature. A function with ``yield`` returns an object that already implements ``__iter__`` and ``__next__``; the cursor state lives in the paused frame. An ``__iter__`` written as a generator makes a class iterable in one line. """ from __future__ import annotations f...
SuperElectron/python-design-patterns
patterns/behavioral/iterator/pythonic.py
.py
2fb1f10c5b4af265
7.15
1
"""``itertools``: the stdlib's iterator toolbox. Iterators compose: ``count`` is infinite, ``islice`` bounds it, and nothing is computed until iteration demands it. """ from __future__ import annotations import itertools from collections.abc import Iterator def first_n_odd_squares(n: int) -> Iterator[int]: """...
SuperElectron/python-design-patterns
patterns/behavioral/iterator/real_world.py
.py
50b3e3a885a584dd
7.15
1
"""The mediator without a Colleague hierarchy. Widgets take a ``notify`` callable; the coordinator holds every interaction rule in one place and the widgets hold none. """ from __future__ import annotations from collections.abc import Callable class TextField: def __init__(self, notify: Callable[[], None]) -> ...
SuperElectron/python-design-patterns
patterns/behavioral/mediator/pythonic.py
.py
a672c38e0bef6986
7.15
1
"""``queue.Queue``: the mediator between threads. Producer and consumer never reference each other; the queue owns all the coordination (ordering, blocking, thread safety). """ from __future__ import annotations import queue import threading def pipeline(items: list[str]) -> list[str]: """Producer and consumer...
SuperElectron/python-design-patterns
patterns/behavioral/mediator/real_world.py
.py
a0dc547d763b9aff
7.15
1
"""The Gang of Four Memento: originator, opaque memento, caretaker.""" from __future__ import annotations class Memento: """Opaque by convention: only the originator reads its fields.""" def __init__(self, text: str, cursor: int) -> None: self._text = text self._cursor = cursor class Edito...
SuperElectron/python-design-patterns
patterns/behavioral/memento/naive.py
.py
7e69b2ce1a8f43c8
7.15
1
"""``pickle``: mementos that survive the process. dumps() produces an opaque snapshot; loads() restores an equivalent object -- checkpoint/rollback for anything picklable. """ from __future__ import annotations import pickle from dataclasses import dataclass, field @dataclass class Game: level: int = 1 inv...
SuperElectron/python-design-patterns
patterns/behavioral/memento/real_world.py
.py
7db771bfc2f8b144
7.15
1
"""``Future.add_done_callback``: the stdlib observer. Any callable can subscribe to a future's completion; late subscribers to an already-resolved future fire immediately. """ from __future__ import annotations from concurrent.futures import Future def observe_completion() -> list[str]: events: list[str] = [] ...
SuperElectron/python-design-patterns
patterns/behavioral/observer/real_world.py
.py
786141405956edcc
7.15
1
"""Two pythonic state machines. 1. Enum + transition table: the machine is data, visible in one dict. 2. A generator: the suspension point is the state; send() drives it. """ from __future__ import annotations from collections.abc import Generator from enum import Enum, auto class State(Enum): LOCKED = auto() ...
SuperElectron/python-design-patterns
patterns/behavioral/state/pythonic.py
.py
b73593b966a1771a
7.15
1
"""Generators as protocol scanners: frame suspension holds the state. A scanner for BEGIN/END blocks -- no state flag anywhere; being inside the ``while`` loop IS the "in a block" state. """ from __future__ import annotations from collections.abc import Iterable, Iterator def blocks(lines: Iterable[str]) -> Iterat...
SuperElectron/python-design-patterns
patterns/behavioral/state/real_world.py
.py
ad6f9f3c746d96e5
7.15
1
"""Shared fixtures. Pipelines are built but never set to PLAYING, so nothing here opens a socket or needs an RTMP server. rtmp2sink only connects on the transition out of NULL, which makes full pipeline construction safe to assert on in a unit test. """ import os import sys import pytest sys.path.insert(0, os.path....
mishan/videomixer
tests/conftest.py
.py
1f23ccb9f61434d9
7.5
0
import re from .service import Service import logging logger = logging.getLogger(__name__) __all__ = [] __all__.append('AlertConsumer') class AlertConsumer(Service): ''' A base class for implementing custom alert message consumers. One is expected to extend this class in one of two ways: 1. More ad...
driplineorg/dripline-python
dripline/core/alert_consumer.py
.py
30cfb68fbf609d7e
7.3
3
__all__ = [] import scarab from _dripline.core import create_dripline_auth_spec, Core, DriplineConfig, Receiver from .request_sender import RequestSender import logging logger = logging.getLogger(__name__) __all__.append("Interface") class Interface(Core, RequestSender): ''' A class that provides user-frien...
driplineorg/dripline-python
dripline/core/interface.py
.py
b25e8ca817e387b1
7.3
3
__all__ = [] import dripline import importlib.util import inspect import logging logger = logging.getLogger(__name__) __all__.append('ObjectCreator') class ObjectCreator: ''' Mixin class providing the ability to create a class based on a provided configuration dictionary. ''' def __init__(self, **...
driplineorg/dripline-python
dripline/core/object_creator.py
.py
859b754cee54a45f
7.3
3
__all__ = [] import scarab from _dripline.core import op_t, Core, Receiver, MsgRequest, MsgReply, DriplineError import uuid import logging logger = logging.getLogger(__name__) __all__.append("RequestSender") class RequestSender(): ''' A mixin class that provides convenient methods for dripline interactions i...
driplineorg/dripline-python
dripline/core/request_sender.py
.py
2dd41826ef37230e
7.3
3
__all__ = [] import scarab from _dripline.core import _Service, DriplineConfig, create_dripline_auth_spec from .throw_reply import ThrowReply from .object_creator import ObjectCreator from .request_sender import RequestSender from .request_handler import RequestHandler import datetime import logging logger = logging...
driplineorg/dripline-python
dripline/core/service.py
.py
9ae73cc36c32373d
7.3
3
__all__ = [] import scarab from _dripline.core import DL_Success, DL_ServiceError, set_reply_cache from .return_codes import get_return_codes_dict import logging logger = logging.getLogger(__name__) __all__.append('ThrowReply') class ThrowReply(Exception): ''' Exception class for use throughout the codebase ...
driplineorg/dripline-python
dripline/core/throw_reply.py
.py
3ac218f392a5ec4d
7.3
3
''' Contains the base class for adding authentication specifications Intended usage: ''' import scarab import logging logger = logging.getLogger(__name__) __all__ = [] __all__.append('BaseAddAuthSpec') class BaseAddAuthSpec: ''' This class should contain functions to add the authentication specifications ...
driplineorg/dripline-python
dripline/implementations/base_add_auth_spec.py
.py
e5ad8b9556d6a142
7.8
3
''' A Entity is an enhanced implementation of a Dripline Endpoint with simple logging capabilities. The Entitys defined here are more broad-ranging than a single service, obviating the need to define new Entitys for each new service or provider. When implementing a Entity, please remember: - All communication must be ...
driplineorg/dripline-python
dripline/implementations/entity_endpoints.py
.py
fbe8d24ccba1cf7c
7.3
3
import re import socket import threading from dripline.core import Service, ThrowReply import logging logger = logging.getLogger(__name__) __all__ = [] __all__.append('EthernetSCPIService') class EthernetSCPIService(Service): ''' A fairly generic subclass of Service for connecting to ethernet-capable instr...
driplineorg/dripline-python
dripline/implementations/ethernet_scpi_service.py
.py
fcbd45ff6cac9c7c
7.3
3
''' A service for monitoring service heartbeats ''' from __future__ import absolute_import # standard libs import logging import time from datetime import datetime, timedelta from enum import Enum import threading # internal imports from dripline.core import AlertConsumer, Endpoint import scarab __all__ = [] logge...
driplineorg/dripline-python
dripline/implementations/heartbeat_monitor.py
.py
422f054dd87a066f
7.3
3
import json import logging from typing import Any, Dict, Optional from aiohttp import web import scarab from dripline.core import Interface, Message # Correct import paths based on your project structure import dripline.core logger = logging.getLogger(__name__) # logger.setLevel("DEBUG") __all__ = ['HTTPServer'] ...
driplineorg/dripline-python
dripline/implementations/http_server.py
.py
1c8ddaa63bc44456
7.3
3
from dripline.core import calibrate from dripline.core import Entity from dripline.core import ThrowReply from dripline.core import get_return_codes_dict from dripline.core import DL_WarningNoActionTaken __all__ = [] import logging logger=logging.getLogger(__name__) __all__.append("KeyValueStore") class KeyValueStore...
driplineorg/dripline-python
dripline/implementations/key_value_store.py
.py
dd58f773777cc9b5
7.3
3
''' A service for interfacing with SQL database for storage. It is currently only developed and tested against Postgres, but should be relatively straight forward to generalize to support other SQL flavors if there is an interest. Note: services using this module will require sqlalchemy (and assuming we're still using...
driplineorg/dripline-python
dripline/implementations/postgres_interface.py
.py
43b68c2014ba3ec6
7.3
3
''' A Postgres Interface-based logger ''' from __future__ import absolute_import # standard libs import logging # 3rd party libs import sqlalchemy # internal imports from dripline.core import AlertConsumer from .postgres_interface import PostgreSQLInterface __all__ = [] logger = logging.getLogger(__name__) __all...
driplineorg/dripline-python
dripline/implementations/postgres_sensor_logger.py
.py
4ca4bbb8c748ead3
7.3
3
#! /usr/bin/env python import signal import socket import re class SCPICommand: """ This class represents a single SCPI get/set command pair. It can be specified as read-only, in which case the client cannot set a value. """ def __init__(self, command, value, read_only=False): self.comma...
driplineorg/dripline-python
tests/integration/scpi_device/scpi_device.py
.py
d230cef61e6d3418
7.8
3
#!/usr/bin/env python3 """Decode Geneve (UDP 6081) and print outer nodes, VNI, and inner 5-tuple. The signal for "is Cilium/OVS encapsulation working and what's inside". Usage: python3 /app/scripts/cni/geneve_decode.py eth0 python3 /app/scripts/cni/geneve_decode.py eth0 200 python3 /app/scripts/cni/ge...
saidsef/scapy-containerised
scripts/cni/geneve_decode.py
.py
710707747949619e
7.39
5
#!/usr/bin/env python3 """Decode VXLAN (UDP 4789) and print outer nodes, VNI, and inner 5-tuple. The signal for "is encapsulation working and what's actually inside it". Usage: python3 /app/scripts/cni/vxlan_decode.py eth0 python3 /app/scripts/cni/vxlan_decode.py eth0 200 python3 /app/scripts/cni/vxla...
saidsef/scapy-containerised
scripts/cni/vxlan_decode.py
.py
7843a53a3fa36a70
7.39
5
#!/usr/bin/env python3 """Top talkers by bytes. Aggregates by endpoint pair regardless of direction so reply traffic folds into the same row as the request. Usage: python3 /app/scripts/discovery/talkers.py eth0 python3 /app/scripts/discovery/talkers.py eth0 60 python3 /app/scripts/discovery/talkers.py...
saidsef/scapy-containerised
scripts/discovery/talkers.py
.py
3c946b0c1e0f900c
7.39
5
""" Django admin config for Todos """ from django import forms from django.contrib import admin from django.db import models as django_models from simple_history.admin import SimpleHistoryAdmin from chalk.todos import models class LabelAdmin(admin.ModelAdmin): """ Admin interface for managing custom labels. ...
wcjordan/chalk
server/chalk/todos/admin.py
.py
7272fe5c17403e27
7.15
1
""" Django Rest Framework serializers for todos """ from django.core.exceptions import ValidationError from rest_framework import serializers from chalk.todos.models import LabelModel, TodoModel class LabelSerializer(serializers.ModelSerializer): """ Serializer for labels """ class Meta: mod...
wcjordan/chalk
server/chalk/todos/serializers.py
.py
214adeeb36e6742a
7.15
1
""" Views for todo app """ from datetime import datetime, timezone import json import math import random import statistics from django.contrib.auth import authenticate, login from django.shortcuts import redirect from django.core.exceptions import ValidationError from google.cloud import storage from rest_framework im...
wcjordan/chalk
server/chalk/todos/views.py
.py
9eb203f4d06ba4ed
7.15
1
#!/usr/bin/env python3 """ Command-line interface for feature extraction. This module provides a CLI tool to extract features from rrweb session files and save them as JSON files for use by the rule engine or other analysis tools. """ import argparse import logging import os import sys from pathlib import Path from ...
wcjordan/chalk
test_gen/rrweb_ingest/cli.py
.py
6c584ea1fcc0bba6
7.65
1
""" Data models for the rrweb_ingest module. Defines the composite data structure of features we extract when processing an rrweb session """ from dataclasses import dataclass, field from typing import List, Dict, Any from rrweb_util.user_interaction.models import UserInteraction FEATURE_EXTRACTION_VERSION = "0.1" ...
wcjordan/chalk
test_gen/rrweb_ingest/models.py
.py
b2901828616a43ae
7.65
1
""" End-to-End Ingest Pipeline for rrweb session data. This module provides the main entry point for processing rrweb session recordings. It orchestrates the complete pipeline from raw JSON loading through user interaction extraction. """ from collections import defaultdict import json import logging from pathlib imp...
wcjordan/chalk
test_gen/rrweb_ingest/pipeline.py
.py
8cb72a1ff7d4e40a
7.65
1
""" Unit tests for the noise filtering module. Tests the is_low_signal function to ensure proper identification and removal of low-signal events from rrweb sessions. """ # pylint: disable=duplicate-code from rrweb_ingest.filter import is_low_signal from rrweb_util import EventType, IncrementalSource class TestIsLo...
wcjordan/chalk
test_gen/rrweb_ingest/tests/test_filter.py
.py
e16e2835955f84ad
7.65
1
""" Unit tests for the JSON loader module. Tests the load_events function to ensure it properly loads, validates, and sorts rrweb session data from JSON files. """ import json import tempfile import pytest from rrweb_ingest.loader import load_events @pytest.fixture(name="create_input_file") def fixture_create_inp...
wcjordan/chalk
test_gen/rrweb_ingest/tests/test_loader.py
.py
182ecf6017daa23f
7.65
1
""" Integration tests for the end-to-end ingest pipeline. Tests the ingest_session function to ensure proper integration of all preprocessing components and correct handling of various session scenarios and error conditions. """ import json from pathlib import Path import tempfile import pytest from rrweb_ingest.mo...
wcjordan/chalk
test_gen/rrweb_ingest/tests/test_pipeline.py
.py
231204d8e1a91f1d
7.65
1
""" Tests for JSON serialization functionality of rrweb_ingest models. """ import json import pytest from rrweb_ingest.models import ProcessedSession @pytest.fixture(name="basic_processed_session") def fixture_basic_processed_session(basic_user_interaction): """Fixture that provides a basic ProcessedSession ins...
wcjordan/chalk
test_gen/rrweb_ingest/tests/test_serialization.py
.py
b2770d6e2cc3953c
7.65
1
""" Shared constants for rrweb event processing across all modules. """ # pylint: disable=too-few-public-methods class EventType: """rrweb event type constants.""" # sync w/ # https://github.com/rrweb-io/rrweb/blob/4db9782d1278a2b7235ed48162ccedf0e0952113/packages/types/src/index.ts DOM_CONTENT_LOAD...
wcjordan/chalk
test_gen/rrweb_util/constants.py
.py
c1a9cf462c5ad76e
7.65
1
""" Virtual DOM State Management for rrweb Session Feature Extraction. This module handles the initialization and maintenance of a virtual DOM state from rrweb snapshot and mutation events. It creates the initial DOM tree from FullSnapshot events and maintains the evolving DOM based on incremental snapshots through mu...
wcjordan/chalk
test_gen/rrweb_util/dom_state/dom_state_helpers.py
.py
eb5ca9676ee0e013
7.65
1
""" Data models for representing the DOM state, DOM mutations, & UI nodes Designed to be built from rrweb data via extractors """ from dataclasses import dataclass, field from typing import Dict, Any, Optional, List @dataclass class UINode: """ Represents a DOM node with its metadata and hierarchy informatio...
wcjordan/chalk
test_gen/rrweb_util/dom_state/models.py
.py
2d06065d63f03af9
7.65
1
""" UI Metadata Resolution for rrweb Session Feature Extraction. This module provides functions to resolve human-readable context for UI nodes, including semantic attributes, DOM paths, and accessibility information that can be used for behavior analysis and test generation. Configuration: Uses default_dom_path_f...
wcjordan/chalk
test_gen/rrweb_util/dom_state/node_metadata.py
.py
7f9d49107596e1ba
7.65
1
''' Created on May 28, 2022 @author: mballance ''' from astbuilder.cpp_type_name_gen import CppTypeNameGen class CppGenParams(object): @classmethod def gen_ctor_params(cls, c, out): """Returns True if this level (or a previous level) added content""" ret = False if c.super is not ...
mballance-utils/pyastbuilder
src/astbuilder/cpp_gen_params.py
.py
830e775fcbb32131
7
0
''' Created on Sep 13, 2020 @author: ballance ''' from astbuilder.visitor import Visitor from astbuilder.ast_ref import AstRef from toposort import toposort, toposort_flatten #>>> list(toposort({2: {11}, #... 9: {11, 8, 10}, #... 10: {11, 3}, #... 11: {7, 5}, ...
mballance-utils/pyastbuilder
src/astbuilder/linker.py
.py
9f3efb277c0da569
7
0
''' Created on Sep 12, 2020 @author: ballance ''' from _io import StringIO class OutStream(object): def __init__(self): self.ind = "" self.out = StringIO() def print(self, s=""): self.out.write(self.ind + s) def println(self, s=""): self.ou...
mballance-utils/pyastbuilder
src/astbuilder/outstream.py
.py
00017829db8a9371
7
0
''' Created on Mar 22, 2021 @author: mballance ''' from astbuilder.outstream import OutStream class PyExtGenExtDef(object): """Generates the extension-definition python file""" def __init__(self, name, package): self.name = name self.package = package ...
mballance-utils/pyastbuilder
src/astbuilder/pyext_gen_extdef.py
.py
3b3546dd60213aad
7
0
''' Created on Mar 23, 2021 @author: mballance ''' from astbuilder.ast_enum import AstEnum from astbuilder.ast_flags import AstFlags from astbuilder.cpp_gen_ns import CppGenNS from astbuilder.visitor import Visitor class PyExtGenFactory(Visitor): def __init__(self, name, na...
mballance-utils/pyastbuilder
src/astbuilder/pyext_gen_factory.py
.py
255aa514fe7ab52e
7
0
''' Created on May 28, 2022 @author: mballance ''' from astbuilder.pyext_type_name_gen import PyExtTypeNameGen from astbuilder.pyext_type_name_gen_pyi import PyExtTypeNameGenPyi from astbuilder.type_userdef import TypeUserDef from astbuilder.type_pointer import TypePointer from astbuilder.type_scalar import TypeScalar...
mballance-utils/pyastbuilder
src/astbuilder/pyext_gen_params.py
.py
a0241dfb7861a587
7
0
''' Created on Mar 23, 2021 @author: mballance ''' from astbuilder.ast_enum import AstEnum from astbuilder.ast_flags import AstFlags from astbuilder.cpp_gen_ns import CppGenNS from astbuilder.visitor import Visitor class PyExtGenVisitor(Visitor): def __init__(self, name, na...
mballance-utils/pyastbuilder
src/astbuilder/pyext_gen_visitor.py
.py
020db0691c818544
7
0
''' Created on Sep 12, 2020 @author: ballance ''' from enum import Enum, auto class TypeKind(Enum): String = auto() Bool = auto() Uint8 = auto() Int8 = auto() Uint16 = auto() Int16 = auto() Uint32 = auto() Int32 = auto() Uint64 = auto() Int64 = auto() Floa...
mballance-utils/pyastbuilder
src/astbuilder/type_scalar.py
.py
2957aa77eaf9d44e
7
0
"""List-accessor generation, per element shape. `PyExtListAccessorGen.gen()` emits the ListUtil property unconditionally -- def path(self) -> ListUtil: return ListUtil(self.numPath, self.getPath) -- and *then* dispatches on the element type to generate `numPath`/`getPath`. So an element shape with no vis...
mballance-utils/pyastbuilder
tests/unit/test_list_accessors.py
.py
84f9e262e3447b1e
7.5
0
''' Created on Mar 21, 2021 @author: mballance ''' from unit.base_test import BaseTest from astbuilder.gen_cpp import GenCPP from astbuilder.pyext_gen import PyExtGen import importlib import os import subprocess import sys import shutil # Builds the generated .pyx together with the generated C++ AST sources, so the #...
mballance-utils/pyastbuilder
tests/unit/test_pyext.py
.py
9718646ed36c00e1
7.5
0
import logging import os from typing import Any from py_toolkit.exceptions import DbError, MissingOptionalDependencyError logger = logging.getLogger(__name__) try: import psycopg2 # type: ignore[import-untyped] except ModuleNotFoundError: # pragma: no cover psycopg2 = None # type: ignore[assignment] def...
rahilsh/py-toolkit
src/py_toolkit/db/db.py
.py
fa2140ad64c41c2d
7
0
"""Git config file helpers. Modernised replacement for the original ``replace_username_in_git_config.py`` one-off script. The original used Python 2 ``print`` statements and hard-coded paths; these functions are parameterised, typed and logged. """ import logging import os logger = logging.getLogger(__name__) def ...
rahilsh/py-toolkit
src/py_toolkit/git/git_config.py
.py
d72114eb6cdbb0b3
7
0
import logging import os import shutil logger = logging.getLogger(__name__) def make_dir_from_path(path: str) -> None: """Create a directory and all parent directories. Succeeds silently if the directory already exists. Args: path: Directory path to create. Raises: OSError: If the ...
rahilsh/py-toolkit
src/py_toolkit/utils/folder_util.py
.py
c52daa603c940bee
7
0
import json import logging from typing import Any from py_toolkit.exceptions import MissingOptionalDependencyError, XmlError logger = logging.getLogger(__name__) try: import xmltodict # type: ignore[import-untyped] except ModuleNotFoundError: # pragma: no cover xmltodict = None # type: ignore[assignment] ...
rahilsh/py-toolkit
src/py_toolkit/utils/xml_to_json.py
.py
ccf2594b5e167766
7
0
# Copyright 2020 Hoplite Industries, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
HopliteInd/nrdpd-daemon
libnrdpd/config.py
.py
bf2ba2e0a3a4b210
7
0
# Copyright 2020 Hoplite Industries, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
HopliteInd/nrdpd-daemon
libnrdpd/main.py
.py
444e1c7bdafb21ca
7
0
# Copyright 2020 Hoplite Industries, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
HopliteInd/nrdpd-daemon
libnrdpd/schedule.py
.py
fcded174032fa7b0
7
0
# Copyright 2020 Hoplite Industries, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
HopliteInd/nrdpd-daemon
libnrdpd/task.py
.py
26b53a281048b7f3
7
0
# Copyright 2020 Hoplite Industries, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
HopliteInd/nrdpd-daemon
libnrdpd/util.py
.py
148bb71303050cc8
7
0
# -*- coding: utf-8 -*- """datatables.py: Django datatableview_advanced_search""" import functools import logging from django.core.exceptions import FieldError from django.db.models import Q from . import compiler __author__ = "Steven Klass" __date__ = "3/1/18 9:22 AM" __copyright__ = "Copyright 2018 IC Manage. All ...
icmanage/django-datatable-view-adv-query
datatableview_advanced_search/datatables.py
.py
72906e62191ca8a5
7
0
# -*- coding: utf-8 -*- """jira_lex.py: Django datatableview_advanced_search""" import sys import logging from datetime import date __author__ = "Steven Klass" __date__ = "2/28/18 9:20 AM" __copyright__ = "Copyright 2018 IC Manage. All rights reserved." __credits__ = [ "Steven Klass", ] log = logging.getLogger...
icmanage/django-datatable-view-adv-query
datatableview_advanced_search/lexer.py
.py
1a928b4e3dd35d23
7
0
# -*- coding: utf-8 -*- """jira_lex.py: Django datatableview_advanced_search""" import functools import logging import sys import operator from .lexer import AdvancedSearchLexer __author__ = "Steven Klass" __date__ = "2/28/18 9:20 AM" __copyright__ = "Copyright 2018 IC Manage. All rights reserved." __credits__ = [ ...
icmanage/django-datatable-view-adv-query
datatableview_advanced_search/parser.py
.py
65b7d19642d687ee
7
0
import numpy as np def sigmoid(x): return 1 / (1 + np.exp(-x)) def modified_sigmoid(x, scale=1, shift=0): return sigmoid(scale * (x - shift)) def pvalue_to_sigmoid(p_values, scale=0.5, shift=5): p_values = np.atleast_1d(p_values) log_value = -np.log10(p_values) result = np.round(modified_sigmo...
ranking-agent/AnswerCoalesce
src/scoring.py
.py
696d77e59e360493
7.24
2
import logging import json import os import yaml from collections import namedtuple import copy from logging.handlers import RotatingFileHandler from datetime import datetime #loggers = {} class LoggingUtil(object): """ Logging utility controlling format and setting initial logging level """ @staticmethod ...
ranking-agent/AnswerCoalesce
src/util.py
.py
a22435d8521ac31c
7.24
2
#In older versions of AC, we were starting with a file that had already been run, i.e. with the result of a query. # In MCQ we are just taking the stuff to be enriched as part of the query graph itself. # We already have a lot of test cases in that original format, and the point of this is to transform # them into McQ ...
ranking-agent/AnswerCoalesce
tests/InputJson_1.5/transform_to_MCQ.py
.py
ff828ff832a5c446
7.74
2
# This script will upgrade TRAPI messages from 1.4 to 1.5. import os import json def main(): # Get all the TRAPI messages in files called "*_1.4.json" and parse them into "*.json" filenames = [f for f in os.listdir() if f.endswith("_1.4.json")] for filename in filenames: with open(filename,"r") as ...
ranking-agent/AnswerCoalesce
tests/InputJson_1.5/upgrade_json.py
.py
663667a525baa40a
7.74
2
import json def load_jsons(input_json): """Given an MCQ json, get the member_ids of the qnodes""" with open(input_json,'r') as inf: data = json.load(inf) node_ids = set() for nid,node in data['message']['query_graph']['nodes'].items(): if 'member_ids' in node: node_ids.upda...
ranking-agent/AnswerCoalesce
tests/create_test_redis.py
.py
fb0b0c34dc65aa7b
7.74
2
"""Tests for the cached_infer wrapper in src/server.py. These tests mock the inner infer() so they don't require the full graph Redis dataset — only a reachable Redis for the cache itself (which the server already needs anyway, and the user port-forwards from k8s for local runs). """ import asyncio from unittest.mock ...
ranking-agent/AnswerCoalesce
tests/test_infer_cache.py
.py
5f37be43c315a714
7.74
2
import asyncio import src.property_coalescence.property_coalescer as pc def test_get_properties(): pl = pc.PropertyLookup() # 'CHEBI:955' should have 4 roles: 'metabolite', 'plant_metabolite', 'biochemical_role', 'eukaryotic_metabolite' props = pl.lookup_property_by_node('CHEBI:955','biolink:ChemicalEnt...
ranking-agent/AnswerCoalesce
tests/test_property_coalescer.py
.py
ded91f547287058b
7.74
2
"""TRAPI 0.9.2 to 1.0.0. to 1.4""" from collections import defaultdict import pydantic from typing import Literal, List from pydantic import BaseModel from enum import Enum # Currently in use def upgrade_Node(node): """Upgrade Node from 0.9.2 to 1.0.0.""" node = {**node} new = dict() if "categories" i...
ranking-agent/AnswerCoalesce
tests/upgrade_trapi.py
.py
65911442dc5f6dfc
7.74
2
"""asyncio utility functions for mobu.""" import asyncio import contextlib from asyncio import Task from collections.abc import Awaitable, Callable, Coroutine from datetime import timedelta __all__ = [ "schedule_periodic", "wait_first", ] def schedule_periodic( func: Callable[[], Awaitable[None]], inter...
lsst-sqre/mobu
src/mobu/asyncio.py
.py
4557d8fd03bc5256
7.3
3
"""Config dependency.""" import os from pathlib import Path from ..config import Config from ..constants import CONFIGURATION_PATH __all__ = [ "ConfigDependency", "config_dependency", ] class ConfigDependency: """Dependency to manage a cached Mobu configuration. The controller configuration is rea...
lsst-sqre/mobu
src/mobu/dependencies/config.py
.py
327e3cd005fd1d71
7.3
3
"""Request context dependency for FastAPI. This dependency gathers a variety of information into a single object for the convenience of writing request handlers. It also provides a place to store a `structlog.BoundLogger` that can gather additional context during processing, including from dependencies. """ from dat...
lsst-sqre/mobu
src/mobu/dependencies/context.py
.py
3a83a51a6307b1f1
7.3
3
"""Dependencies GitHub CI app functionality.""" from ..models.user import User from ..services.github_ci.ci_manager import CiManager from ..storage.gafaelfawr import GafaelfawrStorage from .config import config_dependency from .context import ContextDependency __all__ = ["CiManagerDependency", "MaybeCiManagerDependen...
lsst-sqre/mobu
src/mobu/dependencies/github.py
.py
9118970c5a2d4160
7.3
3
"""Exceptions for mobu.""" from __future__ import annotations from pathlib import Path from typing import override from fastapi import status from safir.fastapi import ClientRequestError from safir.models import ErrorLocation from safir.slack.blockkit import SlackException, SlackWebException from safir.slack.sentry ...
lsst-sqre/mobu
src/mobu/exceptions.py
.py
d86f2a40cda82967
7.3
3
"""Component factory and process-wide status for mobu.""" from __future__ import annotations import structlog from httpx import AsyncClient from rubin.gafaelfawr import GafaelfawrClient from rubin.repertoire import DiscoveryClient from safir.slack.webhook import SlackWebhookClient from structlog.stdlib import BoundLo...
lsst-sqre/mobu
src/mobu/factory.py
.py
f46877dadf73a178
7.3
3
"""The main application factory for the mobu service.""" from __future__ import annotations import json from collections.abc import AsyncGenerator, Awaitable from contextlib import asynccontextmanager from datetime import timedelta from importlib.metadata import metadata, version import structlog from fastapi import...
lsst-sqre/mobu
src/mobu/main.py
.py
e4a5546729599eee
7.3
3
"""Base models for monkey business.""" from __future__ import annotations from datetime import timedelta from pydantic import BaseModel, ConfigDict, Field from safir.logging import LogLevel from safir.pydantic import HumanTimedelta __all__ = [ "BusinessConfig", "BusinessData", "BusinessOptions", ] cla...
lsst-sqre/mobu
src/mobu/models/business/base.py
.py
c77217f78f8f90fa
7.3
3
"""Models for the Muster monkey business.""" from typing import Literal from pydantic import Field from .base import BusinessConfig, BusinessOptions __all__ = [ "MusterConfig", "MusterOptions", ] class MusterOptions(BusinessOptions): """Options for the Muster monkey business.""" class MusterConfig(B...
lsst-sqre/mobu
src/mobu/models/business/muster.py
.py
358bd882210c5c85
7.3
3
"""Models for the NotebookRunnerCounting monkey business.""" from __future__ import annotations from typing import Literal from pydantic import Field from .base import BusinessConfig from .notebookrunner import NotebookRunnerOptions __all__ = [ "NotebookRunnerCountingConfig", "NotebookRunnerCountingOptions...
lsst-sqre/mobu
src/mobu/models/business/notebookrunnercounting.py
.py
143d7ccda9892309
7.3
3
"""Models for the NubladoPythonLoop monkey business.""" from __future__ import annotations from typing import Literal from pydantic import Field from safir.pydantic import HumanTimedelta from .base import BusinessConfig from .nublado import NubladoBusinessOptions __all__ = [ "NubladoPythonLoopConfig", "Nub...
lsst-sqre/mobu
src/mobu/models/business/nubladopythonloop.py
.py
15c1d3dbf155dae1
7.3
3
"""Models for the SIAQuerySetRunner monkey business.""" from __future__ import annotations from typing import Literal, override from astropy.time import Time from pydantic import BaseModel, Field from .base import BusinessConfig, BusinessData, BusinessOptions __all__ = [ "SIABusinessData", "SIAQuery", ...
lsst-sqre/mobu
src/mobu/models/business/siaquerysetrunner.py
.py
966861b77c840caf
7.3
3
"""Base models for TAP-related monkey business.""" from __future__ import annotations from pydantic import Field from .base import BusinessData, BusinessOptions __all__ = [ "TAPBusinessData", "TAPBusinessOptions", ] class TAPBusinessOptions(BusinessOptions): """Options for any business that runs TAP q...
lsst-sqre/mobu
src/mobu/models/business/tap.py
.py
e051f3788e9f6146
7.3
3
"""Models for the TAPQueryRunner monkey business.""" from __future__ import annotations from typing import Literal from pydantic import Field from .base import BusinessConfig from .tap import TAPBusinessOptions __all__ = [ "TAPQueryRunnerConfig", "TAPQueryRunnerOptions", ] class TAPQueryRunnerOptions(TAP...
lsst-sqre/mobu
src/mobu/models/business/tapqueryrunner.py
.py
85ce9843c3373892
7.3
3
"""Models for the TAPQuerySetRunner monkey business.""" from __future__ import annotations from typing import Literal from pydantic import Field from .base import BusinessConfig from .tap import TAPBusinessOptions __all__ = [ "TAPQuerySetRunnerConfig", "TAPQuerySetRunnerOptions", ] class TAPQuerySetRunne...
lsst-sqre/mobu
src/mobu/models/business/tapquerysetrunner.py
.py
78d54d2eb2e8e137
7.3
3
"""Data models for a monkey.""" from enum import Enum from pydantic import BaseModel, Field from .business.base import BusinessData from .business.notebookrunner import NotebookRunnerData from .business.nublado import NubladoBusinessData from .business.siaquerysetrunner import SIABusinessData from .business.tap impo...
lsst-sqre/mobu
src/mobu/models/monkey.py
.py
e03c1577f3619c02
7.3
3
"""Models related to GitHub repos for the GitHub CI app functionality.""" from __future__ import annotations from dataclasses import dataclass from pathlib import Path from tempfile import TemporaryDirectory from pydantic import ConfigDict from .business.notebookrunner import Filterable __all__ = ["ClonedRepoInfo"...
lsst-sqre/mobu
src/mobu/models/repo.py
.py
43885dde0b1aa035
7.3
3
"""Models for running a single instance of a business by itself.""" from __future__ import annotations from pydantic import BaseModel, Field from .business.business_config_type import BusinessConfigType from .user import User __all__ = ["SolitaryConfig", "SolitaryResult"] class SolitaryConfig(BaseModel): """C...
lsst-sqre/mobu
src/mobu/models/solitary.py
.py
6f17dc1464b85ee5
7.3
3