input string | label int64 | sample_id string | category string | repo_id string |
|---|---|---|---|---|
import math
from dataclasses import dataclass
from typing import Any
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
from transformers import AutoConfig
from transformers.activations import ACT2FN
from transformers.cache_utils import (
Cache,
DynamicCach... | 1 | huggingface/lerobot:src/lerobot/policies/wall_x/qwen_model/qwen2_5_vl_moe.py | function_complex | huggingface/lerobot |
"""Anthropic content block formatter."""
from __future__ import annotations
import base64
from typing import Any
from crewai_files.core.resolved import (
FileReference,
InlineBase64,
InlineBytes,
ResolvedFileType,
UrlReference,
)
from crewai_files.core.types import FileInput
class AnthropicForm... | 1 | crewAIInc/crewAI:lib/crewai-files/src/crewai_files/formatting/anthropic.py | function_simple | crewAIInc/crewAI |
from __future__ import annotations
from typing_extensions import TypeVar
from langgraph._internal._typing import StateLike
__all__ = (
"StateT",
"StateT_co",
"StateT_contra",
"InputT",
"OutputT",
"ContextT",
)
StateT = TypeVar("StateT", bound=StateLike)
"""Type variable used to represent the... | 1 | langchain-ai/langgraph:libs/langgraph/langgraph/typing.py | function_simple | langchain-ai/langgraph |
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from __future__ import annotations
from typing import Any, List, Iterable, cast
from typing_extensions import Literal
import httpx
from ... import _legacy_response
from ..._types import Body, Omit, Query, Headers, NotGiven, omit, ... | 1 | openai/openai-python:src/openai/resources/conversations/items.py | function_complex | openai/openai-python |
# coding=utf-8
from typing import Dict
from django.utils.translation import gettext_lazy as _, gettext
from common import forms
from common.exception.app_exception import AppApiException
from common.forms import BaseForm, TooltipLabel
from models_provider.base_model_provider import BaseModelCredential, ValidCode
from... | 1 | 1Panel-dev/MaxKB:apps/models_provider/impl/regolo_model_provider/credential/tti.py | function_simple | 1Panel-dev/MaxKB |
# /// script
# dependencies = ["anthropic", "fastmcp", "rich"]
# ///
"""
Simple Text Sampling
Demonstrates the basic MCP sampling flow where a server tool requests
an LLM completion from the client.
Run:
uv run examples/sampling/text.py
"""
import asyncio
from rich.console import Console
from rich.panel import ... | 1 | PrefectHQ/fastmcp:examples/sampling/text.py | function_simple | PrefectHQ/fastmcp |
#!/usr/bin/env python
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | 0 | huggingface/lerobot:src/lerobot/configs/default.py | unknown | huggingface/lerobot |
"""
Configuration objects for language servers
"""
import fnmatch
from collections.abc import Iterable
from dataclasses import dataclass, field
from enum import Enum
from typing import TYPE_CHECKING, Self
if TYPE_CHECKING:
from solidlsp import SolidLanguageServer
class FilenameMatcher:
def __init__(self, *p... | 0 | oraios/serena:src/solidlsp/ls_config.py | unknown | oraios/serena |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload
from datetime import date, datetime
from typing_extensions import Self, Literal, TypedDict
import pydantic
from pydantic.fields import FieldInfo
from ._types import IncEx, StrBytesIntFloat
_T ... | 0 | openai/openai-python:src/openai/_compat.py | unknown | openai/openai-python |
from typing import Callable, TypedDict, Optional, List, Tuple
ProgressCallback = Optional[Callable[[float], None]]
try:
from typing import NotRequired
except ImportError:
from typing_extensions import NotRequired
class SingleWordSegment(TypedDict):
"""
A single word of a speech.
"""
word: st... | 0 | m-bain/whisperX:whisperx/schema.py | unknown | m-bain/whisperX |
import os
import shutil
from pathlib import Path
import pytest
from pipenv.project import Project
from pipenv.utils.pylock import PylockFile, find_pylock_file
@pytest.fixture
def pylock_project(tmp_path):
"""Create a temporary project with a pylock.toml file."""
# Copy the example pylock.toml to the tempora... | 1 | pypa/pipenv:tests/integration/test_pylock.py | test | pypa/pipenv |
from dataclasses import dataclass
from aider.dump import dump # noqa: F401
@dataclass
class ExInfo:
name: str
retry: bool
description: str
EXCEPTIONS = [
ExInfo("APIConnectionError", True, None),
ExInfo("APIError", True, None),
ExInfo("APIResponseValidationError", True, None),
ExInfo(
... | 0 | Aider-AI/aider:aider/exceptions.py | unknown | Aider-AI/aider |
#!/usr/bin/env python3
"""
Skill Packager - Creates a distributable .skill file of a skill folder
Usage:
python package_skill.py <path/to/skill-folder> [output-directory]
Example:
python package_skill.py skills/public/my-skill
python package_skill.py skills/public/my-skill ./dist
"""
import sys
import zi... | 0 | HKUDS/nanobot:nanobot/skills/skill-creator/scripts/package_skill.py | unknown | HKUDS/nanobot |
"""This module provides utilities for managing Reflex app templates."""
import dataclasses
import shutil
import tempfile
import zipfile
from pathlib import Path
from urllib.parse import urlparse
from reflex import constants
from reflex.config import get_config
from reflex.utils import console, net, path_ops, redir
... | 1 | reflex-dev/reflex:reflex/utils/templates.py | function_complex | reflex-dev/reflex |
# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | 0 | verl-project/verl:tests/utils/test_fsdp2_peft_wrapping.py | unknown | verl-project/verl |
# Copyright 2026 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | 1 | verl-project/verl:tests/utils/test_torch_profile.py | test | verl-project/verl |
import os
import re
from collections import defaultdict
from typing import List, Pattern
import utils.constants as constants
from utils.tools import get_real_path, resource_path
from utils.types import WhitelistMaps
def load_whitelist_maps(path: str = constants.whitelist_path) -> WhitelistMaps:
"""
Load whit... | 1 | Guovin/iptv-api:utils/whitelist.py | function_complex | Guovin/iptv-api |
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | 0 | streamlit/streamlit:e2e_playwright/st_popover_test.py | unknown | streamlit/streamlit |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | 1 | apache/airflow:providers/apache/livy/src/airflow/providers/apache/livy/version_compat.py | function_simple | apache/airflow |
import os
import tempfile
import warnings
from typing import Any
from unittest.mock import patch
import pytest
import torch
from torch_geometric import is_in_onnx_export, safe_onnx_export
# Global mock to prevent ANY real ONNX calls in tests
# This ensures no deprecation warnings or real ONNX issues
pytestmark = pyt... | 1 | pyg-team/pytorch_geometric:test/test_onnx.py | test | pyg-team/pytorch_geometric |
"""Picture description stage using the VLM engine system.
This module provides an engine-agnostic picture description stage that can use
any VLM engine (Transformers, MLX, API, etc.) through the unified engine interface.
"""
import logging
from collections.abc import Iterable
from pathlib import Path
from typing impo... | 1 | docling-project/docling:docling/models/stages/picture_description/picture_description_vlm_engine_model.py | function_complex | docling-project/docling |
"""
Agent Command Registrar for Spec Kit
Shared infrastructure for registering commands with AI agents.
Used by both the extension system and the preset system to write
command files into agent-specific directories in the correct format.
"""
from pathlib import Path
from typing import Dict, List, Any
import yaml
c... | 0 | github/spec-kit:src/specify_cli/agents.py | unknown | github/spec-kit |
from pydantic import BaseModel
class Example:
"""A flexible data container for DSPy examples and training data with named fields.
An `Example` is roughly one row from a HuggingFace dataset or pandas
`DataFrame`. It behaves a lot like a dictionary or dot-access record: you
can read fields with `exampl... | 0 | stanfordnlp/dspy:dspy/primitives/example.py | unknown | stanfordnlp/dspy |
import datetime
from collections.abc import Callable
from dataclasses import InitVar, dataclass, field
from decimal import Decimal
from enum import Enum
from functools import cached_property
from typing import TYPE_CHECKING, Any, Optional, Union
from ..order import FulfillmentLineData
from ..order.fetch import OrderLi... | 0 | saleor/saleor:saleor/payment/interface.py | unknown | saleor/saleor |
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | 0 | streamlit/streamlit:e2e_playwright/st_time_input.py | unknown | streamlit/streamlit |
from __future__ import annotations
import logging
import sys
from unittest.mock import patch
from supervision.utils.logger import _get_logger
class TestGetLogger:
def test_default_name(self):
"""Logger is created with default name."""
logger = _get_logger()
assert logger.name == "supervi... | 1 | roboflow/supervision:tests/utils/test_logger.py | test | roboflow/supervision |
import importlib
import pytest
if importlib.util.find_spec("langchain_core") is None:
pytest.skip(reason="langchain_core is not installed", allow_module_level=True)
from pydantic import BaseModel
from dspy.utils.langchain_tool import convert_langchain_tool
@pytest.mark.asyncio
@pytest.mark.extra
async def tes... | 1 | stanfordnlp/dspy:tests/utils/test_langchain_tool.py | test | stanfordnlp/dspy |
import time
from utils_tests.test_csp import basic_config, basic_policy
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test import SimpleTestCase
from django.test.selenium import SeleniumTestCase
from django.test.utils import modify_settings, override_settings
from django.utils.cs... | 1 | django/django:tests/middleware/test_csp.py | test | django/django |
"""Sparse accessor"""
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy as np
from pandas.compat._optional import import_optional_dependency
from pandas.core.dtypes.cast import find_common_type
from pandas.core.dtypes.dtypes import SparseDtype
from pandas.core.accessor import (
... | 0 | pandas-dev/pandas:pandas/core/arrays/sparse/accessor.py | unknown | pandas-dev/pandas |
from dataclasses import dataclass
@dataclass
class ProjectInfo:
"""Dataclass for storing project information."""
title: str
author: str
url: str
description: str
repo_url_part: str
PROJECTS = [
ProjectInfo(
"Posting",
"Darren Burns",
"https://posting.sh/",
... | 1 | Textualize/textual:src/textual/demo/_project_data.py | function_complex | Textualize/textual |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import frappe
from frappe import _
from frappe.utils import add_to_date, formatdate, get_link_to_form, getdate, nowdate
from frappe.utils.dashboard import cache_source
from frappe.utils.dateu... | 0 | frappe/erpnext:erpnext/accounts/dashboard_chart_source/account_balance_timeline/account_balance_timeline.py | unknown | frappe/erpnext |
"""
Project Euler Problem 345: https://projecteuler.net/problem=345
Matrix Sum
We define the Matrix Sum of a matrix as the maximum possible sum of
matrix elements such that none of the selected elements share the same row or column.
For example, the Matrix Sum of the matrix below equals
3315 ( = 863 + 383 + 343 + 95... | 1 | TheAlgorithms/Python:project_euler/problem_345/sol1.py | documentation | TheAlgorithms/Python |
import asyncio
import json
from pathlib import Path
from typing import IO, Any, List, Optional, Union
from uuid import uuid4
from agno.knowledge.chunking.fixed import FixedSizeChunking
from agno.knowledge.chunking.strategy import ChunkingStrategy, ChunkingStrategyType
from agno.knowledge.document.base import Document
... | 1 | agno-agi/agno:libs/agno/agno/knowledge/reader/json_reader.py | function_complex | agno-agi/agno |
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | 0 | streamlit/streamlit:lib/streamlit/elements/balloons.py | unknown | streamlit/streamlit |
import logging
from redash.query_runner import (
TYPE_BOOLEAN,
TYPE_DATE,
TYPE_DATETIME,
TYPE_FLOAT,
TYPE_INTEGER,
TYPE_STRING,
BaseSQLQueryRunner,
InterruptException,
register,
)
logger = logging.getLogger(__name__)
try:
import duckdb
enabled = True
except ImportError:
... | 1 | getredash/redash:redash/query_runner/duckdb.py | function_complex | getredash/redash |
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao.
import math
import itertools
import os
import random
import pytest
import torch
from einops import rearrange, repeat
try:
from flash_attn.layers.rotary import apply_rotary_emb
except ImportError:
apply_rota... | 1 | Dao-AILab/flash-attention:tests/cute/test_flash_attn.py | test | Dao-AILab/flash-attention |
#!/usr/bin/env python3
"""
Generate Kaplan-Meier Survival Curves for Clinical Decision Support Documents
This script creates publication-quality survival curves with:
- Kaplan-Meier survival estimates
- 95% confidence intervals
- Log-rank test statistics
- Hazard ratios with confidence intervals
- Number at risk table... | 1 | davila7/claude-code-templates:cli-tool/components/skills/scientific/clinical-decision-support/scripts/generate_survival_analysis.py | function_complex | davila7/claude-code-templates |
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | 1 | streamlit/streamlit:lib/streamlit/runtime/theme_util.py | license | streamlit/streamlit |
"""Mock implementation of redis for unit testing."""
import asyncio
import contextlib
import fnmatch
import time
from collections.abc import AsyncGenerator, Callable
from typing import Any
from unittest.mock import AsyncMock, Mock
from redis.asyncio import Redis
from redis.typing import EncodableT, KeyT
from reflex.... | 1 | reflex-dev/reflex:tests/units/mock_redis.py | test | reflex-dev/reflex |
import asyncio
import logging
from typing import Any, List, Optional, Type
from llama_index.core.base.base_query_engine import BaseQueryEngine
from llama_index.core.base.llms.types import ChatMessage, MessageRole
from llama_index.core.base.response.schema import (
RESPONSE_TYPE,
StreamingResponse,
AsyncStr... | 0 | run-llama/llama_index:llama-index-core/llama_index/core/chat_engine/condense_question.py | unknown | run-llama/llama_index |
#!/usr/bin/env python3
import json
import os
import re
import sys
_ = r"""
reject file upload (with a nice explanation why)
example usage as global config:
--xbu j,c1,bin/hooks/reject-and-explain.py
example usage as a volflag (per-volume config):
-v srv/inc:inc:r:rw,ed:c,xbu=j,c1,bin/hooks/reject-and-expla... | 1 | 9001/copyparty:bin/hooks/reject-and-explain.py | documentation | 9001/copyparty |
import numpy as np
import pytest
from numpy.testing import assert_allclose
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.manifold import ClassicalMDS
from sklearn.metrics import euclidean_distances
def test_classical_mds_equivalent_to_pca():
X, _ = load_iris(return_X_y... | 1 | scikit-learn/scikit-learn:sklearn/manifold/tests/test_classical_mds.py | test | scikit-learn/scikit-learn |
import pickle
import time
import logging
import pytest
from cssselect import SelectorError, SelectorSyntaxError
from scrapling import Selector
logging.getLogger("scrapling").setLevel(logging.DEBUG)
@pytest.fixture
def html_content():
return """
<html>
<head>
<title>Complex Web Page</title>
... | 0 | D4Vinci/Scrapling:tests/parser/test_general.py | unknown | D4Vinci/Scrapling |
from __future__ import annotations
import uuid
from ast import literal_eval
from datetime import timedelta
from enum import Enum
from typing import TYPE_CHECKING, Annotated, Any
from fastapi import Depends, HTTPException, Path, Query
from fastapi_pagination import Params
from lfx.graph.graph.base import Graph
from lf... | 0 | langflow-ai/langflow:src/backend/base/langflow/api/utils/core.py | unknown | langflow-ai/langflow |
""" Attention Pool 2D
Implementations of 2D spatial feature pooling using multi-head attention instead of average pool.
Based on idea in CLIP by OpenAI, licensed Apache 2.0
https://github.com/openai/CLIP/blob/3b473b0e682c091a9e53623eebc1ca1657385717/clip/model.py
Hacked together by / Copyright 2021 Ross Wightman
"""... | 0 | huggingface/pytorch-image-models:timm/layers/attention_pool2d.py | unknown | huggingface/pytorch-image-models |
from typing import Any
from pydantic import BaseModel
from crewai_tools.tools.brave_search_tool.base import BraveSearchToolBase
from crewai_tools.tools.brave_search_tool.schemas import (
NewsSearchHeaders,
NewsSearchParams,
)
class BraveNewsSearchTool(BraveSearchToolBase):
"""A tool that performs news s... | 0 | crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/brave_search_tool/brave_news_tool.py | unknown | crewAIInc/crewAI |
from typing import final
import mlx.core as mx
from mflux.models.qwen.model.qwen_transformer.qwen_attention import QwenAttention
from mflux.models.qwen.model.qwen_transformer.qwen_transformer_block import (
QwenTransformerBlock,
)
from pydantic import BaseModel, ConfigDict
from exo.worker.engines.image.models.bas... | 1 | exo-explore/exo:src/exo/worker/engines/image/models/qwen/wrappers.py | function_simple | exo-explore/exo |
from changedetectionio import queuedWatchMetaData
from changedetectionio import worker_pool
from flask_restful import abort, Resource
from loguru import logger
import threading
from flask import request
from . import auth
from . import validate_openapi_request
class Tag(Resource):
def __init__(self, **kwargs):
... | 0 | dgtlmoon/changedetection.io:changedetectionio/api/Tags.py | unknown | dgtlmoon/changedetection.io |
shell_cmd_prompt = """
4. *Concisely* suggest any shell commands the user might want to run in ```bash blocks.
Just suggest shell commands this way, not example code.
Only suggest complete shell commands that are ready to execute, without placeholders.
Only suggest at most a few shell commands at a time, not more than... | 1 | Aider-AI/aider:aider/coders/shell.py | documentation | Aider-AI/aider |
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import importlib.util
import json
import logging
import pytest
import pytest_asyncio
from openai import OpenAI
from tests.utils import RemoteOpenAIServer
from .conftest import (
BASE_TEST_ENV,
has_outp... | 0 | vllm-project/vllm:tests/entrypoints/openai/responses/test_parsable_context.py | unknown | vllm-project/vllm |
# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | 1 | verl-project/verl:tests/single_controller/test_get_set_dispatch_collect_cpu.py | test | verl-project/verl |
import os
ZULIP_VERSION = "12.0-beta1+git"
# Add information on number of commits and commit hash to version, if available
ZULIP_VERSION_WITHOUT_COMMIT = ZULIP_VERSION
zulip_git_version_file = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "zulip-git-version"
)
lines = [ZULIP_VERSION, ""]
if os.path.ex... | 0 | zulip/zulip:version.py | unknown | zulip/zulip |
"""
Bidirectional Search Algorithm.
This algorithm searches from both the source and target nodes simultaneously,
meeting somewhere in the middle. This approach can significantly reduce the
search space compared to a traditional one-directional search.
Time Complexity: O(b^(d/2)) where b is the branching factor and d... | 1 | TheAlgorithms/Python:graphs/bidirectional_search.py | function_complex | TheAlgorithms/Python |
# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 1 | PaddlePaddle/PaddleOCR:paddleocr/_pipelines/pp_chatocrv4_doc.py | license | PaddlePaddle/PaddleOCR |
"""Feishu/Lark channel implementation using lark-oapi SDK with WebSocket long connection."""
import asyncio
import json
import os
import re
import threading
from collections import OrderedDict
from pathlib import Path
from typing import Any
from loguru import logger
from nanobot.bus.events import OutboundMessage
fro... | 1 | HKUDS/nanobot:nanobot/channels/feishu.py | function_complex | HKUDS/nanobot |
from dataclasses import dataclass
from datetime import datetime
from typing import Any, NamedTuple
from app.assets.database.models import Asset, AssetReference
UserMetadata = dict[str, Any] | None
@dataclass(frozen=True)
class AssetData:
hash: str | None
size_bytes: int | None
mime_type: str | None
@d... | 0 | Comfy-Org/ComfyUI:app/assets/services/schemas.py | unknown | Comfy-Org/ComfyUI |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import copy
import torch
import warnings
import numpy as np
import pandas as pd
from qlib.utils.data import guess_horizon
from qlib.utils import init_instance_by_config
from qlib.data.dataset import DatasetH
device = "cuda" if torch.cuda.is_ava... | 0 | microsoft/qlib:qlib/contrib/data/dataset.py | unknown | microsoft/qlib |
"""
OpenRouter model metadata caching and lookup.
This module keeps a local cached copy of the OpenRouter model list
(downloaded from ``https://openrouter.ai/api/v1/models``) and exposes a
helper class that returns metadata for a given model in a format compatible
with litellm’s ``get_model_info``.
"""
from __future__... | 1 | Aider-AI/aider:aider/openrouter.py | function_complex | Aider-AI/aider |
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
import math
from pydantic import field_validator
from deepspeed.runtime.config_utils import DeepSpeedConfigModel
from .fp16.loss_scaler import (
INITIAL_LOSS_SCALE,
SCALE_WINDOW,
DELAYED_SHIFT,
CONSECUTIVE_HY... | 0 | deepspeedai/DeepSpeed:deepspeed/runtime/precision_config.py | unknown | deepspeedai/DeepSpeed |
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
import urllib.error
import urllib.request
from typing import Optional
from marimo import _loggers
from marimo._save.stores.store import Store
from marimo._version import __version__
LOGGER = _loggers.marimo_logger()
class RestStore(St... | 1 | marimo-team/marimo:marimo/_save/stores/rest.py | function_complex | marimo-team/marimo |
"""Matrix Exponentiation"""
import timeit
"""
Matrix Exponentiation is a technique to solve linear recurrences in logarithmic time.
You read more about it here:
https://zobayer.blogspot.com/2010/11/matrix-exponentiation.html
https://www.hackerearth.com/practice/notes/matrix-exponentiation-1/
"""
class Matrix:
d... | 0 | TheAlgorithms/Python:maths/matrix_exponentiation.py | unknown | TheAlgorithms/Python |
"""
Memory service for handling memory query operations via cloud protocol.
Provides a unified interface for listing and reading memory files,
callable from the cloud client (LinkAI) or a future web console.
Memory file layout (under workspace_root):
MEMORY.md -> type: global
memory/2026-02-20.m... | 1 | zhayujie/chatgpt-on-wechat:agent/memory/service.py | function_complex | zhayujie/chatgpt-on-wechat |
r"""Mobjects representing matrices.
Examples
--------
.. manim:: MatrixExamples
:save_last_frame:
class MatrixExamples(Scene):
def construct(self):
m0 = Matrix([["\\pi", 0], [-1, 1]])
m1 = IntegerMatrix([[1.5, 0.], [12, -1.3]],
left_bracket="(",
... | 0 | ManimCommunity/manim:manim/mobject/matrix.py | unknown | ManimCommunity/manim |
"""Ministral3 templates"""
from mlc_llm.protocol.conversation_protocol import Conversation, MessagePlaceholders
from .registry import ConvTemplateRegistry
# Ministral3
ConvTemplateRegistry.register_conv_template(
Conversation(
name="ministral3",
system_template=(
f"[SYSTEM_PROMPT]{Mes... | 1 | mlc-ai/mlc-llm:python/mlc_llm/conversation_template/ministral3.py | function_simple | mlc-ai/mlc-llm |
from argparse import ArgumentParser
from http import HTTPStatus
from typing import Annotated, Any
import ormsgpack
from baize.datastructures import ContentType
from kui.asgi import (
HTTPException,
HttpRequest,
JSONResponse,
request,
)
from loguru import logger
from pydantic import BaseModel
from fish... | 0 | fishaudio/fish-speech:tools/server/api_utils.py | unknown | fishaudio/fish-speech |
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) ONNX Project Contributors
from __future__ import annotations
import unittest
import parameterized
import onnx.helper
import onnx.shape_inference
class NodeInferenceTest(unittest.TestCase):
@parameterized.parameterized.expand(
[
("Greate... | 1 | onnx/onnx:onnx/test/node_shape_inference_test.py | test | onnx/onnx |
import os
import time
import pytest
import numpy as np
from cereal.services import SERVICE_LIST
from openpilot.tools.lib.log_time_series import msgs_to_time_series
from openpilot.system.camerad.snapshot import get_snapshots
from openpilot.selfdrive.test.helpers import collect_logs, log_collector, processes_context
TE... | 0 | commaai/openpilot:system/camerad/test/test_camerad.py | unknown | commaai/openpilot |
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from typing import List, Union, Optional
from typing_extensions import Literal, Annotated, TypeAlias
from ..._utils import PropertyInfo
from ..._models import BaseModel
from .custom_tool import CustomTool
__all__ = ["NamespaceTool"... | 0 | openai/openai-python:src/openai/types/responses/namespace_tool.py | unknown | openai/openai-python |
# Copyright 2026 The JAX Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | 0 | jax-ml/jax:jax/_src/numpy/hijax.py | unknown | jax-ml/jax |
#!/usr/bin/env python3
"""
Quick exploration of Neuropixels recording.
Usage:
python explore_recording.py /path/to/spikeglx/data
"""
import argparse
import spikeinterface.full as si
import matplotlib.pyplot as plt
import numpy as np
def explore_recording(data_path: str, stream_id: str = 'imec0.ap'):
"""Expl... | 1 | davila7/claude-code-templates:cli-tool/components/skills/scientific/neuropixels-analysis/scripts/explore_recording.py | function_complex | davila7/claude-code-templates |
"""
Classical multi-dimensional scaling (classical MDS).
"""
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
from numbers import Integral
import numpy as np
from scipy import linalg
from sklearn.base import BaseEstimator, _fit_context
from sklearn.metrics import pairwise_distances
fro... | 1 | scikit-learn/scikit-learn:sklearn/manifold/_classical_mds.py | license | scikit-learn/scikit-learn |
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
import numpy
import torch
from dataclasses import dataclass
@dataclass
class serialize_details:
obj: object
dtype: torch.dtype
size: int
nbytes: int
def tensor_to_bytes(tensor):
return tensor.numpy().... | 1 | deepspeedai/DeepSpeed:deepspeed/io/utils.py | license | deepspeedai/DeepSpeed |
import pytest
from agno.agent import Agent, RunOutput
from agno.db.sqlite import SqliteDb
from agno.models.vercel import V0
def _assert_metrics(response: RunOutput):
assert response.metrics is not None
input_tokens = response.metrics.input_tokens
output_tokens = response.metrics.output_tokens
total_t... | 1 | agno-agi/agno:libs/agno/tests/integration/models/vercel/test_basic.py | test | agno-agi/agno |
# Copyright 2026 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | 0 | verl-project/verl:tests/workers/rollout/rollout_trtllm/test_trtllm_rollout_utils.py | unknown | verl-project/verl |
"""
Hosoya Triangle
The Hosoya triangle (originally Fibonacci triangle) is a triangular arrangement
of numbers where each entry is the sum of two entries above it.
Reference: https://en.wikipedia.org/wiki/Hosoya%27s_triangle
Complexity:
Time: O(n^3) (naive recursive per entry)
Space: O(n) (call stack de... | 1 | keon/algorithms:algorithms/dynamic_programming/hosoya_triangle.py | documentation | keon/algorithms |
# Copyright 2025 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | 0 | huggingface/diffusers:src/diffusers/modular_pipelines/helios/modular_pipeline.py | unknown | huggingface/diffusers |
"""Experimental client-side task support.
This module provides client methods for interacting with MCP tasks.
WARNING: These APIs are experimental and may change without notice.
Example:
```python
# Call a tool as a task
result = await session.experimental.call_tool_as_task("tool_name", {"arg": "value"})... | 1 | modelcontextprotocol/python-sdk:src/mcp/client/experimental/tasks.py | documentation | modelcontextprotocol/python-sdk |
from typing import Any
import pydantic
class History(pydantic.BaseModel):
"""Class representing the conversation history.
The conversation history is a list of messages, each message entity should have keys from the associated signature.
For example, if you have the following signature:
```
cla... | 0 | stanfordnlp/dspy:dspy/adapters/types/history.py | unknown | stanfordnlp/dspy |
"""Ministral3 reasoning templates"""
from mlc_llm.protocol.conversation_protocol import Conversation, MessagePlaceholders
from .registry import ConvTemplateRegistry
# Ministral-3-XB-Reasoning-2512
ConvTemplateRegistry.register_conv_template(
Conversation(
name="ministral3_reasoning",
system_templ... | 1 | mlc-ai/mlc-llm:python/mlc_llm/conversation_template/ministral3_reasoning.py | function_simple | mlc-ai/mlc-llm |
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from __future__ import annotations
from typing import Union
from typing_extensions import Literal, Required, TypeAlias, TypedDict
from .speech_model import SpeechModel
__all__ = ["SpeechCreateParams", "Voice", "VoiceID"]
class S... | 0 | openai/openai-python:src/openai/types/audio/speech_create_params.py | unknown | openai/openai-python |
import json
from types import SimpleNamespace
from typer.testing import CliRunner
from nanobot.cli.commands import app
from nanobot.config.loader import load_config, save_config
runner = CliRunner()
def test_load_config_keeps_max_tokens_and_warns_on_legacy_memory_window(tmp_path) -> None:
config_path = tmp_pat... | 0 | HKUDS/nanobot:tests/test_config_migration.py | unknown | HKUDS/nanobot |
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | 1 | streamlit/streamlit:lib/streamlit/components/v2/manifest_scanner.py | license | streamlit/streamlit |
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
from .constants import *
BASE_STAT_KEYS = [
CLOSE_COUNT_KEY, FILENO_COUNT_KEY, FLUSH_COUNT_KEY, WRITE_COUNT_KEY, WRITE_BYTES_KEY, WRITE_SEC_KEY,
WRITE_SPEED_KEY
]
class BaseFileWriter(object):
def __init__(se... | 1 | deepspeedai/DeepSpeed:deepspeed/io/base_file_writer.py | license | deepspeedai/DeepSpeed |
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
import itertools
from sklearn import __version__
from sklearn._config import get_config
from sklearn.utils.fixes import parse_version
class _HTMLDocumentationLinkMixin:
"""Mixin class allowing to generate a link to the API documentat... | 1 | scikit-learn/scikit-learn:sklearn/utils/_repr_html/base.py | license | scikit-learn/scikit-learn |
# Copyright 2025 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | 1 | huggingface/transformers:tests/models/efficientloftr/test_image_processing_efficientloftr.py | test | huggingface/transformers |
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
import sys
from marimo._messaging.context import is_code_mode_request
from marimo._messaging.types import Stderr
def _highlight_traceback(traceback: str) -> str:
"""
Highlight the traceback with color.
"""
from pygment... | 0 | marimo-team/marimo:marimo/_messaging/tracebacks.py | unknown | marimo-team/marimo |
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from __future__ import annotations
import httpx
from ... import _legacy_response
from ..._types import Body, Omit, Query, Headers, NotGiven, omit, not_given
from ..._utils import maybe_transform, async_maybe_transform
from ..._comp... | 1 | openai/openai-python:src/openai/resources/realtime/client_secrets.py | function_complex | openai/openai-python |
# Copyright 2025-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | 1 | huggingface/peft:examples/miss_finetuning/miss_finetuning.py | license | huggingface/peft |
"""Test the elicitation feature using stdio transport."""
from typing import Any
import pytest
from pydantic import BaseModel, Field
from mcp import Client, types
from mcp.client.session import ClientSession, ElicitationFnT
from mcp.server.mcpserver import Context, MCPServer
from mcp.shared._context import RequestCo... | 0 | modelcontextprotocol/python-sdk:tests/server/mcpserver/test_elicitation.py | unknown | modelcontextprotocol/python-sdk |
"""
Unit tests for datetime serialization in database utilities.
These tests verify the fix for GitHub issue #6327:
TypeError: Object of type datetime is not JSON serializable when saving agent sessions.
"""
import json
from datetime import date, datetime, timezone
from uuid import uuid4
from agno.db.utils import Cu... | 1 | agno-agi/agno:libs/agno/tests/unit/db/test_datetime_serialization.py | test | agno-agi/agno |
# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 1 | PaddlePaddle/PaddleOCR:paddleocr/_cli.py | license | PaddlePaddle/PaddleOCR |
# Copyright (c) 2025, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class FinancialReportRow(Document):
# begin: auto-generated types
# This code is auto-generated. Do not modify anything in this block.
... | 1 | frappe/erpnext:erpnext/accounts/doctype/financial_report_row/financial_report_row.py | license | frappe/erpnext |
from collections import defaultdict, namedtuple
from django.contrib.gis import forms, gdal
from django.contrib.gis.db.models.proxy import SpatialProxy
from django.contrib.gis.gdal.error import GDALException
from django.contrib.gis.geos import (
GeometryCollection,
GEOSException,
GEOSGeometry,
LineStrin... | 0 | django/django:django/contrib/gis/db/models/fields.py | unknown | django/django |
# Copyright 2025 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | 0 | verl-project/verl:tests/utils/test_prepare_micro_batches_with_group_size.py | unknown | verl-project/verl |
"""Unit tests for langflow.core.celeryconfig module."""
# Import the module to test
from langflow.core import celeryconfig
class TestCeleryConfigAcceptContent:
"""Unit tests for accept_content configuration."""
def test_accept_content_configuration(self):
"""Test that accept_content is set to the ex... | 1 | langflow-ai/langflow:src/backend/tests/unit/core/test_celeryconfig.py | test | langflow-ai/langflow |
#!/usr/bin/env python3
import ctypes, pathlib, argparse, pickle, dataclasses, threading
from typing import Generator
from tinygrad.helpers import temp, unwrap, DEBUG
from tinygrad.runtime.ops_amd import ProfileSQTTEvent
from tinygrad.runtime.autogen import rocprof
from tinygrad.renderer.amd.dsl import Inst
from test.am... | 1 | tinygrad/tinygrad:extra/sqtt/roc.py | function_complex | tinygrad/tinygrad |
import logging
from typing import TYPE_CHECKING, Any, get_origin
import json_repair
import litellm
from dspy.adapters.types import History, Type
from dspy.adapters.types.base_type import split_message_content_for_custom_types
from dspy.adapters.types.reasoning import Reasoning
from dspy.adapters.types.tool import Too... | 0 | stanfordnlp/dspy:dspy/adapters/base.py | unknown | stanfordnlp/dspy |
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao.
# SM120 (Blackwell GeForce / DGX Spark) backward pass.
#
# SM120 uses the same SM80-era MMA instructions (mma.sync.aligned.m16n8k16) but has
# a smaller shared memory capacity (99 KB vs 163 KB on SM80). This module sub... | 0 | Dao-AILab/flash-attention:flash_attn/cute/flash_bwd_sm120.py | unknown | Dao-AILab/flash-attention |
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json
import openai # use the official client for correctness check
import pytest
MODEL_NAME = "Qwen/Qwen3-1.7B"
tools = [
{
"type": "function",
"name": "get_current_weather",
... | 0 | vllm-project/vllm:tests/entrypoints/openai/responses/test_function_call.py | unknown | vllm-project/vllm |
import io
import sys
from io import TextIOWrapper
import anyio
import pytest
from mcp.server.stdio import stdio_server
from mcp.shared.message import SessionMessage
from mcp.types import JSONRPCMessage, JSONRPCRequest, JSONRPCResponse, jsonrpc_message_adapter
@pytest.mark.anyio
async def test_stdio_server():
st... | 0 | modelcontextprotocol/python-sdk:tests/server/test_stdio.py | unknown | modelcontextprotocol/python-sdk |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.