input
string
label
int64
sample_id
string
category
string
repo_id
string
from __future__ import annotations from functools import wraps from typing import TYPE_CHECKING, Any, ParamSpec import pytest from twisted.internet.defer import Deferred, inlineCallbacks from scrapy.utils.defer import deferred_from_coro, deferred_to_future from scrapy.utils.reactor import is_reactor_installed if TY...
1
scrapy/scrapy:tests/utils/decorators.py
test
scrapy/scrapy
from typing import Any from pydantic import BaseModel from crewai_tools.tools.brave_search_tool.base import BraveSearchToolBase from crewai_tools.tools.brave_search_tool.response_types import LocalPOIs from crewai_tools.tools.brave_search_tool.schemas import ( LocalPOIsDescriptionHeaders, LocalPOIsDescription...
0
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/brave_search_tool/brave_local_pois_tool.py
unknown
crewAIInc/crewAI
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
0
apache/airflow:airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dashboard.py
unknown
apache/airflow
import os import shlex import subprocess import sys import json import sysconfig import pytest component_template = """ from dash_generator_test_component_typescript import TypeScriptComponent t = TypeScriptComponent({0}) """ basic_app_template = """ from dash import Dash, html, dcc, callback, Input, Output app = ...
1
plotly/dash:tests/compliance/test_typing.py
test
plotly/dash
import numpy as np from metadrive.component.sensors.rgb_camera import RGBCamera from panda3d.core import Texture, GraphicsOutput class CopyRamRGBCamera(RGBCamera): """Camera which copies its content into RAM during the render process, for faster image grabbing.""" def __init__(self, *args, **kwargs): super()...
0
commaai/openpilot:tools/sim/bridge/metadrive/metadrive_common.py
unknown
commaai/openpilot
""" Example: Interrupt System Implementation This example demonstrates how to implement a robust interrupt system that allows users to interrupt the bot mid-sentence. """ import asyncio import threading from typing import Any from dataclasses import dataclass import logging logger = logging.getLogger(__name__) # =...
1
sickn33/antigravity-awesome-skills:skills/voice-ai-engine-development/examples/interrupt_system_example.py
function_complex
sickn33/antigravity-awesome-skills
"""Base class for Aladdin Connect entities.""" from genie_partner_sdk.client import AladdinConnectClient from genie_partner_sdk.model import GarageDoor from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .c...
0
home-assistant/core:homeassistant/components/aladdin_connect/entity.py
unknown
home-assistant/core
"""AIO Sandbox Provider — orchestrates sandbox lifecycle with pluggable backends. This provider composes two abstractions: - SandboxBackend: how sandboxes are provisioned (local container vs remote/K8s) - SandboxStateStore: how thread→sandbox mappings are persisted (file vs Redis) The provider itself handles: - In-pr...
1
bytedance/deer-flow:backend/src/community/aio_sandbox/aio_sandbox_provider.py
function_complex
bytedance/deer-flow
""" Functions to parse datetime objects. We're using regular expressions rather than time.strptime because: - They provide both validation and parsing. - They're more flexible for datetimes. - The date/datetime/time constructors produce friendlier error messages. Stolen from https://raw.githubusercontent.com/django/d...
0
pydantic/pydantic:pydantic/v1/datetime_parse.py
unknown
pydantic/pydantic
#!/usr/bin/env python3 """ Sync Microsoft Skills Repository - v4 (Flat Structure) Reads each SKILL.md frontmatter 'name' field and uses it as a flat directory name under skills/ to comply with the repository's indexing conventions. """ import re import shutil import subprocess import tempfile import json from pathlib ...
0
sickn33/antigravity-awesome-skills:tools/scripts/sync_microsoft_skills.py
unknown
sickn33/antigravity-awesome-skills
"""Base retriever.""" from abc import abstractmethod from typing import Any, Dict, List, Optional from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.callbacks.base import CallbackManager from llama_index.core.callbacks.schema import CBEventType, EventPayload from llama_index.cor...
0
run-llama/llama_index:llama-index-core/llama_index/core/base/base_retriever.py
unknown
run-llama/llama_index
from unittest.mock import MagicMock, patch from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist from django.test import TestCase from core.choices import ObjectChangeActionChoices from core.models import DataSource, Job, ObjectType from dcim.models import De...
0
netbox-community/netbox:netbox/core/tests/test_models.py
unknown
netbox-community/netbox
# Copyright 2024 The HuggingFace Inc. team. 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/LICENSE-2.0 # # Unless required by appl...
0
huggingface/lerobot:src/lerobot/configs/policies.py
unknown
huggingface/lerobot
from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from typing import Any from docling_core.types.doc.document import ( DocItemLabel, DoclingDocument, Formatting, GroupLabel, NodeItem, ) from pylatexenc.latexwalker import LatexEnvironmentNode, LatexMacroNode from docling.backend.lat...
0
docling-project/docling:docling/backend/latex/handlers/environments.py
unknown
docling-project/docling
""" Add system_metadata and job_id columns to asset_references. Change preview_id FK from assets.id to asset_references.id. Revision ID: 0003_add_metadata_job_id Revises: 0002_merge_to_asset_references Create Date: 2026-03-09 """ from alembic import op import sqlalchemy as sa from app.database.models import NAMING_C...
0
Comfy-Org/ComfyUI:alembic_db/versions/0003_add_metadata_job_id.py
unknown
Comfy-Org/ComfyUI
import logging from typing import Any import litellm from strix.config.config import Config, resolve_llm_config logger = logging.getLogger(__name__) MAX_TOTAL_TOKENS = 100_000 MIN_RECENT_MESSAGES = 15 SUMMARY_PROMPT_TEMPLATE = """You are an agent performing context condensation for a security agent. Your job is ...
1
usestrix/strix:strix/llm/memory_compressor.py
function_complex
usestrix/strix
"""Global configuration state and functions for management""" # Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause import os import threading from contextlib import contextmanager as contextmanager _global_config = { "assume_finite": bool(os.environ.get("SKLEARN_ASSUME_FINITE", False)),...
0
scikit-learn/scikit-learn:sklearn/_config.py
unknown
scikit-learn/scikit-learn
"""Autoscaler monitoring loop daemon. See autoscaler._private/monitor.py for the legacy implementation. All the legacy flags are supported here, but the new implementation uses the new autoscaler v2. """ import argparse import logging import os import sys import time from typing import Optional import ray import ray...
0
ray-project/ray:python/ray/autoscaler/v2/monitor.py
unknown
ray-project/ray
# Copyright (c) ONNX Project Contributors # # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations from typing import Any import numpy as np import onnx from onnx.backend.test.case.base import Base from onnx.backend.test.case.node import expect class RNNHelper: def __init__(self, **params: An...
0
onnx/onnx:onnx/backend/test/case/node/rnn.py
unknown
onnx/onnx
""" Inverse kinematics for rigid body entities. This module contains the inverse kinematics kernel for computing joint configurations that achieve desired end-effector poses. """ import quadrants as qd import genesis as gs import genesis.utils.geom as gu import genesis.utils.linalg as lu import genesis.utils.array_c...
1
Genesis-Embodied-AI/Genesis:genesis/engine/solvers/rigid/abd/inverse_kinematics.py
function_complex
Genesis-Embodied-AI/Genesis
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2026 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
1
python-telegram-bot/python-telegram-bot:tests/test_suggestedpost.py
test
python-telegram-bot/python-telegram-bot
""" Followups — Streaming ===================== Stream the main response token-by-token and capture followup suggestions via events at the end. Key concepts: - stream=True, stream_events=True: enables streaming with events - RunEvent.run_content: tokens of the main response - RunEvent.followups_completed: carries the...
0
agno-agi/agno:cookbook/02_agents/02_input_output/followup_suggestions_streaming.py
unknown
agno-agi/agno
""" On-Page SEO Audit & Optimization Team built with Google ADK. The workflow runs three specialized agents in sequence: 1. Page Auditor → scrapes the target URL with Firecrawl and extracts the structural audit + keyword focus. 2. SERP Analyst → performs competitive analysis with Google Search using the discovered pri...
1
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/agent_teams/ai_seo_audit_team/agent.py
documentation
Shubhamsaboo/awesome-llm-apps
import logging from langchain.agents import create_agent from langchain.agents.middleware import SummarizationMiddleware from langchain_core.runnables import RunnableConfig from deerflow.agents.lead_agent.prompt import apply_prompt_template from deerflow.agents.middlewares.clarification_middleware import Clarificatio...
0
bytedance/deer-flow:backend/packages/harness/deerflow/agents/lead_agent/agent.py
unknown
bytedance/deer-flow
from __future__ import annotations from typing import TYPE_CHECKING, AsyncIterator, Iterator, List, Optional, Tuple from agno.models.base import Model from agno.models.message import Message from agno.utils.log import logger if TYPE_CHECKING: from agno.metrics import RunMetrics def is_anthropic_reasoning_model...
1
agno-agi/agno:libs/agno/agno/reasoning/anthropic.py
function_complex
agno-agi/agno
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations from typing import Union, Iterable, Optional from typing_extensions import Literal, Required, TypeAlias, TypedDict from .custom_tool_param import CustomToolParam __all__ = ["NamespaceToolParam", ...
0
openai/openai-python:src/openai/types/responses/namespace_tool_param.py
unknown
openai/openai-python
from datetime import timedelta from typing import TYPE_CHECKING, Any import orjson from django.conf import settings from django.test import override_settings from django.utils.timezone import now as timezone_now from typing_extensions import override from analytics.models import StreamCount from zerver.actions.stream...
1
zulip/zulip:zerver/tests/test_channel_fetch.py
test
zulip/zulip
"""Agent skill configuration models.""" from dataclasses import dataclass, field, replace from pathlib import Path from typing import Any, Dict, List, Mapping import yaml from entity.configs.base import ( BaseConfig, ConfigError, ConfigFieldSpec, EnumOption, optional_bool, extend_path, re...
0
OpenBMB/ChatDev:entity/configs/node/skills.py
unknown
OpenBMB/ChatDev
"""Reddit thread enrichment with real engagement metrics.""" import re from typing import Any, Dict, List, Optional from urllib.parse import urlparse from . import http, dates def extract_reddit_path(url: str) -> Optional[str]: """Extract the path from a Reddit URL. Args: url: Reddit URL Retur...
1
sickn33/antigravity-awesome-skills:skills/last30days/scripts/lib/reddit_enrich.py
function_complex
sickn33/antigravity-awesome-skills
""" Tests for Cursor .mdc frontmatter generation (issue #669). Verifies that update-agent-context.sh properly prepends YAML frontmatter to .mdc files so that Cursor IDE auto-includes the rules. """ import os import shutil import subprocess import textwrap import pytest SCRIPT_PATH = os.path.join( os.path.dirnam...
1
github/spec-kit:tests/test_cursor_frontmatter.py
test
github/spec-kit
"""Image generation provider for GPT Researcher. This module provides image generation capabilities using Google's Gemini/Imagen models via the google.genai SDK. Supported models: - Gemini image models (free tier): models/gemini-2.5-flash-image - Imagen models (requires billing): imagen-4.0-generate-001 """ import a...
1
assafelovic/gpt-researcher:gpt_researcher/llm_provider/image/image_generator.py
function_complex
assafelovic/gpt-researcher
import shutil from pathlib import Path import pytest @pytest.mark.integration @pytest.mark.install @pytest.mark.editable @pytest.mark.vcs def test_editable_vcs_reinstall(pipenv_instance_private_pypi): """Test that editable VCS dependencies are reinstalled when the source checkout is missing.""" with pipenv_i...
1
pypa/pipenv:tests/integration/test_editable_vcs.py
test
pypa/pipenv
# Copyright (c) ONNX Project Contributors # # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from collections.abc import Sequence import numpy as np import onnx from onnx.backend.test.case.base import Base from onnx.backend.test.cas...
0
onnx/onnx:onnx/backend/test/case/node/scatterelements.py
unknown
onnx/onnx
__package__ = 'archivebox.api' import json from io import StringIO from typing import List, Dict, Any, Optional from enum import Enum from django.http import HttpRequest from ninja import Router, Schema from archivebox.misc.util import ansi_to_html from archivebox.config.common import ARCHIVING_CONFIG # from .aut...
0
ArchiveBox/ArchiveBox:archivebox/api/v1_cli.py
unknown
ArchiveBox/ArchiveBox
# Copyright 2026 Marimo. All rights reserved. from __future__ import annotations from typing import Literal, NewType, Optional import msgspec # Type-safe server identifier LspServerId = NewType("LspServerId", str) # Status enum for LSP server health LspServerStatus = Literal[ "starting", # process launched, in...
1
marimo-team/marimo:marimo/_server/models/lsp.py
function_simple
marimo-team/marimo
"""Shared type declarations for the Apache Solr vector store integration.""" from typing import TypedDict from pydantic import BaseModel from typing_extensions import NotRequired class BoostedTextField(BaseModel): """ A text field with an optional boost value for Solr queries. This model represents a S...
1
run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-solr/llama_index/vector_stores/solr/types.py
documentation
run-llama/llama_index
"""Shared HuggingFace-based helpers for image-classification engines.""" from __future__ import annotations from pathlib import Path from typing import TYPE_CHECKING, Any, Iterable, Optional, Union import numpy as np from docling.datamodel.accelerator_options import AcceleratorOptions from docling.models.inference_...
1
docling-project/docling:docling/models/inference_engines/image_classification/hf_base.py
function_simple
docling-project/docling
import pyray as rl from cereal import log, messaging from msgq.visionipc import VisionStreamType from openpilot.selfdrive.ui.mici.onroad.cameraview import CameraView from openpilot.selfdrive.ui.mici.onroad.driver_state import DriverStateRenderer from openpilot.selfdrive.ui.ui_state import ui_state, device from openpilo...
1
commaai/openpilot:selfdrive/ui/mici/onroad/driver_camera_dialog.py
function_complex
commaai/openpilot
"""Content type negotiation for A2A protocol. This module handles negotiation of input/output MIME types between A2A clients and servers based on AgentCard capabilities. """ from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING, Annotated, Final, Literal, cast from a2...
1
crewAIInc/crewAI:lib/crewai/src/crewai/a2a/utils/content_type.py
function_complex
crewAIInc/crewAI
import torch from typing_extensions import override from comfy_api.latest import IO, ComfyExtension from comfy_api_nodes.apis.pixverse import ( PixverseTextVideoRequest, PixverseImageVideoRequest, PixverseTransitionVideoRequest, PixverseImageUploadResponse, PixverseVideoResponse, PixverseGenerat...
1
Comfy-Org/ComfyUI:comfy_api_nodes/nodes_pixverse.py
function_complex
Comfy-Org/ComfyUI
from warnings import warn from django.forms import Media from django.utils import translation from django.utils.translation import gettext_lazy as _ from wagtail import hooks from wagtail.admin.ui.components import Component from wagtail.admin.utils import get_admin_base_url from wagtail.coreutils import accepts_kwar...
0
wagtail/wagtail:wagtail/admin/userbar.py
unknown
wagtail/wagtail
""" Copyright 2024, Zep Software, 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 in writing, sof...
0
getzep/graphiti:graphiti_core/errors.py
unknown
getzep/graphiti
import logging import subprocess logger = logging.getLogger(__name__) def safe_run_cmd(cmd_args, shell=False): if shell: raise ValueError("shell=True is not allowed in safe_run_cmd. " "Pass command as a list with shell=False.") cmd_args = [str(arg) for arg in cmd_args] try: return subproc...
1
jumpserver/jumpserver:apps/common/utils/safe.py
function_simple
jumpserver/jumpserver
import json import os import logging import queue import torch import numpy as np from torch.utils.dlpack import to_dlpack import triton_python_backend_utils as pb_utils from hyperpyyaml import load_hyperpyyaml logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logg...
0
FunAudioLLM/CosyVoice:runtime/triton_trtllm/model_repo_cosyvoice3/token2wav/1/model.py
unknown
FunAudioLLM/CosyVoice
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2026 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
0
python-telegram-bot/python-telegram-bot:src/telegram/_version.py
unknown
python-telegram-bot/python-telegram-bot
""" File and file system-related tools, specifically for * listing directory contents * reading files * creating files * editing at the file level """ import os from collections import defaultdict from fnmatch import fnmatch from pathlib import Path from typing import Literal from serena.tools import SUCCESS_...
1
oraios/serena:src/serena/tools/file_tools.py
documentation
oraios/serena
#!/usr/bin/env python3 """Ensure keyword arguments use spaces around '=', prune redundant pass statements.""" from __future__ import annotations import ast import argparse import io import sys import tokenize from collections import defaultdict from pathlib import Path def enforce_spacing(text: str) -> tuple[str, b...
1
unslothai/unsloth:scripts/enforce_kwargs_spacing.py
function_complex
unslothai/unsloth
""" Provides Elm specific instantiation of the LanguageServer class. Contains various configurations and settings specific to Elm. """ import logging import os import pathlib import shutil import threading from overrides import override from sensai.util.logging import LogTime from solidlsp.ls import SolidLanguageSer...
1
oraios/serena:src/solidlsp/language_servers/elm_language_server.py
function_complex
oraios/serena
from unittest.mock import MagicMock import pytest from scrapy import signals from scrapy.exceptions import NotConfigured from scrapy.extensions import statsmailer from scrapy.mail import MailSender from scrapy.signalmanager import SignalManager from scrapy.statscollectors import StatsCollector from scrapy.utils.spide...
1
scrapy/scrapy:tests/test_extension_statsmailer.py
test
scrapy/scrapy
import time from dataclasses import dataclass, field from typing import Callable, cast import mlx.core as mx from mlx_lm.generate import ( BatchGenerator as MlxBatchGenerator, ) from mlx_lm.models.cache import RotatingKVCache from mlx_lm.sample_utils import make_logits_processors, make_sampler from mlx_lm.tokenize...
0
exo-explore/exo:src/exo/worker/engines/mlx/generator/batch_generate.py
unknown
exo-explore/exo
#Original code can be found on: https://github.com/black-forest-labs/flux from dataclasses import dataclass import torch from torch import Tensor, nn from einops import rearrange, repeat import comfy.ldm.common_dit import comfy.patcher_extension from .layers import ( DoubleStreamBlock, EmbedND, LastLayer...
0
Comfy-Org/ComfyUI:comfy/ldm/flux/model.py
unknown
Comfy-Org/ComfyUI
from __future__ import annotations from datetime import datetime, timezone from uuid import UUID, uuid4 from pydantic import BaseModel, computed_field, field_serializer from pydantic import Field as PydanticField from sqlalchemy import CheckConstraint, Column, DateTime, ForeignKey, UniqueConstraint, func from sqlmode...
0
langflow-ai/langflow:src/backend/base/langflow/services/database/models/flow_version/model.py
unknown
langflow-ai/langflow
from unittest.mock import MagicMock, Mock, patch import pytest from rich.console import Console from rich.text import Text from agno.agent import Agent from agno.models.openai import OpenAIChat def test_print_response_with_message_panel(): """Test that print_response creates a message panel when show_message=Tr...
1
agno-agi/agno:libs/agno/tests/integration/agent/test_print_response.py
test
agno-agi/agno
""" Script to run GPT-Researcher queries and evaluate them for hallucination. """ import json import logging import random import asyncio import argparse import os from pathlib import Path from typing import Dict, List, Optional from dotenv import load_dotenv from gpt_researcher.agent import GPTResearcher from gpt_res...
1
assafelovic/gpt-researcher:evals/hallucination_eval/run_eval.py
function_complex
assafelovic/gpt-researcher
# pragma pylint: disable=missing-docstring, W0212, line-too-long, C0103, unused-argument from copy import deepcopy from unittest.mock import MagicMock import pandas as pd import pytest from freqtrade.configuration import TimeRange from freqtrade.data import history from freqtrade.data.history import get_timerange fr...
0
freqtrade/freqtrade:tests/optimize/test_backtesting_adjust_position.py
unknown
freqtrade/freqtrade
import logging import re import uuid from pathlib import Path from django.conf import settings from django.contrib.auth.models import User from django.utils import timezone from documents.data_models import ConsumableDocument from documents.data_models import DocumentMetadataOverrides from documents.mail import Email...
1
paperless-ngx/paperless-ngx:src/documents/workflows/actions.py
function_complex
paperless-ngx/paperless-ngx
import pytest import torch from torch_geometric.llm.utils.vectorrag import DocumentRetriever from torch_geometric.testing import onlyRAG @pytest.fixture def sample_documents(): """Fixture providing sample documents for testing.""" return [ "This is the first test document.", "This is the seco...
1
pyg-team/pytorch_geometric:test/llm/utils/test_vectorrag.py
test
pyg-team/pytorch_geometric
import numpy as np from dspy.clients import Embedder from dspy.primitives import Example class KNN: def __init__(self, k: int, trainset: list[Example], vectorizer: Embedder): """ A k-nearest neighbors retriever that finds similar examples from a training set. Args: k: Number ...
0
stanfordnlp/dspy:dspy/predict/knn.py
unknown
stanfordnlp/dspy
import warnings from asyncio import sleep import pytest from scrapy import Spider, signals from scrapy.exceptions import ScrapyDeprecationWarning from scrapy.utils.defer import maybe_deferred_to_future from scrapy.utils.test import get_crawler from tests.test_spider_start import SLEEP_SECONDS from .utils import twis...
1
scrapy/scrapy:tests/test_spidermiddleware_process_start.py
test
scrapy/scrapy
"""Execution policies for the persistent shell middleware.""" from __future__ import annotations import abc import json import os import shutil import subprocess import sys import typing from collections.abc import Mapping, Sequence from dataclasses import dataclass, field from pathlib import Path try: # pragma: no...
1
langchain-ai/langchain:libs/langchain_v1/langchain/agents/middleware/_execution.py
function_complex
langchain-ai/langchain
import os import pytest from solidlsp import SolidLanguageServer from solidlsp.ls_config import Language from solidlsp.ls_utils import SymbolUtils from test.conftest import is_ci # Kotlin LSP (IntelliJ-based, pre-alpha v261) crashes on JVM restart under CI resource constraints # (2 CPUs, 7GB RAM). First start succe...
1
oraios/serena:test/solidlsp/kotlin/test_kotlin_basic.py
test
oraios/serena
import pytest from scrapling.engines.toolbelt.custom import StatusText, Response from scrapling.engines.toolbelt.navigation import ( construct_proxy_dict, create_intercept_handler, create_async_intercept_handler, ) from scrapling.engines.toolbelt.fingerprints import ( get_os_name, generate_headers ...
0
D4Vinci/Scrapling:tests/fetchers/test_utils.py
unknown
D4Vinci/Scrapling
import re from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Dict, List, Optional import pyarrow as pa from huggingface_hub import HfApi import datasets from datasets import Audio, Image, Video from datasets.builder import Key from datasets.table import table_cast from datase...
1
huggingface/datasets:src/datasets/packaged_modules/lance/lance.py
function_complex
huggingface/datasets
""" Project Euler Problem 9: https://projecteuler.net/problem=9 Special Pythagorean triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2. For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find t...
1
TheAlgorithms/Python:project_euler/problem_009/sol4.py
documentation
TheAlgorithms/Python
def _setup_env(monkeypatch): monkeypatch.setenv("DOCLING_PERF_PAGE_BATCH_SIZE", "12") monkeypatch.setenv("DOCLING_DEBUG_VISUALIZE_RAW_LAYOUT", "True") monkeypatch.setenv("DOCLING_ARTIFACTS_PATH", "/path/to/artifacts") monkeypatch.setenv("DOCLING_INFERENCE_COMPILE_TORCH_MODELS", "True") def test_settin...
1
docling-project/docling:tests/test_settings_load.py
test
docling-project/docling
import re from typing import Dict, List import numpy as np import trimesh from pxr import Usd, UsdGeom, UsdPhysics import genesis as gs from genesis.utils import geom as gu from .usd_context import UsdContext from .usd_utils import AXES_T, usd_attr_array_to_numpy, usd_primvar_array_to_numpy def geom_exception(geom...
1
Genesis-Embodied-AI/Genesis:genesis/utils/usd/usd_geometry.py
function_complex
Genesis-Embodied-AI/Genesis
# HumanEval/147 # Loki Mode Multi-Agent Solution # Attempts: 1 # Passed: True def get_max_triples(n): """ You are given a positive integer n. You have to create an integer array a of length n. For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1. Return the number of triples (a[i], a[j], a...
1
davila7/claude-code-templates:cli-tool/components/skills/ai-research/loki-mode/benchmarks/results/humaneval-loki-solutions/147.py
documentation
davila7/claude-code-templates
"""Auto-discovery for built-in channel modules and external plugins.""" from __future__ import annotations import importlib import pkgutil from typing import TYPE_CHECKING from loguru import logger if TYPE_CHECKING: from nanobot.channels.base import BaseChannel _INTERNAL = frozenset({"base", "manager", "regist...
0
HKUDS/nanobot:nanobot/channels/registry.py
unknown
HKUDS/nanobot
""" LightRAG Demo with OpenSearch + OpenAI This example demonstrates how to use LightRAG with: - OpenAI (LLM + Embeddings) - OpenSearch-backed storages for: - KV storage - Vector storage (k-NN) - Graph storage (dual-index nodes + edges) - Document status storage Prerequisites: 1. OpenSearch cluster running an...
0
HKUDS/LightRAG:examples/lightrag_openai_opensearch_graph_demo.py
unknown
HKUDS/LightRAG
"""Factory helpers for node executors. Create and manage executors for different node types. """ from typing import Dict from runtime.node.executor.base import NodeExecutor, ExecutionContext from runtime.node.registry import iter_node_registrations class NodeExecutorFactory: """Factory class that instantiates ...
1
OpenBMB/ChatDev:runtime/node/executor/factory.py
documentation
OpenBMB/ChatDev
# Zulip's OpenAPI-based API documentation system is documented at # https://zulip.readthedocs.io/en/latest/documentation/api.html # # This file contains helper functions for generating cURL examples # based on Zulip's OpenAPI definitions, as well as test setup and # fetching of appropriate parameter values to use whe...
0
zulip/zulip:zerver/openapi/curl_param_value_generators.py
unknown
zulip/zulip
import uuid from datetime import UTC, datetime from typing import Any from strix.tools.registry import register_tool _notes_storage: dict[str, dict[str, Any]] = {} def _filter_notes( category: str | None = None, tags: list[str] | None = None, search_query: str | None = None, ) -> list[dict[str, Any]]: ...
1
usestrix/strix:strix/tools/notes/notes_actions.py
function_complex
usestrix/strix
#!/usr/bin/env python3 """Handles updating of an alignments file from an older version to the current version.""" from __future__ import annotations import logging import os import typing as T import numpy as np from lib.logger import parse_class_init from lib.utils import get_module_objects, VIDEO_EXTENSIONS logge...
0
deepfakes/faceswap:lib/align/updater.py
unknown
deepfakes/faceswap
""" Make Sentence For a given string and dictionary, count how many sentences can be formed from the string such that all words are contained in the dictionary. Reference: https://en.wikipedia.org/wiki/Word_break_problem Complexity: Time: O(2^n) worst case due to recursive exploration Space: O(n) recursion ...
1
keon/algorithms:algorithms/string/make_sentence.py
documentation
keon/algorithms
import django_filters import graphene from django.db.models import Q from ....product.models import Category from ...core.doc_category import DOC_CATEGORY_PRODUCTS from ...core.filters import ( FilterInputObjectType, GlobalIDMultipleChoiceFilter, GlobalIDMultipleChoiceWhereFilter, ListObjectTypeFilter,...
1
saleor/saleor:saleor/graphql/product/filters/category.py
function_simple
saleor/saleor
#! /usr/env/bin/python3 """ Handles interfacing between Faceswap Configs and ConfigParser .ini files """ from __future__ import annotations import logging import os import textwrap import typing as T from configparser import ConfigParser from lib.logger import parse_class_init from lib.utils import get_module_object...
1
deepfakes/faceswap:lib/config/ini.py
documentation
deepfakes/faceswap
""" Custom adapter for improving structured outputs using the information from Pydantic models. Based on the format used by BAML: https://github.com/BoundaryML/baml """ import inspect import types from typing import Any, Literal, Union, get_args, get_origin from pydantic import BaseModel from dspy.adapters.json_adap...
1
stanfordnlp/dspy:dspy/adapters/baml_adapter.py
function_complex
stanfordnlp/dspy
""" Cloud management client for connecting to the LinkAI control console. Handles remote configuration sync, message push, and skill management via the LinkAI socket protocol. """ from bridge.context import Context, ContextType from bridge.reply import Reply, ReplyType from common.log import logger from linkai import...
1
zhayujie/chatgpt-on-wechat:common/cloud_client.py
function_complex
zhayujie/chatgpt-on-wechat
import json import os from typing import Dict from utils.config import config, resource_path _LOCALES_CACHE: Dict[str, Dict[str, str]] = {} _CURRENT_LANG = None _TRANSLATIONS: Dict[str, str] = {} def _load_locale(lang: str) -> Dict[str, str]: global _LOCALES_CACHE if lang in _LOCALES_CACHE: return _...
1
Guovin/iptv-api:utils/i18n.py
function_simple
Guovin/iptv-api
# This script is based on examples/lily_finetuning/lily_finetuning.py import os import torch from datasets import load_dataset from transformers import ( AutoModelForCausalLM, AutoTokenizer, DataCollatorForLanguageModeling, Trainer, TrainingArguments, ) from peft import PeanutConfig, get_peft_mode...
0
huggingface/peft:examples/peanut_finetuning/peanut_finetuning.py
unknown
huggingface/peft
import time from collections import defaultdict from dataclasses import asdict, dataclass, field from django.db import transaction from django.db.models import F from django.utils.timezone import now as timezone_now from django.utils.translation import gettext as _ from analytics.lib.counts import COUNT_STATS, do_inc...
0
zulip/zulip:zerver/actions/message_flags.py
unknown
zulip/zulip
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ ColQwen3 late interaction model for multi-modal retrieval and reranking. ColQwen3 extends Qwen3-VL with a ColBERT-style late interaction head, producing per-token embeddings for both text and image inputs. It...
1
vllm-project/vllm:vllm/model_executor/models/colqwen3.py
license
vllm-project/vllm
from django.core.management import call_command from django.core.management.base import CommandError from rest_framework import status from rest_framework.test import APITestCase class TestApiSchema(APITestCase): ENDPOINT = "/api/schema/" def test_valid_schema(self) -> None: """ Test that the...
0
paperless-ngx/paperless-ngx:src/documents/tests/test_api_schema.py
unknown
paperless-ngx/paperless-ngx
# Copyright 2026 Marimo. All rights reserved. from __future__ import annotations import abc import io from typing import NewType, Optional from marimo._messaging.mimetypes import ConsoleMimeType from marimo._types.ids import CellId_t # A KernelMessage is a bytes object that contains a serialized NotificationMessage....
0
marimo-team/marimo:marimo/_messaging/types.py
unknown
marimo-team/marimo
"""Base index classes.""" import logging from abc import ABC, abstractmethod from typing import Any, Dict, Generic, List, Optional, Sequence, Type, TypeVar from llama_index.core.base.base_query_engine import BaseQueryEngine from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.callbacks...
0
run-llama/llama_index:llama-index-core/llama_index/core/indices/base.py
unknown
run-llama/llama_index
"""Base classes and functions for HTTP mockservers.""" from __future__ import annotations import argparse import sys from abc import ABC, abstractmethod from subprocess import PIPE, Popen from typing import TYPE_CHECKING from urllib.parse import urlparse from twisted.web.server import Site from tests.utils import g...
1
scrapy/scrapy:tests/mockserver/http_base.py
test
scrapy/scrapy
""" Tests for Lean 4 Language Server integration with Serena. Tests prove that Serena's symbol tools can: 1. Start the Lean 4 language server 2. Discover all expected symbols with precise matching 3. Track within-file references 4. Track cross-file references Test Repository Structure: - Helper.lean: Calculator struc...
0
oraios/serena:test/solidlsp/lean4/test_lean4_basic.py
unknown
oraios/serena
""" Bash tool - Execute bash commands """ import os import re import sys import subprocess import tempfile from typing import Dict, Any from agent.tools.base_tool import BaseTool, ToolResult from agent.tools.utils.truncate import truncate_tail, format_size, DEFAULT_MAX_LINES, DEFAULT_MAX_BYTES from common.log import ...
1
zhayujie/chatgpt-on-wechat:agent/tools/bash/bash.py
function_complex
zhayujie/chatgpt-on-wechat
import re import pytest from sklearn import config_context from sklearn.utils._repr_html.common import generate_link_to_param_doc from sklearn.utils._repr_html.params import ParamsDict, _params_html_repr, _read_params def test_params_dict_content(): """Check the behavior of the ParamsDict class.""" params =...
1
scikit-learn/scikit-learn:sklearn/utils/_repr_html/tests/test_params.py
test
scikit-learn/scikit-learn
MACROS_NEWCOMMAND = frozenset(["newcommand", "renewcommand", "providecommand"]) MACROS_PREAMBLE_METADATA = frozenset(["title", "author", "date"]) MACROS_INLINE_VERBATIM = frozenset(["%", "$", "&", "#", "_", "{", "}", "~"]) MACROS_TEXT_FORMATTING = frozenset(["textbf", "textit", "emph", "texttt", "underline"]) MACRO...
0
docling-project/docling:docling/backend/latex/constants.py
unknown
docling-project/docling
""" Provides TypeScript specific instantiation of the LanguageServer class. Contains various configurations and settings specific to TypeScript. """ import logging import os import pathlib import shutil import threading from typing import Any, cast from overrides import override from sensai.util.logging import LogTim...
0
oraios/serena:src/solidlsp/language_servers/typescript_language_server.py
unknown
oraios/serena
import base64 import os import time import requests def generate_video( prompt_file: str, reference_images: list[str], output_file: str, aspect_ratio: str = "16:9", ) -> str: with open(prompt_file, "r") as f: prompt = f.read() referenceImages = [] i = 0 json = { "insta...
1
bytedance/deer-flow:skills/public/video-generation/scripts/generate.py
function_complex
bytedance/deer-flow
import json import uuid from unittest.mock import Mock, patch import pytest from opentelemetry import trace as trace_api from opentelemetry.sdk.trace import ReadableSpan as OTelReadableSpan import mlflow from mlflow.entities.span import create_mlflow_span from mlflow.environment_variables import MLFLOW_TRACING_SQL_WA...
1
mlflow/mlflow:tests/tracing/test_tracing_client.py
test
mlflow/mlflow
""" Integração com a skill web-scraper para extração inteligente de fallback. Quando um scraper nativo retorna 0 registros, este módulo aciona o web-scraper para tentativa adicional de extração estruturada dos dados de leiloeiros. Uso direto: python web_scraper_fallback.py --estado MA RN AP python web_scraper...
0
sickn33/antigravity-awesome-skills:skills/junta-leiloeiros/scripts/web_scraper_fallback.py
unknown
sickn33/antigravity-awesome-skills
from __future__ import annotations import asyncio from abc import ABC, abstractmethod from dataclasses import dataclass from functools import partial from typing import TYPE_CHECKING, Any, Callable, TypeVar from typing_extensions import Protocol, runtime_checkable from textual import _time from textual._callback imp...
0
Textualize/textual:src/textual/_animator.py
unknown
Textualize/textual
from typing import TYPE_CHECKING, Callable, List, Optional if TYPE_CHECKING: from typing import Any from docling_core.types.doc.document import TableCell, TableData from pylatexenc.latexwalker import LatexCharsNode, LatexEnvironmentNode, LatexMacroNode from docling.backend.latex.constants import ( MACROS_ESC...
0
docling-project/docling:docling/backend/latex/utils/table.py
unknown
docling-project/docling
"""Mobjects representing objects from probability theory and statistics.""" from __future__ import annotations __all__ = ["SampleSpace", "BarChart"] from collections.abc import Iterable, MutableSequence, Sequence from typing import Any import numpy as np from manim import config, logger from manim.constants impor...
0
ManimCommunity/manim:manim/mobject/graphing/probability.py
unknown
ManimCommunity/manim
""" Telegram Agent with User Memory ================================ Personal assistant bot that remembers user preferences, hobbies, and interests across conversations. Uses MemoryManager to automatically capture and recall personal details from chat history. Key concepts: - ``MemoryManager`` with custom capture i...
0
agno-agi/agno:cookbook/05_agent_os/interfaces/telegram/agent_with_user_memory.py
unknown
agno-agi/agno
#!/usr/bin/env python3 """ Quick tree visualization script with common customization options. Provides command-line interface for rapid tree visualization with customizable styles, layouts, and output formats. """ import argparse import sys from pathlib import Path try: from ete3 import Tree, TreeStyle, NodeStyl...
1
davila7/claude-code-templates:cli-tool/components/skills/scientific/etetoolkit/scripts/quick_visualize.py
function_complex
davila7/claude-code-templates
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations from typing import Union from typing_extensions import Literal import httpx from ... import _legacy_response from ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given from ..._u...
0
openai/openai-python:src/openai/resources/audio/speech.py
unknown
openai/openai-python