sample_id
string
instruction
string
completion
string
category
string
label
int64
metadata
string
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/adapters/mcp_adapter.py:MCPServerAdapter:class_doc
Write a class-level docstring for `MCPServerAdapter` which has methods: `__init__`, `start`, `stop`, `tools`, `__enter__`.
Manages the lifecycle of an MCP server and make its tools available to CrewAI. Note: tools can only be accessed after the server has been started with the `start()` method. Usage: # context manager + stdio with MCPServerAdapter(...) as tools: # tools is now available # context manager + sse ...
documentation
0
{"doc_type": "class", "class_name": "MCPServerAdapter", "file_path": "lib/crewai-tools/src/crewai_tools/adapters/mcp_adapter.py", "repo_id": "crewAIInc/crewAI", "char_length": 1249, "methods": ["__init__", "start", "stop", "tools", "__enter__", "__exit__"]}
huggingface/transformers:tests/trainer/test_training_args.py:TestTrainingArguments.test_custom_output_dir
# Context: import tempfile from transformers import TrainingArguments class TestTrainingArguments(unittest.TestCase): def test_default_output_dir(self): ... def test_output_dir_creation(self): ... def test_torch_empty_cache_steps_requirements(self): ... def test_output_dir_expands_user(self): ... d...
def test_custom_output_dir(self): """Test that output_dir is respected when specified.""" with tempfile.TemporaryDirectory() as tmp_dir: args = TrainingArguments(output_dir=tmp_dir) self.assertEqual(args.output_dir, tmp_dir)
test
0
{"function_name": "test_custom_output_dir", "class_name": "TestTrainingArguments", "qualname": "TestTrainingArguments.test_custom_output_dir", "file_path": "tests/trainer/test_training_args.py", "repo_id": "huggingface/transformers", "loc": 5, "tested_modules": ["transformers", "transformers.debug_utils", "transformers...
fastapi/fastapi:tests/test_request_params/test_body/test_list.py:test_required_list_alias_by_name
# Context: import pytest from dirty_equals import IsOneOf, IsPartialDict from fastapi.testclient import TestClient async def read_required_list_str(p: Annotated[list[str], Body(embed=True)]): ... class BodyModelRequiredListStr(BaseModel): ... def read_model_required_list_str(p: BodyModelRequiredListStr): ... def test_...
def test_required_list_alias_by_name(path: str): client = TestClient(app) response = client.post(path, json={"p": ["hello", "world"]}) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": ["body", "p_al...
test
1
{"function_name": "test_required_list_alias_by_name", "class_name": null, "qualname": "test_required_list_alias_by_name", "file_path": "tests/test_request_params/test_body/test_list.py", "repo_id": "fastapi/fastapi", "loc": 14, "tested_modules": ["typing", "dirty_equals", "fastapi", "fastapi.testclient", "pydantic"], "...
apache/airflow:airflow-core/tests/unit/serialization/test_stringify.py:TestStringify.test_stringify_nested_serialized
# Context: from airflow.serialization.stringify import CLASSNAME, VERSION, stringify class W: ... class V: ... class TestStringify: def test_stringify(self): ... def test_serde_stringify_primitives(self, value, expected): ... def test_stringify_none(self): ... def test_stringify_primitives(self, value...
def test_stringify_nested_serialized(self): e = { CLASSNAME: "test.Outer", VERSION: 1, "__data__": { "inner": {CLASSNAME: "builtins.tuple", VERSION: 1, "__data__": [1, 2, 3]}, }, } result = stringify(e) assert "test.Outer@ve...
test
1
{"function_name": "test_stringify_nested_serialized", "class_name": "TestStringify", "qualname": "TestStringify.test_stringify_nested_serialized", "file_path": "airflow-core/tests/unit/serialization/test_stringify.py", "repo_id": "apache/airflow", "loc": 11, "tested_modules": ["__future__", "dataclasses", "typing", "ai...
langflow-ai/langflow:src/backend/tests/unit/base/tools/test_run_flow.py:TestRunFlowBaseComponentFlowRetrieval.test_get_flow_with_id
# Context: from unittest.mock import AsyncMock, MagicMock, Mock, PropertyMock, patch from uuid import uuid4 import pytest from lfx.base.tools.run_flow import RunFlowBaseComponent from lfx.schema.data import Data def mock_shared_cache(): ... class TestRunFlowBaseComponentInitialization: ... class TestRunFlowBaseCompone...
async def test_get_flow_with_id(self): """Test getting a flow by ID.""" component = RunFlowBaseComponent() component._user_id = str(uuid4()) flow_id = str(uuid4()) expected_flow = Data(data={"name": "test_flow"}) with patch("lfx.base.tools.run_flow.get_flow_by_id_or_name...
test
1
{"function_name": "test_get_flow_with_id", "class_name": "TestRunFlowBaseComponentFlowRetrieval", "qualname": "TestRunFlowBaseComponentFlowRetrieval.test_get_flow_with_id", "file_path": "src/backend/tests/unit/base/tools/test_run_flow.py", "repo_id": "langflow-ai/langflow", "loc": 18, "tested_modules": ["uuid", "lfx.ba...
karpathy/nanochat:nanochat/report.py:Report:class_doc
Write a class-level docstring for `Report` which has methods: `__init__`, `log`, `generate`, `reset`.
Maintains a bunch of logs, generates a final markdown report.
documentation
0
{"doc_type": "class", "class_name": "Report", "file_path": "nanochat/report.py", "repo_id": "karpathy/nanochat", "char_length": 61, "methods": ["__init__", "log", "generate", "reset"]}
vllm-project/vllm:vllm/utils/async_utils.py:AsyncMicrobatchTokenizer._batch_encode_loop
# Context: import asyncio from functools import partial from transformers.tokenization_utils_base import BatchEncoding def cancel_task_threadsafe(task: Task): ... def make_async(func: Callable[P, T], executor: Executor | None) -> Callable[P, Awaitable[T]]: ... def run_in_loop(loop: AbstractEventLoop, function: Callabl...
async def _batch_encode_loop(self, queue: asyncio.Queue, can_batch: bool): """Batch incoming encode requests for efficiency.""" while True: prompt, kwargs, result_future = await queue.get() prompts = [prompt] kwargs_list = [kwargs] result_futures = [result...
function_complex
1
{"cognitive_complexity": 42, "loc": 52, "code_loc": 44, "docstring_loc": 1, "function_name": "_batch_encode_loop", "class_name": "AsyncMicrobatchTokenizer", "qualname": "AsyncMicrobatchTokenizer._batch_encode_loop", "file_path": "vllm/utils/async_utils.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "runnab...
langflow-ai/langflow:src/backend/tests/unit/api/test_s3_endpoints.py:module_doc
Write a module-level docstring for the Python module `test_s3_endpoints` which contains class `TestS3FileEndpoints`.
API endpoint tests for S3 storage. This module tests the file API endpoints (download, upload, delete) work correctly with S3 storage. These are unit tests that mock the storage layer to focus on testing API logic: - Path parsing from database file records - HTTP response construction (StreamingResponse vs content) - ...
documentation
1
{"doc_type": "module", "module_name": "test_s3_endpoints", "file_path": "src/backend/tests/unit/api/test_s3_endpoints.py", "repo_id": "langflow-ai/langflow", "char_length": 560}
run-llama/llama_index:llama-index-integrations/memory/llama-index-memory-bedrock-agentcore/tests/test_agentcore_memory.py:TestBaseAgentCoreMemoryMethods:class_doc
Write a class-level docstring for `TestBaseAgentCoreMemoryMethods` which has methods: `test_create_event_success`, `test_create_event_no_client`, `test_create_event_empty_messages`, `test_create_event_no_event_id`, `test_list_events_simple`.
Test BaseAgentCoreMemory methods using AgentCoreMemory instance.
documentation
1
{"doc_type": "class", "class_name": "TestBaseAgentCoreMemoryMethods", "file_path": "llama-index-integrations/memory/llama-index-memory-bedrock-agentcore/tests/test_agentcore_memory.py", "repo_id": "run-llama/llama_index", "char_length": 64, "methods": ["test_create_event_success", "test_create_event_no_client", "test_c...
streamlit/streamlit:lib/tests/streamlit/components/v2/test_component_path_utils.py:test_looks_like_inline_content_heuristic
# Context: import pytest from streamlit.components.v2.component_path_utils import ComponentPathUtils def _touch(path: Path) -> None: ... def test_resolve_glob_pattern_accepts_file_within_root(tmp_path: Path) -> None: ... def test_resolve_glob_pattern_handles_subdirectory_wildcards_single_match(tmp_path: Path) -> None:...
def test_looks_like_inline_content_heuristic(value: str, expected_inline: bool) -> None: """Inline content heuristic should classify strings correctly across cases.""" assert ComponentPathUtils.looks_like_inline_content(value) == expected_inline
test
1
{"function_name": "test_looks_like_inline_content_heuristic", "class_name": null, "qualname": "test_looks_like_inline_content_heuristic", "file_path": "lib/tests/streamlit/components/v2/test_component_path_utils.py", "repo_id": "streamlit/streamlit", "loc": 3, "tested_modules": ["__future__", "typing", "streamlit.compo...
ray-project/ray:python/ray/data/tests/datasource/test_turbopuffer_datasink.py:TestConstructorValidation.test_accepts_region_only
# Context: def mock_turbopuffer_module(monkeypatch): ... def sink(): ... def mock_client(): ... def sample_table(): ... def make_sink(**kwargs) -> TurbopufferDatasink: ... class TestClientInitialization: ... class TestArrowTablePreparation: ... class TestSingleNamespaceBatching: ... class TestTransformToTurbopufferFor...
def test_accepts_region_only(self): """Constructor succeeds with region and no base_url.""" sink = make_sink(region="gcp-us-central1") assert sink.region == "gcp-us-central1" assert sink.base_url is None
test
0
{"function_name": "test_accepts_region_only", "class_name": "TestConstructorValidation", "qualname": "TestConstructorValidation.test_accepts_region_only", "file_path": "python/ray/data/tests/datasource/test_turbopuffer_datasink.py", "repo_id": "ray-project/ray", "loc": 5, "tested_modules": ["typing", "packaging.version...
deepfakes/faceswap:lib/config/config.py:FaceswapConfig.__init__
# Context: from .ini import ConfigFile from .objects import ConfigItem, ConfigSection, GlobalSection def get_configs() -> dict[str, FaceswapConfig]: ... def generate_configs(force: bool) -> None: ... class FaceswapConfig: def _get_plugin_group(self) -> str: ... def add_section(self, title: str, info: str) -> ...
def __init__(self, configfile: str | None = None) -> None: """ Init Configuration Parameters ---------- configfile : str, optional Optional path to a config file. ``None`` for default location. Default: ``None`` """ logger.debug("Initializing: %s", self.__cla...
function_simple
1
{"cognitive_complexity": 0, "loc": 21, "code_loc": 9, "docstring_loc": 7, "function_name": "__init__", "class_name": "FaceswapConfig", "qualname": "FaceswapConfig.__init__", "file_path": "lib/config/config.py", "repo_id": "deepfakes/faceswap", "has_docstring": true, "runnable_level": "project_runnable"}
run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-bigquery/tests/test_parameterized_queries.py:test_build_where_clause_and_params_with_single_filter
# Context: import pytest from google.cloud import bigquery from llama_index.core.vector_stores import MetadataFilter, MetadataFilters from llama_index.vector_stores.bigquery.utils import build_where_clause_and_params def test_build_where_clause_and_params(): ... def test_build_where_clause_and_params_with_nested_filte...
def test_build_where_clause_and_params_with_single_filter( key, value, operator, expected_where_clause, expected_query_parameter ): """It should construct a parameterized SQL WHERE clause and corresponding query parameters.""" # Given a MetadataFilters instance filters = MetadataFilters( filters...
test
1
{"function_name": "test_build_where_clause_and_params_with_single_filter", "class_name": null, "qualname": "test_build_where_clause_and_params_with_single_filter", "file_path": "llama-index-integrations/vector_stores/llama-index-vector-stores-bigquery/tests/test_parameterized_queries.py", "repo_id": "run-llama/llama_in...
crewAIInc/crewAI:lib/crewai/src/crewai/events/depends.py:EventHandler:class_doc
Write a class-level docstring for `EventHandler` (inherits from Protocol[EventT_co]) which has methods: `__call__`.
Protocol for event handler functions. Generic protocol that accepts any subclass of BaseEvent. Handlers can be either synchronous (returning None) or asynchronous (returning a coroutine).
documentation
0
{"doc_type": "class", "class_name": "EventHandler", "file_path": "lib/crewai/src/crewai/events/depends.py", "repo_id": "crewAIInc/crewAI", "char_length": 188, "methods": ["__call__"]}
run-llama/llama_index:llama-index-integrations/tools/llama-index-tools-signnow/tests/test_tools_signnow.py:test_class
# Context: from llama_index.tools.signnow.base import SignNowMCPToolSpec def test_from_env_returns_spec(mock_which: MagicMock) -> None: ... # Task: Write a Python test function `test_class` to verify the behavior of `class`. Module under test: llama_index.tools.signnow.base
def test_class() -> None: names_of_base_classes = [b.__name__ for b in SignNowMCPToolSpec.__mro__] assert "BaseToolSpec" in names_of_base_classes
test
1
{"function_name": "test_class", "class_name": null, "qualname": "test_class", "file_path": "llama-index-integrations/tools/llama-index-tools-signnow/tests/test_tools_signnow.py", "repo_id": "run-llama/llama_index", "loc": 3, "tested_modules": ["llama_index.tools.signnow.base"], "has_docstring": false, "runnable_level":...
crewAIInc/crewAI:lib/crewai-files/src/crewai_files/resolution/resolver.py:FileResolver._resolve_as_url
# Context: from crewai_files.core.resolved import ( FileReference, InlineBase64, InlineBytes, ResolvedFile, UrlReference, ) from crewai_files.core.sources import FileUrl from crewai_files.core.types import FileInput class FileContext: ... class FileResolverConfig: ... def create_resolver(provider: ...
def _resolve_as_url(file: FileInput) -> UrlReference: """Resolve a URL source as UrlReference. Args: file: The file with URL source. Returns: UrlReference with the URL and content type. """ source = file._file_source if not isinstance(source, Fil...
function_simple
0
{"cognitive_complexity": 1, "loc": 16, "code_loc": 7, "docstring_loc": 8, "function_name": "_resolve_as_url", "class_name": "FileResolver", "qualname": "FileResolver._resolve_as_url", "file_path": "lib/crewai-files/src/crewai_files/resolution/resolver.py", "repo_id": "crewAIInc/crewAI", "has_docstring": true, "runnable...
ray-project/ray:python/ray/tests/test_exceptions.py:TestAuthenticationError.test_is_ray_error_subclass
# Context: from ray.exceptions import AuthenticationError, RayError class FakeAuthMode(Enum): ... class TestAuthenticationError: auth_doc_url = "https://docs.ray.io/en/latest/ray-security/token-auth.html" def test_basic_creation(self): ... def test_auth_mode_note_in_message(self, auth_mode, expected_note)...
def test_is_ray_error_subclass(self): """Test that AuthenticationError is a RayError subclass.""" error = AuthenticationError("Test") assert isinstance(error, RayError)
test
0
{"function_name": "test_is_ray_error_subclass", "class_name": "TestAuthenticationError", "qualname": "TestAuthenticationError.test_is_ray_error_subclass", "file_path": "python/ray/tests/test_exceptions.py", "repo_id": "ray-project/ray", "loc": 4, "tested_modules": ["enum", "ray.exceptions"], "has_docstring": true, "run...
google/langextract:tests/inference_test.py:TestOllamaLanguageModel.test_ollama_default_timeout
# Context: from unittest import mock from langextract.providers import ollama class TestBaseLanguageModel(absltest.TestCase): ... class TestGeminiLanguageModel(absltest.TestCase): ... class TestOpenAILanguageModelInference(parameterized.TestCase): ... class TestOpenAILanguageModel(absltest.TestCase): ... class TestOl...
def test_ollama_default_timeout(self): """Test that default timeout is used when not specified.""" model = ollama.OllamaLanguageModel( model_id="test-model", model_url="http://localhost:11434", ) mock_response = mock.Mock(spec=["status_code", "json"]) mock_response.status_code = 200...
test
1
{"function_name": "test_ollama_default_timeout", "class_name": "TestOllamaLanguageModel", "qualname": "TestOllamaLanguageModel.test_ollama_default_timeout", "file_path": "tests/inference_test.py", "repo_id": "google/langextract", "loc": 23, "tested_modules": ["absl.testing", "absl.testing", "langextract", "langextract....
browser-use/browser-use:browser_use/screenshots/service.py:ScreenshotService.store_screenshot
# Context: import base64 import anyio from browser_use.observability import observe_debug class ScreenshotService: def __init__(self, agent_directory: str | Path): """Initialize with agent directory path""" self.agent_directory = Path(agent_directory) if isinstance(agent_directory, str) else agent_directory # ...
async def store_screenshot(self, screenshot_b64: str, step_number: int) -> str: """Store screenshot to disk and return the full path as string""" screenshot_filename = f'step_{step_number}.png' screenshot_path = self.screenshots_dir / screenshot_filename # Decode base64 and save to disk screenshot_data = bas...
function_simple
0
{"cognitive_complexity": 0, "loc": 12, "code_loc": 6, "docstring_loc": 1, "function_name": "store_screenshot", "class_name": "ScreenshotService", "qualname": "ScreenshotService.store_screenshot", "file_path": "browser_use/screenshots/service.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_le...
ray-project/ray:python/ray/llm/examples/serve/example_reset_kv_cache/reset_kv_cache_example.py:module_doc
Write a module-level docstring for the Python module `reset_kv_cache_example` which contains function `create_llm_config`, function `start_server`, function `reset_cache_via_handle`.
Example: Resetting KV Cache in Ray Serve LLM via Control Plane Messages. This example demonstrates two approaches to reset the KV cache on all replicas of a Ray Serve LLM deployment using DevIngress: 1. **HTTP Endpoint Path** (`--use-http`): Calls the built-in `/reset_prefix_cache` HTTP endpoint provided by Dev...
documentation
0
{"doc_type": "module", "module_name": "reset_kv_cache_example", "file_path": "python/ray/llm/examples/serve/example_reset_kv_cache/reset_kv_cache_example.py", "repo_id": "ray-project/ray", "char_length": 1312}
roboflow/supervision:.github/scripts/augment_links.py:get_repo_root
# Context: import os def augment_links_in_file(file_path: str, branch: str) -> None: ... def main() -> None: ... # Task: Write a Python function `get_repo_root` to get the repository root path. Returns: str
def get_repo_root() -> str: """Get the repository root path.""" script_dir = os.path.dirname(os.path.abspath(__file__)) return os.path.dirname(os.path.dirname(script_dir))
function_simple
1
{"cognitive_complexity": 0, "loc": 4, "code_loc": 2, "docstring_loc": 1, "function_name": "get_repo_root", "class_name": null, "qualname": "get_repo_root", "file_path": ".github/scripts/augment_links.py", "repo_id": "roboflow/supervision", "has_docstring": true, "runnable_level": "slib_runnable"}
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/adapters/enterprise_adapter.py:EnterpriseActionKitToolAdapter:class_doc
Write a class-level docstring for `EnterpriseActionKitToolAdapter` which has methods: `__init__`, `tools`, `_fetch_actions`, `_generate_detailed_description`, `_create_tools`.
Adapter that creates BaseTool instances for enterprise actions.
documentation
0
{"doc_type": "class", "class_name": "EnterpriseActionKitToolAdapter", "file_path": "lib/crewai-tools/src/crewai_tools/adapters/enterprise_adapter.py", "repo_id": "crewAIInc/crewAI", "char_length": 63, "methods": ["__init__", "tools", "_fetch_actions", "_generate_detailed_description", "_create_tools", "_set_enterprise_...
crewAIInc/crewAI:lib/crewai/src/crewai/mcp/transports/base.py:BaseTransport:class_doc
Write a class-level docstring for `BaseTransport` (inherits from ABC) which has methods: `__init__`, `transport_type`, `connected`, `read_stream`, `write_stream`.
Base class for MCP transport implementations. This abstract base class defines the interface that all transport implementations must follow. Transports handle the low-level communication with MCP servers.
documentation
0
{"doc_type": "class", "class_name": "BaseTransport", "file_path": "lib/crewai/src/crewai/mcp/transports/base.py", "repo_id": "crewAIInc/crewAI", "char_length": 205, "methods": ["__init__", "transport_type", "connected", "read_stream", "write_stream", "connect", "disconnect", "__aenter__", "__aexit__", "_set_streams"]}
fastapi/fastapi:tests/test_tutorial/test_security/test_tutorial004.py:test_openapi_schema
# Context: from types import ModuleType from fastapi.testclient import TestClient from inline_snapshot import snapshot def get_mod(request: pytest.FixtureRequest): ... def get_access_token(username, password, client: TestClient): ... def test_login(mod: ModuleType): ... def test_login_incorrect_password(mod: ModuleTyp...
def test_openapi_schema(mod: ModuleType): client = TestClient(mod.app) response = client.get("/openapi.json") assert response.status_code == 200, response.text assert response.json() == snapshot( { "openapi": "3.1.0", "info": {"title": "FastAPI", "version": "0.1.0"}, ...
test
1
{"function_name": "test_openapi_schema", "class_name": null, "qualname": "test_openapi_schema", "file_path": "tests/test_tutorial/test_security/test_tutorial004.py", "repo_id": "fastapi/fastapi", "loc": 187, "tested_modules": ["types", "fastapi.testclient", "inline_snapshot", "utils"], "has_docstring": false, "runnable...
deepfakes/faceswap:lib/config/ini.py:ConfigFile.format_help
# Context: import textwrap class ConfigFile: def __init__(self, plugin_group: str, ini_path: str | None = None) -> None: parse_class_init(locals()) self._plugin_group = plugin_group self._file_path = self._get_config_path(ini_path) self._parser = self._get_new_configparser() ...
def format_help(self, helptext: str, is_section: bool = False) -> str: """ Format comments for insertion into a config ini file Parameters ---------- helptext : str The help text to be formatted is_section : bool, optional ``True`` if the help text pertai...
function_complex
1
{"cognitive_complexity": 6, "loc": 29, "code_loc": 13, "docstring_loc": 15, "function_name": "format_help", "class_name": "ConfigFile", "qualname": "ConfigFile.format_help", "file_path": "lib/config/ini.py", "repo_id": "deepfakes/faceswap", "has_docstring": true, "runnable_level": "file_runnable"}
ray-project/ray:python/ray/serve/tests/test_list_outbound_deployments.py:TestListOutboundDeployments.test_no_handles
# Context: from typing import List import ray from ray import serve from ray.serve._private.common import DeploymentID class DownstreamA: ... class DownstreamB: ... class UpstreamWithStoredHandles: ... class UpstreamWithNestedHandles: ... class DynamicDeployment: ... def get_replica_actor_handle(deployment_name: str, ...
async def test_no_handles(self, serve_instance): """Test deployment with no outbound handles.""" app_name = "test_no_handles" # Deploy a simple deployment with no handles app = DownstreamA.bind() serve.run(app, name=app_name) # Get the replica actor replica_acto...
test
0
{"function_name": "test_no_handles", "class_name": "TestListOutboundDeployments", "qualname": "TestListOutboundDeployments.test_no_handles", "file_path": "python/ray/serve/tests/test_list_outbound_deployments.py", "repo_id": "ray-project/ray", "loc": 18, "tested_modules": ["typing", "ray", "ray.serve._private.common", ...
langflow-ai/langflow:src/backend/tests/unit/base/mcp/test_mcp_util.py:TestMCPUtilityFunctions.test_get_unique_name
# Context: from lfx.base.mcp import util class TestMCPSessionManager: ... class TestHeaderValidation: ... class TestGlobalVariableResolution: ... class TestStreamableHTTPHeaderIntegration: ... class TestUpdateToolsStdioHeaders: ... class TestFieldNameConversion: ... class TestToolExecutionWithFieldConversion: ... clas...
def test_get_unique_name(self): """Test unique name generation.""" names = {"foo", "foo_1"} assert util.get_unique_name("foo", 10, names) == "foo_2" assert util.get_unique_name("bar", 10, names) == "bar" assert util.get_unique_name("longname", 4, {"long"}) == "lo_1"
test
1
{"function_name": "test_get_unique_name", "class_name": "TestMCPUtilityFunctions", "qualname": "TestMCPUtilityFunctions.test_get_unique_name", "file_path": "src/backend/tests/unit/base/mcp/test_mcp_util.py", "repo_id": "langflow-ai/langflow", "loc": 6, "tested_modules": ["lfx.base.mcp", "lfx.base.mcp.util", "lfx.base.m...
infiniflow/ragflow:common/metadata_utils.py:apply_meta_data_filter
# Context: from typing import Any, Callable, Dict from rag.prompts.generator import gen_meta_filter # move from the top of the file to avoid circular import def convert_conditions(metadata_condition): ... def meta_filter(metas: dict, filters: list[dict], logic: str): ... def dedupe_list(values: list) -> list: ... def ...
async def apply_meta_data_filter( meta_data_filter: dict | None, metas: dict, question: str, chat_mdl: Any = None, base_doc_ids: list[str] | None = None, manual_value_resolver: Callable[[dict], dict] | None = None, ) -> list[str] | None: """ Apply metadata filtering rules and return the ...
function_complex
1
{"cognitive_complexity": 31, "loc": 63, "code_loc": 37, "docstring_loc": 12, "function_name": "apply_meta_data_filter", "class_name": null, "qualname": "apply_meta_data_filter", "file_path": "common/metadata_utils.py", "repo_id": "infiniflow/ragflow", "has_docstring": true, "runnable_level": "project_runnable"}
huggingface/transformers:tests/models/parakeet/test_feature_extraction_parakeet.py:module_doc
Write a module-level docstring for the Python module `test_feature_extraction_parakeet` which contains function `floats_list`, class `ParakeetFeatureExtractionTester`, class `ParakeetFeatureExtractionTest`.
Testing suite for the Parakeet feature extraction.
documentation
0
{"doc_type": "module", "module_name": "test_feature_extraction_parakeet", "file_path": "tests/models/parakeet/test_feature_extraction_parakeet.py", "repo_id": "huggingface/transformers", "char_length": 50}
browser-use/browser-use:browser_use/llm/browser_use/chat.py:module_doc
Write a module-level docstring for the Python module `chat` which contains class `ChatBrowserUse`.
ChatBrowserUse - Client for browser-use cloud API This wraps the BaseChatModel protocol and sends requests to the browser-use cloud API for optimized browser automation LLM inference.
documentation
0
{"doc_type": "module", "module_name": "chat", "file_path": "browser_use/llm/browser_use/chat.py", "repo_id": "browser-use/browser-use", "char_length": 184}
docling-project/docling:docling/experimental/pipeline/threaded_layout_vlm_pipeline.py:ThreadedLayoutVlmPipeline._build_document
# Context: from typing import TYPE_CHECKING, List, Optional, Union, cast from docling.backend.pdf_backend import PdfDocumentBackend from docling.datamodel.base_models import ConversionStatus, Page from docling.datamodel.document import ConversionResult from docling.pipeline.standard_pdf_pipeline import ( Processing...
def _build_document(self, conv_res: ConversionResult) -> ConversionResult: """Build document using threaded layout+VLM pipeline.""" run_id = next(self._run_seq) assert isinstance(conv_res.input._backend, PdfDocumentBackend) backend = conv_res.input._backend # Initialize pages ...
function_complex
1
{"cognitive_complexity": 50, "loc": 82, "code_loc": 68, "docstring_loc": 1, "function_name": "_build_document", "class_name": "ThreadedLayoutVlmPipeline", "qualname": "ThreadedLayoutVlmPipeline._build_document", "file_path": "docling/experimental/pipeline/threaded_layout_vlm_pipeline.py", "repo_id": "docling-project/do...
ray-project/ray:python/ray/llm/_internal/common/utils/lora_utils.py:get_lora_id
Write a Python function `get_lora_id` to get lora id for a given lora model id. Parameters: lora_model_id: str Returns: str
def get_lora_id(lora_model_id: str) -> str: """Get lora id for a given lora model id.""" return ":".join(lora_model_id.split(":")[1:])
function_simple
0
{"cognitive_complexity": 0, "loc": 3, "code_loc": 1, "docstring_loc": 1, "function_name": "get_lora_id", "class_name": null, "qualname": "get_lora_id", "file_path": "python/ray/llm/_internal/common/utils/lora_utils.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "self_contained"}
crewAIInc/crewAI:lib/crewai/tests/hooks/test_decorators.py:TestMultipleDecorators.test_decorator_and_manual_registration_work_together
# Context: from crewai.hooks import ( after_llm_call, after_tool_call, before_llm_call, before_tool_call, get_after_llm_call_hooks, get_after_tool_call_hooks, get_before_llm_call_hooks, get_before_tool_call_hooks, ) from crewai.hooks import register_before_tool_call_hook def clear_hooks...
def test_decorator_and_manual_registration_work_together(self): """Test that decorators and manual registration can be mixed.""" from crewai.hooks import register_before_tool_call_hook @before_tool_call def decorated_hook(context): return None def manual_hook(contex...
test
0
{"function_name": "test_decorator_and_manual_registration_work_together", "class_name": "TestMultipleDecorators", "qualname": "TestMultipleDecorators.test_decorator_and_manual_registration_work_together", "file_path": "lib/crewai/tests/hooks/test_decorators.py", "repo_id": "crewAIInc/crewAI", "loc": 16, "tested_modules...
ray-project/ray:python/ray/serve/tests/test_task_processor.py:TestTaskConsumerWithRayServe.test_task_processor_with_cancel_tasks_and_app_custom_config
# Context: import os import ray from ray import serve from ray._common.test_utils import SignalActor, wait_for_condition from ray.serve.schema import CeleryAdapterConfig, TaskProcessorConfig from ray.serve.task_consumer import ( instantiate_adapter_from_config, task_consumer, task_handler, ) class Processe...
def test_task_processor_with_cancel_tasks_and_app_custom_config( self, external_redis, serve_instance # noqa: F811 ): """Test the cancel task functionality with celery broker.""" redis_address = os.environ.get("RAY_REDIS_ADDRESS") processor_config = TaskProcessorConfig( ...
test
0
{"function_name": "test_task_processor_with_cancel_tasks_and_app_custom_config", "class_name": "TestTaskConsumerWithRayServe", "qualname": "TestTaskConsumerWithRayServe.test_task_processor_with_cancel_tasks_and_app_custom_config", "file_path": "python/ray/serve/tests/test_task_processor.py", "repo_id": "ray-project/ray...
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/source_service.py:SourceService.update_feed
# Context: from typing import List, Optional, Dict, Any from fastapi import HTTPException from services.db_service import sources_db, tracking_db class SourceService: async def get_sources(self, page: int, per_page: int, category: Optional[str], search: Optional[str], include_inactive: bool) -> PaginatedSources: ....
async def update_feed(self, feed_id: int, feed_data: Dict[str, Any]) -> Dict[str, Any]: """Update an existing feed.""" try: feed_query = "SELECT id, source_id FROM source_feeds WHERE id = ?" feed = await sources_db.execute_query(feed_query, (feed_id,), fetch=True, fetch_one=True)...
function_complex
0
{"cognitive_complexity": 16, "loc": 34, "code_loc": 32, "docstring_loc": 1, "function_name": "update_feed", "class_name": "SourceService", "qualname": "SourceService.update_feed", "file_path": "advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/source_service.py", "repo_id": "Shubhamsaboo/a...
browser-use/browser-use:browser_use/integrations/gmail/service.py:GmailService._parse_email
# Context: from typing import Any class GmailService: SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] def __init__( self, credentials_file: str | None = None, token_file: str | None = None, config_dir: str | None = None, access_token: str | None = None, ): """ Initialize Gmail Service ...
def _parse_email(self, message: dict[str, Any]) -> dict[str, Any]: """Parse Gmail message into readable format""" headers = {h['name']: h['value'] for h in message['payload']['headers']} return { 'id': message['id'], 'thread_id': message['threadId'], 'subject': headers.get('Subject', ''), 'from': hea...
function_simple
0
{"cognitive_complexity": 0, "loc": 15, "code_loc": 12, "docstring_loc": 1, "function_name": "_parse_email", "class_name": "GmailService", "qualname": "GmailService._parse_email", "file_path": "browser_use/integrations/gmail/service.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_level": "cla...
vllm-project/vllm:vllm/model_executor/models/bailing_moe_linear.py:BailingMoeV25:class_doc
Write a class-level docstring for `BailingMoeV25` (inherits from nn.Module) which has methods: `__init__`, `forward`.
Bailing MoE v2.5 - standalone implementation for linear attention model.
documentation
1
{"doc_type": "class", "class_name": "BailingMoeV25", "file_path": "vllm/model_executor/models/bailing_moe_linear.py", "repo_id": "vllm-project/vllm", "char_length": 72, "methods": ["__init__", "forward"]}
crewAIInc/crewAI:lib/crewai/tests/utilities/test_agent_utils.py:TestConvertToolsToOpenaiSchema.test_converts_multiple_tools
# Context: from crewai.utilities.agent_utils import ( _asummarize_chunks, _estimate_token_count, _extract_summary_tags, _format_messages_for_summary, _split_messages_into_chunks, convert_tools_to_openai_schema, parse_tool_call_args, summarize_messages, ) class CalculatorInput(BaseModel)...
def test_converts_multiple_tools(self) -> None: """Test converting multiple tools to OpenAI schema.""" tools = [CalculatorTool(), SearchTool()] schemas, functions, _ = convert_tools_to_openai_schema(tools) assert len(schemas) == 2 assert len(functions) == 2 # Check calc...
test
0
{"function_name": "test_converts_multiple_tools", "class_name": "TestConvertToolsToOpenaiSchema", "qualname": "TestConvertToolsToOpenaiSchema.test_converts_multiple_tools", "file_path": "lib/crewai/tests/utilities/test_agent_utils.py", "repo_id": "crewAIInc/crewAI", "loc": 17, "tested_modules": ["__future__", "typing",...
ray-project/ray:python/ray/data/tests/expressions/test_namespace_arr.py:module_doc
Write a module-level docstring for the Python module `test_namespace_arr` which contains function `_make_fixed_size_list_table`, function `test_arr_to_list_fixed_size`, function `test_arr_to_list_invalid_dtype_raises`.
Integration tests for array namespace expressions. These tests require Ray and test end-to-end array namespace expression evaluation.
documentation
0
{"doc_type": "module", "module_name": "test_namespace_arr", "file_path": "python/ray/data/tests/expressions/test_namespace_arr.py", "repo_id": "ray-project/ray", "char_length": 134}
google/langextract:tests/progress_test.py:ProgressTest.test_extraction_progress_bar
# Context: import tqdm from langextract import progress class ProgressTest(unittest.TestCase): def test_download_progress_bar(self): ... def test_save_load_progress_bars(self): ... def test_model_info_extraction(self): ... def test_formatting_functions(self): ... # Task: Write a Python test method `te...
def test_extraction_progress_bar(self): """Test extraction progress bar creation.""" pbar = progress.create_extraction_progress_bar( range(10), "gemini-2.0-flash" ) self.assertIsInstance(pbar, tqdm.tqdm) self.assertIn("LangExtract", pbar.desc) self.assertIn("gemini-2.0-flash", pbar.desc...
test
1
{"function_name": "test_extraction_progress_bar", "class_name": "ProgressTest", "qualname": "ProgressTest.test_extraction_progress_bar", "file_path": "tests/progress_test.py", "repo_id": "google/langextract", "loc": 9, "tested_modules": ["langextract"], "has_docstring": true, "runnable_level": "project_runnable"}
ray-project/ray:python/ray/data/_internal/planner/plan_download_op.py:PartitionActor:class_doc
Write a class-level docstring for `PartitionActor` which has methods: `__init__`, `__call__`, `_estimate_nrows_per_partition`, `_sample_sizes`.
Actor that partitions download operations based on estimated file sizes. For multiple URI columns, estimates the combined size across all columns.
documentation
0
{"doc_type": "class", "class_name": "PartitionActor", "file_path": "python/ray/data/_internal/planner/plan_download_op.py", "repo_id": "ray-project/ray", "char_length": 147, "methods": ["__init__", "__call__", "_estimate_nrows_per_partition", "_sample_sizes"]}
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/bip32_path.py:Bip32PathParser.Parse
# Context: class Bip32PathConst: ... class Bip32Path: ... class Bip32PathParser: def __ParseElements(path_elems: List[str]) -> Bip32Path: ... def __ParseElem(path_elem: str) -> int: ... # Task: Write a Python method `Parse` for the class `Bip32PathParser` to parse a path and return a Bip32Path object. Param...
def Parse(path: str) -> Bip32Path: """ Parse a path and return a Bip32Path object. Args: path (str): Path Returns: Bip32Path object: Bip32Path object Raises: Bip32PathError: If the path is not valid """ # Remove trailing "/"...
function_simple
1
{"cognitive_complexity": 1, "loc": 22, "code_loc": 5, "docstring_loc": 12, "function_name": "Parse", "class_name": "Bip32PathParser", "qualname": "Bip32PathParser.Parse", "file_path": "python/ccxt/static_dependencies/bip/bip32/bip32_path.py", "repo_id": "ccxt/ccxt", "has_docstring": true, "runnable_level": "file_runnab...
browser-use/browser-use:browser_use/llm/openai/serializer.py:OpenAIMessageSerializer._serialize_user_content
# Context: from openai.types.chat import ( ChatCompletionAssistantMessageParam, ChatCompletionContentPartImageParam, ChatCompletionContentPartRefusalParam, ChatCompletionContentPartTextParam, ChatCompletionMessageFunctionToolCallParam, ChatCompletionMessageParam, ChatCompletionSystemMessageParam, ChatCompletion...
def _serialize_user_content( content: str | list[ContentPartTextParam | ContentPartImageParam], ) -> str | list[ChatCompletionContentPartTextParam | ChatCompletionContentPartImageParam]: """Serialize content for user messages (text and images allowed).""" if isinstance(content, str): return content seriali...
function_simple
0
{"cognitive_complexity": 5, "loc": 14, "code_loc": 9, "docstring_loc": 1, "function_name": "_serialize_user_content", "class_name": "OpenAIMessageSerializer", "qualname": "OpenAIMessageSerializer._serialize_user_content", "file_path": "browser_use/llm/openai/serializer.py", "repo_id": "browser-use/browser-use", "has_do...
huggingface/transformers:tests/models/sam2/test_modeling_sam2.py:Sam2ModelIntegrationTest.test_inference_batched_images_batched_boxes
# Context: from transformers.testing_utils import ( backend_empty_cache, require_torch, slow, torch_device, ) import torch class Sam2VisionModelTester: ... class Sam2VisionModelTest(ModelTesterMixin, unittest.TestCase): ... class Sam2PromptEncoderTester: ... class Sam2MaskDecoderTester: ... class Sam2M...
def test_inference_batched_images_batched_boxes(self): raw_image1 = prepare_image() raw_image2 = prepare_groceries_image() input_boxes = [ [[75, 275, 1725, 850], [425, 600, 700, 875], [1375, 550, 1650, 800], [1240, 675, 1400, 750]], [[450, 170, 520, 350], [350, 190, 450, ...
test
0
{"function_name": "test_inference_batched_images_batched_boxes", "class_name": "Sam2ModelIntegrationTest", "qualname": "Sam2ModelIntegrationTest.test_inference_batched_images_batched_boxes", "file_path": "tests/models/sam2/test_modeling_sam2.py", "repo_id": "huggingface/transformers", "loc": 43, "tested_modules": ["tra...
crewAIInc/crewAI:lib/crewai-tools/tests/tools/rag/test_rag_tool_add_data_type.py:TestFileExistenceValidation.test_docx_file_not_found_raises_error
# Context: import pytest from crewai_tools.tools.rag.rag_tool import RagTool def mock_rag_client() -> MagicMock: ... def rag_tool(mock_rag_client: MagicMock) -> RagTool: ... class TestDataTypeFileAlias: ... class TestDataTypeStringValues: ... class TestDataTypeEnumValues: ... class TestInvalidDataType: ... class TestK...
def test_docx_file_not_found_raises_error(self, rag_tool: RagTool) -> None: """Test that non-existent DOCX file raises FileNotFoundError.""" with pytest.raises(FileNotFoundError, match="File does not exist"): rag_tool.add(path="nonexistent.docx", data_type="docx")
test
0
{"function_name": "test_docx_file_not_found_raises_error", "class_name": "TestFileExistenceValidation", "qualname": "TestFileExistenceValidation.test_docx_file_not_found_raises_error", "file_path": "lib/crewai-tools/tests/tools/rag/test_rag_tool_add_data_type.py", "repo_id": "crewAIInc/crewAI", "loc": 4, "tested_module...
TheAlgorithms/Python:machine_learning/t_stochastic_neighbour_embedding.py:main
# Context: import numpy as np def collect_dataset() -> tuple[ndarray, ndarray]: ... def compute_pairwise_affinities(data_matrix: ndarray, sigma: float) -> ndarray: ... def compute_low_dim_affinities(embedding_matrix: ndarray) -> tuple[ndarray, ndarray]: ... def apply_tsne(data_matrix: ndarray, n_components: int, learn...
def main() -> None: """ Run t-SNE on the Iris dataset and display the first 5 embeddings. >>> main() # doctest: +ELLIPSIS t-SNE embedding (first 5 points): [[... """ features, _labels = collect_dataset() embedding = apply_tsne(features, n_components=2, n_iter=300) if not isinstanc...
function_simple
1
{"cognitive_complexity": 1, "loc": 16, "code_loc": 6, "docstring_loc": 7, "function_name": "main", "class_name": null, "qualname": "main", "file_path": "machine_learning/t_stochastic_neighbour_embedding.py", "repo_id": "TheAlgorithms/Python", "has_docstring": true, "runnable_level": "file_runnable"}
ray-project/ray:python/ray/tests/test_label_scheduling.py:test_fallback_strategy
# Context: import ray class MyActor: ... def get_node_id(): ... def cluster_with_labeled_nodes(ray_start_cluster): ... def test_label_selector_equals(cluster_with_labeled_nodes): ... def test_label_selector_not_equals(cluster_with_labeled_nodes): ... def test_label_selector_in(cluster_with_labeled_nodes): ... def test...
def test_fallback_strategy(cluster_with_labeled_nodes): # Create a RayCluster with labelled nodes. gpu_node, _, _ = cluster_with_labeled_nodes # Define an unsatisfiable label selector. infeasible_label_selector = {"ray.io/accelerator-type": "does-not-exist"} # Create a fallback strategy with multi...
test
0
{"function_name": "test_fallback_strategy", "class_name": null, "qualname": "test_fallback_strategy", "file_path": "python/ray/tests/test_label_scheduling.py", "repo_id": "ray-project/ray", "loc": 22, "tested_modules": [], "has_docstring": false, "runnable_level": "file_runnable"}
ray-project/ray:python/ray/dashboard/modules/reporter/tests/test_gpu_profiler_manager.py:test_start_monitoring_daemon
# Context: from ray.dashboard.modules.reporter.gpu_profile_manager import GpuProfilingManager def mock_node_has_gpus(monkeypatch): ... def mock_dynolog_binaries(monkeypatch): ... def mock_subprocess_popen(monkeypatch): ... def mock_asyncio_create_subprocess_exec(monkeypatch): ... def test_enabled(tmp_path, mock_node_h...
def test_start_monitoring_daemon( tmp_path, mock_node_has_gpus, mock_dynolog_binaries, mock_subprocess_popen ): gpu_profiler = GpuProfilingManager(tmp_path, ip_address=LOCALHOST) mocked_popen, mocked_proc = mock_subprocess_popen mocked_proc.pid = 123 mocked_proc.poll.return_value = None gpu_pr...
test
0
{"function_name": "test_start_monitoring_daemon", "class_name": null, "qualname": "test_start_monitoring_daemon", "file_path": "python/ray/dashboard/modules/reporter/tests/test_gpu_profiler_manager.py", "repo_id": "ray-project/ray", "loc": 23, "tested_modules": ["pathlib", "ray.dashboard.modules.reporter.gpu_profile_ma...
apache/airflow:providers/common/sql/tests/unit/common/sql/datafusion/test_engine.py:TestDataFusionEngine.test_get_credentials_unknown_type
# Context: from unittest.mock import MagicMock, patch import pytest from airflow.providers.common.sql.datafusion.engine import DataFusionEngine class TestDataFusionEngine: def setup_connections(self, create_connection_without_db): ... def test_init(self): ... def test_session_context_property(self): ... ...
def test_get_credentials_unknown_type(self): mock_conn = MagicMock() mock_conn.conn_type = "dummy" engine = DataFusionEngine() with pytest.raises(ValueError, match="Unknown connection type dummy"): engine._get_credentials(mock_conn)
test
1
{"function_name": "test_get_credentials_unknown_type", "class_name": "TestDataFusionEngine", "qualname": "TestDataFusionEngine.test_get_credentials_unknown_type", "file_path": "providers/common/sql/tests/unit/common/sql/datafusion/test_engine.py", "repo_id": "apache/airflow", "loc": 7, "tested_modules": ["__future__", ...
huggingface/diffusers:src/diffusers/models/transformers/transformer_glm_image.py:license_header
Add a Apache-2.0 license header comment for the project 'diffusers', authored by The CogView team, Tsinghua University & ZhipuAI and The HuggingFace Team, year 2025.
# Copyright 2025 The CogView team, Tsinghua University & ZhipuAI and The HuggingFace 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/l...
license
1
{"license_type": "Apache-2.0", "author": "The CogView team, Tsinghua University & ZhipuAI and The HuggingFace Team", "year": "2025", "source": "header", "repo_id": "huggingface/diffusers"}
jax-ml/jax:tests/mosaic/gpu_torch_test_distributed.py:TorchTest.test_get_device_id
# Context: import jax from jax._src.lib.mlir import ir from jax._src.lib.mlir.dialects import arith from jax._src.lib.mlir.dialects import memref import jax.numpy as jnp import jax.experimental.mosaic.gpu as mgpu import torch import torch.distributed as dist class TorchTest(parameterized.TestCase): def setUpClass(...
def test_get_device_id(self): index = ir.IndexType.get() def kernel_body(ctx, dst, _): device_id = ctx.device_id() memref.store(device_id, dst, [arith.constant(index, 0)]) out_shape = jax.ShapeDtypeStruct((1,), jnp.int32) kernel = mgpu.as_torch_gpu_kernel( kernel_body, (1, 1, 1), (128...
test
1
{"function_name": "test_get_device_id", "class_name": "TorchTest", "qualname": "TorchTest.test_get_device_id", "file_path": "tests/mosaic/gpu_torch_test_distributed.py", "repo_id": "jax-ml/jax", "loc": 13, "tested_modules": ["absl.testing", "jax._src", "jax._src", "jax._src", "jax._src.interpreters"], "has_docstring": ...
streamlit/streamlit:lib/tests/streamlit/elements/feedback_test.py:test_apptest_feedback_value_retained_on_rerun
# Context: import streamlit as st from streamlit.testing.v1 import AppTest class TestFeedbackSerde: ... class TestFeedbackCommand(DeltaGeneratorTestCase): ... class TestFeedbackWidthConfig(DeltaGeneratorTestCase): ... class TestFeedbackStableId(DeltaGeneratorTestCase): ... class TestFeedbackDuplicateId(DeltaGeneratorT...
def test_apptest_feedback_value_retained_on_rerun(): """Test that feedback value is retained across reruns.""" from streamlit.testing.v1 import AppTest def script(): import streamlit as st st.feedback("faces", key="test_feedback") st.button("Rerun") at = AppTest.from_function(...
test
1
{"function_name": "test_apptest_feedback_value_retained_on_rerun", "class_name": null, "qualname": "test_apptest_feedback_value_retained_on_rerun", "file_path": "lib/tests/streamlit/elements/feedback_test.py", "repo_id": "streamlit/streamlit", "loc": 21, "tested_modules": ["__future__", "typing", "parameterized", "stre...
vllm-project/vllm:tests/kernels/helion/test_register.py:TestValidateHelionSettings.test_accepts_valid_settings
# Context: import helion from vllm.kernels.helion.register import ( _HOP_AVAILABLE, ConfiguredHelionKernel, HelionKernelWrapper, get_kernel_by_name, get_registered_kernels, register_kernel, validate_helion_settings, ) def sample_configs(): ... def sample_kernel(): ... def config_manager_wit...
def test_accepts_valid_settings(self): """Test that valid settings without conflicts are accepted.""" settings = helion.Settings() settings.static_shapes = False settings.print_output_code = True validate_helion_settings(settings, "test_kernel") # Should not raise
test
1
{"function_name": "test_accepts_valid_settings", "class_name": "TestValidateHelionSettings", "qualname": "TestValidateHelionSettings.test_accepts_valid_settings", "file_path": "tests/kernels/helion/test_register.py", "repo_id": "vllm-project/vllm", "loc": 6, "tested_modules": ["vllm.utils.import_utils", "vllm.kernels.h...
vllm-project/vllm:tests/v1/kv_connector/unit/test_nixl_connector.py:TestNixlHandshake.test_handshake_succeed_on_kv_cache_layout_mismatch_with_experimental
# Context: from unittest.mock import MagicMock, patch from vllm.distributed.kv_transfer.kv_connector.v1.nixl_connector import ( KVConnectorRole, NixlAgentMetadata, NixlConnector, NixlConnectorMetadata, NixlConnectorScheduler, NixlConnectorWorker, NixlHandshakePayload, NixlKVConnectorStat...
def test_handshake_succeed_on_kv_cache_layout_mismatch_with_experimental( self, default_vllm_config, dist_init ): """ Verify that adding a remote agent fails if kv_cache_layout differs. This test is only relevant for heterogeneous TP. """ vllm_config = create_vllm_con...
test
1
{"function_name": "test_handshake_succeed_on_kv_cache_layout_mismatch_with_experimental", "class_name": "TestNixlHandshake", "qualname": "TestNixlHandshake.test_handshake_succeed_on_kv_cache_layout_mismatch_with_experimental", "file_path": "tests/v1/kv_connector/unit/test_nixl_connector.py", "repo_id": "vllm-project/vl...
ray-project/ray:python/ray/dashboard/modules/reporter/tests/test_gpu_profiler_manager.py:module_doc
Write a module-level docstring for the Python module `test_gpu_profiler_manager` which contains function `mock_node_has_gpus`, function `mock_dynolog_binaries`, function `mock_subprocess_popen`, function `mock_asyncio_create_subprocess_exec`, function `test_enabled`.
Unit tests for the GPU profiler manager. All GPU and dynolog dependencies are mocked out. This test just verifies that commands are launched correctly and that validations are correctly performed.
documentation
0
{"doc_type": "module", "module_name": "test_gpu_profiler_manager", "file_path": "python/ray/dashboard/modules/reporter/tests/test_gpu_profiler_manager.py", "repo_id": "ray-project/ray", "char_length": 197}
streamlit/streamlit:lib/tests/streamlit/web/server/starlette/starlette_websocket_test.py:TestStarletteSessionClient.test_write_forward_msg_queues_message
# Context: from unittest.mock import AsyncMock, MagicMock, patch import pytest from streamlit.web.server.starlette.starlette_websocket import ( StarletteClientContext, StarletteSessionClient, _gather_user_info, _get_signed_cookie_with_chunks, _is_origin_allowed, _parse_decoded_user_cookie, _...
async def test_write_forward_msg_queues_message(self) -> None: """Test that write_forward_msg adds message to queue.""" mock_websocket = MagicMock() client = StarletteSessionClient(mock_websocket) mock_msg = MagicMock() with patch( "streamlit.web.server.starlette.st...
test
1
{"function_name": "test_write_forward_msg_queues_message", "class_name": "TestStarletteSessionClient", "qualname": "TestStarletteSessionClient.test_write_forward_msg_queues_message", "file_path": "lib/tests/streamlit/web/server/starlette/starlette_websocket_test.py", "repo_id": "streamlit/streamlit", "loc": 17, "tested...
crewAIInc/crewAI:lib/crewai/tests/llms/bedrock/test_bedrock_async.py:test_bedrock_async_with_temperature
# Context: import pytest from crewai.llm import LLM async def test_bedrock_async_basic_call(): ... async def test_bedrock_async_with_max_tokens(): ... async def test_bedrock_async_with_system_message(): ... async def test_bedrock_async_conversation(): ... async def test_bedrock_async_multiple_calls(): ... async def te...
async def test_bedrock_async_with_temperature(): """Test async call with temperature parameter.""" llm = LLM(model="bedrock/us.anthropic.claude-3-5-sonnet-20241022-v2:0", temperature=0.1) result = await llm.acall("Say the word 'test' once") assert result is not None assert isinstance(result, str)
test
0
{"function_name": "test_bedrock_async_with_temperature", "class_name": null, "qualname": "test_bedrock_async_with_temperature", "file_path": "lib/crewai/tests/llms/bedrock/test_bedrock_async.py", "repo_id": "crewAIInc/crewAI", "loc": 8, "tested_modules": ["crewai.llm"], "has_docstring": true, "runnable_level": "project...
vllm-project/vllm:vllm/model_executor/models/gpt_oss.py:_get_moe_weight_dtype
Write a Python function `_get_moe_weight_dtype` to helper function to get MoE quantization weight dtype. Parameters: layer_id: int Returns: str | None
def _get_moe_weight_dtype(layer_id: int = 0) -> str | None: """Helper function to get MoE quantization weight dtype. Args: layer_id: Layer index to check (default 0, as all layers should have the same quantization method) Returns: ...
function_simple
1
{"cognitive_complexity": 1, "loc": 13, "code_loc": 3, "docstring_loc": 9, "function_name": "_get_moe_weight_dtype", "class_name": null, "qualname": "_get_moe_weight_dtype", "file_path": "vllm/model_executor/models/gpt_oss.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "runnable_level": "self_contained"}
apache/airflow:providers/teradata/src/airflow/providers/teradata/utils/bteq_util.py:is_valid_encoding
Write a Python function `is_valid_encoding` to check if the file can be read with the specified encoding. Parameters: file_path: str, encoding: str Returns: bool
def is_valid_encoding(file_path: str, encoding: str = "UTF-8") -> bool: """ Check if the file can be read with the specified encoding. :param file_path: Path to the file to be checked. :param encoding: Encoding to use for reading the file. :return: True if the file can be read with the specified en...
function_simple
1
{"cognitive_complexity": 0, "loc": 11, "code_loc": 3, "docstring_loc": 7, "function_name": "is_valid_encoding", "class_name": null, "qualname": "is_valid_encoding", "file_path": "providers/teradata/src/airflow/providers/teradata/utils/bteq_util.py", "repo_id": "apache/airflow", "has_docstring": true, "runnable_level": ...
binary-husky/gpt_academic:crazy_functions/doc_fns/read_fns/unstructured_all/paper_metadata_extractor.py:PaperMetadataExtractor._validate_file
# Context: from pathlib import Path from typing import Optional, Set, Dict, Union, List import os class PaperMetadata: ... class ExtractorConfig: ... def main(): ... class PaperMetadataExtractor: SECTION_PATTERNS = { def __init__(self, config: Optional[ExtractorConfig] = None): """初始化提取器 Args...
def _validate_file(self, file_path: Union[str, Path], max_size_mb: int = 100) -> Path: """验证文件 Args: file_path: 文件路径 max_size_mb: 允许的最大文件大小(MB) Returns: Path: 验证后的Path对象 Raises: ValueError: 文件不存在、格式不支持或大小超限 PermissionError: 没...
function_simple
1
{"cognitive_complexity": 5, "loc": 38, "code_loc": 18, "docstring_loc": 13, "function_name": "_validate_file", "class_name": "PaperMetadataExtractor", "qualname": "PaperMetadataExtractor._validate_file", "file_path": "crazy_functions/doc_fns/read_fns/unstructured_all/paper_metadata_extractor.py", "repo_id": "binary-hus...
ray-project/ray:rllib/algorithms/tqc/default_tqc_rl_module.py:DefaultTQCRLModule:class_doc
Write a class-level docstring for `DefaultTQCRLModule` (inherits from RLModule, InferenceOnlyAPI, TargetNetworkAPI, QNetAPI) which has methods: `setup`, `make_target_networks`, `get_non_inference_attributes`, `get_target_network_pairs`, `get_initial_state`.
RLModule for the TQC (Truncated Quantile Critics) algorithm. TQC extends SAC by using distributional critics with quantile regression. Each critic outputs n_quantiles values instead of a single Q-value. Architecture: - Policy (Actor): Same as SAC [obs] -> [pi_encoder] -> [pi_head] -> [action_dist_inputs] - Quantil...
documentation
0
{"doc_type": "class", "class_name": "DefaultTQCRLModule", "file_path": "rllib/algorithms/tqc/default_tqc_rl_module.py", "repo_id": "ray-project/ray", "char_length": 589, "methods": ["setup", "make_target_networks", "get_non_inference_attributes", "get_target_network_pairs", "get_initial_state"]}
ray-project/ray:doc/source/ray-overview/examples/multi_agent_a2a/content/agent_runtime/agent_builder.py:module_doc
Write a module-level docstring for the Python module `agent_builder` which contains function `build_llm`.
Shared agent-building helpers. This repo had multiple agents with very similar boilerplate: - load config - build LLM - (optionally) discover MCP tools - create a LangChain agent with MemorySaver This module centralizes that logic so individual agents only specify: - system prompt - tools source (MCP endpoints vs exp...
documentation
0
{"doc_type": "module", "module_name": "agent_builder", "file_path": "doc/source/ray-overview/examples/multi_agent_a2a/content/agent_runtime/agent_builder.py", "repo_id": "ray-project/ray", "char_length": 343}
crewAIInc/crewAI:lib/crewai-files/src/crewai_files/resolution/resolver.py:FileResolver._resolve_inline
# Context: import base64 from crewai_files.core.resolved import ( FileReference, InlineBase64, InlineBytes, ResolvedFile, UrlReference, ) from crewai_files.core.types import FileInput class FileContext: ... class FileResolverConfig: ... def create_resolver(provider: str | None, prefer_upload: bool,...
def _resolve_inline( self, file: FileInput, provider: str, context: FileContext, ) -> ResolvedFile: """Resolve a file as inline content. Args: file: The file to resolve (used for logging). provider: Provider name. context: Pre-comp...
function_simple
0
{"cognitive_complexity": 2, "loc": 28, "code_loc": 11, "docstring_loc": 10, "function_name": "_resolve_inline", "class_name": "FileResolver", "qualname": "FileResolver._resolve_inline", "file_path": "lib/crewai-files/src/crewai_files/resolution/resolver.py", "repo_id": "crewAIInc/crewAI", "has_docstring": true, "runnab...
ray-project/ray:python/ray/data/_internal/execution/bundle_queue/base.py:QueueWithRemoval.remove
# Context: from ray.data._internal.execution.interfaces import RefBundle class BaseBundleQueue: ... class QueueWithRemoval(BaseBundleQueue): def __contains__(self, bundle: RefBundle) -> bool: ... def _remove_inner(self, bundle: RefBundle) -> RefBundle: ... # Task: Write a Python method `remove` for the class...
def remove(self, bundle: RefBundle) -> RefBundle: """Remove the specified bundle from the queue. If multiple instances exist, remove the first one.""" bundle = self._remove_inner(bundle) self._on_dequeue_bundle(bundle) return bundle
function_simple
0
{"cognitive_complexity": 0, "loc": 5, "code_loc": 3, "docstring_loc": 1, "function_name": "remove", "class_name": "QueueWithRemoval", "qualname": "QueueWithRemoval.remove", "file_path": "python/ray/data/_internal/execution/bundle_queue/base.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "cl...
Shubhamsaboo/awesome-llm-apps:ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/util.py:AudioPlayer.stop
# Context: def record_audio(duration: float, sample_rate: int, channels: int, dtype) -> np.ndarray: ... def create_silence(duration: float, sample_rate: int, dtype) -> np.ndarray: ... def save_audio(audio_data: np.ndarray, filename: str, sample_rate: int): ... def load_audio(filename: str, sample_rate: int, dtype) -> ...
def stop(self): """Stop the audio player.""" self._stop_event.set()
function_simple
0
{"cognitive_complexity": 0, "loc": 3, "code_loc": 1, "docstring_loc": 1, "function_name": "stop", "class_name": "AudioPlayer", "qualname": "AudioPlayer.stop", "file_path": "ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/util.py", "repo_id": "Shubhamsaboo/awesome-llm-apps", "has_docstring": true...
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/contextualai_rerank_tool/contextual_rerank_tool.py:ContextualAIRerankTool:class_doc
Write a class-level docstring for `ContextualAIRerankTool` (inherits from BaseTool) which has methods: `_run`.
Tool to rerank documents using Contextual AI's instruction-following reranker.
documentation
0
{"doc_type": "class", "class_name": "ContextualAIRerankTool", "file_path": "lib/crewai-tools/src/crewai_tools/tools/contextualai_rerank_tool/contextual_rerank_tool.py", "repo_id": "crewAIInc/crewAI", "char_length": 78, "methods": ["_run"]}
browser-use/browser-use:browser_use/browser/watchdogs/downloads_watchdog.py:DownloadsWatchdog.trigger_pdf_download
# Context: import asyncio import json import os from urllib.parse import urlparse import anyio from cdp_use.cdp.target import SessionID, TargetID from browser_use.browser.events import ( BrowserLaunchEvent, BrowserStateRequestEvent, BrowserStoppedEvent, DownloadProgressEvent, DownloadStartedEvent, FileDownloadedE...
async def trigger_pdf_download(self, target_id: TargetID) -> str | None: """Trigger download of a PDF from Chrome's PDF viewer. Returns the download path if successful, None otherwise. """ self.logger.debug(f'[DownloadsWatchdog] trigger_pdf_download called for target_id={target_id}') if not self.browser_ses...
function_complex
0
{"cognitive_complexity": 34, "loc": 192, "code_loc": 148, "docstring_loc": 4, "function_name": "trigger_pdf_download", "class_name": "DownloadsWatchdog", "qualname": "DownloadsWatchdog.trigger_pdf_download", "file_path": "browser_use/browser/watchdogs/downloads_watchdog.py", "repo_id": "browser-use/browser-use", "has_d...
zhayujie/chatgpt-on-wechat:agent/protocol/agent.py:Agent.get_skills_prompt
# Context: from common.log import logger class Agent: def __init__(self, system_prompt: str, description: str = "AI Agent", model: LLMModel = None, tools=None, output_mode="print", max_steps=100, max_context_tokens=None, context_reserve_tokens=None, memory_manager=None, name: str...
def get_skills_prompt(self, skill_filter=None) -> str: """ Get the skills prompt to append to system prompt. :param skill_filter: Optional list of skill names to include :return: Formatted skills prompt or empty string """ if not self.skill_manager: r...
function_simple
1
{"cognitive_complexity": 2, "loc": 15, "code_loc": 7, "docstring_loc": 6, "function_name": "get_skills_prompt", "class_name": "Agent", "qualname": "Agent.get_skills_prompt", "file_path": "agent/protocol/agent.py", "repo_id": "zhayujie/chatgpt-on-wechat", "has_docstring": true, "runnable_level": "project_runnable"}
apache/airflow:providers/teradata/tests/unit/teradata/operators/test_bteq.py:TestBteqOperator.test_invalid_file_path
# Context: from unittest import mock import pytest from airflow.providers.teradata.operators.bteq import BteqOperator class TestBteqOperator: def test_execute(self, mock_hook_init, mock_execute_bteq): ... def test_execute_sql_only(self, mock_hook_init, mock_execute_bteq): ... def test_execute_sql_local(sel...
def test_invalid_file_path(self, mock_is_valid_file): op = BteqOperator( task_id="fail_invalid_file", file_path="/invalid/path.sql", teradata_conn_id="td_conn", ) with pytest.raises(ValueError, match="Failed to execute BTEQ script due to invalid file path"): ...
test
1
{"function_name": "test_invalid_file_path", "class_name": "TestBteqOperator", "qualname": "TestBteqOperator.test_invalid_file_path", "file_path": "providers/teradata/tests/unit/teradata/operators/test_bteq.py", "repo_id": "apache/airflow", "loc": 8, "tested_modules": ["__future__", "airflow.providers.teradata.hooks.bte...
apache/airflow:providers/amazon/tests/unit/amazon/aws/executors/ecs/test_utils.py:TestEcsTaskCollection.test_get_all_task_keys
# Context: class TestEcsQueuedTask: ... class TestEcsTaskInfo: ... class TestRunTaskKwargsConfigKeys: ... class TestAllEcsConfigKeys: ... class TestEcsExecutorException: ... class TestEcsExecutorTask: ... class TestRecursiveFlattenDict: ... class TestParseAssignPublicIp: ... class TestCamelizeDictKeys: ... class Test...
def test_get_all_task_keys(self): """Test getting all task keys from collection.""" self.collection.add_task( task=self.task, airflow_task_key=self.task_key, queue=self.queue, airflow_cmd=self.cmd, exec_config=self.exec_config, atte...
test
1
{"function_name": "test_get_all_task_keys", "class_name": "TestEcsTaskCollection", "qualname": "TestEcsTaskCollection.test_get_all_task_keys", "file_path": "providers/amazon/tests/unit/amazon/aws/executors/ecs/test_utils.py", "repo_id": "apache/airflow", "loc": 13, "tested_modules": ["__future__", "airflow.models.taski...
ocrmypdf/OCRmyPDF:tests/test_null_ocr_engine.py:TestNullOcrEngineInterface.test_version_returns_none
# Context: from ocrmypdf.builtin_plugins.null_ocr import NullOcrEngine class TestNullOcrEngineExists: ... class TestNullOcrEngineGenerateOcr: ... class TestOcrEngineOption: ... class TestNullOcrEngineInterface: def test_creator_tag(self): ... def test_languages_returns_empty_set(self): ... def test_suppor...
def test_version_returns_none(self): """NullOcrEngine.version() should return 'none'.""" from ocrmypdf.builtin_plugins.null_ocr import NullOcrEngine assert NullOcrEngine.version() == "none"
test
1
{"function_name": "test_version_returns_none", "class_name": "TestNullOcrEngineInterface", "qualname": "TestNullOcrEngineInterface.test_version_returns_none", "file_path": "tests/test_null_ocr_engine.py", "repo_id": "ocrmypdf/OCRmyPDF", "loc": 5, "tested_modules": ["__future__", "pathlib", "ocrmypdf.builtin_plugins", "...
ray-project/ray:python/ray/serve/tests/unit/test_deployment_rank_manager.py:TestDeploymentRankManagerMultiNode.test_complex_multi_node_lifecycle
# Context: from ray.serve._private.deployment_state import DeploymentRankManager def rank_manager() -> DeploymentRankManager: ... class MockDeploymentReplica: ... class TestDeploymentRankManager: ... class TestDeploymentRankManagerEdgeCases: ... class TestDeploymentRankManagerErrorHandling: ... class TestDeploymentRa...
def test_complex_multi_node_lifecycle(self): """Test a complex scenario with adds, releases, and consistency checks across nodes.""" rank_manager = DeploymentRankManager() # Phase 1: Initial deployment across 3 nodes rank_manager.assign_rank("n1_r1", "node_1") rank_manager.assig...
test
0
{"function_name": "test_complex_multi_node_lifecycle", "class_name": "TestDeploymentRankManagerMultiNode", "qualname": "TestDeploymentRankManagerMultiNode.test_complex_multi_node_lifecycle", "file_path": "python/ray/serve/tests/unit/test_deployment_rank_manager.py", "repo_id": "ray-project/ray", "loc": 32, "tested_modu...
huggingface/transformers:src/transformers/trainer_optimizer.py:_get_adamw_torch
# Context: from typing import TYPE_CHECKING, Any from .training_args import OptimizerNames, ParallelMode from torch.optim import AdamW from bitsandbytes.optim import AdamW, Lion, RMSprop from torch_xla.amp.syncfree import AdamW class OptimizerContext: ... def _parse_optim_args(optim_args_str: str | None) -> dict[str, ...
def _get_adamw_torch(ctx: OptimizerContext) -> tuple[Any, dict[str, Any]]: """Get PyTorch AdamW optimizer (regular or fused).""" from torch.optim import AdamW ctx.optimizer_kwargs.update(ctx.adam_kwargs) if ctx.args.optim == OptimizerNames.ADAMW_TORCH_FUSED: ctx.optimizer_kwargs.update({"fused"...
function_simple
0
{"cognitive_complexity": 1, "loc": 8, "code_loc": 5, "docstring_loc": 1, "function_name": "_get_adamw_torch", "class_name": null, "qualname": "_get_adamw_torch", "file_path": "src/transformers/trainer_optimizer.py", "repo_id": "huggingface/transformers", "has_docstring": true, "runnable_level": "project_runnable"}
browser-use/browser-use:tests/ci/interactions/test_autocomplete_interaction.py:TestAutocompleteInteraction.test_datalist_field_no_delay
# Context: import asyncio from browser_use.browser import BrowserSession from browser_use.tools.service import Tools import time def http_server(): ... def base_url(http_server): ... async def browser_session(): ... def tools(): ... class TestAutocompleteInteraction: async def test_value_mismatch_detected(self, t...
async def test_datalist_field_no_delay(self, tools: Tools, browser_session: BrowserSession, base_url: str): """Native datalist fields should NOT get the 400ms delay — browser handles them instantly.""" import time await tools.navigate(url=f'{base_url}/datalist-field', new_tab=False, browser_session=browser_sessi...
test
0
{"function_name": "test_datalist_field_no_delay", "class_name": "TestAutocompleteInteraction", "qualname": "TestAutocompleteInteraction.test_datalist_field_no_delay", "file_path": "tests/ci/interactions/test_autocomplete_interaction.py", "repo_id": "browser-use/browser-use", "loc": 17, "tested_modules": ["browser_use.a...
langflow-ai/langflow:src/backend/tests/unit/components/processing/test_text_operations_component.py:TestTextOperationsOutputMethods.test_get_dataframe
# Context: from lfx.components.processing.text_operations import TextOperations from lfx.schema.dataframe import DataFrame class TestTextOperationsComponent(ComponentTestBaseWithoutClient): ... class TestTextOperationsWordCount: ... class TestTextOperationsCaseConversion: ... class TestTextOperationsReplace: ... class...
def test_get_dataframe(self): """Test get_dataframe method.""" component = TextOperations() component.operation = [{"name": "Text to DataFrame"}] component.text_input = "| A | B |\n| 1 | 2 |" component.table_separator = "|" component.has_header = True component.lo...
test
1
{"function_name": "test_get_dataframe", "class_name": "TestTextOperationsOutputMethods", "qualname": "TestTextOperationsOutputMethods.test_get_dataframe", "file_path": "src/backend/tests/unit/components/processing/test_text_operations_component.py", "repo_id": "langflow-ai/langflow", "loc": 12, "tested_modules": ["lfx....
exo-explore/exo:src/exo/worker/engines/image/models/flux/kontext_adapter.py:FluxKontextModelAdapter.encode_prompt
# Context: from mflux.models.flux.model.flux_text_encoder.prompt_encoder import PromptEncoder from mflux.models.flux.variants.kontext.kontext_util import KontextUtil class FluxKontextPromptData(PromptData): ... class FluxKontextModelAdapter(ModelAdapter[Flux1Kontext, Transformer]): def __init__( self, ...
def encode_prompt( self, prompt: str, negative_prompt: str | None = None ) -> FluxKontextPromptData: """Encode prompt and create conditioning from stored input image. Must call set_image_dimensions() before this method. Args: prompt: Text prompt for editing ...
function_simple
0
{"cognitive_complexity": 2, "loc": 55, "code_loc": 34, "docstring_loc": 11, "function_name": "encode_prompt", "class_name": "FluxKontextModelAdapter", "qualname": "FluxKontextModelAdapter.encode_prompt", "file_path": "src/exo/worker/engines/image/models/flux/kontext_adapter.py", "repo_id": "exo-explore/exo", "has_docst...
infiniflow/ragflow:common/data_source/utils.py:SlackTextCleaner._get_slack_name
# Context: import logging from slack_sdk.errors import SlackApiError def datetime_from_string(datetime_string: str) -> datetime: ... def is_valid_image_type(mime_type: str) -> bool: ... def _handle_http_error(e: requests.HTTPError, attempt: int) -> int: ... def update_param_in_path(path: str, param: str, value: str) -...
def _get_slack_name(self, user_id: str) -> str: """Get Slack username""" if user_id not in self._id_to_name_map: try: response = self._client.users_info(user=user_id) self._id_to_name_map[user_id] = response["user"]["profile"]["display_name"] or response["user...
function_simple
1
{"cognitive_complexity": 3, "loc": 11, "code_loc": 8, "docstring_loc": 1, "function_name": "_get_slack_name", "class_name": "SlackTextCleaner", "qualname": "SlackTextCleaner._get_slack_name", "file_path": "common/data_source/utils.py", "repo_id": "infiniflow/ragflow", "has_docstring": true, "runnable_level": "project_r...
ray-project/ray:python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py:TestPrefixTreeEviction.test_eviction_insufficient_chars_evicts_all
# Context: from ray.llm._internal.serve.routing_policies.prefix_aware.prefix_tree import ( Node, PrefixTree, PrefixTreeActor, ) def tree() -> PrefixTree: ... def tree_actor(): ... def get_lru_texts_from_tree(tree: PrefixTree, tenant_id: str) -> List[str]: ... async def get_lru_texts_from_tree_actor(tree_ac...
def test_eviction_insufficient_chars_evicts_all(self, tree: PrefixTree) -> None: """Test evicting when min_remove_size is larger than available; evicts all.""" tree.add_tenants(["tenant_1"], 0) tree.insert("xyz", "tenant_1", 1) # 3 chars available evicted_count = tree.evict_tenant_by_lr...
test
0
{"function_name": "test_eviction_insufficient_chars_evicts_all", "class_name": "TestPrefixTreeEviction", "qualname": "TestPrefixTreeEviction.test_eviction_insufficient_chars_evicts_all", "file_path": "python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py", "repo_id": "ray-project/ray", "loc": 8, "tested_module...
langflow-ai/langflow:src/backend/base/langflow/agentic/utils/template_create.py:create_flow_from_template_and_get_link
# Context: from typing import TYPE_CHECKING, Any from fastapi import HTTPException from langflow.agentic.utils.template_search import get_template_by_id from langflow.api.v1.flows import _new_flow, _save_flow_to_fs from langflow.initial_setup.setup import get_or_create_default_folder from langflow.services.database.mod...
async def create_flow_from_template_and_get_link( *, session: AsyncSession, user_id: UUID, template_id: str, target_folder_id: UUID | None = None, ) -> dict[str, Any]: """Create a new flow from a starter template and return its id and UI link. Args: session: Active async DB session....
function_complex
1
{"cognitive_complexity": 6, "loc": 60, "code_loc": 32, "docstring_loc": 12, "function_name": "create_flow_from_template_and_get_link", "class_name": null, "qualname": "create_flow_from_template_and_get_link", "file_path": "src/backend/base/langflow/agentic/utils/template_create.py", "repo_id": "langflow-ai/langflow", "...
Zie619/n8n-workflows:scripts/update_readme_stats.py:get_category_list
Write a Python function `get_category_list` to get formatted list of all categories (same logic as search index). Parameters: categories
def get_category_list(categories): """Get formatted list of all categories (same logic as search index).""" formatted_categories = set() # Map technical categories to display names category_mapping = { "messaging": "Communication & Messaging", "email": "Communication & Messaging", ...
function_simple
0
{"cognitive_complexity": 2, "loc": 41, "code_loc": 32, "docstring_loc": 1, "function_name": "get_category_list", "class_name": null, "qualname": "get_category_list", "file_path": "scripts/update_readme_stats.py", "repo_id": "Zie619/n8n-workflows", "has_docstring": true, "runnable_level": "self_contained"}
streamlit/streamlit:lib/tests/streamlit/web/server/component_file_utils_test.py:test_mixed_separators_not_rejected_early
# Context: from pathlib import Path from streamlit.web.server.component_file_utils import ( build_safe_abspath, guess_content_type, ) def root(tmp_path: Path) -> Path: ... def test_path_security_cases(root: Path, candidate: str, expect_allowed: bool) -> None: ... def test_rejects_symlink_escape(root: Path, tmp...
def test_mixed_separators_not_rejected_early(root: Path) -> None: """Paths with mixed separators should not be rejected by the early validation. On Windows, backslashes are path separators. On Unix, they're valid filename characters. Safe relative paths with backslashes should not be rejected. """ ...
test
1
{"function_name": "test_mixed_separators_not_rejected_early", "class_name": null, "qualname": "test_mixed_separators_not_rejected_early", "file_path": "lib/tests/streamlit/web/server/component_file_utils_test.py", "repo_id": "streamlit/streamlit", "loc": 12, "tested_modules": ["__future__", "pathlib", "typing", "urllib...
zhayujie/chatgpt-on-wechat:agent/skills/manager.py:SkillManager.set_skill_enabled
# Context: class SkillManager: def __init__( self, builtin_dir: Optional[str] = None, custom_dir: Optional[str] = None, config: Optional[Dict] = None, ): """ Initialize the skill manager. :param builtin_dir: Built-in skills directory (project root ``skil...
def set_skill_enabled(self, name: str, enabled: bool): """ Set a skill's enabled state and persist. :param name: skill name :param enabled: True to enable, False to disable """ if name not in self.skills_config: raise ValueError(f"skill '{name}' not found in ...
function_simple
1
{"cognitive_complexity": 1, "loc": 11, "code_loc": 4, "docstring_loc": 6, "function_name": "set_skill_enabled", "class_name": "SkillManager", "qualname": "SkillManager.set_skill_enabled", "file_path": "agent/skills/manager.py", "repo_id": "zhayujie/chatgpt-on-wechat", "has_docstring": true, "runnable_level": "class_run...
PaddlePaddle/PaddleOCR:mcp_server/paddleocr_mcp/pipelines.py:_LayoutParsingHandler._parse_markdown_with_images
# Context: import re from typing import Any, Callable, Dict, List, NoReturn, Optional, Type, Union from mcp.types import ImageContent, TextContent def _is_file_path(s: str) -> bool: ... def _is_base64(s: str) -> bool: ... def _is_url(s: str) -> bool: ... def _infer_file_type_from_bytes(data: bytes) -> Optional[str]: ....
def _parse_markdown_with_images( self, markdown_text: str, images_mapping: Dict[str, str] ) -> List[Union[TextContent, ImageContent]]: """Parse markdown text and return mixed list of text and images.""" if not images_mapping: return [TextContent(type="text", text=markdown_text)] ...
function_complex
0
{"cognitive_complexity": 8, "loc": 33, "code_loc": 23, "docstring_loc": 1, "function_name": "_parse_markdown_with_images", "class_name": "_LayoutParsingHandler", "qualname": "_LayoutParsingHandler._parse_markdown_with_images", "file_path": "mcp_server/paddleocr_mcp/pipelines.py", "repo_id": "PaddlePaddle/PaddleOCR", "h...
vllm-project/vllm:vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_engine.py:MoRIIOWriter.ensure_worker_started
# Context: import threading class MoRIIOWrapper: ... class MoRIIOWriter: def __init__(self, worker: "MoRIIOConnectorWorker"): """Initialize the writer. Args: worker: Reference to the parent worker """ self._worker_ref: weakref_ref[MoRIIOConnectorWorker] = weakref_ref(w...
def ensure_worker_started(self) -> None: """Ensure the background write worker is running.""" if self._write_worker_started: return self._write_worker_started = True with self._write_worker_lock: thread = threading.Thread( target=self._write_worker...
function_simple
1
{"cognitive_complexity": 1, "loc": 11, "code_loc": 9, "docstring_loc": 1, "function_name": "ensure_worker_started", "class_name": "MoRIIOWriter", "qualname": "MoRIIOWriter.ensure_worker_started", "file_path": "vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_engine.py", "repo_id": "vllm-project/vllm", "has_do...
geekcomputers/Python:Street_Fighter/src/main.py:draw_gradient_text
# Context: def resource_path(relative_path): ... def draw_text(text, font, color, x, y): ... def blur_bg(image): ... def draw_bg(image, is_game_started): ... def draw_button(text, font, text_col, button_col, x, y, width, height): ... def victory_screen(winner_img): ... def main_menu(): ... def scores_screen(): ... def...
def draw_gradient_text(text, font, x, y, colors): """ Draws a gradient text by layering multiple text surfaces with slight offsets. """ offset = 2 for i, color in enumerate(colors): img = font.render(text, True, color) screen.blit(img, (x + i * offset, y + i * offset))
function_simple
1
{"cognitive_complexity": 1, "loc": 8, "code_loc": 4, "docstring_loc": 3, "function_name": "draw_gradient_text", "class_name": null, "qualname": "draw_gradient_text", "file_path": "Street_Fighter/src/main.py", "repo_id": "geekcomputers/Python", "has_docstring": true, "runnable_level": "file_runnable"}
streamlit/streamlit:lib/streamlit/components/v2/component_registry.py:module_doc
Write a module-level docstring for the Python module `component_registry` which contains class `BidiComponentDefinition`, class `BidiComponentRegistry`.
Component registry for Custom Components v2. This module defines the data model and in-memory registry for Custom Components v2. During development, component assets (JS/CSS/HTML) may change on disk as build tools produce new outputs. See Also -------- - :class:`streamlit.components.v2.component_file_watcher.Componen...
documentation
1
{"doc_type": "module", "module_name": "component_registry", "file_path": "lib/streamlit/components/v2/component_registry.py", "repo_id": "streamlit/streamlit", "char_length": 384}
huggingface/transformers:src/transformers/utils/output_capturing.py:recursively_install_hooks
# Context: from torch import nn from ..modeling_utils import PreTrainedModel class OutputRecorder: ... class CompileableContextVar: ... def install_output_capuring_hook(module: nn.Module, key: str, index: int) -> None: ... def install_all_output_capturing_hooks(model: PreTrainedModel, prefix: str | None) -> None: ... ...
def recursively_install_hooks( parent_module: nn.Module, module_name: str, capture_tasks: list[tuple[str, OutputRecorder]] ) -> None: """ Recursively install all output capturing hooks on all submodules of `parent_module`. Note that we need to use this recursive approach instead of simply iterating over...
function_complex
0
{"cognitive_complexity": 14, "loc": 30, "code_loc": 13, "docstring_loc": 7, "function_name": "recursively_install_hooks", "class_name": null, "qualname": "recursively_install_hooks", "file_path": "src/transformers/utils/output_capturing.py", "repo_id": "huggingface/transformers", "has_docstring": true, "runnable_level"...
ray-project/ray:python/ray/tests/test_autoscaler_azure.py:TestAzureAvailabilityZonePrecedence.test_provider_auto_allows_auto_selection
# Context: class TestAzureAvailabilityZones(unittest.TestCase): ... class TestAzureAvailabilityZonePrecedence(unittest.TestCase): def setUp(self): ... def _create_mock_provider(self, provider_config): ... def _extract_zone_logic(self, provider, node_config): ... def test_node_availability_zone_overrid...
def test_provider_auto_allows_auto_selection(self): """Test that provider-level 'auto' allows auto-selection.""" provider = self._create_mock_provider({"availability_zone": "auto"}) node_config = {"azure_arm_parameters": {"vmSize": "Standard_D2s_v3"}} zones, source = self._extract_zone_...
test
0
{"function_name": "test_provider_auto_allows_auto_selection", "class_name": "TestAzureAvailabilityZonePrecedence", "qualname": "TestAzureAvailabilityZonePrecedence.test_provider_auto_allows_auto_selection", "file_path": "python/ray/tests/test_autoscaler_azure.py", "repo_id": "ray-project/ray", "loc": 9, "tested_modules...
huggingface/transformers:tests/models/video_llama_3/test_image_processing_video_llama_3.py:VideoLlama3ImageProcessingTest.test_call_numpy
# Context: import numpy as np import torch class VideoLlama3ImageProcessingTester: ... class VideoLlama3ImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = VideoLlama3ImageProcessor if is_vision_available() else None fast_image_processing_class = VideoLlama3ImageProcesso...
def test_call_numpy(self): for image_processing_class in self.image_processor_list: # Initialize image_processing image_processing = image_processing_class(**self.image_processor_dict) # create random numpy tensors image_inputs = self.image_processor_tester.prepar...
test
0
{"function_name": "test_call_numpy", "class_name": "VideoLlama3ImageProcessingTest", "qualname": "VideoLlama3ImageProcessingTest.test_call_numpy", "file_path": "tests/models/video_llama_3/test_image_processing_video_llama_3.py", "repo_id": "huggingface/transformers", "loc": 26, "tested_modules": ["transformers.image_ut...
huggingface/transformers:src/transformers/models/kosmos2_5/modeling_kosmos2_5.py:Kosmos2_5PreTrainedModel:class_doc
Write a class-level docstring for `Kosmos2_5PreTrainedModel` (inherits from PreTrainedModel) which has methods: `_init_weights`.
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
documentation
0
{"doc_type": "class", "class_name": "Kosmos2_5PreTrainedModel", "file_path": "src/transformers/models/kosmos2_5/modeling_kosmos2_5.py", "repo_id": "huggingface/transformers", "char_length": 120, "methods": ["_init_weights"]}
browser-use/browser-use:tests/ci/infrastructure/test_registry_validation.py:TestDecoratedFunctionBehavior:class_doc
Write a class-level docstring for `TestDecoratedFunctionBehavior` which has methods: `test_decorated_function_only_accepts_kwargs`, `test_decorated_function_accepts_params_model`, `test_decorated_function_ignores_extra_kwargs`.
Test behavior of decorated action functions (from normalization tests)
documentation
0
{"doc_type": "class", "class_name": "TestDecoratedFunctionBehavior", "file_path": "tests/ci/infrastructure/test_registry_validation.py", "repo_id": "browser-use/browser-use", "char_length": 70, "methods": ["test_decorated_function_only_accepts_kwargs", "test_decorated_function_accepts_params_model", "test_decorated_fun...
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/adapters/enterprise_adapter.py:EnterpriseActionKitToolAdapter.tools
# Context: from crewai.tools import BaseTool def get_enterprise_api_base_url() -> str: ... class EnterpriseActionTool(BaseTool): ... class EnterpriseActionKitToolAdapter: def __init__( self, enterprise_action_token: str, enterprise_api_base_url: str | None = None, ): """Initial...
def tools(self) -> list[BaseTool]: """Get the list of tools created from enterprise actions.""" if self._tools is None: self._fetch_actions() self._create_tools() return self._tools or []
function_simple
0
{"cognitive_complexity": 2, "loc": 6, "code_loc": 4, "docstring_loc": 1, "function_name": "tools", "class_name": "EnterpriseActionKitToolAdapter", "qualname": "EnterpriseActionKitToolAdapter.tools", "file_path": "lib/crewai-tools/src/crewai_tools/adapters/enterprise_adapter.py", "repo_id": "crewAIInc/crewAI", "has_docs...
vllm-project/vllm:vllm/distributed/device_communicators/all2all.py:AgRsAll2AllManager:class_doc
Write a class-level docstring for `AgRsAll2AllManager` (inherits from All2AllManagerBase) which has methods: `__init__`, `dispatch_router_logits`, `dispatch`, `combine`, `destroy`.
An implementation of all2all communication based on all-gather (dispatch) and reduce-scatter (combine).
documentation
1
{"doc_type": "class", "class_name": "AgRsAll2AllManager", "file_path": "vllm/distributed/device_communicators/all2all.py", "repo_id": "vllm-project/vllm", "char_length": 103, "methods": ["__init__", "dispatch_router_logits", "dispatch", "combine", "destroy"]}
Comfy-Org/ComfyUI:comfy_api_nodes/nodes_kling.py:get_video_url_from_response
# Context: def _generate_storyboard_inputs(count: int) -> list: ... def normalize_omni_prompt_references(prompt: str) -> str: ... async def finish_omni_video_task(cls: type[IO.ComfyNode], response: TaskStatusResponse) -> IO.NodeOutput: ... def is_valid_camera_control_configs(configs: list[float]) -> bool: ... def is_v...
def get_video_url_from_response(response) -> str | None: """Returns the first video url from the Kling video generation task result. Will not raise an error if the response is not valid. """ if response and is_valid_video_response(response): return str(get_video_from_response(response).url) ...
function_simple
1
{"cognitive_complexity": 3, "loc": 8, "code_loc": 4, "docstring_loc": 3, "function_name": "get_video_url_from_response", "class_name": null, "qualname": "get_video_url_from_response", "file_path": "comfy_api_nodes/nodes_kling.py", "repo_id": "Comfy-Org/ComfyUI", "has_docstring": true, "runnable_level": "file_runnable"}
browser-use/browser-use:tests/ci/test_doctor_command.py:test_summarize_checks_with_errors
# Context: from browser_use.skill_cli.commands import doctor async def test_doctor_handle_returns_valid_structure(): ... def test_check_package_installed(): ... def test_check_browser_returns_valid_structure(): ... def test_check_api_key_with_env_var(monkeypatch): ... def test_check_api_key_missing(monkeypatch): ... d...
def test_summarize_checks_with_errors(): """Test _summarize_checks with errors.""" checks = { 'check1': {'status': 'ok'}, 'check2': {'status': 'error'}, } summary = doctor._summarize_checks(checks) assert '1/2' in summary assert '1 error' in summary
test
0
{"function_name": "test_summarize_checks_with_errors", "class_name": null, "qualname": "test_summarize_checks_with_errors", "file_path": "tests/ci/test_doctor_command.py", "repo_id": "browser-use/browser-use", "loc": 9, "tested_modules": ["browser_use.skill_cli.commands", "browser_use.skill_cli"], "has_docstring": true...
scrapy/scrapy:tests/test_downloader_handler_twisted_http11.py:module_doc
Write a module-level docstring for the Python module `test_downloader_handler_twisted_http11` which contains class `HTTP11DownloadHandlerMixin`, class `TestHttp11`, class `TestHttps11`, class `TestSimpleHttps`, class `TestHttps11WrongHostname`.
Tests for scrapy.core.downloader.handlers.http11.HTTP11DownloadHandler.
documentation
1
{"doc_type": "module", "module_name": "test_downloader_handler_twisted_http11", "file_path": "tests/test_downloader_handler_twisted_http11.py", "repo_id": "scrapy/scrapy", "char_length": 71}
apache/airflow:task-sdk/tests/task_sdk/definitions/test_callback.py:TestCallback.test_callback_equality
# Context: import pytest from airflow.sdk.definitions.callback import AsyncCallback, Callback, SyncCallback async def empty_async_callback_for_deadline_tests(): ... def empty_sync_callback_for_deadline_tests(): ... class TestAsyncCallback: ... class TestSyncCallback: ... class TestCallback: def test_init_error_re...
def test_callback_equality(self, callback1_args, callback2_args, should_equal): callback1 = AsyncCallback(*callback1_args) callback2 = AsyncCallback(*callback2_args) assert (callback1 == callback2) == should_equal
test
1
{"function_name": "test_callback_equality", "class_name": "TestCallback", "qualname": "TestCallback.test_callback_equality", "file_path": "task-sdk/tests/task_sdk/definitions/test_callback.py", "repo_id": "apache/airflow", "loc": 4, "tested_modules": ["__future__", "typing", "airflow.sdk._shared.module_loading", "airfl...
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/devpulse_ai/adapters/arxiv.py:fetch_arxiv_papers
# Context: import httpx import xml.etree.ElementTree as ET from typing import List, Dict, Any # Task: Write a Python function `fetch_arxiv_papers` to fetch recent AI/ML papers from ArXiv. Parameters: limit: int Returns: List[Dict[str, Any]]
def fetch_arxiv_papers(limit: int = 5) -> List[Dict[str, Any]]: """ Fetch recent AI/ML papers from ArXiv. Args: limit: Maximum number of papers to return. Returns: List of signal dictionaries with standardized schema. """ base_url = "https://export.arxiv.org/api/que...
function_complex
0
{"cognitive_complexity": 23, "loc": 67, "code_loc": 46, "docstring_loc": 9, "function_name": "fetch_arxiv_papers", "class_name": null, "qualname": "fetch_arxiv_papers", "file_path": "advanced_ai_agents/multi_agent_apps/devpulse_ai/adapters/arxiv.py", "repo_id": "Shubhamsaboo/awesome-llm-apps", "has_docstring": true, "r...
exo-explore/exo:src/exo/shared/models/model_cards.py:delete_custom_card
# Context: from exo.shared.types.common import ModelId async def _refresh_card_cache(): ... def _is_image_card(card: 'ModelCard') -> bool: ... async def get_model_cards() -> list['ModelCard']: ... class ModelTask(str, Enum): ... class ComponentInfo(CamelCaseModel): ... class ModelCard(CamelCaseModel): ... def is_custo...
async def delete_custom_card(model_id: ModelId) -> bool: """Delete a user-added custom model card. Returns True if deleted.""" card_path = _custom_cards_dir / (ModelId(model_id).normalize() + ".toml") if await card_path.exists(): await card_path.unlink() _card_cache.pop(model_id, None) ...
function_simple
0
{"cognitive_complexity": 1, "loc": 8, "code_loc": 6, "docstring_loc": 1, "function_name": "delete_custom_card", "class_name": null, "qualname": "delete_custom_card", "file_path": "src/exo/shared/models/model_cards.py", "repo_id": "exo-explore/exo", "has_docstring": true, "runnable_level": "project_runnable"}
Comfy-Org/ComfyUI:tests-unit/folder_paths_test/system_user_test.py:TestGetSystemUserDirectory.test_default_name
# Context: from folder_paths import ( get_system_user_directory, get_public_user_directory, get_user_directory, set_user_directory, ) def mock_user_directory(): ... class TestGetPublicUserDirectory: ... class TestBackwardCompatibility: ... class TestEdgeCases: ... class TestGetSystemUserDirectory: ...
def test_default_name(self, mock_user_directory): """Test default 'system' name.""" path = get_system_user_directory() assert path.endswith("__system") assert mock_user_directory in path
test
1
{"function_name": "test_default_name", "class_name": "TestGetSystemUserDirectory", "qualname": "TestGetSystemUserDirectory.test_default_name", "file_path": "tests-unit/folder_paths_test/system_user_test.py", "repo_id": "Comfy-Org/ComfyUI", "loc": 5, "tested_modules": ["folder_paths"], "has_docstring": true, "runnable_l...