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 |
|---|---|---|---|---|---|---|
"""Shared SPIRIT1 packet-engine framing configuration."""
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass, field
from .enums import CrcMode
@dataclass
class PacketConfig:
"""Framing settings shared by SPIRIT1 hardware packet formats.
This config de... | zathras777/py-spirit1 | src/spirit1/packet_config.py | .py | 6ce935248a4dee2b | 7.15 | 1 |
"""Declarative configuration for a SPIRIT1 radio."""
from __future__ import annotations
from dataclasses import dataclass
from .enums import Spirit1Modulation
from .frequency import Frequency
@dataclass
class RadioConfig:
"""Settings that can be validated before they are applied to hardware."""
xtal_frequ... | zathras777/py-spirit1 | src/spirit1/radio_config.py | .py | 4fb1cb1281b9d26c | 7.15 | 1 |
"""Raw packet reception."""
from __future__ import annotations
import asyncio
import errno
import logging
from collections.abc import AsyncIterator
from dataclasses import dataclass, field
from typing import Protocol
from .device import Spirit1Device
from .irq import IRQ, SpiritIrq
from .registers import Spirit1Regi... | zathras777/py-spirit1 | src/spirit1/receiver.py | .py | a2d539de0265991a | 7.15 | 1 |
"""Coordinated half-duplex SPIRIT1 receive and transmit sessions."""
from __future__ import annotations
import asyncio
import logging
from collections.abc import AsyncGenerator
from typing import Callable, Generic, Protocol, TypeVar, overload
from .basic_packet import BasicPacket, BasicPacketMessage
from .device imp... | zathras777/py-spirit1 | src/spirit1/session.py | .py | 601e3955f5ff3b8e | 7.15 | 1 |
"""Experimental support for SPIRIT1 STack packets.
STack's automatic acknowledgement, retransmission, and sequence-number
behaviour has not been verified against hardware in this project. Treat this
module as experimental until it has been exercised with compatible devices.
"""
from __future__ import annotations
im... | zathras777/py-spirit1 | src/spirit1/stack_packet.py | .py | 98571f4af187126e | 7.15 | 1 |
from django.db.models.signals import m2m_changed
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.core.cache import cache
from django.contrib.auth.models import User, Group
from .models import Company, Industry, Category, stakeholderGroups, Stage, ProductGroup... | osu-cass/hemp-db | helloworld/signals.py | .py | 47e902a100a9959d | 7.24 | 2 |
"""Health checks for container orchestration."""
import logging
from uuid import uuid4
from django.core.cache import cache
from django.db import connections
from django.http import JsonResponse
from django.views.decorators.http import require_GET
logger = logging.getLogger(__name__)
CACHE_HEALTH_KEY = 'hempdb-healt... | osu-cass/hemp-db | hempdb/health.py | .py | 671aec23fb79787a | 7.24 | 2 |
import json
import os
from django.conf import settings
from .csp import REPORTING_GROUP, validate_report_uri
class PermissionsPolicyMiddleware:
"""Add the configured Permissions-Policy header to responses."""
def __init__(self, get_response):
"""Store the next middleware callable."""
self.g... | osu-cass/hemp-db | hempdb/middleware.py | .py | 744a546b99469dfc | 7.24 | 2 |
from pathlib import Path
from dotenv import load_dotenv
import os
import ssl
import dj_database_url
import sentry_sdk
from hempdb.csp import build_csp_directives, validate_report_uri
load_dotenv()
def env_value(name, default=None):
"""Read an environment value or its Docker secret file."""
file_path = os.ge... | osu-cass/hemp-db | hempdb/settings.py | .py | aafabd4a7514de3a | 7.24 | 2 |
from django.contrib.auth import get_user_model
from django.test import TestCase
class LogoutTests(TestCase):
"""Verify the Django 5 POST-only logout flow."""
def setUp(self):
"""Create and authenticate a user."""
self.user = get_user_model().objects.create_user(
username='logout-u... | osu-cass/hemp-db | hempdb/tests/test_auth.py | .py | 88629f44bc71c156 | 7.74 | 2 |
from unittest.mock import patch
from django.test import SimpleTestCase, override_settings
class HealthViewTests(SimpleTestCase):
"""Verify the container health endpoints."""
def test_liveness_does_not_check_dependencies(self):
"""Liveness succeeds without accessing backing services."""
with ... | osu-cass/hemp-db | hempdb/tests/test_health.py | .py | 9e704df2c9368354 | 7.74 | 2 |
import os
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
from django.test import SimpleTestCase
from hempdb.settings import database_configuration, database_ssl_options, env_value
class EnvironmentValueTests(SimpleTestCase):
"""Verify environment and Docker secr... | osu-cass/hemp-db | hempdb/tests/test_settings.py | .py | b5ba1c4b819b30fd | 7.74 | 2 |
# 20 november 2025 - Dick van Mersbergen / Jonathan Blok
# Dit script voegt in bulk een nieuw veld toe aan bestaande pagina's op de Kennisbank
import getpass
from urllib.error import URLError
from requests import JSONDecodeError, Session
import pandas as pd
import mwparserfromhell as mwp
TEST = True
def get_session(... | cultureelerfgoed/kennisbank | src/batch_add_pages.py | .py | ee69861f895031f1 | 7 | 0 |
# 20 november 2025 - Dick van Mersbergen / Jonathan Blok
# Dit script voegt in bulk een nieuw veld toe aan bestaande pagina's op de Kennisbank
import getpass
from urllib.error import URLError
from requests import JSONDecodeError, Session
import pandas as pd
import mwparserfromhell as mwp
TEST = True
def get_session(... | cultureelerfgoed/kennisbank | src/batch_edit_pages.py | .py | aeaf64825b59512d | 7 | 0 |
import json
import os
import logging
import requests
from rdflib import Graph, Literal, URIRef
from rdflib.namespace import RDF, SDO
from _CEO import CEO
GRAPH_ID = os.getenv('GRAPH_ID', 'default')
OUTPUT_FILE_FORMAT = os.getenv('OUTPUT_FILE_FORMAT', 'json-ld')
TARGET_FILEPATH = os.getenv('TARGET_FILEPATH',... | cultureelerfgoed/kennisbank | src/extract_monumenten_service.py | .py | 6f23c534949abcee | 7 | 0 |
import time
import datetime
import requests
import numpy as np
from support import logger
from bs4 import BeautifulSoup
def date_convert(time_str:str)->datetime:
dateOb = datetime.datetime.strptime(time_str, "%a, %d %b %Y %H:%M:%S %Z")
return dateOb
def get_articles(result:BeautifulSoup, cat:str, source:str, ... | Landcruiser87/newsbyrob | scripts/aila.py | .py | 4269643e89349390 | 7.15 | 1 |
import time
import datetime
from support import logger
from bs4 import BeautifulSoup
from playwright.sync_api import sync_playwright
from playwright._impl._errors import Error as PlaywrightError
def date_convert(time_str:str)->datetime:
# _.strftime("%a, %d %b %y %H:%M:%S %z") #To verify correct converstion
# ... | Landcruiser87/newsbyrob | scripts/boundless.py | .py | bf25c407852e5e17 | 7.15 | 1 |
import logging
from bs4 import BeautifulSoup
import requests
import time
import datetime
def date_convert(time_str:str)->datetime:
# _.strftime("%a, %d %b %Y %H:%M:%S %z") #To verify correct converstion
dateOb = datetime.datetime.strptime(time_str, "%a, %d %b %Y %H:%M:%S %z")
return dateOb
def get_article... | Landcruiser87/newsbyrob | scripts/cbp.py | .py | d8570fd9e9f8712f | 7.15 | 1 |
import time
import datetime
import requests
from support import logger
from bs4 import BeautifulSoup
def date_convert(time_str:str)->datetime:
# _.strftime("%a, %d %b %y %H:%M:%S %z") #To verify correct converstion
dateOb = datetime.datetime.strptime(time_str, "%a, %d %b %Y %H:%M:%S %Z")
return dateOb
def... | Landcruiser87/newsbyrob | scripts/g_news.py | .py | a59b113da3955abe | 7.15 | 1 |
import time
import datetime
# import requests
import curl_cffi as cf
from support import logger, USER_AGENTS, chrome_version
from bs4 import BeautifulSoup
def date_convert(time_str:str)->datetime:
# dateOb.strftime("%a, %d %b %Y %H:%M:%S %z") #To verify correct converstion
dateOb = datetime.datetime.strptime(t... | Landcruiser87/newsbyrob | scripts/ice.py | .py | 217c0406ea2bcd1a | 7.15 | 1 |
import time
import datetime
import requests
from support import logger
from bs4 import BeautifulSoup
def date_convert(time_str:str)->datetime:
# _.strftime("%a, %d %b %Y %H:%M:%S %z") #To verify correct converstion
dateOb = datetime.datetime.strptime(time_str, "%a, %d %b %Y")
return dateOb
def get_article... | Landcruiser87/newsbyrob | scripts/travel.py | .py | 93b0fc9af4092a79 | 7.15 | 1 |
import time
import datetime
# import requests
import curl_cffi as cf
from support import logger, USER_AGENTS, chrome_version
from bs4 import BeautifulSoup
def date_convert(time_str:str)->datetime:
# _.strftime("%a, %d %b %y %H:%M:%S %z") #To verify correct converstion
dateOb = datetime.datetime.strptime(time_s... | Landcruiser87/newsbyrob | scripts/uscis.py | .py | 12718f70717ac9a9 | 7.15 | 1 |
class Doc:
"""Define the documentation of a type annotation using `Annotated`, to be
used in class attributes, function and method parameters, return values,
and variables.
The value should be a positional-only string literal to allow static tools
like editors and documentation generators t... | ghkdqhrbals/portfolios | venv/lib/python3.12/site-packages/annotated_doc/main.py | .py | e597efc6ff344b0c | 7 | 0 |
import math
import sys
import types
from dataclasses import dataclass
from datetime import tzinfo
from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, SupportsFloat, SupportsIndex, TypeVar, Union
if sys.version_info < (3, 8):
from typing_extensions import Protocol, runtime_checkable
else:
from ... | ghkdqhrbals/portfolios | venv/lib/python3.12/site-packages/annotated_types/__init__.py | .py | 4729cbb112941062 | 7 | 0 |
import math
import sys
from datetime import date, datetime, timedelta, timezone
from decimal import Decimal
from typing import Any, Dict, Iterable, Iterator, List, NamedTuple, Set, Tuple
if sys.version_info < (3, 9):
from typing_extensions import Annotated
else:
from typing import Annotated
import annotated_t... | ghkdqhrbals/portfolios | venv/lib/python3.12/site-packages/annotated_types/test_cases.py | .py | cc7157e84a5c31b1 | 7.5 | 0 |
from __future__ import annotations
import math
import sys
import threading
from collections.abc import Awaitable, Callable, Generator
from contextlib import contextmanager
from contextvars import Token
from importlib import import_module
from typing import TYPE_CHECKING, Any, TypeVar
from ._exceptions import NoEventL... | ghkdqhrbals/portfolios | venv/lib/python3.12/site-packages/anyio/_core/_eventloop.py | .py | 73611d7015fec672 | 7 | 0 |
from __future__ import annotations
from collections.abc import Awaitable, Generator
from typing import Any, cast
from ._eventloop import get_async_backend
class TaskInfo:
"""
Represents an asynchronous task.
:ivar int id: the unique identifier of the task
:ivar parent_id: the identifier of the pare... | ghkdqhrbals/portfolios | venv/lib/python3.12/site-packages/anyio/_core/_testing.py | .py | bbb30fa865f0a53c | 7.5 | 0 |
from __future__ import annotations
from collections.abc import Callable, Mapping
from typing import Any, TypeVar, final, overload
from ._exceptions import TypedAttributeLookupError
T_Attr = TypeVar("T_Attr")
T_Default = TypeVar("T_Default")
undefined = object()
def typed_attribute() -> Any:
"""Return a unique ... | ghkdqhrbals/portfolios | venv/lib/python3.12/site-packages/anyio/_core/_typedattr.py | .py | 3f8a33662927dfe0 | 7 | 0 |
from __future__ import annotations
from abc import ABCMeta, abstractmethod
from types import TracebackType
from typing import TypeVar
T = TypeVar("T")
class AsyncResource(metaclass=ABCMeta):
"""
Abstract base class for all closeable asynchronous resources.
Works as an asynchronous context manager which... | ghkdqhrbals/portfolios | venv/lib/python3.12/site-packages/anyio/abc/_resources.py | .py | 0eb62f90d375847e | 7 | 0 |
from __future__ import annotations
import sys
from abc import ABCMeta, abstractmethod
from collections.abc import Awaitable, Callable
from types import TracebackType
from typing import TYPE_CHECKING, Any, Protocol, overload
if sys.version_info >= (3, 13):
from typing import TypeVar
else:
from typing_extension... | ghkdqhrbals/portfolios | venv/lib/python3.12/site-packages/anyio/abc/_tasks.py | .py | 282ef0adc884e3c0 | 7 | 0 |
from __future__ import annotations
import types
from abc import ABCMeta, abstractmethod
from collections.abc import AsyncGenerator, Callable, Coroutine, Iterable
from typing import Any, TypeVar
_T = TypeVar("_T")
class TestRunner(metaclass=ABCMeta):
"""
Encapsulates a running event loop. Every call made thr... | ghkdqhrbals/portfolios | venv/lib/python3.12/site-packages/anyio/abc/_testing.py | .py | b41254ce449f3972 | 7.5 | 0 |
from __future__ import annotations
__all__ = (
"BlockingPortal",
"BlockingPortalProvider",
"check_cancelled",
"run",
"run_sync",
"start_blocking_portal",
)
import sys
from collections.abc import Awaitable, Callable, Generator
from concurrent.futures import Future
from contextlib import (
A... | ghkdqhrbals/portfolios | venv/lib/python3.12/site-packages/anyio/from_thread.py | .py | 2fed30d47c49e814 | 7 | 0 |
from __future__ import annotations
__all__ = (
"EventLoopToken",
"RunvarToken",
"RunVar",
"checkpoint",
"checkpoint_if_cancelled",
"cancel_shielded_checkpoint",
"current_token",
)
import enum
from dataclasses import dataclass
from types import TracebackType
from typing import Any, Generic,... | ghkdqhrbals/portfolios | venv/lib/python3.12/site-packages/anyio/lowlevel.py | .py | 03228b54adcb6964 | 7 | 0 |
#%%
import pandas as pd
import numpy as np
# importing spark session
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.functions import col, count, when, isnan, isnull, mean, min, max
# data visualization modules
import matplotlib.pyplot as plt
import seaborn as sns
import pl... | EllaN12/Customer_Churn_Analysis | Phase_1_ML_Analysis/Decision_Tress_analysis.py | .py | f2396410ab0dc46a | 7 | 0 |
"""
Shared output-path configuration for Phase 4 scripts.
All results are written under Phase_4_implementation_and_Monitoring/Results/.
"""
from pathlib import Path
results_dir = Path(__file__).resolve().parent / "Results"
visualizations_dir = results_dir / "visualizations"
reports_dir = results_dir / "reports"
moni... | EllaN12/Customer_Churn_Analysis | Phase_4_implementation_and_Monitoring/config.py | .py | 965fef7824fe7769 | 7 | 0 |
#!/usr/bin/env python3
"""Pure exact-revision contract for the P2 AdGuard transition."""
import re
HEX64=re.compile(r"^[0-9a-f]{64}$")
COMMITS={"forward":"9969e35dca0cfb49a68bda3ba10156667cd4b53f","rollback":"b676063eafa53c00947c458d631493f98349f63c"}
TREES={"forward":"64d61bb25e0ee7cadda556e54ec86c4faf4f1fd8","rollba... | ErikBPF/desktop-nixos | modules/hosts/discovery/_stateful-adguard-transition-revision.py | .py | 0ba6de7a47b3e6df | 7 | 0 |
"""rtk-rewrite — compress terminal output by rewriting commands through rtk.
Registers a ``pre_tool_call`` hook that rewrites the terminal tool's
``command`` to its ``rtk <cmd>`` form via ``rtk rewrite``. The hook receives
the live ``args`` dict by reference (see
``hermes_cli.plugins.get_pre_tool_call_block_message`` ... | ErikBPF/desktop-nixos | modules/hosts/discovery/hermes-plugins/rtk-rewrite/__init__.py | .py | eb9066b8b5c52f07 | 7 | 0 |
#!/usr/bin/env python3
"""DS8 ha-harness SecretSpec runtime wiring contract."""
from __future__ import annotations
import pathlib
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[2]
COMPOSE = ROOT / "modules/hosts/discovery/compose.nix"
class HaHarnessCutoverTest(unittest.TestCase):
def test_di... | ErikBPF/desktop-nixos | tests/discovery-secret-contract/test_ha_harness_cutover.py | .py | 42bd6d9249590dfb | 7.5 | 0 |
#!/usr/bin/env python3
"""Homepage SecretSpec runtime wiring contract."""
from __future__ import annotations
import pathlib
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[2]
COMPOSE = ROOT / "modules/hosts/discovery/compose.nix"
class HomepageCutoverTest(unittest.TestCase):
def test_homepage_... | ErikBPF/desktop-nixos | tests/discovery-secret-contract/test_homepage_cutover.py | .py | d0ad5aeaefd38073 | 7.5 | 0 |
import mne
import numpy as np
import pandas as pd
import os
import networkx as nx
from glob import glob
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, make_scorer
fro... | amirhossein-eskorouchi/ML-PSG-ADHD-Analysis | reference_implementations/published_pipeline/ADHD_Final_Code.py | .py | 9e4ef5baa345b836 | 7.15 | 1 |
"""Graph-based PSG feature extraction.
This module reconstructs the graph-feature calculations used in the
historical ML-PSG-ADHD analysis.
The primary goal at this stage is behavioral fidelity to the historical
implementation preserved in:
reference_implementations/published_pipeline/
Feature extraction (Sl... | amirhossein-eskorouchi/ML-PSG-ADHD-Analysis | src/psg_adhd/graph_features.py | .py | f43b519e4353854f | 7.15 | 1 |
"""Generate fully artificial MNE Epochs data for software demonstrations.
The synthetic PSG data created by this module are completely artificial.
They:
- do not contain study-participant data;
- are not anonymized or transformed clinical recordings;
- do not reproduce the original PSG signal distributions;
- are no... | amirhossein-eskorouchi/ML-PSG-ADHD-Analysis | src/psg_adhd/synthetic_psg.py | .py | c04b72c68cdcc3f4 | 7.15 | 1 |
import json
import logging
from time import perf_counter
from typing import Dict, List, Optional
from urllib.parse import urlparse
import numpy as np
from tritonclient.utils import InferenceServerException
logger = logging.getLogger("ALS Model")
logger.setLevel(logging.INFO)
class TritonModelClient:
"""
A w... | epoch8/smartrec | smartrec-client/smartrec_client/triton_client.py | .py | 107234bf07f6ff05 | 7 | 0 |
import typing as tp
import pandas as pd
from rectools import Columns
from rectools.dataset import Dataset
from rectools.metrics import MAP, Precision, Recall, calc_metrics
from rectools.model_selection import TimeRangeSplitter
from smartrec_lib.research.covis import CoVisModel
# Most-recent-first external session it... | epoch8/smartrec | smartrec-lib/smartrec_lib/evaluation/next_item.py | .py | ed7a1d4663aa2f8e | 7 | 0 |
"""Co-visitation algorithm kernel - shared by both layers, belongs to neither.
Layer L1 (see ../../CLAUDE.md). Generic over the item id type: it groups, counts
and sorts ids but never converts them, which is what lets the serving layer keep
external tour-id strings and the research layer keep rectools internal ints.
... | epoch8/smartrec | smartrec-lib/smartrec_lib/kernels/cooccurrence.py | .py | c1f383eafa1c366e | 7 | 0 |
import typing as tp
def rrf_fuse(
rankings: tp.Mapping[str, tp.Sequence[tp.Any]],
weights: tp.Mapping[str, float],
rrf_k: int = 60,
) -> tp.List[tp.Tuple[tp.Any, float]]:
"""
Weighted Reciprocal Rank Fusion.
score(item) = sum over sources of weight_s / (rrf_k + rank_s(item)), ranks
are 1-... | epoch8/smartrec | smartrec-lib/smartrec_lib/kernels/fusion.py | .py | 5378177397229144 | 7 | 0 |
from datetime import timedelta
from enum import Enum
from typing import Any, Dict, List, Literal, Optional, Union
from pydantic import BaseModel, Field
from pydantic_settings import BaseSettings
class RecomItems(BaseModel):
item_ids: List[str]
scores: List[float]
strategy: Optional[str] = None
class Co... | epoch8/smartrec | smartrec-lib/smartrec_lib/model.py | .py | e1a0c72b14fc7549 | 7 | 0 |
"""Layer: serving. Triton loads this module, its artifact goes to S3.
Layer L2. May depend on `smartrec_lib.model` (settings, `Strategy`), `kernels/`
and `save_and_load_triton_models`. Must NOT depend on `research/` or
`evaluation/`. `RecommenderCoVis` and `CoVisSettings` are reconstructed by
module path from pickles ... | epoch8/smartrec | smartrec-lib/smartrec_lib/recommenders/recommender_covis.py | .py | 05c4a8f35e66f073 | 7 | 0 |
"""Layer L3: the research co-visitation model. Shares one algorithm with the
serving shell (`recommenders/recommender_covis.py`) via `kernels.cooccurrence`;
the two differ only in the explicit parameters they pass, which is exactly what
`tests/test_covis_equivalence.py` pins.
"""
import typing as tp
from collections i... | epoch8/smartrec | smartrec-lib/smartrec_lib/research/covis.py | .py | de109cc390c26ccb | 7 | 0 |
import logging
import os
import tempfile
from pathlib import Path
from typing import Any
import dill
import fsspec
from pathy import Pathy
CURRENT_DIR = Path(__file__).parent
SERVING_FOLDER_PATH = CURRENT_DIR.parent / "smartrec_lib/serving"
logger = logging.getLogger("ALS Model saving stage:")
def get_s3_filesyste... | epoch8/smartrec | smartrec-lib/smartrec_lib/save_and_load_triton_models.py | .py | 5bc474e0cfb9056c | 7 | 0 |
import json
import os
import sys
import logging
from time import perf_counter
import dill
import numpy as np
import pandas as pd
import triton_python_backend_utils as pb_utils
from smartrec_lib.recommenders import (
RecommenderALS,
RecommenderCoVis,
RecommenderEASE,
RecommenderModelSet,
Recommende... | epoch8/smartrec | smartrec-lib/smartrec_lib/serving/model.py | .py | 3fee0fc91ed1736c | 7 | 0 |
import pandas as pd
from rectools import Columns
from rectools.dataset import Dataset
from rectools.models import model_from_config
from smartrec_lib.research import CoVisModel
def _internal(dataset, external_id):
return int(dataset.item_id_map.convert_to_internal([external_id])[0])
def test_fit_builds_symmetri... | epoch8/smartrec | smartrec-lib/tests/test_covis_model.py | .py | 1eeb4656d410e7e3 | 7.5 | 0 |
"""Tests for the "sw" scoring variant (COVIS_SESSION_WEIGHTS): seed recency is
multiplied by the API event weight carried in "tour_id:weight" history entries.
Uses the shared synthetic dataset from conftest.py. With COVIS_MIN_COOC=2 the
relevant neighbor counts are: m1 -> m2(2), pop1(2); t1 -> t2(2), pop1(2).
"""
fro... | epoch8/smartrec | smartrec-lib/tests/test_covis_session_weights.py | .py | 9cbfb02e4c139d5a | 7.5 | 0 |
from rectools.dataset import Dataset
from rectools.model_selection import TimeRangeSplitter
from rectools.models.serialization import model_from_config
from smartrec_lib.evaluation import evaluate_e2e
from smartrec_lib.evaluation.next_item import _fold_frames
POLICY_CONFIG = {
"cls": "smartrec_lib.research.policy... | epoch8/smartrec | smartrec-lib/tests/test_evaluation_e2e.py | .py | 193fd762c0ea7fb2 | 7.5 | 0 |
"""Unit tests for the L1 co-visitation kernel.
The kernel is the one implementation behind both the serving shell
(`recommenders/recommender_covis.py`) and the research model
(`research/covis.py`), so its four parameters are tested here directly rather
than only through whichever caller happens to exercise them.
"""
... | epoch8/smartrec | smartrec-lib/tests/test_kernels_cooccurrence.py | .py | 805bf46ba70b873c | 7.5 | 0 |
"""What Triton actually loads, per pickle shape.
`serving/model.py` is the deployed file - the trainer overwrites it in S3 on every
run - and its `_load_model` picks the class that will answer every request. It
cannot go by artifact name: `als_covis_youtravel` was a RecommenderALS __dict__
before 2026-08-22 and is a R... | epoch8/smartrec | smartrec-lib/tests/test_serving_loader.py | .py | cea98e273692e193 | 7.5 | 0 |
import requests
from datetime import datetime
import pandas as pd
class Zhihu:
"""
知乎热榜
"""
def __init__(self):
self.hot_lists_api = 'https://api.zhihu.com/topstory/hot-lists/total' # 热榜api
self.recommend_lists_api = 'https://api.zhihu.com/topstory/recommend' # 推荐api
self.he... | clgtc/zhihu_hotpoint | dailyUpdate.py | .py | 29cf280c2007d9d8 | 7.24 | 2 |
#!/usr/bin/env python3
#
# Copyright this project and it's contributors
# SPDX-License-Identifier: Apache-2.0
#
# encoding=utf8
import logging
from contextlib import suppress
import os
import re
from urllib.parse import urlparse
## third party modules
import ruamel.yaml
import requests
from lfx_landscape_tools.membe... | jmertic/lfx-landscape-tools | lfx_landscape_tools/landscapemembers.py | .py | 6ecf7e6da49ebd19 | 7.15 | 1 |
#!/usr/bin/env python3
#
# Copyright this project and it's contributors
# SPDX-License-Identifier: Apache-2.0
#
# encoding=utf8
import logging
# third party modules
import requests
import requests_cache
from lfx_landscape_tools.members import Members
from lfx_landscape_tools.member import Member
from lfx_landscape_t... | jmertic/lfx-landscape-tools | lfx_landscape_tools/lfxmembers.py | .py | 8057679daa388e37 | 7.15 | 1 |
#!/usr/bin/env python3
#
# Copyright this project and it's contributors
# SPDX-License-Identifier: Apache-2.0
#
# encoding=utf8
import logging
# third party modules
import requests
import requests_cache
from urllib.parse import urlparse
from lfx_landscape_tools.members import Members
from lfx_landscape_tools.member ... | jmertic/lfx-landscape-tools | lfx_landscape_tools/lfxprojects.py | .py | 639e36c4e0047dc9 | 7.15 | 1 |
#!/usr/bin/env python3
#
# Copyright this project and it's contributors
# SPDX-License-Identifier: Apache-2.0
#
# encoding=utf8
## built in modules
import re
from abc import ABC, abstractmethod
from typing import Self
import logging
## third party modules
from url_normalize import url_normalize
from lfx_landscape_to... | jmertic/lfx-landscape-tools | lfx_landscape_tools/members.py | .py | 72cec9891fd1bda4 | 7.15 | 1 |
#!/usr/bin/env python3
#
# Copyright this project and it's contributors
# SPDX-License-Identifier: Apache-2.0
#
# encoding=utf8
## built in modules
import os
import tempfile
from pathlib import Path
from slugify import slugify
from typing import Self
import logging
## third party modules
import requests
from requests... | jmertic/lfx-landscape-tools | lfx_landscape_tools/svglogo.py | .py | a3c75041f8c340b0 | 7.15 | 1 |
#!/usr/bin/env python3
#
# Copyright this project and it's contributors
# SPDX-License-Identifier: Apache-2.0
#
# encoding=utf8
import unittest
from unittest.mock import patch, MagicMock, mock_open
import sys
import argparse
from datetime import datetime
import logging
from lfx_landscape_tools.cli import Cli
class T... | jmertic/lfx-landscape-tools | test/test_cli.py | .py | 31f1c7db4389c973 | 7.65 | 1 |
import boto3
import os
import json
import requests
import glueops.setup_logging
import glueops.getoutline
from aws import AWSOrganization
GETOUTLINE_API_URL = "https://glueops.getoutline.com"
REQUIRED_ENV_VARS = [
"GETOUTLINE_DOCUMENT_ID",
"GETOUTLINE_API_TOKEN",
"AWS_CREDENTIALS_JSON"
]
OPTIONAL_ENV_VARS... | GlueOps/getoutline-docs-update-aws-organizations | app/main.py | .py | f906c138c8e056bb | 7 | 0 |
"""Resolve shared OSWM identity assets from the canonical JSON manifest."""
from functools import lru_cache
import json
from pathlib import Path
from typing import Any, Iterator
CODEBASE_ROOT = Path(__file__).resolve().parent
BRANDING_MANIFEST_PATH = CODEBASE_ROOT / "assets" / "branding" / "manifest.json"
@lru_cac... | kauevestena/oswm_codebase | branding.py | .py | b4777ac79b360e63 | 7.15 | 1 |
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from datetime import datetime
from functions import *
from branding import branding_asset_url
# from constants import *
import geopandas as gpd
import pandas as pd
import altair as alt
alt.data_transformers.disabl... | kauevestena/oswm_codebase | dashboard/statistics_funcs.py | .py | 000d9709bf6dcb3f | 7.15 | 1 |
"""
Completeness analysis runner for OSWM.
Hybrid pipeline:
- Current month: computed from local GeoParquet data (fast, offline)
- Historical months: OHSOME API at Z15 (fewer calls than Z17)
First run: 3 prior months via OHSOME + current month local = 4 timestamps
Monthly: +1 current (local) + -1 historical (OHSO... | kauevestena/oswm_codebase | data_quality/completeness/completeness_runner.py | .py | 3bcd6e3876836fa8 | 7.15 | 1 |
"""Stable temporal-attribute lookups for OSM-derived feature tables."""
from __future__ import annotations
from typing import Any
import pandas as pd
TEMPORAL_COLUMNS = ("age", "last_update")
def build_temporal_lookup(frame: pd.DataFrame) -> dict[object, dict[str, Any]]:
"""Index temporal values without assu... | kauevestena/oswm_codebase | data_quality/temporal_lookup.py | .py | 7176dae375bfbd79 | 7.15 | 1 |
# from constants import *
from versioning_funcs import *
import geopandas as gpd
import pandas as pd
from tqdm import tqdm
from concurrent.futures import ThreadPoolExecutor, as_completed
import osmapi
"""
This script stores the versioning info of the OSM Features.
Uses batch API calls (WaysGet/NodesGet) wit... | kauevestena/oswm_codebase | getting_feature_versioning_data.py | .py | 78f84b6f677bf831 | 7.15 | 1 |
#!/usr/bin/env python3
"""Compatibility wrapper for the generic ACPX trigger eval runner."""
from __future__ import annotations
import os
import sys
from pathlib import Path
SKILL_DIR = Path(__file__).resolve().parents[1]
SKILLS_ROOT = Path(__file__).resolve().parents[2]
TARGET = SKILLS_ROOT / "adapting-skill-creat... | nisavid/dotfiles | home/dot_agents/skills/getting-prs-merged/scripts/acpx_trigger_eval.py | .py | 2a3418ada49fa9d2 | 7.15 | 1 |
#!/usr/bin/env python3
"""Compatibility wrapper for the generic Claude Code trigger eval runner."""
from __future__ import annotations
import os
import sys
from pathlib import Path
SKILL_DIR = Path(__file__).resolve().parents[1]
SKILLS_ROOT = Path(__file__).resolve().parents[2]
TARGET = SKILLS_ROOT / "adapting-skil... | nisavid/dotfiles | home/dot_agents/skills/getting-prs-merged/scripts/claude_trigger_eval.py | .py | ee12094f2411dc51 | 7.15 | 1 |
#!/usr/bin/env python3
"""Compatibility wrapper for the generic Codex trigger eval runner."""
from __future__ import annotations
import os
import sys
from pathlib import Path
SKILL_DIR = Path(__file__).resolve().parents[1]
SKILLS_ROOT = Path(__file__).resolve().parents[2]
TARGET = SKILLS_ROOT / "adapting-skill-crea... | nisavid/dotfiles | home/dot_agents/skills/getting-prs-merged/scripts/codex_trigger_eval.py | .py | 4024c037247bd4e9 | 7.15 | 1 |
#!/usr/bin/env python3
"""Compatibility wrapper for the generic Cursor Agent trigger eval runner."""
from __future__ import annotations
import os
import sys
from pathlib import Path
SKILL_DIR = Path(__file__).resolve().parents[1]
SKILLS_ROOT = Path(__file__).resolve().parents[2]
TARGET = SKILLS_ROOT / "adapting-ski... | nisavid/dotfiles | home/dot_agents/skills/getting-prs-merged/scripts/cursor_trigger_eval.py | .py | d1a8d3f63568dce7 | 7.15 | 1 |
#!/usr/bin/env python3
"""Compatibility wrapper for the generic behavioral eval workspace preparer."""
from __future__ import annotations
import os
import sys
from pathlib import Path
SKILL_DIR = Path(__file__).resolve().parents[1]
SKILLS_ROOT = Path(__file__).resolve().parents[2]
TARGET = SKILLS_ROOT / "adapting-s... | nisavid/dotfiles | home/dot_agents/skills/getting-prs-merged/scripts/prepare_behavior_evals.py | .py | 0c245b660b4220f2 | 7.15 | 1 |
# MIT license
# Copyright (c) 2024 ???
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, d... | arrow-maintenance/arrowdash | ml_data/data_methods.py | .py | d77352f5ca3af068 | 7.39 | 5 |
import mailbox
from email.utils import parsedate_to_datetime
from collections import defaultdict
from datetime import datetime, timezone
import re
from email.header import decode_header, make_header
import os
from chatlas import ChatGoogle
import ml_data.data_methods as ml
def decode_mime_words(s):
"""
Decode... | arrow-maintenance/arrowdash | ml_data/summarise_ml.py | .py | 341a3a0c93b361e3 | 7.39 | 5 |
import os
class Credential:
"""
Classe para gerenciar credenciais de usuário e senha, com suporte a variáveis de ambiente.
"""
def __init__(
self, username: str | None = None, password: str | None = None
):
"""
Inicializa a classe Credential com um nome de usuário e senha.... | irissonnlima/chatgraph | chatgraph/auth/credentials.py | .py | d2e054303ebbd144 | 7.24 | 2 |
import inspect
from functools import wraps
from ..error.chatbot_error import ChatbotError
from ..logger.user_logger import UserLoggerManager
_logger = UserLoggerManager.get_system_logger()
class ChatbotRouter:
"""
Classe responsável por gerenciar e registrar as rotas do chatbot, associando-as a funções espe... | irissonnlima/chatgraph | chatgraph/bot/chatbot_router.py | .py | d93ff022ab32540c | 7.24 | 2 |
import os
from typing import TYPE_CHECKING
from dotenv import load_dotenv
if TYPE_CHECKING:
from ..services.router_http_client import RouterHTTPClient
class Container:
@classmethod
def load_dotenv(cls, env_path: str = '.env') -> None:
load_dotenv(dotenv_path=env_path)
"""Carrega variáve... | irissonnlima/chatgraph | chatgraph/container/container.py | .py | 001c4fa8f0277c7a | 7.24 | 2 |
class RouteError(Exception):
"""
Exceção personalizada para erros relacionados a rotas no sistema do chatbot.
Atributos:
message (str): A mensagem de erro descrevendo o problema.
"""
def __init__(self, message: str):
"""
Inicializa a exceção RouteError com uma mensagem de e... | irissonnlima/chatgraph | chatgraph/error/route_error.py | .py | 958b9155a4ec354c | 7.24 | 2 |
from typing import Optional, Protocol
from .entry import HistoryEntry
class HistoryStore(Protocol):
async def record(self, entry: HistoryEntry) -> bool:
"""Registra entry. Retorna False se duplicada."""
...
async def get(
self,
chat_id: str,
session_id: Optional[int],... | irissonnlima/chatgraph | chatgraph/history/store.py | .py | 084cbaabfe3850fc | 7.24 | 2 |
import os
from typing import Optional
from urllib.parse import quote
import aio_pika
from ..logger.user_logger import UserLoggerManager
from ..models.log_envelope import LogEnvelope
_logger = UserLoggerManager.get_system_logger()
# '/' é sintaxe de vhost, nunca nome de exchange: um get_exchange('/')
# devolve NOT_F... | irissonnlima/chatgraph | chatgraph/messages/log_publisher.py | .py | 90d4e76e246cd1dc | 7.24 | 2 |
import json
from dataclasses import dataclass, field
class EventType:
MESSAGE = 'log_message'
SESSION = 'log_session'
ROUTE = 'log_route'
END_ACTION = 'log_end_action'
ERROR = 'log_error'
ACK = 'log_ack'
ERROR_CODE_MAP = {
'ChatbotMessageError': 'CHATBOT_MESSAGE_ERROR',
'ChatbotError... | irissonnlima/chatgraph | chatgraph/models/log_envelope.py | .py | cd7f410393617ac7 | 7.24 | 2 |
"""
Modelos de dados para mensagens do chatbot.
Este módulo contém as dataclasses e enums para representar mensagens,
botões, arquivos e seus tipos no sistema de chatbot.
"""
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import List, Optional, Union
import ht... | irissonnlima/chatgraph | chatgraph/models/message.py | .py | 92478537c1f32ca0 | 7.24 | 2 |
"""
Modelos de dados para gerenciamento de estado de usuário.
Este módulo contém as dataclasses que representam o estado do usuário
no sistema de chatbot, incluindo identificação, informações pessoais,
menu atual e metadados da sessão.
"""
import asyncio
import concurrent.futures
import json
from dataclasses import d... | irissonnlima/chatgraph | chatgraph/models/userstate.py | .py | 1ddf8973f30273c5 | 7.24 | 2 |
import asyncio
from typing import Any, Callable
import threading
class BackgroundTask:
def __init__(self, func: Callable, *args: Any, **kwargs: Any) -> None:
"""
Inicia uma função de forma assíncrona em segundo plano e printa sua saída.
Args:
func (Callable): A função a ser ex... | irissonnlima/chatgraph | chatgraph/types/background_task.py | .py | 6eafd1c48b7f1b8f | 7.24 | 2 |
"""
Configuração de fixtures para testes de integração.
Este módulo contém fixtures para testes de integração que fazem
chamadas reais para APIs externas.
"""
import os
from dotenv import load_dotenv
import pytest
import pytest_asyncio
from chatgraph.services.router_http_client import RouterHTTPClient
load_dotenv(... | irissonnlima/chatgraph | tests/integration/conftest.py | .py | 391445977700475d | 7.74 | 2 |
import sys
import os
import cv2
import pandas as pd
import albumentations
import random
import matplotlib.pyplot as plt
from pathlib import Path
def load_image(image_path):
""" Load image using CV2 """
image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
return image
def read... | BenioffOceanInitiative/SharkEye_App | find_images_for_game.py | .py | d6c3dfabc2b63104 | 7 | 0 |
import numpy as np
class SharkTracker:
"""
A class to track individual sharks across video frames.
This class maintains the state of a tracked shark, including its position,
detection history, best detected frame, and maximum estimated length.
"""
def __init__(self, track_id: int, initial... | BenioffOceanInitiative/SharkEye_App | src/archive/shark_tracker.py | .py | 2dc6536afc12a315 | 7 | 0 |
# Find every video in base_directory (year)
# Choose parent directory and look for csv files
# If there's only one video in the directory
# For 2023
# Download Comparison sheet, save video_names to list
# Scan only parent directories of these videos for csvs
import os
import pandas as pd
from pathlib import Path
... | BenioffOceanInitiative/SharkEye_App | src/find_flight_data.py | .py | 451a4db6e9152a89 | 7 | 0 |
"""Sequential frame sampling shared by the GUI and headless video processors.
The processors previously seeked with ``cap.set(CAP_PROP_POS_FRAMES, n)`` before every
``cap.read()``. A random seek forces the decoder back to the nearest keyframe and
re-decodes forward on each iteration, which dominates runtime on long 4K... | BenioffOceanInitiative/SharkEye_App | src/frame_sampling.py | .py | d67aec4042d0465f | 7 | 0 |
"""Keyframe-scan frame sampling — a decode-cheap alternative to grab-through sampling.
``frame_sampling.iter_sampled_frames`` advances an OpenCV ``VideoCapture`` by
``grab()``-ing through *every* frame, so on long-GOP 10-bit HEVC drone footage it
software-decodes thousands of frames it immediately discards. Decode — n... | BenioffOceanInitiative/SharkEye_App | src/keyframe_sampling.py | .py | 0138427c3ef61c9e | 7 | 0 |
"""Update sharkeye-app-build/latest_version.json with the commit SHA + timestamp for a build platform."""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import time
from google.api_core.exceptions import NotFound, PreconditionFailed
from google.cloud import storage
BUCKET... | BenioffOceanInitiative/SharkEye_App | src/manage_version.py | .py | bd5fbc8da255dcd1 | 7 | 0 |
import numpy as np
import torch
import matplotlib.pyplot as plt
import cv2
import time
import math
import threading
from segment_anything import sam_model_registry, SamPredictor
from utility import resource_path, select_torch_device
from log_config import get_logger
logger = get_logger("sharkeye.segment")
from pathlib... | BenioffOceanInitiative/SharkEye_App | src/segmentation/segmentation_model.py | .py | fba7d5faf8a796b5 | 7 | 0 |
import os
import sys
import json
def select_torch_device():
"""Prefer CUDA, then MPS, then CPU.
GitHub Actions macOS runners advertise MPS but typically cannot allocate
shared GPU memory, so skip MPS when CI=true.
"""
import torch
if torch.cuda.is_available():
return torch.device("cu... | BenioffOceanInitiative/SharkEye_App | src/utility.py | .py | 98fac5b7f7b7060e | 7 | 0 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# Licensed under the Apache2.0. See LICENSE file in charm source for details.
"""Library to manage the relation data for the SAML Integrator charm.
This library contains the Requires and Provides classes for handling the relation
between an application and a cha... | canonical/saml-integrator-operator | lib/charms/saml_integrator/v0/saml.py | .py | 8c2de32b820044cf | 7 | 0 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""SAML Integrator Charm service."""
import logging
import ops
from charms.saml_integrator.v0 import saml
from ops.main import main
from charm_state import CharmConfigInvalidError, CharmState
from saml import SamlInteg... | canonical/saml-integrator-operator | src/charm.py | .py | 11af14e5a1126dfb | 7 | 0 |
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Module defining the CharmState class which represents the state of the SAML Integrator charm."""
import itertools
import urllib
from typing import Optional
import ops
from pydantic import AnyHttpUrl, BaseModel, Field... | canonical/saml-integrator-operator | src/charm_state.py | .py | a15f33e15fd446d9 | 7 | 0 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Provide the SamlApp class to encapsulate the business logic."""
import base64
import hashlib
import logging
import secrets
from functools import cached_property
from typing import Optional
import signxml
from charms.saml_integrator.v0 impor... | canonical/saml-integrator-operator | src/saml.py | .py | 6637289829871976 | 7 | 0 |
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
# pylint: disable=import-error,consider-using-with,no-member
"""This code snippet is used to be loaded into any-charm which is used for integration tests."""
from any_charm_base import AnyCharmBase
import saml
class AnyCharm(AnyCharmBase): ... | canonical/saml-integrator-operator | tests/integration/any_charm.py | .py | 5403e3b6de1927c6 | 7.5 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.