sample_id
string
instruction
string
completion
string
category
string
label
int64
metadata
string
exo-explore/exo:src/exo/worker/engines/image/models/qwen/adapter.py:QwenModelAdapter.get_joint_block_wrappers
# Context: from typing import Any import mlx.core as mx from exo.worker.engines.image.models.qwen.wrappers import QwenJointBlockWrapper from exo.worker.engines.image.pipeline.block_wrapper import ( JointBlockWrapper, SingleBlockWrapper, ) class QwenPromptData(PromptData): ... class QwenModelAdapter(ModelAdapt...
def get_joint_block_wrappers( self, text_seq_len: int, encoder_hidden_states_mask: mx.array | None = None, ) -> list[JointBlockWrapper[Any]]: """Create wrapped joint blocks for Qwen.""" return [ QwenJointBlockWrapper(block, text_seq_len, encoder_hidden_states_mask...
function_simple
0
{"cognitive_complexity": 0, "loc": 10, "code_loc": 4, "docstring_loc": 1, "function_name": "get_joint_block_wrappers", "class_name": "QwenModelAdapter", "qualname": "QwenModelAdapter.get_joint_block_wrappers", "file_path": "src/exo/worker/engines/image/models/qwen/adapter.py", "repo_id": "exo-explore/exo", "has_docstri...
huggingface/transformers:tests/models/llava_onevision/test_video_processing_llava_onevision.py:LlavaOnevisionVideoProcessingTest.test_video_processor_properties
# Context: class LlavaOnevisionVideoProcessingTester: ... class LlavaOnevisionVideoProcessingTest(VideoProcessingTestMixin, unittest.TestCase): fast_video_processing_class = LlavaOnevisionVideoProcessor if is_torchvision_available() else None def setUp(self): ... def video_processor_dict(self): ... de...
def test_video_processor_properties(self): video_processing = self.fast_video_processing_class(**self.video_processor_dict) self.assertTrue(hasattr(video_processing, "do_resize")) self.assertTrue(hasattr(video_processing, "size")) self.assertTrue(hasattr(video_processing, "do_normalize")...
test
0
{"function_name": "test_video_processor_properties", "class_name": "LlavaOnevisionVideoProcessingTest", "qualname": "LlavaOnevisionVideoProcessingTest.test_video_processor_properties", "file_path": "tests/models/llava_onevision/test_video_processing_llava_onevision.py", "repo_id": "huggingface/transformers", "loc": 8, ...
ray-project/ray:python/ray/tests/test_util_helpers.py:test_map_unordered_chunk_size_1
# Context: import pytest import ray from ray._common.test_utils import SignalActor from ray.util import as_completed, map_unordered def ray_init_4_cpu_shared(): ... def test_as_completed_chunk_size_1(ray_init_4_cpu_shared, yield_obj_refs): ... def test_as_completed_chunk_size_2(ray_init_4_cpu_shared, yield_obj_refs): ...
def test_map_unordered_chunk_size_1(ray_init_4_cpu_shared, yield_obj_refs): """Test map_unordered with chunk_size=1. Use SignalActor to control task completion order and mimic time.sleep(x) behavior. """ inputs = [10, 8, 6, 4, 2] # Create signals for each task signals = [SignalActor.remote() ...
test
0
{"function_name": "test_map_unordered_chunk_size_1", "class_name": null, "qualname": "test_map_unordered_chunk_size_1", "file_path": "python/ray/tests/test_util_helpers.py", "repo_id": "ray-project/ray", "loc": 35, "tested_modules": ["ray._common.test_utils", "ray.util"], "has_docstring": true, "runnable_level": "proje...
huggingface/transformers:src/transformers/integrations/mxfp4.py:load_and_swizzle_mxfp4
# Context: import torch from ..integrations.tensor_parallel import shard_and_distribute_module def on_device(dev): ... class Mxfp4Quantize(ConversionOps): ... class Mxfp4Dequantize(ConversionOps): ... class Mxfp4Deserialize(ConversionOps): ... class Mxfp4ReverseDeserialize(ConversionOps): ... def quantize_to_mxfp4(w, ...
def load_and_swizzle_mxfp4(module, param_name, param_value, target_device, triton_kernels_hub, **kwargs): """ This transforms the weights obtained using `convert_gpt_oss.py` to load them into `Mxfp4GptOssExperts`. """ PrecisionConfig, FlexCtx, InFlexData = ( triton_kernels_hub.matmul_ogs.Precisi...
function_complex
0
{"cognitive_complexity": 15, "loc": 69, "code_loc": 57, "docstring_loc": 3, "function_name": "load_and_swizzle_mxfp4", "class_name": null, "qualname": "load_and_swizzle_mxfp4", "file_path": "src/transformers/integrations/mxfp4.py", "repo_id": "huggingface/transformers", "has_docstring": true, "runnable_level": "project...
google/langextract:tests/factory_schema_test.py:FactorySchemaIntegrationTest.test_no_examples_no_schema
# Context: from unittest import mock from langextract import factory class SchemaApplicationTest(absltest.TestCase): ... class FactorySchemaIntegrationTest(absltest.TestCase): def setUp(self): ... def test_gemini_with_schema_returns_false_fence(self): ... def test_ollama_with_schema_returns_false_fence(se...
def test_no_examples_no_schema(self): """Test that no examples means no schema is created.""" config = factory.ModelConfig( model_id="gemini-2.5-flash", provider_kwargs={"api_key": "test_key"} ) with mock.patch( "langextract.providers.gemini.GeminiLanguageModel.__init__", return...
test
1
{"function_name": "test_no_examples_no_schema", "class_name": "FactorySchemaIntegrationTest", "qualname": "FactorySchemaIntegrationTest.test_no_examples_no_schema", "file_path": "tests/factory_schema_test.py", "repo_id": "google/langextract", "loc": 21, "tested_modules": ["absl.testing", "langextract", "langextract", "...
vllm-project/vllm:vllm/distributed/kv_transfer/kv_connector/v1/lmcache_integration/multi_process_adapter.py:LMCacheMPWorkerAdapter.batched_submit_store_requests
# Context: import torch from lmcache.v1.multiprocess.custom_types import ( CudaIPCWrapper, IPCCacheEngineKey, KVCache, ) from lmcache.v1.multiprocess.protocol import RequestType, get_response_class def wrap_kv_caches(kv_caches: dict[str, torch.Tensor]) -> KVCache: ... def striding_block_hashes(block_hashes...
def batched_submit_store_requests( self, request_ids: list[str], ops: list[LoadStoreOp], event: torch.cuda.Event, ): """ Submit a batched store request to LMCache Args: request_ids: The IDs of the requests ops: The LoadStoreOps describ...
function_simple
1
{"cognitive_complexity": 4, "loc": 47, "code_loc": 31, "docstring_loc": 10, "function_name": "batched_submit_store_requests", "class_name": "LMCacheMPWorkerAdapter", "qualname": "LMCacheMPWorkerAdapter.batched_submit_store_requests", "file_path": "vllm/distributed/kv_transfer/kv_connector/v1/lmcache_integration/multi_p...
apache/airflow:providers/teradata/src/airflow/providers/teradata/utils/tpt_util.py:verify_tpt_utility_on_remote_host
# Context: import logging from paramiko import SSHClient class TPTConfig: ... def execute_remote_command(ssh_client: SSHClient, command: str) -> tuple[int, str, str]: ... def write_file(path: str, content: str) -> None: ... def secure_delete(file_path: str, logger: logging.Logger | None) -> None: ... def remote_secure...
def verify_tpt_utility_on_remote_host( ssh_client: SSHClient, utility: str, logger: logging.Logger | None = None ) -> None: """ Verify if a TPT utility (tbuild) is installed on the remote host via SSH. :param ssh_client: SSH client connection :param utility: Name of the utility to verify :param...
function_complex
1
{"cognitive_complexity": 12, "loc": 38, "code_loc": 19, "docstring_loc": 9, "function_name": "verify_tpt_utility_on_remote_host", "class_name": null, "qualname": "verify_tpt_utility_on_remote_host", "file_path": "providers/teradata/src/airflow/providers/teradata/utils/tpt_util.py", "repo_id": "apache/airflow", "has_doc...
PaddlePaddle/PaddleOCR:langchain-paddleocr/langchain_paddleocr/document_loaders/paddleocr_vl.py:PaddleOCRVLLoader.__init__
# Context: import os from collections.abc import Iterable, Iterator from typing import Any, Literal from pydantic import SecretStr def _snake_to_camel(name: str) -> str: ... def _snake_keys_to_camel(params: dict[str, Any]) -> dict[str, Any]: ... def _normalize_file_type(file_type: FileTypeInput) -> FileType | None: .....
def __init__( self, file_path: str | Iterable[str], *, api_url: str, access_token: SecretStr | None = None, file_type: FileTypeInput = None, use_doc_orientation_classify: bool | None = False, use_doc_unwarping: bool | None = False, use_layout_detec...
function_complex
0
{"cognitive_complexity": 12, "loc": 143, "code_loc": 50, "docstring_loc": 45, "function_name": "__init__", "class_name": "PaddleOCRVLLoader", "qualname": "PaddleOCRVLLoader.__init__", "file_path": "langchain-paddleocr/langchain_paddleocr/document_loaders/paddleocr_vl.py", "repo_id": "PaddlePaddle/PaddleOCR", "has_docst...
apache/airflow:devel-common/tests/unit/tests_common/test_utils/test_stream_capture_manager.py:test_handler_restoration
# Context: import logging import sys def test_stdout_only(stdout_capture): ... def test_stderr_only(stderr_capture): ... def test_combined(combined_capture): ... def test_configurable(stream_capture): ... def test_stdout_logging_isolation(stdout_capture): ... def test_stderr_logging_isolation(stderr_capture): ... def ...
def test_handler_restoration(stdout_capture): """Test that logging handlers are properly restored after capture.""" root_logger = logging.getLogger() # Add a test handler to root logger to ensure we have something to test test_root_handler = logging.StreamHandler(sys.stdout) test_root_handler.setFo...
test
1
{"function_name": "test_handler_restoration", "class_name": null, "qualname": "test_handler_restoration", "file_path": "devel-common/tests/unit/tests_common/test_utils/test_stream_capture_manager.py", "repo_id": "apache/airflow", "loc": 47, "tested_modules": ["__future__"], "has_docstring": true, "runnable_level": "pro...
vllm-project/vllm:tests/cuda/test_cuda_compatibility_path.py:TestCudaCompatibilityLdPathManipulation.test_prepends_to_existing_ld_path
# Context: import os from vllm.env_override import ( _get_torch_cuda_version, _maybe_set_cuda_compatibility_path, ) class TestCudaCompatibilityEnvParsing: ... class TestCudaCompatibilityPathDetection: ... class TestGetTorchCudaVersion: ... class TestCudaCompatibilityLdPathManipulation: def test_prepends_t...
def test_prepends_to_existing_ld_path(self, monkeypatch, tmp_path): """Compat path is prepended before existing entries.""" compat_dir = tmp_path / "compat" compat_dir.mkdir() monkeypatch.setenv("VLLM_ENABLE_CUDA_COMPATIBILITY", "1") monkeypatch.setenv("VLLM_CUDA_COMPATIBILITY_PA...
test
1
{"function_name": "test_prepends_to_existing_ld_path", "class_name": "TestCudaCompatibilityLdPathManipulation", "qualname": "TestCudaCompatibilityLdPathManipulation.test_prepends_to_existing_ld_path", "file_path": "tests/cuda/test_cuda_compatibility_path.py", "repo_id": "vllm-project/vllm", "loc": 13, "tested_modules":...
ray-project/ray:python/ray/llm/tests/serve/cpu/deployments/llm/vllm/kv_transfer_backends/test_registry.py:TestComponentRegistry.test_double_registration_raises
# Context: import pytest from ray.llm._internal.serve.utils.registry import ComponentRegistry, get_registry class TestComponentRegistry: def test_register_and_get_direct_class(self): ... def test_register_and_get_module_path(self): ... def test_get_nonexistent_component_raises(self): ... def test_inval...
def test_double_registration_raises(self): """Test that double registration raises ValueError.""" registry = ComponentRegistry("test_category") test_class1 = type("TestClass1", (), {}) test_class2 = type("TestClass2", (), {}) registry.register("test_component", test_class1) ...
test
0
{"function_name": "test_double_registration_raises", "class_name": "TestComponentRegistry", "qualname": "TestComponentRegistry.test_double_registration_raises", "file_path": "python/ray/llm/tests/serve/cpu/deployments/llm/vllm/kv_transfer_backends/test_registry.py", "repo_id": "ray-project/ray", "loc": 13, "tested_modu...
streamlit/streamlit:lib/tests/streamlit/components/v2/test_component_manager.py:test_manager_uses_lock_for_api_inputs
# Context: from pathlib import Path def _setup_manager_with_manifest(tmp_path: Path) -> tuple[BidiComponentManager, str]: ... def test_concurrent_record_and_change_no_exceptions(tmp_path: Path) -> None: ... def test_get_component_path_prefers_asset_dir_when_present() -> None: ... def test_register_from_manifest_does_n...
def test_manager_uses_lock_for_api_inputs(tmp_path: Path) -> None: """Verify manager exposes a lock and handles inputs safely during updates.""" manager, comp_name = _setup_manager_with_manifest(tmp_path) # The manager is expected to expose an _api_inputs_lock used to guard access. assert hasattr(manag...
test
1
{"function_name": "test_manager_uses_lock_for_api_inputs", "class_name": null, "qualname": "test_manager_uses_lock_for_api_inputs", "file_path": "lib/tests/streamlit/components/v2/test_component_manager.py", "repo_id": "streamlit/streamlit", "loc": 16, "tested_modules": ["__future__", "pathlib", "typing", "streamlit.co...
mitmproxy/mitmproxy:test/mitmproxy/contentviews/test__view_zip.py:test_view_zip
# Context: import io import zipfile def meta(content_type: str) -> Metadata: ... def test_view_zip_empty(): ... def test_render_priority(): ... # Task: Write a Python test function `test_view_zip` to verify the behavior of `view_zip`. Module under test: mitmproxy, mitmproxy.contentviews, mitmproxy.contentviews._view...
def test_view_zip(): buffer = io.BytesIO() with zipfile.ZipFile(buffer, "w") as zf: for name in [ "normal.txt", "with spaces.txt", "dir/nested.txt", "file\nwith\nnewlines.txt", "unicode_文件.txt", "café.txt", ]: zf...
test
0
{"function_name": "test_view_zip", "class_name": null, "qualname": "test_view_zip", "file_path": "test/mitmproxy/contentviews/test__view_zip.py", "repo_id": "mitmproxy/mitmproxy", "loc": 23, "tested_modules": ["mitmproxy", "mitmproxy.contentviews", "mitmproxy.contentviews._view_zip"], "has_docstring": false, "runnable_...
huggingface/transformers:tests/quantization/mxfp4/test_mxfp4.py:Mxfp4ModelTest.test_gpt_oss_model_loading_quantized_with_device_map
# Context: from transformers import AutoTokenizer, GptOssForCausalLM, Mxfp4Config import torch def _empty_accelerator_cache(): ... def _patch_no_accelerator(): ... class Mxfp4ConfigTest(unittest.TestCase): ... class Mxfp4QuantizerTest(unittest.TestCase): ... class Mxfp4IntegrationTest(unittest.TestCase): ... class Mx...
def test_gpt_oss_model_loading_quantized_with_device_map(self): """Test loading OpenAI MoE model with mxfp4 quantization and device_map""" model = GptOssForCausalLM.from_pretrained( self.model_name, dtype=torch.bfloat16, device_map="auto", ) tokenizer...
test
0
{"function_name": "test_gpt_oss_model_loading_quantized_with_device_map", "class_name": "Mxfp4ModelTest", "qualname": "Mxfp4ModelTest.test_gpt_oss_model_loading_quantized_with_device_map", "file_path": "tests/quantization/mxfp4/test_mxfp4.py", "repo_id": "huggingface/transformers", "loc": 10, "tested_modules": ["contex...
vllm-project/vllm:vllm/benchmarks/mm_processor.py:benchmark_multimodal_processor
# Context: import argparse import dataclasses import time from typing import TYPE_CHECKING, Any, Literal import numpy as np from vllm.benchmarks.throughput import get_requests from vllm.engine.arg_utils import EngineArgs from vllm.utils.gc_utils import freeze_gc_heap from vllm import LLM, SamplingParams def get_timing...
def benchmark_multimodal_processor( args: argparse.Namespace, ) -> dict[str, Any]: """ Run the multimodal processor benchmark. """ from vllm import LLM, SamplingParams validate_args(args) if args.seed is None: args.seed = 0 engine_args = EngineArgs.from_cli_args(args) llm ...
function_complex
1
{"cognitive_complexity": 16, "loc": 157, "code_loc": 123, "docstring_loc": 3, "function_name": "benchmark_multimodal_processor", "class_name": null, "qualname": "benchmark_multimodal_processor", "file_path": "vllm/benchmarks/mm_processor.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "runnable_level": "pro...
streamlit/streamlit:e2e_playwright/theming/theme_metric_value_style_test.py:test_metric_value_font_size_with_rem
# Context: import pytest from playwright.sync_api import Page, expect from e2e_playwright.shared.app_utils import expect_no_skeletons, get_metric def configure_metric_value_style(): ... def test_metric_value_style_snapshot(app: Page, assert_snapshot: ImageCompareFunction): ... # Task: Write a Python test function `te...
def test_metric_value_font_size_with_rem(app: Page): """Test that metricValueFontSize accepts rem values and applies them correctly.""" expect_no_skeletons(app, timeout=25000) metric = get_metric(app, "Revenue") metric_value = metric.get_by_test_id("stMetricValue") # Verify rem value is converted ...
test
1
{"function_name": "test_metric_value_font_size_with_rem", "class_name": null, "qualname": "test_metric_value_font_size_with_rem", "file_path": "e2e_playwright/theming/theme_metric_value_style_test.py", "repo_id": "streamlit/streamlit", "loc": 15, "tested_modules": ["playwright.sync_api", "e2e_playwright.conftest", "e2e...
ray-project/ray:python/ray/data/tests/unit/test_transform_pyarrow.py:test_arrow_concat_with_objects
# Context: import pyarrow as pa 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_partitioni...
def test_arrow_concat_with_objects(object_concat_blocks, object_concat_expected): t3 = concat(object_concat_blocks) assert isinstance(t3, pa.Table) assert len(t3) == object_concat_expected["length"] assert isinstance(t3.schema.field("a").type, object_concat_expected["a_type"]) assert object_concat_e...
test
0
{"function_name": "test_arrow_concat_with_objects", "class_name": null, "qualname": "test_arrow_concat_with_objects", "file_path": "python/ray/data/tests/unit/test_transform_pyarrow.py", "repo_id": "ray-project/ray", "loc": 8, "tested_modules": ["typing", "ray.data._internal.arrow_ops.transform_pyarrow", "ray.data._int...
huggingface/transformers:src/transformers/models/qwen3_vl_moe/modular_qwen3_vl_moe.py:Qwen3VLMoePreTrainedModel._init_weights
# Context: import torch from ... import initialization as init from ...modeling_utils import PreTrainedModel class Qwen3VLMoeTextConfig(PreTrainedConfig): ... class Qwen3VLMoeVisionConfig(Qwen3VLVisionConfig): ... class Qwen3VLMoeConfig(Qwen3VLConfig): ... class Qwen3VLMoeTextRMSNorm(Qwen3MoeRMSNorm): ... class Qwen3V...
def _init_weights(self, module): """Initialize the weights.""" PreTrainedModel._init_weights(self, module) if hasattr(self.config, "initializer_range"): std = self.config.initializer_range else: std = getattr(self.config.get_text_config(), "initializer_range", 0.0...
function_simple
0
{"cognitive_complexity": 5, "loc": 15, "code_loc": 13, "docstring_loc": 1, "function_name": "_init_weights", "class_name": "Qwen3VLMoePreTrainedModel", "qualname": "Qwen3VLMoePreTrainedModel._init_weights", "file_path": "src/transformers/models/qwen3_vl_moe/modular_qwen3_vl_moe.py", "repo_id": "huggingface/transformers...
keras-team/keras:keras/src/layers/pooling/adaptive_pooling1d_test.py:AdaptivePooling1DLayerTest.test_max_pooling_compute_output_shape
# Context: from keras.src import layers class AdaptivePooling1DLayerTest(testing.TestCase): def _run_layer_test(self, layer_class, x_np, output_size, data_format): ... def test_average_pooling_basic_shapes(self): ... def test_max_pooling_basic_shapes(self): ... def test_average_pooling_channels_last(se...
def test_max_pooling_compute_output_shape(self): """Test compute_output_shape() for AdaptiveMaxPooling1D.""" layer = layers.AdaptiveMaxPooling1D( output_size=16, data_format="channels_first" ) input_shape = (2, 3, 64) output_shape = layer.compute_output_shape(input_sh...
test
1
{"function_name": "test_max_pooling_compute_output_shape", "class_name": "AdaptivePooling1DLayerTest", "qualname": "AdaptivePooling1DLayerTest.test_max_pooling_compute_output_shape", "file_path": "keras/src/layers/pooling/adaptive_pooling1d_test.py", "repo_id": "keras-team/keras", "loc": 8, "tested_modules": ["keras.sr...
ManimCommunity/manim:tests/module/mobject/test_matrix.py:TestIntegerMatrix.test_integer_matrix_init
# Context: import pytest from manim.mobject.matrix import ( DecimalMatrix, IntegerMatrix, Matrix, ) class TestMatrix: ... class TestDecimalMatrix: ... class TestIntegerMatrix: # Task: Write a Python test method `test_integer_matrix_init` in test class `TestIntegerMatrix` to verify the behavior of `intege...
def test_integer_matrix_init(self, matrix_elements, expected_elements): matrix = IntegerMatrix(matrix_elements) assert isinstance(matrix, IntegerMatrix) for row_index, row in enumerate(matrix.get_rows()): for column_index, element in enumerate(row): assert element.nu...
test
1
{"function_name": "test_integer_matrix_init", "class_name": "TestIntegerMatrix", "qualname": "TestIntegerMatrix.test_integer_matrix_init", "file_path": "tests/module/mobject/test_matrix.py", "repo_id": "ManimCommunity/manim", "loc": 7, "tested_modules": ["__future__", "manim.mobject.matrix", "manim.mobject.text.tex_mob...
ray-project/ray:python/ray/data/examples/data/video_processing/http_utils.py:HTTPConnection:class_doc
Write a class-level docstring for `HTTPConnection` which has methods: `__init__`, `get_sync_client`, `get_async_client`, `_validate_http_url`, `_headers`.
Small helper around ``requests``/``aiohttp`` for reuseable HTTP clients.
documentation
0
{"doc_type": "class", "class_name": "HTTPConnection", "file_path": "python/ray/data/examples/data/video_processing/http_utils.py", "repo_id": "ray-project/ray", "char_length": 72, "methods": ["__init__", "get_sync_client", "get_async_client", "_validate_http_url", "_headers", "get_response", "get_async_response", "get_...
ray-project/ray:ci/raydepsets/tests/test_cli.py:TestCli.test_subset
# Context: import tempfile from pathlib import Path from ci.raydepsets.tests.utils import ( append_to_file, copy_data_to_tmpdir, replace_in_file, save_file_as, save_packages_to_file, write_to_config_file, ) def _create_test_manager(tmpdir: str, config_path: Optional[str], check: bool, build_all...
def test_subset(self): with tempfile.TemporaryDirectory() as tmpdir: copy_data_to_tmpdir(tmpdir) # Add six to requirements_test_subset.txt save_packages_to_file( Path(tmpdir) / "requirements_test_subset.txt", ["six==1.16.0"], ) ...
test
0
{"function_name": "test_subset", "class_name": "TestCli", "qualname": "TestCli.test_subset", "file_path": "ci/raydepsets/tests/test_cli.py", "repo_id": "ray-project/ray", "loc": 31, "tested_modules": ["pathlib", "typing", "click.testing", "networkx", "ci.raydepsets.cli"], "has_docstring": false, "runnable_level": "proj...
browser-use/browser-use:browser_use/browser/profile.py:BrowserLaunchArgs.validate_devtools_headless
# Context: from typing import Annotated, Any, Literal, Self from pydantic import AfterValidator, AliasChoices, BaseModel, ConfigDict, Field, field_validator, model_validator def _get_enable_default_extensions_default() -> bool: ... class ViewportSize(BaseModel): ... def get_display_size() -> ViewportSize | None: ... d...
def validate_devtools_headless(self) -> Self: """Cannot open devtools when headless is True""" assert not (self.headless and self.devtools), 'headless=True and devtools=True cannot both be set at the same time' return self
function_simple
0
{"cognitive_complexity": 1, "loc": 4, "code_loc": 2, "docstring_loc": 1, "function_name": "validate_devtools_headless", "class_name": "BrowserLaunchArgs", "qualname": "BrowserLaunchArgs.validate_devtools_headless", "file_path": "browser_use/browser/profile.py", "repo_id": "browser-use/browser-use", "has_docstring": tru...
crewAIInc/crewAI:lib/crewai/src/crewai/events/types/a2a_events.py:A2AServerTaskFailedEvent:class_doc
Write a class-level docstring for `A2AServerTaskFailedEvent` (inherits from A2AEventBase) which has methods: various methods.
Event emitted when an A2A server task execution fails. Attributes: task_id: A2A task ID for this execution. context_id: A2A context ID grouping related tasks. error: Error message describing the failure. metadata: Custom A2A metadata key-value pairs.
documentation
0
{"doc_type": "class", "class_name": "A2AServerTaskFailedEvent", "file_path": "lib/crewai/src/crewai/events/types/a2a_events.py", "repo_id": "crewAIInc/crewAI", "char_length": 267, "methods": []}
huggingface/transformers:tests/models/d_fine/test_modeling_d_fine.py:DFineModelTest.test_retain_grad_hidden_states_attentions
# Context: from transformers.testing_utils import ( require_torch, require_torch_accelerator, require_vision, slow, torch_device, ) class DFineModelTester: ... def prepare_img(): ... class DFineModelIntegrationTest(unittest.TestCase): ... class DFineModelTest(ModelTesterMixin, PipelineTesterMixin,...
def test_retain_grad_hidden_states_attentions(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.output_hidden_states = True config.output_attentions = True model_class = self.all_model_classes[0] model = model_class(config) mode...
test
0
{"function_name": "test_retain_grad_hidden_states_attentions", "class_name": "DFineModelTest", "qualname": "DFineModelTest.test_retain_grad_hidden_states_attentions", "file_path": "tests/models/d_fine/test_modeling_d_fine.py", "repo_id": "huggingface/transformers", "loc": 33, "tested_modules": ["functools", "parameteri...
ray-project/ray:doc/source/serve/tutorials/video-analysis/autoscaling_policy.py:_find_deployment
# Context: from typing import Dict, Tuple from ray.serve._private.common import DeploymentID from ray.serve.config import AutoscalingContext def _get_error_ratio(ctx: AutoscalingContext) -> float: ... def _scale_by_error_ratio(ctx: AutoscalingContext, floor: int) -> int: ... def coordinated_scaling_policy(contexts: Di...
def _find_deployment( contexts: Dict[DeploymentID, AutoscalingContext], name: str, ) -> Tuple[DeploymentID, AutoscalingContext]: """Find deployment by name.""" for dep_id, ctx in contexts.items(): if dep_id.name == name: return dep_id, ctx raise KeyError(f"Deployment '{name}' no...
function_simple
0
{"cognitive_complexity": 3, "loc": 9, "code_loc": 4, "docstring_loc": 1, "function_name": "_find_deployment", "class_name": null, "qualname": "_find_deployment", "file_path": "doc/source/serve/tutorials/video-analysis/autoscaling_policy.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "plib_r...
browser-use/browser-use:browser_use/browser/watchdogs/dom_watchdog.py:DOMWatchdog:class_doc
Write a class-level docstring for `DOMWatchdog` (inherits from BaseWatchdog) which has methods: `on_TabCreatedEvent`, `_get_recent_events_str`, `_get_pending_network_requests`, `on_BrowserStateRequestEvent`, `_build_dom_tree_without_highlights`.
Handles DOM tree building, serialization, and element access via CDP. This watchdog acts as a bridge between the event-driven browser session and the DomService implementation, maintaining cached state and providing helper methods for other watchdogs.
documentation
0
{"doc_type": "class", "class_name": "DOMWatchdog", "file_path": "browser_use/browser/watchdogs/dom_watchdog.py", "repo_id": "browser-use/browser-use", "char_length": 252, "methods": ["on_TabCreatedEvent", "_get_recent_events_str", "_get_pending_network_requests", "on_BrowserStateRequestEvent", "_build_dom_tree_without_...
vllm-project/vllm:vllm/model_executor/models/funasr.py:FunASRAudioInputs:class_doc
Write a class-level docstring for `FunASRAudioInputs` (inherits from TensorSchema) which has methods: various methods.
Dimensions: - b: Batch size - nmb: Number of mel bins - t: Time frames (M)
documentation
1
{"doc_type": "class", "class_name": "FunASRAudioInputs", "file_path": "vllm/model_executor/models/funasr.py", "repo_id": "vllm-project/vllm", "char_length": 86, "methods": []}
infiniflow/ragflow:test/unit_test/common/test_token_utils.py:TestTotalTokenCountFromResponse.test_dict_with_usage_total_tokens
# Context: from common.token_utils import num_tokens_from_string, total_token_count_from_response, truncate, encoder class TestNumTokensFromString: ... def test_token_count_ranges(input_string, expected_min_tokens): ... def test_consistency(): ... class TestTruncate: ... class TestTotalTokenCountFromResponse: def...
def test_dict_with_usage_total_tokens(self): """Test dictionary response with usage['total_tokens']""" resp_dict = { 'usage': { 'total_tokens': 175 } } result = total_token_count_from_response(resp_dict) assert result == 175
test
1
{"function_name": "test_dict_with_usage_total_tokens", "class_name": "TestTotalTokenCountFromResponse", "qualname": "TestTotalTokenCountFromResponse.test_dict_with_usage_total_tokens", "file_path": "test/unit_test/common/test_token_utils.py", "repo_id": "infiniflow/ragflow", "loc": 10, "tested_modules": ["common.token_...
vllm-project/vllm:tests/kernels/moe/test_silu_mul_per_token_group_quant_fp8_colmajor.py:test_silu_mul_fp8_quant_deep_gemm
# Context: import pytest import torch from vllm.model_executor.layers.quantization.utils.fp8_utils import ( _per_token_group_quant_fp8_colmajor, silu_mul_per_token_group_quant_fp8_colmajor, ) from vllm.platforms import current_platform from vllm.utils.deep_gemm import is_deep_gemm_e8m0_used from vllm.utils.torc...
def test_silu_mul_fp8_quant_deep_gemm(T: int, N: int): set_random_seed(42) input = torch.rand((T, N), dtype=torch.bfloat16, device="cuda") use_ue8m0 = is_deep_gemm_e8m0_used() # Test output, output_scales = silu_mul_per_token_group_quant_fp8_colmajor( input, use_ue8m0=use_ue8m0 ) ...
test
1
{"function_name": "test_silu_mul_fp8_quant_deep_gemm", "class_name": null, "qualname": "test_silu_mul_fp8_quant_deep_gemm", "file_path": "tests/kernels/moe/test_silu_mul_per_token_group_quant_fp8_colmajor.py", "repo_id": "vllm-project/vllm", "loc": 17, "tested_modules": ["vllm.model_executor.layers.quantization.utils.f...
Shubhamsaboo/awesome-llm-apps:ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/calculator_agent.py:demonstrate_calculator
# Context: from agents import Agent, Runner, function_tool def add_numbers(a: float, b: float) -> float: ... def subtract_numbers(a: float, b: float) -> float: ... def multiply_numbers(a: float, b: float) -> float: ... def divide_numbers(a: float, b: float) -> float: ... def calculate_compound_interest(principal: floa...
def demonstrate_calculator(): """Demonstrate the calculator agent with various examples""" print("🎯 OpenAI Agents SDK - Tutorial 3: Calculator Agent") print("=" * 60) print() # Test cases test_cases = [ "Calculate 15 + 27", "What's the compound interest on $5000 at 3.5% for...
function_simple
0
{"cognitive_complexity": 2, "loc": 29, "code_loc": 22, "docstring_loc": 1, "function_name": "demonstrate_calculator", "class_name": null, "qualname": "demonstrate_calculator", "file_path": "ai_agent_framework_crash_course/openai_sdk_crash_course/3_tool_using_agent/calculator_agent.py", "repo_id": "Shubhamsaboo/awesome-...
ocrmypdf/OCRmyPDF:tests/test_multi_font_manager.py:test_select_font_arabic_text_without_language_hint
# Context: import pytest def font_dir(): ... def multi_font_manager(font_dir): ... def has_cjk_font(manager: MultiFontManager) -> bool: ... def has_arabic_font(manager: MultiFontManager) -> bool: ... def has_devanagari_font(manager: MultiFontManager) -> bool: ... def test_init_loads_builtin_fonts(multi_font_manager): ...
def test_select_font_arabic_text_without_language_hint(multi_font_manager): """Test that Arabic text is handled via fallback without language hint.""" if not has_arabic_font(multi_font_manager): pytest.skip("Arabic font not available") font_manager = multi_font_manager.select_font_for_word("مرحبا", ...
test
1
{"function_name": "test_select_font_arabic_text_without_language_hint", "class_name": null, "qualname": "test_select_font_arabic_text_without_language_hint", "file_path": "tests/test_multi_font_manager.py", "repo_id": "ocrmypdf/OCRmyPDF", "loc": 7, "tested_modules": ["__future__", "pathlib", "ocrmypdf.font"], "has_docs...
exo-explore/exo:src/exo/worker/tests/unittests/test_runner/test_glm_tool_parsing.py:TestGlmToolParsingEdgeCases.test_empty_value_with_closing
# Context: def _parse_args(text: str) -> list[tuple[str, str]]: ... def _parse_func_name(text: str) -> str: ... class TestGlmToolParsingWithClosingTags: ... class TestGlmToolParsingMissingClosingTags: ... class TestGlmToolParsingEdgeCases: def test_value_with_json_content(self): ... def test_value_with_json_n...
def test_empty_value_with_closing(self): text = "fn<arg_key>empty</arg_key><arg_value></arg_value>" pairs = _parse_args(text) assert pairs == [("empty", "")]
test
0
{"function_name": "test_empty_value_with_closing", "class_name": "TestGlmToolParsingEdgeCases", "qualname": "TestGlmToolParsingEdgeCases.test_empty_value_with_closing", "file_path": "src/exo/worker/tests/unittests/test_runner/test_glm_tool_parsing.py", "repo_id": "exo-explore/exo", "loc": 4, "tested_modules": [], "has_...
ray-project/ray:python/ray/llm/_internal/common/utils/cloud_filesystem/pyarrow_filesystem.py:PyArrowFileSystem.upload_files
# Context: 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 _create_abfss_filesystem(object_uri: str) -> Tuple[pa_fs.FileS...
def upload_files( local_path: str, bucket_uri: str, ) -> None: """Upload files to cloud storage. Args: local_path: The local path of the files to upload. bucket_uri: The bucket uri to upload the files to, must start with `s3://`, `gs://`, `abf...
function_simple
0
{"cognitive_complexity": 1, "loc": 23, "code_loc": 11, "docstring_loc": 7, "function_name": "upload_files", "class_name": "PyArrowFileSystem", "qualname": "PyArrowFileSystem.upload_files", "file_path": "python/ray/llm/_internal/common/utils/cloud_filesystem/pyarrow_filesystem.py", "repo_id": "ray-project/ray", "has_doc...
binary-husky/gpt_academic:crazy_functions/doc_fns/conversation_doc/html_doc.py:HtmlFormatter.create_document
# Context: class HtmlFormatter: def __init__(self, chatbot, history): self.chatbot = chatbot self.history = history self.css_styles = """ :root { --primary-color: #2563eb; --primary-light: #eff6ff; --secondary-color: #1e293b; --backgro...
def create_document(self) -> str: """生成完整的HTML文档 Returns: str: 完整的HTML文档字符串 """ return f""" <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> ...
function_simple
1
{"cognitive_complexity": 0, "loc": 25, "code_loc": 19, "docstring_loc": 5, "function_name": "create_document", "class_name": "HtmlFormatter", "qualname": "HtmlFormatter.create_document", "file_path": "crazy_functions/doc_fns/conversation_doc/html_doc.py", "repo_id": "binary-husky/gpt_academic", "has_docstring": true, "...
huggingface/pytorch-image-models:tests/test_layers_drop.py:TestDropBlock2d.test_drop_block_2d_scale_by_keep
# Context: import torch from timm.layers.drop import drop_block_2d, DropBlock2d, drop_path, DropPath class TestDropBlock2dModule: ... class TestDropPath: ... class TestDropPathModule: ... class TestDropBlock2d: def test_drop_block_2d_output_shape(self): ... def test_drop_block_2d_no_drop_when_prob_zero(self):...
def test_drop_block_2d_scale_by_keep(self): """Test scale_by_keep parameter.""" torch.manual_seed(42) x = torch.ones((2, 3, 16, 16)) # With scale_by_keep=True (default), kept values are scaled up result_scaled = drop_block_2d(x.clone(), drop_prob=0.3, block_size=5, scale_by_keep...
test
1
{"function_name": "test_drop_block_2d_scale_by_keep", "class_name": "TestDropBlock2d", "qualname": "TestDropBlock2d.test_drop_block_2d_scale_by_keep", "file_path": "tests/test_layers_drop.py", "repo_id": "huggingface/pytorch-image-models", "loc": 18, "tested_modules": ["timm.layers.drop"], "has_docstring": true, "runna...
vllm-project/vllm:benchmarks/benchmark_topk_topp.py:benchmark_function
# Context: import torch class BenchmarkConfig: ... def calculate_ops_pct(k_values: torch.Tensor | None, p_values: torch.Tensor | None, vocab_size: int, batch_size: int) -> float: ... def create_logits(batch_size: int, vocab_size: int, device: str) -> torch.Tensor: ... def measure_memory() -> tuple[int, int]: ... def r...
def benchmark_function( func, logits: torch.Tensor, k: torch.Tensor | None, p: torch.Tensor | None, warmup_iters: int = 5, benchmark_iters: int = 20, ) -> tuple[float, int]: """ Benchmark a function and return (avg_time_ms, peak_memory_bytes). Returns average time in milliseconds an...
function_simple
1
{"cognitive_complexity": 2, "loc": 46, "code_loc": 21, "docstring_loc": 5, "function_name": "benchmark_function", "class_name": null, "qualname": "benchmark_function", "file_path": "benchmarks/benchmark_topk_topp.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "runnable_level": "file_runnable"}
huggingface/transformers:src/transformers/models/ernie4_5_vl_moe/modular_ernie4_5_vl_moe.py:Ernie4_5_VLMoeImageProcessor:class_doc
Write a class-level docstring for `Ernie4_5_VLMoeImageProcessor` (inherits from Glm4vImageProcessor) which has methods: `__init__`, `_preprocess`, `get_number_of_image_patches`.
Constructs a Ernie 4.5 VL image processor that dynamically resizes images based on the original images. Args: do_resize (`bool`, *optional*, defaults to `True`): Whether to resize the image's (height, width) dimensions. size (`dict[str, int]`, *optional*, defaults to `{"shortest_edge": 56 * 56, "longes...
documentation
0
{"doc_type": "class", "class_name": "Ernie4_5_VLMoeImageProcessor", "file_path": "src/transformers/models/ernie4_5_vl_moe/modular_ernie4_5_vl_moe.py", "repo_id": "huggingface/transformers", "char_length": 1878, "methods": ["__init__", "_preprocess", "get_number_of_image_patches"]}
streamlit/streamlit:e2e_playwright/window_config_test.py:test_window_config_captured_at_preload
# Context: from playwright.sync_api import Page, Request, expect from e2e_playwright.conftest import ( ImageCompareFunction, wait_for_app_loaded, wait_until, ) def test_window_theme_config_immutable_after_load(app: Page, assert_snapshot: ImageCompareFunction): ... def test_window_config_backend_base_url_im...
def test_window_config_captured_at_preload( app: Page, assert_snapshot: ImageCompareFunction ): """Test that window.__streamlit configuration works when set before load. This verifies the normal use case where embedding environments set configuration before the Streamlit bundle loads. Tests multiple co...
test
1
{"function_name": "test_window_config_captured_at_preload", "class_name": null, "qualname": "test_window_config_captured_at_preload", "file_path": "e2e_playwright/window_config_test.py", "repo_id": "streamlit/streamlit", "loc": 66, "tested_modules": ["playwright.sync_api", "e2e_playwright.conftest"], "has_docstring": t...
sansan0/TrendRadar:mcp_server/tools/system.py:check_single_version
# Context: from typing import Dict, List, Optional import requests class SystemManagementTools: ... # Task: Write a Python function `check_single_version` to 检查单个组件的版本. Parameters: name: str, local_version: str, remote_url: str, proxies: Optional[Dict], headers: Dict Returns: Dict
def check_single_version( name: str, local_version: str, remote_url: str, proxies: Optional[Dict], headers: Dict ) -> Dict: """检查单个组件的版本""" try: response = requests.get( remote_url, proxies=pr...
function_complex
1
{"cognitive_complexity": 7, "loc": 57, "code_loc": 46, "docstring_loc": 1, "function_name": "check_single_version", "class_name": null, "qualname": "check_single_version", "file_path": "mcp_server/tools/system.py", "repo_id": "sansan0/TrendRadar", "has_docstring": true, "runnable_level": "file_runnable"}
ray-project/ray:release/ray_release/kuberay_util.py:convert_cluster_compute_to_kuberay_compute_config
Write a Python function `convert_cluster_compute_to_kuberay_compute_config` to convert cluster compute config to KubeRay compute config format. Parameters: compute_config: dict Returns: dict
def convert_cluster_compute_to_kuberay_compute_config(compute_config: dict) -> dict: """Convert cluster compute config to KubeRay compute config format. Args: compute_config: Original cluster compute configuration dict. Returns: Dict containing KubeRay-formatted compute configuration. ""...
function_simple
0
{"cognitive_complexity": 4, "loc": 28, "code_loc": 19, "docstring_loc": 6, "function_name": "convert_cluster_compute_to_kuberay_compute_config", "class_name": null, "qualname": "convert_cluster_compute_to_kuberay_compute_config", "file_path": "release/ray_release/kuberay_util.py", "repo_id": "ray-project/ray", "has_doc...
langflow-ai/langflow:src/backend/base/langflow/utils/template_validation.py:validate_flow_execution
# Context: import asyncio from typing import Any def validate_template_structure(template_data: dict[str, Any], filename: str) -> list[str]: ... def validate_flow_can_build(template_data: dict[str, Any], filename: str) -> list[str]: ... def validate_flow_code(template_data: dict[str, Any], filename: str) -> list[str]:...
async def validate_flow_execution( client, template_data: dict[str, Any], filename: str, headers: dict[str, str] ) -> list[str]: """Validate flow execution by building and running the flow. Args: client: AsyncClient for API requests template_data: The template data to validate filen...
function_complex
1
{"cognitive_complexity": 11, "loc": 61, "code_loc": 29, "docstring_loc": 11, "function_name": "validate_flow_execution", "class_name": null, "qualname": "validate_flow_execution", "file_path": "src/backend/base/langflow/utils/template_validation.py", "repo_id": "langflow-ai/langflow", "has_docstring": true, "runnable_l...
apache/airflow:providers/edge3/src/airflow/providers/edge3/worker_api/datamodels_ui.py:Worker:class_doc
Write a class-level docstring for `Worker` (inherits from WorkerStateBody) which has methods: various methods.
Details of the worker state sent to the scheduler.
documentation
1
{"doc_type": "class", "class_name": "Worker", "file_path": "providers/edge3/src/airflow/providers/edge3/worker_api/datamodels_ui.py", "repo_id": "apache/airflow", "char_length": 50, "methods": []}
ocrmypdf/OCRmyPDF:tests/test_ocr_engine_selection.py:TestOcrEnginePluginSelection:class_doc
Write a class-level docstring for `TestOcrEnginePluginSelection` which has methods: `test_tesseract_selected_when_auto`, `test_tesseract_selected_when_tesseract`, `test_null_selected_when_none`, `test_null_returns_none_when_auto`.
Test that get_ocr_engine() hook selects correct engine based on options.
documentation
1
{"doc_type": "class", "class_name": "TestOcrEnginePluginSelection", "file_path": "tests/test_ocr_engine_selection.py", "repo_id": "ocrmypdf/OCRmyPDF", "char_length": 72, "methods": ["test_tesseract_selected_when_auto", "test_tesseract_selected_when_tesseract", "test_null_selected_when_none", "test_null_returns_none_whe...
crewAIInc/crewAI:lib/crewai/tests/test_human_feedback_decorator.py:TestAsyncSupport.test_sync_method_remains_sync
# Context: import asyncio from crewai.flow import Flow, human_feedback, listen, start class TestHumanFeedbackValidation: ... class TestHumanFeedbackConfig: ... class TestHumanFeedbackResult: ... class TestDecoratorAttributePreservation: ... class TestHumanFeedbackExecution: ... class TestHumanFeedbackHistory: ... clas...
def test_sync_method_remains_sync(self): """Test that sync methods remain synchronous.""" @human_feedback(message="Review:") def sync_method(self): return "sync output" assert not asyncio.iscoroutinefunction(sync_method)
test
0
{"function_name": "test_sync_method_remains_sync", "class_name": "TestAsyncSupport", "qualname": "TestAsyncSupport.test_sync_method_remains_sync", "file_path": "lib/crewai/tests/test_human_feedback_decorator.py", "repo_id": "crewAIInc/crewAI", "loc": 8, "tested_modules": ["__future__", "datetime", "typing", "crewai.flo...
exo-explore/exo:src/exo/worker/tests/unittests/test_mlx/test_kv_prefix_cache.py:TestGetPrefixLength.test_empty_prompt
# Context: import mlx.core as mx from exo.worker.engines.mlx.cache import ( KVPrefixCache, cache_length, encode_prompt, get_prefix_length, make_kv_cache, ) def _check_model_exists() -> bool: ... class TestKVPrefix: ... def _load_gpt_oss() -> tuple[Model, object]: ... class TestKVPrefixCacheWithMode...
def test_empty_prompt(self): a = mx.array([]).astype(mx.int32) b = mx.array([1, 2, 3]) assert get_prefix_length(a, b) == 0
test
0
{"function_name": "test_empty_prompt", "class_name": "TestGetPrefixLength", "qualname": "TestGetPrefixLength.test_empty_prompt", "file_path": "src/exo/worker/tests/unittests/test_mlx/test_kv_prefix_cache.py", "repo_id": "exo-explore/exo", "loc": 4, "tested_modules": ["typing", "mlx_lm.models.cache", "mlx_lm.sample_util...
apache/airflow:providers/google/tests/unit/google/cloud/fs/test_gcs.py:TestGCSFilesystem.test_get_fs_with_anonymous_credentials
# Context: from unittest.mock import MagicMock, patch from airflow.providers.google.cloud.fs.gcs import get_fs from google.auth.credentials import AnonymousCredentials def _setup_connections(): ... class TestGCSFilesystem: def test_get_fs_passes_credentials_object(self, mock_gcsfs, mock_hook): ... def test_ge...
def test_get_fs_with_anonymous_credentials(self, mock_gcsfs, mock_hook): """Test that get_fs works with anonymous credentials.""" from google.auth.credentials import AnonymousCredentials from airflow.providers.google.cloud.fs.gcs import get_fs anonymous_creds = AnonymousCredentials() ...
test
1
{"function_name": "test_get_fs_with_anonymous_credentials", "class_name": "TestGCSFilesystem", "qualname": "TestGCSFilesystem.test_get_fs_with_anonymous_credentials", "file_path": "providers/google/tests/unit/google/cloud/fs/test_gcs.py", "repo_id": "apache/airflow", "loc": 17, "tested_modules": ["__future__", "airflow...
langchain-ai/langchain:libs/langchain_v1/tests/unit_tests/agents/middleware_typing/test_middleware_backwards_compat.py:test_old_pattern_1_unparameterized
# Context: from langchain_core.language_models.fake_chat_models import GenericFakeChatModel from langchain_core.messages import AIMessage, HumanMessage from langchain.agents import create_agent class OldStyleMiddleware1(AgentMiddleware): ... class OldStyleMiddleware2(AgentMiddleware[AgentState[Any], ContextT]): ... cl...
def test_old_pattern_1_unparameterized(fake_model: GenericFakeChatModel) -> None: """Old pattern 1: Completely unparameterized middleware.""" agent = create_agent( model=fake_model, middleware=[OldStyleMiddleware1()], ) result = agent.invoke({"messages": [HumanMessage(content="hi")]}) ...
test
1
{"function_name": "test_old_pattern_1_unparameterized", "class_name": null, "qualname": "test_old_pattern_1_unparameterized", "file_path": "libs/langchain_v1/tests/unit_tests/agents/middleware_typing/test_middleware_backwards_compat.py", "repo_id": "langchain-ai/langchain", "loc": 9, "tested_modules": ["__future__", "t...
run-llama/llama_index:llama-index-integrations/llms/llama-index-llms-baseten/llama_index/llms/baseten/utils.py:validate_model_slug
# Context: class Model(BaseModel): ... def is_supported_model_slug(model_id: str) -> bool: ... def get_supported_models() -> List[str]: ... def get_available_models_dynamic(client) -> List[Model]: ... def validate_model_dynamic(client, model_name: str) -> None: ... # Task: Write a Python function `validate_model_slug...
def validate_model_slug(model_id: str) -> None: """ Validate that the model_id is a supported model slug for Baseten Model APIs. Args: model_id: The model ID to validate Raises: ValueError: If the model_id is not a supported model slug """ if model_id not in SUPPORTED_MODEL_SL...
function_simple
1
{"cognitive_complexity": 1, "loc": 16, "code_loc": 5, "docstring_loc": 10, "function_name": "validate_model_slug", "class_name": null, "qualname": "validate_model_slug", "file_path": "llama-index-integrations/llms/llama-index-llms-baseten/llama_index/llms/baseten/utils.py", "repo_id": "run-llama/llama_index", "has_docs...
commaai/openpilot:system/ui/lib/tests/test_handle_state_change.py:TestDisconnected.test_new_activation_is_noop
# Context: from openpilot.system.ui.lib.networkmanager import NMDeviceState, NMDeviceStateReason from openpilot.system.ui.lib.wifi_manager import WifiManager, WifiState, ConnectStatus def _make_wm(mocker: MockerFixture, connections): ... def fire(wm: WifiManager, new_state: int, prev_state: int, reason: int) -> None: ...
def test_new_activation_is_noop(self, mocker): """NEW_ACTIVATION means NM is about to connect to another network — don't clear.""" wm = _make_wm(mocker) wm._wifi_state = WifiState(ssid="OldNet", status=ConnectStatus.CONNECTED) fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.NEW_ACTIVATI...
test
0
{"function_name": "test_new_activation_is_noop", "class_name": "TestDisconnected", "qualname": "TestDisconnected.test_new_activation_is_noop", "file_path": "system/ui/lib/tests/test_handle_state_change.py", "repo_id": "commaai/openpilot", "loc": 9, "tested_modules": ["jeepney.low_level", "openpilot.system.ui.lib.networ...
unclecode/crawl4ai:docs/examples/demo_multi_config_clean.py:print_section
Write a Python function `print_section` to print a formatted section header. Parameters: title
def print_section(title): """Print a formatted section header""" print(f"\n{'=' * 60}") print(f"{title}") print(f"{'=' * 60}\n")
function_simple
1
{"cognitive_complexity": 0, "loc": 5, "code_loc": 3, "docstring_loc": 1, "function_name": "print_section", "class_name": null, "qualname": "print_section", "file_path": "docs/examples/demo_multi_config_clean.py", "repo_id": "unclecode/crawl4ai", "has_docstring": true, "runnable_level": "self_contained"}
ray-project/ray:python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py:TestPrefixTreeInitialization.test_add_existing_tenant_noop
# Context: from ray.llm._internal.serve.routing_policies.prefix_aware.prefix_tree import ( Node, PrefixTree, PrefixTreeActor, ) def tree() -> PrefixTree: ... def tree_actor(): ... def get_lru_texts_from_tree(tree: PrefixTree, tenant_id: str) -> List[str]: ... async def get_lru_texts_from_tree_actor(tree_ac...
def test_add_existing_tenant_noop(self, tree: PrefixTree) -> None: """Test that adding an existing tenant via add_tenants is a no-op.""" tree.add_tenants(["tenant_1"], 0) assert tree.tenant_to_char_count == {"tenant_1": 0} assert tree.tenant_to_lru_tail.get("tenant_1") == tree.root ...
test
0
{"function_name": "test_add_existing_tenant_noop", "class_name": "TestPrefixTreeInitialization", "qualname": "TestPrefixTreeInitialization.test_add_existing_tenant_noop", "file_path": "python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py", "repo_id": "ray-project/ray", "loc": 14, "tested_modules": ["typing", ...
crewAIInc/crewAI:lib/crewai-files/tests/test_resolved.py:TestInlineBase64.test_create_inline_base64
# Context: from crewai_files.core.resolved import ( FileReference, InlineBase64, InlineBytes, ResolvedFile, UrlReference, ) class TestInlineBytes: ... class TestFileReference: ... class TestUrlReference: ... class TestInlineBase64: def test_inline_base64_is_resolved_file(self): ... def tes...
def test_create_inline_base64(self): """Test creating InlineBase64 instance.""" resolved = InlineBase64( content_type="image/png", data="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==", ) assert resolved.content_t...
test
0
{"function_name": "test_create_inline_base64", "class_name": "TestInlineBase64", "qualname": "TestInlineBase64.test_create_inline_base64", "file_path": "lib/crewai-files/tests/test_resolved.py", "repo_id": "crewAIInc/crewAI", "loc": 9, "tested_modules": ["datetime", "crewai_files.core.resolved"], "has_docstring": true,...
unslothai/unsloth:unsloth/kernels/moe/grouped_gemm/reference/moe_ops.py:permute
# Context: import torch def unpermute(X: torch.Tensor, gather_indices: torch.Tensor): ... def calculate_topk(gating_output: torch.Tensor, top_k: int, use_sigmoid: bool, renormalize: bool, pre_act: bool, post_act: bool): ... def get_routing_indices(selected_experts, num_experts, return_scatter_indices: bool): ... def t...
def permute(X: torch.Tensor, gather_indices: torch.Tensor, topk: int): """ Scatters X to a new tensor with shape [total_tokens, hidden_dim] where total_tokens is num_tokens * topk, permuting the tokens according to sorted_token_idx. Helper for grouped gemm where hidden states need be ordered by expert....
function_simple
0
{"cognitive_complexity": 1, "loc": 20, "code_loc": 5, "docstring_loc": 12, "function_name": "permute", "class_name": null, "qualname": "permute", "file_path": "unsloth/kernels/moe/grouped_gemm/reference/moe_ops.py", "repo_id": "unslothai/unsloth", "has_docstring": true, "runnable_level": "plib_runnable"}
apache/airflow:providers/amazon/tests/unit/amazon/aws/executors/ecs/test_utils.py:TestCamelizeDictKeys.test_camelize_dict_keys_with_mock
# Context: from unittest import mock from airflow.providers.amazon.aws.executors.ecs.utils import ( AllEcsConfigKeys, EcsExecutorException, EcsExecutorTask, EcsQueuedTask, EcsTaskCollection, EcsTaskInfo, RunTaskKwargsConfigKeys, _recursive_flatten_dict, camelize_dict_keys, parse_...
def test_camelize_dict_keys_with_mock(self, mock_camelize): """Test camelize_dict_keys with mocked camelize function.""" mock_camelize.side_effect = lambda x, uppercase_first_letter=False: f"camelized_{x}" input_dict = {"test_key": {"nested_key": "value"}} result = camelize_dict_keys(in...
test
1
{"function_name": "test_camelize_dict_keys_with_mock", "class_name": "TestCamelizeDictKeys", "qualname": "TestCamelizeDictKeys.test_camelize_dict_keys_with_mock", "file_path": "providers/amazon/tests/unit/amazon/aws/executors/ecs/test_utils.py", "repo_id": "apache/airflow", "loc": 10, "tested_modules": ["__future__", "...
apache/airflow:providers/teradata/tests/unit/teradata/utils/test_tpt_util.py:TestTptUtil.test_verify_tpt_utility_installed_not_found
# Context: from unittest.mock import Mock, patch import pytest from airflow.providers.teradata.utils.tpt_util import ( TPTConfig, decrypt_remote_file, execute_remote_command, get_remote_os, get_remote_temp_directory, is_valid_file, is_valid_remote_job_var_file, prepare_tdload_job_var_fil...
def test_verify_tpt_utility_installed_not_found(self, mock_which): """Test verify_tpt_utility_installed when utility is not found.""" mock_which.return_value = None with pytest.raises(FileNotFoundError, match="TPT utility 'tdload' is not installed"): verify_tpt_utility_installed("td...
test
1
{"function_name": "test_verify_tpt_utility_installed_not_found", "class_name": "TestTptUtil", "qualname": "TestTptUtil.test_verify_tpt_utility_installed_not_found", "file_path": "providers/teradata/tests/unit/teradata/utils/test_tpt_util.py", "repo_id": "apache/airflow", "loc": 6, "tested_modules": ["__future__", "airf...
apache/airflow:scripts/ci/prek/check_notice_files.py:license_header
Add a Apache-2.0 license header comment for the project 'airflow', authored by Unknown, year Unknown.
#!/usr/bin/env python # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "Li...
license
1
{"license_type": "Apache-2.0", "author": "Unknown", "year": "Unknown", "source": "header", "repo_id": "apache/airflow"}
vllm-project/vllm:vllm/model_executor/models/arcee.py:ArceeModel.load_weights
# Context: from collections.abc import Iterable import torch from vllm.model_executor.model_loader.weight_utils import ( default_weight_loader, maybe_remap_kv_scale_name, ) from .utils import ( AutoWeightsLoader, PPMissingLayer, is_pp_missing_parameter, make_empty_intermediate_tensors_factory, ...
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: """Load weights, mapping q/k/v projections to fused qkv_proj.""" stacked_params_mapping = [ (".qkv_proj", ".q_proj", "q"), (".qkv_proj", ".k_proj", "k"), (".qkv_proj", ".v_proj", "v"), ...
function_complex
1
{"cognitive_complexity": 37, "loc": 72, "code_loc": 56, "docstring_loc": 1, "function_name": "load_weights", "class_name": "ArceeModel", "qualname": "ArceeModel.load_weights", "file_path": "vllm/model_executor/models/arcee.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "runnable_level": "project_runnable"}
huggingface/transformers:src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py:PaddleOCRVLImageProcessor:class_doc
Write a class-level docstring for `PaddleOCRVLImageProcessor` (inherits from Qwen2VLImageProcessor) which has methods: `__init__`, `_preprocess`.
Constructs a PaddleOCRVL image processor that dynamically resizes images based on the original images. Args: do_resize (`bool`, *optional*, defaults to `True`): Whether to resize the image's (height, width) dimensions. size (`dict[str, int]`, *optional*): Size of the image after resizing. `shor...
documentation
0
{"doc_type": "class", "class_name": "PaddleOCRVLImageProcessor", "file_path": "src/transformers/models/paddleocr_vl/modular_paddleocr_vl.py", "repo_id": "huggingface/transformers", "char_length": 1892, "methods": ["__init__", "_preprocess"]}
browser-use/browser-use:tests/ci/test_action_loop_detection.py:test_scroll_different_elements_different_hash
# Context: from browser_use.agent.views import ( ActionLoopDetector, PageFingerprint, compute_action_hash, ) def _get_context_messages(agent: Agent) -> list[str]: ... def test_search_normalization_ignores_keyword_order(): ... def test_search_normalization_ignores_case(): ... def test_search_normalization_ignores_pu...
def test_scroll_different_elements_different_hash(): """Scrolling different elements produces different hashes.""" h1 = compute_action_hash('scroll', {'down': True, 'index': 5}) h2 = compute_action_hash('scroll', {'down': True, 'index': 10}) assert h1 != h2
test
0
{"function_name": "test_scroll_different_elements_different_hash", "class_name": null, "qualname": "test_scroll_different_elements_different_hash", "file_path": "tests/ci/test_action_loop_detection.py", "repo_id": "browser-use/browser-use", "loc": 5, "tested_modules": ["browser_use.agent.service", "browser_use.agent.vi...
karpathy/nanochat:nanochat/report.py:module_doc
Write a module-level docstring for the Python module `report` which contains function `run_command`, function `get_git_info`, function `get_gpu_info`, function `get_system_info`, function `estimate_cost`.
Utilities for generating training report cards. More messy code than usual, will fix.
documentation
0
{"doc_type": "module", "module_name": "report", "file_path": "nanochat/report.py", "repo_id": "karpathy/nanochat", "char_length": 85}
TheAlgorithms/Python:sorts/cyclic_sort.py:cyclic_sort
Write a Python function `cyclic_sort` to sorts the input list of n integers from 1 to n in-place. Parameters: nums: list[int] Returns: list[int]
def cyclic_sort(nums: list[int]) -> list[int]: """ Sorts the input list of n integers from 1 to n in-place using the Cyclic Sort algorithm. :param nums: List of n integers from 1 to n to be sorted. :return: The same list sorted in ascending order. Time complexity: O(n), where n is the number o...
function_simple
1
{"cognitive_complexity": 4, "loc": 32, "code_loc": 8, "docstring_loc": 15, "function_name": "cyclic_sort", "class_name": null, "qualname": "cyclic_sort", "file_path": "sorts/cyclic_sort.py", "repo_id": "TheAlgorithms/Python", "has_docstring": true, "runnable_level": "self_contained"}
ray-project/ray:ci/raydepsets/cli.py:DependencySetManager.relax
# Context: from typing import List, Optional import click def cli(): ... def build(config_path: str, workspace_dir: Optional[str], name: Optional[str], uv_cache_dir: Optional[str], check: Optional[bool], all_configs: Optional[bool]): ... def _get_bytes(packages: List[str]) -> bytes: ... def _get_depset(depsets: List[D...
def relax( self, source_depset: str, packages: List[str], name: str, output: str = None, ): """Relax a dependency set by removing specified packages from the lock file.""" source_depset = _get_depset(self.config.depsets, source_depset) lock_file_path ...
function_simple
0
{"cognitive_complexity": 4, "loc": 30, "code_loc": 17, "docstring_loc": 1, "function_name": "relax", "class_name": "DependencySetManager", "qualname": "DependencySetManager.relax", "file_path": "ci/raydepsets/cli.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "file_runnable"}
ray-project/ray:python/ray/train/tests/test_iter_torch_batches_gpu.py:BasePandasBatchCollateFn:class_doc
Write a class-level docstring for `BasePandasBatchCollateFn` (inherits from PandasBatchCollateFn) which has methods: `__init__`, `_process_batch`, `_get_tensors`.
Base class for Pandas batch collate functions that process and convert to tensors. This class provides common functionality for processing Pandas DataFrames and converting them to PyTorch tensors. It handles device placement and dtype conversion. Attributes: device: Optional device to place tensors on. Can be a s...
documentation
0
{"doc_type": "class", "class_name": "BasePandasBatchCollateFn", "file_path": "python/ray/train/tests/test_iter_torch_batches_gpu.py", "repo_id": "ray-project/ray", "char_length": 382, "methods": ["__init__", "_process_batch", "_get_tensors"]}
unclecode/crawl4ai:tests/cache_validation/test_head_fingerprint.py:TestHeadFingerprint.test_extracts_og_tags
# Context: from crawl4ai.utils import compute_head_fingerprint class TestHeadFingerprint: def test_same_content_same_fingerprint(self): ... def test_different_title_different_fingerprint(self): ... def test_empty_head_returns_empty_string(self): ... def test_head_without_signals_returns_empty(self): .....
def test_extracts_og_tags(self): """Open Graph tags are extracted.""" head1 = '<head><meta property="og:title" content="OG Title"></head>' head2 = '<head><meta property="og:title" content="Different OG Title"></head>' assert compute_head_fingerprint(head1) != compute_head_fingerprint(hea...
test
1
{"function_name": "test_extracts_og_tags", "class_name": "TestHeadFingerprint", "qualname": "TestHeadFingerprint.test_extracts_og_tags", "file_path": "tests/cache_validation/test_head_fingerprint.py", "repo_id": "unclecode/crawl4ai", "loc": 5, "tested_modules": ["crawl4ai.utils"], "has_docstring": true, "runnable_level...
crewAIInc/crewAI:lib/crewai/tests/agents/test_native_tool_calling.py:TestOpenAINativeToolCalling.test_openai_agent_with_native_tool_calling
# Context: import pytest from crewai import Agent, Crew, Task from crewai.llm import LLM class CalculatorInput(BaseModel): ... class CalculatorTool(BaseTool): ... class WeatherInput(BaseModel): ... class WeatherTool(BaseTool): ... class FailingTool(BaseTool): ... class LocalSearchInput(BaseModel): ... class ParallelPr...
def test_openai_agent_with_native_tool_calling( self, calculator_tool: CalculatorTool ) -> None: """Test OpenAI agent can use native tool calling.""" agent = Agent( role="Math Assistant", goal="Help users with mathematical calculations", backstory="You are...
test
0
{"function_name": "test_openai_agent_with_native_tool_calling", "class_name": "TestOpenAINativeToolCalling", "qualname": "TestOpenAINativeToolCalling.test_openai_agent_with_native_tool_calling", "file_path": "lib/crewai/tests/agents/test_native_tool_calling.py", "repo_id": "crewAIInc/crewAI", "loc": 26, "tested_modules...
ocrmypdf/OCRmyPDF:src/ocrmypdf/builtin_plugins/null_ocr.py:get_ocr_engine
# Context: class NullOcrEngine(OcrEngine): ... # Task: Write a Python function `get_ocr_engine` to return NullOcrEngine when --ocr-engine none is selected. Parameters: options
def get_ocr_engine(options): """Return NullOcrEngine when --ocr-engine none is selected.""" if options is not None: ocr_engine = getattr(options, 'ocr_engine', 'auto') if ocr_engine != 'none': return None return NullOcrEngine()
function_simple
1
{"cognitive_complexity": 3, "loc": 7, "code_loc": 5, "docstring_loc": 1, "function_name": "get_ocr_engine", "class_name": null, "qualname": "get_ocr_engine", "file_path": "src/ocrmypdf/builtin_plugins/null_ocr.py", "repo_id": "ocrmypdf/OCRmyPDF", "has_docstring": true, "runnable_level": "file_runnable"}
crewAIInc/crewAI:lib/crewai/tests/cli/authentication/providers/test_keycloak.py:TestKeycloakProvider.test_get_issuer_with_different_domain
# Context: from crewai.cli.authentication.main import Oauth2Settings from crewai.cli.authentication.providers.keycloak import KeycloakProvider class TestKeycloakProvider: def setup_method(self): ... def test_initialization_with_valid_settings(self): ... def test_get_authorize_url(self): ... def test_ge...
def test_get_issuer_with_different_domain(self): settings = Oauth2Settings( provider="keycloak", domain="login.myapp.io", client_id="test-client", audience="test-audience", extra={ "realm": "app-realm" } ) pr...
test
0
{"function_name": "test_get_issuer_with_different_domain", "class_name": "TestKeycloakProvider", "qualname": "TestKeycloakProvider.test_get_issuer_with_different_domain", "file_path": "lib/crewai/tests/cli/authentication/providers/test_keycloak.py", "repo_id": "crewAIInc/crewAI", "loc": 13, "tested_modules": ["crewai.c...
huggingface/transformers:tests/models/granitemoehybrid/test_modeling_granitemoehybrid.py:GraniteMoeHybridIntegrationTest.test_model_logits
# Context: from parameterized import parameterized import torch from transformers import ( GraniteMoeHybridForCausalLM, GraniteMoeHybridModel, ) class GraniteMoeHybridModelTester(BambaModelTester): ... class GraniteMoeHybridModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, uni...
def test_model_logits(self, device): input_ids = [31390, 631, 4162, 30, 322, 25342, 432, 1875, 43826, 10066, 688, 225] model = GraniteMoeHybridForCausalLM.from_pretrained("ibm-granite/granite-4.0-h-tiny", device_map=device) with torch.no_grad(): out = model(torch.tensor([input_ids]...
test
0
{"function_name": "test_model_logits", "class_name": "GraniteMoeHybridIntegrationTest", "qualname": "GraniteMoeHybridIntegrationTest.test_model_logits", "file_path": "tests/models/granitemoehybrid/test_modeling_granitemoehybrid.py", "repo_id": "huggingface/transformers", "loc": 30, "tested_modules": ["parameterized", "...
ray-project/ray:python/ray/llm/_internal/batch/constants.py:TaskType.values
# Context: class vLLMTaskType(TaskType): ... class SGLangTaskType(TaskType): ... class TaskType: # Task: Write a Python method `values` for the class `TaskType` to return a set of all valid task type values.
def values(cls): """Return a set of all valid task type values.""" return { value for key, value in vars(cls).items() if not key.startswith("_") and isinstance(value, str) }
function_simple
0
{"cognitive_complexity": 0, "loc": 7, "code_loc": 5, "docstring_loc": 1, "function_name": "values", "class_name": "TaskType", "qualname": "TaskType.values", "file_path": "python/ray/llm/_internal/batch/constants.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "file_runnable"}
ray-project/ray:python/ray/data/util/torch_utils.py:tensorize
# Context: import numpy as np import pandas as pd import torch def convert_pandas_to_torch_tensor(data_batch: pd.DataFrame, columns: Optional[Union[List[str], List[List[str]]]], column_dtypes: Optional[Union[torch.dtype, List[torch.dtype]]], unsqueeze: bool) -> Union[torch.Tensor, List[torch.Tensor]]: ... def convert_...
def tensorize(vals, dtype): """This recursive function allows to convert pyarrow List dtypes to multi-dimensional tensors.""" if isinstance(vals, pd.api.extensions.ExtensionArray): # torch.as_tensor() does not yet support the __array__ protocol, so we need # to convert ex...
function_simple
0
{"cognitive_complexity": 4, "loc": 23, "code_loc": 10, "docstring_loc": 2, "function_name": "tensorize", "class_name": null, "qualname": "tensorize", "file_path": "python/ray/data/util/torch_utils.py", "repo_id": "ray-project/ray", "has_docstring": true, "runnable_level": "plib_runnable"}
huggingface/transformers:src/transformers/models/qwen3_vl/modular_qwen3_vl.py:Qwen3VLTextModel.forward
# Context: import torch from ...cache_utils import Cache, DynamicCache from ...masking_utils import create_causal_mask from ...modeling_flash_attention_utils import FlashAttentionKwargs from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling from ...processing_utils import ProcessingKwargs, ...
def forward( self, input_ids: torch.LongTensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.LongTensor | None = None, past_key_values: Cache | None = None, inputs_embeds: torch.FloatTensor | None = None, use_cache: bool | None = N...
function_complex
0
{"cognitive_complexity": 16, "loc": 91, "code_loc": 52, "docstring_loc": 8, "function_name": "forward", "class_name": "Qwen3VLTextModel", "qualname": "Qwen3VLTextModel.forward", "file_path": "src/transformers/models/qwen3_vl/modular_qwen3_vl.py", "repo_id": "huggingface/transformers", "has_docstring": true, "runnable_l...
browser-use/browser-use:browser_use/browser/session.py:BrowserSession.cdp_client_for_frame
# Context: class Target(BaseModel): ... class CDPSession(BaseModel): ... class BrowserSession(BaseModel): model_config = ConfigDict( def __init__( self, *, # Cloud browser params - use these for cloud mode cloud_profile_id: UUID | str | None = None, cloud_proxy_country_code: ProxyCountryCode | None = N...
async def cdp_client_for_frame(self, frame_id: str) -> CDPSession: """Get a CDP client attached to the target containing the specified frame. Builds a unified frame hierarchy from all targets to find the correct target for any frame, including OOPIFs (Out-of-Process iframes). Args: frame_id: The frame ID t...
function_simple
0
{"cognitive_complexity": 4, "loc": 37, "code_loc": 11, "docstring_loc": 14, "function_name": "cdp_client_for_frame", "class_name": "BrowserSession", "qualname": "BrowserSession.cdp_client_for_frame", "file_path": "browser_use/browser/session.py", "repo_id": "browser-use/browser-use", "has_docstring": true, "runnable_le...
ray-project/ray:python/ray/data/tests/test_join.py:test_join_with_unjoinable_non_key_columns
# Context: import numpy as np import pytest from packaging.version import parse as parse_version import ray from ray.data._internal.utils.arrow_utils import get_pyarrow_version def test_simple_inner_join(ray_start_regular_shared_2_cpus, num_rows_left: int, num_rows_right: int, partition_size_hint: Optional[int]): ... ...
def test_join_with_unjoinable_non_key_columns( ray_start_regular_shared_2_cpus, join_type ): """Test that joins work correctly when non-key columns have unjoinable types.""" # Left dataset with joinable key but unjoinable non-key columns # Create test data - centralized for clarity and maintainability ...
test
0
{"function_name": "test_join_with_unjoinable_non_key_columns", "class_name": null, "qualname": "test_join_with_unjoinable_non_key_columns", "file_path": "python/ray/data/tests/test_join.py", "repo_id": "ray-project/ray", "loc": 138, "tested_modules": ["typing", "packaging.version", "ray.data._internal.logical.operators...
huggingface/diffusers:tests/models/testing_utils/quantization.py:TorchAoConfigMixin:class_doc
Write a class-level docstring for `TorchAoConfigMixin` which has methods: `_create_quantized_model`, `_verify_if_layer_quantized`.
Base mixin providing TorchAO quantization config and model creation. Expected class attributes: - model_class: The model class to test - pretrained_model_name_or_path: Hub repository ID for the pretrained model - pretrained_model_kwargs: (Optional) Dict of kwargs to pass to from_pretrained
documentation
1
{"doc_type": "class", "class_name": "TorchAoConfigMixin", "file_path": "tests/models/testing_utils/quantization.py", "repo_id": "huggingface/diffusers", "char_length": 303, "methods": ["_create_quantized_model", "_verify_if_layer_quantized"]}
ray-project/ray:python/ray/serve/taskiq_task_processor.py:TaskiqTaskProcessorAdapter.initialize
# Context: from ray.serve._private.constants import ( DEFAULT_CONSUMER_CONCURRENCY, SERVE_LOGGER_NAME, ) from taskiq_redis import RedisAsyncResultBackend def _import_broker_class(broker_type: str): ... def _create_broker(broker_type: str, queue_name: str, broker_kwargs: Optional[Dict[str, Any]]): ... class Tas...
def initialize(self, consumer_concurrency: int = DEFAULT_CONSUMER_CONCURRENCY): """Initialize the taskiq broker and result backend.""" self._consumer_concurrency = consumer_concurrency adapter_config: TaskiqAdapterConfig = self._config.adapter_config # Create the broker using the factor...
function_simple
0
{"cognitive_complexity": 1, "loc": 25, "code_loc": 17, "docstring_loc": 1, "function_name": "initialize", "class_name": "TaskiqTaskProcessorAdapter", "qualname": "TaskiqTaskProcessorAdapter.initialize", "file_path": "python/ray/serve/taskiq_task_processor.py", "repo_id": "ray-project/ray", "has_docstring": true, "runna...
ray-project/ray:python/ray/data/tests/test_downstream_capacity_backpressure_policy.py:TestDownstreamCapacityBackpressurePolicy.test_no_backpressure_low_queue_ratio
# Context: from ray.data._internal.execution.backpressure_policy.downstream_capacity_backpressure_policy import ( DownstreamCapacityBackpressurePolicy, ) class TestDownstreamCapacityBackpressurePolicy: def setup_budget_fraction_mock(self): ... def _mock_operator(self, op_class: type, num_tasks_running: int...
def test_no_backpressure_low_queue_ratio(self): """Test no backpressure when queue/capacity ratio is acceptable.""" op, op_state = self._mock_operator() downstream_op, downstream_op_state = self._mock_operator() op.output_dependencies = [downstream_op] topology = {op: op_state, d...
test
0
{"function_name": "test_no_backpressure_low_queue_ratio", "class_name": "TestDownstreamCapacityBackpressurePolicy", "qualname": "TestDownstreamCapacityBackpressurePolicy.test_no_backpressure_low_queue_ratio", "file_path": "python/ray/data/tests/test_downstream_capacity_backpressure_policy.py", "repo_id": "ray-project/r...
vllm-project/vllm:vllm/model_executor/models/isaac.py:process_vision_for_patches
# Context: import torch import torch.nn.functional as F def create_cumulative_seq_lengths(seq_sizes: torch.Tensor, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]: ... class Siglip2VariableSequenceEmbeddings(nn.Module): ... def create_pixel_shuffle_index_map(seq_sizes: torch.Tensor, token_grids: torch.Tenso...
def process_vision_for_patches( images: torch.Tensor, patch_size: int, max_num_patches: int, min_num_patches: int | None = None, pixel_shuffle_scale: int = 1, ) -> tuple[torch.Tensor, list[int]]: r"""Resize, normalize, and patchify RGB images for the vision encoder. Args: images (`t...
function_simple
1
{"cognitive_complexity": 2, "loc": 76, "code_loc": 28, "docstring_loc": 25, "function_name": "process_vision_for_patches", "class_name": null, "qualname": "process_vision_for_patches", "file_path": "vllm/model_executor/models/isaac.py", "repo_id": "vllm-project/vllm", "has_docstring": true, "runnable_level": "file_runn...
666ghj/BettaFish:ReportEngine/flask_interface.py:_broadcast_event
# Context: from typing import Dict, Any, List, Optional from loguru import logger def _is_excluded_engine_log(record: Dict[str, Any]) -> bool: ... def _stream_log_to_task(message): ... def _setup_log_stream_forwarder(): ... def _register_stream(task_id: str) -> Queue: ... def _unregister_stream(task_id: str, queue: Qu...
def _broadcast_event(task_id: str, event: Dict[str, Any]): """ 将事件推送给所有监听者,失败时做好异常捕获。 采用浅拷贝监听列表,防止并发移除导致遍历异常。 参数: task_id: 待推送的任务ID。 event: 结构化事件payload。 """ with stream_lock: listeners = list(stream_subscribers.get(task_id, [])) for queue in listeners: try:...
function_simple
1
{"cognitive_complexity": 2, "loc": 17, "code_loc": 7, "docstring_loc": 9, "function_name": "_broadcast_event", "class_name": null, "qualname": "_broadcast_event", "file_path": "ReportEngine/flask_interface.py", "repo_id": "666ghj/BettaFish", "has_docstring": true, "runnable_level": "file_runnable"}
ray-project/ray:python/ray/tests/unit/test_runtime_env.py:test_runtime_env_merge
# Context: from ray.runtime_env.runtime_env import ( RuntimeEnvConfig, _merge_runtime_env, ) def test_current_py_version_supported(): ... def test_compatible_with_dataclasses(): ... def test_container_option_serialize(runtime_env_class): ... class TestURICache: ... def enable_dev_mode(local_env_var_enabled, mo...
def test_runtime_env_merge(): # Both are None. parent = None child = None assert _merge_runtime_env(parent, child) == {} parent = {} child = None assert _merge_runtime_env(parent, child) == {} parent = None child = {} assert _merge_runtime_env(parent, child) == {} parent =...
test
0
{"function_name": "test_runtime_env_merge", "class_name": null, "qualname": "test_runtime_env_merge", "file_path": "python/ray/tests/unit/test_runtime_env.py", "repo_id": "ray-project/ray", "loc": 63, "tested_modules": ["dataclasses", "typing", "ray._private.runtime_env.uri_cache", "ray._private.runtime_env.utils", "ra...
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/routers/article_router.py:read_articles
# Context: from fastapi import APIRouter, Query from typing import List, Optional, Dict, Any from models.article_schemas import Article, PaginatedArticles from services.article_service import article_service async def read_article(article_id: int): ... async def read_sources(): ... async def read_categories(): ... # ...
async def read_articles( page: int = Query(1, ge=1, description="Page number"), per_page: int = Query(10, ge=1, le=100, description="Items per page"), source: Optional[str] = Query(None, description="Filter by source name"), category: Optional[str] = Query(None, description="Filter by category"), da...
function_simple
0
{"cognitive_complexity": 0, "loc": 23, "code_loc": 3, "docstring_loc": 11, "function_name": "read_articles", "class_name": null, "qualname": "read_articles", "file_path": "advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/routers/article_router.py", "repo_id": "Shubhamsaboo/awesome-llm-apps", "has_...
vllm-project/vllm:tests/reasoning/test_deepseekv3_reasoning_parser.py:test_parser_selection
# Context: import pytest from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser from vllm.reasoning.deepseek_v3_reasoning_parser import DeepSeekV3ReasoningParser from vllm.reasoning.identity_reasoning_parser import IdentityReasoningParser def tokenizer(): ... def test_identity_reasoning_pars...
def test_parser_selection(tokenizer, thinking, expected_parser_type): parser = DeepSeekV3ReasoningParser( tokenizer, chat_template_kwargs={"thinking": thinking} ) assert isinstance(parser._parser, expected_parser_type)
test
1
{"function_name": "test_parser_selection", "class_name": null, "qualname": "test_parser_selection", "file_path": "tests/reasoning/test_deepseekv3_reasoning_parser.py", "repo_id": "vllm-project/vllm", "loc": 6, "tested_modules": ["transformers", "vllm.entrypoints.openai.chat_completion.protocol", "vllm.entrypoints.opena...
huggingface/transformers:src/transformers/trainer_optimizer.py:_get_bitsandbytes_optimizer
# Context: from typing import TYPE_CHECKING, Any from .utils import ( is_apollo_torch_available, is_bitsandbytes_available, is_galore_torch_available, is_grokadamw_available, is_lomo_available, is_schedulefree_available, is_torch_optimi_available, is_torchao_available, strtobool, ) f...
def _get_bitsandbytes_optimizer(ctx: OptimizerContext) -> tuple[Any, dict[str, Any]]: """Get bitsandbytes optimizer (AdamW, Lion, RMSprop variants).""" if not is_bitsandbytes_available(): raise ImportError( "You need to install `bitsandbytes` in order to use bitsandbytes optimizers: `pip ins...
function_complex
0
{"cognitive_complexity": 11, "loc": 48, "code_loc": 40, "docstring_loc": 1, "function_name": "_get_bitsandbytes_optimizer", "class_name": null, "qualname": "_get_bitsandbytes_optimizer", "file_path": "src/transformers/trainer_optimizer.py", "repo_id": "huggingface/transformers", "has_docstring": true, "runnable_level":...
ray-project/ray:python/ray/data/tests/test_download_expression.py:TestDownloadExpressionErrors.test_download_expression_with_malformed_uris
# Context: import ray from ray.data.expressions import DownloadExpr, col, download class TestDownloadExpressionStructure: ... class TestDownloadExpressionFunctionality: ... class TestDownloadExpressionIntegration: ... class TestDownloadExpressionErrors: def test_download_expression_invalid_uri_column(self): ... ...
def test_download_expression_with_malformed_uris(self, tmp_path): """Test download expression with malformed URIs. This tests that various malformed URIs are caught and return None instead of crashing. All of the URIs should be malformed in order to test the ZeroDivisionError d...
test
0
{"function_name": "test_download_expression_with_malformed_uris", "class_name": "TestDownloadExpressionErrors", "qualname": "TestDownloadExpressionErrors.test_download_expression_with_malformed_uris", "file_path": "python/ray/data/tests/test_download_expression.py", "repo_id": "ray-project/ray", "loc": 32, "tested_modu...
crewAIInc/crewAI:lib/crewai/tests/utilities/test_pydantic_schema_utils.py:TestEnsureTypeInSchemas.test_empty_schema_in_anyof_gets_type
# Context: from copy import deepcopy from crewai.utilities.pydantic_schema_utils import ( build_rich_field_description, convert_oneof_to_anyof, create_model_from_schema, ensure_all_properties_required, ensure_type_in_schemas, force_additional_properties_false, resolve_refs, strip_null_fr...
def test_empty_schema_in_anyof_gets_type(self) -> None: schema = {"anyOf": [{}, {"type": "string"}]} result = ensure_type_in_schemas(deepcopy(schema)) assert result["anyOf"][0] == {"type": "object"}
test
0
{"function_name": "test_empty_schema_in_anyof_gets_type", "class_name": "TestEnsureTypeInSchemas", "qualname": "TestEnsureTypeInSchemas.test_empty_schema_in_anyof_gets_type", "file_path": "lib/crewai/tests/utilities/test_pydantic_schema_utils.py", "repo_id": "crewAIInc/crewAI", "loc": 4, "tested_modules": ["__future__"...
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/routers/social_media_router.py:read_engagement_stats
# Context: from fastapi import APIRouter, Query from typing import List, Optional, Dict, Any from services.social_media_service import social_media_service async def read_posts(page: int, per_page: int, platform: Optional[str], user_handle: Optional[str], sentiment: Optional[str], category: Optional[str], date_from: O...
async def read_engagement_stats( date_from: Optional[str] = Query(None, description="Filter by start date (format: YYYY-MM-DD)"), date_to: Optional[str] = Query(None, description="Filter by end date (format: YYYY-MM-DD)"), ): """Get overall engagement statistics.""" return await social_media_service.get...
function_simple
0
{"cognitive_complexity": 0, "loc": 6, "code_loc": 1, "docstring_loc": 1, "function_name": "read_engagement_stats", "class_name": null, "qualname": "read_engagement_stats", "file_path": "advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/routers/social_media_router.py", "repo_id": "Shubhamsaboo/aweso...
ray-project/ray:ci/ray_ci/test_supported_images.py:TestRayImagesSchema.test_python_versions_are_strings
# Context: import pytest from ci.ray_ci.supported_images import get_image_config, load_supported_images class TestRayImagesSchema: def test_has_image_types(self): ... def test_required_keys(self, image_type): ... def test_required_defaults(self, image_type): ... def test_defaults_in_supported(self, ima...
def test_python_versions_are_strings(self, image_type): for v in get_image_config(image_type)["python"]: assert isinstance(v, str), ( f"{image_type}: python version {v!r} is {type(v).__name__}, " f"not str (missing quotes in YAML?)" )
test
0
{"function_name": "test_python_versions_are_strings", "class_name": "TestRayImagesSchema", "qualname": "TestRayImagesSchema.test_python_versions_are_strings", "file_path": "ci/ray_ci/test_supported_images.py", "repo_id": "ray-project/ray", "loc": 6, "tested_modules": ["ci.ray_ci.supported_images"], "has_docstring": fal...
huggingface/transformers:tests/trainer/test_trainer_checkpointing.py:JITCheckpointTest.test_jit_checkpoint_callback_on_train_end
# Context: import signal from unittest.mock import Mock, patch from transformers.trainer_jit_checkpoint import CheckpointManager, JITCheckpointCallback class TrainerCheckpointSaveTest(TestCasePlus, TrainerIntegrationCommon): ... class TrainerResumeTrainingTest(TestCasePlus, TrainerIntegrationCommon): ... class Trainer...
def test_jit_checkpoint_callback_on_train_end(self): """Test signal handler restoration on training end.""" trainer = self.get_trainer() callback = JITCheckpointCallback() # Store original SIGTERM handler original_handler = signal.signal(signal.SIGTERM, signal.SIG_DFL) ...
test
0
{"function_name": "test_jit_checkpoint_callback_on_train_end", "class_name": "JITCheckpointTest", "qualname": "JITCheckpointTest.test_jit_checkpoint_callback_on_train_end", "file_path": "tests/trainer/test_trainer_checkpointing.py", "repo_id": "huggingface/transformers", "loc": 27, "tested_modules": ["pathlib", "typing...
huggingface/transformers:tests/models/eomt/test_image_processing_eomt.py:EomtImageProcessingTest.test_call_numpy
# Context: import numpy as np class EomtImageProcessingTester: ... def prepare_semantic_single_inputs(): ... def prepare_semantic_batch_inputs(): ... class EomtImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = EomtImageProcessor if is_vision_available() else None fast_...
def test_call_numpy(self): for image_processing_class in self.image_processor_list: # Initialize image_processing image_processing = image_processing_class(**self.image_processor_dict) # create random numpy tensors image_inputs = self.image_processor_tester.prepar...
test
0
{"function_name": "test_call_numpy", "class_name": "EomtImageProcessingTest", "qualname": "EomtImageProcessingTest.test_call_numpy", "file_path": "tests/models/eomt/test_image_processing_eomt.py", "repo_id": "huggingface/transformers", "loc": 18, "tested_modules": ["datasets", "transformers.image_utils", "transformers....
vllm-project/vllm:tests/kernels/helion/test_silu_mul_fp8.py:TestSiluMulFp8ConfigPicker.test_config_picker_default_ignored_when_valid_keys_exist
# Context: import torch from vllm.kernels.helion.ops.silu_mul_fp8 import ( pick_silu_mul_fp8_config, silu_mul_fp8, silu_mul_fp8_baseline, ) def skip_if_platform_unsupported(): ... def reset_config_manager_singleton(): ... class TestSiluMulFp8Correctness: ... def silu_mul_fp8_pytorch(input: torch.Tensor, sc...
def test_config_picker_default_ignored_when_valid_keys_exist(self): """'default' is skipped in favor of a real match.""" config_keys = [ "default", "intermediate_4096_numtokens_32", "intermediate_4096_numtokens_128", ] input_tensor = torch.randn(64, 81...
test
1
{"function_name": "test_config_picker_default_ignored_when_valid_keys_exist", "class_name": "TestSiluMulFp8ConfigPicker", "qualname": "TestSiluMulFp8ConfigPicker.test_config_picker_default_ignored_when_valid_keys_exist", "file_path": "tests/kernels/helion/test_silu_mul_fp8.py", "repo_id": "vllm-project/vllm", "loc": 12...
browser-use/browser-use:browser_use/llm/ollama/serializer.py:OllamaMessageSerializer._serialize_tool_calls
# Context: import json from ollama._types import Image, Message from browser_use.llm.messages import ( AssistantMessage, BaseMessage, SystemMessage, ToolCall, UserMessage, ) class OllamaMessageSerializer: def _extract_text_content(content: Any) -> str: ... def _extract_images(content: Any) -> list[Image]:...
def _serialize_tool_calls(tool_calls: list[ToolCall]) -> list[Message.ToolCall]: """Convert browser-use ToolCalls to Ollama ToolCalls.""" ollama_tool_calls: list[Message.ToolCall] = [] for tool_call in tool_calls: # Parse arguments from JSON string to dict for Ollama try: arguments_dict = json.loads(to...
function_simple
0
{"cognitive_complexity": 2, "loc": 18, "code_loc": 11, "docstring_loc": 1, "function_name": "_serialize_tool_calls", "class_name": "OllamaMessageSerializer", "qualname": "OllamaMessageSerializer._serialize_tool_calls", "file_path": "browser_use/llm/ollama/serializer.py", "repo_id": "browser-use/browser-use", "has_docst...
langflow-ai/langflow:src/lfx/tests/unit/cli/test_common.py:TestApiKey.test_get_api_key_not_set
# Context: import os from unittest.mock import MagicMock, Mock, patch import pytest from lfx.cli.common import ( create_verbose_printer, execute_graph_with_capture, extract_result_data, flow_id_from_path, get_api_key, get_best_access_host, get_free_port, is_port_in_use, load_graph_fr...
def test_get_api_key_not_set(self): """Test error when API key is not set.""" with ( patch.dict(os.environ, {}, clear=True), pytest.raises(ValueError, match="LANGFLOW_API_KEY environment variable is not set"), ): get_api_key()
test
1
{"function_name": "test_get_api_key_not_set", "class_name": "TestApiKey", "qualname": "TestApiKey.test_get_api_key_not_set", "file_path": "src/lfx/tests/unit/cli/test_common.py", "repo_id": "langflow-ai/langflow", "loc": 7, "tested_modules": ["pathlib", "lfx.cli.common"], "has_docstring": true, "runnable_level": "proje...
ray-project/ray:python/ray/serve/tests/test_metrics_haproxy.py:test_replica_metrics_fields
# Context: import httpx from ray import serve from ray._common.test_utils import ( SignalActor, fetch_prometheus_metrics, wait_for_condition, ) from ray.serve._private.test_utils import get_application_url, get_metric_dictionaries def metrics_start_shutdown(request): ... def extract_tags(line: str) -> Dict...
def test_replica_metrics_fields(metrics_start_shutdown): """Test replica metrics fields""" @serve.deployment def f(): return "hello" @serve.deployment def g(): return "world" serve.run(f.bind(), name="app1", route_prefix="/f") serve.run(g.bind(), name="app2", route_prefix=...
test
0
{"function_name": "test_replica_metrics_fields", "class_name": null, "qualname": "test_replica_metrics_fields", "file_path": "python/ray/serve/tests/test_metrics_haproxy.py", "repo_id": "ray-project/ray", "loc": 118, "tested_modules": ["concurrent.futures", "typing", "fastapi", "starlette.requests", "starlette.response...
huggingface/transformers:tests/models/pp_doclayout_v2/test_modeling_pp_doclayout_v2.py:PPDocLayoutV2ModelTest.test_forward_signature
# Context: import inspect class PPDocLayoutV2ModelTester: ... class PPDocLayoutV2ModelIntegrationTest(unittest.TestCase): ... class PPDocLayoutV2ModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (PPDocLayoutV2ForObjectDetection,) if is_torch_available() else () pipeline_...
def test_forward_signature(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) signature = inspect.signature(model.forward) arg_names = [*signature.parameters.keys()] ...
test
0
{"function_name": "test_forward_signature", "class_name": "PPDocLayoutV2ModelTest", "qualname": "PPDocLayoutV2ModelTest.test_forward_signature", "file_path": "tests/models/pp_doclayout_v2/test_modeling_pp_doclayout_v2.py", "repo_id": "huggingface/transformers", "loc": 9, "tested_modules": ["parameterized", "transformer...
browser-use/browser-use:tests/ci/test_search_find.py:TestFindElements.test_empty_page
# Context: from browser_use.agent.views import ActionResult def http_server(): ... def base_url(http_server): ... async def browser_session(): ... def tools(): ... async def _navigate_and_wait(tools, browser_session, url): ... class TestSearchPage: ... class TestRegistration: ... class TestFindElements: async def...
async def test_empty_page(self, tools, browser_session, base_url): """Works on a nearly empty page without errors.""" await _navigate_and_wait(tools, browser_session, f'{base_url}/empty') result = await tools.find_elements(selector='p', browser_session=browser_session) assert isinstance(result, ActionResult) ...
test
0
{"function_name": "test_empty_page", "class_name": "TestFindElements", "qualname": "TestFindElements.test_empty_page", "file_path": "tests/ci/test_search_find.py", "repo_id": "browser-use/browser-use", "loc": 10, "tested_modules": ["browser_use.agent.views", "browser_use.browser", "browser_use.tools.service"], "has_doc...
langflow-ai/langflow:src/lfx/src/lfx/custom/utils.py:build_custom_components
# Context: from lfx.custom.directory_reader.utils import ( abuild_custom_component_list_from_path, build_custom_component_list_from_path, merge_nested_dicts_with_renaming, ) from lfx.log.logger import logger def _generate_code_hash(source_code: str, modname: str) -> str: ... class UpdateBuildConfigError(Ex...
def build_custom_components(components_paths: list[str]): """Build custom components from the specified paths.""" if not components_paths: return {} logger.info(f"Building custom components from {components_paths}") custom_components_from_file: dict = {} processed_paths = set() for pat...
function_complex
1
{"cognitive_complexity": 6, "loc": 24, "code_loc": 18, "docstring_loc": 1, "function_name": "build_custom_components", "class_name": null, "qualname": "build_custom_components", "file_path": "src/lfx/src/lfx/custom/utils.py", "repo_id": "langflow-ai/langflow", "has_docstring": true, "runnable_level": "project_runnable"...
huggingface/transformers:tests/kernels/test_kernels.py:TestHubKernels.test_kernelize
# Context: import copy from kernels import Device, Mode, kernelize class TestKernelsEnv(TestCasePlus): ... class TestKernelUtilities(TestCasePlus): ... class TestAttentionKernelRegistration(TestCasePlus): ... class TestUseKernelsLifecycle(TestCasePlus): ... class TestKernelMappingDeviceFiltering(TestCasePlus): ... cl...
def test_kernelize(self): model = copy.deepcopy(self.model_not_kernelized) kernelize(model, mode=Mode.INFERENCE, device=Device(type=model.device.type)) # type: ignore[arg-type] self.assert_kernelized_forward_is_different(model, self.model_not_kernelized) self.assert_kernelized_forward_i...
test
0
{"function_name": "test_kernelize", "class_name": "TestHubKernels", "qualname": "TestHubKernels.test_kernelize", "file_path": "tests/kernels/test_kernels.py", "repo_id": "huggingface/transformers", "loc": 6, "tested_modules": ["transformers", "transformers.integrations.hub_kernels", "transformers.masking_utils", "trans...
huggingface/transformers:tests/models/auto/test_video_processing_auto.py:AutoVideoProcessorTest.test_video_processor_not_found
# Context: from transformers import ( CONFIG_MAPPING, VIDEO_PROCESSOR_MAPPING, AutoConfig, AutoVideoProcessor, LlavaOnevisionConfig, LlavaOnevisionVideoProcessor, ) class AutoVideoProcessorTest(unittest.TestCase): def setUp(self): ... def test_video_processor_from_model_shortcut(self): ...
def test_video_processor_not_found(self): with self.assertRaisesRegex( EnvironmentError, "Can't load video processor for 'hf-internal-testing/config-no-model'.", ): _ = AutoVideoProcessor.from_pretrained("hf-internal-testing/config-no-model")
test
0
{"function_name": "test_video_processor_not_found", "class_name": "AutoVideoProcessorTest", "qualname": "AutoVideoProcessorTest.test_video_processor_not_found", "file_path": "tests/models/auto/test_video_processing_auto.py", "repo_id": "huggingface/transformers", "loc": 6, "tested_modules": ["pathlib", "transformers", ...
langflow-ai/langflow:src/backend/tests/unit/base/tools/test_run_flow.py:TestRunFlowBaseComponentInputOutputHandling.test_format_flow_outputs_creates_output_objects
# Context: from unittest.mock import AsyncMock, MagicMock, Mock, PropertyMock, patch from lfx.base.tools.run_flow import RunFlowBaseComponent from lfx.graph.graph.base import Graph from lfx.template.field.base import Output def mock_shared_cache(): ... class TestRunFlowBaseComponentInitialization: ... class TestRunFlo...
def test_format_flow_outputs_creates_output_objects(self): """Test that _format_flow_outputs creates Output objects from graph.""" component = RunFlowBaseComponent() mock_vertex = MagicMock() mock_vertex.id = "vertex_123" mock_vertex.is_output = True mock_vertex.outputs ...
test
1
{"function_name": "test_format_flow_outputs_creates_output_objects", "class_name": "TestRunFlowBaseComponentInputOutputHandling", "qualname": "TestRunFlowBaseComponentInputOutputHandling.test_format_flow_outputs_creates_output_objects", "file_path": "src/backend/tests/unit/base/tools/test_run_flow.py", "repo_id": "lang...
huggingface/transformers:src/transformers/models/jetmoe/modular_jetmoe.py:JetMoeAttention.__init__
# Context: import torch from .configuration_jetmoe import JetMoeConfig class JetMoeRMSNorm(MixtralRMSNorm): ... class JetMoeRotaryEmbedding(MixtralRotaryEmbedding): ... class JetMoeParallelExperts(nn.Module): ... class JetMoeTopKGating(nn.Module): ... class JetMoeMoE(nn.Module): ... class JetMoeMoA(nn.Module): ... cla...
def __init__(self, config: JetMoeConfig, layer_idx: int | None = None): """ Initialize the JetMoeAttention module. Args: config: Configuration object with model hyperparameters. layer_idx: Index of the layer in the model. """ ...
function_simple
0
{"cognitive_complexity": 1, "loc": 32, "code_loc": 20, "docstring_loc": 9, "function_name": "__init__", "class_name": "JetMoeAttention", "qualname": "JetMoeAttention.__init__", "file_path": "src/transformers/models/jetmoe/modular_jetmoe.py", "repo_id": "huggingface/transformers", "has_docstring": true, "runnable_level"...