sample_id string | instruction string | completion string | category string | label int64 | metadata string |
|---|---|---|---|---|---|
exo-explore/exo:src/exo/download/tests/test_download_verification.py:TestFileVerification.test_redownload_when_file_size_changes_upstream | # Context:
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
import aiofiles
import aiofiles.os as aios
from exo.shared.types.common import ModelId
from exo.download.download_utils import (
_download_file, # pyright: ignore[reportPrivateUsage]
)
def model_id() -> Model... | async def test_redownload_when_file_size_changes_upstream(
self, model_id: ModelId, tmp_path: Path
) -> None:
"""Test that files with mismatched sizes are re-downloaded."""
# Import inside test to allow patching
from exo.download.download_utils import (
_download_file, #... | test | 0 | {"function_name": "test_redownload_when_file_size_changes_upstream", "class_name": "TestFileVerification", "qualname": "TestFileVerification.test_redownload_when_file_size_changes_upstream", "file_path": "src/exo/download/tests/test_download_verification.py", "repo_id": "exo-explore/exo", "loc": 61, "tested_modules": [... |
vllm-project/vllm:vllm/model_executor/layers/fused_moe/router/base_router.py:BaseRouter.select_experts | # Context:
import torch
class BaseRouter(FusedMoERouter):
def __init__(
self,
top_k: int,
global_num_experts: int,
eplb_state: EplbLayerState,
enable_eplb: bool = False,
# TODO(bnell): Once the MK is constructed at layer init time, we
# can make this a plain ... | def select_experts(
self,
hidden_states: torch.Tensor,
router_logits: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Route the input hidden states to the top-k experts based on the
router logits.
This method implements the template method pattern:
... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 47, "code_loc": 10, "docstring_loc": 20, "function_name": "select_experts", "class_name": "BaseRouter", "qualname": "BaseRouter.select_experts", "file_path": "vllm/model_executor/layers/fused_moe/router/base_router.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "runnable_... |
666ghj/BettaFish:MediaEngine/nodes/report_structure_node.py:ReportStructureNode.mutate_state | # Context:
from typing import Dict, Any, List
from loguru import logger
from ..state.state import State
class ReportStructureNode(StateMutationNode):
def __init__(self, llm_client, query: str):
"""
初始化报告结构节点
Args:
llm_client: LLM客户端
query: 用户查询
"""
... | def mutate_state(self, input_data: Any = None, state: State = None, **kwargs) -> State:
"""
将报告结构写入状态
Args:
input_data: 输入数据
state: 当前状态,如果为None则创建新状态
**kwargs: 额外参数
Returns:
更新后的状态
"""
if state is None... | function_complex | 1 | {"cognitive_complexity": 6, "loc": 37, "code_loc": 17, "docstring_loc": 11, "function_name": "mutate_state", "class_name": "ReportStructureNode", "qualname": "ReportStructureNode.mutate_state", "file_path": "MediaEngine/nodes/report_structure_node.py", "repo_id": "666ghj/BettaFish", "has_docstring": true, "runnable_lev... |
huggingface/diffusers:src/diffusers/pipelines/cosmos/pipeline_cosmos2_5_predict.py:Cosmos2_5_PredictBasePipeline.encode_prompt | # Context:
import torch
def retrieve_latents(encoder_output: torch.Tensor, generator: torch.Generator | None, sample_mode: str): ...
class Cosmos2_5_PredictBasePipeline(DiffusionPipeline):
model_cpu_offload_seq = "text_encoder->transformer->vae"
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative... | def encode_prompt(
self,
prompt: str | list[str],
negative_prompt: str | list[str] | None = None,
do_classifier_free_guidance: bool = True,
num_videos_per_prompt: int = 1,
prompt_embeds: torch.Tensor | None = None,
negative_prompt_embeds: torch.Tensor | None = Non... | function_complex | 1 | {"cognitive_complexity": 15, "loc": 82, "code_loc": 34, "docstring_loc": 26, "function_name": "encode_prompt", "class_name": "Cosmos2_5_PredictBasePipeline", "qualname": "Cosmos2_5_PredictBasePipeline.encode_prompt", "file_path": "src/diffusers/pipelines/cosmos/pipeline_cosmos2_5_predict.py", "repo_id": "huggingface/di... |
unclecode/crawl4ai:crawl4ai/script/c4ai_script.py:C4AScriptError.from_exception | # Context:
import pathlib, re, sys, textwrap
from typing import Any, Dict, List, Union
from lark.exceptions import UnexpectedToken, UnexpectedCharacters, VisitError
class Cmd: ...
class Proc: ...
class ASTBuilder(Transformer): ...
class Compiler: ...
def compile_string(script: Union[str, List[str]], root: Union[pathli... | def from_exception(cls, exc: Exception, script: Union[str, List[str]]) -> 'C4AScriptError':
"""Create C4AScriptError from another exception"""
script_text = script if isinstance(script, str) else '\n'.join(script)
script_lines = script_text.split('\n')
if isinstance(exc, Unexpec... | function_complex | 1 | {"cognitive_complexity": 43, "loc": 76, "code_loc": 53, "docstring_loc": 1, "function_name": "from_exception", "class_name": "C4AScriptError", "qualname": "C4AScriptError.from_exception", "file_path": "crawl4ai/script/c4ai_script.py", "repo_id": "unclecode/crawl4ai", "has_docstring": true, "runnable_level": "project_ru... |
Comfy-Org/ComfyUI:tests-unit/folder_paths_test/system_user_test.py:TestEdgeCases.test_triple_underscore_blocked | # Context:
from folder_paths import (
get_system_user_directory,
get_public_user_directory,
get_user_directory,
set_user_directory,
)
def mock_user_directory(): ...
class TestGetSystemUserDirectory: ...
class TestGetPublicUserDirectory: ...
class TestBackwardCompatibility: ...
class TestEdgeCases:
... | def test_triple_underscore_blocked(self):
"""Test triple underscore is blocked (starts with __)."""
assert get_public_user_directory("___system") is None | test | 1 | {"function_name": "test_triple_underscore_blocked", "class_name": "TestEdgeCases", "qualname": "TestEdgeCases.test_triple_underscore_blocked", "file_path": "tests-unit/folder_paths_test/system_user_test.py", "repo_id": "Comfy-Org/ComfyUI", "loc": 3, "tested_modules": ["folder_paths"], "has_docstring": true, "runnable_l... |
apache/airflow:airflow-core/tests/unit/api_fastapi/common/db/test_dags.py:TestGenerateDagWithLatestRunQuery.test_queued_runs_with_null_start_date_are_properly_joined | # Context:
from airflow.api_fastapi.common.db.dags import generate_dag_with_latest_run_query
from airflow.api_fastapi.common.parameters import SortParam
from airflow.models import DagModel
from airflow.models.dagrun import DagRun
class TestGenerateDagWithLatestRunQuery:
def _clear_db(): ...
def setup_teardown(... | def test_queued_runs_with_null_start_date_are_properly_joined(
self, dag_with_queued_run, dag_with_running_run, session
):
"""
Verifies that DAGs with null start_date are properly joined in the query.
If a WHERE clause filters out null start_dates, these DAGs would be excluded.
... | test | 1 | {"function_name": "test_queued_runs_with_null_start_date_are_properly_joined", "class_name": "TestGenerateDagWithLatestRunQuery", "qualname": "TestGenerateDagWithLatestRunQuery.test_queued_runs_with_null_start_date_are_properly_joined", "file_path": "airflow-core/tests/unit/api_fastapi/common/db/test_dags.py", "repo_id... |
ray-project/ray:python/ray/tests/test_open_telemetry_metric_recorder.py:test_register_histogram_metric | # Context:
from unittest.mock import MagicMock, patch
import pytest
from opentelemetry.metrics import NoOpHistogram
from ray._private.telemetry.open_telemetry_metric_recorder import (
OpenTelemetryMetricRecorder,
)
def test_register_gauge_metric(mock_get_meter, mock_set_meter_provider): ...
def test_register_count... | def test_register_histogram_metric(
mock_get_meter, mock_set_meter_provider, mock_logger_warning
):
"""
Test the register_histogram_metric method of OpenTelemetryMetricRecorder.
- Test that it registers a histogram metric with the correct name and description.
- Test that a value can be set for the ... | test | 0 | {"function_name": "test_register_histogram_metric", "class_name": null, "qualname": "test_register_histogram_metric", "file_path": "python/ray/tests/test_open_telemetry_metric_recorder.py", "repo_id": "ray-project/ray", "loc": 32, "tested_modules": ["opentelemetry.metrics", "ray._private.metrics_agent", "ray._private.t... |
crewAIInc/crewAI:lib/crewai/tests/mcp/test_amp_mcp.py:TestFetchAmpMCPConfigs.test_returns_empty_on_http_error | # Context:
from unittest.mock import AsyncMock, MagicMock, patch
def agent(): ...
def resolver(agent): ...
def mock_tool_definitions(): ...
class TestBuildMCPConfigFromDict: ...
class TestParseAmpRef: ...
class TestGetMCPToolsAmpIntegration: ...
class TestFetchAmpMCPConfigs:
def test_fetches_configs_successfully(... | def test_returns_empty_on_http_error(self, mock_get_token, mock_plus_api_class, resolver):
mock_response = MagicMock()
mock_response.status_code = 500
mock_plus_api = MagicMock()
mock_plus_api.get_mcp_configs.return_value = mock_response
mock_plus_api_class.return_value = mock_pl... | test | 0 | {"function_name": "test_returns_empty_on_http_error", "class_name": "TestFetchAmpMCPConfigs", "qualname": "TestFetchAmpMCPConfigs.test_returns_empty_on_http_error", "file_path": "lib/crewai/tests/mcp/test_amp_mcp.py", "repo_id": "crewAIInc/crewAI", "loc": 10, "tested_modules": ["crewai.agent.core", "crewai.mcp.config",... |
ray-project/ray:python/ray/serve/tests/test_gang_scheduling.py:TestGangResourceReservation.test_gang_resource_reservation | # Context:
import pytest
import ray
from ray import serve
from ray._common.test_utils import SignalActor, wait_for_condition
from ray.serve._private.test_utils import check_apps_running
from ray.serve.config import GangPlacementStrategy, GangSchedulingConfig
from ray.util.placement_group import get_current_placement_gr... | def test_gang_resource_reservation(
self,
ray_cluster,
ray_actor_options,
placement_group_bundles,
gang_placement_strategy,
expected_bundles,
expected_strategy,
expect_same_node,
):
"""Verifies the gang PG has the correct bundles, strategy, and... | test | 0 | {"function_name": "test_gang_resource_reservation", "class_name": "TestGangResourceReservation", "qualname": "TestGangResourceReservation.test_gang_resource_reservation", "file_path": "python/ray/serve/tests/test_gang_scheduling.py", "repo_id": "ray-project/ray", "loc": 77, "tested_modules": ["ray", "ray._common.test_u... |
streamlit/streamlit:lib/streamlit/web/server/starlette/starlette_server.py:UvicornServer.stop | # Context:
class RetriesExceededError(Exception): ...
def _get_server_address() -> str: ...
def _get_server_port() -> int: ...
def _is_port_manually_set() -> bool: ...
def _server_address_is_unix_socket() -> bool: ...
def _validate_ssl_config() -> tuple[str | None, str | None]: ...
def _get_websocket_settings() -> tup... | def stop(self) -> None:
"""Signal the server to stop."""
if self._server is not None:
self._server.should_exit = True | function_simple | 1 | {"cognitive_complexity": 1, "loc": 4, "code_loc": 2, "docstring_loc": 1, "function_name": "stop", "class_name": "UvicornServer", "qualname": "UvicornServer.stop", "file_path": "lib/streamlit/web/server/starlette/starlette_server.py", "repo_id": "streamlit/streamlit", "has_docstring": true, "runnable_level": "class_runn... |
sansan0/TrendRadar:trendradar/storage/local.py:LocalStorageBackend._get_configured_time | # Context:
from datetime import datetime, timedelta
from trendradar.utils.time import (
DEFAULT_TIMEZONE,
get_configured_time,
format_date_folder,
format_time_filename,
)
class LocalStorageBackend(SQLiteStorageMixin, StorageBackend):
def __init__(
self,
data_dir: str = "output",
... | def _get_configured_time(self) -> datetime:
"""获取配置时区的当前时间"""
return get_configured_time(self.timezone) | function_simple | 1 | {"cognitive_complexity": 0, "loc": 3, "code_loc": 1, "docstring_loc": 1, "function_name": "_get_configured_time", "class_name": "LocalStorageBackend", "qualname": "LocalStorageBackend._get_configured_time", "file_path": "trendradar/storage/local.py", "repo_id": "sansan0/TrendRadar", "has_docstring": true, "runnable_lev... |
run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-solr/llama_index/vector_stores/solr/client/responses.py:SolrSelectResponse:class_doc | Write a class-level docstring for `SolrSelectResponse` (inherits from BaseModel) which has methods: `from_pysolr_results`, `from_aiosolr_response`. | Solr search response.
See `Solr documentation
<https://solr.apache.org/guide/solr/latest/query-guide/response-writers.html#json-response-writer>`_
for details. | documentation | 1 | {"doc_type": "class", "class_name": "SolrSelectResponse", "file_path": "llama-index-integrations/vector_stores/llama-index-vector-stores-solr/llama_index/vector_stores/solr/client/responses.py", "repo_id": "run-llama/llama_index", "char_length": 160, "methods": ["from_pysolr_results", "from_aiosolr_response"]} |
huggingface/transformers:tests/models/vibevoice_acoustic_tokenizer/test_modeling_vibevoice_acoustic_tokenizer.py:VibeVoiceAcousticTokenizerModelTest.test_use_cache | # Context:
from transformers import (
AutoFeatureExtractor,
AutoModel,
VibeVoiceAcousticTokenizerConfig,
VibeVoiceAcousticTokenizerModel,
)
from transformers.testing_utils import cleanup, is_torch_available, require_torch, slow, torch_device
import torch
class VibeVoiceAcousticTokenizerModelTester: ...... | def test_use_cache(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs()
model = VibeVoiceAcousticTokenizerModel(config=config).to(torch_device).eval()
input_values = inputs_dict["input_values"]
with torch.no_grad():
output = model(input_values, use_cach... | test | 0 | {"function_name": "test_use_cache", "class_name": "VibeVoiceAcousticTokenizerModelTest", "qualname": "VibeVoiceAcousticTokenizerModelTest.test_use_cache", "file_path": "tests/models/vibevoice_acoustic_tokenizer/test_modeling_vibevoice_acoustic_tokenizer.py", "repo_id": "huggingface/transformers", "loc": 11, "tested_mod... |
huggingface/transformers:src/transformers/models/glm4v/modular_glm4v.py:Glm4vProcessor.__call__ | # Context:
import numpy as np
from ...feature_extraction_utils import BatchFeature
from ...image_utils import ImageInput
from ...processing_utils import Unpack
from ...tokenization_utils_base import PreTokenizedInput, TextInput
from ...video_utils import VideoInput
class Glm4vVisionConfig(PreTrainedConfig): ...
class ... | def __call__(
self,
images: ImageInput | None = None,
text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
videos: VideoInput | None = None,
**kwargs: Unpack[Glm4vProcessorKwargs],
) -> BatchFeature:
r"""
Returns:
... | function_complex | 0 | {"cognitive_complexity": 50, "loc": 120, "code_loc": 82, "docstring_loc": 13, "function_name": "__call__", "class_name": "Glm4vProcessor", "qualname": "Glm4vProcessor.__call__", "file_path": "src/transformers/models/glm4v/modular_glm4v.py", "repo_id": "huggingface/transformers", "has_docstring": true, "runnable_level":... |
ray-project/ray:python/ray/tests/unit/test_resource_and_label_spec.py:test_env_resource_overrides_with_conflict | # Context:
import json
import ray._private.ray_constants as ray_constants
from ray._private.resource_and_label_spec import ResourceAndLabelSpec
class FakeAcceleratorManager(AcceleratorManager): ...
def test_resource_and_label_spec_resolves_with_params(): ...
def test_resource_and_label_spec_resolves_auto_detect(monkey... | def test_env_resource_overrides_with_conflict(monkeypatch):
"""Validate that RESOURCES_ENVIRONMENT_VARIABLE overrides Ray Param resources."""
# Prepare environment overrides
env_resources = {
"CPU": 8,
"GPU": 4,
"TPU": 4,
}
monkeypatch.setenv(
ray_constants.RESOURCES_... | test | 0 | {"function_name": "test_env_resource_overrides_with_conflict", "class_name": null, "qualname": "test_env_resource_overrides_with_conflict", "file_path": "python/ray/tests/unit/test_resource_and_label_spec.py", "repo_id": "ray-project/ray", "loc": 29, "tested_modules": ["ray._common.constants", "ray._private.accelerator... |
vllm-project/vllm:vllm/lora/layers/logits_processor.py:LogitsProcessorWithLoRA:class_doc | Write a class-level docstring for `LogitsProcessorWithLoRA` (inherits from BaseLayerWithLoRA) which has methods: `__init__`, `logits_as_input`, `vocab_size`, `scale`, `soft_cap`. | LoRA wrapper for LogitsProcessor, with extra logic to handle the
application of the LoRA adapter and added LoRA vocabulary.
Args:
base_layer: LogitsProcessor layer
hidden_size: hidden size of the model
dtype: data type of the model
device: device of the model
sharded_to_full_mapping: index mapping ... | documentation | 1 | {"doc_type": "class", "class_name": "LogitsProcessorWithLoRA", "file_path": "vllm/lora/layers/logits_processor.py", "repo_id": "vllm-project/vllm", "char_length": 461, "methods": ["__init__", "logits_as_input", "vocab_size", "scale", "soft_cap", "use_all_gather", "org_vocab_size", "include_gpu_probs_tensor", "should_mo... |
fastapi/fastapi:tests/test_tutorial/test_python_types/test_tutorial006.py:test_process_items | # Context:
from unittest.mock import patch
from docs_src.python_types.tutorial006_py310 import process_items
# Task:
Write a Python test function `test_process_items` to verify the behavior of `process_items`.
Module under test: docs_src.python_types.tutorial006_py310 | def test_process_items():
with patch("builtins.print") as mock_print:
process_items(["item_a", "item_b", "item_c"])
assert mock_print.call_count == 3
call_args = [arg.args for arg in mock_print.call_args_list]
assert call_args == [
("item_a",),
("item_b",),
("item_c",),
... | test | 1 | {"function_name": "test_process_items", "class_name": null, "qualname": "test_process_items", "file_path": "tests/test_tutorial/test_python_types/test_tutorial006.py", "repo_id": "fastapi/fastapi", "loc": 11, "tested_modules": ["docs_src.python_types.tutorial006_py310"], "has_docstring": false, "runnable_level": "proje... |
huggingface/transformers:src/transformers/models/doge/modular_doge.py:license_header | Add a Apache-2.0 license header comment for the project 'transformers', authored by Jingze Shi and the HuggingFace Inc, year 2025. | # Copyright 2025 Jingze Shi and the HuggingFace Inc. team. All rights reserved.
#
# The Doge family of small language models is trained by SmallDoge Team.
#
# 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 | 0 | {"license_type": "Apache-2.0", "author": "Jingze Shi and the HuggingFace Inc", "year": "2025", "source": "header", "repo_id": "huggingface/transformers"} |
run-llama/llama_index:llama-index-core/tests/agent/workflow/test_thinking_delta.py:test_agent_stream_default_thinking_delta | # Context:
from llama_index.core.agent.workflow.workflow_events import AgentStream
class MockThinkingLLM(MockLLM): ...
def test_agent_stream_with_thinking_delta(): ...
def test_agent_stream_default_thinking_delta_none(): ...
def test_thinking_delta_extraction(): ...
async def test_streaming_an_agent_with_thinking_delt... | def test_agent_stream_default_thinking_delta():
"""Test AgentStream defaults thinking_delta to None."""
stream = AgentStream(
delta="Hello", response="Hello there", current_agent_name="test_agent"
)
assert stream.thinking_delta is None | test | 1 | {"function_name": "test_agent_stream_default_thinking_delta", "class_name": null, "qualname": "test_agent_stream_default_thinking_delta", "file_path": "llama-index-core/tests/agent/workflow/test_thinking_delta.py", "repo_id": "run-llama/llama_index", "loc": 7, "tested_modules": ["typing", "llama_index.core.base.llms.ty... |
ray-project/ray:python/ray/llm/_internal/common/utils/cloud_filesystem/pyarrow_filesystem.py:PyArrowFileSystem._filter_files | # Context:
import os
from typing import List, Optional, Tuple, Union
import pyarrow.fs as pa_fs
class PyArrowFileSystem(BaseCloudFileSystem):
def get_fs_and_path(object_uri: str) -> Tuple[pa_fs.FileSystem, str]: ...
def _create_azure_filesystem(object_uri: str) -> Tuple[pa_fs.FileSystem, str]: ...
def _cre... | def _filter_files(
fs: pa_fs.FileSystem,
source_path: str,
destination_path: str,
substrings_to_include: Optional[List[str]] = None,
suffixes_to_exclude: Optional[List[str]] = None,
) -> List[Tuple[str, str]]:
"""Filter files from cloud storage based on inclusion and ... | function_complex | 0 | {"cognitive_complexity": 13, "loc": 45, "code_loc": 19, "docstring_loc": 12, "function_name": "_filter_files", "class_name": "PyArrowFileSystem", "qualname": "PyArrowFileSystem._filter_files", "file_path": "python/ray/llm/_internal/common/utils/cloud_filesystem/pyarrow_filesystem.py", "repo_id": "ray-project/ray", "has... |
ray-project/ray:rllib/examples/envs/classes/multi_agent/footsies/encoder.py:FootsiesEncoder.encode | # Context:
import copy
from typing import Any, Optional, Union
import numpy as np
from ray.rllib.examples.envs.classes.multi_agent.footsies.game.proto import (
footsies_service_pb2 as footsies_pb2,
)
def one_hot_encoder(value: Union[int, float, str], collection: list[Union[int, float, str]]) -> np.ndarray: ...
cl... | def encode(
self,
game_state: footsies_pb2.GameState,
) -> dict[str, Any]:
"""Encodes the game state into observations for all agents.
:param game_state: The game state to encode
:type game_state: footsies_pb2.GameState
:return: The encoded observations for all agent... | function_simple | 0 | {"cognitive_complexity": 2, "loc": 62, "code_loc": 37, "docstring_loc": 7, "function_name": "encode", "class_name": "FootsiesEncoder", "qualname": "FootsiesEncoder.encode", "file_path": "rllib/examples/envs/classes/multi_agent/footsies/encoder.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": ... |
run-llama/llama_index:llama-index-core/tests/memory/blocks/test_vector.py:test_vector_memory_block_get | # Context:
import pytest
from llama_index.core.base.llms.types import ChatMessage
from llama_index.core.memory.memory_blocks.vector import VectorMemoryBlock
class MockVectorStore(BasePydanticVectorStore): ...
class MockNodePostprocessor(BaseNodePostprocessor): ...
def mock_embedding(): ...
def mock_vector_store(): ...... | async def test_vector_memory_block_get(vector_memory_block: VectorMemoryBlock):
"""Test getting messages from the vector memory block."""
# Create and store some messages
history_messages = [
ChatMessage(role="user", content="What's the capital of France?"),
ChatMessage(role="assistant", con... | test | 1 | {"function_name": "test_vector_memory_block_get", "class_name": null, "qualname": "test_vector_memory_block_get", "file_path": "llama-index-core/tests/memory/blocks/test_vector.py", "repo_id": "run-llama/llama_index", "loc": 21, "tested_modules": ["typing", "llama_index.core.base.llms.types", "llama_index.core.embeddin... |
ray-project/ray:python/ray/tests/test_autoscaler_azure.py:TestAzureAvailabilityZonePrecedence.test_provider_empty_string_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_empty_string_allows_auto_selection(self):
"""Test that provider-level empty string allows auto-selection."""
provider = self._create_mock_provider({"availability_zone": ""})
node_config = {"azure_arm_parameters": {"vmSize": "Standard_D2s_v3"}}
zones, source = self._ext... | test | 0 | {"function_name": "test_provider_empty_string_allows_auto_selection", "class_name": "TestAzureAvailabilityZonePrecedence", "qualname": "TestAzureAvailabilityZonePrecedence.test_provider_empty_string_allows_auto_selection", "file_path": "python/ray/tests/test_autoscaler_azure.py", "repo_id": "ray-project/ray", "loc": 9,... |
huggingface/diffusers:tests/pipelines/cosmos/test_cosmos2_5_predict.py:Cosmos2_5_PredictPipelineFastTests.test_attention_slicing_forward_pass | # Context:
import numpy as np
from ...testing_utils import enable_full_determinism, torch_device
from ..test_pipelines_common import PipelineTesterMixin, to_np
class Cosmos2_5_PredictBaseWrapper(Cosmos2_5_PredictBasePipeline): ...
class Cosmos2_5_PredictPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
p... | def test_attention_slicing_forward_pass(
self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
):
if not getattr(self, "test_attention_slicing", True):
return
components = self.get_dummy_components()
pipe = self.pipeline_class(**componen... | test | 1 | {"function_name": "test_attention_slicing_forward_pass", "class_name": "Cosmos2_5_PredictPipelineFastTests", "qualname": "Cosmos2_5_PredictPipelineFastTests.test_attention_slicing_forward_pass", "file_path": "tests/pipelines/cosmos/test_cosmos2_5_predict.py", "repo_id": "huggingface/diffusers", "loc": 34, "tested_modul... |
ray-project/ray:python/ray/data/tests/expressions/test_predicate.py:TestPredicateIntegration.test_filter_in_pipeline_with_dataset | # Context:
import pandas as pd
import ray
from ray.data._internal.util import rows_same
from ray.data.expressions import col
class TestPredicateIntegration:
def test_null_predicates_with_dataset(self, ray_start_regular_shared): ...
def test_membership_predicates_with_dataset(self, ray_start_regular_shared): ..... | def test_filter_in_pipeline_with_dataset(self, ray_start_regular_shared):
"""Test filter expressions in a data processing pipeline."""
test_data = [
{"product": "A", "quantity": 10, "price": 100, "region": "North"},
{"product": "B", "quantity": 5, "price": 200, "region": "South"}... | test | 0 | {"function_name": "test_filter_in_pipeline_with_dataset", "class_name": "TestPredicateIntegration", "qualname": "TestPredicateIntegration.test_filter_in_pipeline_with_dataset", "file_path": "python/ray/data/tests/expressions/test_predicate.py", "repo_id": "ray-project/ray", "loc": 41, "tested_modules": ["packaging.vers... |
crewAIInc/crewAI:lib/crewai-files/tests/processing/test_processor.py:TestFileProcessorPerFileMode.test_file_custom_mode | # Context:
from crewai_files import FileBytes, ImageFile
class TestFileProcessorInit: ...
class TestFileProcessorValidate: ...
class TestFileProcessorProcess: ...
class TestFileProcessorProcessFiles: ...
class TestFileHandlingEnum: ...
class TestFileProcessorPerFileMode:
def test_file_default_mode_is_auto(self): ... | def test_file_custom_mode(self):
"""Test setting custom mode on file."""
file = ImageFile(
source=FileBytes(data=MINIMAL_PNG, filename="test.png"), mode="strict"
)
assert file.mode == "strict" | test | 0 | {"function_name": "test_file_custom_mode", "class_name": "TestFileProcessorPerFileMode", "qualname": "TestFileProcessorPerFileMode.test_file_custom_mode", "file_path": "lib/crewai-files/tests/processing/test_processor.py", "repo_id": "crewAIInc/crewAI", "loc": 6, "tested_modules": ["crewai_files", "crewai_files.process... |
huggingface/transformers:tests/models/gemma3n/test_modeling_gemma3n.py:Gemma3nTextModelTest.test_generate_with_static_cache | # Context:
import copy
import pytest
from transformers import (
AutoModelForCausalLM,
AutoProcessor,
AutoTokenizer,
Gemma3nAudioConfig,
Gemma3nAudioFeatureExtractor,
Gemma3nConfig,
StaticCache,
is_torch_available,
)
from transformers.testing_utils import (
Expectations,
cleanup,
... | def test_generate_with_static_cache(self):
"""
Tests that generating with static cache give almost same results as with dynamic cache, and the output cache
has the expected shapes
"""
for model_class in self.all_generative_model_classes:
# Here, we should ideally not ... | test | 0 | {"function_name": "test_generate_with_static_cache", "class_name": "Gemma3nTextModelTest", "qualname": "Gemma3nTextModelTest.test_generate_with_static_cache", "file_path": "tests/models/gemma3n/test_modeling_gemma3n.py", "repo_id": "huggingface/transformers", "loc": 67, "tested_modules": ["datasets", "parameterized", "... |
browser-use/browser-use:browser_use/agent/variable_detector.py:_detect_in_action | # Context:
from browser_use.agent.views import AgentHistoryList, DetectedVariable
from browser_use.dom.views import DOMInteractedElement
def detect_variables_in_history(history: AgentHistoryList) -> dict[str, DetectedVariable]: ...
def _detect_variable_type(value: str, element: DOMInteractedElement | None) -> tuple[st... | def _detect_in_action(
action_dict: dict,
element: DOMInteractedElement | None,
detected: dict[str, DetectedVariable],
detected_values: set[str],
) -> None:
"""Detect variables in a single action using element context"""
# Extract action type and parameters
for action_type, params in action_dict.items():
if n... | function_complex | 0 | {"cognitive_complexity": 18, "loc": 47, "code_loc": 24, "docstring_loc": 1, "function_name": "_detect_in_action", "class_name": null, "qualname": "_detect_in_action", "file_path": "browser_use/agent/variable_detector.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_level": "project_runnable"} |
vllm-project/vllm:vllm/kernels/helion/config_manager.py:module_doc | Write a module-level docstring for the Python module `config_manager` which contains class `ConfigSet`, class `ConfigManager`. | Configuration management for Helion kernels.
This module provides centralized configuration file management for Helion custom
operations, including naming conventions, directory resolution, and file I/O.
Config File Structure
---------------------
Each kernel has a single JSON config file: {kernel_name}.json
The fil... | documentation | 1 | {"doc_type": "module", "module_name": "config_manager", "file_path": "vllm/kernels/helion/config_manager.py", "repo_id": "vllm-project/vllm", "char_length": 1022} |
exo-explore/exo:src/exo/master/tests/test_topology.py:test_add_connection | # Context:
from exo.shared.topology import Topology
from exo.shared.types.common import NodeId
from exo.shared.types.topology import Connection, SocketConnection
def topology() -> Topology: ...
def socket_connection() -> SocketConnection: ...
def test_add_node(topology: Topology): ...
def test_remove_connection_still_... | def test_add_connection(topology: Topology, socket_connection: SocketConnection):
# arrange
node_a = NodeId()
node_b = NodeId()
connection = Connection(source=node_a, sink=node_b, edge=socket_connection)
topology.add_node(node_a)
topology.add_node(node_b)
topology.add_connection(connection)... | test | 0 | {"function_name": "test_add_connection", "class_name": null, "qualname": "test_add_connection", "file_path": "src/exo/master/tests/test_topology.py", "repo_id": "exo-explore/exo", "loc": 18, "tested_modules": ["exo.shared.topology", "exo.shared.types.common", "exo.shared.types.multiaddr", "exo.shared.types.topology"], ... |
huggingface/diffusers:tests/pipelines/cosmos/test_cosmos2_text2image.py:Cosmos2TextToImagePipelineFastTests.test_inference | # Context:
import torch
class Cosmos2TextToImagePipelineWrapper(Cosmos2TextToImagePipeline): ...
class Cosmos2TextToImagePipelineFastTests(PipelineTesterMixin, unittest.TestCase):
pipeline_class = Cosmos2TextToImagePipelineWrapper
params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
batch_params = T... | def test_inference(self):
device = "cpu"
components = self.get_dummy_components()
pipe = self.pipeline_class(**components)
pipe.to(device)
pipe.set_progress_bar_config(disable=None)
inputs = self.get_dummy_inputs(device)
image = pipe(**inputs).images
gen... | test | 1 | {"function_name": "test_inference", "class_name": "Cosmos2TextToImagePipelineFastTests", "qualname": "Cosmos2TextToImagePipelineFastTests.test_inference", "file_path": "tests/pipelines/cosmos/test_cosmos2_text2image.py", "repo_id": "huggingface/diffusers", "loc": 20, "tested_modules": ["transformers", "diffusers", "tes... |
fastapi/fastapi:tests/test_tutorial/test_python_types/test_tutorial005.py:test_get_items | # Context:
from docs_src.python_types.tutorial005_py310 import get_items
# Task:
Write a Python test function `test_get_items` to verify the behavior of `get_items`.
Module under test: docs_src.python_types.tutorial005_py310 | def test_get_items():
res = get_items(
"item_a",
"item_b",
"item_c",
"item_d",
"item_e",
)
assert res == ("item_a", "item_b", "item_c", "item_d", "item_e") | test | 1 | {"function_name": "test_get_items", "class_name": null, "qualname": "test_get_items", "file_path": "tests/test_tutorial/test_python_types/test_tutorial005.py", "repo_id": "fastapi/fastapi", "loc": 9, "tested_modules": ["docs_src.python_types.tutorial005_py310"], "has_docstring": false, "runnable_level": "project_runnab... |
langflow-ai/langflow:src/backend/tests/unit/agentic/api/test_streaming_validation.py:TestValidationRetryBehavior:class_doc | Write a class-level docstring for `TestValidationRetryBehavior` which has methods: `test_retry_includes_previous_error_in_prompt`. | Tests specifically for the retry behavior with error context. | documentation | 1 | {"doc_type": "class", "class_name": "TestValidationRetryBehavior", "file_path": "src/backend/tests/unit/agentic/api/test_streaming_validation.py", "repo_id": "langflow-ai/langflow", "char_length": 61, "methods": ["test_retry_includes_previous_error_in_prompt"]} |
huggingface/transformers:src/transformers/models/maskformer/image_processing_maskformer_fast.py:MaskFormerImageProcessorFast.preprocess | # Context:
from ...image_processing_utils import BatchFeature, get_size_dict
from ...image_utils import (
IMAGENET_DEFAULT_MEAN,
IMAGENET_DEFAULT_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
)
from ...processing_utils import Unpack
from .image_processing_maskformer import (
MaskFormerI... | def preprocess(
self,
images: ImageInput,
segmentation_maps: ImageInput | None = None,
instance_id_to_semantic_id: list[dict[int, int]] | dict[int, int] | None = None,
**kwargs: Unpack[MaskFormerImageProcessorKwargs],
) -> BatchFeature:
r"""
segmentation_maps ... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 19, "code_loc": 6, "docstring_loc": 6, "function_name": "preprocess", "class_name": "MaskFormerImageProcessorFast", "qualname": "MaskFormerImageProcessorFast.preprocess", "file_path": "src/transformers/models/maskformer/image_processing_maskformer_fast.py", "repo_id": "huggingface/tra... |
ccxt/ccxt:python/ccxt/static_dependencies/bip/bech32/bch_bech32.py:BchBech32Utils:class_doc | Write a class-level docstring for `BchBech32Utils` which has methods: `PolyMod`, `HrpExpand`, `ComputeChecksum`, `VerifyChecksum`. | Class container for Bitcoin Cash utility functions. | documentation | 1 | {"doc_type": "class", "class_name": "BchBech32Utils", "file_path": "python/ccxt/static_dependencies/bip/bech32/bch_bech32.py", "repo_id": "ccxt/ccxt", "char_length": 51, "methods": ["PolyMod", "HrpExpand", "ComputeChecksum", "VerifyChecksum"]} |
huggingface/diffusers:tests/pipelines/ltx/test_ltx_latent_upsample.py:LTXLatentUpsamplePipelineFastTests.test_attention_slicing_forward_pass | # Context:
import unittest
class LTXLatentUpsamplePipelineFastTests(PipelineTesterMixin, unittest.TestCase):
pipeline_class = LTXLatentUpsamplePipeline
params = {"video", "generator"}
batch_params = {"video", "generator"}
required_optional_params = frozenset(["generator", "latents", "return_dict"])
... | def test_attention_slicing_forward_pass(
self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
):
pass | test | 1 | {"function_name": "test_attention_slicing_forward_pass", "class_name": "LTXLatentUpsamplePipelineFastTests", "qualname": "LTXLatentUpsamplePipelineFastTests.test_attention_slicing_forward_pass", "file_path": "tests/pipelines/ltx/test_ltx_latent_upsample.py", "repo_id": "huggingface/diffusers", "loc": 4, "tested_modules... |
huggingface/transformers:src/transformers/models/cohere2_vision/modular_cohere2_vision.py:get_all_supported_aspect_ratios | # Context:
from functools import lru_cache
class Cohere2VisionMultiModalProjector(nn.Module): ...
class Cohere2VisionModelOutputWithPast(AyaVisionModelOutputWithPast): ...
class Cohere2VisionCausalLMOutputWithPast(AyaVisionCausalLMOutputWithPast): ...
class Cohere2VisionPreTrainedModel(AyaVisionPreTrainedModel): ...
c... | def get_all_supported_aspect_ratios(max_image_tiles: int) -> list[tuple[int, int]]:
"""
Computes all allowed aspect ratios for a given maximum number of input tiles.
This function calculates all possible arrangements of tiles that can be formed
within the constraint of the maximum number of tiles. Each... | function_complex | 0 | {"cognitive_complexity": 6, "loc": 27, "code_loc": 6, "docstring_loc": 20, "function_name": "get_all_supported_aspect_ratios", "class_name": null, "qualname": "get_all_supported_aspect_ratios", "file_path": "src/transformers/models/cohere2_vision/modular_cohere2_vision.py", "repo_id": "huggingface/transformers", "has_d... |
huggingface/transformers:tests/trainer/test_trainer_checkpointing.py:TrainerIntegrationWithHubTester.test_push_to_hub_in_organization | # Context:
import os
import re
import tempfile
from transformers.testing_utils import (
ENDPOINT_STAGING,
TOKEN,
USER,
CaptureLogger,
TemporaryHubRepo,
TestCasePlus,
backend_device_count,
evaluate_side_effect_factory,
get_steps_per_epoch,
is_staging_test,
require_accelerate,
... | def test_push_to_hub_in_organization(self):
with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo:
with tempfile.TemporaryDirectory() as tmp_dir:
trainer = get_regression_trainer(output_dir=tmp_dir)
trainer.save_model()
output_dir... | test | 0 | {"function_name": "test_push_to_hub_in_organization", "class_name": "TrainerIntegrationWithHubTester", "qualname": "TrainerIntegrationWithHubTester.test_push_to_hub_in_organization", "file_path": "tests/trainer/test_trainer_checkpointing.py", "repo_id": "huggingface/transformers", "loc": 23, "tested_modules": ["pathlib... |
langflow-ai/langflow:src/backend/tests/unit/groq/test_groq_constants.py:TestDeprecatedModels.test_deprecated_models_marked_correctly | # Context:
from lfx.base.models.groq_constants import GROQ_MODELS_DETAILED
from lfx.base.models.groq_constants import DEPRECATED_GROQ_MODELS
from lfx.base.models.groq_constants import GROQ_MODELS_DETAILED, GROQ_PRODUCTION_MODELS
from lfx.base.models.groq_constants import DEPRECATED_GROQ_MODELS, GROQ_MODELS_DETAILED
fro... | def test_deprecated_models_marked_correctly(self):
"""Test that deprecated models have the deprecated flag."""
from lfx.base.models.groq_constants import DEPRECATED_GROQ_MODELS, GROQ_MODELS_DETAILED
for model in GROQ_MODELS_DETAILED:
if model["name"] in DEPRECATED_GROQ_MODELS:
... | test | 1 | {"function_name": "test_deprecated_models_marked_correctly", "class_name": "TestDeprecatedModels", "qualname": "TestDeprecatedModels.test_deprecated_models_marked_correctly", "file_path": "src/backend/tests/unit/groq/test_groq_constants.py", "repo_id": "langflow-ai/langflow", "loc": 7, "tested_modules": ["lfx.base.mode... |
unclecode/crawl4ai:deploy/docker/tests/test_security_fixes.py:TestURLValidation.test_file_url_blocked | # Context:
class TestHookBuiltins(unittest.TestCase): ...
class TestHooksEnabled(unittest.TestCase): ...
class TestURLValidation(unittest.TestCase):
def setUp(self): ...
def validate_url_scheme(self, url: str, allow_raw: bool) -> bool: ...
def test_file_url_blocked_windows(self): ...
def test_javascri... | def test_file_url_blocked(self):
"""file:// URLs must be blocked (LFI vulnerability)."""
self.assertFalse(self.validate_url_scheme("file:///etc/passwd"))
self.assertFalse(self.validate_url_scheme("file:///etc/passwd", allow_raw=True)) | test | 1 | {"function_name": "test_file_url_blocked", "class_name": "TestURLValidation", "qualname": "TestURLValidation.test_file_url_blocked", "file_path": "deploy/docker/tests/test_security_fixes.py", "repo_id": "unclecode/crawl4ai", "loc": 4, "tested_modules": [], "has_docstring": true, "runnable_level": "class_runnable"} |
ray-project/ray:python/ray/train/v2/tests/test_data_config.py:test_per_dataset_execution_options_default | # Context:
from ray.train import DataConfig
def test_per_dataset_execution_options_single(ray_start_4_cpus): ...
def test_per_dataset_execution_options_dict(ray_start_4_cpus): ...
# Task:
Write a Python test function `test_per_dataset_execution_options_default` to test that None or empty dict execution_options result... | def test_per_dataset_execution_options_default(ray_start_4_cpus):
"""Test that None or empty dict execution_options results in all datasets
using default options."""
# Test with None
data_config_none = DataConfig(execution_options=None)
default_options = DataConfig.default_ingest_options()
retri... | test | 0 | {"function_name": "test_per_dataset_execution_options_default", "class_name": null, "qualname": "test_per_dataset_execution_options_default", "file_path": "python/ray/train/v2/tests/test_data_config.py", "repo_id": "ray-project/ray", "loc": 19, "tested_modules": ["ray.data._internal.execution.interfaces.execution_optio... |
browser-use/browser-use:browser_use/actor/element.py:Element.hover | # Context:
class Position(TypedDict): ...
class BoundingBox(TypedDict): ...
class ElementInfo(TypedDict): ...
class Element:
def __init__(
self,
browser_session: 'BrowserSession',
backend_node_id: int,
session_id: str | None = None,
):
self._browser_session = browser_session
self._client = browser_sessi... | async def hover(self) -> None:
"""Hover over the element."""
box = await self.get_bounding_box()
if not box:
raise RuntimeError('Element is not visible or has no bounding box')
x = box['x'] + box['width'] / 2
y = box['y'] + box['height'] / 2
params: 'DispatchMouseEventParameters' = {'type': 'mouseMoved... | function_simple | 0 | {"cognitive_complexity": 1, "loc": 11, "code_loc": 7, "docstring_loc": 1, "function_name": "hover", "class_name": "Element", "qualname": "Element.hover", "file_path": "browser_use/actor/element.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_level": "class_runnable"} |
ray-project/ray:ci/ray_ci/automation/test_crane_lib.py:TestCraneIndexIntegration.test_create_multiarch_index | # Context:
import requests
from ci.ray_ci.automation.crane_lib import (
CraneError,
_crane_binary,
call_crane_copy,
call_crane_export,
call_crane_index,
call_crane_manifest,
)
class TestCraneBinary: ...
class TestCraneCopyIntegration: ...
class TestCraneManifestIntegration: ...
class TestCraneE... | def test_create_multiarch_index(self, local_registry): # noqa: F811
"""Test creating a multi-architecture index."""
port = local_registry
# Copy two different architecture images
amd64_dest = f"localhost:{port}/index-test:amd64"
arm64_dest = f"localhost:{port}/index-test:arm64"... | test | 0 | {"function_name": "test_create_multiarch_index", "class_name": "TestCraneIndexIntegration", "qualname": "TestCraneIndexIntegration.test_create_multiarch_index", "file_path": "ci/ray_ci/automation/test_crane_lib.py", "repo_id": "ray-project/ray", "loc": 23, "tested_modules": ["ci.ray_ci.automation.crane_lib", "ci.ray_ci... |
sansan0/TrendRadar:mcp_server/tools/system.py:SystemManagementTools._html_escape | Write a Python method `_html_escape` for the class `SystemManagementTools` to hTML 转义.
Parameters: text: str
Returns: str | def _html_escape(self, text: str) -> str:
"""HTML 转义"""
if not isinstance(text, str):
text = str(text)
return (
text.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace('"', """)
.replace("'", "&#... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 11, "code_loc": 9, "docstring_loc": 1, "function_name": "_html_escape", "class_name": "SystemManagementTools", "qualname": "SystemManagementTools._html_escape", "file_path": "mcp_server/tools/system.py", "repo_id": "sansan0/TrendRadar", "has_docstring": true, "runnable_level": "self_c... |
ray-project/ray:python/ray/data/tests/test_progress_manager.py:TestGetProgressManager.test_ray_tqdm_in_worker_uses_tqdm | # Context:
from unittest.mock import MagicMock, patch
from ray.data._internal.progress import get_progress_manager
from ray.data._internal.progress.tqdm_progress import (
TqdmExecutionProgressManager,
)
from ray.data.context import DataContext
class TestLoggingProgressManager: ...
class TestGetProgressManager:
... | def test_ray_tqdm_in_worker_uses_tqdm(
self, mock_isatty, mock_topology, setup_ray_worker, restore_data_context
):
"""Test that TqdmExecutionProgressManager is used when use_ray_tqdm is True in Ray worker."""
ctx = DataContext.get_current()
ctx.use_ray_tqdm = True
manager = ... | test | 0 | {"function_name": "test_ray_tqdm_in_worker_uses_tqdm", "class_name": "TestGetProgressManager", "qualname": "TestGetProgressManager.test_ray_tqdm_in_worker_uses_tqdm", "file_path": "python/ray/data/tests/test_progress_manager.py", "repo_id": "ray-project/ray", "loc": 10, "tested_modules": ["ray.data._internal.progress",... |
ray-project/ray:python/ray/tune/examples/custom_checkpointing_with_callback.py:OptimizationTrainable.setup | # Context:
def evaluation_fn(step, width, height): ...
class SmartCheckpointCallback(Callback): ...
class OptimizationTrainable(tune.Trainable):
def step(self): ...
def save_checkpoint(self, checkpoint_dir): ...
def load_checkpoint(self, checkpoint): ...
# Task:
Write a Python method `setup` for the clas... | def setup(self, config):
"""Initialize the trainable"""
self.current_step = 0
self.width = config["width"]
self.height = config["height"] | function_simple | 0 | {"cognitive_complexity": 0, "loc": 5, "code_loc": 3, "docstring_loc": 1, "function_name": "setup", "class_name": "OptimizationTrainable", "qualname": "OptimizationTrainable.setup", "file_path": "python/ray/tune/examples/custom_checkpointing_with_callback.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnab... |
google/langextract:tests/tokenizer_test.py:UnicodeTokenizerTest.test_acronym_inconsistency | # Context:
from langextract.core import tokenizer
class TokenizerTest(parameterized.TestCase): ...
class ExceptionTest(absltest.TestCase): ...
class NegativeTestCases(parameterized.TestCase): ...
class TokensTextTest(parameterized.TestCase): ...
class SentenceRangeTest(parameterized.TestCase): ...
class UnicodeTokeni... | def test_acronym_inconsistency(self):
"""Test that RegexTokenizer does NOT produce ACRONYM tokens (standardization)."""
tok = tokenizer.RegexTokenizer()
text = "A/B"
tokenized = tok.tokenize(text)
# Ensure parity with UnicodeTokenizer by splitting acronyms into constituent parts.
self.assertLen(... | test | 1 | {"function_name": "test_acronym_inconsistency", "class_name": "UnicodeTokenizerTest", "qualname": "UnicodeTokenizerTest.test_acronym_inconsistency", "file_path": "tests/tokenizer_test.py", "repo_id": "google/langextract", "loc": 12, "tested_modules": ["absl.testing", "absl.testing", "langextract.core"], "has_docstring"... |
binary-husky/gpt_academic:crazy_functions/doc_fns/conversation_doc/word_doc.py:WordFormatter.create_document | # Context:
from docx.shared import Cm, Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT, WD_LINE_SPACING
from docx.oxml.ns import qn
from datetime import datetime
def convert_markdown_to_word(markdown_text): ...
class WordFormatter:
def __init__(self):
self.doc = Document()
self._setup_documen... | def create_document(self, history):
"""写入聊天历史"""
# 添加标题
title_para = self.doc.add_paragraph(style='Title_Custom')
title_run = title_para.add_run('GPT-Academic 对话记录')
# 添加日期
date_para = self.doc.add_paragraph()
date_para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
... | function_simple | 1 | {"cognitive_complexity": 5, "loc": 33, "code_loc": 21, "docstring_loc": 1, "function_name": "create_document", "class_name": "WordFormatter", "qualname": "WordFormatter.create_document", "file_path": "crazy_functions/doc_fns/conversation_doc/word_doc.py", "repo_id": "binary-husky/gpt_academic", "has_docstring": true, "... |
vllm-project/vllm:vllm/entrypoints/openai/server_utils.py:SSEDecoder.extract_content | # Context:
class AuthenticationMiddleware: ...
class XRequestIdMiddleware: ...
def load_log_config(log_config_file: str | None) -> dict | None: ...
def get_uvicorn_log_config(args: Namespace) -> dict | None: ...
def _extract_content_from_chunk(chunk_data: dict) -> str: ...
def _log_streaming_response(response, respons... | def extract_content(self, event_data: dict) -> str:
"""Extract content from event data."""
return _extract_content_from_chunk(event_data) | function_simple | 1 | {"cognitive_complexity": 0, "loc": 3, "code_loc": 1, "docstring_loc": 1, "function_name": "extract_content", "class_name": "SSEDecoder", "qualname": "SSEDecoder.extract_content", "file_path": "vllm/entrypoints/openai/server_utils.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "runnable_level": "file_runnab... |
Comfy-Org/ComfyUI:comfy/ldm/ace/attention.py:CustomLiteLAProcessor2_0:class_doc | Write a class-level docstring for `CustomLiteLAProcessor2_0` which has methods: `__init__`, `apply_rotary_emb`, `__call__`. | Attention processor used typically in processing the SD3-like self-attention projections. add rms norm for query and key and apply RoPE | documentation | 1 | {"doc_type": "class", "class_name": "CustomLiteLAProcessor2_0", "file_path": "comfy/ldm/ace/attention.py", "repo_id": "Comfy-Org/ComfyUI", "char_length": 135, "methods": ["__init__", "apply_rotary_emb", "__call__"]} |
sansan0/TrendRadar:mcp_server/utils/validators.py:_parse_string_to_bool | Write a Python function `_parse_string_to_bool` to 将字符串解析为布尔值.
Parameters: value: str
Returns: bool | def _parse_string_to_bool(value: str) -> bool:
"""
将字符串解析为布尔值
Args:
value: 字符串值
Returns:
解析后的布尔值
"""
value = value.strip().lower()
if value in ('true', '1', 'yes', 'on'):
return True
elif value in ('false', '0', 'no', 'off', ''):
return False
else:
... | function_simple | 1 | {"cognitive_complexity": 3, "loc": 19, "code_loc": 7, "docstring_loc": 9, "function_name": "_parse_string_to_bool", "class_name": null, "qualname": "_parse_string_to_bool", "file_path": "mcp_server/utils/validators.py", "repo_id": "sansan0/TrendRadar", "has_docstring": true, "runnable_level": "self_contained"} |
666ghj/BettaFish:tests/test_report_engine_sanitization.py:ChapterSanitizationTestCase.test_table_cell_empty_blocks_repaired | # Context:
class ChapterSanitizationTestCase(unittest.TestCase):
def setUp(self): ...
def test_table_rows_scalar_values_expanded(self): ...
def test_engine_quote_validation(self): ...
def test_engine_quote_rejects_disallowed_marks_and_blocks(self): ...
def test_engine_quote_sanitization_strips_disa... | def test_table_cell_empty_blocks_repaired(self):
chapter = {
"blocks": [
{
"type": "table",
"rows": [
{
"cells": [
{"blocks": []},
... | test | 1 | {"function_name": "test_table_cell_empty_blocks_repaired", "class_name": "ChapterSanitizationTestCase", "qualname": "ChapterSanitizationTestCase.test_table_cell_empty_blocks_repaired", "file_path": "tests/test_report_engine_sanitization.py", "repo_id": "666ghj/BettaFish", "loc": 26, "tested_modules": ["ReportEngine.ir"... |
langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/scoring/eval_chain.py:ScoreStringEvalChain._prepare_output | # Context:
from langchain_classic.schema import RUN_KEY
def resolve_criteria(criteria: CRITERIA_TYPE | str | list[CRITERIA_TYPE] | None) -> dict: ...
class ScoreStringResultOutputParser(BaseOutputParser[dict]): ...
class LabeledScoreStringEvalChain(ScoreStringEvalChain): ...
class ScoreStringEvalChain(StringEvaluator... | def _prepare_output(self, result: dict) -> dict:
"""Prepare the output."""
parsed = result[self.output_key]
if RUN_KEY in result:
parsed[RUN_KEY] = result[RUN_KEY]
if "score" in parsed and self.normalize_by is not None:
parsed["score"] = parsed["score"] / self.nor... | function_simple | 1 | {"cognitive_complexity": 3, "loc": 8, "code_loc": 6, "docstring_loc": 1, "function_name": "_prepare_output", "class_name": "ScoreStringEvalChain", "qualname": "ScoreStringEvalChain._prepare_output", "file_path": "libs/langchain/langchain_classic/evaluation/scoring/eval_chain.py", "repo_id": "langchain-ai/langchain", "h... |
infiniflow/ragflow:test/testcases/test_web_api/test_memory_app/test_list_memory.py:TestMemoryList.test_filter_memory_type | # Context:
import pytest
from test_web_api.common import list_memory, get_memory_config
class TestAuthorization: ...
class TestCapability: ...
class TestMemoryList:
def test_params_unset(self, WebApiAuth): ...
def test_params_empty(self, WebApiAuth): ...
def test_page(self, WebApiAuth, params, expected_pa... | def test_filter_memory_type(self, WebApiAuth):
res = list_memory(WebApiAuth, {"memory_type": ["semantic"]})
assert res["code"] == 0, res
for memory in res["data"]["memory_list"]:
assert "semantic" in memory["memory_type"], res | test | 1 | {"function_name": "test_filter_memory_type", "class_name": "TestMemoryList", "qualname": "TestMemoryList.test_filter_memory_type", "file_path": "test/testcases/test_web_api/test_memory_app/test_list_memory.py", "repo_id": "infiniflow/ragflow", "loc": 5, "tested_modules": ["concurrent.futures", "test_web_api.common", "c... |
vnpy/vnpy:vnpy/alpha/dataset/math_function.py:quesval2 | # Context:
import polars as pl
from .utility import DataProxy
def less(feature1: DataProxy, feature2: DataProxy | float) -> DataProxy: ...
def greater(feature1: DataProxy, feature2: DataProxy | float) -> DataProxy: ...
def log(feature: DataProxy) -> DataProxy: ...
def abs(feature: DataProxy) -> DataProxy: ...
def sign... | def quesval2(threshold: DataProxy, feature1: DataProxy, feature2: DataProxy | float | int, feature3: DataProxy | float | int) -> DataProxy:
"""Return feature2 if threshold < feature1, otherwise feature3 (DataProxy threshold version)"""
df_merged: pl.DataFrame = threshold.df.join(feature1.df, on=["datetime", "vt... | function_simple | 1 | {"cognitive_complexity": 4, "loc": 22, "code_loc": 16, "docstring_loc": 1, "function_name": "quesval2", "class_name": null, "qualname": "quesval2", "file_path": "vnpy/alpha/dataset/math_function.py", "repo_id": "vnpy/vnpy", "has_docstring": true, "runnable_level": "project_runnable"} |
666ghj/BettaFish:ReportEngine/utils/test_json_parser.py:TestRobustJSONParser.test_complex_real_world_case | # Context:
def run_manual_test(): ...
class TestRobustJSONParser(unittest.TestCase):
def setUp(self): ...
def test_basic_json(self): ...
def test_markdown_wrapped(self): ...
def test_thinking_content_removal(self): ...
def test_missing_comma_fix(self): ...
def test_unbalanced_brackets(self): .... | def test_complex_real_world_case(self):
"""测试真实世界的复杂案例(类似实际错误)。"""
# 模拟实际错误:缺少逗号、有markdown包裹、有思考内容
json_str = """<thinking>我需要构造一个篇幅规划</thinking>
```json
{
"totalWords": 40000,
"tolerance": 2000,
"globalGuidelines": [
"重点突出技术红利分配失衡、人才流失与职业认同危机等结构性矛盾"
"详略策略:技术创新与传统技艺的碰撞"
"案例导向:优... | test | 1 | {"function_name": "test_complex_real_world_case", "class_name": "TestRobustJSONParser", "qualname": "TestRobustJSONParser.test_complex_real_world_case", "file_path": "ReportEngine/utils/test_json_parser.py", "repo_id": "666ghj/BettaFish", "loc": 26, "tested_modules": ["json_parser"], "has_docstring": true, "runnable_le... |
infiniflow/ragflow:common/doc_store/es_conn_base.py:ESConnectionBase.get_cluster_stats | # Context:
from common.misc_utils import convert_bytes
class ESConnectionBase(DocStoreConnection):
def __init__(self, mapping_file_name: str="mapping.json", logger_name: str='ragflow.es_conn'):
from common.doc_store.es_conn_pool import ES_CONN
self.logger = logging.getLogger(logger_name)
... | def get_cluster_stats(self):
"""
curl -XGET "http://{es_host}/_cluster/stats" -H "kbn-xsrf: reporting" to view raw stats.
"""
raw_stats = self.es.cluster.stats()
self.logger.debug(f"ESConnection.get_cluster_stats: {raw_stats}")
try:
res = {
'cl... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 48, "code_loc": 43, "docstring_loc": 3, "function_name": "get_cluster_stats", "class_name": "ESConnectionBase", "qualname": "ESConnectionBase.get_cluster_stats", "file_path": "common/doc_store/es_conn_base.py", "repo_id": "infiniflow/ragflow", "has_docstring": true, "runnable_level": ... |
crewAIInc/crewAI:lib/crewai/tests/llms/test_multimodal_integration.py:TestOpenAIResponsesFileUploadIntegration.test_describe_image_with_file_id | # Context:
import pytest
from crewai.llm import LLM
from crewai_files import (
AudioFile,
File,
ImageFile,
PDFFile,
TextFile,
VideoFile,
format_multimodal_content,
)
def test_image_bytes() -> bytes: ...
def test_text_bytes() -> bytes: ...
def test_video_bytes() -> bytes: ...
def test_audio_... | def test_describe_image_with_file_id(self, test_image_bytes: bytes) -> None:
"""Test OpenAI Responses API can describe an image uploaded via Files API."""
llm = LLM(model="openai/gpt-4o-mini", api="responses")
files = {"image": ImageFile(source=test_image_bytes)}
messages, content_block... | test | 0 | {"function_name": "test_describe_image_with_file_id", "class_name": "TestOpenAIResponsesFileUploadIntegration", "qualname": "TestOpenAIResponsesFileUploadIntegration.test_describe_image_with_file_id", "file_path": "lib/crewai/tests/llms/test_multimodal_integration.py", "repo_id": "crewAIInc/crewAI", "loc": 25, "tested_... |
apache/airflow:providers/standard/tests/unit/standard/operators/test_hitl.py:TestHITLOperator.test_validate_defaults_with_invalid_defaults | # Context:
import pytest
from typing import TYPE_CHECKING, Any
from airflow.providers.standard.operators.hitl import (
ApprovalOperator,
HITLBranchOperator,
HITLEntryOperator,
HITLOperator,
)
from airflow.sdk.definitions.param import ParamsDict
def hitl_task_and_ti_for_generating_link(dag_maker: DagMak... | def test_validate_defaults_with_invalid_defaults(
self,
extra_kwargs: dict[str, Any],
expected_error_msg: str,
) -> None:
# validate_default is called during initialization
with pytest.raises(ValueError, match=expected_error_msg):
HITLOperator(
tas... | test | 1 | {"function_name": "test_validate_defaults_with_invalid_defaults", "class_name": "TestHITLOperator", "qualname": "TestHITLOperator.test_validate_defaults_with_invalid_defaults", "file_path": "providers/standard/tests/unit/standard/operators/test_hitl.py", "repo_id": "apache/airflow", "loc": 15, "tested_modules": ["__fut... |
langflow-ai/langflow:src/lfx/src/lfx/cli/common.py:extract_script_dependencies | # Context:
from pathlib import Path
def create_verbose_printer(verbose: bool): ...
def is_port_in_use(port: int, host: str) -> bool: ...
def get_free_port(starting_port: int) -> int: ...
def get_best_access_host(host: str) -> str: ...
def get_api_key() -> str: ...
def is_url(path_or_url: str) -> bool: ...
def download... | def extract_script_dependencies(script_path: Path, verbose_print) -> list[str]:
"""Return dependency strings declared via PEP-723 inline metadata.
Only `.py` files are supported for now. Returns an empty list if the file has
no metadata block or could not be parsed.
"""
if script_path.suffix != ".p... | function_simple | 1 | {"cognitive_complexity": 3, "loc": 18, "code_loc": 9, "docstring_loc": 5, "function_name": "extract_script_dependencies", "class_name": null, "qualname": "extract_script_dependencies", "file_path": "src/lfx/src/lfx/cli/common.py", "repo_id": "langflow-ai/langflow", "has_docstring": true, "runnable_level": "file_runnabl... |
langflow-ai/langflow:src/backend/tests/unit/components/llm_operations/test_guardrails_component.py:TestGuardrailsComponent.test_extract_text_from_message_object | # Context:
from unittest.mock import MagicMock, patch
from lfx.components.llm_operations.guardrails import GuardrailsComponent
class TestGuardrailsComponent(ComponentTestBaseWithoutClient):
def component_class(self): ...
def default_kwargs(self): ...
def file_names_mapping(self): ...
def mock_llm(self)... | def test_extract_text_from_message_object(self):
"""Test text extraction from Message-like object."""
component = GuardrailsComponent()
mock_message = MagicMock()
mock_message.text = "Message content"
result = component._extract_text(mock_message)
assert result == "Messag... | test | 1 | {"function_name": "test_extract_text_from_message_object", "class_name": "TestGuardrailsComponent", "qualname": "TestGuardrailsComponent.test_extract_text_from_message_object", "file_path": "src/backend/tests/unit/components/llm_operations/test_guardrails_component.py", "repo_id": "langflow-ai/langflow", "loc": 7, "tes... |
huggingface/transformers:tests/models/colqwen2/test_processing_colqwen2.py:ColQwen2ProcessorTest.test_process_images | # Context:
import torch
class ColQwen2ProcessorTest(ProcessorTesterMixin, unittest.TestCase):
processor_class = ColQwen2Processor
model_id = "vidore/colqwen2-v1.0-hf"
def test_apply_chat_template_image(self, batch_size, return_tensors): ...
def test_processor_with_multiple_inputs(self): ...
def tes... | def test_process_images(self):
# Processor configuration
image_input = self.prepare_image_inputs()
image_processor = self.get_component("image_processor")
tokenizer = self.get_component("tokenizer", max_length=112, padding="max_length")
image_processor.image_seq_length = 14
... | test | 0 | {"function_name": "test_process_images", "class_name": "ColQwen2ProcessorTest", "qualname": "ColQwen2ProcessorTest.test_process_images", "file_path": "tests/models/colqwen2/test_processing_colqwen2.py", "repo_id": "huggingface/transformers", "loc": 19, "tested_modules": ["parameterized", "transformers.models.colqwen2.p... |
vllm-project/vllm:vllm/model_executor/models/parakeet.py:module_doc | Write a module-level docstring for the Python module `parakeet` which contains class `ParakeetProjection`, class `ProjectedParakeet`, class `ParakeetExtractor`. | Modules below used for the audio encoder component in: models/nano_nemotron_vl.py | documentation | 1 | {"doc_type": "module", "module_name": "parakeet", "file_path": "vllm/model_executor/models/parakeet.py", "repo_id": "vllm-project/vllm", "char_length": 81} |
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/rag/types.py:AddDocumentParams:class_doc | Write a class-level docstring for `AddDocumentParams` (inherits from TypedDict) which has methods: various methods. | Parameters for adding documents to the RAG system. | documentation | 0 | {"doc_type": "class", "class_name": "AddDocumentParams", "file_path": "lib/crewai-tools/src/crewai_tools/tools/rag/types.py", "repo_id": "crewAIInc/crewAI", "char_length": 50, "methods": []} |
binary-husky/gpt_academic:shared_utils/fastapi_stream_server.py:MasterMindWebSocketServer:class_doc | Write a class-level docstring for `MasterMindWebSocketServer` (inherits from PythonMethod_AsyncConnectionMaintainer_AgentcraftInterface) which has methods: `__init__`, `create_event`, `terminate_event`, `long_task_01_wait_incoming_connection`. | WebSocket服务器主类
继承自异步连接维护器接口,实现了完整的WebSocket服务器功能。
负责处理客户端连接、事件管理和消息路由。 | documentation | 1 | {"doc_type": "class", "class_name": "MasterMindWebSocketServer", "file_path": "shared_utils/fastapi_stream_server.py", "repo_id": "binary-husky/gpt_academic", "char_length": 71, "methods": ["__init__", "create_event", "terminate_event", "long_task_01_wait_incoming_connection"]} |
huggingface/transformers:src/transformers/generation/continuous_batching/continuous_api.py:ContinuousMixin.generate_batch | # Context:
import torch
from tqdm import tqdm
from tqdm.contrib.logging import logging_redirect_tqdm
from ...generation.configuration_utils import CompileConfig, GenerationConfig
from ...utils.logging import logging
from .requests import GenerationOutput, RequestState, RequestStatus, logger
class ProtoPretrainedModel(... | def generate_batch(
self,
inputs: list[list[int]],
generation_config: GenerationConfig | None = None,
q_padding_interval_size: int = 0,
kv_padding_interval_size: int = 0,
allow_block_sharing: bool = True,
record_timestamps: bool = False,
progress_bar: bool... | function_complex | 0 | {"cognitive_complexity": 26, "loc": 92, "code_loc": 54, "docstring_loc": 17, "function_name": "generate_batch", "class_name": "ContinuousMixin", "qualname": "ContinuousMixin.generate_batch", "file_path": "src/transformers/generation/continuous_batching/continuous_api.py", "repo_id": "huggingface/transformers", "has_doc... |
huggingface/transformers:src/transformers/models/dia/feature_extraction_dia.py:DiaFeatureExtractor.__call__ | # Context:
import numpy as np
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging
class DiaFeatureExtractor(SequenceFeatureExtractor):
model_input_names = ["input_values", "n_quantizers"]
def __init__(
self,
feature_size: int = 1,
... | def __call__(
self,
raw_audio: np.ndarray | list[float] | list[np.ndarray] | list[list[float]],
padding: bool | str | PaddingStrategy | None = None,
truncation: bool | None = False,
max_length: int | None = None,
return_tensors: str | TensorType | None = None,
sam... | function_complex | 0 | {"cognitive_complexity": 31, "loc": 120, "code_loc": 59, "docstring_loc": 32, "function_name": "__call__", "class_name": "DiaFeatureExtractor", "qualname": "DiaFeatureExtractor.__call__", "file_path": "src/transformers/models/dia/feature_extraction_dia.py", "repo_id": "huggingface/transformers", "has_docstring": true, ... |
ray-project/ray:ci/fossa/test_ray_oss_analysis.py:test_is_own_code | # Context:
from unittest.mock import mock_open, patch
from ci.fossa import ray_oss_analysis
def reset_logger(): ...
def test_setup_logger(mock_file_handler) -> None: ...
def test_is_excluded_kind() -> None: ...
def test_is_build_tool() -> None: ...
def test_is_cpp_code() -> None: ...
def test_get_dependency_info() -> ... | def test_is_own_code(mock_getcwd) -> None:
mock_getcwd.return_value = "/repo/root"
assert ray_oss_analysis._is_own_code("/repo/root/file.py")
assert not ray_oss_analysis._is_own_code("/other/root/file.py")
assert not ray_oss_analysis._is_own_code(None) | test | 0 | {"function_name": "test_is_own_code", "class_name": null, "qualname": "test_is_own_code", "file_path": "ci/fossa/test_ray_oss_analysis.py", "repo_id": "ray-project/ray", "loc": 5, "tested_modules": ["ci.fossa"], "has_docstring": false, "runnable_level": "project_runnable"} |
crewAIInc/crewAI:lib/crewai-files/src/crewai_files/cache/cleanup.py:delete_one | # Context:
from crewai_files.cache.upload_cache import CachedUpload, UploadCache
from crewai_files.uploaders.base import FileUploader
def _safe_delete(uploader: FileUploader, file_id: str, provider: str) -> bool: ...
def cleanup_uploaded_files(cache: UploadCache, delete_from_provider: bool, providers: list[ProviderTyp... | async def delete_one(file_uploader: FileUploader, cached: CachedUpload) -> bool:
"""Delete a single file with semaphore limiting."""
async with semaphore:
return await _asafe_delete(
file_uploader, cached.file_id, cached.provider
) | function_simple | 0 | {"cognitive_complexity": 0, "loc": 6, "code_loc": 4, "docstring_loc": 1, "function_name": "delete_one", "class_name": null, "qualname": "delete_one", "file_path": "lib/crewai-files/src/crewai_files/cache/cleanup.py", "repo_id": "crewAIInc/crewAI", "has_docstring": true, "runnable_level": "project_runnable"} |
huggingface/transformers:tests/quantization/mxfp4/test_mxfp4.py:Mxfp4IntegrationTest.test_should_convert_module | # Context:
from transformers.quantizers.quantizers_utils import should_convert_module
def _empty_accelerator_cache(): ...
def _patch_no_accelerator(): ...
class Mxfp4ConfigTest(unittest.TestCase): ...
class Mxfp4QuantizerTest(unittest.TestCase): ...
class Mxfp4ModelTest(unittest.TestCase): ...
class Mxfp4IntegrationT... | def test_should_convert_module(self):
"""Test module conversion decision logic"""
from transformers.quantizers.quantizers_utils import should_convert_module
# Should convert by default
self.assertTrue(should_convert_module("model", None))
self.assertTrue(should_convert_module("m... | test | 0 | {"function_name": "test_should_convert_module", "class_name": "Mxfp4IntegrationTest", "qualname": "Mxfp4IntegrationTest.test_should_convert_module", "file_path": "tests/quantization/mxfp4/test_mxfp4.py", "repo_id": "huggingface/transformers", "loc": 12, "tested_modules": ["contextlib", "transformers", "transformers.tes... |
crewAIInc/crewAI:lib/crewai-files/src/crewai_files/cache/upload_cache.py:_cleanup_on_exit | # Context:
from crewai_files.cache.cleanup import cleanup_uploaded_files
class CachedUpload: ...
def _make_key(file_hash: str, provider: str) -> str: ...
def _compute_file_hash_streaming(chunks: Iterator[bytes]) -> str: ...
def _compute_file_hash(file: FileInput) -> str: ...
class UploadCache: ...
def get_upload_cache... | def _cleanup_on_exit() -> None:
"""Clean up uploaded files on process exit."""
global _default_cache
if _default_cache is None or len(_default_cache) == 0:
return
from crewai_files.cache.cleanup import cleanup_uploaded_files
try:
cleanup_uploaded_files(_default_cache)
except Ex... | function_simple | 0 | {"cognitive_complexity": 3, "loc": 12, "code_loc": 8, "docstring_loc": 1, "function_name": "_cleanup_on_exit", "class_name": null, "qualname": "_cleanup_on_exit", "file_path": "lib/crewai-files/src/crewai_files/cache/upload_cache.py", "repo_id": "crewAIInc/crewAI", "has_docstring": true, "runnable_level": "project_runn... |
unclecode/crawl4ai:docs/examples/adaptive_crawling/custom_strategies.py:APIDocumentationStrategy:class_doc | Write a class-level docstring for `APIDocumentationStrategy` which has methods: `__init__`, `score_link`, `calculate_api_coverage`. | Custom strategy optimized for API documentation crawling.
Prioritizes endpoint references, code examples, and parameter descriptions. | documentation | 1 | {"doc_type": "class", "class_name": "APIDocumentationStrategy", "file_path": "docs/examples/adaptive_crawling/custom_strategies.py", "repo_id": "unclecode/crawl4ai", "char_length": 133, "methods": ["__init__", "score_link", "calculate_api_coverage"]} |
666ghj/BettaFish:ReportEngine/renderers/html_renderer.py:HTMLRenderer._transpose_single_cell_table | # Context:
import copy
from typing import Any, Dict, List
class HTMLRenderer:
CALLOUT_ALLOWED_TYPES = {
INLINE_ARTIFACT_KEYS = {
TABLE_COMPLEX_CHARS = set(
def __init__(self, config: Dict[str, Any] | None = None):
"""
初始化渲染器缓存并允许注入额外配置。
参数层级说明:
- config: dict | None,供调用... | def _transpose_single_cell_table(self, rows: List[Dict[str, Any]], span: int) -> List[Dict[str, Any]]:
"""将单列多行的表格转换为标准表头 + 若干数据行"""
total = len(rows)
if total <= span or (total - span) % span != 0:
return []
header_rows = rows[:span]
data_rows = rows[span:]
n... | function_complex | 1 | {"cognitive_complexity": 6, "loc": 27, "code_loc": 25, "docstring_loc": 1, "function_name": "_transpose_single_cell_table", "class_name": "HTMLRenderer", "qualname": "HTMLRenderer._transpose_single_cell_table", "file_path": "ReportEngine/renderers/html_renderer.py", "repo_id": "666ghj/BettaFish", "has_docstring": true,... |
fastapi/fastapi:tests/test_tutorial/test_body/test_tutorial002.py:test_post_with_tax | # Context:
import pytest
from fastapi.testclient import TestClient
def get_client(request: pytest.FixtureRequest): ...
def test_post_without_tax(client: TestClient, price: str | float): ...
def test_post_with_no_data(client: TestClient): ...
def test_openapi_schema(client: TestClient): ...
# Task:
Write a Python test... | def test_post_with_tax(client: TestClient, price: str | float):
response = client.post(
"/items/",
json={"name": "Foo", "price": price, "description": "Some Foo", "tax": 0.3},
)
assert response.status_code == 200
assert response.json() == {
"name": "Foo",
"price": 50.5,
... | test | 1 | {"function_name": "test_post_with_tax", "class_name": null, "qualname": "test_post_with_tax", "file_path": "tests/test_tutorial/test_body/test_tutorial002.py", "repo_id": "fastapi/fastapi", "loc": 13, "tested_modules": ["fastapi.testclient", "inline_snapshot", "utils"], "has_docstring": false, "runnable_level": "projec... |
huggingface/transformers:src/transformers/models/t5gemma2/modular_t5gemma2.py:sliding_window_mask_function | # Context:
from collections.abc import Callable
class T5Gemma2TextConfig(Gemma3TextConfig, PreTrainedConfig): ...
class T5Gemma2EncoderConfig(Gemma3Config): ...
class T5Gemma2DecoderConfig(Gemma3TextConfig, PreTrainedConfig): ...
class T5Gemma2Config(PreTrainedConfig): ...
class T5Gemma2RMSNorm(Gemma3RMSNorm): ...
cla... | def sliding_window_mask_function(sliding_window: int, is_causal=True) -> Callable:
"""
This creates uni/bidirectional attention mask with sliding window.
"""
def inner_mask(batch_idx: int, head_idx: int, q_idx: int, kv_idx: int) -> bool:
if is_causal:
left_window_size, right_window_... | function_simple | 0 | {"cognitive_complexity": 3, "loc": 17, "code_loc": 10, "docstring_loc": 3, "function_name": "sliding_window_mask_function", "class_name": null, "qualname": "sliding_window_mask_function", "file_path": "src/transformers/models/t5gemma2/modular_t5gemma2.py", "repo_id": "huggingface/transformers", "has_docstring": true, "... |
ray-project/ray:python/ray/data/tests/expressions/test_namespace_string.py:TestStringTransform.test_reverse | # Context:
import pandas as pd
from ray.data._internal.util import rows_same
from ray.data.expressions import col
def _create_dataset(items_data, dataset_format, arrow_table): ...
class TestStringLength: ...
class TestStringCase: ...
class TestStringPredicates: ...
class TestStringTrimming: ...
class TestStringPadding... | def test_reverse(self, ray_start_regular_shared, dataset_format):
"""Test str.reverse() reverses strings."""
data = [{"val": "hello"}, {"val": "world"}]
ds = _create_dataset(data, dataset_format)
result = ds.with_column("rev", col("val").str.reverse()).to_pandas()
expected = pd.D... | test | 0 | {"function_name": "test_reverse", "class_name": "TestStringTransform", "qualname": "TestStringTransform.test_reverse", "file_path": "python/ray/data/tests/expressions/test_namespace_string.py", "repo_id": "ray-project/ray", "loc": 7, "tested_modules": ["packaging", "ray.data._internal.util", "ray.data.expressions", "ra... |
ray-project/ray:python/ray/serve/_private/rolling_window_accumulator.py:RollingWindowAccumulator:class_doc | Write a class-level docstring for `RollingWindowAccumulator` which has methods: `__init__`, `window_duration_s`, `num_buckets`, `bucket_duration_s`, `_ensure_initialized`. | Tracks cumulative values over a rolling time window.
Uses bucketing for memory efficiency - divides the window into N buckets
and rotates them as time passes. This allows efficient tracking of values
over a sliding window without storing individual data points.
Uses thread-local storage for lock-free writes on the ho... | documentation | 0 | {"doc_type": "class", "class_name": "RollingWindowAccumulator", "file_path": "python/ray/serve/_private/rolling_window_accumulator.py", "repo_id": "ray-project/ray", "char_length": 981, "methods": ["__init__", "window_duration_s", "num_buckets", "bucket_duration_s", "_ensure_initialized", "_rotate_buckets_if_needed", "... |
crewAIInc/crewAI:lib/crewai-tools/tests/rag/test_text_loaders.py:TestTextLoader.test_whitespace_text | # Context:
from crewai_tools.rag.loaders.text_loader import TextFileLoader, TextLoader
from crewai_tools.rag.source_content import SourceContent
def write_temp_file(content, suffix, encoding): ...
def cleanup_temp_file(path): ...
class TestTextFileLoader: ...
class TestTextLoadersIntegration: ...
class TestTextLoader... | def test_whitespace_text(self):
content = " \n\t "
result = TextLoader().load(SourceContent(content))
assert result.content == content | test | 0 | {"function_name": "test_whitespace_text", "class_name": "TestTextLoader", "qualname": "TestTextLoader.test_whitespace_text", "file_path": "lib/crewai-tools/tests/rag/test_text_loaders.py", "repo_id": "crewAIInc/crewAI", "loc": 4, "tested_modules": ["crewai_tools.rag.base_loader", "crewai_tools.rag.loaders.text_loader",... |
vllm-project/vllm:vllm/reasoning/basic_parsers.py:BaseThinkingReasoningParser.extract_reasoning_streaming | # Context:
from collections.abc import Iterable, Sequence
from vllm.entrypoints.openai.engine.protocol import DeltaMessage
class BaseThinkingReasoningParser(ReasoningParser):
def start_token(self) -> str: ...
def end_token(self) -> str: ...
def __init__(self, tokenizer: TokenizerLike, *args, **kwargs):
... | def extract_reasoning_streaming(
self,
previous_text: str,
current_text: str,
delta_text: str,
previous_token_ids: Sequence[int],
current_token_ids: Sequence[int],
delta_token_ids: Sequence[int],
) -> DeltaMessage | None:
"""
Extract reasoning ... | function_complex | 1 | {"cognitive_complexity": 12, "loc": 58, "code_loc": 29, "docstring_loc": 5, "function_name": "extract_reasoning_streaming", "class_name": "BaseThinkingReasoningParser", "qualname": "BaseThinkingReasoningParser.extract_reasoning_streaming", "file_path": "vllm/reasoning/basic_parsers.py", "repo_id": "vllm-project/vllm", ... |
ray-project/ray:python/ray/data/tests/unit/test_transform_pyarrow.py:test_align_struct_fields_empty_blocks | # Context:
from ray.data._internal.arrow_ops.transform_pyarrow import (
MIN_PYARROW_VERSION_TYPE_PROMOTION,
_align_struct_fields,
concat,
hash_partition,
shuffle,
try_combine_chunked_columns,
unify_schemas,
)
def test_try_defragment_table(): ...
def test_hash_partitioning(): ...
def test_sh... | def test_align_struct_fields_empty_blocks(empty_block_blocks, empty_block_schema):
"""Test alignment with empty blocks."""
t1, t2 = empty_block_blocks
aligned_blocks = _align_struct_fields([t1, t2], empty_block_schema)
assert len(aligned_blocks) == 2
# Check empty block
result1 = aligned_bloc... | test | 0 | {"function_name": "test_align_struct_fields_empty_blocks", "class_name": null, "qualname": "test_align_struct_fields_empty_blocks", "file_path": "python/ray/data/tests/unit/test_transform_pyarrow.py", "repo_id": "ray-project/ray", "loc": 20, "tested_modules": ["typing", "ray.data._internal.arrow_ops.transform_pyarrow",... |
run-llama/llama_index:llama-index-integrations/llms/llama-index-llms-cloudflare-ai-gateway/llama_index/llms/cloudflare_ai_gateway/base.py:CloudflareAIGateway._get_aclient | # Context:
import httpx
class CloudflareAIGatewayError(Exception): ...
class CloudflareAIGatewayUnauthorizedError(CloudflareAIGatewayError): ...
class CloudflareAIGatewayDoesNotExistError(CloudflareAIGatewayError): ...
class CloudflareAIGatewayOptions(BaseModel): ...
class AIGatewayClientWrapper: ...
class Cloudflare... | def _get_aclient(self) -> httpx.AsyncClient:
"""Get async HTTP client."""
if self._aclient is None:
self._aclient = httpx.AsyncClient(
timeout=self.timeout,
headers=self.default_headers,
)
return self._aclient | function_simple | 1 | {"cognitive_complexity": 1, "loc": 8, "code_loc": 6, "docstring_loc": 1, "function_name": "_get_aclient", "class_name": "CloudflareAIGateway", "qualname": "CloudflareAIGateway._get_aclient", "file_path": "llama-index-integrations/llms/llama-index-llms-cloudflare-ai-gateway/llama_index/llms/cloudflare_ai_gateway/base.py... |
huggingface/transformers:tests/models/kosmos2_5/test_processor_kosmos2_5.py:Kosmos2_5ProcessorTest.test_full_processor | # Context:
import os
import numpy as np
from transformers.image_utils import load_image
from ...test_processing_common import ProcessorTesterMixin, url_to_local_path
from PIL import Image
from transformers import (
AutoProcessor,
AutoTokenizer,
Kosmos2_5ImageProcessor,
Kosmos2_5Processor... | def test_full_processor(self):
url = url_to_local_path("https://huggingface.co/microsoft/kosmos-2.5/resolve/main/receipt_00008.png")
processor = AutoProcessor.from_pretrained("microsoft/kosmos-2.5")
texts = ["<md>", "<ocr>"]
expected_input_ids = [
[100288],
[10028... | test | 0 | {"function_name": "test_full_processor", "class_name": "Kosmos2_5ProcessorTest", "qualname": "Kosmos2_5ProcessorTest.test_full_processor", "file_path": "tests/models/kosmos2_5/test_processor_kosmos2_5.py", "repo_id": "huggingface/transformers", "loc": 91, "tested_modules": ["tempfile", "transformers.image_utils", "tran... |
ray-project/ray:python/ray/data/tests/unit/test_fifo_bundle_queue.py:test_fifo_queue_iter | # Context:
from ray.data._internal.execution.bundle_queue import FIFOBundleQueue
def _create_bundle(data: Any) -> RefBundle: ...
def test_fifo_queue_add_and_length(): ...
def test_fifo_queue_get_next_fifo_order(): ...
def test_fifo_queue_init_with_bundles(): ...
def test_fifo_queue_peek_next(): ...
def test_fifo_queue... | def test_fifo_queue_iter():
"""Test iterating over the queue."""
queue = FIFOBundleQueue()
bundle1 = _create_bundle("data1")
bundle2 = _create_bundle("data11")
bundle3 = _create_bundle("data111")
queue.add(bundle1)
queue.add(bundle2)
queue.add(bundle3)
# Iterate without consuming
... | test | 0 | {"function_name": "test_fifo_queue_iter", "class_name": null, "qualname": "test_fifo_queue_iter", "file_path": "python/ray/data/tests/unit/test_fifo_bundle_queue.py", "repo_id": "ray-project/ray", "loc": 15, "tested_modules": ["typing", "uuid", "ray.data._internal.execution.bundle_queue", "ray.data._internal.execution.... |
langflow-ai/langflow:src/backend/tests/unit/groq/test_groq_integration.py:TestGroqModelBackwardCompatibility.test_model_name_input_has_default_options | # Context:
from lfx.base.models.groq_constants import GROQ_MODELS
class TestGroqModelIntegration: ...
class TestGroqModelEdgeCases: ...
class TestGroqModelBackwardCompatibility:
def groq_model_instance(self): ...
def test_groq_models_constant_available(self): ...
def test_fallback_to_groq_models_on_error(... | def test_model_name_input_has_default_options(self, groq_model_instance):
"""Test that model_name input has default options from GROQ_MODELS."""
from lfx.base.models.groq_constants import GROQ_MODELS
model_name_input = next(inp for inp in groq_model_instance.inputs if inp.name == "model_name")
... | test | 1 | {"function_name": "test_model_name_input_has_default_options", "class_name": "TestGroqModelBackwardCompatibility", "qualname": "TestGroqModelBackwardCompatibility.test_model_name_input_has_default_options", "file_path": "src/backend/tests/unit/groq/test_groq_integration.py", "repo_id": "langflow-ai/langflow", "loc": 8,... |
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/routers/podcast_router.py:get_podcast | # Context:
from fastapi import APIRouter, HTTPException, File, UploadFile, Body, Query, Path
from models.podcast_schemas import Podcast, PodcastDetail, PodcastCreate, PodcastUpdate, PaginatedPodcasts
from services.podcast_service import podcast_service
async def get_podcasts(page: int, per_page: int, search: Optional[... | async def get_podcast(podcast_id: int = Path(..., description="The ID of the podcast to retrieve")):
"""
Get detailed information about a specific podcast.
Parameters:
- **podcast_id**: The ID of the podcast to retrieve
Returns the podcast metadata and content.
"""
podcast = await podcast_... | function_simple | 0 | {"cognitive_complexity": 2, "loc": 19, "code_loc": 10, "docstring_loc": 8, "function_name": "get_podcast", "class_name": null, "qualname": "get_podcast", "file_path": "advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/routers/podcast_router.py", "repo_id": "Shubhamsaboo/awesome-llm-apps", "has_docs... |
ocrmypdf/OCRmyPDF:src/ocrmypdf/_validation_coordinator.py:ValidationCoordinator._validate_plugin_contexts | # Context:
from ocrmypdf._options import OcrOptions
class ValidationCoordinator:
def __init__(self, plugin_manager: pluggy.PluginManager):
self.plugin_manager = plugin_manager
self.registry = getattr(plugin_manager, '_option_registry', None)
def validate_all_options(self, options: OcrOptions) -... | def _validate_plugin_contexts(self, options: OcrOptions) -> None:
"""Validate plugin options that require external context."""
# For now, we'll run the plugin validation directly since the models
# are still being integrated. This ensures the validation warnings
# and checks still work a... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 11, "code_loc": 2, "docstring_loc": 1, "function_name": "_validate_plugin_contexts", "class_name": "ValidationCoordinator", "qualname": "ValidationCoordinator._validate_plugin_contexts", "file_path": "src/ocrmypdf/_validation_coordinator.py", "repo_id": "ocrmypdf/OCRmyPDF", "has_docst... |
google/langextract:langextract/providers/patterns.py:module_doc | Write a module-level docstring for the Python module `patterns` which contains various utilities. | Centralized pattern definitions for built-in providers.
This module defines all patterns and priorities for built-in providers
in one place to avoid duplication. | documentation | 1 | {"doc_type": "module", "module_name": "patterns", "file_path": "langextract/providers/patterns.py", "repo_id": "google/langextract", "char_length": 162} |
ray-project/ray:python/ray/serve/tests/test_task_processor.py:TestTaskConsumerWithRayServe.test_task_consumer_persistence_across_restarts | # Context:
import ray
from ray import serve
from ray._common.test_utils import SignalActor, wait_for_condition
from ray.serve.task_consumer import (
instantiate_adapter_from_config,
task_consumer,
task_handler,
)
class ProcessedTasksTracker: ...
def send_request_to_queue(processor_config: TaskProcessorConf... | def test_task_consumer_persistence_across_restarts(
self, temp_queue_directory, serve_instance, create_processor_config
):
"""Test that tasks persist in queue and get executed after deployment restart."""
# Setup
config = create_processor_config()
tracker = ProcessedTasksTrac... | test | 0 | {"function_name": "test_task_consumer_persistence_across_restarts", "class_name": "TestTaskConsumerWithRayServe", "qualname": "TestTaskConsumerWithRayServe.test_task_consumer_persistence_across_restarts", "file_path": "python/ray/serve/tests/test_task_processor.py", "repo_id": "ray-project/ray", "loc": 77, "tested_modu... |
huggingface/transformers:tests/quantization/mxfp4/test_mxfp4.py:Mxfp4ConfigTest.test_config_with_modules_to_not_convert | # Context:
from transformers import AutoTokenizer, GptOssForCausalLM, Mxfp4Config
def _empty_accelerator_cache(): ...
def _patch_no_accelerator(): ...
class Mxfp4QuantizerTest(unittest.TestCase): ...
class Mxfp4IntegrationTest(unittest.TestCase): ...
class Mxfp4ModelTest(unittest.TestCase): ...
class Mxfp4ConfigTest(... | def test_config_with_modules_to_not_convert(self):
"""Test configuration with modules to not convert"""
modules = ["model.layers.*.self_attn", "lm_head"]
config = Mxfp4Config(modules_to_not_convert=modules)
self.assertEqual(config.modules_to_not_convert, modules) | test | 0 | {"function_name": "test_config_with_modules_to_not_convert", "class_name": "Mxfp4ConfigTest", "qualname": "Mxfp4ConfigTest.test_config_with_modules_to_not_convert", "file_path": "tests/quantization/mxfp4/test_mxfp4.py", "repo_id": "huggingface/transformers", "loc": 5, "tested_modules": ["contextlib", "transformers", "t... |
harry0703/MoneyPrinterTurbo:test/services/test_task.py:TestTaskService.test_task_local_materials | # Context:
import os
from app.services import task as tm
from app.models.schema import MaterialInfo, VideoParams
class TestTaskService(unittest.TestCase):
def setUp(self): ...
def tearDown(self): ...
# Task:
Write a Python test method `test_task_local_materials` in test class `TestTaskService` to verify the b... | def test_task_local_materials(self):
task_id = "00000000-0000-0000-0000-000000000000"
video_materials=[]
for i in range(1, 4):
video_materials.append(MaterialInfo(
provider="local",
url=os.path.join(resources_dir, f"{i}.png"),
duration=... | test | 0 | {"function_name": "test_task_local_materials", "class_name": "TestTaskService", "qualname": "TestTaskService.test_task_local_materials", "file_path": "test/services/test_task.py", "repo_id": "harry0703/MoneyPrinterTurbo", "loc": 42, "tested_modules": ["pathlib", "app.services", "app.models.schema"], "has_docstring": fa... |
Shubhamsaboo/awesome-llm-apps:ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/agent.py:get_weather | # Context:
import random
def get_time() -> str: ...
def calculate_tip(bill_amount: float, tip_percentage: float) -> str: ...
class WorkflowCallbacks(SingleAgentWorkflowCallbacks): ...
async def main(): ...
def demo_with_examples(): ...
# Task:
Write a Python function `get_weather` to get the weather for a given city.... | def get_weather(city: str) -> str:
"""Get the weather for a given city."""
print(f"[debug] get_weather called with city: {city}")
choices = ["sunny", "cloudy", "rainy", "snowy"]
return f"The weather in {city} is {random.choice(choices)}." | function_simple | 0 | {"cognitive_complexity": 0, "loc": 5, "code_loc": 3, "docstring_loc": 1, "function_name": "get_weather", "class_name": null, "qualname": "get_weather", "file_path": "ai_agent_framework_crash_course/openai_sdk_crash_course/11_voice/static/agent.py", "repo_id": "Shubhamsaboo/awesome-llm-apps", "has_docstring": true, "run... |
crewAIInc/crewAI:lib/crewai/src/crewai/crews/utils.py:setup_agents | # Context:
from collections.abc import Callable, Coroutine, Iterable, Mapping
from typing import TYPE_CHECKING, Any
from crewai.agents.agent_builder.base_agent import BaseAgent
from crewai.rag.embeddings.types import EmbedderConfig
from crewai.crew import Crew
def enable_agent_streaming(agents: Iterable[BaseAgent]) ->... | def setup_agents(
crew: Crew,
agents: Iterable[BaseAgent],
embedder: EmbedderConfig | None,
function_calling_llm: Any,
step_callback: Callable[..., Any] | None,
) -> None:
"""Set up agents for crew execution.
Args:
crew: The crew instance agents belong to.
agents: Iterable o... | function_simple | 0 | {"cognitive_complexity": 5, "loc": 24, "code_loc": 8, "docstring_loc": 9, "function_name": "setup_agents", "class_name": null, "qualname": "setup_agents", "file_path": "lib/crewai/src/crewai/crews/utils.py", "repo_id": "crewAIInc/crewAI", "has_docstring": true, "runnable_level": "project_runnable"} |
infiniflow/ragflow:api/apps/services/canvas_replica_service.py:CanvasReplicaService.create_if_absent | # Context:
from api.db import CanvasCategory
class CanvasReplicaService:
TTL_SECS = 3 * 60 * 60
REPLICA_KEY_PREFIX = "canvas:replica"
LOCK_KEY_PREFIX = "canvas:replica:lock"
LOCK_TIMEOUT_SECS = 10
LOCK_BLOCKING_TIMEOUT_SECS = 1
LOCK_RETRY_ATTEMPTS = 3
LOCK_RETRY_SLEEP_SECS = 0.2
def nor... | def create_if_absent(
cls,
canvas_id: str,
tenant_id: str,
runtime_user_id: str,
dsl,
canvas_category=CanvasCategory.Agent,
title="",
):
"""Create a runtime replica if it does not exist; otherwise keep existing state."""
replica_key = cls._repl... | function_simple | 1 | {"cognitive_complexity": 1, "loc": 17, "code_loc": 7, "docstring_loc": 1, "function_name": "create_if_absent", "class_name": "CanvasReplicaService", "qualname": "CanvasReplicaService.create_if_absent", "file_path": "api/apps/services/canvas_replica_service.py", "repo_id": "infiniflow/ragflow", "has_docstring": true, "r... |
huggingface/transformers:src/transformers/utils/output_capturing.py:install_all_output_capturing_hooks | # Context:
from ..modeling_utils import PreTrainedModel
class OutputRecorder: ...
class CompileableContextVar: ...
def install_output_capuring_hook(module: nn.Module, key: str, index: int) -> None: ...
def recursively_install_hooks(parent_module: nn.Module, module_name: str, capture_tasks: list[tuple[str, OutputRecord... | def install_all_output_capturing_hooks(model: PreTrainedModel, prefix: str | None = None) -> None:
"""
Install the output recording hooks on all the modules in `model`. Tis will take care of correctly dispatching
the `_can_record_outputs` property of each individual submodels in case of composite models.
... | function_complex | 0 | {"cognitive_complexity": 22, "loc": 25, "code_loc": 15, "docstring_loc": 4, "function_name": "install_all_output_capturing_hooks", "class_name": null, "qualname": "install_all_output_capturing_hooks", "file_path": "src/transformers/utils/output_capturing.py", "repo_id": "huggingface/transformers", "has_docstring": true... |
huggingface/diffusers:src/diffusers/modular_pipelines/qwenimage/before_denoise.py:QwenImageSetTimestepsStep:class_doc | Write a class-level docstring for `QwenImageSetTimestepsStep` (inherits from ModularPipelineBlocks) which has methods: `description`, `expected_components`, `inputs`, `intermediate_outputs`, `__call__`. | Step that sets the scheduler's timesteps for text-to-image generation. Should be run after prepare latents step.
Components:
scheduler (`FlowMatchEulerDiscreteScheduler`)
Inputs:
num_inference_steps (`int`, *optional*, defaults to 50):
The number of denoising steps.
sigmas (`list`, *op... | documentation | 1 | {"doc_type": "class", "class_name": "QwenImageSetTimestepsStep", "file_path": "src/diffusers/modular_pipelines/qwenimage/before_denoise.py", "repo_id": "huggingface/diffusers", "char_length": 616, "methods": ["description", "expected_components", "inputs", "intermediate_outputs", "__call__"]} |
psf/black:tests/test_concurrency_manager_shutdown.py:test_manager_shutdown_called_for_diff | # Context:
import asyncio
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any, Optional
import black.concurrency as concurrency
from black import Mode, WriteBack
from black.report import Report
class FakeManager: ...
# Task:
Write a Python test function `test_manager_shut... | def test_manager_shutdown_called_for_diff(monkeypatch: Any, tmp_path: Path) -> None:
"""
schedule_formatting() creates multiprocessing.Manager() for DIFF/COLOR_DIFF
and must shut it down deterministically.
"""
fake_manager = FakeManager()
monkeypatch.setattr(concurrency, "Manager", lambd... | test | 1 | {"function_name": "test_manager_shutdown_called_for_diff", "class_name": null, "qualname": "test_manager_shutdown_called_for_diff", "file_path": "tests/test_concurrency_manager_shutdown.py", "repo_id": "psf/black", "loc": 41, "tested_modules": ["__future__", "concurrent.futures", "pathlib", "typing", "black"], "has_doc... |
exo-explore/exo:src/exo/worker/engines/image/models/flux/kontext_adapter.py:FluxKontextModelAdapter.create_latents | # Context:
import mlx.core as mx
from mflux.models.common.config.config import Config
from mflux.models.flux.latent_creator.flux_latent_creator import FluxLatentCreator
class FluxKontextPromptData(PromptData): ...
class FluxKontextModelAdapter(ModelAdapter[Flux1Kontext, Transformer]):
def __init__(
self,
... | def create_latents(self, seed: int, runtime_config: Config) -> mx.array:
"""Create initial noise latents for Kontext.
Unlike standard img2img which blends noise with encoded input,
Kontext uses pure noise latents. The input image is provided
separately as conditioning.
"""
... | function_simple | 0 | {"cognitive_complexity": 0, "loc": 12, "code_loc": 5, "docstring_loc": 6, "function_name": "create_latents", "class_name": "FluxKontextModelAdapter", "qualname": "FluxKontextModelAdapter.create_latents", "file_path": "src/exo/worker/engines/image/models/flux/kontext_adapter.py", "repo_id": "exo-explore/exo", "has_docst... |
666ghj/BettaFish:SentimentAnalysisModel/WeiboSentiment_SmallQwen/qwen3_lora_universal.py:Qwen3LoRAUniversal.train | # Context:
from transformers import (
AutoTokenizer,
AutoModelForCausalLM,
TrainingArguments,
Trainer,
DataCollatorForLanguageModeling
)
from typing import List, Tuple
def main(): ...
class Qwen3LoRAUniversal(BaseQwenModel):
def __init__(self, model_size: str = "0.6B"):
if model_siz... | def train(self, train_data: List[Tuple[str, int]], **kwargs) -> None:
"""训练模型"""
print(f"开始训练 Qwen3-{self.model_size}-LoRA 模型...")
# 加载基础模型
self._load_base_model()
# 设置LoRA
self._setup_lora(**kwargs)
# 超参数(使用配置文件的推荐值或用户指定值)
num_e... | function_simple | 1 | {"cognitive_complexity": 0, "loc": 69, "code_loc": 45, "docstring_loc": 1, "function_name": "train", "class_name": "Qwen3LoRAUniversal", "qualname": "Qwen3LoRAUniversal.train", "file_path": "SentimentAnalysisModel/WeiboSentiment_SmallQwen/qwen3_lora_universal.py", "repo_id": "666ghj/BettaFish", "has_docstring": true, "... |
gradio-app/gradio:gradio/mcp.py:GradioMCPServer.get_image | # Context:
import os
from PIL import Image
def resource(uri_template: str, description: str | None, mime_type: str | None): ...
def prompt(name: str | None, description: str | None): ...
def tool(name: str | None, description: str | None, structured_output: bool, _meta: dict[str, Any] | None): ...
class GradioMCPServ... | def get_image(file_path: str) -> Image.Image | None:
"""
If a filepath is a valid image, returns a PIL Image object. Otherwise returns None.
"""
if not os.path.exists(file_path):
return None
ext = os.path.splitext(file_path.lower())[1]
if ext not in Image.regi... | function_simple | 1 | {"cognitive_complexity": 3, "loc": 13, "code_loc": 9, "docstring_loc": 3, "function_name": "get_image", "class_name": "GradioMCPServer", "qualname": "GradioMCPServer.get_image", "file_path": "gradio/mcp.py", "repo_id": "gradio-app/gradio", "has_docstring": true, "runnable_level": "project_runnable"} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.