input string | label int64 | category string | sample_id string |
|---|---|---|---|
tokenize=True,
add_generation_prompt=True,
return_dict=True,
return_tensors="pt",
padding=True,
).to(torch_device)
output = model.generate(**inputs, max_new_tokens=3)
EXPECTED_DECODED_TEXT = ["\n012345Describe this video.\n<think>Got it"] # ... | 0 | test | huggingface/transformers:tests/models/glm4v_moe/test_modeling_glm4v_moe.py:Glm4vMoeIntegrationTest.test_small_model_integration_test_with_video |
ames: list[str],
size: int,
coverage_ratio: float,
status: str,
mocker: pytest_mock.MockerFixture) -> None:
""" Test cache.get_cache function when the cache does not yet exist """
mocker.patch(f"{MODULE_P... | 1 | test | deepfakes/faceswap:tests/lib/training/cache_test.py:test_get_cache_initial |
"""Validate that the serialization methods are supported."""
valid_methods = {
SerializationMethod.CLOUDPICKLE,
SerializationMethod.PICKLE,
SerializationMethod.MSGPACK,
SerializationMethod.ORJSON,
SerializationMethod.NOOP,
}
if self.... | 0 | function_simple | ray-project/ray:python/ray/serve/_private/serialization.py:RPCSerializer._validate_methods |
confirms Serve doesn't block it, allowing vLLM to manage its constraints.
"""
llm_config = get_llm_config_with_placement_group(
tensor_parallel_size=1,
pipeline_parallel_size=1,
placement_group_config={
"bundles": [{"GPU": 2, "CPU": 4}],
"strategy": "PACK",
... | 0 | test | ray-project/ray:python/ray/llm/tests/serve/cpu/configs/test_multi_node_placement_groups.py:test_llm_serve_multi_gpu_per_bundle_passes_through |
triggers retry."""
call_count = [0]
headers_captured = []
def get_side_effect(url, headers=None, **kwargs):
call_count[0] += 1
headers_captured.append(headers.get("Authorization", ""))
if call_count[0] == 1:
return MockResponse(status_code=40... | 0 | test | ray-project/ray:python/ray/data/tests/datasource/test_uc_datasource.py:TestUnityCatalogConnector401Retry.test_401_during_get_table_info |
,
agent_cards=agent_cards_dict,
remote_status_notice=remote_status_notice,
)
original_response_model = task.response_model
if disable_structured_output:
task.response_model = None
raw_result = await original_fn(self, task, context, tools)
if disable_structured_output:
... | 0 | function_simple | crewAIInc/crewAI:lib/crewai/src/crewai/a2a/wrapper.py:_ahandle_agent_response_and_continue |
warnings.simplefilter("always", DeprecationWarning)
proxy_str = "23.95.150.145:6114:username:password"
with warnings.catch_warnings(record=True) as caught:
cfg = BrowserConfig(proxy=proxy_str, headless=True)
dep_warnings = [w for w in caught if issubclass(w.category, DeprecationWarning)]
as... | 1 | test | unclecode/crawl4ai:tests/proxy/test_proxy_deprecation.py:test_browser_config_proxy_string_emits_deprecation_and_autoconverts |
test_offline_policy_evaluation_runner_setup(self):
"""Test the setup of the `OfflinePolicyEvaluationRunner`.
Checks that after instantiation, the runner has a valid config and
a `MultiRLModule`.
"""
# Create an `OfflinePolicyEvaluationRunner` instance.
offline_policy_ev... | 0 | test | ray-project/ray:rllib/offline/tests/test_offline_policy_evaluation_runner.py:TestOfflineEvaluationRunner.test_offline_policy_evaluation_runner_setup |
ames = {"x"} if "x" not in output
"""
output_column_names = {
expr.name for expr in upstream_project.exprs if not isinstance(expr, StarExpr)
}
# Compose column definitions in the form of a mapping of
# - Target column name
# - Target expression
output_column_defs = {
exp... | 0 | function_simple | ray-project/ray:python/ray/data/_internal/logical/rules/projection_pushdown.py:_analyze_upstream_project |
"""
初始化客户端。
Args:
api_key: Tavily API密钥,若不提供则从环境变量 TAVILY_API_KEY 读取。
"""
if api_key is None:
api_key = os.getenv("TAVILY_API_KEY")
if not api_key:
raise ValueError("Tavily API Key未找到!请设置TAVILY_API_KEY环境变量或在初始化时提供")
| 1 | function_simple | 666ghj/BettaFish:QueryEngine/tools/search.py:TavilyNewsAgency.__init__ |
ception(self):
"""Test that multiple fonts in code font source raises StreamlitAPIException."""
msg = CustomThemeConfig()
with pytest.raises(StreamlitAPIException) as exc_info:
parse_fonts_with_source(
msg,
body_font_config=None,
code_f... | 1 | test | streamlit/streamlit:lib/tests/streamlit/runtime/theme_util_test.py:TestParseFontsWithSource.test_code_font_multiple_families_raises_exception |
""
# If this came via a named $ref, use that name
if "$ref" in subschema:
refname = subschema["$ref"].split("/")[-1]
if refname in model_cache:
return model_cache[refname]
target = defs.get(refname)
if not target:
msg = f"De... | 1 | function_complex | langflow-ai/langflow:src/lfx/src/lfx/schema/json_schema.py:_build_model |
feedback_collapsing(self, mock_print, mock_input):
"""Test that feedback is collapsed to an outcome."""
class TestFlow(Flow):
@start()
@human_feedback(
message="Review:",
emit=["approved", "rejected"],
llm="gpt-4o-mini",
... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/test_human_feedback_decorator.py:TestHumanFeedbackExecution.test_feedback_collapsing |
_valkey_client):
"""Test get method with binary data that fails UTF-8 decoding."""
# Mock result with binary data that can't be decoded
mock_result = {
"memory_id": "test_id",
"hash": b"\xff\xfe", # Invalid UTF-8 bytes
"memory": "test_memory",
"created_at": "1234567890",
... | 1 | test | mem0ai/mem0:tests/vector_stores/test_valkey.py:test_get_with_binary_data_and_unicode_error |
response_format: JSONSchema = {
'name': 'agent_output',
'strict': True,
'schema': SchemaOptimizer.create_optimized_json_schema(
output_format,
remove_min_items=self.remove_min_items_from_schema,
remove_defaults=self.remove_defaults_from_schema,
),
}
# Add JSON schema to... | 0 | function_complex | browser-use/browser-use:browser_use/llm/openai/chat.py:ChatOpenAI.ainvoke |
delete_instance_cancels_only_matching_tasks(
instance: Instance,
):
# arrange
instance_id_a = InstanceId()
instance_id_b = InstanceId()
current_instances: dict[InstanceId, Instance] = {
instance_id_a: instance,
instance_id_b: instance,
}
# only delete instance A, keep instanc... | 0 | test | exo-explore/exo:src/exo/master/tests/test_placement.py:test_get_transition_events_delete_instance_cancels_only_matching_tasks |
if do_assert:
assert metric in resp
if metric not in resp:
return False
return True
# Trigger HTTP 404 error via the deployed application
httpx.get("http://127.0.0.1:8000/A/nonexistent")
httpx.get("http://127.0.0.1:8000/A/nonexistent")
# Ensure all ... | 0 | test | ray-project/ray:python/ray/serve/tests/test_metrics_haproxy.py:test_proxy_metrics_not_found |
module = _load_system_module(monkeypatch)
monkeypatch.setattr(module, "run_health_checks", lambda: ({"status": "ok"}, True))
payload, status = module.healthz()
assert status == 200
assert payload["status"] == "ok"
monkeypatch.setattr(module, "run_health_checks", lambda: ({"status": "degraded"}, ... | 1 | test | infiniflow/ragflow:test/testcases/test_web_api/test_system_app/test_system_routes_unit.py:test_healthz_and_oceanbase_status_matrix_unit |
g1_alphas: torch.Tensor,
g2_alphas: torch.Tensor,
per_act_token_quant: bool = False,
per_out_ch_quant: bool = False,
block_shape: list[int] | None = None,
) -> FusedMoEQuantConfig:
"""
Construct a quant config for fp8 activations and int4 weights.
"""
return FusedMoEQuantConfig.make(... | 1 | function_simple | vllm-project/vllm:vllm/model_executor/layers/fused_moe/config.py:int4_w4afp8_moe_quant_config |
msg = f"File not found: {old_path}"
raise ValueError(msg)
# Create parent directory for new path
new_full.parent.mkdir(parents=True, exist_ok=True)
# Rename
old_full.rename(new_full)
return Command(
update={
"messages": [
... | 1 | function_simple | langchain-ai/langchain:libs/partners/anthropic/langchain_anthropic/middleware/anthropic_tools.py:_FilesystemClaudeFileToolMiddleware._handle_rename |
},
},
"required": [
"title",
"timestamp",
],
"title": "Item",
"type": "object",
},
| 1 | test | fastapi/fastapi:tests/test_tutorial/test_encoder/test_tutorial001.py:test_openapi_schema |
__init__() # type: ignore[call-arg]
try:
from linkup import LinkupClient
except ImportError:
import click
if click.confirm(
"You are missing the 'linkup-sdk' package. Would you like to install it?"
):
import subprocess
... | 0 | function_simple | crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/linkup/linkup_search_tool.py:LinkupSearchTool.__init__ |
= self._doc.read_to_next_empty_line()
summary_str = " ".join([s.strip() for s in summary]).strip()
compiled = re.compile(r"^([\w., ]+=)?\s*[\w\.]+\(.*\)$")
if compiled.match(summary_str):
self["Signature"] = summary_str
if not self._is_at_section():
... | 0 | function_complex | scikit-learn/scikit-learn:sklearn/externals/_numpydoc/docscrape.py:NumpyDocString._parse_summary |
command,
check=False,
shell=isinstance(command, str),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
return_code = result.returncode
log.info("Execution completed for task %s with return code %s", task_key, return_code)
log.info(... | 1 | function_simple | apache/airflow:providers/amazon/src/airflow/providers/amazon/aws/executors/aws_lambda/docker/app.py:run_and_report |
if self.image_processing_class is None or self.fast_image_processing_class is None:
self.skipTest(reason="Skipping slow/fast equivalence test as one of the image processors is not defined")
dummy_image = self.image_processor_tester.prepare_image_inputs(
equal_resolution=False, numpify=... | 0 | test | huggingface/transformers:tests/models/efficientloftr/test_image_processing_efficientloftr.py:EfficientLoFTRImageProcessingTest.test_slow_fast_equivalence |
"medium"
advanced_params = task.advanced_params
if advanced_params is not None and advanced_params.seed is not None:
base_seed = advanced_params.seed
else:
base_seed = random.randint(0, 2**32 - 1)
is_bench = getattr(task, "bench", False)
num_images = task.n or 1
generation_st... | 0 | function_complex | exo-explore/exo:src/exo/worker/engines/image/generate.py:generate_image |
Attributes:
requires_input: Whether this evaluator requires an
input string. Always False.
requires_reference: Whether this evaluator requires
a reference string. Always True.
evaluation_name: The name of the evaluation metric.
Always "parsed_equality".
Examples:
>>> evaluator... | 1 | documentation | langchain-ai/langchain:libs/langchain/langchain_classic/evaluation/parsing/base.py:JsonEqualityEvaluator:class_doc |
information?"""
if not state.new_terms_history:
return 0.0
if len(state.new_terms_history) < 2:
return 0.0 # Not enough history
# Calculate rate of new term discovery
recent_rate = state.new_terms_history[-1] if state.new_terms_history[... | 1 | function_simple | unclecode/crawl4ai:crawl4ai/adaptive_crawler copy.py:StatisticalStrategy._calculate_saturation |
self.parent_connection.close()
self.process.join(timeout=2.0)
if self.process.is_alive():
self.process.terminate()
if gpu_utilization:
timestamp_0 = timestamps[0]
metrics = GPURawMetrics(
utilization=gpu_utilization,
me... | 0 | function_complex | huggingface/transformers:benchmark_v2/framework/hardware_metrics.py:GPUMonitor.stop_and_collect |
AdaptiveCrawler(crawler, config)
result = await adaptive.digest(start_url=url, query=query)
print("\n" + "="*50)
print("CRAWL STATISTICS")
print("="*50)
adaptive.print_stats(detailed=False)
# Get the most relevant content found
print("\n" + "="*... | 1 | function_complex | unclecode/crawl4ai:docs/examples/adaptive_crawling/llm_config_example.py:test_configuration |
auth_url": "http://auth",
"oauth_token_url": "http://token",
}
legacy_url = "http://test/legacy-sse"
streamable_url = "http://test/streamable"
mcp_service._start_locks[project_id] = asyncio.Lock()
mock_process = MagicMock(pid=4321)
with (
patch.o... | 1 | test | langflow-ai/langflow:src/lfx/tests/unit/services/settings/test_mcp_composer.py:TestPortChangeHandling.test_legacy_sse_url_preserved_in_composer_state |
from ..plugins.trainer_plugins.distributed.hub import DistributedPlugin
DistributedPlugin(self.args.dist_config.name).save_model(
self.model, self.args.output_dir, self.renderer.processor
)
else:
model_to_save = self.model.module if hasattr(self.model... | 1 | function_simple | hiyouga/LlamaFactory:src/llamafactory/v1/core/base_trainer.py:BaseTrainer.save_model |
frame
torch.testing.assert_close(
frames[:3, :, :, :2, :2],
torch.tensor(
[
[[[[-12.3525, -12.3525], [-13.0608, -13.0608]]]],
[[[[-15.8181, -15.8181], [-16.4163, -16.4163]]]],
[[[[-15.8900, -15.8900], [-16.5953,... | 0 | test | huggingface/transformers:tests/models/sam2_video/test_modeling_sam2_video.py:Sam2VideoModelIntegrationTest.test_inference_mask_generation_video_one_point_one_bb |
usr/share/nltk_data``, ``/usr/local/share/nltk_data``,
``/usr/lib/nltk_data``, ``/usr/local/lib/nltk_data``, ``~/nltk_data``.
"""
# Check if we are on GAE where we cannot write into filesystem.
if "APPENGINE_RUNTIME" in os.environ:
return
# Check if we have sufficien... | 1 | function_complex | binary-husky/gpt_academic:shared_utils/nltk_downloader.py:Downloader.default_download_dir |
ers
device: (`torch.device`):
torch device
num_images_per_prompt (`int`):
number of images that should be generated per prompt
prompt_embeds (`torch.FloatTensor`, *optional*):
Pre-generated text embeddings. Can be used to easily tweak t... | 1 | function_complex | huggingface/diffusers:src/diffusers/pipelines/flux/pipeline_flux_kontext.py:FluxKontextPipeline.encode_prompt |
target_dtype = self.patch_embedding.weight.dtype
if isinstance(self.patch_embedding, LinearBase):
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype))
elif isinstance(self.patch_embedding, Conv2dLayer):
pixel_values = pixel_values.view(
-1... | 1 | function_simple | vllm-project/vllm:vllm/model_executor/models/siglip2navit.py:Siglip2VisionEmbeddings.forward |
}
},
}
},
]
],
}
result = strip_dynamic_fields_func(data)
assert result["version"] == "1.7.0"
assert result["metadata"]["num_modules"] == 95
model_value = result["entri... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/test_strip_dynamic_fields.py:TestStripDynamicFields.test_complex_nested_structure |
# Test that each format either succeeds or fails gracefully
with contextlib.suppress(typer.Exit):
run(
script_path=simple_chat_script,
input_value="Test input",
input_value_option=None,
verbose=False,
... | 1 | test | langflow-ai/langflow:src/lfx/tests/unit/cli/test_run_command.py:TestRunCommand.test_execute_python_script_different_formats |
operator = PowerBIWorkspaceListOperator(
**CONFIG_WORKSPACES,
)
context = {"ti": MagicMock()}
with pytest.raises(AirflowException) as exc:
operator.execute_complete(
context=context,
event={
"status": "error",
... | 1 | test | apache/airflow:providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_powerbi_list.py:TestPowerBIWorkspaceListOperator.test_powerbi_operator_async_execute_complete_fail |
Height of the input image.
width (`int`):
Width of the input image.
images_kwargs (`dict`, *optional*):
Any kwargs to override defaults of the image processor.
Returns:
`int`: Number of image patches per image.
"""
... | 1 | function_simple | vllm-project/vllm:vllm/transformers_utils/processors/hunyuan_vl_image.py:HunYuanVLImageProcessor.get_number_of_image_patches |
(os.environ, {
"AZURE_API_KEY": "test-key",
"AZURE_ENDPOINT": "https://test.openai.azure.com/openai/deployments/gpt-4"
}):
llm_openai = LLM(model="azure/gpt-4")
assert llm_openai.is_azure_openai_endpoint == True
with patch.dict(os.environ, {
"AZURE_API_KEY": "test-key",
... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/llms/azure/test_azure.py:test_azure_endpoint_detection_flags |
current accelerator."""
device = get_current_accelerator()
is_tensor = isinstance(data, torch.Tensor)
is_ndarray = isinstance(data, np.ndarray)
if is_tensor:
orig_device = data.device
data = data.to(device=device)
elif is_ndarray:
data = torch.from_numpy(data).to(device=dev... | 1 | function_complex | hiyouga/LlamaFactory:src/llamafactory/v1/accelerator/helper.py:operate_tensorlike |
console.print("[cyan]URL Seeder Configuration:[/cyan]")
console.print(f" - Source: {seeding_config.source}")
console.print(f" - Pattern: {seeding_config.pattern}")
console.print(f" - Max URLs: {seeding_config.max_urls}")
console.print(f" - Query: {seeding_config.query}")
console.print(f" - Sc... | 1 | function_simple | unclecode/crawl4ai:docs/releases_review/demo_v0.7.0.py:demo_4_url_seeder |
logger.exception("无法修复JSON,直接使用清理后的文本")
# 如果不是JSON格式,直接返回清理后的文本
return cleaned_output
# 提取段落内容
if isinstance(result, dict):
paragraph_content = result.get("paragraph_latest_state", "")
if paragraph_co... | 1 | function_complex | 666ghj/BettaFish:MediaEngine/nodes/summary_node.py:FirstSummaryNode.process_output |
_provider(
self, credential_provider_arg
):
"""Test that EnvironmentCredentialProvider is returned when none provided."""
with mock.patch.dict(
os.environ, {"DATABRICKS_TOKEN": "token", "DATABRICKS_HOST": "host"}
):
if credential_provider_arg == "no_arg":
... | 0 | test | ray-project/ray:python/ray/data/tests/datasource/test_databricks_credentials.py:TestResolveCredentialProvider.test_resolve_with_none_returns_environment_provider |
Encoding header"""
data = "compress-me"
# send a request to mock resource that gzip encodes the "data" url parameter
request = Request(
mockserver.url(f"/compress?data={data}", is_secure=self.is_secure),
headers={
"accept-encoding": "gzip",
}... | 1 | test | scrapy/scrapy:tests/test_downloader_handlers_http_base.py:TestHttpBase.test_download_is_not_automatically_gzip_decoded |
获取 RSS 源状态
Returns:
RSS 源状态信息
"""
try:
status = self.data_service.get_rss_feeds_status()
return {
**status,
"success": True
}
except MCPError as e:
return {
"success": ... | 1 | function_simple | sansan0/TrendRadar:mcp_server/tools/data_query.py:DataQueryTools.get_rss_feeds_status |
padding_cache=padding_cache,
return_dict=True,
use_cache=use_cache,
use_padding_cache=use_cache,
**kwargs,
)
audio_hidden_states = audio_outputs.last_hidden_state
audio_hidden_states = audio_hidden_states.reshape(
audio_hidden_s... | 0 | function_simple | huggingface/transformers:src/transformers/models/voxtral_realtime/modular_voxtral_realtime.py:VoxtralRealtimeForConditionalGeneration.get_audio_features |
()
llm.supports_function_calling.return_value = True
# After intra-batch dedup (identical embeddings), only 1 item survives.
# That item hits parallel_analyze which calls analyze_for_consolidation.
# The single-item call returns a ConsolidationPlan directly.
llm.call.return_value = ConsolidationPlan... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/memory/test_unified_memory.py:test_batch_consolidation_deduplicates_against_storage |
compute(optimize_graph=False)
assert result == pinned_node.unique_id
# Test compute global Ray remote args.
c = dask.delayed(get_node_id)
result = c().compute(ray_remote_args={"resources": {"pin": 0.01}})
assert result == pinned_node.unique_id
# Test annotations on collection override global... | 0 | test | ray-project/ray:python/ray/util/dask/tests/test_dask_multi_node.py:test_ray_dask_resources |
blocks importing of unsafe modules.
Args:
name: The name of the module to import.
custom_globals: Global namespace to use.
custom_locals: Local namespace to use.
fromlist: List of items to import from the module.
level: The level value passed to __im... | 0 | function_simple | crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/code_interpreter_tool/code_interpreter_tool.py:SandboxPython.restricted_import |
key_values,
inputs_embeds=inputs_embeds,
cache_position=cache_position,
**kwargs,
)
hidden_states = outputs[0]
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
slice_indices = slice(-logits_to_keep, No... | 0 | function_simple | huggingface/transformers:src/transformers/models/qwen3_vl_moe/modular_qwen3_vl_moe.py:Qwen3VLMoeForConditionalGeneration.forward |
)
else:
raise TimeoutError("Polling timed out before job completed.")
# Step 3: Retrieve result
async with session.get(
f"{BRIGHTDATA_API_URL}/datasets/v3/snapshot/{snapshot_id}",
params={"format": output_format},
... | 0 | function_complex | crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/brightdata_tool/brightdata_dataset.py:BrightDataDatasetTool.get_dataset_data_async |
If the latter, the path must be a network-mounted file system (e.g.
`/mnt/cluster_storage/`) that is accessible to the entire cluster.
If not set, defaults to `RAY_DATA_CHECKPOINT_PATH_BUCKET/ray_data_checkpoint`.
delete_checkpoint_on_success: If true, automatically delete checkpoint
... | 0 | documentation | ray-project/ray:python/ray/data/checkpoint/interfaces.py:CheckpointConfig:class_doc |
0:
logger.warning(
f"networksetup -listnetworkserviceorder failed with code "
f"{result.returncode}: {result.stderr.decode()}"
)
return None
# Parse service order to find bridge devices and their service names
# Format: "(1) Service Name\n(Hardware Port: ..., De... | 0 | function_complex | exo-explore/exo:src/exo/utils/info_gatherer/info_gatherer.py:_get_bridge_services |
yield {"type": "non_standard", "value": block}
elif (
block_type == "image"
and "source" in block
and "type" in block["source"]
):
if block["source"]["type"] == "base64":
image_block: types.ImageContentBlock =... | 1 | function_complex | langchain-ai/langchain:libs/core/langchain_core/messages/block_translators/anthropic.py:_convert_to_v1_from_anthropic_input |
return False
wait_for_condition(check_proxy_status, timeout=30)
# Verify the metric has the expected tags
metrics = get_metric_dictionaries(
"ray_serve_proxy_status", timeseries=timeseries
)
assert len(metrics) >= 1
for metric in metrics:
... | 0 | test | ray-project/ray:python/ray/serve/tests/test_metrics_2.py:TestProxyStateMetrics.test_proxy_status_metric |
dot_naming(self, layer: dict[str, T.Any]):
""" Sometime between 3.3.3 and 3.12 (during beta testing) layers with "." in the name
started generating a KeyError. This is odd as the error comes from Torch, but dot naming is
standard. To work around this all dots (.) in layer names have been convert... | 1 | function_simple | deepfakes/faceswap:plugins/train/model/_base/update.py:PatchKerasConfig._update_dot_naming |
"cupy-cuda12x",
"dm-tree",
"fastrlock",
"filelock",
"frozenlist",
"google-auth",
"grpcio",
"idna",
"jinja2",
"jsonschema",
"markupsafe",
... | 0 | test | ray-project/ray:ci/raydepsets/tests/test_cli.py:TestCli.test_parse_large_lock_file |
_padding(self, tokenizer: TokenizerLike | None, tokens: _S) -> _S:
"""Apply padding to prompt tokens if necessary."""
pad_length = self.pad_prompt_tokens
if pad_length is not None and pad_length < 0:
pad_length = self.max_input_tokens
if pad_length is None or pad_length <= l... | 1 | function_complex | vllm-project/vllm:vllm/renderers/params.py:TokenizeParams._token_padding |
)
],
),
]
)
api_client = api_client_maker(
path="/api/v2/config",
response_json=response_config.model_dump(),
expected_http_status_code=200,
kind=ClientKind.CLI,
)
api_cli... | 1 | test | apache/airflow:airflow-ctl/tests/airflow_ctl/ctl/commands/test_config_command.py:TestCliConfigCommands.test_lint_detects_renamed_configs_different_section |
def test_required_list_str_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
"p_alias": {
"items": {"type": "string"},
... | 1 | test | fastapi/fastapi:tests/test_request_params/test_form/test_list.py:test_required_list_str_alias_schema |
Response)
mock_response.status_code = 200
mock_response.ok = True
mock_response.json.return_value = {
"sample_payload": {"key": "value", "data": "test"}
}
self.mock_client.get_trigger_payload.return_value = mock_response
self.triggers_command.execute_with_tri... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/cli/triggers/test_main.py:TestTriggersCommand.test_execute_with_trigger_success |
.tool.description if request.tool else "No description available"
# Build prompt for emulator LLM
prompt = (
f"You are emulating a tool call for testing purposes.\n\n"
f"Tool: {tool_name}\n"
f"Description: {tool_description}\n"
f"Arguments: {tool_args}\n\... | 1 | function_simple | langchain-ai/langchain:libs/langchain_v1/langchain/agents/middleware/tool_emulator.py:LLMToolEmulator.awrap_tool_call |
"DRY RUN MODE - upload conditions not met, no images will be pushed"
)
platforms = list(platform)
logger.info(f"Processing {len(platforms)} platform(s): {platforms}")
ecr_registry = rayci_work_repo.split("/")[0]
ecr_docker_login(ecr_registry)
all_tags = []
for plat in platforms:... | 0 | function_complex | ray-project/ray:ci/ray_ci/automation/push_ray_image.py:main |
fields when present.
This mirrors SGLang's chat-serving pipeline semantics without directly
coupling to its internal server classes.
"""
kwargs: dict[str, Any] = {}
tools = getattr(request, "tools", None)
if tools is not None:
kwargs["tools"] = tools
... | 0 | function_simple | ray-project/ray:python/ray/llm/examples/sglang/modules/sglang_engine.py:SGLangServer._build_chat_template_kwargs |
meta",
new_callable=AsyncMock,
side_effect=Exception("Network error"),
),
patch(
"exo.download.download_utils.create_http_session"
) as mock_session_factory,
):
result = await _download_file(
model_id... | 0 | test | exo-explore/exo:src/exo/download/tests/test_download_verification.py:TestFileVerification.test_offline_fallback_uses_local_file |
"""Test when constraint does not exist."""
mock_inspector = Mock()
mock_inspector.get_unique_constraints.return_value = [
{"name": "uq_username", "column_names": ["username"]},
{"name": "uq_email", "column_names": ["email"]},
]
mock_inspect.return_value = moc... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/utils/test_migration.py:TestConstraintExists.test_constraint_exists_false |
vertex_ainvoke_structured(self):
"""Test structured output from Google Gemini via Vertex AI"""
# Skip if no project ID
if not os.getenv('GOOGLE_CLOUD_PROJECT'):
pytest.skip('GOOGLE_CLOUD_PROJECT not set')
chat = ChatGoogle(
model='gemini-2.0-flash',
vertexai=True,
project=os.getenv('GOOGLE_CLOUD_PR... | 0 | test | browser-use/browser-use:browser_use/llm/tests/test_chat_models.py:TestChatModels.test_google_vertex_ainvoke_structured |
AgentExecutor
) -> None:
"""Test that ainvoke properly propagates exceptions."""
with patch.object(executor, "_show_start_logs"):
with patch.object(
executor,
"_ainvoke_loop",
new_callable=AsyncMock,
side_effect=ValueError("... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/agents/test_async_agent_executor.py:TestAsyncAgentExecutor.test_ainvoke_handles_exceptions |
0.0)
# Get API key from config or environment
api_key = model_config.get('api_keys', {}).get('OPENAI_API_KEY') or CONFIG.OPENAI_API_KEY
if model_name:
if model_name.startswith('gpt'):
if not api_key and not CONFIG.OPENAI_API_KEY:
print('⚠️ OpenAI API key not found. Please update your config or set OPENA... | 0 | function_complex | browser-use/browser-use:browser_use/cli.py:get_llm |
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 matter whether two images are the sa... | 0 | test | huggingface/transformers:tests/models/ernie4_5_vl_moe/test_modeling_ernie4_5_vl_moe.py:Ernie4_5_VLMoeIntegrationTest.test_small_model_integration_test_batch_different_resolutions |
"""Test that window.__streamlit.HOST_CONFIG values override endpoint values.
Even though the host-config endpoint returns its own values, the initial
window config should take precedence for allowedOrigins, useExternalAuthToken,
and metricsUrl.
"""
# Custom values that differ from defaults
... | 1 | test | streamlit/streamlit:e2e_playwright/host_config_bypass_test.py:test_bypass_mode_host_config_values_take_precedence |
_log(package: Package, env: Env) -> str:
"""Format a log message indicating
that a wheel is being built for the given package and environment."""
marker_env = env.marker_env
python_version_info = marker_env.get(
"version_info", ("<unknown>", "<unknown>", "<unknown>")
)
python_version = ... | 1 | function_simple | python-poetry/poetry:src/poetry/utils/log_utils.py:format_build_wheel_log |
the minimum and maximum number of tiles. Each arrangement is
represented by its aspect ratio (width/height) and the corresponding tile configuration.
Args:
min_image_tiles (`int`):
The minimum number of tiles allowed.
max_image_tiles (`int`):
The maximum number of tiles... | 0 | function_complex | huggingface/transformers:src/transformers/models/ovis2/image_processing_ovis2.py:get_all_supported_aspect_ratios |
)
sorting = torch.argsort(expert_indices, stable=True)
token_indices = token_indices[sorting]
expert_indices = expert_indices[sorting]
routing_weights = routing_weights[sorting]
dispatched_tokens = hidden_states_flat.index_select(0, token_indices)
expert_outputs = torch... | 0 | function_simple | huggingface/transformers:src/transformers/models/afmoe/modular_afmoe.py:AfmoeExperts.forward |
file.TemporaryDirectory() as tmpdirname:
processor_tmpfile = Path(tmpdirname) / "preprocessor_config.json"
config_tmpfile = Path(tmpdirname) / "config.json"
json.dump(
{
"video_processor_type": "LlavaOnevisionVideoProcessor",
"p... | 0 | test | huggingface/transformers:tests/models/auto/test_video_processing_auto.py:AutoVideoProcessorTest.test_video_processor_from_local_directory_from_preprocessor_key |
tar1 = tmp_path / "test1.tar.gz"
tar2 = tmp_path / "test2.tar.gz"
# Create source files
src_dir = tmp_path / "src"
src_dir.mkdir()
(src_dir / "main.py").write_text("def main(): pass")
# Create identical tarballs
with tarfile.open(tar1, "w:gz") as t:
... | 1 | test | apache/airflow:dev/breeze/tests/test_airflow_release_validator.py:TestCompareArchives.test_identical_tarball_files |
"widgetType": "chart.js/bar",
"props": {"type": "bar"},
"data": {
"labels": ["A", "B"],
"datasets": [
{
"label": "系列1",
"data": ["abc", "def"] # 应该是数值
}
]
... | 1 | test | 666ghj/BettaFish:ReportEngine/utils/test_chart_validator.py:TestChartValidator.test_invalid_data_type |
Documentation"
for selector in [
"main",
"article",
'[role="main"]',
".content",
"#content",
".documentation",
]:
main_content = soup.select_one(selector)
if main_content:
break
if n... | 0 | function_complex | crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/rag/loaders/docs_site_loader.py:DocsSiteLoader.load |
model and self.reasoning_effort:
params["reasoning_effort"] = self.reasoning_effort
if self.response_format is not None:
if isinstance(self.response_format, type) and issubclass(
self.response_format, BaseModel
):
params["response_format"] = g... | 0 | function_complex | crewAIInc/crewAI:lib/crewai/src/crewai/llms/providers/openai/completion.py:OpenAICompletion._prepare_completion_params |
error cases for model and provider inference."""
# Test missing provider
with pytest.raises(ValueError, match="Must specify either"):
_infer_model_and_provider("text-embedding-3-small")
# Test empty model
with pytest.raises(ValueError, match="Model name cannot be empty"):
_infer_model_... | 1 | test | langchain-ai/langchain:libs/langchain_v1/tests/unit_tests/embeddings/test_base.py:test_infer_model_and_provider_errors |
raise ValueError(
f"Gemini API blocked the request. Reason: {feedback.blockReason} ({feedback.blockReasonMessage})"
)
raise ValueError(
"Gemini API returned no response candidates. If you are using the `IMAGE` modality, "
"try changing it to `IMAGE+TEX... | 1 | function_complex | Comfy-Org/ComfyUI:comfy_api_nodes/nodes_gemini.py:get_parts_by_type |
crew = Crew(
agents=[researcher],
tasks=[simple_task],
verbose=False,
stream=True,
)
original_kickoff = Crew.kickoff
call_count = [0]
def mock_kickoff_fn(self: Any, inputs: Any = None, **kwargs: Any) -> Any:
call_count[0] ... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/test_streaming.py:TestStreamingEdgeCases.test_streaming_handles_exceptions |
action(
app: Page, assert_snapshot: ImageCompareFunction, sidebar_mode: str
):
"""Test sidebar collapse interaction on desktop with auto mode."""
setup_viewport_and_verify_title(app, 1280, 800, sidebar_mode)
# Verify initial expanded state
verify_sidebar_state(app, True)
verify_sidebar_content_... | 1 | test | streamlit/streamlit:e2e_playwright/st_main_layout_test.py:test_sidebar_auto_desktop_collapse_interaction |
contract_phase_requirements(self, content: str) -> list[Violation]:
"""Check CONTRACT phase specific requirements."""
# Check for data migration before dropping columns
if not ("SELECT" in content and "COUNT" in content):
return [
Violation(
"MISSI... | 1 | function_simple | langflow-ai/langflow:src/backend/base/langflow/alembic/migration_validator.py:MigrationValidator._check_contract_phase_requirements |
[torch.Tensor, float]], float]:
"""Return a function that controls the stochasticity of SA-Solver.
When eta = 0, SA-Solver runs as ODE. The official approach uses
time t to determine the SDE interval, while here we use sigma instead.
See:
https://github.com/scxue/SA-Solver/blob/main/README.md
... | 1 | function_complex | Comfy-Org/ComfyUI:comfy/k_diffusion/sa_solver.py:get_tau_interval_func |
get_calendar(
dag_id: str,
session: SessionDep,
dag_bag: DagBagDep,
logical_date: Annotated[RangeFilter, Depends(datetime_range_filter_factory("logical_date", DagRun))],
granularity: Literal["hourly", "daily"] = "daily",
) -> CalendarTimeRangeCollectionResponse:
"""Get calendar data for a DAG i... | 1 | function_simple | apache/airflow:airflow-core/src/airflow/api_fastapi/core_api/routes/ui/calendar.py:get_calendar |
"ExecutionEndDateTime": "2023-01-01T12:00:10Z",
"DocumentName": "AWS-RunShellScript",
"Comment": "",
}
mock_hook.get_command_invocation.side_effect = [
mock_invocation_details_1,
mock_invocation_details_2,
]
result = operator.execute({... | 1 | test | apache/airflow:providers/amazon/tests/unit/amazon/aws/operators/test_ssm.py:TestSsmGetCommandInvocationOperator.test_execute_all_instances |
ter.num_channels - 1)
) + 2
for max_patch in self.image_processor_tester.max_patches:
# Test not batched input
encoded_images = image_processor(
image_inputs[0], return_tensors="pt", max_patches=max_patch
).flattened_patches
self.assertEqu... | 0 | test | huggingface/transformers:tests/models/kosmos2_5/test_image_processing_kosmos2_5.py:Kosmos2_5ImageProcessingTestFourChannels.test_call_pil |
_inputs: BatchFeature,
hf_processor_mm_kwargs: Mapping[str, object],
) -> Mapping[str, MultiModalFieldConfig]:
"""Indicates how to slice media input into multiple items.
pixel_values: [N, 3, patch_size, patch_size], all patches collected from B medias
grid_thws: [B,3], each item: [N... | 1 | function_simple | vllm-project/vllm:vllm/model_executor/models/kimi_k25.py:KimiK25MultiModalProcessor._get_mm_fields_config |
length for the adapter, if it exists.
Raises: HTTPException if the LoRA adapter config file isn't available
in the cloud storage repository.
"""
if bucket_uri.endswith("/"):
bucket_uri = bucket_uri.rstrip("/")
object_uri = f"{bucket_uri}/{LORA_ADAPTER_CONFIG_NAME}"
object_str_or_m... | 0 | function_simple | ray-project/ray:python/ray/llm/_internal/serve/utils/lora_serve_utils.py:get_lora_finetuned_context_length |
VBoxLayout(form_frame)
form_layout.setSpacing(20)
# Input fields
name_frame, name_edit = create_input_field(form_frame, name_field_text)
password_frame, password_edit = create_input_field(form_frame, password_field_text)
# Submit button
button_frame = create_styled_frame(form_frame, style="pad... | 1 | function_simple | geekcomputers/Python:bank_managment_system/QTFrontend.py:create_login_page |
.MessageHook"):
trigger = AzureServiceBusQueueTrigger(
queues=["test_queue"],
poll_interval=0.01, # Very short for testing
)
mock_message = Mock(body=b"test message")
trigger.message_hook.read_message = Mock(return_value=mock_message)
... | 1 | test | apache/airflow:providers/microsoft/azure/tests/unit/microsoft/azure/triggers/test_message_bus.py:TestAzureServiceBusQueueTrigger.test_run_with_message |
_custom_filename_with_extension(self, tools, browser_session, base_url):
"""save_as_pdf doesn't double the .pdf extension."""
await tools.navigate(url=f'{base_url}/pdf-test', new_tab=False, browser_session=browser_session)
await asyncio.sleep(0.5)
with tempfile.TemporaryDirectory() as temp_dir:
file_system ... | 0 | test | browser-use/browser-use:tests/ci/test_action_save_as_pdf.py:TestSaveAsPdf.test_save_as_pdf_custom_filename_with_extension |
break normal stop word behavior.
"""
from crewai.llms.providers.gemini.completion import GeminiCompletion
# Create Gemini completion instance with stop words configured
# Gemini uses stop_sequences instead of stop
llm = GeminiCompletion(
model="gemini-2.0-flash-001",
stop_sequences... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/llms/google/test_google.py:test_gemini_stop_words_still_applied_to_regular_responses |
_model(self, customer_id: str):
"""Load a customer's forecasting model.
In production, this function downloads from cloud storage or loads from a database.
For this example, the code mocks the I/O with asyncio.sleep().
"""
# Simulate downloading model from remote storage... | 0 | function_simple | ray-project/ray:doc/source/serve/tutorials/model_multiplexing_forecast/content/serve_forecast_multiplex.py:ForecastingService.get_model |
), pa.table({"a": [3, 4]})]
else:
blocks = [pd.DataFrame({"a": [1, 2]}), pd.DataFrame({"a": [3, 4]})]
# Create dataset with 2 blocks of 2 rows each
ds = ray.data.from_blocks(blocks)
ds = ds.with_column("uid", monotonically_increasing_id())
expected = {0, 1, (1 << 33) + 0, (1 << 33) + 1}
... | 0 | test | ray-project/ray:python/ray/data/tests/test_monotonically_increasing_id.py:test_monotonically_increasing_id |
Args:
messages: List of non-system messages to clean
Returns:
List of messages with cleaned cache settings
"""
if not messages:
return messages
# Create a copy to avoid modifying the original
cleaned_messages = [msg.model_copy(deep=True) for msg in messages]
# Find the last message with cache=T... | 0 | function_complex | browser-use/browser-use:browser_use/llm/anthropic/serializer.py:AnthropicMessageSerializer._clean_cache_messages |
Any) -> None:
"""Pushes a value into this Stats object.
Args:
value: The value to be pushed. Can be of any type.
PyTorch GPU tensors are kept on GPU until reduce() or peek().
TensorFlow tensors are moved to CPU immediately.
"""
# Convert Tens... | 0 | function_simple | ray-project/ray:rllib/utils/metrics/stats/lifetime_sum.py:LifetimeSumStats.push |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.