sample_id string | instruction string | completion string | category string | label int64 | metadata string |
|---|---|---|---|---|---|
run-llama/llama_index:llama-index-core/llama_index/core/chat_engine/multi_modal_context.py:MultiModalContextChatEngine.from_defaults | # Context:
from typing import Any, List, Optional, Sequence, Tuple, Union
from llama_index.core.base.llms.types import (
ChatMessage,
ChatResponse,
ChatResponseAsyncGen,
ChatResponseGen,
MessageRole,
)
from llama_index.core.llms import LLM, TextBlock, ChatMessage, ImageBlock
from llama_index.core.po... | def from_defaults(
cls,
retriever: BaseRetriever,
chat_history: Optional[List[ChatMessage]] = None,
memory: Optional[BaseMemory] = None,
system_prompt: Optional[str] = None,
node_postprocessors: Optional[List[BaseNodePostprocessor]] = None,
context_template: Optio... | function_simple | 1 | {"cognitive_complexity": 5, "loc": 32, "code_loc": 17, "docstring_loc": 1, "function_name": "from_defaults", "class_name": "MultiModalContextChatEngine", "qualname": "MultiModalContextChatEngine.from_defaults", "file_path": "llama-index-core/llama_index/core/chat_engine/multi_modal_context.py", "repo_id": "run-llama/ll... |
huggingface/transformers:src/transformers/models/xlm_roberta_xl/modular_xlm_roberta_xl.py:license_header | Add a Apache-2.0 license header comment for the project 'transformers', authored by The Google AI Language Team Authors and The HuggingFace Inc, year 2018. | # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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.
# coding=utf-8
# Copyright 2022 The H... | license | 0 | {"license_type": "Apache-2.0", "author": "The Google AI Language Team Authors and The HuggingFace Inc", "year": "2018", "source": "header", "repo_id": "huggingface/transformers"} |
ray-project/ray:python/ray/serve/tests/test_direct_ingress.py:test_get_serve_instance_details_json_serializable | # Context:
import json
import pytest
import ray
from ray import serve
from ray.serve._private.constants import (
DEFAULT_AUTOSCALING_POLICY_NAME,
HEALTHY_MESSAGE,
RAY_SERVE_DIRECT_INGRESS_MAX_HTTP_PORT,
RAY_SERVE_DIRECT_INGRESS_MIN_GRPC_PORT,
RAY_SERVE_DIRECT_INGRESS_MIN_HTTP_PORT,
RAY_SERVE_DIR... | def test_get_serve_instance_details_json_serializable(
_skip_if_ff_not_enabled, serve_instance, policy_name
):
"""Test the result from get_serve_instance_details is json serializable."""
controller = _get_global_client()._controller
autoscaling_config = {
"min_replicas": 1,
"max_replic... | test | 0 | {"function_name": "test_get_serve_instance_details_json_serializable", "class_name": null, "qualname": "test_get_serve_instance_details_json_serializable", "file_path": "python/ray/serve/tests/test_direct_ingress.py", "repo_id": "ray-project/ray", "loc": 196, "tested_modules": ["concurrent.futures", "typing", "uuid", "... |
ray-project/ray:python/ray/train/lint/check_circular_imports.py:expand_to_include_reexports | # Context:
from typing import Dict, List, Optional, Set, Tuple
def find_train_packages(base_train_dir: Path, patch_train_dir: Path) -> None: ...
def is_train_package(module_str: str) -> bool: ...
def get_base_dir() -> Path: ...
def get_base_train_dir() -> Path: ...
def does_overlap(main_module: str, module: str) -> bo... | def expand_to_include_reexports(import_map: Dict[str, List[Import]]) -> None:
"""
Expands the set of imports for a given import map to include the modules resulting from reexports.
So if in the base train module, there is "from x import a, b" and x is a package, then this function
will explore the __ini... | function_complex | 0 | {"cognitive_complexity": 6, "loc": 26, "code_loc": 15, "docstring_loc": 5, "function_name": "expand_to_include_reexports", "class_name": null, "qualname": "expand_to_include_reexports", "file_path": "python/ray/train/lint/check_circular_imports.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level":... |
Comfy-Org/ComfyUI:tests-unit/prompt_server_test/system_user_endpoint_test.py:TestSystemUserEndpointBlocking.test_userdata_post_blocks_system_user | # Context:
import pytest
from unittest.mock import patch
def mock_user_directory(tmp_path): ...
def user_manager_multi_user(mock_user_directory): ...
def app_multi_user(user_manager_multi_user): ...
class TestSystemUserCreationBlocking: ...
class TestPublicUserStillWorks: ...
class TestCustomNodeScenario: ...
class Te... | async def test_userdata_post_blocks_system_user(
self, aiohttp_client, app_multi_user, mock_user_directory
):
"""
POST /userdata with System User header should be blocked.
"""
client = await aiohttp_client(app_multi_user)
with patch('app.user_manager.args') as mock_a... | test | 1 | {"function_name": "test_userdata_post_blocks_system_user", "class_name": "TestSystemUserEndpointBlocking", "qualname": "TestSystemUserEndpointBlocking.test_userdata_post_blocks_system_user", "file_path": "tests-unit/prompt_server_test/system_user_endpoint_test.py", "repo_id": "Comfy-Org/ComfyUI", "loc": 21, "tested_mod... |
ray-project/ray:release/nightly_tests/dataset/training_ingest_benchmark.py:BaseDataLoader.__init__ | # Context:
from typing import Dict, List, Optional
from dataset_benchmark_util import IMAGENET_WNID_TO_ID
class BenchmarkConfig: ...
class S3ParquetDataLoader(BaseDataLoader): ...
class S3UrlImageDataLoader(BaseDataLoader): ...
class S3ReadImagesDataLoader(BaseDataLoader): ...
def create_data_loader(data_loader: str, ... | def __init__(self, data_dir: str, label_to_id_map: Dict[str, int] = None):
"""Initialize the data loader.
Args:
data_dir: Path to data directory
label_to_id_map: Mapping from label strings to integer IDs
"""
self.data_dir = data_dir
self.label_to_id_map =... | function_simple | 0 | {"cognitive_complexity": 1, "loc": 9, "code_loc": 2, "docstring_loc": 6, "function_name": "__init__", "class_name": "BaseDataLoader", "qualname": "BaseDataLoader.__init__", "file_path": "release/nightly_tests/dataset/training_ingest_benchmark.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "... |
crewAIInc/crewAI:lib/crewai/tests/utilities/test_pydantic_schema_utils.py:TestBuildRichFieldDescription.test_min_max_length | # Context:
from crewai.utilities.pydantic_schema_utils import (
build_rich_field_description,
convert_oneof_to_anyof,
create_model_from_schema,
ensure_all_properties_required,
ensure_type_in_schemas,
force_additional_properties_false,
resolve_refs,
strip_null_from_types,
strip_unsupp... | def test_min_max_length(self) -> None:
desc = build_rich_field_description({"minLength": 1, "maxLength": 255})
assert "Min length: 1" in desc
assert "Max length: 255" in desc | test | 0 | {"function_name": "test_min_max_length", "class_name": "TestBuildRichFieldDescription", "qualname": "TestBuildRichFieldDescription.test_min_max_length", "file_path": "lib/crewai/tests/utilities/test_pydantic_schema_utils.py", "repo_id": "crewAIInc/crewAI", "loc": 4, "tested_modules": ["__future__", "copy", "typing", "p... |
ray-project/ray:python/ray/dashboard/tests/test_dashboard_auth.py:test_dashboard_request_requires_auth_invalid_token | # Context:
import requests
def test_dashboard_request_requires_auth_with_valid_token(setup_cluster_with_token_auth): ...
def test_dashboard_request_requires_auth_missing_token(setup_cluster_with_token_auth): ...
def test_dashboard_request_with_ray_auth_header(setup_cluster_with_token_auth): ...
def test_authorization_... | def test_dashboard_request_requires_auth_invalid_token(setup_cluster_with_token_auth):
"""Test that requests fail with invalid token when auth is enabled."""
cluster_info = setup_cluster_with_token_auth
headers = {"Authorization": "Bearer wrong_token_00000000000000000000000000000000"}
response = reque... | test | 0 | {"function_name": "test_dashboard_request_requires_auth_invalid_token", "class_name": null, "qualname": "test_dashboard_request_requires_auth_invalid_token", "file_path": "python/ray/dashboard/tests/test_dashboard_auth.py", "repo_id": "ray-project/ray", "loc": 13, "tested_modules": [], "has_docstring": true, "runnable_... |
ray-project/ray:doc/source/train/tutorials/ci/py_scripts/04b_tabular_workload_pattern.py:_dmat_from_arrow | # Context:
import numpy as np
import xgboost as xgb
import pyarrow as pa
def _arrow_table_from_shard(name: str) -> pa.Table: ...
def train_func(config): ...
class XGBPredictor: ...
# Task:
Write a Python function `_dmat_from_arrow` to build XGBoost DMatrix from pyarrow.Table with explicit feature_names.
Parameters: ... | def _dmat_from_arrow(table: pa.Table, feature_cols, label_col: str):
"""Build XGBoost DMatrix from pyarrow.Table with explicit feature_names."""
X = np.column_stack([table[c].to_numpy(zero_copy_only=False) for c in feature_cols])
y = table[label_col].to_numpy(zero_copy_only=False)
return xgb.DMatrix(X, ... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 5, "code_loc": 3, "docstring_loc": 1, "function_name": "_dmat_from_arrow", "class_name": null, "qualname": "_dmat_from_arrow", "file_path": "doc/source/train/tutorials/ci/py_scripts/04b_tabular_workload_pattern.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level"... |
vllm-project/vllm:tests/entrypoints/openai/tool_parsers/test_hunyuan_a13b_tool_parser.py:test_hunyuan_a13b_tool_parser_streaming | # Context:
from unittest.mock import MagicMock
import pytest
from tests.entrypoints.openai.tool_parsers.utils import (
run_tool_extraction,
run_tool_extraction_streaming,
)
from vllm.tool_parsers import ToolParser, ToolParserManager
def make_tool_call(name, arguments): ...
def test_hunyuan_a13b_tool_parser_ext... | def test_hunyuan_a13b_tool_parser_streaming(model_deltas, expected_tool_calls):
mock_tokenizer = MagicMock()
tool_parser: ToolParser = ToolParserManager.get_tool_parser("hunyuan_a13b")(
mock_tokenizer
)
reconstructor = run_tool_extraction_streaming(
tool_parser, model_deltas, assert_one... | test | 1 | {"function_name": "test_hunyuan_a13b_tool_parser_streaming", "class_name": null, "qualname": "test_hunyuan_a13b_tool_parser_streaming", "file_path": "tests/entrypoints/openai/tool_parsers/test_hunyuan_a13b_tool_parser.py", "repo_id": "vllm-project/vllm", "loc": 15, "tested_modules": ["tests.entrypoints.openai.tool_pars... |
zhayujie/chatgpt-on-wechat:agent/tools/scheduler/scheduler_tool.py:module_doc | Write a module-level docstring for the Python module `scheduler_tool` which contains class `SchedulerTool`. | Scheduler tool for creating and managing scheduled tasks | documentation | 1 | {"doc_type": "module", "module_name": "scheduler_tool", "file_path": "agent/tools/scheduler/scheduler_tool.py", "repo_id": "zhayujie/chatgpt-on-wechat", "char_length": 56} |
infiniflow/ragflow:test/testcases/test_sdk_api/test_chat_assistant_management/test_delete_chat_assistants.py:TestChatAssistantsDelete.test_repeated_deletion | # Context:
import pytest
class TestChatAssistantsDelete:
def test_basic_scenarios(self, client, add_chat_assistants_func, payload, expected_message, remaining): ...
def test_delete_chats_nonzero_response_raises(self, client, monkeypatch): ...
def test_delete_partial_invalid_id(self, client, add_chat_assist... | def test_repeated_deletion(self, client, add_chat_assistants_func):
_, _, chat_assistants = add_chat_assistants_func
chat_ids = [chat.id for chat in chat_assistants]
client.delete_chats(ids=chat_ids)
with pytest.raises(Exception) as exception_info:
client.delete_chats(ids=ch... | test | 1 | {"function_name": "test_repeated_deletion", "class_name": "TestChatAssistantsDelete", "qualname": "TestChatAssistantsDelete.test_repeated_deletion", "file_path": "test/testcases/test_sdk_api/test_chat_assistant_management/test_delete_chat_assistants.py", "repo_id": "infiniflow/ragflow", "loc": 8, "tested_modules": ["co... |
crewAIInc/crewAI:lib/crewai/tests/cli/authentication/providers/test_keycloak.py:TestKeycloakProvider.test_get_token_url_with_different_domain | # Context:
from crewai.cli.authentication.main import Oauth2Settings
from crewai.cli.authentication.providers.keycloak import KeycloakProvider
class TestKeycloakProvider:
def setup_method(self): ...
def test_initialization_with_valid_settings(self): ...
def test_get_authorize_url(self): ...
def test_ge... | def test_get_token_url_with_different_domain(self):
settings = Oauth2Settings(
provider="keycloak",
domain="sso.enterprise.com",
client_id="test-client",
audience="test-audience",
extra={
"realm": "enterprise-realm"
}
... | test | 0 | {"function_name": "test_get_token_url_with_different_domain", "class_name": "TestKeycloakProvider", "qualname": "TestKeycloakProvider.test_get_token_url_with_different_domain", "file_path": "lib/crewai/tests/cli/authentication/providers/test_keycloak.py", "repo_id": "crewAIInc/crewAI", "loc": 13, "tested_modules": ["cr... |
crewAIInc/crewAI:lib/crewai/tests/utilities/test_pydantic_schema_utils.py:TestRequiredOptional.test_required_field_has_no_default | # Context:
import pytest
from crewai.utilities.pydantic_schema_utils import (
build_rich_field_description,
convert_oneof_to_anyof,
create_model_from_schema,
ensure_all_properties_required,
ensure_type_in_schemas,
force_additional_properties_false,
resolve_refs,
strip_null_from_types,
... | def test_required_field_has_no_default(self) -> None:
schema = {
"type": "object",
"properties": {"name": {"type": "string"}},
"required": ["name"],
}
Model = create_model_from_schema(schema)
with pytest.raises(Exception):
Model() | test | 0 | {"function_name": "test_required_field_has_no_default", "class_name": "TestRequiredOptional", "qualname": "TestRequiredOptional.test_required_field_has_no_default", "file_path": "lib/crewai/tests/utilities/test_pydantic_schema_utils.py", "repo_id": "crewAIInc/crewAI", "loc": 9, "tested_modules": ["__future__", "copy", ... |
crewAIInc/crewAI:lib/crewai/tests/test_human_feedback_decorator.py:TestHumanFeedbackLearn.test_learn_true_empty_feedback_does_not_store | # Context:
from unittest.mock import MagicMock, patch
from crewai.flow import Flow, human_feedback, listen, start
class TestHumanFeedbackValidation: ...
class TestHumanFeedbackConfig: ...
class TestHumanFeedbackResult: ...
class TestDecoratorAttributePreservation: ...
class TestAsyncSupport: ...
class TestHumanFeedbac... | def test_learn_true_empty_feedback_does_not_store(self):
"""When learn=True but feedback is empty, no lessons are stored."""
class LearnFlow(Flow):
@start()
@human_feedback(message="Review:", llm="gpt-4o-mini", learn=True)
def produce(self):
return "o... | test | 0 | {"function_name": "test_learn_true_empty_feedback_does_not_store", "class_name": "TestHumanFeedbackLearn", "qualname": "TestHumanFeedbackLearn.test_learn_true_empty_feedback_does_not_store", "file_path": "lib/crewai/tests/test_human_feedback_decorator.py", "repo_id": "crewAIInc/crewAI", "loc": 20, "tested_modules": ["_... |
browser-use/browser-use:tests/ci/test_cli_headed_flag.py:test_headed_flag_with_session | # Context:
from browser_use.skill_cli.main import build_parser
def test_headed_flag_before_open_subcommand(): ...
def test_headed_flag_default_is_false(): ...
def test_headed_flag_with_browser_mode(): ...
# Task:
Write a Python test function `test_headed_flag_with_session` to test that --headed works with other globa... | def test_headed_flag_with_session():
"""Test that --headed works with other global flags like -s/--session."""
parser = build_parser()
args = parser.parse_args(['--headed', '-s', 'mysession', 'open', 'http://example.com'])
assert args.headed is True
assert args.session == 'mysession'
assert args.url == 'http://e... | test | 0 | {"function_name": "test_headed_flag_with_session", "class_name": null, "qualname": "test_headed_flag_with_session", "file_path": "tests/ci/test_cli_headed_flag.py", "repo_id": "browser-use/browser-use", "loc": 8, "tested_modules": ["browser_use.skill_cli.main"], "has_docstring": true, "runnable_level": "project_runnabl... |
xtekky/gpt4free:g4f/Provider/qwen/cookie_generator.py:refresh_cookies | # Context:
from g4f import debug
import asyncio
def lzw_compress(data: Optional[str], bits: int, char_func: Callable[[int], str]) -> str: ...
def custom_encode(data: Optional[str], url_safe: bool) -> str: ...
def random_hash() -> int: ...
def generate_device_id() -> str: ...
def parse_real_data(real_data: str) -> List... | async def refresh_cookies():
"""Refresh SSXMOD cookies (async wrapper)."""
global _current_cookies
try:
# generate_cookies() is CPU-bound sync; run it off the event loop.
result = await asyncio.to_thread(generate_cookies)
async with _lock:
_current_cookies = {
... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 18, "code_loc": 13, "docstring_loc": 1, "function_name": "refresh_cookies", "class_name": null, "qualname": "refresh_cookies", "file_path": "g4f/Provider/qwen/cookie_generator.py", "repo_id": "xtekky/gpt4free", "has_docstring": true, "runnable_level": "project_runnable"} |
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/invoke_crewai_automation_tool/invoke_crewai_automation_tool.py:InvokeCrewAIAutomationTool:class_doc | Write a class-level docstring for `InvokeCrewAIAutomationTool` (inherits from BaseTool) which has methods: `__init__`, `_kickoff_crew`, `_get_crew_status`, `_run`. | A CrewAI tool for invoking external crew/flows APIs.
This tool provides CrewAI Platform API integration with external crew services, supporting:
- Dynamic input schema configuration
- Automatic polling for task completion
- Bearer token authentication
- Comprehensive error handling
Example:
Basic usage:
>>> t... | documentation | 0 | {"doc_type": "class", "class_name": "InvokeCrewAIAutomationTool", "file_path": "lib/crewai-tools/src/crewai_tools/tools/invoke_crewai_automation_tool/invoke_crewai_automation_tool.py", "repo_id": "crewAIInc/crewAI", "char_length": 1650, "methods": ["__init__", "_kickoff_crew", "_get_crew_status", "_run"]} |
crewAIInc/crewAI:lib/crewai/src/crewai/a2a/config.py:A2AClientConfig:class_doc | Write a class-level docstring for `A2AClientConfig` (inherits from BaseModel) which has methods: `_migrate_deprecated_transport_fields`. | Configuration for connecting to remote A2A agents.
Attributes:
endpoint: A2A agent endpoint URL.
auth: Authentication scheme.
timeout: Request timeout in seconds.
max_turns: Maximum conversation turns with A2A agent.
response_model: Optional Pydantic model for structured A2A agent responses.
fa... | documentation | 0 | {"doc_type": "class", "class_name": "A2AClientConfig", "file_path": "lib/crewai/src/crewai/a2a/config.py", "repo_id": "crewAIInc/crewAI", "char_length": 874, "methods": ["_migrate_deprecated_transport_fields"]} |
ray-project/ray:python/ray/llm/tests/common/cloud/test_utils.py:TestRemoteObjectCacheDecorator.test_expiration | # Context:
import asyncio
import pytest
from ray.llm._internal.common.utils.cloud_utils import (
CloudObjectCache,
is_remote_path,
remote_object_cache,
)
class MockSyncFetcher: ...
class MockAsyncFetcher: ...
class TestCloudObjectCache: ...
class TestIsRemotePath: ...
class TestRemoteObjectCacheDecorator:... | async def test_expiration(self):
"""Test cache expiration for both missing and existing objects."""
call_count = 0
MISSING = object()
@remote_object_cache(
max_size=2,
missing_expire_seconds=1, # 1 second to expire missing object
exists_expire_second... | test | 0 | {"function_name": "test_expiration", "class_name": "TestRemoteObjectCacheDecorator", "qualname": "TestRemoteObjectCacheDecorator.test_expiration", "file_path": "python/ray/llm/tests/common/cloud/test_utils.py", "repo_id": "ray-project/ray", "loc": 41, "tested_modules": ["ray.llm._internal.common.utils.cloud_utils"], "h... |
huggingface/diffusers:src/diffusers/pipelines/qwenimage/pipeline_qwenimage_controlnet.py:license_header | Add a Apache-2.0 license header comment for the project 'diffusers', authored by Qwen-Image Team, InstantX Team and The HuggingFace Team, year 2025. | # Copyright 2025 Qwen-Image Team, InstantX Team 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/licenses/LICENSE-2... | license | 1 | {"license_type": "Apache-2.0", "author": "Qwen-Image Team, InstantX Team and The HuggingFace Team", "year": "2025", "source": "header", "repo_id": "huggingface/diffusers"} |
browser-use/browser-use:browser_use/skills/service.py:module_doc | Write a module-level docstring for the Python module `service` which contains class `SkillService`. | Skills service for fetching and executing skills from the Browser Use API | documentation | 0 | {"doc_type": "module", "module_name": "service", "file_path": "browser_use/skills/service.py", "repo_id": "browser-use/browser-use", "char_length": 73} |
infiniflow/ragflow:test/testcases/test_web_api/test_chunk_app/test_retrieval_chunks.py:TestChunksRetrieval.test_keyword | # Context:
import pytest
from common import retrieval_chunks
class TestAuthorization: ...
class TestChunksRetrieval:
def test_basic_scenarios(self, WebApiAuth, add_chunks, payload, expected_code, expected_page_size, expected_message): ...
def test_page(self, WebApiAuth, add_chunks, payload, expected_code, exp... | def test_keyword(self, WebApiAuth, add_chunks, payload, expected_code, expected_page_size, expected_message):
dataset_id, _, _ = add_chunks
payload.update({"question": "chunk test", "kb_id": [dataset_id]})
res = retrieval_chunks(WebApiAuth, payload)
assert res["code"] == expected_code, r... | test | 1 | {"function_name": "test_keyword", "class_name": "TestChunksRetrieval", "qualname": "TestChunksRetrieval.test_keyword", "file_path": "test/testcases/test_web_api/test_chunk_app/test_retrieval_chunks.py", "repo_id": "infiniflow/ragflow", "loc": 9, "tested_modules": ["concurrent.futures", "common", "configs", "libs.auth"]... |
crewAIInc/crewAI:lib/crewai-tools/tests/tools/tool_collection_test.py:TestToolCollection.test_access_by_index | # Context:
class TestToolCollection(unittest.TestCase):
def setUp(self): ...
def _create_mock_tool(self, name, description): ...
def test_initialization(self): ...
def test_empty_initialization(self): ...
def test_initialization_with_none(self): ...
def test_access_by_name(self): ...
def te... | def test_access_by_index(self):
self.assertEqual(self.tools[0], self.search_tool)
self.assertEqual(self.tools[1], self.calculator_tool)
self.assertEqual(self.tools[2], self.translator_tool) | test | 0 | {"function_name": "test_access_by_index", "class_name": "TestToolCollection", "qualname": "TestToolCollection.test_access_by_index", "file_path": "lib/crewai-tools/tests/tools/tool_collection_test.py", "repo_id": "crewAIInc/crewAI", "loc": 4, "tested_modules": ["crewai.tools", "crewai_tools.adapters.tool_collection"], ... |
browser-use/browser-use:tests/ci/test_structured_extraction.py:TestSchemaDictToPydanticModel.test_rejects_ref | # Context:
import pytest
from browser_use.tools.extraction.schema_utils import schema_dict_to_pydantic_model
class TestExtractionResult: ...
def _make_extraction_llm(structured_response: dict | None, freetext_response: str) -> BaseChatModel: ...
async def browser_session(): ...
def http_server(): ...
def base_url(http... | def test_rejects_ref(self):
schema = {
'type': 'object',
'properties': {'item': {'$ref': '#/$defs/Item'}},
'$defs': {'Item': {'type': 'object', 'properties': {'name': {'type': 'string'}}}},
}
with pytest.raises(ValueError, match='Unsupported JSON Schema keyword'):
schema_dict_to_pydantic_model(schema) | test | 0 | {"function_name": "test_rejects_ref", "class_name": "TestSchemaDictToPydanticModel", "qualname": "TestSchemaDictToPydanticModel.test_rejects_ref", "file_path": "tests/ci/test_structured_extraction.py", "repo_id": "browser-use/browser-use", "loc": 8, "tested_modules": ["pydantic", "browser_use.agent.views", "browser_use... |
ray-project/ray:ci/ray_ci/ray_image.py:RayImage.wanda_image_name | # Context:
class RayImageError(Exception): ...
class RayImage:
def __post_init__(self): ...
def arch_suffix(self) -> str: ...
def repo(self) -> str: ...
def variation_suffix(self) -> str: ...
def validate(self) -> None: ...
# Task:
Write a Python method `wanda_image_name` for the class `RayImage`... | def wanda_image_name(self) -> str:
"""Wanda output image name (without registry prefix)."""
if self.platform == "cpu":
return f"{self.image_type}-py{self.python_version}-cpu{self.arch_suffix}"
return f"{self.image_type}-py{self.python_version}-{self.platform}{self.arch_suffix}" | function_simple | 0 | {"cognitive_complexity": 1, "loc": 5, "code_loc": 3, "docstring_loc": 1, "function_name": "wanda_image_name", "class_name": "RayImage", "qualname": "RayImage.wanda_image_name", "file_path": "ci/ray_ci/ray_image.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "class_runnable"} |
infiniflow/ragflow:common/data_source/confluence_connector.py:ConfluenceConnector._fetch_page_attachments | # Context:
import logging
from pathlib import Path
from typing import Any, cast, Iterator, Callable, Generator
from common.data_source.config import INDEX_BATCH_SIZE, DocumentSource, CONTINUE_ON_CONNECTOR_FAILURE, \
CONFLUENCE_CONNECTOR_LABELS_TO_SKIP, CONFLUENCE_TIMEZONE_OFFSET, CONFLUENCE_CONNECTOR_USER_PROFILES_... | def _fetch_page_attachments(
self,
page: dict[str, Any],
start: SecondsSinceUnixEpoch | None = None,
end: SecondsSinceUnixEpoch | None = None,
) -> tuple[list[Document], list[ConnectorFailure]]:
"""
Inline attachments are added directly to the document as text or imag... | function_complex | 1 | {"cognitive_complexity": 58, "loc": 167, "code_loc": 128, "docstring_loc": 5, "function_name": "_fetch_page_attachments", "class_name": "ConfluenceConnector", "qualname": "ConfluenceConnector._fetch_page_attachments", "file_path": "common/data_source/confluence_connector.py", "repo_id": "infiniflow/ragflow", "has_docst... |
ray-project/ray:python/ray/llm/_internal/batch/benchmark/benchmark_processor.py:_build_serve_deployment_config | # Context:
from ray.data.llm import (
ChatTemplateStageConfig,
DetokenizeStageConfig,
ServeDeploymentProcessorConfig,
TokenizerStageConfig,
build_processor,
vLLMEngineProcessorConfig,
)
from ray.serve.llm.openai_api_models import CompletionRequest
class Mode(Enum): ...
def build_vllm_engine_kwa... | def _build_serve_deployment_config(
batch_size: int,
concurrency: int,
deployment_name: str = None,
app_name: str = None,
) -> ServeDeploymentProcessorConfig:
"""Helper to create ServeDeploymentProcessorConfig."""
return ServeDeploymentProcessorConfig(
deployment_name=deployment_name,
... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 16, "code_loc": 9, "docstring_loc": 1, "function_name": "_build_serve_deployment_config", "class_name": null, "qualname": "_build_serve_deployment_config", "file_path": "python/ray/llm/_internal/batch/benchmark/benchmark_processor.py", "repo_id": "ray-project/ray", "has_docstring": tr... |
langflow-ai/langflow:src/backend/tests/unit/components/processing/test_type_converter_component.py:TestTypeConverterComponent.test_dataframe_to_data | # Context:
import pandas as pd
from lfx.schema.data import Data
from lfx.schema.dataframe import DataFrame
class TestTypeConverterComponent(ComponentTestBaseWithoutClient):
def component_class(self): ...
def file_names_mapping(self): ...
def test_message_to_message(self, component_class): ...
def test_... | def test_dataframe_to_data(self, component_class):
"""Test converting DataFrame to Data."""
df_data = pd.DataFrame({"col1": ["Hello"]})
component = component_class(input_data=DataFrame(data=df_data), output_type="Data")
result = component.convert_to_data()
assert isinstance(resul... | test | 1 | {"function_name": "test_dataframe_to_data", "class_name": "TestTypeConverterComponent", "qualname": "TestTypeConverterComponent.test_dataframe_to_data", "file_path": "src/backend/tests/unit/components/processing/test_type_converter_component.py", "repo_id": "langflow-ai/langflow", "loc": 7, "tested_modules": ["io", "lf... |
apache/airflow:providers/ssh/tests/unit/ssh/hooks/test_ssh_async.py:TestSSHHookAsync.test_parse_extras_host_key | # Context:
from unittest import mock
from airflow.providers.ssh.hooks.ssh import SSHHookAsync
class TestSSHHookAsync:
def test_init_with_conn_id(self): ...
def test_init_with_overrides(self): ...
def test_init_default_known_hosts(self): ...
def test_parse_extras_key_file(self): ...
def test_parse_e... | def test_parse_extras_host_key(self):
"""Test parsing host_key from connection extras."""
hook = SSHHookAsync(ssh_conn_id="test_conn")
mock_conn = mock.MagicMock()
mock_conn.extra_dejson = {"host_key": "ssh-rsa AAAAB3...", "no_host_key_check": "false"}
mock_conn.host = "test.host... | test | 1 | {"function_name": "test_parse_extras_host_key", "class_name": "TestSSHHookAsync", "qualname": "TestSSHHookAsync.test_parse_extras_host_key", "file_path": "providers/ssh/tests/unit/ssh/hooks/test_ssh_async.py", "repo_id": "apache/airflow", "loc": 9, "tested_modules": ["__future__", "airflow.providers.ssh.hooks.ssh"], "h... |
browser-use/browser-use:browser_use/browser/session.py:BrowserSession.get_target_id_from_tab_id | # Context:
from cdp_use.cdp.target import SessionID, TargetID
class Target(BaseModel): ...
class CDPSession(BaseModel): ...
class BrowserSession(BaseModel):
model_config = ConfigDict(
def __init__(
self,
*,
# Cloud browser params - use these for cloud mode
cloud_profile_id: UUID | str | None = None,
cl... | async def get_target_id_from_tab_id(self, tab_id: str) -> TargetID:
"""Get the full-length TargetID from the truncated 4-char tab_id using SessionManager."""
if not self.session_manager:
raise RuntimeError('SessionManager not initialized')
for full_target_id in self.session_manager.get_all_target_ids():
if... | function_complex | 0 | {"cognitive_complexity": 7, "loc": 14, "code_loc": 8, "docstring_loc": 1, "function_name": "get_target_id_from_tab_id", "class_name": "BrowserSession", "qualname": "BrowserSession.get_target_id_from_tab_id", "file_path": "browser_use/browser/session.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "run... |
crewAIInc/crewAI:lib/crewai/tests/a2a/utils/test_task.py:TestExecute.test_emits_completed_event | # Context:
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from crewai.a2a.utils.task import cancel, cancellable, execute
def mock_agent() -> MagicMock: ...
def mock_task(mock_context: MagicMock) -> MagicMock: ...
def mock_context() -> MagicMock: ...
def mock_event_queue() -> AsyncMock: ...
async d... | async def test_emits_completed_event(
self,
mock_agent: MagicMock,
mock_context: MagicMock,
mock_event_queue: AsyncMock,
mock_task: MagicMock,
) -> None:
"""Execute emits A2AServerTaskCompletedEvent on success."""
with (
patch("crewai.a2a.utils.tas... | test | 0 | {"function_name": "test_emits_completed_event", "class_name": "TestExecute", "qualname": "TestExecute.test_emits_completed_event", "file_path": "lib/crewai/tests/a2a/utils/test_task.py", "repo_id": "crewAIInc/crewAI", "loc": 20, "tested_modules": ["__future__", "typing", "a2a.server.agent_execution", "a2a.server.events... |
ray-project/ray:python/ray/data/tests/test_default_cluster_autoscaler_v2.py:TestClusterAutoscaling.test_get_node_resource_spec_and_count_from_zero | # Context:
from unittest.mock import MagicMock, patch
from ray.core.generated import autoscaler_pb2
from ray.data._internal.cluster_autoscaler.default_cluster_autoscaler_v2 import (
DefaultClusterAutoscalerV2,
_get_node_resource_spec_and_count,
_NodeResourceSpec,
)
class StubUtilizationGauge(ResourceUtiliz... | def test_get_node_resource_spec_and_count_from_zero(self):
"""Test that get_node_resource_spec_and_count can discover node types
from cluster config even when there are zero worker nodes."""
# Simulate a cluster with only head node (no worker nodes)
node_table = [
{
... | test | 0 | {"function_name": "test_get_node_resource_spec_and_count_from_zero", "class_name": "TestClusterAutoscaling", "qualname": "TestClusterAutoscaling.test_get_node_resource_spec_and_count_from_zero", "file_path": "python/ray/data/tests/test_default_cluster_autoscaler_v2.py", "repo_id": "ray-project/ray", "loc": 41, "tested_... |
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/crypto/blake2.py:Blake2b.QuickDigest | # Context:
import hashlib
from typing import Union
from ..misc import AlgoUtils
class _Blake2bWithSpecificSize(ABC): ...
class Blake2b32(_Blake2bWithSpecificSize): ...
class Blake2b40(_Blake2bWithSpecificSize): ...
class Blake2b160(_Blake2bWithSpecificSize): ...
class Blake2b224(_Blake2bWithSpecificSize): ...
class Bl... | def QuickDigest(data: Union[bytes, str],
digest_size: int,
key: Union[bytes, str] = b"",
salt: Union[bytes, str] = b"") -> bytes:
"""
Compute the digest (quick version).
Args:
data (str or bytes) : Data
... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 20, "code_loc": 4, "docstring_loc": 12, "function_name": "QuickDigest", "class_name": "Blake2b", "qualname": "Blake2b.QuickDigest", "file_path": "python/ccxt/static_dependencies/bip/utils/crypto/blake2.py", "repo_id": "ccxt/ccxt", "has_docstring": true, "runnable_level": "project_runn... |
langchain-ai/langchain:libs/partners/anthropic/tests/unit_tests/middleware/test_prompt_caching.py:TestCollectCodeExecutionToolIds.test_no_code_execution_calls | # Context:
from langchain_anthropic.chat_models import (
ChatAnthropic,
_collect_code_execution_tool_ids,
_is_code_execution_related_block,
)
class FakeToolCallingModel(BaseChatModel): ...
def test_anthropic_prompt_caching_middleware_initialization() -> None: ...
def test_anthropic_prompt_caching_middlewar... | def test_no_code_execution_calls(self) -> None:
"""Test messages without any code_execution calls."""
messages = [
{
"role": "user",
"content": [{"type": "text", "text": "Hello"}],
},
{
"role": "assistant",
... | test | 1 | {"function_name": "test_no_code_execution_calls", "class_name": "TestCollectCodeExecutionToolIds", "qualname": "TestCollectCodeExecutionToolIds.test_no_code_execution_calls", "file_path": "libs/partners/anthropic/tests/unit_tests/middleware/test_prompt_caching.py", "repo_id": "langchain-ai/langchain", "loc": 21, "teste... |
ray-project/ray:rllib/examples/envs/classes/multi_agent/footsies/test/footsies_suppress_unity_logs.py:TestFootsies.test_default_supress_output_mode | # Context:
import os
import time
from pathlib import Path
def _create_env(config_overrides): ...
def capture_stdout_stderr(): ...
class TestFootsies(unittest.TestCase):
def test_enable_output_mode(self): ...
# Task:
Write a Python test method `test_default_supress_output_mode` in test class `TestFootsies` to ver... | def test_default_supress_output_mode(self):
with capture_stdout_stderr() as log_path:
env = _create_env({})
time.sleep(2) # Give Unity time to write output
env.close()
# Give a bit more time for any buffered output to be written
time.sleep(0.5)
... | test | 0 | {"function_name": "test_default_supress_output_mode", "class_name": "TestFootsies", "qualname": "TestFootsies.test_default_supress_output_mode", "file_path": "rllib/examples/envs/classes/multi_agent/footsies/test/footsies_suppress_unity_logs.py", "repo_id": "ray-project/ray", "loc": 21, "tested_modules": ["contextlib",... |
huggingface/diffusers:src/diffusers/pipelines/hunyuan_video1_5/pipeline_hunyuan_video1_5_image2video.py:HunyuanVideo15ImageToVideoPipeline.prepare_cond_latents_and_mask | # Context:
import PIL
import torch
def format_text_input(prompt: list[str], system_message: str) -> list[dict[str, Any]]: ...
def extract_glyph_texts(prompt: str) -> list[str]: ...
def retrieve_latents(encoder_output: torch.Tensor, generator: torch.Generator | None, sample_mode: str): ...
def retrieve_timesteps(schedu... | def prepare_cond_latents_and_mask(
self,
latents: torch.Tensor,
image: PIL.Image.Image,
batch_size: int,
height: int,
width: int,
dtype: torch.dtype,
device: torch.device,
):
"""
Prepare conditional latents and mask for t2v generation.
... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 39, "code_loc": 15, "docstring_loc": 9, "function_name": "prepare_cond_latents_and_mask", "class_name": "HunyuanVideo15ImageToVideoPipeline", "qualname": "HunyuanVideo15ImageToVideoPipeline.prepare_cond_latents_and_mask", "file_path": "src/diffusers/pipelines/hunyuan_video1_5/pipeline... |
vllm-project/vllm:vllm/model_executor/layers/quantization/utils/nvfp4_utils.py:prepare_weights_for_nvfp4_flashinfer_trtllm | # Context:
import torch
from flashinfer import shuffle_matrix_a, shuffle_matrix_sf_a
class NvFp4LinearBackend(Enum): ...
def select_nvfp4_linear_backend() -> NvFp4LinearBackend: ...
def prepare_weights_for_nvfp4_cutlass(weight: torch.Tensor, weight_scale: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, int]: ...
de... | def prepare_weights_for_nvfp4_flashinfer_trtllm(
weight: torch.Tensor,
weight_scale: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Prepare weights and scales for FlashInfer TRTLLM FP4 GEMM."""
from flashinfer import shuffle_matrix_a, shuffle_matrix_sf_a
epilogue_tile_m = 128
shuffled... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 16, "code_loc": 9, "docstring_loc": 1, "function_name": "prepare_weights_for_nvfp4_flashinfer_trtllm", "class_name": null, "qualname": "prepare_weights_for_nvfp4_flashinfer_trtllm", "file_path": "vllm/model_executor/layers/quantization/utils/nvfp4_utils.py", "repo_id": "vllm-project/v... |
ray-project/ray:python/ray/data/_internal/execution/operators/hash_shuffle.py:ShuffleAggregation.is_compacting | Write a Python method `is_compacting` for the class `ShuffleAggregation` to returns whether this aggregation is capable of compacting partial. | def is_compacting(cls):
"""Returns whether this aggregation is capable of compacting partial
partition's shards list.
"""
return False | function_simple | 0 | {"cognitive_complexity": 0, "loc": 5, "code_loc": 1, "docstring_loc": 3, "function_name": "is_compacting", "class_name": "ShuffleAggregation", "qualname": "ShuffleAggregation.is_compacting", "file_path": "python/ray/data/_internal/execution/operators/hash_shuffle.py", "repo_id": "ray-project/ray", "has_docstring": true... |
vllm-project/vllm:vllm/distributed/kv_transfer/kv_connector/v1/offloading_connector.py:OffloadingConnectorScheduler.request_finished | # Context:
from typing import Any
from vllm.v1.request import Request
class OffloadingOperationMetrics: ...
class OffloadingConnectorStats(KVConnectorStats): ...
class OffloadingConnectorMetadata(KVConnectorMetadata): ...
class OffloadingConnector(KVConnectorBase_V1): ...
class OffloadingConnectorWorker: ...
class Off... | def request_finished(
self,
request: Request,
block_ids: list[int],
) -> tuple[bool, dict[str, Any] | None]:
"""
Called when a request has finished, before its blocks are freed.
Returns:
True if the request is being saved/sent asynchronously and blocks
... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 22, "code_loc": 6, "docstring_loc": 10, "function_name": "request_finished", "class_name": "OffloadingConnectorScheduler", "qualname": "OffloadingConnectorScheduler.request_finished", "file_path": "vllm/distributed/kv_transfer/kv_connector/v1/offloading_connector.py", "repo_id": "vllm... |
apache/airflow:providers/redis/tests/unit/redis/triggers/test_redis_await_message.py:TestAwaitMessageTrigger.test_trigger_serialization | # Context:
from airflow.providers.redis.triggers.redis_await_message import AwaitMessageTrigger
class TestAwaitMessageTrigger:
async def test_trigger_run_succeed(self, mock_redis_conn): ...
async def test_trigger_run_succeed_with_bytes(self, mock_redis_conn): ...
async def test_trigger_run_fail(self, mock_... | def test_trigger_serialization(self):
trigger = AwaitMessageTrigger(
channels=["test_channel"],
redis_conn_id="redis_default",
poll_interval=30,
)
assert isinstance(trigger, AwaitMessageTrigger)
classpath, kwargs = trigger.serialize()
assert... | test | 1 | {"function_name": "test_trigger_serialization", "class_name": "TestAwaitMessageTrigger", "qualname": "TestAwaitMessageTrigger.test_trigger_serialization", "file_path": "providers/redis/tests/unit/redis/triggers/test_redis_await_message.py", "repo_id": "apache/airflow", "loc": 17, "tested_modules": ["__future__", "airfl... |
infiniflow/ragflow:common/data_source/utils.py:make_paginated_slack_api_call | # Context:
from collections.abc import Callable, Generator, Iterator, Mapping, Sequence
from typing import IO, Any, Generic, Iterable, Optional, Protocol, TypeVar, cast
from slack_sdk.web import SlackResponse
def datetime_from_string(datetime_string: str) -> datetime: ...
def is_valid_image_type(mime_type: str) -> boo... | def make_paginated_slack_api_call(call: Callable[..., SlackResponse], **kwargs: Any) -> Generator[dict[str, Any], None, None]:
"""Make paginated Slack API call"""
return _make_slack_api_call_paginated(call)(**kwargs) | function_simple | 1 | {"cognitive_complexity": 0, "loc": 3, "code_loc": 1, "docstring_loc": 1, "function_name": "make_paginated_slack_api_call", "class_name": null, "qualname": "make_paginated_slack_api_call", "file_path": "common/data_source/utils.py", "repo_id": "infiniflow/ragflow", "has_docstring": true, "runnable_level": "project_runna... |
ray-project/ray:python/ray/llm/tests/batch/gpu/stages/test_serve_deployment_stage.py:test_serve_deployment_invalid_method | # Context:
import pytest
from ray.llm._internal.batch.stages.serve_deployment_stage import (
ServeDeploymentStageUDF,
)
from ray.serve.llm.openai_api_models import ChatCompletionRequest, CompletionRequest
def mock_serve_deployment_handle(): ...
async def test_serve_deployment_udf_methods(mock_serve_deployment_hand... | async def test_serve_deployment_invalid_method(mock_serve_deployment_handle):
"""Test that invalid method raises error at runtime."""
# Set up the mock to simulate a method that doesn't exist
mock_serve_deployment_handle.invalid_method = None
udf = ServeDeploymentStageUDF(
data_column="__data",... | test | 0 | {"function_name": "test_serve_deployment_invalid_method", "class_name": null, "qualname": "test_serve_deployment_invalid_method", "file_path": "python/ray/llm/tests/batch/gpu/stages/test_serve_deployment_stage.py", "repo_id": "ray-project/ray", "loc": 30, "tested_modules": ["ray.exceptions", "ray.llm._internal.batch.st... |
ray-project/ray:python/ray/data/util/data_batch_conversion.py:_unwrap_ndarray_object_type_if_needed | # Context:
import numpy as np
def _lazy_import_pandas(): ...
class BatchFormat(str, Enum): ...
def _convert_batch_type_to_pandas(data: DataBatchType, cast_tensor_columns: bool) -> 'pd.DataFrame': ...
def _convert_pandas_to_batch_type(data: 'pd.DataFrame', type: BatchFormat, cast_tensor_columns: bool) -> DataBatchType:... | def _unwrap_ndarray_object_type_if_needed(arr: np.ndarray) -> np.ndarray:
"""Unwrap an object-dtyped NumPy ndarray containing ndarray pointers into a single
contiguous ndarray, if needed/possible.
"""
if arr.dtype.type is np.object_:
try:
# Try to convert the NumPy ndarray to a non-o... | function_simple | 0 | {"cognitive_complexity": 2, "loc": 12, "code_loc": 6, "docstring_loc": 3, "function_name": "_unwrap_ndarray_object_type_if_needed", "class_name": null, "qualname": "_unwrap_ndarray_object_type_if_needed", "file_path": "python/ray/data/util/data_batch_conversion.py", "repo_id": "ray-project/ray", "has_docstring": true, ... |
huggingface/transformers:src/transformers/masking_utils.py:sliding_window_causal_mask_function | # Context:
from collections.abc import Callable
def and_masks(*mask_functions) -> Callable: ...
def or_masks(*mask_functions) -> Callable: ...
def causal_mask_function(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool: ...
def bidirectional_mask_function(batch_idx: int, head_idx: int, q_idx: int, kv_idx:... | def sliding_window_causal_mask_function(sliding_window: int) -> Callable:
"""
This return the mask_function function to create a sliding window mask.
"""
return and_masks(sliding_window_overlay(sliding_window), causal_mask_function) | function_simple | 0 | {"cognitive_complexity": 0, "loc": 5, "code_loc": 1, "docstring_loc": 3, "function_name": "sliding_window_causal_mask_function", "class_name": null, "qualname": "sliding_window_causal_mask_function", "file_path": "src/transformers/masking_utils.py", "repo_id": "huggingface/transformers", "has_docstring": true, "runnabl... |
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/serper_dev_tool/serper_dev_tool.py:SerperDevTool._make_api_request | # Context:
import json
import os
from typing import Any, TypedDict
import requests
class KnowledgeGraph(TypedDict): ...
class Sitelink(TypedDict): ...
class OrganicResult(TypedDict): ...
class PeopleAlsoAskResult(TypedDict): ...
class RelatedSearchResult(TypedDict): ...
class NewsResult(TypedDict): ...
class SearchPar... | def _make_api_request(self, search_query: str, search_type: str) -> dict[str, Any]:
"""Make API request to Serper."""
search_url = self._get_search_url(search_type)
payload = {"q": search_query, "num": self.n_results}
if self.country != "":
payload["gl"] = self.country
... | function_complex | 0 | {"cognitive_complexity": 14, "loc": 45, "code_loc": 40, "docstring_loc": 1, "function_name": "_make_api_request", "class_name": "SerperDevTool", "qualname": "SerperDevTool._make_api_request", "file_path": "lib/crewai-tools/src/crewai_tools/tools/serper_dev_tool/serper_dev_tool.py", "repo_id": "crewAIInc/crewAI", "has_d... |
ray-project/ray:ci/ray_ci/test_ray_image.py:TestValidateInvalid.test_invalid_platform_for_ray_llm | # Context:
import pytest
from ci.ray_ci.ray_image import IMAGE_TYPE_CONFIG, RayImage, RayImageError
class TestWandaImageName: ...
class TestArchSuffix: ...
class TestRepo: ...
class TestVariationSuffix: ...
class TestValidateValid: ...
class TestImageTypeConfig: ...
class TestValidateInvalid:
def test_unknown_ima... | def test_invalid_platform_for_ray_llm(self):
with pytest.raises(RayImageError, match="Invalid platform cpu for ray-llm"):
RayImage("ray-llm", "3.11", "cpu").validate() | test | 0 | {"function_name": "test_invalid_platform_for_ray_llm", "class_name": "TestValidateInvalid", "qualname": "TestValidateInvalid.test_invalid_platform_for_ray_llm", "file_path": "ci/ray_ci/test_ray_image.py", "repo_id": "ray-project/ray", "loc": 3, "tested_modules": ["ci.ray_ci.configs", "ci.ray_ci.docker_container", "ci.r... |
huggingface/transformers:tests/models/vaultgemma/test_modeling_vaultgemma.py:VaultGemmaIntegrationTest.test_export_static_cache | # Context:
import pytest
from packaging import version
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
DynamicCache,
is_torch_available,
pipeline,
)
from transformers.generation.configuration_utils import GenerationConfig
from transformers.testing_utils import (
Expectations,
... | def test_export_static_cache(self):
if version.parse(torch.__version__) < version.parse("2.5.0"):
self.skipTest(reason="This test requires torch >= 2.5 to run.")
from transformers.integrations.executorch import (
TorchExportableModuleWithStaticCache,
)
model_id ... | test | 0 | {"function_name": "test_export_static_cache", "class_name": "VaultGemmaIntegrationTest", "qualname": "VaultGemmaIntegrationTest.test_export_static_cache", "file_path": "tests/models/vaultgemma/test_modeling_vaultgemma.py", "repo_id": "huggingface/transformers", "loc": 60, "tested_modules": ["packaging", "parameterized"... |
vllm-project/vllm:vllm/model_executor/models/molmo2.py:Molmo2VisionBlock:class_doc | Write a class-level docstring for `Molmo2VisionBlock` (inherits from nn.Module) which has methods: `__init__`, `forward`. | Residual attention block used in Vision Transformer. | documentation | 1 | {"doc_type": "class", "class_name": "Molmo2VisionBlock", "file_path": "vllm/model_executor/models/molmo2.py", "repo_id": "vllm-project/vllm", "char_length": 52, "methods": ["__init__", "forward"]} |
ray-project/ray:release/train_tests/benchmark/runner.py:TrainLoopRunner._train_epoch | # Context:
import pprint
class VanillaTorchRunner(TrainLoopRunner): ...
class TrainLoopRunner:
def __init__(self, factory: BenchmarkFactory):
self.factory = factory
self.benchmark_config = factory.benchmark_config
self._setup()
# Training progress state.
self._train_batch... | def _train_epoch(self):
"""Subclasses can override the entrire `_train_epoch` method for more training
logic customization."""
if ray.train.get_context().get_world_rank() == 0:
logger.info(f"Training starting @ epoch={self._train_epoch_idx}")
train_dataloader = self.factory.... | function_complex | 0 | {"cognitive_complexity": 16, "loc": 46, "code_loc": 30, "docstring_loc": 2, "function_name": "_train_epoch", "class_name": "TrainLoopRunner", "qualname": "TrainLoopRunner._train_epoch", "file_path": "release/train_tests/benchmark/runner.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "file_r... |
666ghj/BettaFish:MediaEngine/state/state.py:State.save_to_file | # Context:
class Search: ...
class Research: ...
class Paragraph: ...
class State:
def add_paragraph(self, title: str, content: str) -> int: ...
def get_paragraph(self, index: int) -> Optional[Paragraph]: ...
def get_completed_paragraphs_count(self) -> int: ...
def get_total_paragraphs_count(self) -> ... | def save_to_file(self, filepath: str):
"""保存状态到文件"""
with open(filepath, 'w', encoding='utf-8') as f:
f.write(self.to_json()) | function_simple | 1 | {"cognitive_complexity": 0, "loc": 4, "code_loc": 2, "docstring_loc": 1, "function_name": "save_to_file", "class_name": "State", "qualname": "State.save_to_file", "file_path": "MediaEngine/state/state.py", "repo_id": "666ghj/BettaFish", "has_docstring": true, "runnable_level": "class_runnable"} |
langflow-ai/langflow:src/backend/tests/unit/utils/test_mcp_cleanup.py:TestTryTerminateMcpProcess.test_terminates_mcp_proxy_process | # Context:
from unittest.mock import AsyncMock, MagicMock, patch
from langflow.utils.mcp_cleanup import (
_kill_mcp_processes,
_terminate_child_mcp_processes,
_terminate_orphaned_mcp_processes,
_try_terminate_mcp_process,
cleanup_mcp_sessions,
)
class TestCleanupMcpSessions: ...
class TestKillMcpPr... | async def test_terminates_mcp_proxy_process(self):
"""Test termination of mcp-proxy process."""
mock_psutil = MagicMock()
mock_psutil.NoSuchProcess = Exception
mock_psutil.AccessDenied = Exception
mock_psutil.ZombieProcess = Exception
mock_psutil.TimeoutExpired = Exceptio... | test | 1 | {"function_name": "test_terminates_mcp_proxy_process", "class_name": "TestTryTerminateMcpProcess", "qualname": "TestTryTerminateMcpProcess.test_terminates_mcp_proxy_process", "file_path": "src/backend/tests/unit/utils/test_mcp_cleanup.py", "repo_id": "langflow-ai/langflow", "loc": 17, "tested_modules": ["langflow.utils... |
crewAIInc/crewAI:lib/crewai/src/crewai/llms/providers/anthropic/completion.py:AnthropicCompletion.call | # Context:
import logging
from typing import TYPE_CHECKING, Any, Final, Literal, TypeGuard, cast
from pydantic import BaseModel
from crewai.llms.base_llm import BaseLLM, llm_call_context
from crewai.utilities.types import LLMMessage
def _supports_native_structured_outputs(model: str) -> bool: ...
def _is_pydantic_mode... | def call(
self,
messages: str | list[LLMMessage],
tools: list[dict[str, Any]] | None = None,
callbacks: list[Any] | None = None,
available_functions: dict[str, Any] | None = None,
from_task: Any | None = None,
from_agent: Any | None = None,
response_model:... | function_complex | 0 | {"cognitive_complexity": 8, "loc": 77, "code_loc": 43, "docstring_loc": 13, "function_name": "call", "class_name": "AnthropicCompletion", "qualname": "AnthropicCompletion.call", "file_path": "lib/crewai/src/crewai/llms/providers/anthropic/completion.py", "repo_id": "crewAIInc/crewAI", "has_docstring": true, "runnable_l... |
ray-project/ray:doc/source/ray-overview/examples/e2e-timeseries/e2e_timeseries/model.py:DLinear.forward | # Context:
import torch
class moving_avg(nn.Module): ...
class series_decomp(nn.Module): ...
class DLinear(nn.Module):
def __init__(self, configs: Dict[str, Any]):
super().__init__()
self.seq_len: int = configs["seq_len"]
self.pred_len: int = configs["pred_len"]
self.decompsition ... | def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Forward pass for the DLinear model.
Args:
x (torch.Tensor): Input tensor. Can be 2D [Batch, SeqLen] (interpreted as 1 channel)
or 3D [Batch, SeqLen, Channels].
Returns:
torch.T... | function_simple | 0 | {"cognitive_complexity": 4, "loc": 46, "code_loc": 26, "docstring_loc": 10, "function_name": "forward", "class_name": "DLinear", "qualname": "DLinear.forward", "file_path": "doc/source/ray-overview/examples/e2e-timeseries/e2e_timeseries/model.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 13