repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
mlflow | mlflow/server/jobs/logging_utils.py | .py | """Shared logging utilities for MLflow job consumers."""
import logging
from mlflow.utils.logging_utils import get_mlflow_log_level
def configure_logging_for_jobs() -> None:
"""Configure Python logging for job consumers to reduce noise for log levels above DEBUG."""
# Suppress noisy alembic and huey INFO lo... | 14 | 560 |
onnx | onnx/reference/ops/op_bitshift.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import numpy as np
from onnx.reference.ops._op import OpRunBinaryNumpy
class BitShift(OpRunBinaryNumpy):
def __init__(self, onnx_node, run_params):
OpRunBinaryNumpy.__init__(self, np.right... | 18 | 569 |
wandb | wandb/sdk/internal/file_stream.py | .py | from __future__ import annotations
import functools
import itertools
import json
import logging
import os
import queue
import random
import sys
import threading
import time
from collections.abc import Callable
from types import TracebackType
from typing import TYPE_CHECKING, Any, NamedTuple
if TYPE_CHECKING:
from... | 678 | 25,529 |
wandb | wandb/proto/v5/wandb_internal_pb2.py | .py | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: wandb/proto/wandb_internal.proto
# Protobuf Python Version: 5.26.0
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from... | 382 | 59,110 |
biopython | Tests/test_BioSQL_MySQLdb_online.py | .py | # This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Run BioSQL tests using MySQL."""
import unittest
import requires_internet
# Really do want "import *" to get all the test clases:
from common_Bio... | 35 | 1,022 |
sphinx | sphinx/util/osutil.py | .py | """Operating system-related utility functions for Sphinx."""
from __future__ import annotations
import contextlib
import filecmp
import os
import os.path
import re
import shutil
import sys
import unicodedata
from io import StringIO
from pathlib import Path
from typing import TYPE_CHECKING
from sphinx.locale import _... | 268 | 8,210 |
mlflow | tests/server/auth/test_cli.py | .py | from click.testing import CliRunner
from mlflow.server.auth import cli
def test_cli():
runner = CliRunner()
res = runner.invoke(cli.commands, ["--help"], catch_exceptions=False)
assert res.exit_code == 0, res.output
| 10 | 231 |
beam | sdks/python/apache_beam/examples/snippets/transforms/elementwise/flatmap_test.py | .py | # coding=utf-8
#
# 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");... | 127 | 4,167 |
pyro | pyro/poutine/condition_messenger.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
from typing import TYPE_CHECKING, Dict, Union
import torch
from pyro.poutine.messenger import Messenger
from pyro.poutine.trace_struct import Trace
if TYPE_CHECKING:
from pyro.poutine.runtime import Message
class Condition... | 72 | 2,367 |
pyomo | examples/performance/misc/bilinear2_100.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 31 | 1,047 |
pyro | tests/infer/test_autoguide.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import functools
import io
import warnings
import numpy as np
import pytest
import torch
from torch import nn
from torch.distributions import constraints
import pyro
import pyro.distributions as dist
import pyro.poutine as poutin... | 1,620 | 51,698 |
textual | src/textual/worker.py | .py | """
This module contains the `Worker` class and related objects.
See the guide for how to use [workers](/guide/workers).
"""
from __future__ import annotations
import asyncio
import enum
import inspect
from contextvars import ContextVar
from threading import Event
from time import monotonic
from typing import (
... | 456 | 13,799 |
mlflow | tests/docker/conftest.py | .py | import subprocess
import pytest
@pytest.fixture(scope="package", autouse=True)
def build_mlflow_image():
subprocess.check_call([
"docker",
"build",
"-t",
"mlflow-integration-test",
"-f",
"docker/Dockerfile.full.dev",
".",
])
yield
# Clean up the... | 20 | 438 |
openvino | tests/layer_tests/tensorflow_tests/test_tf_ExtractImagePatches.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
import tensorflow as tf
from common.tf_layer_test_class import CommonTFLayerTest
class TestExtractImagePatches(CommonTFLayerTest):
def _prepare_input(self, inputs_info):
# generate elements ... | 44 | 2,031 |
mlflow | mlflow/data/http_dataset_source.py | .py | import os
import re
from typing import Any
from urllib.parse import urlparse
from mlflow.data.dataset_source import DatasetSource
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE
from mlflow.utils.file_utils import create_tmp_dir
from mlflow.utils.rest_util... | 146 | 4,599 |
biopython | Scripts/Restriction/rebase_update.py | .py | #!/usr/bin/env python
#
# Restriction Analysis Libraries.
# Copyright (C) 2004. Frederic Sohm.
#
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
#
"""Update the Rebase EMBOSS files and NCBI ... | 65 | 2,130 |
bazel | third_party/py/mock/tests/support.py | .py | import sys
info = sys.version_info
if info[:3] >= (3, 2, 0):
# for Python 3.2 ordinary unittest is fine
import unittest as unittest2
else:
import unittest2
try:
callable = callable
except NameError:
def callable(obj):
return hasattr(obj, '__call__')
inPy3k = sys.version_info[0] == 3
wit... | 42 | 702 |
saleor | saleor/graphql/invoice/mutations/invoice_delete.py | .py | import graphene
from ....invoice import events, models
from ....order.search import update_order_search_vector
from ....permission.enums import OrderPermissions
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
from ...core.mutations import ModelDeleteMutation
from ...core.types import Inv... | 37 | 1,293 |
pyomo | doc/OnlineDocs/tests/test_examples.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 74 | 2,958 |
hydra | examples/plugins/example_sweeper_plugin/tests/test_example_sweeper_plugin.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from pytest import mark
from hydra.core.plugins import Plugins
from hydra.plugins.sweeper import Sweeper
from hydra.test_utils.launcher_common_tests import (
BatchedSweeperTestSuite,
IntegrationTestSuite,
LauncherTestSuite,
)
from hydra... | 95 | 2,853 |
pyomo | pyomo/contrib/parmest/examples/semibatch/semibatch.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 333 | 9,863 |
astropy | astropy/table/meta.py | .py | import copy
import json
import textwrap
from collections import OrderedDict
import numpy as np
import yaml
__all__ = ["get_header_from_yaml", "get_yaml_from_header", "get_yaml_from_table"]
class ColumnOrderList(list):
"""
List of tuples that sorts in a specific order that makes sense for
astropy table c... | 422 | 13,553 |
textual | docs/examples/styles/content_align.py | .py | from textual.app import App
from textual.widgets import Label
class ContentAlignApp(App):
CSS_PATH = "content_align.tcss"
def compose(self):
yield Label("With [i]content-align[/] you can...", id="box1")
yield Label("...[b]Easily align content[/]...", id="box2")
yield Label("...Horizon... | 17 | 432 |
probability | tensorflow_probability/python/internal/parameter_properties.py | .py | # Copyright 2018 The TensorFlow Probability 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 407 | 20,756 |
textual | examples/five_by_five.py | .py | """Simple version of 5x5, developed for/with Textual."""
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING, cast
from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.containers import Horizontal
from textual.css.query import DOMQuery
f... | 324 | 10,056 |
saleor | saleor/core/tests/test_core.py | .py | from unittest.mock import Mock, patch
from urllib.parse import urljoin
import pytest
from django.core.management import CommandError, call_command
from django.db.utils import DataError
from django.templatetags.static import static
from django.test import RequestFactory, override_settings
from django.utils.crypto impor... | 468 | 14,173 |
textual | tests/snapshot_tests/snapshot_apps/keyline.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Static
from textual.containers import Horizontal, Vertical, Grid
class Box(Static):
pass
class KeylineApp(App):
CSS = """
Vertical {
keyline: thin red;
}
Horizontal {
keyline: heavy green;
}
Grid {
... | 53 | 980 |
wandb | tests/unit_tests/test_pydantic_helpers.py | .py | """Basic tests for W&B's Pydantic helper layer."""
from __future__ import annotations
import json
from typing import Any
from pydantic import ConfigDict, Field, Json, ValidationError
from pytest import raises
from wandb._pydantic import (
AliasChoices,
CompatBaseModel,
GQLInput,
GQLResult,
comput... | 411 | 12,230 |
openvino | src/bindings/python/tests/test_graph/test_utils.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
from openvino._pyopenvino.util import deprecation_warning
def test_deprecation_warning():
with pytest.warns(DeprecationWarning, match="function1 is deprecated"):
deprecation_warning("fu... | 21 | 947 |
flit | bootstrap_dev.py | .py | #!/usr/bin/env python3
# Symlink install flit & flit_core for development.
# Most projects can do the same with 'flit install --symlink'.
# But that doesn't work until Flit is installed, so we need some bootstrapping.
import argparse
import logging
import os
from pathlib import Path
import sys
my_dir = Path(__file__... | 41 | 1,044 |
saleor | saleor/webhook/tests/subscription_webhooks/payloads.py | .py | import json
import graphene
from django.utils import timezone
from .... import __version__
from ....core.utils import build_absolute_uri
from ....discount.models import Promotion
from ....graphql.attribute.enums import AttributeInputTypeEnum, AttributeTypeEnum
from ....graphql.discount.utils import get_categories_fro... | 716 | 22,056 |
pyomo | examples/pyomobook/overview-ch/wl_abstract_script.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 58 | 1,664 |
pyomo | pyomo/solvers/plugins/converter/ampl.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 86 | 3,333 |
gunicorn | tests/test_asgi_streaming.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
"""
ASGI streaming response tests.
Tests for chunked transfer encoding, Server-Sent Events (SSE),
and streaming response handling.
"""
from unittest import mock
import pytest
from gunicorn.config import Config
... | 582 | 19,742 |
textual | docs/examples/styles/background.py | .py | from textual.app import App
from textual.widgets import Label
class BackgroundApp(App):
CSS_PATH = "background.tcss"
def compose(self):
yield Label("Widget 1", id="static1")
yield Label("Widget 2", id="static2")
yield Label("Widget 3", id="static3")
if __name__ == "__main__":
ap... | 17 | 354 |
coremltools | deps/pybind11/tests/test_pytypes.py | .py | from __future__ import annotations
import contextlib
import sys
import types
import pytest
import env
from pybind11_tests import detailed_error_messages_enabled
from pybind11_tests import pytypes as m
def test_obj_class_name():
assert m.obj_class_name(None) == "NoneType"
assert m.obj_class_name(list) == "l... | 1,051 | 27,883 |
tqdm | tqdm/_tqdm_gui.py | .py | from warnings import warn
from .gui import * # NOQA
from .gui import __all__ # NOQA
from .std import TqdmDeprecationWarning
warn("This function will be removed in tqdm==5.0.0\n"
"Please use `tqdm.gui.*` instead of `tqdm._tqdm_gui.*`",
TqdmDeprecationWarning, stacklevel=2)
| 10 | 287 |
probability | tensorflow_probability/python/stats/calibration.py | .py | # Copyright 2019 The TensorFlow Probability 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 551 | 23,885 |
saleor | saleor/graphql/page/tests/queries/pages_with_where/test_with_where_slug.py | .py | import pytest
from .....tests.utils import get_graphql_content
from .shared import QUERY_PAGES_WITH_WHERE
@pytest.mark.parametrize(
("where", "pages_count"),
[
({"slug": {"eq": "test-url-1"}}, 1),
({"slug": {"oneOf": ["test-url-1", "test-url-2"]}}, 2),
],
)
def test_pages_with_where_slug(... | 28 | 681 |
metrics | tests/unittests/audio/test_sdr.py | .py | # Copyright The Lightning 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 agreed to in writin... | 163 | 5,639 |
pynacl | noxfile.py | .py | import nox
nox.options.reuse_existing_virtualenvs = True
nox.options.default_venv_backend = "uv|virtualenv"
@nox.session
def tests(session: nox.Session) -> None:
session.install(".[tests]")
if session.posargs:
tests = session.posargs
else:
tests = ["tests/"]
session.run(
"py... | 72 | 1,499 |
mlflow | mlflow/genai/judges/tools/utils.py | .py | """
Utilities for MLflow GenAI judge tools.
This module contains utility functions and classes used across
different judge tool implementations.
"""
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE
def create_page_token(offset: int) -> str:
"""
C... | 48 | 1,147 |
mlflow | mlflow/store/tracking/sqlalchemy_store.py | .py | from __future__ import annotations
import base64
import hashlib
import json
import logging
import math
import random
import threading
import time
import uuid
from collections import defaultdict
from dataclasses import dataclass, field
from functools import lru_cache, reduce
from pathlib import PurePath
from typing imp... | 10,289 | 440,265 |
onnx | tests/python/reference_evaluator_ml_test.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors
from __future__ import annotations
import importlib
import itertools
import os
import numpy as np
import pytest
from numpy.testing import assert_allclose
import onnx
from onnx import ONNX_ML, TensorProto, TypeProto... | 2,354 | 87,916 |
readthedocs.org | readthedocs/core/tests/test_signals.py | .py | import pytest
from django.contrib.auth.models import User
from django_dynamic_fixture import get
from readthedocs.builds.models import Version
from readthedocs.organizations.models import Organization, Team, TeamMember
from readthedocs.projects.models import Project
@pytest.mark.django_db
class TestProjectOrganizati... | 77 | 2,855 |
wandb | wandb/proto/v5/wandb_base_pb2.py | .py | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: wandb/proto/wandb_base.proto
# Protobuf Python Version: 5.26.0
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from goo... | 32 | 1,572 |
ipython | tests/test_tools.py | .py | # encoding: utf-8
"""
Tests for testing.tools
"""
# -----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this softwa... | 138 | 3,815 |
pyomo | doc/OnlineDocs/src/data/import5.tab.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 19 | 737 |
mlflow | tests/store/artifact/test_databricks_artifact_repo.py | .py | import json
import os
import posixpath
import re
import shutil
import time
from pathlib import Path
from unittest import mock
from unittest.mock import ANY
import pytest
import requests
from requests.models import Response
from mlflow.entities import TraceData
from mlflow.entities.file_info import FileInfo as FileInf... | 2,076 | 83,206 |
coremltools | deps/pybind11/tests/test_unnamed_namespace_b.py | .py | from __future__ import annotations
from pybind11_tests import unnamed_namespace_b as m
def test_have_attr_any_struct():
assert hasattr(m, "unnamed_namespace_b_any_struct")
| 8 | 179 |
pdm | tests/cli/test_venv.py | .py | import os
import platform
import re
import shutil
import subprocess
import sys
from pathlib import Path
from unittest.mock import ANY
import pytest
import shellingham
from pdm.cli.commands.venv import backends
from pdm.cli.commands.venv.utils import get_venv_prefix
@pytest.fixture(params=[True, False])
def with_pip... | 395 | 14,292 |
deap | examples/bbob.py | .py |
# This file is part of DEAP.
#
# DEAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# DEAP is distributed... | 140 | 5,020 |
confluent-kafka-python | examples/avro_consumer_encryption.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2024 Confluent Inc.
#
# 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 requi... | 131 | 4,688 |
hydra | tests/test_apps/app_print_hydra_mode/my_app.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from omegaconf import DictConfig
import hydra
from hydra.core.hydra_config import HydraConfig
@hydra.main(config_path="conf", config_name="config")
def my_app(_: DictConfig) -> None:
print(HydraConfig.get().mode)
if __name__ == "__main__":
... | 15 | 333 |
beam | sdks/python/apache_beam/examples/ml-orchestration/kfp/components/ingestion/src/ingest.py | .py | # 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 use ... | 75 | 3,521 |
lemur | lemur/policies/schemas.py | .py | """
.. module: lemur.policies.schemas
:platform: unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from marshmallow import fields
from lemur.common.schema import LemurOutputSchema
clas... | 20 | 502 |
openvino | src/bindings/python/tests/test_runtime/subprocess_test_tensor.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
from openvino import Tensor, Type
def test_run():
tensor = Tensor(np.random.randn(1, 3, 224, 224).astype(np.float32))
assert tensor.element_type == Type.f32
if __name__ == "__main__... | 17 | 338 |
saleor | saleor/graphql/core/validators/mutation_count_limit_rule.py | .py | import logging
from typing import Any
from django.conf import settings
from graphql import GraphQLError
from graphql.language.ast import OperationDefinition
from graphql.validation.rules.base import ValidationRule
from graphql.validation.validation import ValidationContext
from ...metrics import record_graphql_mutati... | 41 | 1,500 |
mlflow | tests/store/artifact/test_dbfs_artifact_repo_delegation.py | .py | import os
from unittest import mock
import pytest
from mlflow.store.artifact.artifact_repository_registry import get_artifact_repository
from mlflow.store.artifact.databricks_run_artifact_repo import DatabricksRunArtifactRepository
from mlflow.store.artifact.dbfs_artifact_repo import DbfsRestArtifactRepository
from m... | 56 | 2,532 |
hypercorn | src/hypercorn/asyncio/task_group.py | .py | from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from functools import partial
from types import TracebackType
from typing import Any
from ..config import Config
from ..typing import AppWrapper, ASGIReceiveCallable, ASGIReceiveEvent, ASGISendEvent, Scope
try:
from... | 76 | 2,240 |
pyomo | examples/pyomo/tutorials/param.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 149 | 4,283 |
openvino | thirdparty/itt_collector/runtool/exporters/Stat.py | .py | # Intel® Single Event API
#
# This file is provided under the BSD 3-Clause license.
# Copyright (c) 2021, Intel Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# Redistri... | 44 | 2,534 |
mlflow | mlflow/genai/scorers/guardrails/utils.py | .py | from __future__ import annotations
from typing import Any
from mlflow.entities.trace import Trace
from mlflow.exceptions import MlflowException
from mlflow.genai.utils.trace_utils import (
parse_inputs_to_str,
parse_outputs_to_str,
resolve_inputs_from_trace,
resolve_outputs_from_trace,
)
def check_g... | 58 | 1,741 |
cvxpy | cvxpy/atoms/sum_smallest.py | .py | """
Copyright 2013 Steven Diamond
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 agreed to in writing, software... | 26 | 890 |
mlflow | tests/genai/evaluate/test_evaluation.py | .py | import threading
import uuid
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal
from unittest import mock
from unittest.mock import ANY, MagicMock
import pandas as pd
import pytest
import mlflow
from mlflow.entities.assessment i... | 2,305 | 81,131 |
saleor | saleor/graphql/channel/enums.py | .py | from typing import Final
import graphene
from ...channel import AllocationStrategy, MarkAsPaidStrategy, TransactionFlowStrategy
from ..core.descriptions import DEPRECATED_LEGACY_PAYMENTS
from ..core.doc_category import (
DOC_CATEGORY_CHANNELS,
DOC_CATEGORY_PAYMENTS,
DOC_CATEGORY_PRODUCTS,
)
from ..core.en... | 42 | 1,277 |
sphinx | tests/test_domains/test_domain_py_canonical.py | .py | """Tests the Python Domain"""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from sphinx import addnodes
from sphinx.addnodes import (
desc,
desc_addname,
desc_annotation,
desc_content,
desc_name,
desc_sig_keyword,
desc_sig_space,
desc_signature,
)
... | 117 | 3,389 |
saleor | saleor/graphql/menu/schema.py | .py | import graphene
from ..channel.utils import get_default_channel_slug_or_graphql_error
from ..core import ResolveInfo
from ..core.connection import create_connection_slice, filter_connection_queryset
from ..core.context import ChannelQsContext
from ..core.fields import FilterConnectionField
from ..core.utils import fro... | 133 | 5,048 |
wagtail | wagtail/tests/test_translatablemixin.py | .py | from unittest.mock import patch
from django.conf import settings
from django.core import checks
from django.db import models
from django.test import TestCase, override_settings
from wagtail.models import Locale
from wagtail.test.i18n.models import (
ClusterableTestModel,
ClusterableTestModelChild,
Cluster... | 271 | 10,283 |
kombu | examples/hello_consumer.py | .py | from __future__ import annotations
from kombu import Connection
with Connection('amqp://guest:guest@localhost:5672//') as conn:
simple_queue = conn.SimpleQueue('simple_queue')
message = simple_queue.get(block=True, timeout=1)
print(f'Received: {message.payload}')
message.ack()
simple_queue.close()... | 11 | 321 |
pymc | tests/dims/__init__.py | .py | # Copyright 2025 - present The PyMC Developers
#
# 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... | 14 | 613 |
kombu | t/unit/utils/test_imports.py | .py | from __future__ import annotations
from unittest.mock import Mock
import pytest
from kombu import Exchange
from kombu.utils.imports import symbol_by_name
class test_symbol_by_name:
def test_instance_returns_instance(self):
instance = object()
assert symbol_by_name(instance) is instance
de... | 35 | 967 |
python-prompt-toolkit | src/prompt_toolkit/formatted_text/__init__.py | .py | """
Many places in prompt_toolkit can take either plain text, or formatted text.
For instance the :func:`~prompt_toolkit.shortcuts.prompt` function takes either
plain text or formatted text for the prompt. The
:class:`~prompt_toolkit.layout.FormattedTextControl` can also take either plain
text or formatted text.
In an... | 60 | 1,509 |
pyro | pyro/poutine/subsample_messenger.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
from typing import Optional, Tuple
import torch
from pyro.distributions.distribution import Distribution
from pyro.poutine.indep_messenger import CondIndepStackFrame, IndepMessenger
from pyro.poutine.runtime import Message, apply... | 218 | 8,426 |
textual | src/textual/widgets/_markdown_viewer.py | .py | from textual.widgets._markdown import MarkdownViewer
__all__ = ["MarkdownViewer"]
| 4 | 83 |
readthedocs.org | readthedocs/proxito/tests/storage.py | .py | """
Helper Django Storage class to use in El Proxito tests.
"""
from readthedocs.builds.storage import BuildMediaFileSystemStorage
class BuildMediaStorageTest(BuildMediaFileSystemStorage):
"""
Storage to use in El Proxito tests to have more control.
Allow to specify when to return ``True`` or ``False``... | 27 | 699 |
wagtail | wagtail/documents/blocks.py | .py | from wagtail.documents.views.chooser import viewset as chooser_viewset
DocumentChooserBlock = chooser_viewset.get_block_class(
name="DocumentChooserBlock", module_path="wagtail.documents.blocks"
)
| 6 | 202 |
tablib | src/tablib/formats/_json.py | .py | """ Tablib - JSON Support
"""
__lazy_modules__ = {"decimal", "json", "uuid"}
import decimal
import json
from uuid import UUID
import tablib
def serialize_objects_handler(obj):
if isinstance(obj, (decimal.Decimal, UUID)):
return str(obj)
elif hasattr(obj, 'isoformat'):
return obj.isoformat()... | 66 | 1,609 |
probability | tensorflow_probability/python/internal/backend/numpy/numpy_array.py | .py | # Copyright 2018 The TensorFlow Probability 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 540 | 16,019 |
wagtail | wagtail/documents/views/bulk_actions/delete.py | .py | from django.utils.translation import gettext_lazy as _
from django.utils.translation import ngettext
from wagtail.admin.views.bulk_action.mixins import ReferenceIndexMixin
from wagtail.documents.views.bulk_actions.document_bulk_action import DocumentBulkAction
class DeleteBulkAction(ReferenceIndexMixin, DocumentBulk... | 38 | 1,396 |
hatch | src/hatch/utils/toml.py | .py | from __future__ import annotations
import sys
from typing import Any
if sys.version_info >= (3, 11):
import tomllib
else:
import tomli as tomllib
def load_toml_data(data: str) -> dict[str, Any]:
return tomllib.loads(data)
def load_toml_file(path: str) -> dict[str, Any]:
with open(path, encoding="u... | 19 | 372 |
rq | tests/test_scripts.py | .py | """Tests for rq.scripts functions."""
import calendar
from datetime import datetime, timedelta, timezone
from rq import Queue
from rq.exceptions import DuplicateJobError
from rq.job import Job, JobStatus
from rq.scripts import save_unique_job, schedule_unique_job
from tests import RQTestCase
from tests.fixtures impor... | 203 | 8,849 |
cvxpy | cvxpy/atoms/sign.py | .py | """
Copyright, the CVXPY 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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
... | 77 | 2,101 |
saleor | saleor/webhook/tests/test_webhook_validators.py | .py | import pytest
from django.core.exceptions import ValidationError
from ..validators import (
HEADERS_LENGTH_LIMIT,
HEADERS_NUMBER_LIMIT,
custom_headers_validator,
)
@pytest.mark.parametrize(
("headers", "err_msg"),
[
(
{
"Key1": "Value1",
"Key2":... | 72 | 2,103 |
gunicorn | tests/test_uwsgi.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import io
import pytest
from unittest import mock
from gunicorn.uwsgi import (
UWSGIRequest,
UWSGIParser,
UWSGIParseException,
InvalidUWSGIHeader,
UnsupportedModifier,
ForbiddenUWSGIRequest... | 436 | 14,386 |
coremltools | coremltools/converters/mil/mil/ops/defs/iOS17/recurrent.py | .py | # Copyright (c) 2023, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from coremltools.converters.mil.mil import types
from coremltools.converters.mil.mil.input_type impo... | 99 | 4,426 |
clearml | examples/advanced/multiple_tasks_single_process.py | .py | from clearml import Task
for i in range(3):
task = Task.init(
project_name="examples",
task_name=f"Same process, Multiple tasks, Task #{i}",
)
print(f"Task #{i} running")
print(f"Task #{i} done :) ")
task.close()
| 12 | 251 |
pyro | tests/infer/test_multi_sample_elbos.py | .py | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import pytest
import torch
import pyro
import pyro.distributions as dist
from pyro.infer import RenyiELBO
from tests.common import assert_close
def check_elbo(model, guide, Elbo):
elbo = Elbo(num_particles=2, vectorize_particles... | 59 | 1,638 |
openvino | src/frontends/paddle/tests/test_models/gen_scripts/generate_dropout.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
# pool2d paddle model generator
#
import numpy as np
from save_model import saveModel
import sys
def paddle_dropout(name : str, x, p, paddle_attrs):
import paddle
paddle.enable_static()
with paddle.static.program_guard(p... | 51 | 1,463 |
mlflow | tests/pyfunc/test_chat_agent_validation.py | .py | import pytest
from mlflow.types.agent import ChatAgentChunk, ChatAgentMessage, ChatAgentResponse
def test_chat_agent_message_throws_on_invalid_data():
# Missing 'content' or 'tool_calls'
data = {"role": "user", "name": "test_user"}
with pytest.raises(ValueError, match="Either 'content' or 'tool_calls'"):... | 79 | 2,893 |
returns | returns/methods/unwrap_or_failure.py | .py | from typing import TypeVar
from returns.interfaces.unwrappable import Unwrappable
from returns.pipeline import is_successful
_FirstType = TypeVar('_FirstType')
_SecondType = TypeVar('_SecondType')
def unwrap_or_failure(
container: Unwrappable[_FirstType, _SecondType],
) -> _FirstType | _SecondType:
"""
... | 28 | 728 |
textual | docs/examples/how-to/layout05.py | .py | from textual.app import App, ComposeResult
from textual.containers import HorizontalScroll, VerticalScroll
from textual.screen import Screen
from textual.widgets import Placeholder
class Header(Placeholder):
DEFAULT_CSS = """
Header {
height: 3;
dock: top;
}
"""
class Footer(Placehol... | 54 | 1,049 |
saleor | saleor/graphql/product/mutations/product_variant/product_variant_update.py | .py | from typing import cast
import graphene
from django.core.exceptions import ValidationError
from .....attribute import models as attribute_models
from .....core.tracing import traced_atomic_transaction
from .....core.utils.update_mutation_manager import InstanceTracker
from .....discount.utils.promotion import mark_ac... | 360 | 13,871 |
saleor | saleor/graphql/checkout/tests/deprecated/test_checkout_language_code_update.py | .py | import graphene
from .....checkout.error_codes import CheckoutErrorCode
from ....tests.utils import get_graphql_content
MUTATION_CHECKOUT_UPDATE_LANGUAGE_CODE = """
mutation checkoutLanguageCodeUpdate(
$checkoutId: ID, $token: UUID, $languageCode: LanguageCodeEnum!
){
checkoutLanguageCodeUpdate(
checkoutI... | 111 | 3,130 |
onnxruntime | onnxruntime/test/testdata/transform/approximation/gelu_approximation_gen.py | .py | import onnx
from onnx import TensorProto, helper
graph = helper.make_graph(
[ # nodes
# Add node before Gelu
helper.make_node("Gelu", ["A"], ["C"], "Gelu_1", domain="com.microsoft"),
],
"Gelu_NoBias", # name
[ # inputs
helper.make_tensor_value_info("A", TensorProto.FLOAT, ["b... | 61 | 1,929 |
cvxpy | cvxpy/reductions/dnlp2smooth/canonicalizers/huber_canon.py | .py | """
Copyright 2025 CVXPY developers
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 agreed to in writing, softwa... | 56 | 1,788 |
cvxpy | cvxpy/atoms/affine/partial_trace.py | .py | """
Copyright 2022, adapted from Convex.jl.
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 agreed to in writing... | 95 | 3,572 |
onnx | onnx/reference/op_run.py | .py | # SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import abc
from typing import TYPE_CHECKING, Any
import numpy as np
import onnx
if TYPE_CHECKING:
from collections.abc import Sequence
class RuntimeTypeError(RuntimeError):
"""Raised when a type of a variable is unexpected."""
cl... | 683 | 25,409 |
scikit-optimize | skopt/sampler/hammersly.py | .py | # -*- coding: utf-8 -*-
""" Inspired by https://github.com/jonathf/chaospy/blob/master/chaospy/
distributions/sampler/sequences/hammersley.py
"""
import numpy as np
from .halton import Halton
from ..space import Space
from .base import InitialPointGenerator
from sklearn.utils import check_random_state
class Hammersly... | 93 | 3,447 |
beam | sdks/python/apache_beam/runners/dataflow/dataflow_exercise_metrics_pipeline.py | .py | #
# 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 us... | 173 | 5,809 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.