input string | label int64 | category string | sample_id string |
|---|---|---|---|
self._access_token is None
or self._token_expires_at is None
or time.time() >= self._token_expires_at
):
async with self._lock:
if (
self._access_token is None
or self._token_expires_at is None
or ... | 0 | function_complex | crewAIInc/crewAI:lib/crewai/src/crewai/a2a/auth/client_schemes.py:OAuth2ClientCredentials.apply_auth |
| None = None,
**kwargs: Unpack[SegformerImageProcessorKwargs],
) -> BatchFeature:
"""
Preprocess image-like inputs.
"""
images = self._prepare_image_like_inputs(
images=images, do_convert_rgb=do_convert_rgb, input_data_format=input_data_format, device=device
... | 0 | function_simple | huggingface/transformers:src/transformers/models/segformer/modular_segformer.py:SegformerImageProcessorFast._preprocess_image_like_inputs |
"""Emit LLM call completed event."""
from crewai.utilities.serialization import to_serializable
crewai_event_bus.emit(
self,
event=LLMCallCompletedEvent(
messages=to_serializable(messages),
response=to_serializable(response),
call... | 0 | function_simple | crewAIInc/crewAI:lib/crewai/src/crewai/llms/base_llm.py:BaseLLM._emit_call_completed_event |
用于处理 inlineRun 类型的外层 marks。
"""
if not isinstance(mark, dict):
return text
mtype = mark.get("type")
if mtype == "bold":
return f"**{text}**"
elif mtype == "italic":
return f"*{text}*"
elif mtype == "underline":
return f"__{... | 1 | function_complex | 666ghj/BettaFish:ReportEngine/renderers/markdown_renderer.py:MarkdownRenderer._apply_mark |
"""
Simple test that checks if the quantized model is working properly after being saved and loaded
"""
with tempfile.TemporaryDirectory() as tmpdirname:
self.quantized_model.save_pretrained(tmpdirname)
model = AutoModelForCausalLM.from_pretrained(tmpdirname, devi... | 0 | test | huggingface/transformers:tests/quantization/fp_quant_integration/test_fp_quant.py:FPQuantBaseTest.test_save_pretrained |
(
response.iter_bytes(1)
) # Read 1 byte, then exit - connection closes
# Run many times to hit the race (disconnect arrives before request_task exits)
num_requests = 500
with ThreadPoolExecutor(max_workers=10) as executor:
futures = [
executor.submi... | 0 | test | ray-project/ray:python/ray/serve/tests/test_metrics_haproxy.py:test_no_499_misclassification_after_successful_response |
still_applied_to_regular_responses():
"""
Test that stop words ARE still applied for regular (non-structured) responses.
This ensures the fix didn't break normal stop word behavior.
"""
# Create OpenAI completion instance with stop words configured
llm = OpenAICompletion(
model="gpt-4o",... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/llms/openai/test_openai.py:test_openai_stop_words_still_applied_to_regular_responses |
large payloads."""
@serve.deployment
class LargePayloadHandler:
def __call__(self, request):
# Return a large response (1MB)
large_data = "x" * (1024 * 1024) # 1MB string
return {"data": large_data, "size": len(large_data)}
serve.ru... | 0 | test | ray-project/ray:python/ray/serve/tests/test_https_proxy.py:TestHTTPSProxy.test_https_large_payload |
batch, grad_value in zip(data_loader, normal_gradients):
run_model_step(model, batch[0], batch[1], grad_value)
expected_loss_scale *= 2
assert loss_scaler.cur_scale == expected_loss_scale
assert loss_scaler.cur_iter == expected_iteration
# Run model with overflows to decre... | 1 | test | deepspeedai/DeepSpeed:tests/unit/runtime/half_precision/test_zero_optim_overflow.py:TestZeROFloat16.test_some_overflow |
3ForConditionalGeneration.from_pretrained(
"lkhl/VideoLLaMA3-2B-Image-HF", dtype=torch.bfloat16, device_map=torch_device
)
text = self.processor.apply_chat_template(self.messages, tokenize=False, add_generation_prompt=True)
messages2 = [
{"role": "user", "content": [{"typ... | 0 | test | huggingface/transformers:tests/models/video_llama_3/test_modeling_video_llama_3.py:VideoLlama3IntegrationTest.test_small_model_integration_test_batch_wo_image |
device,
rank,
dtype,
seed=42 + i,
lr=lr,
| 1 | test | deepspeedai/DeepSpeed:tests/unit/v1/zero/test_zero_user_backward.py:TestZeroUserBackwardMultipleEngines.test_multiple_engines_combined_loss |
**ray.get(client._controller.get_serve_instance_details.remote())
)
proxy_actor_ids = {proxy.actor_id for _, proxy in serve_details.proxies.items()}
assert len(proxy_actor_ids) == 3
# Start a long-running request in background to test draining behavior
request_result = []
def make_blo... | 0 | test | ray-project/ray:python/ray/serve/tests/test_haproxy.py:test_drain_and_undrain_haproxy_manager |
heads
)
num_key_value_heads = (
text_config.num_attention_heads
if getattr(text_config, "num_key_value_heads", None) is None
else text_config.num_key_value_heads
)
num_hidden_layers = text_config.num_hidden_layers
... | 0 | test | huggingface/transformers:tests/models/gemma3n/test_modeling_gemma3n.py:Gemma3nTextModelTest.test_generate_from_inputs_embeds_with_static_cache |
MagicMock()
var1.name = "WATSONX_APIKEY"
var1.type = "Credential"
var2 = MagicMock()
var2.name = "WATSONX_PROJECT_ID"
var2.type = "Credential"
var3 = MagicMock()
var3.name = "WATSONX_URL"
var3.type = "Credential"
mock_variables = [var1, var2, var... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/agentic/services/test_provider_service_multi.py:TestGetEnabledProvidersForUserMulti.test_should_enable_provider_when_all_required_vars_present |
shape, expected_shape)
# Confirm out_indices was propagated to backbone
self.assertEqual(len(model.model.backbone.intermediate_channel_sizes), 3)
else:
# Confirm out_indices was propagated to backbone
self.assertEqual(len(mo... | 0 | test | huggingface/transformers:tests/models/d_fine/test_modeling_d_fine.py:DFineModelTest.test_backbone_selection |
model_eager = model_eager.eval().to(torch_device)
self.assertTrue(model_eager.config._attn_implementation == "eager")
self.assertTrue(model_eager.language_model.config._attn_implementation == "eager")
self.assertTrue(model_eager.audio_tower.config._attn_impl... | 0 | test | huggingface/transformers:tests/models/glmasr/test_modeling_glmasr.py:GlmAsrForConditionalGenerationModelTest.test_sdpa_can_dispatch_composite_models |
encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
self.assertEqual(
tuple(encoded_images.shape),
(1, image_processing.max_num_patches, 3 * image_processing.encoder_patch_size**2),
)
# Test batched
encoded_images = image_proces... | 0 | test | huggingface/transformers:tests/models/lfm2_vl/test_image_processing_lfm2_vl.py:Lfm2VlImageProcessingTest.test_call_pytorch |
single_image_embeds = ip_adapter_image_embeds
elif ip_adapter_image is not None:
single_image_embeds = self.encode_image(ip_adapter_image, device)
if do_classifier_free_guidance:
single_negative_image_embeds = torch.zeros_like(single_image_embeds)
el... | 1 | function_complex | huggingface/diffusers:examples/community/pipeline_stable_diffusion_3_instruct_pix2pix.py:StableDiffusion3InstructPix2PixPipeline.prepare_ip_adapter_image_embeds |
_weights, block_size
):
"""Test that grouped and per-channel have different scale shapes."""
input_dim, output_dim = 100, 256
layer = layers.ReversibleEmbedding(
input_dim=input_dim, output_dim=output_dim, tie_weights=tie_weights
)
layer.build()
config =... | 1 | test | keras-team/keras:keras/src/layers/core/reversible_embedding_test.py:ReversibleEmbeddingTest.test_int4_grouped_vs_perchannel_scale_shapes |
maintain the aspect ratio.
interpolation:
`tvF.InterpolationMode` filter to use when resizing the image e.g. `tvF.InterpolationMode.BICUBIC`.
Returns:
`torch.Tensor`: The resized image.
"""
if not size.longest_edge:
raise ValueError(f"T... | 0 | function_simple | huggingface/transformers:src/transformers/models/sam/image_processing_sam_fast.py:SamImageProcessorFast.resize |
]
):
"""Decorator to register a function as a before_tool_call hook.
Example:
Simple usage::
@before_tool_call
def log_all_tools(context):
print(f"Tool: {context.tool_name}")
return None
With tool filter::
@before_tool_cal... | 0 | function_simple | crewAIInc/crewAI:lib/crewai/src/crewai/hooks/decorators.py:before_tool_call |
, conda=conda_name)
runtime_env = RuntimeEnv(pip=pip_packages)
runtime_env["conda"] = conda_name
with pytest.raises(ValueError):
runtime_env.serialize()
# Test the interface related to container
container_init = {
"image": "anyscale/ray-ml:nightly-py38-cpu",
"run_options": ... | 0 | test | ray-project/ray:python/ray/tests/unit/test_runtime_env.py:test_runtime_env_interface |
class MyModel(PreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.layer = None
@auto_docstring
def forward(self, input_ids, scale_factor: float = 1.0):
... | 0 | test | huggingface/transformers:tests/utils/test_auto_docstring.py:TestCheckDocstrings.test_multi_item_file_processing |
size (C = W+L+R), max_span_plus_1 (F_span = L+R+1).
Returns:
Tensor of shape [B, N, U, W, C].
"""
# term_bd_before_shift shape: [B, N, U, W, F_span]
# Target shape after shift: [B, N, U, W, C]
# Padding amount for the last dimension (F_span) to become (C + 1)
... | 0 | function_simple | huggingface/transformers:src/transformers/models/gemma3n/modular_gemma3n.py:Gemma3nAudioRelativePositionEmbedding._relative_shift |
):
The scheduler to get timesteps from.
num_inference_steps (`int`):
The number of diffusion steps 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... | 1 | function_complex | huggingface/diffusers:src/diffusers/pipelines/sana/pipeline_sana_sprint_img2img.py:retrieve_timesteps |
name=None, type_="STRING", value="cfo@company.com"
),
bigquery.ArrayQueryParameter(
name="node_ids", array_type="STRING", values=["node1", "node2"]
),
bigquery.ScalarQueryParameter("top_k", "INTEGER", 5),
bigquery.ScalarQueryParameter("distance_type", "STRI... | 1 | test | run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-bigquery/tests/test_vector_search.py:test_query_vector_store_with_filters_generates_correct_sql_and_params |
Line one\nLine two\nLine three\nLine four\nLine five"
text = TextFile(source=content.encode(), filename="lines.txt")
result = list(
chunk_text(text, max_chars=25, overlap_chars=0, split_on_newlines=True)
)
# Should split at newline boundaries
for chunk in result:
... | 0 | test | crewAIInc/crewAI:lib/crewai-files/tests/processing/test_transformers.py:TestChunkText.test_chunk_prefers_newline_boundaries |
self):
docs = render_chart(
values={
"airflowVersion": "3.0.0",
"ingress": {
"apiServer": {
"enabled": True,
"tls": {"enabled": True, "secretName": "oldsecret"},
"hosts": [
... | 1 | test | apache/airflow:helm-tests/tests/helm_tests/apiserver/test_ingress_apiserver.py:TestIngressAPIServer.test_should_ingress_hosts_objs_have_priority_over_host |
batch_tokens
num_pages = self.cache.num_blocks * self.cache.block_size
pin_memory = self.device.type == "cpu"
# Small inputs are allocated as slices in a larget tensor aligned to 128 bytes (32 * 4b). This reduces the
# reduces fragmentation, so it lowers the number of D2H transfers and ... | 0 | function_complex | huggingface/transformers:src/transformers/generation/continuous_batching/input_outputs.py:ContinuousBatchingIOs._setup_static_tensors |
Update the podcast language with the specified language code.
This ensures the language is properly tracked for generating content and audio.
Args:
agent: The agent instance
language_code: The language code (e.g., 'en', 'es', 'fr', etc..)
Returns:
Confirmation message
"""
... | 0 | function_simple | Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/tools/session_state_manager.py:update_language |
-Configure MCP servers disabled, skipping starter project MCP configuration")
return
await logger.adebug(
f"Auto-configure settings: add_projects_to_mcp_servers="
f"{settings_service.settings.add_projects_to_mcp_servers}, "
f"create_starter_projects={settings_service.settings.create_... | 1 | function_complex | langflow-ai/langflow:src/backend/base/langflow/api/utils/mcp/config_utils.py:auto_configure_starter_projects_mcp |
Corresponds to the ``--preview`` CLI option.
:param fast: True to enable fast mode.
Corresponds to the ``--fast`` CLI option.
:param python_variant: The Python variant to use.
Corresponds to the ``--pyi`` CLI option if this is "pyi".
Otherwise, corresponds to th... | 1 | function_complex | psf/black:src/blackd/client.py:BlackDClient.__init__ |
msg)
if term.lower() != self.lookup_str:
self.lookup_str = term.lower()
self.lookup_index = 0
else:
self.lookup_index += 1
lookups = [p for p in self._paragraphs if self.lookup_str in p.lower()]
if len(lookups) == 0:
return "No Results"
... | 1 | function_simple | langchain-ai/langchain:libs/langchain/langchain_classic/agents/react/base.py:DocstoreExplorer.lookup |
Dict[str, Any]) -> Dict[str, Any]:
"""Transform request for AI Gateway format."""
# Extract headers and body
headers = kwargs.get("headers", {})
json_data = kwargs.get("json", {})
# Get endpoint from URL
endpoint = self.provider_config.transform_endpoint(url)
#... | 1 | function_simple | run-llama/llama_index:llama-index-integrations/llms/llama-index-llms-cloudflare-ai-gateway/llama_index/llms/cloudflare_ai_gateway/base.py:AIGatewayClientWrapper._transform_request |
_session)
# Verify we're on the second page
second_url = await browser_session.get_current_page_url()
print(f'Second page URL: {second_url}')
assert f'{base_url}/page2' in second_url
# Execute go back action
result = await tools.go_back(browser_session=browser_session)
# Verify the result
assert isin... | 0 | test | browser-use/browser-use:tests/ci/test_tools.py:TestToolsIntegration.test_go_back_action |
input_tensor = torch.randn(num_tokens, hidden_size, device="cuda", dtype=dtype)
# Create a random permutation map
dst2src_map = torch.randperm(num_tokens, device="cuda", dtype=torch.int32)
# Test shuffle_rows
output = shuffle_rows(input_tensor, dst2src_map)
# Check output shape and properties
... | 1 | test | vllm-project/vllm:tests/kernels/test_shuffle_rows.py:test_shuffle_rows_random_permutation |
timeout=30
)
# Check that model parameters are stored on the LLM instance
assert llm.temperature == 0.7
assert llm.max_tokens == 1000
assert llm.top_p == 0.5
# Check that client parameters are properly configured
assert llm.client.max_retries == 3
assert llm.client.timeout == 30
... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/llms/openai/test_openai.py:test_openai_client_setup_with_extra_arguments |
= layers.Dense(32, activation="relu", name="shared_layer")(inputs)
output1 = layers.Dense(1, activation="sigmoid", name="output_1")(x)
output2 = layers.Dense(2, activation="softmax", name="output_2")(x)
model = models.Model(
inputs=inputs, outputs=[output1, output2], name="multi_out... | 1 | test | keras-team/keras:keras/src/export/litert_test.py:ExportLitertTest.test_signature_def_with_multi_output_model |
with_models_ollama):
"""Test that each model maintains its own dimension."""
embeddings_list = [embeddings_with_models_openai, embeddings_with_models_ollama]
for emb_wrapper in embeddings_list:
if isinstance(emb_wrapper, EmbeddingsWithModels):
for model_instance in e... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/components/vectorstores/test_opensearch_multimodal.py:TestOpenSearchMultimodalIntegration.test_embedding_dimension_consistency |
.
Args:
a2a_task: A2A Task object
default: Default message if no error found
Returns:
Error message string
"""
if a2a_task.status and a2a_task.status.message:
msg = a2a_task.status.message
if msg:
for part in msg.parts:
if part.root.k... | 0 | function_complex | crewAIInc/crewAI:lib/crewai/src/crewai/a2a/task_helpers.py:extract_error_message |
def _attempt_json_repair(self, text: str) -> str | None:
"""使用可选的json_repair库进一步修复复杂语法错误"""
if not _json_repair_fn:
return None
try:
fixed = _json_repair_fn(text)
except Exception as exc: # pragma: no cover - 库级故障
logger.warning(f"json_repair 修复章节JSON... | 1 | function_simple | 666ghj/BettaFish:ReportEngine/nodes/chapter_generation_node.py:ChapterGenerationNode._attempt_json_repair |
examples, ddp_world_size):
conversation = task[idx]
tokens = tokenizer.render_for_completion(conversation)
prefix_length = len(tokens)
# Generate k samples using batched generation inside the Engine
assert num_samples <= args.device_batch_size # usually this is true. we can add a... | 0 | function_simple | karpathy/nanochat:scripts/chat_rl.py:run_gsm8k_eval |
if collection not in self.collections:
logger.warning(f"Collection '{collection}' not found in ComponentsManager")
return
if component_id not in self.collections[collection]:
logger.warning(f"Component '{component_id}' not found in collection '{collection}'")
re... | 1 | function_simple | huggingface/diffusers:src/diffusers/modular_pipelines/components_manager.py:ComponentsManager.remove_from_collection |
def is_sleeping(
self, model: str = Query(..., description="The model ID to check")
) -> IsSleepingResponse:
"""Check if the engine is sleeping for the specified model.
This checks the sleep status across all replicas. Returns True if
ANY replica is sleeping (uses logical OR across... | 0 | function_simple | ray-project/ray:python/ray/llm/_internal/serve/core/ingress/mixins/sleepable.py:SleepableIngressMixin.is_sleeping |
user="test_user",
password="test_pass",
host="localhost",
port=5432,
diskann=False,
hnsw=False,
minconn=1,
maxconn=4,
sslmode="require",
connection_string=connection_string
)
# V... | 1 | test | mem0ai/mem0:tests/vector_stores/test_pgvector.py:TestPGVector.test_connection_string_with_sslmode_psycopg3 |
s3_path = "flow_123/data.csv"
component.set_attributes(
{
"model": model_value,
"path": s3_path,
"agent_type": "openai-tools",
"input_value": "test",
}
)
csv_content = b"col1,col2\n1,2\n3,4"
# ... | 1 | test | langflow-ai/langflow:src/lfx/tests/unit/components/langchain_utilities/test_csv_agent.py:TestCSVAgentComponent.test_get_local_path_with_s3_file |
:
Tuple of (pos_x, pos_y) positional embeddings
"""
x_embed = x * self.scale
y_embed = y * self.scale
dim_t = torch.arange(self.num_pos_feats, dtype=torch.int64, device=x.device).to(x.dtype)
dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
... | 0 | function_simple | huggingface/transformers:src/transformers/models/sam3/modeling_sam3.py:Sam3SinePositionEmbedding.encode_1d_positions |
"""Test that when variable not found in db and env var doesn't exist.
The field is set to None.
"""
# Make sure env var doesn't exist
if "NONEXISTENT_KEY" in os.environ:
del os.environ["NONEXISTENT_KEY"]
# Create mock custom component
custom_component = MagicMock()
# Change this e... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/interface/initialize/test_loading.py:test_update_params_sets_none_when_no_env_var_and_fallback_enabled |
s
continue
normalized_node = {}
for media_type, items in node_outputs.items():
if media_type == 'animated' or not isinstance(items, list):
normalized_node[media_type] = items
continue
normalized_items = []
for item in items:... | 1 | function_complex | Comfy-Org/ComfyUI:comfy_execution/jobs.py:normalize_outputs |
path (str or Bip32Path object): Path
Returns:
Bip32Base object: Bip32Base object
Raises:
Bip32KeyError: If the index results in an invalid key
Bip32PathError: If the path is not valid
ValueError: If the path is a master path and the key is a child ... | 1 | function_simple | ccxt/ccxt:python/ccxt/static_dependencies/bip/bip32/base/bip32_base.py:Bip32Base.DerivePath |
This provider blocks execution and waits for console input from the user.
It serves two purposes:
- **Feedback** (``request_feedback``): Used by ``@human_feedback`` to
display method output and collect review feedback.
- **Input** (``request_input``): Used by ``Flow.ask()`` to prompt the
user with a question and ... | 0 | documentation | crewAIInc/crewAI:lib/crewai/src/crewai/flow/async_feedback/providers.py:ConsoleProvider:class_doc |
points.openai.responses.context.logger.error") as mock_log:
context = HarmonyContext(messages=[], available_tools=["browser"])
# First turn
mock_output1 = create_mock_request_output(
prompt_token_ids=list(range(10)), # 10 tokens
output_token_ids=[1, 2, 3, 4, 5], # 5 to... | 1 | test | vllm-project/vllm:tests/entrypoints/test_context.py:test_negative_tool_tokens_edge_case |
, mock_get_connection, mock_connection_minimal):
mock_get_connection.return_value = mock_connection_minimal
mock_fs_instance = MagicMock()
mock_msgdrivefs.return_value = mock_fs_instance
storage_options = {"drive_id": "storage_drive_id", "scope": "custom.scope"}
result = get_fs(... | 1 | test | apache/airflow:providers/microsoft/azure/tests/unit/microsoft/azure/fs/test_msgraph.py:TestMSGraphFS.test_get_fs_with_storage_options |
that empty feedback without default uses first outcome."""
class FallbackFlow(Flow):
@start()
@human_feedback(
message="Review:",
emit=["first", "second", "third"],
llm="gpt-4o-mini",
# No default_outcome specified
... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/test_human_feedback_integration.py:TestEdgeCases.test_empty_feedback_first_outcome_fallback |
input_path,
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
)
expected_output = os.path.join(
os.path.dirname(output_path),
os.path.splitext(os.path.basename(input_p... | 1 | function_simple | docling-project/docling:docling/backend/docx/drawingml/utils.py:get_docx_to_pdf_converter |
ryable
if attempt < self.max_retries - 1:
delay = min(self.retry_base_delay * (2**attempt), self.retry_max_delay)
jitter = random.uniform(0, delay * 0.1)
total_delay = delay + jitter
error_type = 'timeout' if isinstance(e, httpx.TimeoutException) else 'connection error'
logger.warning(
... | 0 | function_complex | browser-use/browser-use:browser_use/llm/browser_use/chat.py:ChatBrowserUse.ainvoke |
f'backendNodeId={node.original_node.backend_node_id} {attr_str}'
)
else:
logger.debug(
f'🔍 SKIPPING interactive <{node.original_node.tag_name}> (no snapshot_node, not in shadow DOM): '
f'backendNodeId={node.original_node.backend_node_id} {attr_str}'
)
# EXCEPTION: File inputs are ... | 0 | function_complex | browser-use/browser-use:browser_use/dom/serializer/serializer.py:DOMTreeSerializer._assign_interactive_indices_and_mark_new_nodes |
ize_vectorx_index_import_error(self):
import builtins
original_import = builtins.__import__
def mock_import(name, *args, **kwargs):
if name == "vecx.vectorx":
raise ImportError("No module named vecx.vectorx")
return original_import(name, *args, **kwargs)... | 1 | test | run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-vectorx/tests/test_vector_stores_vectorx.py:TestVectorXAdvanced.test_initialize_vectorx_index_import_error |
class__.__name__
op_name = _format_op_name(op)
tb_str = "".join(traceback.format_exception(type(e), e, e.__traceback__))
if isinstance(extras, tuple) and len(extras) == 2:
length, target_keys = extras
descriptor = f"{op_name} " if op_name else ""
loading_inf... | 0 | function_complex | huggingface/transformers:src/transformers/core_model_loading.py:log_conversion_errors |
tree.add_tenants(["tenant_1"], 0)
tree.insert("hello", "tenant_1", 1)
hello_node = tree.root.edge_label_to_child["h"]
assert hello_node.tenant_to_last_access_time == {"tenant_1": 1}
assert tree.tenant_to_char_count == {"tenant_1": 5}
assert tree.root.edge_label_to_child == {"h... | 0 | test | ray-project/ray:python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py:TestPrefixTreeRemove.test_remove_single_leaf_node_pruned |
pad_dims = (0, pad_width)
logits = nn.functional.pad(logits, pad_dims, value=-float("inf"))
padded_logits.append(logits)
# Stack along new dim=0 (categorical dimension).
# Shape: (num_components, B, T, max_K) or (num_components, B, max_K)
stacked = torch... | 0 | function_simple | ray-project/ray:rllib/core/distribution/torch/torch_distribution.py:TorchMultiCategorical.to_deterministic |
, match="`use_gpu` is False but `GPU` was found in"):
ScalingConfig(num_workers=2, use_gpu=False, resources_per_worker={"GPU": 1})
with pytest.raises(ValueError, match="Cannot specify both"):
ScalingConfig(num_workers=2, use_gpu=True, use_tpu=True)
with pytest.raises(
ValueError,
... | 0 | test | ray-project/ray:python/ray/train/v2/tests/test_config.py:test_scaling_config_validation |
ises_error_when_default_invalid(
self,
mocker: MockerFixture,
valid_choices: set[str],
) -> None:
"""Test that function raises ValueError when default value is not in choices."""
mocker.patch.dict("os.environ", {}, clear=True)
with pytest.raises(ValueError) as exc_in... | 1 | test | paperless-ngx/paperless-ngx:src/paperless/tests/settings/test_environment_parsers.py:TestGetEnvChoice.test_raises_error_when_default_invalid |
37813758850098,
-9.995306968688965, -10.06312370300293, -10.039563179016113, -10.00948715209961, -10.04725170135498,
-10.08010196685791, -10.043283462524414, -10.06112289428711, -9.989591598510742, -10.034473419189453,
-9.958343505859375, -9.956878662109375, -10.006301879882812, -10.... | 0 | test | huggingface/transformers:tests/models/moonshine_streaming/test_modeling_moonshine_streaming.py:MoonshineStreamingModelIntegrationTests.test_medium_logits_single |
WorkflowValidationError: If flow validation fails
"""
try:
return await asyncio.wait_for(
execute_sync_workflow(
workflow_request=workflow_request,
flow=flow,
job_id=job_id,
api_key_user=api_key_user,
ba... | 1 | function_simple | langflow-ai/langflow:src/backend/base/langflow/api/v2/workflow.py:execute_sync_workflow_with_timeout |
=True)
# Mock context to capture stream events
mock_context = AsyncMock(spec=Context)
mock_context.is_running = True # Required for event writing
stream_events = []
def capture_event(event):
stream_events.append(event)
mock_context.write_event_to_stream.side_effect = capture_event
... | 1 | test | run-llama/llama_index:llama-index-core/tests/agent/workflow/test_thinking_delta.py:test_react_agent_comprehensive_thinking_streaming |
defaults["python"] in cfg["python"], (
f"{image_type}: default python '{defaults['python']}' "
f"not in supported {cfg['python']}"
)
assert defaults["gpu_platform"] in cfg["platforms"], (
f"{image_type}: default gpu_platform '{defaults['gpu_platform']}' "
... | 0 | test | ray-project/ray:ci/ray_ci/test_supported_images.py:TestRayImagesSchema.test_defaults_in_supported |
_value = mock_browser
mock_get_current_page.return_value = mock_page
mock_page.eval_on_selector_all.return_value = []
tool_spec = AgentCoreBrowserToolSpec()
tool_spec._session_manager = mock_session_manager
result = tool_spec.extract_hyperlinks(thread_id="test-thread")
... | 1 | test | run-llama/llama_index:llama-index-integrations/tools/llama-index-tools-aws-bedrock-agentcore/tests/test_browser.py:TestAgentCoreBrowserToolSpec.test_extract_hyperlinks_no_links |
multi-mask outputs (based on output token 1~3) the mask with the highest predicted
IoU score. This is intended to ensure a valid mask for both clicking and tracking.
"""
# The best mask from multimask output tokens (1~3)
multimask_logits = all_mask_logits[:, :, 1:, :, :]
... | 0 | function_simple | huggingface/transformers:src/transformers/models/sam2/modular_sam2.py:Sam2MaskDecoder._dynamic_multimask_via_stability |
child):
"""Extract structured reference info from PubMed XML"""
def safe_find(path):
node = child
for p in path.split("/"):
if node is None:
return None
node = node.find(p)
return node.text if node is not None and n... | 1 | function_complex | infiniflow/ragflow:agent/tools/pubmed.py:PubMed._format_pubmed_content |
_multiple_errors_do_not_crash_with_fail_on_rank_error_false(self):
"""Test that multiple consecutive errors don't crash when fail_on_rank_error=False."""
rank_manager = DeploymentRankManager(fail_on_rank_error=False)
# Multiple errors in a row should all return safe defaults
result1 = r... | 0 | test | ray-project/ray:python/ray/serve/tests/unit/test_deployment_rank_manager.py:TestDeploymentRankManagerErrorHandling.test_multiple_errors_do_not_crash_with_fail_on_rank_error_false |
ify embeddings endpoint works with single and batch inputs."""
# Single input
emb_resp = sglang_embedding_client.embeddings.create(
model=RAY_MODEL_ID,
input="Hello world",
)
assert emb_resp.data
assert len(emb_resp.data) == 1
assert emb_resp.data[0].embedding
assert len(emb_... | 0 | test | ray-project/ray:release/llm_tests/serve/test_llm_serve_sglang.py:test_sglang_embeddings |
"""Test local file processing with captured_console initialization"""
with tempfile.NamedTemporaryFile(mode='w', suffix='.html', delete=False) as f:
f.write("<html><body><h1>Local File Test</h1></body></html>")
temp_file = f.name
try:
async with AsyncWe... | 1 | test | unclecode/crawl4ai:tests/releases/test_release_0.7.0.py:TestCrawl4AIv070.test_local_file_processing |
enable_remote_services: bool,
artifacts_path: Optional[Union[Path, str]],
options: CodeFormulaVlmOptions,
accelerator_options: AcceleratorOptions,
):
"""Initialize the code/formula extraction stage.
Args:
enabled: Whether this stage is enabled
... | 1 | function_simple | docling-project/docling:docling/models/stages/code_formula/code_formula_vlm_model.py:CodeFormulaVlmModel.__init__ |
"""Poll cache for cancellation flag."""
while True:
if await cache.get(f"cancel:{task_id}"):
return True
await asyncio.sleep(0.1)
async def watch_for_cancel() -> bool:
"""Watch for cancellation events via pub/sub or polling."""
... | 0 | function_complex | crewAIInc/crewAI:lib/crewai/src/crewai/a2a/utils/task.py:wrapper |
large_node_spec: 1, # 1 existing large node (6 CPUs)
small_node_spec: 0, # 0 existing small nodes
}
autoscaler = DefaultClusterAutoscalerV2(
resource_manager=MagicMock(),
resource_limits=resource_limits,
execution_id="test_execution_id",
... | 0 | test | ray-project/ray:python/ray/data/tests/test_default_cluster_autoscaler_v2.py:TestClusterAutoscaling.test_try_scale_up_existing_nodes_prioritized_over_delta |
scale_eps: bool,
) -> None:
"""Functional API that performs Muon algorithm computation."""
_single_tensor_muon(
params,
grads,
momentum_bufs,
lr=lr,
weight_decay=weight_decay,
momentum=momentum,
nesterov=nesterov,
ns_steps=ns_steps,
ns... | 1 | function_simple | huggingface/pytorch-image-models:timm/optim/muon.py:muon |
pace should be skipped."""
content = dedent("""\
<?xml version="1.0" encoding="UTF-8"?>
<html>
<body>
<div class='ocr_page' title='bbox 0 0 1000 500'>
<p class='ocr_par'>
<span class='ocr_line' title='bbox 100 100 90... | 1 | test | ocrmypdf/OCRmyPDF:tests/test_hocr_parser.py:TestHocrParserEdgeCases.test_whitespace_only_word |
-> bool:
"""Async delete an uploaded file from Gemini.
Args:
file_id: The file name/ID to delete.
Returns:
True if deletion was successful, False otherwise.
"""
try:
client = self._get_client()
await client.aio.files.delete(name=... | 0 | function_simple | crewAIInc/crewAI:lib/crewai-files/src/crewai_files/uploaders/gemini.py:GeminiFileUploader.adelete |
"name": "Jira",
"id": "jira",
"version": "1.0.0",
"description": "Jira",
"tags": ["issue-tracking", "jira"],
},
"linear": {
"name": "Linear",
"id":... | 0 | test | github/spec-kit:tests/test_extensions.py:TestExtensionCatalog.test_search_by_tag |
(`List[str]`, *optional*):
The list of inputs accepted by the forward pass of the model (like `"token_type_ids"` or
`"attention_mask"`). Default value is picked from the class attribute of the same name.
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):... | 0 | function_simple | huggingface/transformers:src/transformers/tokenization_mistral_common.py:MistralCommonBackend.from_pretrained |
to_landmarks,
batch_src_points=None,
batch_dst_points=kwargs["batch_dst_points"])
warp_mock = mocker.patch(f"{MODULE_PREFIX}.ImageAugmentation._random_warp")
warp_lm_mock = mocker.patch(f"{MODUL... | 1 | test | deepfakes/faceswap:tests/lib/training/augmentation_test.py:test_image_augmentation_warp |
with mock.patch("airflow.providers.edge3.models.db.inspect", return_value=mock_inspector):
# Mock the migration context
mock_version_table = mock.MagicMock()
mock_version_table.name = "alembic_version_edge3"
mock_migration_ctx = mock.MagicMock()
mock_migr... | 1 | test | apache/airflow:providers/edge3/tests/unit/edge3/models/test_db.py:TestEdgeDBManager.test_drop_tables_only_drops_edge_tables |
151655, 151655, 151655, 151655, 151655, 151655, 151655, 151655, 151655, 151655, 151655, 151655, 151655] # fmt: skip
self.assertListEqual(expected_input_ids, inputs.input_ids[0].tolist()[:17])
expected_pixel_slice = torch.tensor(
[
[-0.0902, -0.0824, -0.0824],
... | 0 | test | huggingface/transformers:tests/models/qwen3_vl_moe/test_modeling_qwen3_vl_moe.py:Qwen3VLMoeIntegrationTest.test_small_model_integration_test |
ock()
mock_cdp_client.send.Target.getTargets = AsyncMock(return_value={'targetInfos': []})
mock_cdp_client.send.Target.createTarget = AsyncMock(return_value={'targetId': 'test-target-id'})
with patch('browser_use.browser.session_manager.SessionManager') as mock_session_manager_class:
mock_session_manager = Ma... | 0 | test | browser-use/browser-use:tests/ci/browser/test_cdp_headers.py:test_cdp_client_no_headers_when_none |
处理新的WebSocket连接请求,接收初始消息并建立持久连接。
参数:
websocket: WebSocket连接对象
"""
try:
await websocket.accept()
logger.info(f"WebSocket connection established: {websocket.client.host}:{websocket.client.port}")
... | 1 | function_simple | binary-husky/gpt_academic:shared_utils/fastapi_stream_server.py:main |
_ids: torch.Tensor | None = None,
task_type_ids: torch.Tensor | None = None,
position_ids: torch.Tensor | None = None,
inputs_embeds: torch.Tensor | None = None,
labels: torch.Tensor | None = None,
next_sentence_label: torch.Tensor | None = None,
**kwargs: Unpack[Transfor... | 0 | function_simple | huggingface/transformers:src/transformers/models/ernie/modular_ernie.py:ErnieForPreTraining.forward |
async def test_find_validation_error_with_context():
"""Test that find_validation_error searches __context__ chain."""
import pydantic
from langflow.api.v1.mcp import find_validation_error
# Create a pydantic ValidationError by catching it
validation_error = None
try:
class TestModel(p... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/api/v1/test_mcp.py:test_find_validation_error_with_context |
expected_css_url: str,
expected_js_url: str,
) -> None:
"""Verify that asset URL overrides take precedence over default filenames."""
caller_dir = tmp_path / "caller"
caller_file = caller_dir / "fakecaller.py"
css_file = caller_dir / "style.css"
js_file = caller_dir / "main.js"
_mk_file(cal... | 1 | test | streamlit/streamlit:lib/tests/streamlit/components/v2/test_component_registry.py:test_asset_url_overrides_and_defaults |
word = OcrElement(
ocr_class=OcrClass.WORD,
text="Caption",
bbox=BoundingBox(left=100, top=300, right=200, bottom=350),
)
caption = OcrElement(
ocr_class=OcrClass.CAPTION,
bbox=BoundingBox(left=100, top=300, right=900, bottom=350),
... | 1 | test | ocrmypdf/OCRmyPDF:tests/test_pdf_renderer.py:TestFpdf2PdfRendererLineTypes.test_caption_line |
= BrowserProfile(**profile_data)
# Create browser session
self.browser_session = BrowserSession(browser_profile=profile)
await self.browser_session.start()
# Track the session for management
self._track_session(self.browser_session)
# Create tools for direct actions
self.tools = Tools()
# Initializ... | 0 | function_simple | browser-use/browser-use:browser_use/mcp/server.py:BrowserUseServer._init_browser_session |
PC handler for adding events to the event aggregator. Receives events from the
request and adds them to the event buffer.
"""
if not self._event_processing_enabled:
return events_event_aggregator_service_pb2.AddEventsReply()
received_count = len(request.events_data.events)
... | 0 | function_complex | ray-project/ray:python/ray/dashboard/modules/aggregator/aggregator_agent.py:AggregatorAgent.AddEvents |
_auth_manager
body = types.SimpleNamespace(
name="editor",
permissions=[
types.SimpleNamespace(
action=types.SimpleNamespace(name="can_edit"),
resource=types.SimpleNamespace(name="DAG"),
)
],
)
... | 1 | test | apache/airflow:providers/fab/tests/unit/fab/auth_manager/api_fastapi/services/test_roles.py:TestRolesService.test_patch_role_rename_success |
: if any branch consumes, the whole does
elif ttype == sre_parse.BRANCH:
_, branches = tval
if any(subpattern_consumes(br) for br in branches):
return True
# grouped subpattern: recurse into its contents
elif ttype == sre_parse.SUBP... | 1 | function_complex | vllm-project/vllm:vllm/v1/structured_output/backend_outlines.py:_prefix_needs_context |
"
yield "data:" + json.dumps({"event": "node_finished", "data": {"component_id": "c1"}})
yield "data:" + json.dumps({"event": "other", "data": {}})
yield "data:" + json.dumps({"event": "message", "data": {"content": "hello"}})
monkeypatch.setattr(module, "agent_completion", _agent_stream)
... | 1 | test | infiniflow/ragflow:test/testcases/test_http_api/test_session_management/test_session_sdk_routes_unit.py:test_agent_completions_stream_and_nonstream_unit |
# To be filled by cloud handler
browser_session_cdp_url='', # To be filled by cloud handler
browser_state={
'viewport': agent.browser_profile.viewport if agent.browser_profile else {'width': 1280, 'height': 720},
'user_agent': agent.browser_profile.user_agent if agent.browser_profile else None,
'he... | 0 | function_simple | browser-use/browser-use:browser_use/agent/cloud_events.py:CreateAgentSessionEvent.from_agent |
, Image.Image, str, ImageBlock],
**kwargs: Any,
) -> List[NodeWithScore]:
"""
Query a multimodal table.
Args:
query (Union[ImageDocument, Image.Image, str, ImageBlock]): An ImageDocument or an ImageBlock, a PIL Image or a string representing an image URL.
"""
if isinstance(query, (Imag... | 1 | function_simple | run-llama/llama_index:llama-index-integrations/indices/llama-index-indices-managed-lancedb/llama_index/indices/managed/lancedb/utils.py:query_multimodal |
start_regular_shared, dataset_format):
"""Test list.sort() sorts each list with custom options."""
data = [
{"items": [3, 1, 2]},
{"items": [None, 4, 2]},
]
ds = _create_dataset(data, dataset_format)
method = col("items").list.sort(order="descending", null... | 0 | test | ray-project/ray:python/ray/data/tests/expressions/test_namespace_list.py:TestListNamespace.test_list_sort |
self._create_file(temp_directory, "test.txt", "Sample")
loader = DirectoryLoader()
result = loader.load(SourceContent(temp_directory))
metadata = result.metadata
expected_keys = {
"format",
"directory_path",
"total_files",
"processed_fil... | 0 | test | crewAIInc/crewAI:lib/crewai-tools/tests/rag/test_directory_loader.py:TestDirectoryLoader.test_metadata_structure |
use encoder_decoder for sequence classification. When set to False, only encoder is used.
"""
if is_encoder_decoder is not None:
config.is_encoder_decoder = is_encoder_decoder
super().__init__(config)
self.num_labels = config.num_labels
if config.is_encoder_decoder:... | 0 | function_simple | huggingface/transformers:src/transformers/models/t5gemma/modular_t5gemma.py:T5GemmaForSequenceClassification.__init__ |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 12