input string | label int64 | category string | sample_id string |
|---|---|---|---|
ings -> cosine similarity = 1.0
embedder.side_effect = lambda texts: [[0.5] * 1536 for _ in texts]
llm = MagicMock()
llm.supports_function_calling.return_value = False
mem = Memory(storage=str(tmp_path / "db"), llm=llm, embedder=embedder)
mem.remember_many(
[
"CrewAI ensures re... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/memory/test_unified_memory.py:test_intra_batch_dedup_drops_near_identical |
# Store the metadata on a named actor that all of the other
# actors can access.
metadata_key = get_master_address_metadata_key(name)
internal_kv._internal_kv_put(metadata_key, f"{master_addr}:{master_port}")
def _do_init_collective_group(self, rank: int):
ray.util.collective.ini... | 0 | function_complex | ray-project/ray:python/ray/experimental/collective/collective.py:create_collective_group |
Test updating vector payload."""
na_instance.reset()
na_instance.insert(
vectors=[VECTOR_1],
ids=["A"],
payloads=[SAMPLE_PAYLOADS[0]]
)
na_instance.update(vector_id="A", payload={"updated_payload_str": "update_str"})
vector_a = na_inst... | 1 | test | mem0ai/mem0:tests/vector_stores/test_neptune_analytics.py:TestNeptuneAnalyticsOperations.test_update |
token_usage(
response: Message | BetaMessage,
) -> dict[str, Any]:
"""Extract token usage from Anthropic response."""
if hasattr(response, "usage") and response.usage:
usage = response.usage
input_tokens = getattr(usage, "input_tokens", 0)
output_tokens = ... | 0 | function_simple | crewAIInc/crewAI:lib/crewai/src/crewai/llms/providers/anthropic/completion.py:AnthropicCompletion._extract_anthropic_token_usage |
replica_id = f"n{node_idx}_r{replica_idx}"
replica_ids.append(replica_id)
rank_manager.assign_rank(replica_id, f"node_{node_idx}")
# Verify total count
mapping = rank_manager.get_replica_ranks_mapping()
assert len(mapping) == total_replicas
# V... | 0 | test | ray-project/ray:python/ray/serve/tests/unit/test_deployment_rank_manager.py:TestDeploymentRankManagerEdgeCases.test_large_scale_rank_management |
prompt_details = getattr(usage, "prompt_tokens_details", None)
if prompt_details:
cached_tokens = getattr(prompt_details, "cached_tokens", 0) or 0
return {
"prompt_tokens": getattr(usage, "prompt_tokens", 0),
"completion_tokens": getattr(usage,... | 0 | function_simple | crewAIInc/crewAI:lib/crewai/src/crewai/llms/providers/azure/completion.py:AzureCompletion._extract_azure_token_usage |
workspace = flashinfer_comm.create_allreduce_fusion_workspace(
backend=backend,
world_size=world_size,
rank=rank,
max_token_num=max_token_num,
hidden_dim=hidden_dim,
dtype=dtype,
**kwargs,
)
_FI_WORKSPACES[backend] = ... | 1 | function_simple | vllm-project/vllm:benchmarks/kernels/benchmark_fused_collective.py:setup_flashinfer_workspace |
)
frames = torch.stack(frames, dim=0)
self.assertEqual(frames.shape, (3, 1, 1, raw_video.shape[-3], raw_video.shape[-2]))
torch.testing.assert_close(
frames[:3, :, :, :2, :2],
torch.tensor(
[
[[[[-10.0000, -10.0000], [-10.0000, -10.0000... | 0 | test | huggingface/transformers:tests/models/sam2_video/test_modeling_sam2_video.py:Sam2VideoModelIntegrationTest.test_inference_propagate_video_from_mask_input |
test_get_email_model_success(self):
"""Test email model retrieval with success."""
# Mock load_registration to return a valid registration
with patch("langflow.utils.registered_email_util.load_registration") as mock_load_registration:
mock_load_registration.return_value = {"email": ... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/utils/test_registered_email_util.py:TestGetEmailModel.test_get_email_model_success |
"entity": {"metadata": {"user_id": "alice"}}
},
{
"id": "mem2",
"distance": 0.85,
"entity": {"metadata": {"user_id": "bob"}}
}
]
parsed = milvus_db._parse_output(raw_data)
asser... | 1 | test | mem0ai/mem0:tests/vector_stores/test_milvus.py:TestMilvusDB.test_parse_output |
[obj_idx]["cond_frame_outputs"]
if not conditioning_outputs:
raise ValueError(
"maskmem_features in conditioning outputs cannot be empty when not is_initial_conditioning_frame"
)
conditioning_outputs, unselected_conditioning_outputs = self._select_closest_cond_fra... | 0 | function_simple | huggingface/transformers:src/transformers/models/sam2_video/modular_sam2_video.py:Sam2VideoModel._gather_memory_frame_outputs |
apply_chat_template(
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)
output = model.generate(**inputs, max_new_tokens=30)
... | 0 | test | huggingface/transformers:tests/models/glm46v/test_modeling_glm46v.py:Glm46VIntegrationTest.test_small_model_integration_test_with_video |
_excluded_with_custom_tools_and_use_vision_false():
"""Test that screenshot action is excluded even when user passes custom tools and use_vision=False.
This is the critical test case that verifies the fix:
When users pass their own Tools instance with screenshot included,
the Agent should still enforce the exclusi... | 0 | test | browser-use/browser-use:tests/ci/test_screenshot_exclusion.py:test_screenshot_excluded_with_custom_tools_and_use_vision_false |
HTML, like Gecko) "
"Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0"
),
"Accept": (
"text/html,application/xhtml+xml,application/xml;q=0.9,"
"image/webp,*/*;q=0.8"
),
"Accept-Language": "en-US,en;q=0.9",
}
if ... | 1 | function_simple | xtekky/gpt4free:g4f/Provider/yupp/token_extractor.py:TokenExtractor._get_headers |
tempfile.TemporaryDirectory() as temp_dir,
patch.dict(
os.environ,
{
"LANGFLOW_CONFIG_DIR": temp_dir,
"LANGFLOW_CORS_ORIGINS": "https://app.example.com",
"LANGFLOW_CORS_ALLOW_CREDENTIALS": "true",
... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/test_security_cors.py:TestCORSConfiguration.test_specific_origins_allow_credentials |
pdfmetrics.registerFont(UnicodeCIDFont(cid_font))
cls._unicode_font_name = cid_font
cls._unicode_font_bold_name = cid_font # CID fonts don't have bold variants
print(f"Registered CID font: {cid_font}")
break
except Exception as e:
... | 1 | function_complex | infiniflow/ragflow:agent/component/docs_generator.py:PDFGenerator._register_unicode_fonts |
",
"name": "Optional run name"
}
"""
try:
req = await get_request_json()
dataset_id = req.get("dataset_id")
dialog_id = req.get("dialog_id")
name = req.get("name")
success, result = EvaluationService.start_evaluation(
dataset_id=dataset_id... | 1 | function_simple | infiniflow/ragflow:api/apps/evaluation_app.py:start_evaluation |
"""
Register the kv caches with LMCache server
Args:
kv_caches: A dict of kv caches to register. The keys are the
layer names and the values are the corresponding tensors.
"""
# Register kv cache and send the request
self.kv_caches = kv_caches
... | 1 | function_simple | vllm-project/vllm:vllm/distributed/kv_transfer/kv_connector/v1/lmcache_integration/multi_process_adapter.py:LMCacheMPWorkerAdapter.register_kv_caches |
group_name, actors = collective_actors
def do_send(self, group_name, dst_rank):
ray.util.collective.send(self.tensor, dst_rank, group_name=group_name)
def do_recv(self, group_name, src_rank):
ray.util.collective.recv(self.tensor, src_rank, group_name=group_name)
# Actors cannot send to... | 0 | test | ray-project/ray:python/ray/tests/test_experimental_collective.py:test_send_recv_exceptions |
ensor]]:
"""Deserialize back to a batch of tensors."""
batch = {}
storage_buffer = self.buffer.untyped_storage()
offsets = []
for name, features in self.metadata.features.items():
for _, _, offset in features:
offsets.append(offset)
offsets.app... | 0 | function_complex | ray-project/ray:doc/source/train/doc_code/collate_utils.py:_TensorBatch.to_batch |
[int(nv_process.pid)] = ProcessGPUInfo(
pid=int(nv_process.pid),
gpu_memory_usage=(
int(nv_process.usedGpuMemory) // MB
if nv_process.usedGpuMemory
else 0
),
... | 0 | function_complex | ray-project/ray:python/ray/dashboard/modules/reporter/gpu_providers.py:NvidiaGpuProvider._get_mig_device_info |
"""Extract valuation for a specific property from the full analysis"""
if not property_valuations:
return None
# Split by property sections - look for the formatted property headers
sections = property_valuations.split('**Property')
# Look for the specific property number
for sect... | 0 | function_complex | Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/agent_teams/ai_real_estate_agent_team/ai_real_estate_agent_team.py:extract_property_valuation |
],
initial_trust: int = 700
) -> bool:
"""Register a new agent with the trust layer"""
# Generate a key pair (simplified)
public_key = hashlib.sha256(f"{agent_id}:{secrets.token_hex(16)}".encode()).hexdigest()
identity = AgentIdentity(
agent_id=a... | 0 | function_simple | Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/multi_agent_trust_layer/multi_agent_trust_layer.py:TrustLayer.register_agent |
api_links = result.links.get("internal", [])
# Categorize by detected content
endpoints = {"GET": [], "POST": [], "PUT": [], "DELETE": [], "OTHER": []}
for link in api_links:
if link.get("head_data"):
... | 1 | function_complex | unclecode/crawl4ai:docs/examples/link_head_extraction_example.py:api_discovery_example |
] = state_dict[key]
else:
converted_state_dict[key] = state_dict[key]
# Load state dict
missing_keys, unexpected_keys = model.load_state_dict(converted_state_dict, strict=False)
if missing_keys:
print(f"Missing keys: {missing_keys}")
if unexpected_keys:
print... | 0 | function_complex | huggingface/transformers:src/transformers/models/lw_detr/convert_lw_detr_to_hf.py:convert_lw_detr_checkpoint |
Event) -> None:
"""Check if navigated URL is allowed (catches redirects to blocked domains)."""
# Check if the navigated URL is allowed (in case of redirects)
if not self._is_url_allowed(event.url):
self.logger.warning(f'⛔️ Navigation to non-allowed URL detected: {event.url}')
# Dispatch browser error
s... | 0 | function_simple | browser-use/browser-use:browser_use/browser/watchdogs/security_watchdog.py:SecurityWatchdog.on_NavigationCompleteEvent |
task="transcribe",
word_timestamps=True,
no_speech_threshold=0.6,
logprob_threshold=-1.0,
compression_ratio_threshold=2.4,
)
else:
return InlineAsrNativeWhisperOptions(
repo_id="small",
inference_framework=InferenceAsr... | 1 | function_complex | docling-project/docling:docling/datamodel/asr_model_specs.py:_get_whisper_small_model |
�内代码
html = re.sub(r'`(.+?)`', r'<code>\1</code>', html)
# 分割线
html = re.sub(r'^[\-\*]{3,}\s*$', '<hr>', html, flags=re.MULTILINE)
# 换行
html = html.replace('\n', '<br>\n')
return f"""<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>TrendRadar 通知</title>
<style>body{{font-family:sans-s... | 1 | function_simple | sansan0/TrendRadar:mcp_server/tools/notification.py:_markdown_to_simple_html |
i, url in enumerate(global_args.decode):
parsed_url = urllib.parse.urlparse(url)
hostname = maybe_wrap_ipv6_address(parsed_url.hostname)
app.state.decode_clients.append(
{
"client": httpx.AsyncClient(
timeout=None,
base_url=url... | 1 | function_simple | vllm-project/vllm:examples/online_serving/disaggregated_serving/mooncake_connector/mooncake_connector_proxy.py:lifespan |
MediaWithBytes has a __getattr__ that delegates to self.media,
but this causes infinite recursion during pickle.load() because pickle
creates objects via __new__ (not __init__), so self.media isn't set
when __getattr__ is first called.
TODO(seiji): remove when https://github.com/vllm-project/vllm/issu... | 0 | function_simple | ray-project/ray:python/ray/llm/_internal/batch/stages/prepare_multimodal_stage.py:_register_vllm_pickle_reducers |
,
*,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
run_name: str | None = None,
include_run_info: bool = False,
) -> dict[str, Any]:
"""Asynchronously execute the chain.
Args:
inputs: Dictionary of inputs, or single input ... | 1 | function_simple | langchain-ai/langchain:libs/langchain/langchain_classic/chains/base.py:Chain.acall |
brackets inside quoted string values
model_output = (
'{"name": "searchTool", '
'"parameters": {'
'"query": "test {value} [complex]",'
'"nested": {"inner": "more {brackets}"}'
"}}"
)
result = parser.extract_tool_calls(model_output, None)
assert result.tools_call... | 1 | test | vllm-project/vllm:tests/entrypoints/openai/tool_parsers/test_llama3_json_tool_parser.py:test_extract_tool_calls_with_quotes_and_brackets_in_string |
ai.events.event_context import reset_last_event_id
reset_emission_counter()
reset_last_event_id()
events: list[BaseEvent] = []
class SyncFlow(Flow):
@start()
def sync_start(self): # Synchronous method
return "sync_done"
@listen(syn... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/events/test_event_ordering.py:TestTriggeredByEventId.test_sync_method_in_flow_triggered_by |
cls.model.create_date,
cls.model.update_date,
]
query = cls.model.select(*fields).order_by(cls.model.create_time.desc()).where(cls.model.tenant_id == tenant_id)
if id_list:
query = query.where(cls.model.id.in_(id_list))
if keywords:
query = query.w... | 1 | function_complex | infiniflow/ragflow:api/db/services/mcp_server_service.py:MCPServerService.get_servers |
use_attention_mask,
output_attentions,
enable_kernels,
):
"""
We need to overwrite this without the fp16 part of the dtype, because the slow path `torch_chunk_gated_delta_rule`
is not robust enough (flaky test) in fp16 due to upscaling in fp32 and then downscaling to fp1... | 0 | test | huggingface/transformers:tests/models/qwen3_next/test_modeling_qwen3_next.py:Qwen3NextModelTest.test_eager_matches_sdpa_inference |
= model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
added_hidden_states = 1
self.assertEqual(out_len + added_hidden_states, len(outputs))
... | 0 | test | huggingface/transformers:tests/models/falcon_h1/test_modeling_falcon_h1.py:FalconH1ModelTest.test_attention_outputs |
self.assertEqual(parsed_text_without_phrase, EXPECTED_PARSED_TEXT_WITHOUT_PHRASE)
text_with_phrase = (
"Hello<loc_769><loc_248><loc_771><loc_234><loc_773><loc_206><loc_773><loc_198><loc_771><loc_193>"
)
image_size = (1000, 1000)
parsed_text_with_phrase = processor.post... | 0 | test | huggingface/transformers:tests/models/florence2/test_processing_florence2.py:Florence2ProcessorTest.test_post_process_parse_description_with_polygons_from_text_and_spans |
_name(self, user_id: str) -> str:
"""Get Slack username"""
if user_id not in self._id_to_name_map:
try:
response = self._client.users_info(user=user_id)
self._id_to_name_map[user_id] = response["user"]["profile"]["display_name"] or response["user"]["profile"][... | 1 | function_simple | infiniflow/ragflow:common/data_source/utils.py:SlackTextCleaner._get_slack_name |
attentions
if outputs.decoder_hidden_states is not None and len(outputs.decoder_hidden_states) > 0:
decoder_hidden_states = outputs.decoder_hidden_states[0]
decoder_hidden_states.retain_grad()
if outputs.detr_decoder_attentions is not None and len(outputs.detr_decoder_attention... | 0 | test | huggingface/transformers:tests/models/sam3/test_modeling_sam3.py:Sam3ModelTest.test_retain_grad_hidden_states_attentions |
_delete_instance_cancels_running_tasks(
instance: Instance,
):
# arrange
instance_id = InstanceId()
current_instances: dict[InstanceId, Instance] = {instance_id: instance}
target_instances: dict[InstanceId, Instance] = {}
task = _make_task(instance_id, TaskStatus.Running)
tasks = {task.task_... | 0 | test | exo-explore/exo:src/exo/master/tests/test_placement.py:test_get_transition_events_delete_instance_cancels_running_tasks |
cmds_dir = project_dir / ".claude" / "commands"
cmds_dir.mkdir(parents=True)
(cmds_dir / "broken.md").write_text(
"---\n"
"description: [unclosed bracket\n"
" invalid: yaml: content: here\n"
"---\n"
"\n"
"# Broken\n",
... | 0 | test | github/spec-kit:tests/test_ai_skills.py:TestInstallAiSkills.test_malformed_yaml_frontmatter |
len(documents),
time.perf_counter() - start,
)
try:
logger.info("Adding %d documents to the Solr collection", len(documents))
# pysolr.Solr.add is not typed, but in code tracing it will always be this
res_text = str(self._get_client().add(updated_... | 1 | function_simple | run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-solr/llama_index/vector_stores/solr/client/sync.py:SyncSolrClient.add |
64_encoding(app: Page, assert_snapshot: ImageCompareFunction):
"""Test st.pdf with base64 encoded data."""
_select_pdf_scenario(app, "base64")
base64_info = app.get_by_test_id("stMarkdown").filter(has_text="Base64 PDF length:")
expect(base64_info).to_be_visible()
code_block = app.get_by_test_id("s... | 1 | test | streamlit/streamlit:e2e_playwright/custom_components/pdf_component_test.py:test_st_pdf_base64_encoding |
"code": "MISSING_PARAMETER",
"message": "Job ID must be provided",
},
)
job_service = get_job_service()
try:
job = await job_service.get_job_by_job_id(job_id=job_id)
except Exception as exc:
raise HTTPException(
status_code=status.HTTP... | 1 | function_complex | langflow-ai/langflow:src/backend/base/langflow/api/v2/workflow.py:get_workflow_status |
_negative_inf_padding_fp8():
"""Test that pack_seq_triton uses -inf padding by default for fp8."""
device = "cuda"
dtype = torch.float8_e4m3fn
# B = 2
N, H, D = 20, 8, 16
lengths = torch.tensor([10, 10], device=device)
x = torch.randn(N, H, D, dtype=torch.float32, device=device) * 0.1
x... | 1 | test | vllm-project/vllm:tests/kernels/attention/test_pack_unpack_triton.py:test_pack_seq_default_negative_inf_padding_fp8 |
image_std=(1.0, 1.0, 1.0, 1.0),
).pixel_values
self.assertEqual(tuple(encoded_images.shape), (10, 4, 30, 30))
# Test batched
encoded_images = image_processor(
image_inputs,
return_tensors="pt",
input_data_format="channe... | 0 | test | huggingface/transformers:tests/models/cohere2_vision/test_image_processing_cohere2_vision.py:Cohere2VisionProcessingTest.test_call_numpy_4_channels |
1, 1, raw_video.shape[-3], raw_video.shape[-2]))
# Test propagation across multiple frames to test memory handling
frames = []
max_frame_num_to_track = 2
for sam2_video_output in video_model.propagate_in_video_iterator(
inference_sessi... | 0 | test | huggingface/transformers:tests/models/sam2_video/test_modeling_sam2_video.py:Sam2VideoModelIntegrationTest.test_inference_with_different_dtypes |
sample.
"""
# Determine output shape
batch_size = len(batch_images)
max_num_images = max(len(images) for images in batch_images)
shapes = [image.shape for images in batch_images for image in images]
_, channels, tile_height, tile_width = shapes[0]
# Initialize the stacked images array wit... | 0 | function_simple | huggingface/transformers:src/transformers/models/mllama/image_processing_mllama_fast.py:pad_batches_and_tiles |
== options.languages
assert reconstructed.optimize == options.optimize
assert reconstructed.tesseract_timeout == options.tesseract.timeout
assert reconstructed.fast_web_view == options.fast_web_view
assert reconstructed.deskew == options.deskew
assert reconstructed.clean == options.clean
# Comp... | 1 | test | ocrmypdf/OCRmyPDF:tests/test_json_serialization.py:test_json_serialization_multiprocessing |
- Concatenation: concatenates received shuffled partitions into a
single block (for ``repartition`` for ex).
- Join: joins corresponding shuffled partitions.
- Group Aggregation: applies aggregation on grouped data (like ``sum``,
``count``, ``unique``, etc).
Each implementation is meant to be *st... | 0 | documentation | ray-project/ray:python/ray/data/_internal/execution/operators/hash_shuffle.py:ShuffleAggregation:class_doc |
This decorator wraps PyArrow compute functions to automatically convert pandas
Series and numpy arrays to PyArrow Arrays, ensuring the function works seamlessly
regardless of the underlying block format (pandas, arrow, or items).
Used internally by namespace methods (list, str, struct) that wrap PyArrow... | 0 | function_simple | ray-project/ray:python/ray/data/expressions.py:pyarrow_udf |
total_count = total_hits if total_hits else len(page_docs)
# Handle list/iterable results
elif hasattr(results, '__iter__') and not isinstance(results, dict):
page_docs = list(results)
else:
page_docs = []
if not page_... | 1 | function_complex | infiniflow/ragflow:api/db/services/doc_metadata_service.py:DocMetadataService._search_metadata |
config, parallel_config)
init_info = engine.parse_init_info(
{
"master_address": "127.0.0.1",
"master_port": 12345,
"rank_offset": 1,
"world_size": 3,
}
)
assert isinstance(init_info, NCCLWeightTransferInit... | 1 | test | vllm-project/vllm:tests/distributed/test_weight_transfer.py:TestNCCLEngineParsing.test_parse_init_info_valid |
"""Create and return a configured boto3 S3 client.
Args:
component: Component instance with AWS credential attributes
Returns:
boto3 S3 client instance
Raises:
ImportError: If boto3 is not installed
"""
try:
import boto3
except ImportError as e:
ms... | 1 | function_simple | langflow-ai/langflow:src/lfx/src/lfx/base/data/cloud_storage_utils.py:create_s3_client |
works when no files are attached."""
messages: list[dict[str, Any]] = [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi there!"},
]
mock_llm = MagicMock()
mock_llm.get_context_window_size.return_value = 1000
mock_llm.call.retur... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/utilities/test_agent_utils.py:TestSummarizeMessages.test_works_without_files |
logs anyway so it's fine.
# Source: https://github.com/pallets/click/issues/824#issuecomment-562581313
with capsys.disabled():
with tempfile.TemporaryDirectory() as tmpdir:
output = cli(
"download",
"hf-internal-testing/test_dynamic_model_with_tokenizer",
... | 0 | test | huggingface/transformers:tests/cli/test_download.py:test_cli_download_trust_remote |
secret: str,
name: str,
value: str | bytes,
) -> bytes:
"""Create a signed cookie value using itsdangerous.
Note: This uses itsdangerous for signing, which is NOT compatible with
Tornado's secure cookie format. Cookies signed by this function cannot
be read by Tornado's get_signed_cookie/get... | 1 | function_simple | streamlit/streamlit:lib/streamlit/web/server/starlette/starlette_app_utils.py:create_signed_value |
assert response.choices[0].message.content is not None
# Decode token_ids and verify consistency
tokenizer = get_tokenizer(tokenizer_name=MODEL_NAME)
decoded_prompt = tokenizer.decode(response.prompt_token_ids)
assert decoded_prompt.startswith(
"<|im_start|>system\nY... | 1 | test | vllm-project/vllm:tests/entrypoints/openai/test_return_token_ids.py:test_chat_completion_with_emoji_and_token_ids |
"type": "function",
"name": "get_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"},
"unit": {"type": "s... | 1 | test | vllm-project/vllm:tests/entrypoints/test_responses_utils.py:TestResponsesUtils.test_convert_tool_responses_to_completions_format |
the fix:
When frozen=True and built=True, build() returns early without
calling finalize_build(), leaving result=None.
"""
# Arrange - simulate the broken state (before fix)
mock_vertex.frozen = True
mock_vertex.built = True # Not reset after failed cache restoration
... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/graph/test_cache_restoration.py:TestCacheRestorationBuiltFlagReset.test_build_returns_early_when_built_flag_not_reset |
TODO: Add description.
generator (`None`, *optional*):
TODO: Add description.
batch_size (`int`):
Number of prompts, the final batch size of model inputs should be `batch_size * num_images_per_prompt`.
Can be generated in input step.
dtype (`dtype`, *optional*):
... | 1 | documentation | huggingface/diffusers:src/diffusers/modular_pipelines/flux/modular_blocks_flux_kontext.py:FluxKontextBeforeDenoiseStep:class_doc |
"operationId": "route1_route1_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {"application/json": {"schema": {}}},
},
... | 1 | test | fastapi/fastapi:tests/test_additional_responses_union_duplicate_anyof.py:test_openapi_schema |
try:
args = json.loads(arguments)
except json.JSONDecodeError:
if executed_tool.get("type") == "python":
try:
args = _parse_code_json(arguments)
except ValueError:
... | 1 | function_complex | langchain-ai/langchain:libs/core/langchain_core/messages/block_translators/groq.py:_convert_to_v1_from_groq |
Args:
x (`torch.Tensor`): Input batch of images.
return_dict (`bool`, *optional*, defaults to `True`):
Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
Returns:
The latent representations of the encoded imag... | 1 | function_simple | huggingface/diffusers:src/diffusers/models/autoencoders/autoencoder_kl_flux2.py:AutoencoderKLFlux2.encode |
Unwrap nested output tensors from a config dict to be a single list of output tensor
Parameters
----------
outputs: list[list[Any]]
The outputs that exist within the Keras 2 config dict that may be nested
Returns
-------
list[list[str | int]]
Th... | 1 | function_simple | deepfakes/faceswap:plugins/train/model/_base/update.py:Legacy._unwrap_outputs |
or 'Not specified'}")
print(f" Category: {analysis.product_info.category.value.title()}")
if analysis.product_info.price_mentioned:
print(f" Price: {analysis.product_info.price_mentioned}")
# Metrics
print(f"\n📊 METRICS:")
pr... | 0 | function_complex | Shubhamsaboo/awesome-llm-apps:ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/product_review_agent.py:interactive_mode |
_score_prompt(
cross_encoder_model_config, # use_sep_token=True
cross_encoder_tokenizer,
tokenization_kwargs,
"query",
"document",
)
assert "prompt_token_ids" in engine_prompt
# Should have token_type_ids from ... | 1 | test | vllm-project/vllm:tests/entrypoints/pooling/score/test_utils.py:TestGetScorePrompt.test_fallback_with_sep_token |
to each task and the `task_type_id` is in the range `[0,
config.task_type_vocab_size-1]
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
config.vocab... | 0 | function_simple | huggingface/transformers:src/transformers/models/ernie/modular_ernie.py:ErnieForMaskedLM.forward |
-image generation.
Reference: [https://bfl.ai/blog/flux-2](https://bfl.ai/blog/flux-2)
Args:
transformer ([`Flux2Transformer2DModel`]):
Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
scheduler ([`FlowMatchEulerDiscreteScheduler`]):
A scheduler to be used in ... | 1 | documentation | huggingface/diffusers:src/diffusers/pipelines/flux2/pipeline_flux2.py:Flux2Pipeline:class_doc |
# This works because in scikit-learn all public estimators are exposed at
# that level, even if they actually live in a private sub-module.
estimator_module = ".".join(
itertools.takewhile(
lambda part: not part.startswith("_"),
self... | 0 | function_simple | scikit-learn/scikit-learn:sklearn/utils/_repr_html/base.py:_HTMLDocumentationLinkMixin._get_doc_link |
end_node_id = getattr(element, 'backend_node_id', None)
index_text = None
if backend_node_id is not None:
if filter_highlight_ids:
# Use the meaningful text that matches what the LLM sees
meaningful_text = element.get_meaningful_text_for_llm()
# Show ID only if meaningful text is less than 5 charact... | 0 | function_complex | browser-use/browser-use:browser_use/browser/python_highlights.py:process_element_highlight |
packages and
populate :attr:`_installed_conda`
Returns
-------
list[str]
Each line of output from the 'conda list' command
"""
if not self._conda_exe:
logger.debug("Conda not found. Not collecting packages")
return
lines = _l... | 1 | function_simple | deepfakes/faceswap:lib/system/system.py:Packages._get_installed_conda |
Validate number_of_results if provided
if self.number_of_results is not None:
if not isinstance(self.number_of_results, int):
raise BedrockValidationError("number_of_results must be an integer")
if self.number_of_results < 1:
raise Bed... | 0 | function_complex | crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/aws/bedrock/knowledge_base/retriever_tool.py:BedrockKBRetrieverTool._validate_parameters |
by the index_suffix). It sorts these pairs
by their indices in ascending order and excludes pairs without an index key,
returning a list of lists of tuples (extraction_class: str, extraction_text:
str).
Args:
extraction_data: A list of dictionaries. Each dictionary contains pairs
of ... | 1 | function_complex | google/langextract:langextract/resolver.py:Resolver.extract_ordered_extractions |
self, serve_instance):
"""Deployment logging config in code should not be overwritten
by application logging config.
"""
client = serve_instance
config_dict = self.get_deploy_config(model_within_logging_config=True)
config_dict["applications"][0]["logging_config"] = {
... | 0 | test | ray-project/ray:python/ray/serve/tests/test_deploy_app_2.py:TestDeploywithLoggingConfig.test_not_overwritting_logging_config_in_code |
.dag_maker:
@task.sql(
conn_id=conn_id,
output_processor=lambda results, descriptions: (descriptions, results),
return_last=False,
)
def sql():
return "SELECT * FROM users;"
sql_task = sql()
# Exec... | 1 | test | apache/airflow:providers/common/sql/tests/unit/common/sql/decorators/test_sql.py:TestSqlDecorator.test_output_processor |
query="web scraping tutorial quiz", # Our search
scoring_method="bm25",
score_threshold=0.2 # Quality filter
))
print(f"\n🎯 Top {len(results)} most relevant r... | 1 | function_simple | unclecode/crawl4ai:docs/examples/url_seeder/url_seeder_quick_demo.py:smart_search_with_bm25 |
"operationId": "read_root__get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
... | 1 | test | fastapi/fastapi:tests/test_schema_ref_pydantic_v2.py:test_openapi_schema |
"before_return_html": before_return_html_hook,
},
hooks_timeout=45
)
execution_time = time.time() - start_time
if results and results.success:
print(f"\n✅ Complete pipeline executed successfully! (took {execution_time:.2f}s)")
print(f" • ... | 1 | function_simple | unclecode/crawl4ai:docs/releases_review/v0.7.5_docker_hooks_demo.py:demo_4_complete_hook_pipeline |
_col_name = "invalid_column"
with pytest.raises(ValueError, match="there's no such column in the dataset"):
ds.sort(invalid_col_name).take_all()
ds_named = ray.data.from_items(
[
{"col1": 1, "col2": 2},
{"col1": 3, "col2": 4},
{"col1": 5, "col2": 6},
... | 0 | test | ray-project/ray:python/ray/data/tests/test_execution_optimizer_advanced.py:test_sort_validate_keys |
f.write(f"## {section}\n")
f.write(f"timestamp: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
for item in data:
if not item:
# skip falsy values like None or empty dict etc.
continue
if isinstance(item, str)... | 0 | function_complex | karpathy/nanochat:nanochat/report.py:Report.log |
lambda self: self.model_runner.model.language_model.model.normalizer.cpu().item() # noqa: E501
)
config = llm.llm.llm_engine.model_config.hf_config.text_config
else:
normalizers = llm.llm.collective_rpc(
lambda self: self.... | 1 | test | vllm-project/vllm:tests/models/language/generation/test_gemma.py:test_dummy_loader |
_ID,
project_id=GCP_PROJECT,
location=GCP_LOCATION,
experiment_name=TEST_EXPERIMENT_NAME,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
delete_backing_tensorboard_runs=TEST_DELETE_BACKING_TENSORBOARD_RUNS,
)
op.e... | 1 | test | apache/airflow:providers/google/tests/unit/google/cloud/operators/vertex_ai/test_experiment_service.py:TestVertexAIDeleteExperimentOperator.test_execute |
test_with_invalid_names(presto_hook, mock_cursor):
"""Ensure PrestoHook.run handles queries returning reserved/invalid column names without raising errors."""
invalid_names = ["1_2_3", "select", "from"]
mock_cursor.description = get_cursor_descriptions(invalid_names)
expected_data = [(1, "row1", "bar... | 1 | test | apache/airflow:providers/presto/tests/unit/presto/hooks/test_presto_sql.py:test_with_invalid_names |
Create a HtpasswdFile from a string.
"""
self.users: dict[str, str] = {}
for line in content.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
if ":" not in line:
raise ValueError(f"Malformed htpa... | 0 | function_complex | mitmproxy/mitmproxy:mitmproxy/utils/htpasswd.py:HtpasswdFile.__init__ |
set_default_attn_processor()
pipe_loaded.to(torch_device)
pipe_loaded.set_progress_bar_config(disable=None)
for component in optional_component:
self.assertTrue(
getattr(pipe_loaded, component) is None,
f"`{component}` did not stay set to None... | 1 | test | huggingface/diffusers:tests/pipelines/wan/test_wan_22_image_to_video.py:Wan225BImageToVideoPipelineFastTests.test_save_load_optional_components |
间字符串标准化为 HH:MM 格式"""
try:
parts = time_str.strip().split(":")
if len(parts) != 2:
raise ValueError(f"时间格式错误: {time_str}")
hour = int(parts[0])
minute = int(parts[1])
if not (0 <= hour <= 23 and 0 <= minute <= 59):
rais... | 1 | function_complex | sansan0/TrendRadar:trendradar/utils/time.py:TimeWindowChecker._normalize_time |
param."""
if isinstance(message, UserMessage):
user_result: ChatCompletionUserMessageParam = {
'role': 'user',
'content': OpenAIMessageSerializer._serialize_user_content(message.content),
}
if message.name is not None:
user_result['name'] = message.name
return user_result
elif isinstance(... | 0 | function_complex | browser-use/browser-use:browser_use/llm/openai/serializer.py:OpenAIMessageSerializer.serialize |
):
"""Test that ExecutorCallback can be serialized and deserialized"""
callback = ExecutorCallback(TEST_SYNC_CALLBACK, fetch_method=CallbackFetchMethod.IMPORT_PATH)
session.add(callback)
session.commit()
retrieved = session.scalar(select(Callback).where(Callback.id == callback.i... | 1 | test | apache/airflow:airflow-core/tests/unit/models/test_callback.py:TestExecutorCallback.test_polymorphic_serde |
def capture_started(source, event):
events.append(event)
@crewai_event_bus.on(MethodExecutionFinishedEvent)
def capture_finished(source, event):
events.append(event)
flow = AndConditionFlow()
await flow.akickoff()
... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/events/test_event_ordering.py:TestTriggeredByEventId.test_and_condition_triggered_by_last_method |
look at first arg.
Args:
args: Flat list of arguments.
in_axes: Flat tuple of axis indices (int or None for each arg).
Returns:
The size of the mapped axis.
Raises:
ValueError: If no args have a mapped axis.
"""
if args and in_axes:
# Fast path: check first arg/axis (most common case).... | 1 | function_complex | jax-ml/jax:jax/_src/pmap.py:_mapped_axis_size |
that TorchTrainer raises exception on NCCL timeouts."""
def train_fn():
model = torch.nn.Linear(1, 1)
model = ray.train.torch.prepare_model(model)
# Rank 0 worker will never reach the collective operation.
# NCCL should timeout.
if ray.train.get_context().get_world_rank() ... | 0 | test | ray-project/ray:python/ray/train/v2/tests/test_torch_gpu.py:test_torch_fail_on_nccl_timeout |
_response_model(agent_ids: tuple[str, ...]) -> type[BaseModel] | None:
"""Create a dynamic AgentResponse model with Literal types for agent IDs.
Args:
agent_ids: List of available A2A agent IDs.
Returns:
Dynamically created Pydantic model with Literal-constrained a2a_ids field,
or ... | 0 | function_simple | crewAIInc/crewAI:lib/crewai/src/crewai/a2a/utils/response_model.py:create_agent_response_model |
image file"""
import tempfile
from pathlib import Path
from PIL import Image as PILImage
# Create a temporary directory and test image
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
tex_file = tmpdir_path / "test.tex"
img_file = tmpdir_path / "tes... | 1 | test | docling-project/docling:tests/test_backend_latex.py:test_latex_includegraphics |
_custom_url(self, mock_crewai):
"""Test Ollama LLM creation with custom base URL."""
from lfx.components.agentics.helpers.llm_factory import create_llm
mock_llm = MagicMock()
mock_crewai.return_value = mock_llm
result = create_llm(
provider=PROVIDER_OLLAMA,
... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/components/bundles/agentics/test_llm_factory.py:TestCreateLlm.test_should_create_ollama_llm_with_custom_url |
"""Run one forward pass and return (keypoints_list, scores_list) for the batch."""
nonlocal captured_feat
captured_feat = None
_ = comfy.sample.sample(
model_clone,
noise=torch.zeros_like(latent_batch),
steps=1, cfg=1.0,
... | 1 | function_simple | Comfy-Org/ComfyUI:comfy_extras/nodes_sdpose.py:_run_on_latent |
if value != "auto":
kwargs[sweep.param_name] = value
# Run benchmark
result = run_benchmark(config, **kwargs)
# Replace backend with labeled version for display
backend_label = sweep.get_label(ba... | 1 | function_complex | vllm-project/vllm:benchmarks/attention_benchmarks/benchmark.py:run_parameter_sweep |
if alice_submitted and alice_input:
with st.spinner("Processing Alice's message..."):
session = st.session_state.session_manager.get_session(alice_session_id, "multi_user.db")
result = asyncio.run(Runner.run(support_agent, alice_input, session=se... | 0 | function_complex | Shubhamsaboo/awesome-llm-apps:ai_agent_framework_crash_course/openai_sdk_crash_course/7_sessions/streamlit_sessions_app.py:render_multi_sessions |
, freshness: str, summary: bool) -> ToolResult:
"""
Search using Bocha API
:param query: Search query
:param count: Number of results
:param freshness: Time range filter
:param summary: Whether to include summary
:return: Formatted search results
"""
... | 1 | function_complex | zhayujie/chatgpt-on-wechat:agent/tools/web_search/web_search.py:WebSearch._search_bocha |
00world\x00test"
expected = "Helloworldtest"
assert sanitize_for_postgres(text_with_nul) == expected
# Test with replacement character
expected_with_replacement = "Hello world test"
assert sanitize_for_postgres(text_with_nul, " ") == expected_with_replacement
# Test with text without NUL bytes... | 1 | test | langchain-ai/langchain:libs/core/tests/unit_tests/utils/test_strings.py:test_sanitize_for_postgres |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.