input
string
label
int64
category
string
sample_id
string
sampled_videos = [] sampled_metadata = [] for video, metadata in zip(videos, video_metadata): indices = sample_indices_fn(metadata=metadata) metadata.frames_indices = indices sampled_videos.append(video[indices]) sampled_metadat...
0
function_complex
huggingface/transformers:src/transformers/video_processing_utils.py:BaseVideoProcessor._decode_and_sample_videos
researcher: Agent, simple_task: Task ) -> None: """Test basic streaming example from documentation.""" crew = Crew( agents=[researcher], tasks=[simple_task], stream=True, verbose=False, ) streaming = crew.kickoff(inputs={"topic": "art...
0
test
crewAIInc/crewAI:lib/crewai/tests/test_streaming_integration.py:TestStreamingCrewIntegration.test_basic_crew_streaming_from_docs
""" sync_queue: queue.Queue[StreamChunk | None | Exception] = queue.Queue() async_queue: asyncio.Queue[StreamChunk | None | Exception] | None = None loop: asyncio.AbstractEventLoop | None = None if use_async: async_queue = asyncio.Queue() loop = asyncio.get_event_loop() handler = ...
0
function_simple
crewAIInc/crewAI:lib/crewai/src/crewai/utilities/streaming.py:create_streaming_state
sample_weight: Sample weights (currently unused). training: Whether the model is in training mode. Returns: Combined loss tensor. """ # Handle case where y_pred is not provided if y_pred is None: y_pred = self(x, training=training) # ...
1
function_complex
keras-team/keras:keras/src/distillation/distiller.py:Distiller.compute_loss
class GangWithBundlesAndChild: def test_second_worker_blocked(self): """The second child actor shouldn't fit in this replica's bundle slice.""" w1 = ChildActor.remote() w2 = ChildActor.remote() ready, _ = ray.wait([w2.get_pg.remote()], timeo...
0
test
ray-project/ray:python/ray/serve/tests/test_gang_scheduling.py:TestGangChildSpawnPlacementGroup.test_child_actor_gang_pg_bundles_bounded
returncode=0, stdout="Command output", stderr="" ) _pytest(Path(), {}, cov=False) assert mock_subprocess.call_args[0][0] == [ "uv", "run", "--no-sync", "--", "pytest", "-q", "--disable-warnings", "--disable-pytest-warnings", ] mock_s...
1
test
run-llama/llama_index:llama-dev/tests/test/test_test.py:test__pytest
# Shift to center of pixel coords = boxes.view(*boxes.shape[:2], 2, 2) # add padding point for consistency with the original implementation coords = torch.nn.functional.pad(coords, (0, 0, 0, 1), mode="constant", value=0) corner_embedding = self.shared_embedding(coords, (self.input_imag...
0
function_simple
huggingface/transformers:src/transformers/models/sam2/modular_sam2.py:Sam2PromptEncoder._embed_boxes
ate per-model costs on-the-fly total_model_cost = 0.0 model_prompt_cost = 0.0 model_completion_cost = 0.0 # Calculate costs for this model for entry in self.usage_history: if entry.model == model: cost = await self.calculate_cost(entry.model, entry.usage) if cost: model_prom...
0
function_complex
browser-use/browser-use:browser_use/tokens/service.py:TokenCost.log_usage_summary
video_hidden_state.shape[0], dtype=torch.long ) if padding_mask is not None: audio_lengths = padding_mask.sum(dim=-1) else: audio_lengths = audio_hidden_state.shape[1] * audio_hidden_state.new_ones( audio_hidden_state.shape[0], dtype=torch...
0
function_complex
huggingface/transformers:src/transformers/models/pe_audio_video/modular_pe_audio_video.py:PeAudioVideoEncoderEmbedder._align_video_hidden_state
ral_tokenizer_does_not_block_event_loop(): expected_tokens = [1, 2, 3] # Mock the blocking version to sleep def mocked_apply_chat_template(*_args, **_kwargs): time.sleep(2) return expected_tokens mock_model_config = MockModelConfig(skip_tokenizer_init=True) mock_tokenizer = Mock(sp...
1
test
vllm-project/vllm:tests/renderers/test_mistral.py:test_async_mistral_tokenizer_does_not_block_event_loop
.""" if not isinstance(filter_obj, MetadataFilter): raise ValueError(f"Expected MetadataFilter, got {type(filter_obj)}") key = filter_obj.key value = filter_obj.value operator = filter_obj.operator # Map LlamaIndex operators to S3 Vectors ope...
1
function_complex
run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-s3/llama_index/vector_stores/s3/base.py:S3VectorStore._build_filter
image1 = image2 = Image.new("1", size=(10, 20)) id = uuid.uuid4() image1.getexif()[Image.ExifTags.Base.ImageID] = id image2 = Image.open(ASSETS_DIR / "image1.png") image2.getexif()[Image.ExifTags.Base.ImageID] = "Not a UUID" image2a = Image.open(ASSETS_DIR / "image1.png") hasher = MultiModal...
1
test
vllm-project/vllm:tests/multimodal/test_hasher.py:test_hash_image_exif_id
None, categories: list[str] | None = None, older_than: datetime | None = None, metadata_filter: dict[str, Any] | None = None, record_ids: list[str] | None = None, ) -> int: """Delete memories matching criteria. Returns: Number of records deleted. ...
0
function_simple
crewAIInc/crewAI:lib/crewai/src/crewai/memory/unified_memory.py:Memory.forget
A JSON string containing the extracted data. """ if not self.client: raise ValueError( "Tavily client is not initialized. Ensure 'tavily-python' is installed and API key is set." ) return json.dumps( self.client.extract( ...
0
function_simple
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/tavily_extractor_tool/tavily_extractor_tool.py:TavilyExtractorTool._run
key_net_ver: Bip32KeyNetVersions) -> bool: """ Get if the key is public. Args: ser_key_bytes (bytes) : Serialized key bytes key_net_ver (Bip32KeyNetVersions object): Key net versions Returns: bool: True if public, fa...
1
function_simple
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/bip32_key_ser.py:Bip32KeyDeserializer.__GetIfPublic
pt-oss-safeguard-20b") == "OpenAI" assert discovery._get_provider_name("qwen/qwen3-32b") == "Alibaba Cloud" assert discovery._get_provider_name("moonshotai/moonshot-v1") == "Moonshot AI" assert discovery._get_provider_name("groq/groq-model") == "Groq" # Models with prefixes asse...
1
test
langflow-ai/langflow:src/backend/tests/unit/groq/test_groq_model_discovery.py:TestGroqModelDiscoverySuccess.test_provider_name_extraction
�于 .env 配置并融合命令行覆盖项生成最终配置""" config_overrides: Dict[str, Any] = {} if args.graphrag_enabled is not None: config_overrides['GRAPHRAG_ENABLED'] = args.graphrag_enabled if args.graphrag_max_queries is not None: if args.graphrag_max_queries <= 0: logger.warning("GRAPHRAG_MAX_QUERIES...
1
function_complex
666ghj/BettaFish:report_engine_only.py:build_agent_config
modified=now) fb.setupPost() fb.setupNameTable( { "familyName": "Occulta", "styleName": "Regular", "uniqueFontIdentifier": "OCRmyPDF;Occulta-Regular;2026", "fullName": "Occulta Regular", "version": "Version 2.0", "psName": "Occulta...
1
function_simple
ocrmypdf/OCRmyPDF:scripts/generate_glyphless_font.py:create_font
).to(torch_device), atol=1e-4, rtol=1e-4, ) # test propagate in video frames frames = [] for sam2_video_output in self.video_model.propagate_in_video_iterator( inference_session=inference_session, start_frame_idx=ann_frame_idx, ...
0
test
huggingface/transformers:tests/models/edgetam_video/test_modeling_edgetam_video.py:EdgeTamVideoModelIntegrationTest.test_inference_mask_generation_video_multi_points
and_validation_alias_missing(path: str): client = TestClient(app) response = client.post(path) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "missing", "loc": [ "body", "p_v...
1
test
fastapi/fastapi:tests/test_request_params/test_form/test_required_str.py:test_required_alias_and_validation_alias_missing
mock_llm.acall = AsyncMock( side_effect=[ "<summary>Result A</summary>", "<summary>Result B</summary>", ] ) results = asyncio.run( _asummarize_chunks( chunks=[chunk_a, chunk_b], llm=mock_llm, ...
0
test
crewAIInc/crewAI:lib/crewai/tests/utilities/test_agent_utils.py:TestParallelSummarization.test_asummarize_chunks_returns_ordered_results
equal_resolution=False, return_tensors="pil" ) for video in video_inputs: self.assertIsInstance(video[0], Image.Image) video_metadata = self.video_processor_tester.prepare_video_metadata(video_inputs) encoded_videos = video_processing( v...
0
test
huggingface/transformers:tests/models/glm4v/test_video_processing_glm4v.py:Glm4vVideoProcessingTest.test_call_pil
""" This transforms the weights obtained using `convert_gpt_oss.py` to load them into `Mxfp4GptOssExperts`. """ PrecisionConfig, FlexCtx, InFlexData = ( triton_kernels_hub.matmul_ogs.PrecisionConfig, triton_kernels_hub.matmul_ogs.FlexCtx, triton_kernels_hub.matmul_ogs.InFlexData, ...
0
function_complex
huggingface/transformers:src/transformers/integrations/mxfp4.py:swizzle_mxfp4_convertops
- NUM_RETRIES: 重试次数(可选) - FALLBACK_MODELS: 备用模型列表(可选) """ self.model = config.get("MODEL", "deepseek/deepseek-chat") self.api_key = config.get("API_KEY") or os.environ.get("AI_API_KEY", "") self.api_base = config.get("API_BASE", "") self.temperature = config.get(...
1
function_simple
sansan0/TrendRadar:trendradar/ai/client.py:AIClient.__init__
color channel (gray_scaled=True) or 3 RGB channels (gray_scaled=False). """ super().__init__() cnn_multiplier = get_cnn_multiplier(model_size, override=cnn_multiplier) self.gray_scaled = gray_scaled config = CNNTransposeHeadConfig( input_dims=[input_size]...
0
function_simple
ray-project/ray:rllib/algorithms/dreamerv3/torch/models/components/conv_transpose_atari.py:ConvTransposeAtari.__init__
�证器 - 验证 IR 表格数据格式是否正确。 验证规则: 1. 基本结构验证:type, rows 字段 2. 行结构验证:每行必须有 cells 数组 3. 单元格结构验证:每个 cell 必须有 blocks 数组 4. 嵌套 cells 检测:检测错误的嵌套 cells 结构 5. 数据完整性验证:检查空单元格和缺失数�
1
documentation
666ghj/BettaFish:ReportEngine/utils/table_validator.py:TableValidator:class_doc
m_set_on_agent(): """ Test that OpenAI is the default provider when no explicit LLM is set on the agent """ agent = Agent( role="Research Assistant", goal="Find information about the population of Tokyo", backstory="You are a helpful research assistant.", llm=LLM(model="g...
0
test
crewAIInc/crewAI:lib/crewai/tests/llms/openai/test_openai.py:test_openai_is_default_provider_without_explicit_llm_set_on_agent
student): """Validate that teacher and student have compatible input shapes.""" if not hasattr(teacher, "inputs") or not hasattr(student, "inputs"): return teacher_inputs = getattr(teacher, "inputs") student_inputs = getattr(student, "inputs") if teacher_inputs is No...
1
function_simple
keras-team/keras:keras/src/distillation/distiller.py:Distiller._validate_input_compatibility
print(f"Function parameters: {params}") if 'webhook_config' in params: print(f"✅ process_llm_extraction has webhook_config parameter") webhook_param = sig.parameters['webhook_config'] if webhook_param.default is None or webhook_param.default == inspect.Parameter.empty:...
1
test
unclecode/crawl4ai:test_llm_webhook_feature.py:test_process_llm_extraction_signature
initialization and basic functionality. """ engine_args = AsyncEngineArgs( model="Qwen/Qwen2.5-0.5B-Instruct", dtype="auto", disable_log_stats=False, enforce_eager=True, trust_remote_code=True, enable_prefix_caching=True, max_model_len=256, specu...
0
test
ray-project/ray:release/llm_tests/serve/test_llm_serve_integration.py:test_engine_metrics_with_spec_decode
else [] ) for comp in comparisons: if not ( isinstance(comp.left, ast.Attribute) and comp.left.attr == "major" and comp.comparators and isin...
1
function_complex
vllm-project/vllm:tools/pre_commit/generate_attention_backend_docs.py:parse_flash_attn_features
task_id: The job's task identifier """ payload = { "url": url, "q": query, "cache": False, "webhook_config": { "webhook_url": webhook_url, "webhook_data_in_payload": include_data, # Optional: Add custom headers for authentication ...
1
function_simple
unclecode/crawl4ai:docs/examples/docker_webhook_example.py:submit_llm_job_with_webhook
Disable auth mode set_auth_mode("disabled") reset_auth_token_state() # Create server without auth server, port = create_sync_test_server(with_auth=False) try: # Client without auth channel = grpc.insecure_channel(f"localhost:{port}") stub = ...
0
test
ray-project/ray:python/ray/tests/authentication/test_sync_grpc_interceptors.py:test_sync_server_without_auth
_ask_in_start_method(self) -> None: """ask() works inside a @start() method, flow completes normally.""" execution_log: list[str] = [] class TestFlow(Flow): input_provider = MockInputProvider(["AI"]) @start() def gather(self): topic = self.as...
0
test
crewAIInc/crewAI:lib/crewai/tests/test_flow_ask.py:TestAskBasic.test_ask_in_start_method
block_ids) >= n_blocks: return True # Exit early if even after uninitializing all initialized blocks, there are not enough free blocks block_to_uninitialize = n_blocks - len(self._uninit_block_ids) if len(self._init_block_ids) < block_to_uninitialize: return False ...
0
function_simple
huggingface/transformers:src/transformers/generation/continuous_batching/cache_manager.py:BlockManager.has_enough_free_blocks
podcast_data["title"]) if "date" in podcast_data: fields.append("date = ?") params.append(podcast_data["date"]) if "content" in podcast_data and isinstance(podcast_data["content"], dict): fields.append("content_json = ?") params.app...
0
function_complex
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/podcast_service.py:PodcastService.update_podcast
_model_len=1024, enable_lora=True, max_loras=4, max_lora_rank=8, max_num_seqs=2, max_num_batched_tokens=2048, compilation_config=vllm.config.CompilationConfig( # Avoid OOM cudagraph_specialize_lora=False, ), ) ...
1
test
vllm-project/vllm:tests/lora/test_gptoss_tp.py:test_gpt_oss_lora
if req.is_prefill: kinds["prefill"].append(tup) elif req.is_extend: kinds["extend"].append(tup) elif req.is_decode: kinds["decode"].append(tup) parts = [] for kind in ["prefill", "extend", "decode"]: lst = kinds[kind] if not lst: ...
1
function_complex
vllm-project/vllm:benchmarks/attention_benchmarks/batch_spec.py:format_batch_spec
dir): """Generated SKILL.md should contain valid, parseable YAML frontmatter.""" install_ai_skills(project_dir, "claude") skill_file = project_dir / ".claude" / "skills" / "speckit-specify" / "SKILL.md" content = skill_file.read_text() # Extract and parse frontmatter as...
0
test
github/spec-kit:tests/test_ai_skills.py:TestInstallAiSkills.test_generated_skill_has_parseable_yaml
for component in pipe.components.values(): if hasattr(component, "set_default_attn_processor"): component.set_default_attn_processor() pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) generator_device = "cpu" inputs = self.get_dummy_inputs(g...
1
test
huggingface/diffusers:tests/pipelines/qwenimage/test_qwenimage.py:QwenImagePipelineFastTests.test_attention_slicing_forward_pass
频率和活跃时间) - "keyword_cooccur": 关键词共现分析(分析关键词同时出现的模式) topic: 话题关键词(可选,platform_compare模式适用) date_range: **【对象类型】** 日期范围(可选) - **格式**: {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}
1
function_simple
sansan0/TrendRadar:mcp_server/server.py:analyze_data_insights
apping functionality since it is implemented in PEFT and is extensively tested there. The goal of this test is specifically to ensure that hotswapping with diffusers does not require recompilation. See https://github.com/huggingface/peft/blob/eaab05e18d51fb4cce20a73c9acd82a00c013b83/tests/test_gpu_examples.py#L4252 fo...
1
documentation
huggingface/diffusers:tests/models/testing_utils/lora.py:LoraHotSwappingForModelTesterMixin:class_doc
": [4, 5, 6], "c": [7, 8, 9]}) parquet_path = tmp_path / "test.parquet" df.to_parquet(parquet_path, index=False) # Build pipeline with operations ds = ray.data.read_parquet(str(parquet_path)) for op_type, *op_args in operations: if op_type == "select": ...
0
test
ray-project/ray:python/ray/data/tests/test_projection_fusion.py:TestProjectionFusion.test_projection_pushdown_into_parquet_read
type": "flip", "p": 0.5}}), }, timeout=120, ) b1 = r1.json() assert r1.status_code == 200 and any(a["name"] == name for a in b1["assets"]) # Non-matching object -> no match r2 = http.get( api_base + "/api/assets", params={ "include_tags": "unit-tests,mf-o...
1
test
Comfy-Org/ComfyUI:tests-unit/assets_test/test_metadata_filters.py:test_meta_list_of_objects_any_of
test_T5Gemma2_sequence_classification_model(self): config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() config.num_labels = 3 input_ids = input_dict["input_ids"] attention_mask = input_ids.ne(1).to(torch_device) sequence_labels = ids_tensor([self.model_t...
0
test
huggingface/transformers:tests/models/t5gemma2/test_modeling_t5gemma2.py:T5Gemma2ModelTest.test_T5Gemma2_sequence_classification_model
: async with websockets.connect(self.uri, additional_headers=headers) as ws: self.ws = ws # Safe: now created inside this thread + loop # Create separate tasks for sending and receiving recv_task = asyncio.create_task(self._recv_loop(ws)) ...
1
function_simple
run-llama/llama_index:llama-index-integrations/voice_agents/llama-index-voice-agents-openai/llama_index/voice_agents/openai/websocket.py:OpenAIVoiceAgentWebsocket._socket_loop
(f"{_root}/plugins/convert/writer", [], ['writer_config.py', '__init__.py']), # Too deep # Wrong name (f"{_root}/plugins/train", ["model", "trainer"], ['train_defaults.py', '__init__.py'])] mock_walk = mocker.MagicMock(return_value=dir_tree) mocker.patch("lib.config.config.os.walk", mock_w...
1
test
deepfakes/faceswap:tests/lib/config/config_test.py:test_generate_configs
"""Download a single file from S3. Args: s3_client: Shared boto3 S3 client bucket: S3 bucket name key: S3 object key local_file_path: Local path where file will be saved Returns: Tuple of (key, success) """ try: ...
0
function_simple
ray-project/ray:python/ray/llm/_internal/common/utils/cloud_filesystem/s3_filesystem.py:S3FileSystem._download_single_file
"nodeAffinity": { "preferredDuringSchedulingIgnoredDuringExecution": [ { "weight": 1, "preference": { "matchExpressions": [ {"key": "not-me", "operator": "In", "valu...
1
test
apache/airflow:helm-tests/tests/helm_tests/airflow_core/test_worker_sets.py:TestWorkerSets.test_overwrite_affinity
Name="container"> <p>Nested content</p> </div> """ result, path = self._load_from_file(content) assert isinstance(result, LoaderResult) assert all( tag not in result.content for tag in ["import", "export", "<Component", "<div", "</div>"] ) assert all(...
0
test
crewAIInc/crewAI:lib/crewai-tools/tests/rag/test_mdx_loader.py:TestMDXLoader.test_load_basic_mdx_file
query = """ INSERT INTO tasks (name, description, command, task_type, frequency, frequency_unit, enabled, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) """ params = ( name, description, command, ...
0
function_complex
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/task_service.py:TaskService.create_task
[str, Any] | None], label: str = "", default_repo: str = "", default_dtype: str = "", ): """ Args: node_specs: Dict mapping node_type to node spec or None. Node spec has: inputs, model_inputs, outputs, required_inputs, required_model_inputs...
1
function_simple
huggingface/diffusers:src/diffusers/modular_pipelines/mellon_node_utils.py:MellonPipelineConfig.__init__
canvas_id: str, tenant_id: str, runtime_user_id: str, dsl, canvas_category=CanvasCategory.Agent, title="", ): """Replace replica content for `/set` under lock.""" replica_key = cls._replica_key(canvas_id, str(tenant_id), str(runtime_user_id)) lock_ke...
1
function_simple
infiniflow/ragflow:api/apps/services/canvas_replica_service.py:CanvasReplicaService.replace_for_set
position_ids=text_position_ids, ) hidden_states = inputs_embeds # create position embeddings to be shared across the decoder layers position_embeddings = self.rotary_emb(hidden_states, position_ids) for decoder_layer in self.layers[: self.config.num_hidden_layers]: ...
0
function_complex
huggingface/transformers:src/transformers/models/ernie4_5_vl_moe/modular_ernie4_5_vl_moe.py:Ernie4_5_VLMoeTextModel.forward
url: str): """Crawl with undetected browser""" print("\n[Undetected Browser Mode]") browser_config = BrowserConfig( headless=False, verbose=True, ) # Create undetected adapter and strategy undetected_adapter = UndetectedAdapter() crawler_strategy = AsyncPlaywrightCrawler...
1
function_simple
unclecode/crawl4ai:docs/examples/undetected_simple_demo.py:crawl_with_undetected_browser
key(feature: str) -> str: """Interactive prompt for API key.""" print( f""" ╭─────────────────────────────────────────────────────────────╮ │ 🔑 Browser-Use API Key Required │ │ │ │ {feature} requires an API key. ...
0
function_simple
browser-use/browser-use:browser_use/skill_cli/api_key.py:prompt_for_api_key
73, 486, 780, 1136, 254, 983, 138, 386, 800, 1819, 1857], [1178, 1939, 107, 1605, 582, 1256, 420, 637, 648, 1023, 1809, 978, 1703, 278, 1668, 2044, 1599, 1321, 1670, 1716, 1155, 56, 602, 877, 886, 220, 910, 797, 1028, 1226, 869, 811], [1432, 1926, 1197, 1687, 540, 1815, 658, 1080, 1162, 192, 31...
0
test
huggingface/transformers:tests/models/csm/test_modeling_csm.py:CsmForConditionalGenerationIntegrationTest.test_1b_model_integration_generate
method="process", dtype=None, request_kwargs=dict(x=row["id"]), ), # Error rows will bypass this postprocess and return raw data with # __inference_error__ set. Only success rows get resp/id keys. postprocess=lambda row: dict( resp=row.get(...
0
test
ray-project/ray:python/ray/llm/tests/batch/gpu/processor/test_serve_deployment_proc.py:test_serve_deployment_continue_on_error
"title": "Fix: A bug", "url": "https://github.com/test/repo/pull/456", } ], } package_versions = {"pkg1": "0.1.0", "pkg2": "0.2.0"} today = date.today().strftime("%Y-%m-%d") expected_text = f"""{CHANGELOG_PLACEHOLDER} ## [{today}] ### pkg1 [0.1.0] -...
1
test
run-llama/llama_index:llama-dev/tests/release/test_changelog.py:test_get_changelog_text
_model_len"] = 1024 compilation_config = dict( use_inductor_graph_partition=inductor_graph_partition, custom_ops=custom_ops.split(","), pass_config=PassConfig( enable_qk_norm_rope_fusion=True, fuse_allreduce_rms=True, ), ) matches_check = [ "...
1
test
vllm-project/vllm:tests/compile/fusions_e2e/test_tp2_ar_rms.py:test_tp2_ar_rms_fusions
mlx_whisper missing class _MpsOff: def is_built(self): return False def is_available(self): return False class _TorchOff: class backends: mps = _MpsOff() monkeypatch.setitem(sys.modules, "torch", _TorchOff())...
1
test
docling-project/docling:tests/test_asr_mlx_whisper.py:TestMlxWhisperIntegration.test_selector_import_errors_force_native
print(f"✓ Successfully crawled bot detection site") print(f"✓ With stealth enabled, many detection tests should show as passed") if result.screenshot: # Save screenshot for verification import base64 with open("stealth_detection...
1
function_simple
unclecode/crawl4ai:docs/examples/stealth_mode_quick_start.py:example_2_stealth_with_screenshot
): """Test that private network IPv4 addresses are blocked.""" browser_profile = BrowserProfile(block_ip_addresses=True, headless=True, user_data_dir=None) browser_session = BrowserSession(browser_profile=browser_profile) event_bus = EventBus() watchdog = SecurityWatchdog(browser_session=browser_session, even...
0
test
browser-use/browser-use:tests/ci/security/test_ip_blocking.py:TestIPv4Blocking.test_block_private_ipv4_networks
command=Command( update={ "messages": [ HumanMessage(content="Inner msg", id="inner"), ] } ), ) model = GenericFakeChatModel(me...
1
test
langchain-ai/langchain:libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_wrap_model_call_state_update.py:TestComposition.test_inner_command_propagated_through_composition
is not None: assert not per_act_token_quant assert not per_out_ch_quant # TODO(bnell): this is not quite right for activations since first # dim should be 1. a_shape = GroupShape(row=block_shape[0], col=block_shape[1]) w_shape = GroupShape(row=block_shape[0], col=block_s...
1
function_complex
vllm-project/vllm:vllm/model_executor/layers/fused_moe/config.py:_quant_flags_to_group_shape
indices: intermediates.append(x) if torch.jit.is_scripting() or not stop_early: stages = self.stages else: # max_index is 0-4, stages are 1-4, so we need max_index stages stages = self.stages[:max_index] if max_index > 0 else [] for feat_idx, sta...
1
function_complex
huggingface/pytorch-image-models:timm/models/csatv2.py:CSATv2.forward_intermediates
" is 72", "°F", " and sunny", ".", ] results = list(parse_deepseek_v32(_simulate_tokens(model_tokens))) # Step 3: Verify all tokens pass through as GenerationResponse gen_results = [r for r in results if isinstance(r, GenerationResponse)] to...
0
test
exo-explore/exo:src/exo/worker/tests/unittests/test_runner/test_dsml_e2e.py:TestE2EStandardResponse.test_plain_text_passthrough
�】创建专用的logger,配置实时写入 # - enqueue=False: 禁用异步队列,立即写入 # - buffering=1: 行缓冲,每条日志立即刷新到文件 # - level="DEBUG": 记录所有级别的日志 # - encoding="utf-8": 明确指定UTF-8编码 # - mode="a": 追加模式,保留历史日志
1
function_complex
666ghj/BettaFish:ReportEngine/agent.py:ReportAgent._setup_logging
replace_in_file(compiled_file, "emoji==2.9.0", "emoji==2.10.0") output_file = Path( _runfiles.Rlocation(f"{tmpdir}/requirements_compiled.txt") ) save_file_as(compiled_file, output_file) manager = _create_test_manager(tmpdir) manager.compile( ...
0
test
ray-project/ray:ci/raydepsets/tests/test_cli.py:TestCli.test_compile_update_package
_spec: Model specification (for generating engine-specific configs) Returns: Initialized engine instance Raises: ValueError: If engine type is not supported ImportError: If required dependencies are not installed """ engine_type = options.engine_type # Generate model_confi...
1
function_complex
docling-project/docling:docling/models/inference_engines/vlm/factory.py:create_vlm_engine
corners. Args: num_patches_h (int): Number of patches along the vertical (height) axis. num_patches_w (int): Number of patches along the horizontal (width) axis. dtype (torch.dtype): The desired data type of the returned tensor. Returns: torch.Tensor: A tensor of shape (height...
0
function_simple
huggingface/transformers:src/transformers/models/dinov3_vit/modular_dinov3_vit.py:get_patches_center_coordinates
"type": "tool_call", "id": "abc_234", "name": "another_tool", "args": {"arg_1": "value_1"}, }, ], response_metadata={ "model_provider": "bedrock", "model_name": "us.anthropic.claude-sonnet-4-20250514-v1:0", ...
1
test
langchain-ai/langchain:libs/core/tests/unit_tests/messages/block_translators/test_bedrock.py:test_convert_to_v1_from_bedrock
Creating subtasks using LLM...') # Create subtasks using LLM subtasks = await create_subtasks(main_task, llm) print(f'📋 Created {len(subtasks)} subtasks:') for i, task in enumerate(subtasks, 1): print(f' {i}. {task}') print(f'\n🔥 Starting {len(subtasks)} agents in parallel...') print('🔍 Each agent will ...
0
function_simple
browser-use/browser-use:examples/custom-functions/parallel_agents.py:run_parallel_agents
"""Test get_configured_op returns cached ConfiguredHelionKernel.""" def fake_impl(*args, **kwargs): return torch.zeros_like(args[0]) def default_picker(args, config_keys): return "default" wrapper = HelionKernelWrapper( raw_kernel_func=sample_kernel,...
1
test
vllm-project/vllm:tests/kernels/helion/test_register.py:TestHelionKernelWrapper.test_get_configured_op_returns_cached_kernel
config": { "encoding": encoding_type, }, }, ] config = ServeDeploySchema.parse_obj(config_dict) client.deploy_apps(config) wait_for_condition( lambda: httpx.post("http://localhost:8000/app1").status_code == 200 ) ...
0
test
ray-project/ray:python/ray/serve/tests/test_deploy_app_2.py:TestDeploywithLoggingConfig.test_deploy_app_with_deployment_logging_config
2", tn_parent=a) c = Tag.objects.create(name="C2", tn_parent=b) d = Tag.objects.create(name="D2", tn_parent=c) x = Tag.objects.create(name="X2") y = Tag.objects.create(name="Y2", tn_parent=x) assert y.parent_pk == x.pk # Moving X under D would make deepest node Y exceed...
1
test
paperless-ngx/paperless-ngx:src/documents/tests/test_tag_hierarchy.py:TestTagHierarchy.test_max_depth_on_move_subtree
(Page): The Playwright page instance Returns: str: Base64-encoded screenshot image """ try: # The page is already loaded, just take the screenshot screenshot = await page.screenshot(full_page=False) return base64.b64encode(screenshot).decode("utf...
1
function_simple
unclecode/crawl4ai:crawl4ai/async_crawler_strategy.back.py:AsyncPlaywrightCrawlerStrategy.take_screenshot_naive
processor_dict) self.assertTrue(hasattr(image_processing, "downsample_factor")) self.assertTrue(hasattr(image_processing, "min_tiles")) self.assertTrue(hasattr(image_processing, "max_tiles")) self.assertTrue(hasattr(image_processing, "use_thumbnail")) self.ass...
0
test
huggingface/transformers:tests/models/lfm2_vl/test_image_processing_lfm2_vl.py:Lfm2VlImageProcessingTest.test_image_processor_properties
id_from_path, get_best_access_host, get_free_port, is_port_in_use, ) # Test port functions assert not is_port_in_use(0) # Port 0 is always available port = get_free_port(8000) assert 8000 <= port < 65535 # Test host resolution assert get_best_access_host("0.0.0.0"...
1
test
langflow-ai/langflow:src/lfx/tests/unit/cli/test_serve_simple.py:test_cli_utility_functions
input_str = "This is a test" image_input = self.prepare_image_inputs() # both image and text inputs = processor(text=input_str, images=image_input) self.assertListEqual( list(inputs.keys()), [ "flattened_patches", "attention_m...
0
test
huggingface/transformers:tests/models/kosmos2_5/test_processor_kosmos2_5.py:Kosmos2_5ProcessorTest.test_model_input_names
Matters") print("=" * 70) print("Before v0.7.7: Docker was just a containerized crawler") print("After v0.7.7: Complete self-hosting platform with enterprise monitoring") print("\nYou now have:") print(" • Full visibility into what's happening inside") print(" • Real-time operational dashboar...
1
function_simple
unclecode/crawl4ai:docs/releases_review/demo_v0.7.7.py:print_summary
": "arn:aws:iam::123456789012:role/firehose_delivery_role", "BucketARN": "arn:aws:s3:::kinesis-test", "Prefix": "airflow/", "BufferingHints": {"SizeInMBs": 123, "IntervalInSeconds": 124}, "CompressionFormat": "UNCOMPRESSED", }, ) ...
1
test
apache/airflow:providers/amazon/tests/unit/amazon/aws/hooks/test_firehose.py:TestFirehoseHook.test_insert_batch_records_kinesis_firehose
Raises: Bip44DepthError: If the current depth is not suitable for deriving keys Bip32KeyError: If the derivation results in an invalid key """ if not self.IsLevel(Bip44Levels.CHANGE): raise Bip44DepthError( f"Current depth ({self.m_bip32_obj.De...
1
function_simple
ccxt/ccxt:python/ccxt/static_dependencies/bip/bip44_base/bip44_base.py:Bip44Base._AddressIndexGeneric
Args( model="Qwen/Qwen2.5-0.5B-Instruct", dtype="auto", disable_log_stats=False, enforce_eager=True, ) engine = AsyncLLM.from_engine_args( engine_args, stat_loggers=[RayPrometheusStatLogger] ) for i, prompt in enumerate(["What is the capital of France?", "What i...
0
test
ray-project/ray:release/llm_tests/serve/test_llm_serve_integration.py:test_engine_metrics
lx.data.Extraction( extraction_class="emotion", extraction_text="But soft!", attributes={"feeling": "gentle awe"}, ), lx.data.Extraction( extraction_class="relationship", extraction_text="Juliet is th...
1
function_simple
google/langextract:examples/ollama/demo_ollama.py:example_romeo_juliet
list[int], min_prime_idx: int, prev_num: int, max_num: int, prev_sum: int, primes_degrees: dict[int, int], ) -> None: """ Run over all prime combinations to generate non-prime numbers. >>> chain = [0] * 3 >>> primes_degrees = {} >>> multiply( ... chain=chain, ... ...
1
function_simple
TheAlgorithms/Python:project_euler/problem_095/sol1.py:multiply
# Return partial success, or adapt as you see fit result = { "success": True, "info": "Navigation triggered, ignoring context destroyed error", } else: ...
1
function_complex
unclecode/crawl4ai:crawl4ai/async_crawler_strategy.back.py:AsyncPlaywrightCrawlerStrategy.robust_execute_user_script
_match.groups() headers.append( HeaderPermalinkInfo( hashes=hashes, line_no=line_no, permalink=permalink, title=title ) ) elif in_code_block3: if line.startswith("```"): count = len(line)...
1
function_complex
fastapi/fastapi:scripts/doc_parsing_utils.py:extract_header_permalinks
sanitize_mcp_name(flow.action_name) if flow.action_name else sanitize_mcp_name(flow.name) ) name = get_unique_name(base_name, MAX_MCP_TOOL_NAME_LENGTH, existing_names) description = flow.action_description or ( flow.description i...
1
function_complex
langflow-ai/langflow:src/backend/base/langflow/api/v1/mcp_utils.py:handle_list_tools
], }, ] formatted_prompt = processor.apply_chat_template([messages], add_generation_prompt=True, tokenize=False) self.assertEqual(len(formatted_prompt), 1) # batch size=1 out_dict = processor.apply_chat_template( messages, add_generation_prom...
0
test
huggingface/transformers:tests/models/qwen3_omni_moe/test_processing_qwen3_omni_moe.py:Qwen3OmniMoeProcessorTest.test_chat_template_audio_from_video
matches in left (id=0, 1) assert len(result) == 2 _assert_columns_match(result, {"id", "value", "score"}) _assert_scalar_values(result_by_id, {0: {"value": "x"}, 1: {"value": "y"}}) elif join_type == "right_anti": # Should return right rows that DON'T have matches in left (id=3) ...
0
test
ray-project/ray:python/ray/data/tests/test_join.py:test_join_with_unjoinable_non_key_columns
raction(): """Demo: Extract structured company data.""" print('\n🏢 Demo 3: Company Information Extraction') print('-' * 40) task = """ Go to a financial website and look up information about Apple Inc. Extract company details including name, stock symbol, market cap, industry, headquarters, and foundi...
0
function_complex
browser-use/browser-use:examples/cloud/03_structured_output.py:demo_company_extraction
() with authentication_env_guard(): set_auth_mode("token") set_env_auth_token(token) reset_auth_token_state() # Create server with auth enabled server, port = create_sync_test_server(with_auth=True) try: # Client with auth interceptor via init_grpc_chan...
0
test
ray-project/ray:python/ray/tests/authentication/test_sync_grpc_interceptors.py:test_sync_server_and_client_with_valid_token
block_ids_per_group3, num_tokens3 = metadata.reqs_to_fill[req3.request_id] # Verify token counts (all tokens except last one) assert num_tokens1 == block_size * 2 - 1 assert num_tokens2 == block_size * 3 - 1 assert num_tokens3 == block_size * 1 - 1 # Verify block counts for each request asse...
1
test
vllm-project/vllm:tests/v1/kv_connector/unit/test_decode_bench_connector.py:test_decode_bench_connector_concurrent_requests
6 and 4 tokens position_ids = torch.tensor([[0, 1, 2, 3, 0, 1, 0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 0, 1, 2, 3]]) causal_mask = create_causal_mask( config=config, # we only need batch size, seq_length and dtype here - we don't care about the values of the embeddings inpu...
0
test
huggingface/transformers:tests/utils/test_masking_utils.py:MaskTest.test_packed_sequence_mask_sdpa
.send.Page.getNavigationHistory(session_id=cdp_session.session_id) current_index = history['currentIndex'] entries = history['entries'] # Check if we can go back if current_index <= 0: self.logger.warning('⚠️ Cannot go back - no previous entry in history') return # Navigate to the previous entr...
0
function_simple
browser-use/browser-use:browser_use/browser/watchdogs/default_action_watchdog.py:DefaultActionWatchdog.on_GoBackEvent
return None register_before_tool_call_hook(before_hook) register_after_tool_call_hook(after_hook) try: agent = Agent( role="Calculator", goal="Perform calculations", backstory="You are a calculator assistant", ...
0
test
crewAIInc/crewAI:lib/crewai/tests/hooks/test_tool_hooks.py:TestNativeToolCallingHooksIntegration.test_agent_native_tool_hooks_before_and_after
, just use the main session if not self.browser_profile.cross_origin_iframes: return await self.get_or_create_cdp_session() # Get complete frame hierarchy all_frames, target_sessions = await self.get_all_frames() # Find the requested frame frame_info = await self.find_frame_target(frame_id, all_frames) ...
0
function_simple
browser-use/browser-use:browser_use/browser/session.py:BrowserSession.cdp_client_for_frame
break except ConnectionRefusedError: time.sleep(5) # Send ping-pong. send_rllink_message(sock_, {"type": RLlink.PING.name}) msg_type, msg_body = get_rllink_message(sock_) assert msg_type == RLlink.PONG # Request config. send_rllink_message(sock_, {"type": RLlink.GET_...
0
function_complex
ray-project/ray:rllib/examples/envs/classes/utils/dummy_external_client.py:_dummy_external_client
def _reset_chart_validation_stats(self) -> None: """重置图表校验统计并清除失败计数标记""" self.chart_validation_stats = { 'total': 0, 'valid': 0, 'repaired_locally': 0, 'repaired_api': 0, 'failed': 0 } # 保留失败原因缓存,但重置本次渲染的计数 self._chart_f...
1
function_simple
666ghj/BettaFish:ReportEngine/renderers/html_renderer.py:HTMLRenderer._reset_chart_validation_stats