input
string
label
int64
category
string
sample_id
string
_screenshot(self, page, **kwargs) -> str: """ Take a screenshot of the current page. Args: page (Page): The Playwright page object kwargs: Additional keyword arguments Returns: str: The base64-encoded screenshot data """ need_scroll =...
1
function_simple
unclecode/crawl4ai:crawl4ai/async_crawler_strategy.back.py:AsyncPlaywrightCrawlerStrategy.take_screenshot
({file_size} bytes)') # Get file extension for file_type file_ext = path.suffix.lower().lstrip('.') # Call direct callbacks first (for click handlers waiting for downloads) complete_info = { 'guid': guid, 'url': str(path), 'path': str(path), 'file_name': path.name, 'file_size...
0
function_complex
browser-use/browser-use:browser_use/browser/watchdogs/downloads_watchdog.py:DownloadsWatchdog._track_download
_table(self): """Create table with vector column if it doesn't exist.""" try: # Create table with vector stored as list<float> and payload as text (JSON) query = f""" CREATE TABLE IF NOT EXISTS {self.keyspace}.{self.collection_name} ( id text P...
1
function_simple
mem0ai/mem0:mem0/vector_stores/cassandra.py:CassandraDB._create_table
_state() assert isinstance(state, dict) assert "rl_module" in state # check that a new env runner can be updated based on an older state new_runner = env_runner_cls(config=env_runner_config) try: # Check the states are not identical new_state = new_runne...
0
test
ray-project/ray:rllib/env/tests/test_env_runner.py:TestEnvRunnerStateManagement.test_get_state_returns_dict
config to a directory.""" if os.path.isfile(save_directory): raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file") os.makedirs(save_directory, exist_ok=True) output_path = os.path.join(save_directory, self.config_name) self.to_json_file...
1
function_simple
huggingface/diffusers:src/diffusers/modular_pipelines/mellon_node_utils.py:MellonPipelineConfig.save
_logger.log_value("simple", 1) root_logger.log_value("simple", 2) time.sleep(0.1) end_time = time.perf_counter() throughput = 3 / (end_time - start_time) # Get compiled results compiled = root_logger.compile() # Check that values and throughputs are correctly combined check(compiled[...
0
test
ray-project/ray:rllib/utils/metrics/tests/test_metrics_logger.py:test_compile
format to Gemini function declaration format.""" gemini_tools = [] from crewai.llms.providers.utils.common import safe_tool_conversion for tool in tools: name, description, parameters = safe_tool_conversion(tool, "Gemini") function_declaration = types.FunctionDeclarat...
0
function_simple
crewAIInc/crewAI:lib/crewai/src/crewai/llms/providers/gemini/completion.py:GeminiCompletion._convert_tools_for_interference
Args: pixel_values: Input pixel values of shape (batch, channels, height, width) Returns: Visual embeddings """ vit_embeds = self.vision_model(pixel_values=pixel_values) h = w = int(vit_embeds.shape[1] ** 0.5) vit_embeds = vit_embeds.reshape(vit_embed...
1
function_simple
vllm-project/vllm:vllm/model_executor/models/eagle2_5_vl.py:Eagle2_5_VLForConditionalGeneration.extract_feature
<html><body> <div id="unicode">日本語 中文 한국어 العربية 🎉 💻 🚀</div> <div id="special">&amp; &lt; &gt; &quot; &apos;</div> </body></html> """ async with AsyncWebCrawler() as crawler: config = CrawlerRunConfig(js_code="document.getElementById('unicode').innerText += ' ✅ Modified'") ...
1
test
unclecode/crawl4ai:tests/test_raw_html_edge_cases.py:test_raw_html_with_unicode
els_should_override_global_labels(self): """Test that component-specific labels take precedence over global labels with the same key.""" docs = render_chart( values={ "airflowVersion": self.AIRFLOW_VERSION, "labels": {"common_label": "global_value"}, ...
1
test
apache/airflow:helm-tests/tests/helm_tests/dagprocessor/test_labels_service_account.py:TestDagProcessorServiceAccount.test_component_specific_labels_should_override_global_labels
("transferOperations/123", IndexError), ("transferOperations/123-", ("123-", "")), ("-transferJobs-job456", IndexError), ("transferOperations/123-transferJobs", ("123-transferJobs", "transferJobs")), ] for operation_name, expected in test_cases: ...
1
test
apache/airflow:providers/google/tests/unit/google/cloud/links/test_cloud_storage_transfer.py:TestCloudStorageTransferLinkHelper.test_extract_parts_with_malformed_operation_names
test_retrieval_generic_exception_mapping(monkeypatch): module = _load_dify_retrieval_module(monkeypatch) _set_request_json(monkeypatch, module, {"knowledge_id": "kb-1", "query": "hello"}) monkeypatch.setattr(module.DocMetadataService, "get_meta_by_kbs", lambda _kb_ids: []) monkeypatch.setattr(module.Kn...
1
test
infiniflow/ragflow:test/testcases/test_http_api/test_dataset_management/test_dify_retrieval_routes_unit.py:test_retrieval_generic_exception_mapping
"""Test the _search_destination_node method.""" # Mock embedding mock_embedding = [0.1, 0.2, 0.3] # Mock the _search_destination_node_cypher method mock_cypher = "MATCH (n) RETURN n" mock_params = {"destination_embedding": mock_embedding, "user_id": self.user_id, "threshold": 0...
1
test
mem0ai/mem0:tests/memory/test_neptune_memory.py:TestNeptuneMemory.test_search_destination_node
A decorator that executes the given function in a parallel loop. """ def decorator(body): flat_carries, carry_tree = jax.tree.flatten(carry) def wrapped(idx, *carries): if carry is None: body(idx) return [] result = body(idx, carry_tree.unflatten(carries)) result, res...
1
function_complex
jax-ml/jax:jax/_src/pallas/mosaic/sc_primitives.py:parallel_loop
/test_main.py": { "content": [], "created_at": "2025-01-01T00:00:00", "modified_at": "2025-01-01T00:00:00", }, }, } result = middleware._handle_glob_search( pattern="**/*.py", path="/", state=state ...
1
test
langchain-ai/langchain:libs/partners/anthropic/tests/unit_tests/middleware/test_file_search.py:TestGlobSearch.test_glob_recursive_pattern
'SessionRegistry', params: dict[str, Any]) -> Any: """Handle session management command.""" if action == 'sessions': sessions = registry.list_sessions() return { 'sessions': sessions, 'count': len(sessions), } elif action == 'close': if params.get('all'): # Close all sessions and signal shutdown ...
0
function_simple
browser-use/browser-use:browser_use/skill_cli/commands/session.py:handle
dbo_enabled(): # If DBO is being used, register the hook with the ubatch # context and call it in dbo_maybe_run_recv_hook instead of # passing it to the receiver. dbo_register_recv_hook(hook) dbo_yield() ...
1
function_complex
vllm-project/vllm:vllm/model_executor/layers/fused_moe/modular_kernel.py:FusedMoEModularKernel._prepare
.""" # Poll for result instead of blocking on thread join start_time = time.time() while time.time() - start_time < self.timeout: if OAuthCallbackHandler.callback_result or OAuthCallbackHandler.callback_error: break time.sleep(0.1) # Signa...
1
function_complex
xtekky/gpt4free:g4f/Provider/needs_auth/Antigravity.py:OAuthCallbackServer.wait_for_callback
text", "value": message["content"]}], "loss_weight": 1.0 if message["role"] == "assistant" else 0.0, } ) return messages sample = {} sample["chosen_messages"] = process_message(raw_sample.get("chosen", [])) sample["rejected_messages"] = p...
1
function_complex
hiyouga/LlamaFactory:src/llamafactory/v1/plugins/data_plugins/converter.py:pair_converter
DPOINT": "https://models.inference.ai.azure.com" }): # Test DeepSeek model llm_deepseek = LLM(model="azure/deepseek-chat") # Endpoint should not be modified for non-OpenAI endpoints assert llm_deepseek.endpoint == "https://models.inference.ai.azure.com" assert llm_deepseek.i...
0
test
crewAIInc/crewAI:lib/crewai/tests/llms/azure/test_azure.py:test_azure_deepseek_model_support
shadow_elements.append((idx, element)) # Iframe content elements have IDs starting with "iframe-" elif elem_id.startswith('iframe-'): iframe_content_elements.append((idx, element)) # Everything else is regular DOM else: regular_elements.append((idx, element)) # Elements without IDs are ...
0
test
browser-use/browser-use:tests/ci/browser/test_dom_serializer.py:TestDOMSerializer.test_dom_serializer_with_shadow_dom_and_iframes
formatted_links.append( f"{i + 1}. {link.get('text', 'No text')}: {link.get('href', 'No href')}" ) result = ( "\n".join(formatted_links) if formatted_links else "No hyperlinks found on the page" ) ...
1
function_simple
run-llama/llama_index:llama-index-integrations/tools/llama-index-tools-aws-bedrock-agentcore/llama_index/tools/aws_bedrock_agentcore/browser/base.py:AgentCoreBrowserToolSpec.extract_hyperlinks
with mock.patch( "langextract.providers.gemini.GeminiLanguageModel.infer", return_value=iter([[mock.Mock(output='{"extractions": []}')]]), ): with mock.patch( "langextract.annotation.Annotator.__init__", return_value=None ) as mock_annotator_init: with...
1
test
google/langextract:tests/extract_schema_integration_test.py:ExtractSchemaIntegrationTest.test_extract_explicit_fence_respected
logger.warning(f"HTTP port out of range: {port}") elif self._protocol == RequestProtocol.GRPC: if not ( RAY_SERVE_DIRECT_INGRESS_MIN_GRPC_PORT <= port <= RAY_SERVE_DIRECT_INGRESS_MAX_GRPC_PORT ): logger.warning(f"GRPC ...
0
function_complex
ray-project/ray:python/ray/serve/_private/node_port_manager.py:PortAllocator.update_port_if_missing
Create a client for submitting and interacting with jobs on a remote cluster. :param address: Either (1) the address of the Ray cluster, or (2) the HTTP address of the dashboard server on the head node, e.g. "http://<head-node-ip>:8265". In case (1) it must be specified as an a...
1
function_simple
apache/airflow:providers/google/src/airflow/providers/google/cloud/hooks/ray.py:RayJobHook.get_client
originals = defaultdict(dict) try: # Replace all torch funcs by the ones in this file for module_name in TORCH_MODULES_TO_PATCH: if module_name in sys.modules: module = sys.modules[module_name] for func_name in TORCH_INIT_FUNCTIONS.keys(): ...
0
function_complex
huggingface/transformers:src/transformers/initialization.py:guard_torch_init_functions
ml_marker_split_at_fullwidth_pipe(self): """The fullwidth pipe character | might be its own token.""" # This is a realistic tokenization: the DSML marker is split at the | chars model_tokens = [ "Let me help.\n\n", "<\uff5c", # start of |DSML| "DSML\uff5c", ...
0
test
exo-explore/exo:src/exo/worker/tests/unittests/test_runner/test_dsml_e2e.py:TestE2EEdgeCases.test_dsml_marker_split_at_fullwidth_pipe
False, ) except asyncio.TimeoutError: return ( None, f"MCP discovery timed out after {MCP_DISCOVERY_TIMEOUT} seconds", True, ) except Exception as e: error_str = str(e).lower() if "authenticat...
0
function_complex
crewAIInc/crewAI:lib/crewai/src/crewai/mcp/tool_resolver.py:MCPToolResolver._attempt_mcp_discovery
pixels² Returns: The input image if valid Raises: ValueError: If image is too small or aspect ratio is too extreme """ if not isinstance(image, PIL.Image.Image): raise ValueError(f"Image must be a PIL.Image.Image, got {type(image)}") width,...
1
function_simple
huggingface/diffusers:src/diffusers/pipelines/flux2/image_processor.py:Flux2ImageProcessor.check_image_input
int_range = IntegerRangeField() bigint_range = BigIntegerRangeField() decimal_range = DecimalRangeField() datetime_range = DateTimeRangeField() date_range = DateRangeField() expected_errors = [ self._make_error(field, field.__class__.__name__) ...
1
test
django/django:tests/postgres_tests/test_app_installed_check.py:TestPostgresAppInstalledCheck.test_range_fields
used when generating samples with a pre-trained model. If used, `timesteps` must be `None`. device (`str` or `torch.device`, *optional*): The device to which the timesteps should be moved to. If `None`, the timesteps are not moved. timesteps (`list[int]`, *optional*): ...
1
function_complex
huggingface/diffusers:src/diffusers/pipelines/flux/pipeline_flux_kontext_inpaint.py:retrieve_timesteps
_version = "1.0.6rc3" repo_root = "/repo/root" confirm_prompts: list[str] = [] def fake_confirm_action(prompt: str, **_kwargs) -> bool: confirm_prompts.append(prompt) return False def should_not_be_called(*_args, **_kwargs): raise AssertionError("This should not have been call...
1
test
apache/airflow:dev/breeze/tests/test_release_candidate_command.py:test_remove_old_releases_returns_early_when_user_declines
"""Delete a file from the local storage. Args: flow_id: The identifier for the flow. file_name: The name of the file to be deleted. Raises: FileNotFoundError: If the file does not exist. """ file_path = self.data_dir / flow_id / file_name ...
1
function_simple
langflow-ai/langflow:src/lfx/src/lfx/services/storage/local.py:LocalStorageService.delete_file
4#file-reproducer-py """ path = Path(__file__).parent.parent.parent / "fixtures/audioflamingo3/expected_results_batched.json" with open(path, "r", encoding="utf-8") as f: raw = json.load(f) exp_ids = torch.tensor(raw["token_ids"]) exp_txt = raw["transcriptions"] ...
0
test
huggingface/transformers:tests/models/audioflamingo3/test_modeling_audioflamingo3.py:AudioFlamingo3ForConditionalGenerationIntegrationTest.test_fixture_batched_matches
ages = AnthropicMessageSerializer._clean_cache_messages(normal_messages) # Verify only the last cache=True message remains cached assert not cleaned_messages[0].cache # First user message should be uncached assert not cleaned_messages[1].cache # First assistant message should be uncached assert not cleaned_m...
0
test
browser-use/browser-use:browser_use/llm/tests/test_anthropic_cache.py:TestAnthropicCache.test_cache_cleaning_last_message_only
. """ sentry.add_tagging(dag_run=dag_run, task_instance=task_instance) assert mock_sentry_sdk.configure_scope.mock_calls == [ mock.call.__call__(), mock.call.__call__().__enter__(), mock.call.__call__().__enter__().set_tag("task_id", TASK_ID), mock...
1
test
apache/airflow:task-sdk/tests/task_sdk/execution_time/test_sentry.py:TestSentryHook.test_add_tagging
batched_messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt", padding=True, ).to(torch_device) # This model on the hub has `do_sample=True`. torch.manual_seed(42) # it should not matte...
0
test
huggingface/transformers:tests/models/glm4v/test_modeling_glm4v.py:Glm4vIntegrationTest.test_small_model_integration_test_batch_wo_image_flashatt2
ard for a given rank, without re-loading the model.""" model_dir = { "base": "base_checkpoints", "sft": "chatsft_checkpoints", "rl": "chatrl_checkpoints", }[source] base_dir = get_base_dir() checkpoints_dir = os.path.join(base_dir, model_dir) if model_tag is None: mod...
0
function_simple
karpathy/nanochat:nanochat/checkpoint_manager.py:load_optimizer_state
Discrete token indices from the VQVAE codebook. Returns: special_image_mask (`torch.LongTensor` of shape `(batch_size, seq_len)`): Mask indicating positions in input ids that will be replaced by actual image tokens. """ special_image_mask = input_id...
0
function_simple
huggingface/transformers:src/transformers/models/glm_image/modular_glm_image.py:GlmImageModel.get_placeholder_mask
.object( AlibabaCloudMySQLVectorStore, "_check_vector_support" ) as mock_check: with patch.object( AlibabaCloudMySQLVectorStore, "_create_table_if_not_exists" ) as mock_create_table: with patch.object(AlibabaCloudMySQLVectorStore, "_connect"): store = ...
1
test
run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-alibabacloud-mysql/tests/test_alibabacloud_mysql.py:test_initialize_without_setup
_run=args.dry_run) _create_group_membership_mapper(client, client_uuid, _dry_run=args.dry_run) _create_permissions(client, client_uuid, teams=[team], include_global_admin=False, _dry_run=args.dry_run) _ensure_group(client, team, _dry_run=args.dry_run) _ensure_team_policies(client, client_uuid, team, _dr...
1
function_simple
apache/airflow:providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py:create_team_command
= None ) -> bool: """Check if the given remote job variable file path is a valid file.""" if remote_job_var_file_path: sftp_client = ssh_client.open_sftp() try: # Get file metadata file_stat = sftp_client.stat(remote_job_var_file_path) if file_stat.st_mode: ...
1
function_complex
apache/airflow:providers/teradata/src/airflow/providers/teradata/utils/tpt_util.py:is_valid_remote_job_var_file
args.session}" is running') return 0 else: print(f'Server for session "{args.session}" is not running') return 1 elif args.server_command == 'stop': if not is_server_running(args.session): print(f'Server for session "{args.session}" is not running') return 0 response = send_command(args.session, ...
0
function_complex
browser-use/browser-use:browser_use/skill_cli/main.py:handle_server_command
_dim_size v_norm = v_norm_sq.sqrt() second_momentum_buffer.lerp_(v_mean.to(dtype=second_momentum_buffer.dtype), 1 - beta2) step_size = second_momentum_buffer.clamp_min(1e-10).rsqrt() scaled_sq_sum = (v_mean * red_dim_size) * step_size.float().square() v_norm_new = scaled_sq_sum.sum(dim=(-2, -1), kee...
0
function_complex
karpathy/nanochat:nanochat/optim.py:muon_step_fused
num_image_tokens = sum(1 for token_id in inputs["input_ids"][0] if token_id == self.image_token_id) # Verify we have image tokens (the bug caused 0 tokens) self.assertGreater(num_image_tokens, 0, "Single-tile image with use_thumbnail=False should have image tokens") # Verify the numbe...
0
test
huggingface/transformers:tests/models/lfm2_vl/test_processing_lfm2_vl.py:Lfm2VlProcessorTest.test_single_tile_image_with_thumbnail_disabled
) mock_output1 = TaskOutput( description="Test task for AI", raw="Result about AI", agent="Test Agent", ) mock_output2 = TaskOutput( description="Test task for ML", raw="Result about ML", agent="Test Agent", ) ...
0
test
crewAIInc/crewAI:lib/crewai/tests/crew/test_async_crew.py:TestAsyncCrewKickoffForEach.test_akickoff_for_each_basic
goal="Complete a simple task", backstory="You are a test agent.", llm=openai_llm # Use same instance ) task = Task( description="Say hello world", expected_output="Hello world", agent=agent, ) crew = Crew(agents=[agent...
0
test
crewAIInc/crewAI:lib/crewai/tests/llms/openai/test_openai.py:test_openai_completion_call_arguments
""" if isinstance(self.running_average, torch.Tensor): shape = tuple(self.running_average.shape) # Calculate statistics with torch.no_grad(): stats = { "mean": self.running_average.mean().item(), "std": self.runnin...
1
function_simple
huggingface/diffusers:src/diffusers/guiders/adaptive_projected_guidance_mix.py:MomentumBuffer.__repr__
tmp_path}/test_grayscale_image.png" image = image.convert("L") image.save(image_path) # Convert to gray RGB for comparison image = image.convert("RGB") video_path = f"{tmp_path}/test_RGB_video.{ext}" create_video_from_image( image_path, video_path, num_fra...
1
test
vllm-project/vllm:tests/multimodal/media/test_video.py:test_opencv_video_io_colorspace
command_receiver=co_rx, is_candidate=True, ) async with create_task_group() as tg: with fail_after(2): tg.start_soon(election.run) # Send any connection message object; we close quickly to cancel before result creation await cm_tx.send(ConnectionMessag...
0
test
exo-explore/exo:src/exo/shared/tests/test_election.py:test_connection_message_triggers_new_round_broadcast
apply_router_weight_on_input: bool, quant_config: FusedMoEQuantConfig, defer_input_quant: bool = False, ) -> mk.PrepareResultType: """ Returns a tuple of: - quantized + dispatched a. - Optional quantized + dispatched a1_scales. - Optional ExpertTokensMetada...
1
function_simple
vllm-project/vllm:vllm/model_executor/layers/fused_moe/mori_prepare_finalize.py:MoriPrepareAndFinalize.prepare
and setup with a single TPU worker. """ actor_name = "test_tpu_single_host" verify_actor = VerificationActor.options(name=actor_name).remote() trainer = JaxTrainer( train_loop_per_worker=train_func, scaling_config=ScalingConfig( use_tpu=True, num_workers=1, ...
0
test
ray-project/ray:python/ray/train/v2/tests/test_jax_trainer.py:test_tpu_single_host
.models.FieldCondition( key=filter_by, match=self.qdrant_package.http.models.MatchValue( value=filter_value ), ) ) query_vector = ( self.custom_embedding_fn(query) if self.cus...
0
function_complex
crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/qdrant_vector_search_tool/qdrant_search_tool.py:QdrantVectorSearchTool._run
_model( self, state: AgentState[Any], runtime: Runtime[Any] ) -> dict[str, Any] | None: # type: ignore[override] """Async version of before_model. Args: state: Current agent state containing messages. runtime: Agent runtime context. Returns: Upd...
1
function_simple
langchain-ai/langchain:libs/partners/openai/langchain_openai/middleware/openai_moderation.py:OpenAIModerationMiddleware.abefore_model
_ref_bundler_basic(target, in_bundles, expected_bundles): # Test that the bundler creates the expected output bundles. bundler = BlockRefBundler(target) bundles = _make_ref_bundles(in_bundles) out_bundles = [] for bundle in bundles: bundler.add_bundle(bundle) while bundler.has_bundle...
0
test
ray-project/ray:python/ray/data/tests/test_block_ref_bundler.py:test_block_ref_bundler_basic
message: The raw message received for the unknown task exc: The exception raised when trying to process the unknown task **kwargs: Additional context information from Celery """ logger.info( f"Unknown task detected by Celery. Name: {name}, ID: {id}, Exc: {str(ex...
0
function_simple
ray-project/ray:python/ray/serve/task_processor.py:CeleryTaskProcessorAdapter._handle_unknown_task
.""" step_num = step.number if step.number is not None else '?' memory = step.memory or '' if verbose: url = step.url or '' actions = step.actions or [] # Truncate URL for display short_url = url[:60] + '...' if len(url) > 60 else url print(f' [{step_num}] {short_url}') if memory: # Truncate memor...
0
function_complex
browser-use/browser-use:browser_use/skill_cli/commands/cloud_task.py:_print_step
test_arun_pipeline() -> None: pipeline = RayIngestionPipeline( readers=[ ReaderConfig( reader=StringIterableReader(), reader_kwargs={"texts": ["This is a test."]}, ) ], documents=[Document.example()], transformations=[...
1
test
run-llama/llama_index:llama-index-integrations/ingestion/llama-index-ingestion-ray/tests/test_pipeline.py:test_arun_pipeline
data = { "name": "Flow to Update", "data": {}, } flow_response = await client.post("api/v1/flows/", json=flow_data, headers=logged_in_headers) assert flow_response.status_code == status.HTTP_201_CREATED flow_id = flow_response.json()["id"] # Now try to update the flow with a non-exi...
1
test
langflow-ai/langflow:src/backend/tests/unit/api/v1/test_flow_folder_integrity.py:test_update_flow_with_nonexistent_folder_id_assigns_default_folder
None, sender_name: str | None = None, session_id: str | UUID | None = None, context_id: str | UUID | None = None, order_by: str | None = "timestamp", order: str | None = "DESC", flow_id: UUID | None = None, limit: int | None = None, ) -> list[Message]: """DEPRECATED - Retrieve messages ...
1
function_simple
langflow-ai/langflow:src/lfx/src/lfx/memory/stubs.py:get_messages
chroma.return_value = mock_chroma_inst mock_chroma_inst.aadd_documents = AsyncMock() mock_meta.return_value = {"chunks": 5, "size": 100, "source_types": []} mock_size.return_value = 100 file_name, file_content = sample_text_file files_data = [(file_name, file_content.encode())]...
1
test
langflow-ai/langflow:src/backend/tests/unit/test_knowledge_bases_api.py:TestPerformIngestionTask.test_perform_ingestion_success
name (str | None): Component name or pattern collection (str | None): Optional collection to filter by load_id (str | None): Optional load_id to filter by Returns: A single component Raises: ValueError: If no components match or multiple components mat...
1
function_complex
huggingface/diffusers:src/diffusers/modular_pipelines/components_manager.py:ComponentsManager.get_one
Args: tokens (`str` or `list[str]`): One or several token(s) to convert to token id(s). Returns: `int` or `list[int]`: The token id or list of token ids. """ if isinstance(tokens, str): one_token = True tokens = [tokens] else: ...
0
function_simple
huggingface/transformers:src/transformers/tokenization_mistral_common.py:MistralCommonBackend.convert_tokens_to_ids
agent_id: str, action: str, delegation_id: Optional[str] = None) -> bool: """Validate if an agent can perform an action under their delegation""" if delegation_id: delegation = self.delegations.get(delegation_id) if not delegation: return False ...
0
function_complex
Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/multi_agent_trust_layer/multi_agent_trust_layer.py:DelegationManager.validate_action
int = 96, min_len: int = 5, max_len: int = 100): """Create a mock Ray dataset with random text and labels.""" numbers = random.choices(range(min_len, max_len + 1), k=dataset_size) ray_dataset = ray.data.from_items(numbers) def map_to_text_and_label(item): length = item['item'] text = r...
0
function_simple
ray-project/ray:doc/source/train/doc_code/random_text_generator.py:create_mock_ray_text_dataset
if not self.test_attention_slicing: return components = self.get_dummy_components() pipe = self.pipeline_class(**components) for component in pipe.components.values(): if hasattr(component, "set_default_attn_processor"): component.set_default_attn_proce...
1
test
huggingface/diffusers:tests/pipelines/qwenimage/test_qwenimage_img2img.py:QwenImageImg2ImgPipelineFastTests.test_attention_slicing_forward_pass
def test_foreign_key_exists_case_sensitive(self, mock_inspect): """Test case sensitivity of foreign key name matching.""" mock_inspector = Mock() mock_inspector.get_foreign_keys.return_value = [{"name": "FK_User_ID", "constrained_columns": ["user_id"]}] mock_inspect.return_value = mock_i...
1
test
langflow-ai/langflow:src/backend/tests/unit/utils/test_migration.py:TestForeignKeyExists.test_foreign_key_exists_case_sensitive
2-5 start_time = time.time() print(f'🎯 URL Search: {url}') print(f"🔍 Looking for: '{query}'") print(f'📊 Navigation depth: {depth}') print(f'💰 Estimated cost: {depth}¢') payload = {'url': url, 'query': query, 'depth': depth} timeout = aiohttp.ClientTimeout(total=TIMEOUT) connector = aiohttp.TCPConnector...
0
function_simple
browser-use/browser-use:examples/cloud/05_search_api.py:search_url
for i in range(0, len(query_embeddings), batch_size): batch_scores: list[torch.Tensor] = [] batch_queries = torch.nn.utils.rnn.pad_sequence( query_embeddings[i : i + batch_size], batch_first=True, padding_value=0 ) for j in range(0, len(passage_embeddi...
0
function_complex
huggingface/transformers:src/transformers/models/colmodernvbert/modular_colmodernvbert.py:ColModernVBertProcessor.score_retrieval
delegator_identity = self._known_identities.get(delegation.delegator) if not delegator_identity: return False delegation_data = json.dumps( { "delegator": delegation.delegator, "delegatee": delegation.delegatee, ...
1
function_complex
run-llama/llama_index:llama-index-integrations/agent/llama-index-agent-agentmesh/llama_index/agent/agentmesh/trust.py:DelegationChain.verify
from crewai.events.event_bus import crewai_event_bus from crewai.events.types.flow_events import FlowInputReceivedEvent events_captured: list[FlowInputReceivedEvent] = [] class MetadataProvider: def request_input( self, message: str, flow: Flow[Any], metadata: di...
0
test
crewAIInc/crewAI:lib/crewai/tests/test_flow_ask.py:TestAskMetadata.test_ask_metadata_in_received_event
llm=llm, prompt=_prompt, callbacks=callbacks, **(llm_chain_kwargs or {}), ) document_prompt = PromptTemplate( input_variables=["page_content"], template="Context:\n{page_content}", ) combine_documents_chain = StuffDocumen...
1
function_simple
langchain-ai/langchain:libs/langchain/langchain_classic/chains/retrieval_qa/base.py:BaseRetrievalQA.from_llm
def test_lt(runner: CliRunner, root_dir: Path, copy_test_files): result = runner.invoke( cli, ["fix-pages", "docs/lang/docs/doc.md"], ) # assert result.exit_code == 1, result.output fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text("utf-8") expected_content ...
1
test
fastapi/fastapi:scripts/tests/test_translation_fixer/test_markdown_links/test_mkd_links_number_mismatch.py:test_lt
"""Generate a new CMVK identity with Ed25519 key pair.""" seed = f"{agent_name}:{time.time_ns()}" did_hash = hashlib.sha256(seed.encode()).hexdigest()[:32] did = f"did:cmvk:{did_hash}" private_key_obj = ed25519.Ed25519PrivateKey.generate() public_key_obj = private_key_obj.pu...
1
function_simple
run-llama/llama_index:llama-index-integrations/agent/llama-index-agent-agentmesh/llama_index/agent/agentmesh/identity.py:CMVKIdentity.generate
1k(self, WebApiAuth, add_document): chunks_num = 1_000 _, doc_id = add_document chunk_ids = batch_add_chunks(WebApiAuth, doc_id, chunks_num) from time import sleep sleep(1) res = delete_chunks(WebApiAuth, {"doc_id": doc_id, "chunk_ids": chunk_ids}) assert res["...
1
test
infiniflow/ragflow:test/testcases/test_web_api/test_chunk_app/test_rm_chunks.py:TestChunksDeletion.test_delete_1k
or transport manager for the given tensor transport protocol. Args: transport_name: The tensor transport protocol to use for the GPU object. Returns: TensorTransportManager: The tensor transport manager for the given tensor transport protocol. """ global transport_manager_info glob...
0
function_simple
ray-project/ray:python/ray/experimental/gpu_object_manager/util.py:get_tensor_transport_manager
-------- Assert that typing did not trigger a rerun or open the clear-cache dialog: >>> expect_global_hotkeys_not_fired(app, expected_runs=1) """ # Rerun hotkey: must not start a script run while we're typing. expect(app.get_by_test_id("stApp")).to_have_attribute( "data-test-script-st...
1
function_simple
streamlit/streamlit:e2e_playwright/shared/input_utils.py:expect_global_hotkeys_not_fired
bar( themed_app: Page, assert_snapshot: ImageCompareFunction ) -> None: select_subtest(themed_app, "large_logo_w_sidebar_subtest") expect(themed_app.get_by_test_id("stSidebar")).to_be_visible() expect(themed_app.get_by_test_id("stSidebarHeader")).to_be_visible() expect(themed_app.get_by_test_id("st...
1
test
streamlit/streamlit:e2e_playwright/st_logo_test.py:test_large_logo_w_sidebar
# to expiration now = datetime.now(timezone.utc) created_at = datetime.fromisoformat(credential_json["created_at"]) expires_in: int = credential_json["expires_in"] renew_at = created_at + timedelta(seconds=expires_in // 2) if now <= renew_at: # cached/current creden...
1
function_complex
infiniflow/ragflow:common/data_source/confluence_connector.py:OnyxConfluence._renew_credentials
httpx.Request("GET", "https://api.example.com/1"), httpx.Request("POST", "https://api.example.com/2"), httpx.Request("PUT", "https://api.example.com/3"), ] for req in requests: transport.handle_request(req) # Verify all...
0
test
crewAIInc/crewAI:lib/crewai/tests/llms/hooks/test_transport.py:TestTransportIntegration.test_multiple_requests_same_interceptor
colors = [ self._ensure_visible_color( raw_colors[i] if i < len(raw_colors) else None, self.DEFAULT_COLORS[i % len(self.DEFAULT_COLORS)] ) for i in range(len(labels)) ] # 计算角度 theta...
1
function_complex
666ghj/BettaFish:ReportEngine/renderers/chart_to_svg.py:ChartToSVGConverter._render_polarArea
ResolverParsingError: If the content within the string cannot be parsed. ValueError: If the input is invalid or does not contain expected format. """ if not input_string or not isinstance(input_string, str): logging.error("Input string must be a non-empty string.") raise ValueError("In...
1
function_simple
google/langextract:langextract/resolver.py:Resolver.string_to_extraction_data
': return ChatOpenAI # type: ignore elif name == 'ChatAzureOpenAI': return ChatAzureOpenAI # type: ignore elif name == 'ChatGoogle': return ChatGoogle # type: ignore elif name == 'ChatMistral': return ChatMistral # type: ignore elif name == 'ChatOCIRaw': if not OCI_AVAILABLE: raise ImportError('O...
0
function_complex
browser-use/browser-use:browser_use/llm/models.py:__getattr__
as tmpdir: with open(os.path.join(tmpdir, "build.sh"), "w") as f: f.write("echo hello") ctx = make_build_context( base_dir=tmpdir, envs={"ZZZ": "last", "AAA": "first"}, post_build_script="build.sh", ) encoded = encode_build_context(ctx) ...
0
test
ray-project/ray:release/ray_release/tests/test_byod_build_context.py:test_encode_build_context
( self, init_overrides: Optional[Dict[str, Any]] = None, ) -> "StatsBase": """Returns a new stats object with the same settings as `self`. Args: init_overrides: Optional dict of initialization arguments to override. Can be used to change is_root, is_leaf, etc. R...
0
function_simple
ray-project/ray:rllib/utils/metrics/stats/base.py:StatsBase.clone
: # noqa: S110 pass crew._task_output_handler.reset() crew._logging_color = "bold_purple" # Check for flow input files in baggage context (inherited from parent Flow) _flow_files = baggage.get_baggage("flow_input_files") flow_files: dict[str, Any] = _flow_files if isinstance(_flow_fil...
0
function_complex
crewAIInc/crewAI:lib/crewai/src/crewai/crews/utils.py:prepare_kickoff
are included in completion params when set """ from crewai.llms.providers.azure.completion import AzureCompletion with patch.dict(os.environ, { "AZURE_API_KEY": "test-key", "AZURE_ENDPOINT": "https://models.inference.ai.azure.com" }): llm = LLM( model="azure/gpt-4",...
0
test
crewAIInc/crewAI:lib/crewai/tests/llms/azure/test_azure.py:test_azure_complete_params_include_optional_params
_labels(self): """Test that component-specific labels take precedence over global labels with the same key.""" docs = render_chart( values={ "statsd": { "enabled": True, "labels": {"common_label": "component_value"}, }, ...
1
test
apache/airflow:helm-tests/tests/helm_tests/statsd/test_labels_deployment.py:TestStatsdDeployment.test_component_specific_labels_should_override_global_labels
text for wrapping long sentences in english language" wrapped_text_en, text_height_en = vd.wrap_text( text=test_text_en, max_width=300, font=font_path, fontsize=30 ) print(wrapped_text_en, text_height_en) ...
0
test
harry0703/MoneyPrinterTurbo:test/services/test_video.py:TestVideoService.test_wrap_text
generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for each generated token), with each tensor of shape `(batch_size, config.vocab_size)`. attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`): Tuple (one elem...
0
documentation
huggingface/transformers:src/transformers/models/parakeet/modular_parakeet.py:ParakeetGenerateOutput:class_doc
available_skills)} available skills from API') # Determine which skills to load if use_wildcard: logger.info('Wildcard "*" detected, loading first 100 skills') skills_to_load = all_available_skills else: # Load only the requested skill IDs skills_to_load = [skill for skill in all_available_ski...
0
function_complex
browser-use/browser-use:browser_use/skills/service.py:SkillService.async_init
text_str = text_val if isinstance(text_val, str) else ("" if text_val is None else str(text_val)) marks_raw = run.get("marks") if isinstance(run.get("marks"), list) else [] marks_filtered: List[Dict[str, Any]] = [] for mark in marks_raw: ...
1
function_complex
666ghj/BettaFish:ReportEngine/nodes/chapter_generation_node.py:ChapterGenerationNode._sanitize_engine_quote_block
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored ...
0
function_simple
huggingface/transformers:src/transformers/models/lfm2_vl/modular_lfm2_vl.py:Lfm2VlForConditionalGeneration.forward
np.zeros((height, width, 3)), size=(size["longest_edge"], size["longest_edge"]), patch_size=patch_size, ) num_height_tokens = resized_height // self.effective_patch_size num_width_tokens = resized_width // self.effective_p...
0
function_complex
huggingface/transformers:src/transformers/models/lighton_ocr/modular_lighton_ocr.py:LightOnOcrProcessor._get_num_multimodal_tokens
"release-management", "prepare-task-sdk-distributions", "--distribution-format", "both", ], cwd=str(self.airflow_repo_root), check=False, capture_output=True, text=True, ) if result.returncode !...
1
function_complex
apache/airflow:dev/breeze/src/airflow_breeze/utils/airflow_release_validator.py:AirflowReleaseValidator.build_packages
await get_and_cache_all_types_dict(settings_service) # Check if component type exists in the cache if ( component_cache.all_types_dict and "components" in component_cache.all_types_dict and component_type in component_cache.all_types_dict["components"] ): # If in lazy mod...
1
function_complex
langflow-ai/langflow:src/lfx/src/lfx/interface/components.py:get_type_dict
return_value=mock_embedding_func, ): config = { "embedding_model": { "provider": "cohere", "config": { "model": "embed-english-v3.0", "api_key": "test-cohere-key", }, } } t...
0
test
crewAIInc/crewAI:lib/crewai-tools/tests/tools/test_txt_search_tool_config.py:test_txt_search_tool_with_cohere_config
_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, 8192, dtype=torch.bfloat16, device="cuda...
1
test
vllm-project/vllm:tests/kernels/helion/test_silu_mul_fp8.py:TestSiluMulFp8ConfigPicker.test_config_picker_default_ignored_when_valid_keys_exist
self.logits_indices[:q_len].zero_() self.output_ids[:q_len].zero_() # Reset the attributes that are either tensors or dict of tensors for layer_type in self.cumulative_seqlens_k: self.max_seqlen_k[layer_type] = 0 if self.attention_mask is not None: ...
0
function_simple
huggingface/transformers:src/transformers/generation/continuous_batching/input_outputs.py:ContinuousBatchingIOs._reset_static_tensors
vector_store: VolcengineMySQLVectorStore, embed_model: ArkEmbedding, question: str ) -> None: """Demonstrate async query capabilities.""" print(f"\n=== Async Similarity search for: {question!r} ===") query_embedding = await embed_model.aget_query_embedding(question) vs_query = VectorStoreQuery( ...
1
function_complex
run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-volcenginemysql/examples/volcengine_mysql_vector_store_demo.py:run_async_query_demo