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 |
|---|---|---|---|---|---|
openvino | src/bindings/python/tests/test_transformations/test_offline_api.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import pytest
import numpy as np
from openvino._offline_transformations import (
apply_moc_transformations,
apply_low_latency_transformation,
apply_pruning_transformation,
apply_make_stat... | 432 | 15,797 |
onnxruntime | onnxruntime/test/python/quantization/test_qnn_preprocess_model.py | .py | #!/usr/bin/env python
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# ---------------------------------------------------------------... | 291 | 12,826 |
saleor | saleor/graphql/page/mutations/page_create.py | .py | import datetime
from typing import cast
import graphene
from django.core.exceptions import ValidationError
from django.db.models import QuerySet
from ....core.tracing import traced_atomic_transaction
from ....page import models
from ....page.error_codes import PageErrorCode
from ....permission.enums import PagePermis... | 147 | 5,584 |
kombu | t/unit/transport/test_qpid.py | .py | from __future__ import annotations
import select
import socket
import ssl
import sys
import time
import uuid
from collections.abc import Callable
from itertools import count
from queue import Empty
from unittest.mock import Mock, call, patch
import pytest
from kombu.transport.qpid import (AuthenticationFailure, Chan... | 1,823 | 71,136 |
mlflow | mlflow/entities/run.py | .py | from typing import Any
from mlflow.entities._mlflow_object import _MlflowObject
from mlflow.entities.run_data import RunData
from mlflow.entities.run_info import RunInfo
from mlflow.entities.run_inputs import RunInputs
from mlflow.entities.run_outputs import RunOutputs
from mlflow.exceptions import MlflowException
fro... | 98 | 2,763 |
kombu | t/unit/test_message.py | .py | from __future__ import annotations
import sys
from unittest.mock import Mock, patch
import pytest
from kombu.message import Message
class test_Message:
def test_repr(self):
assert repr(Message('b', channel=Mock()))
def test_decode(self):
m = Message('body', channel=Mock())
decode ... | 45 | 1,285 |
pyro | tests/doctest_fixtures.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import numpy
import pytest
import torch
import pyro
import pyro.contrib.autoname.named as named
import pyro.contrib.gp as gp
import pyro.distributions as dist
import pyro.poutine as poutine
from pyro.infer import EmpiricalMarginal... | 36 | 1,075 |
astropy | scripts/check-lowest-resolved-tree.py | .py | # /// script
# requires-python = ">=3.11"
# dependencies = [
# "uv==0.11.19",
# ]
# ///
"""
This CLI (re)generates lowest-resolved-tree.txt, which represents a complete,
universal and reproducible solution to astropy's dependency constraints, using uv's
--resolution=lowest resolution strategy.
This solution should... | 149 | 4,043 |
openvino | tools/ovc/unit_tests/moc_tf_fe/conversion_basic_models_test.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import os
import pytest
from openvino import Core
from openvino.tools.ovc.convert import convert_model
class TestMoFreezePlaceholderTFFE():
def basic(self, input_model, argv_input, inputs, dtype, expected, only_c... | 145 | 6,037 |
mlflow | mlflow/mistral/autolog.py | .py | import inspect
import logging
import mlflow
import mlflow.mistral
from mlflow.entities import SpanType
from mlflow.mistral.chat import convert_tool_to_mlflow_chat_tool
from mlflow.tracing.constant import SpanAttributeKey, TokenUsageKey
from mlflow.tracing.provider import detach_span_from_context, set_span_in_context
f... | 133 | 4,610 |
qutip | qutip/tests/core/test_qobjevo.py | .py | import operator
import pytest
from qutip import (
Qobj, QobjEvo, coefficient, qeye, sigmax, sigmaz, num, destroy, rand_stochastic,
rand_herm, rand_ket, liouvillian, basis, spre, spost, to_choi, expect,
rand_ket, rand_dm, operator_to_vector, SESolver, MESolver, CoreOptions
)
import qutip.core.data as _data
... | 717 | 23,197 |
probability | tensorflow_probability/python/bijectors/lambertw_transform_test.py | .py | # Copyright 2020 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... | 183 | 7,889 |
saleor | saleor/tests/e2e/checkout/test_checkout_create_partially_paid_order.py | .py | import pytest
from ..product.utils.preparing_product import prepare_product
from ..shop.utils import prepare_shop
from ..transactions.utils import create_transaction
from ..utils import assign_permissions
from .utils import (
checkout_create,
checkout_delivery_method_update,
raw_checkout_complete,
)
@pyt... | 128 | 3,624 |
wandb | wandb/__init__.py | .py | """Use wandb to track machine learning work.
Train and fine-tune models, manage models from experimentation to production.
For guides and examples, see https://docs.wandb.ai.
For scripts and interactive notebooks, see https://github.com/wandb/examples.
For reference documentation, see https://docs.wandb.ai/models/r... | 215 | 5,914 |
wagtail | wagtail/actions/convert_alias.py | .py | from django.core.exceptions import PermissionDenied
from wagtail.actions.base import BaseAction
from wagtail.log_actions import log
class ConvertAliasPageError(RuntimeError):
"""
Raised when the page to convert is not an alias.
"""
pass
class ConvertAliasPagePermissionError(PermissionDenied):
... | 74 | 2,163 |
tablib | src/tablib/_vendor/dbfpy/header.py | .py | import datetime
import io
import struct
import sys
from . import fields
from .utils import getDate
__version__ = "$Revision: 1.6 $"[11:-2]
__date__ = "$Date: 2010/09/16 05:06:39 $"[7:-2]
__all__ = ["DbfHeader"]
"""DBF header definition.
TODO:
- handle encoding of the character fields
(encoding information s... | 273 | 9,385 |
openvino | src/frontends/tensorflow_lite/tests/test_models/gen_wrapper.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import subprocess
import sys
if len(sys.argv) < 4:
print("Script[model in pbtxt format], output folder and mark file must be specified as arguments", str(sys.argv))
exit(1)
gen_script = sys.argv[1]
out_folder = sys.ar... | 27 | 745 |
saleor | saleor/graphql/order/tests/integration/test_bulk_order.py | .py | import copy
from decimal import Decimal
from unittest.mock import patch
import graphene
import pytest
from saleor.order import OrderEvents
from saleor.order.models import Order, OrderLine
from saleor.payment.models import TransactionItem
from .....order.calculations import fetch_order_prices_if_expired
from .....plu... | 411 | 14,011 |
mamba | micromamba/tests/test_run.py | .py | import os
import random
import shutil
import string
import subprocess
from sys import platform
import pytest
from .helpers import create, random_string, subprocess_run, umamba_run
common_simple_flags = ["", "-d", "--detach", "--clean-env"]
# -d/--detach are not available on Windows (see run.cpp)
common_simple_flags_... | 131 | 4,906 |
conda | conda/plugins/config.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""
Handles plugin configuration functionality including:
- Managing plugin-specific settings
- Processing configuration data from various sources
- Dynamically adding and removing plugin settings
- Providing a standardized interface for... | 133 | 4,392 |
loguru | tests/test_defaults.py | .py | import pytest
from loguru._defaults import env
@pytest.mark.parametrize("value", ["test", ""])
def test_string(value, monkeypatch):
with monkeypatch.context() as context:
key = "VALID_STRING"
context.setenv(key, value)
assert env(key, str) == value
@pytest.mark.parametrize("value", ["y"... | 67 | 1,984 |
pyro | pyro/contrib/bnn/utils.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import math
import torch
def xavier_uniform(D_in, D_out):
scale = math.sqrt(6.0 / float(D_in + D_out))
noise = torch.rand(D_in, D_out)
return 2.0 * scale * noise - scale
def adjoin_ones_vector(x):
return torch.... | 21 | 490 |
probability | tensorflow_probability/python/internal/backend/numpy/dtype.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... | 117 | 2,662 |
saleor | saleor/tests/e2e/orders/discounts/test_order_products_on_promotion_and_manual_order_discount.py | .py | from decimal import Decimal
import pytest
from .....core.prices import quantize_price
from .....product.tasks import recalculate_discounted_price_for_products_task
from ... import DEFAULT_ADDRESS
from ...product.utils.preparing_product import prepare_product
from ...promotions.utils import create_promotion, create_pr... | 184 | 7,047 |
biopython | Tests/test_bgzf.py | .py | # Copyright 2010-2016, 2024 by Peter Cock.
# All rights reserved.
# 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.
"""Test code for working with BGZF files (used in BAM files).
See also the doctests i... | 523 | 20,642 |
astropy | astropy/io/misc/pickle_helpers.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains simple input/output related functionality that is not
part of a larger framework or standard.
"""
import pickle
from astropy.utils.decorators import deprecated
__all__ = ["fnpickle", "fnunpickle"]
@deprecated(since="6.0", mess... | 109 | 3,316 |
onnx | onnx/inliner.py | .py | # Copyright (c) ONNX Project Contributors
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import onnx
import onnx.onnx_cpp2py_export.inliner as C # noqa: N812
def inline_local_functions(
model: onnx.ModelProto, convert_version: bool = False
) -> onnx.ModelProto:
"""Inline model-l... | 61 | 2,106 |
saleor | saleor/tax/tests/test_calculations.py | .py | from decimal import Decimal
import pytest
from prices import Money
from ...core.prices import quantize_price
from ..calculations import calculate_flat_rate_tax
@pytest.mark.parametrize(
("amount", "net", "gross", "rate", "prices_entered_with_tax"),
[
("10.00", "10.00", "12.30", Decimal(23), False),
... | 23 | 778 |
saleor | saleor/graphql/checkout/mutations/__init__.py | .py | from .checkout_add_promo_code import CheckoutAddPromoCode
from .checkout_billing_address_update import CheckoutBillingAddressUpdate
from .checkout_complete import CheckoutComplete
from .checkout_create import CheckoutCreate
from .checkout_create_from_order import CheckoutCreateFromOrder
from .checkout_customer_attach i... | 42 | 1,742 |
probability | tensorflow_probability/python/internal/monte_carlo.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... | 142 | 5,499 |
mlflow | mlflow/gateway/runner.py | .py | import logging
import os
import subprocess
import sys
from typing import Generator
from watchfiles import watch
from mlflow.environment_variables import (
MLFLOW_GATEWAY_CONFIG,
MLFLOW_GATEWAY_RESOLVE_API_KEY_FROM_ENV,
MLFLOW_GATEWAY_RESOLVE_API_KEY_FROM_FILE,
)
from mlflow.gateway import app
from mlflow.... | 113 | 3,060 |
pyomo | pyomo/contrib/pynumero/sparse/tests/test_block_vector.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... | 1,163 | 36,154 |
mlflow | mlflow/deployments/plugin_manager.py | .py | import abc
import importlib.metadata
import inspect
import importlib_metadata
from mlflow.deployments.base import BaseDeploymentClient
from mlflow.deployments.utils import parse_target_uri
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INTERNAL_ERROR, RESOURCE_DOES_NOT_EXIST
fr... | 144 | 5,604 |
returns | tests/test_io/test_io_container/test_io_functions/test_impure.py | .py | from returns.io import IO, impure
def _fake_impure_function(some_param: int) -> int:
return some_param
def test_impure():
"""Ensures that impure returns IO container."""
impure_result = impure(_fake_impure_function)(1)
assert isinstance(impure_result, IO)
assert impure_result == IO(1)
| 13 | 310 |
mlflow | mlflow/genai/judges/prompts/conversational_safety.py | .py | # NB: User-facing name for the conversational safety assessment.
CONVERSATIONAL_SAFETY_ASSESSMENT_NAME = "conversational_safety"
CONVERSATIONAL_SAFETY_PROMPT = """\
Consider the following conversation history between a user and an assistant. Your task is to \
evaluate the safety of the assistant's responses only and o... | 27 | 1,403 |
ipython | tests/test_pycolorize.py | .py | # coding: utf-8
"""Test suite for our color utilities.
Authors
-------
* Min RK
"""
# -----------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING.txt, ... | 72 | 1,812 |
beam | sdks/python/apache_beam/ml/rag/ingestion/base_test.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... | 82 | 2,801 |
pyomo | examples/pyomobook/python-ch/BadIndent.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... | 23 | 853 |
probability | spinoffs/autobnn/autobnn/models.py | .py | # Copyright 2023 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... | 314 | 9,847 |
saleor | saleor/plugins/openid_connect/tests/test_plugin.py | .py | from unittest.mock import MagicMock, Mock, patch
from urllib.parse import parse_qs, urlparse
import pytest
from authlib.integrations.base_client.errors import OAuthError
from authlib.jose.errors import JoseError
from django.core import signing
from django.core.exceptions import ValidationError
from freezegun import fr... | 2,147 | 72,680 |
beam | sdks/python/apache_beam/examples/inference/vllm_gemma_batch.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... | 130 | 4,732 |
scikit-bio | skbio/metadata/missing.py | .py | """Defines Handling of different Missing classes for Metadata module."""
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2023, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distribut... | 116 | 3,361 |
slimit | src/slimit/visitors/ecmavisitor.py | .py | ###############################################################################
#
# Copyright (c) 2011 Ruslan Spivak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, inc... | 398 | 12,757 |
beam | sdks/python/apache_beam/typehints/arrow_type_compatibility_test.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... | 221 | 7,798 |
coveragepy | tests/test_setup.py | .py | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/coveragepy/coveragepy/blob/main/NOTICE.txt
"""Tests of miscellaneous stuff."""
from __future__ import annotations
import sys
from typing import cast
import pytest
import coverage
from coverage import ... | 63 | 2,044 |
sqlmap | tamper/charencode.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
import string
from lib.core.enums import PRIORITY
__priority__ = PRIORITY.LOWEST
def dependencies():
pass
def tamper(payload, **kwargs):
"""
URL-encodes all charac... | 50 | 1,387 |
conda | tests/plugins/test_health_checks.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
import pytest
from conda import plugins
from conda.base.context import context
from conda.exceptions import CondaSystemExit
from conda.plugins.subcommands import doctor
from conda.plugins.types import CondaHealthCheck
class HealthCheckPlugin:... | 140 | 4,264 |
pyomo | pyomo/contrib/piecewise/transform/multiple_choice.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... | 42 | 1,921 |
eve | tests/methods/patch_atomic_concurrency.py | .py | import sys
import simplejson as json
import eve.methods.common
from eve.utils import config
from tests import TestBase
"""
Atomic Concurrency Checks
Prior to commit 54fd697 from 2016-November, ETags would be verified
twice during a patch. One ETag check would be non-atomic by Eve,
then again atomically by MongoDB ... | 77 | 2,583 |
confluent-kafka-python | src/confluent_kafka/schema_registry/serde.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... | 22 | 732 |
sqlmap | lib/takeover/metasploit.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
from __future__ import print_function
import errno
import os
import re
import select
import sys
import tempfile
import time
from subprocess import PIPE
from extra.cloak.cloak i... | 706 | 28,235 |
beam | sdks/python/apache_beam/examples/snippets/transforms/elementwise/enrichment_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");... | 420 | 16,610 |
coremltools | coremltools/converters/mil/frontend/torch/__init__.py | .py | # Copyright (c) 2020, 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._deps import _HAS_TORCH
register_torch_op = None
if _HAS_TORCH:
from . import ... | 15 | 577 |
mlflow | tests/pyfunc/test_uv_model_logging.py | .py | import platform
import shutil
import subprocess
import sys
from pathlib import Path
from unittest import mock
import pytest
import mlflow
import mlflow.pyfunc
from mlflow.utils.os import is_windows
from mlflow.utils.uv_utils import (
_PYPROJECT_FILE,
_PYTHON_VERSION_FILE,
_UV_LOCK_FILE,
is_uv_availabl... | 504 | 16,338 |
coremltools | coremltools/test/optimize/torch/palettization/test_post_training_palettization.py | .py | # Copyright (c) 2024, 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
import copy
import pytest
import torch
import torch.functional as F
import torch.nn as nn
from core... | 230 | 7,502 |
coremltools | coremltools/converters/mil/frontend/tensorflow/test/test_parsed_tf_node.py | .py | # Copyright (c) 2020, 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
import unittest
import pytest
pytest.importorskip("tensorflow", minversion="1.15.0")
from tensorflo... | 66 | 2,187 |
probability | spinoffs/inference_gym/inference_gym/targets/log_gaussian_cox_process_test.py | .py | # Copyright 2020 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... | 129 | 4,308 |
sphinx | tests/roots/test-ext-autodoc/target/pep604.py | .py | from __future__ import annotations
attr: int | str #: docstring
def sum(x: int | str, y: int | str) -> int | str:
"""docstring"""
class Foo:
"""docstring"""
attr: int | str #: docstring
def meth(self, x: int | str, y: int | str) -> int | str:
"""docstring"""
| 17 | 292 |
clearml | examples/optimization/hyper-parameter-optimization/hyper_parameter_optimizer.py | .py | import logging
import argparse
from clearml import Task
from clearml.automation import (
DiscreteParameterRange, HyperParameterOptimizer, RandomSearch,
UniformIntegerParameterRange)
# trying to load Bayesian optimizer package
try:
from clearml.automation.optuna import OptimizerOptuna # noqa
aSearchSt... | 134 | 6,707 |
conda | tests/core/test_envs_manager.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import os
from logging import getLogger
from os.path import isdir, join
from types import SimpleNamespace
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
from conda.auxlib.col... | 197 | 6,445 |
openvino | tests/e2e_tests/common/ref_collector/score_tf_hub.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import sys
import logging as log
import tensorflow as tf
from .tf_hub_ref_provider import ClassProvider
os.environ['GLOG_minloglevel'] = '3'
class ScoreTFHub(ClassProvider):
"""Reference collector for TensorFlow Hub mod... | 35 | 989 |
marshmallow | tests/foo_serializer.py | .py | from marshmallow import Schema, fields
class FooSerializer(Schema):
_id = fields.Integer()
| 6 | 97 |
sphinx | tests/utils.py | .py | from __future__ import annotations
__all__ = (
'http_server',
'extract_node',
'extract_element',
)
import os
import socket
from contextlib import contextmanager
from http.server import ThreadingHTTPServer
from pathlib import Path
from ssl import PROTOCOL_TLS_SERVER, SSLContext
from threading import Thread... | 188 | 5,980 |
returns | tests/test_primitives/test_laws/test_lawful/test_laws_resolution.py | .py | import pytest
from test_hypothesis.test_laws import (
test_custom_interface_with_laws,
test_custom_type_applicative,
)
from returns.context import (
RequiresContext,
RequiresContextFutureResult,
RequiresContextIOResult,
RequiresContextResult,
)
from returns.future import Future, FutureResult
fr... | 79 | 2,479 |
wandb | wandb/integration/sklearn/calculate/confusion_matrix.py | .py | import itertools
from warnings import simplefilter
import numpy as np
from sklearn import metrics
from sklearn.utils.multiclass import unique_labels
import wandb
from .. import utils
# ignore all future warnings
simplefilter(action="ignore", category=FutureWarning)
def validate_labels(*args, **kwargs): # FIXME
... | 94 | 2,543 |
openvino | src/bindings/python/tests/test_runtime/test_tensor.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from copy import deepcopy, copy
import os
import subprocess
import sys
import numpy as np
import openvino as ov
import openvino.opset13 as ops
from openvino.helpers import pack_data, unpack_data
import pytest
... | 779 | 25,919 |
saleor | saleor/graphql/order/tests/benchmark/test_fulfillment_refund_and_return_products.py | .py | from unittest.mock import patch
import graphene
import pytest
from .....payment import ChargeStatus
from .....warehouse.models import Stock
from ....tests.utils import get_graphql_content
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
@patch("saleor.payment.gateway.refund")
def test_fulfillment_re... | 177 | 5,231 |
biopython | Bio/SeqIO/PdbIO.py | .py | # Copyright 2012 by Eric Talevich. All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Bio.SeqIO support for ... | 578 | 22,951 |
saleor | saleor/graphql/invoice/tests/test_invoice_delete.py | .py | from unittest.mock import patch
import graphene
from ....graphql.tests.utils import assert_no_permission, get_graphql_content
from ....invoice.error_codes import InvoiceErrorCode
from ....invoice.models import Invoice, InvoiceEvent, InvoiceEvents
INVOICE_DELETE_MUTATION = """
mutation invoiceDelete($id: ID!) {
... | 105 | 3,281 |
openvino | tests/layer_tests/pytorch_tests/test_flip.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
from pytorch_layer_test_class import PytorchLayerTest, skip_if_export
class TestFlip(PytorchLayerTest):
def _prepare_input(self, out=False, dtype="float32"):
import numpy as np
x = self.random.randn(2... | 44 | 1,506 |
textual | tests/snapshot_tests/snapshot_apps/layer_fix.py | .py | from textual.app import App, ComposeResult
from textual.containers import Vertical
from textual.widgets import Header, Footer, Label
from textual.binding import Binding
class Dialog(Vertical):
def compose(self) -> ComposeResult:
"""Compose the child widgets."""
yield Label("This should not cause a... | 49 | 1,034 |
mlflow | tests/pyspark/optuna/test_study.py | .py | import logging
import os
import numpy as np
import pyspark
import pytest
from optuna.exceptions import TrialPruned
from optuna.pruners import NopPruner, ThresholdPruner
from optuna.samplers import TPESampler
from optuna.study import StudyDirection
from optuna.trial import TrialState
from packaging.version import Versi... | 386 | 13,398 |
onnxruntime | onnxruntime/python/tools/transformers/profiler.py | .py | import argparse
import os
import numpy
import psutil
from onnx import TensorProto
"""
This profiler tool could run a transformer model and print out the kernel time spent on each Node of the model.
Example of profiling of longformer model:
python profiler.py --model longformer-base-4096_fp32.onnx --batch_size 1 -... | 435 | 13,302 |
mlflow | tests/assistant/providers/test_provider_resolution.py | .py | import pytest
from mlflow.assistant.providers import (
ClaudeCodeProvider,
CodexProvider,
MlflowGatewayProvider,
OllamaProvider,
resolve_default_provider,
)
_PROVIDERS = {
"claude_code": ClaudeCodeProvider,
"codex": CodexProvider,
"mlflow_gateway": MlflowGatewayProvider,
"ollama": ... | 67 | 1,811 |
hydra | hydra/__init__.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Source of truth for Hydra's version
__version__ = "1.4.0.dev9"
from hydra import utils
from hydra.errors import MissingConfigException
from hydra.main import main
from hydra.types import TaskFunction
from .compose import compose
from .initialize... | 24 | 591 |
hydra | plugins/hydra_ray_launcher/hydra_plugins/hydra_ray_launcher/_launcher_util.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
import os
from contextlib import contextmanager
from subprocess import PIPE, Popen
from typing import Any, Dict, Generator, List, Tuple, cast
import ray
from hydra.core.hydra_config import HydraConfig
from hydra.core.singleton import... | 150 | 4,521 |
django-cms | cms/management/commands/subcommands/tree.py | .py | from collections import OrderedDict
from django.db import IntegrityError
from cms.models.pagemodel import Page, PageUrl
from .base import SubcommandsCommand
def get_descendants(root):
"""
Returns a generator of primary keys which represent
descendants of the given node ID (root_id)
"""
# Note t... | 111 | 3,648 |
luigi | luigi/contrib/presto.py | .py | import inspect
import logging
import re
from collections import OrderedDict
from contextlib import closing
from enum import Enum
from time import sleep
import luigi
from luigi.contrib import rdbms
from luigi.task_register import Register
logger = logging.getLogger("luigi-interface")
try:
from pyhive.exc import D... | 269 | 7,620 |
attrs | tests/test_config.py | .py | # SPDX-License-Identifier: MIT
"""
Tests for `attr._config`.
"""
import pytest
from attr import _config
class TestConfig:
def test_default(self):
"""
Run validators by default.
"""
assert True is _config._run_validators
def test_set_run_validators(self):
"""
... | 44 | 1,122 |
clearml | clearml/cli/data/__main__.py | .py | import json
import os
import shutil
from argparse import ArgumentParser, HelpFormatter
from functools import partial
from typing import Sequence, Optional, Dict, Any
from pathlib2 import Path
import clearml.backend_api.session
from clearml.datasets import Dataset
from clearml.version import __version__
clearml.backe... | 980 | 33,133 |
confluent-kafka-python | tests/test_partitioners.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Unit tests for partitioner functions.
"""
import pytest
from confluent_kafka import consistent, fnv1a, murmur2
class TestPartitioners:
def test_deterministic(self):
"""Test that deterministic partitioners produce the same output for the same input."""
... | 37 | 1,107 |
pyro | tests/contrib/bnn/test_hidden_layer.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import pytest
import torch
import torch.nn.functional as F
from torch.distributions import Normal
from pyro.contrib.bnn import HiddenLayer
from tests.common import assert_equal
@pytest.mark.parametrize("non_linearity", [F.relu])... | 68 | 2,100 |
astropy | astropy/visualization/tests/test_histogram.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from numpy.testing import assert_allclose
from astropy.utils.compat.optional_deps import HAS_PLT, HAS_SCIPY
if HAS_PLT:
from matplotlib.figure import Figure
import numpy as np
import pytest
from astropy.stats import histogram
from astropy.visuali... | 87 | 2,445 |
openvino | tools/commit_slider/utils/templates/benchmark_cross_check.py | .py | from utils.templates.common import CommonTemplate
class BenchmarkCrossCheckTemplate(CommonTemplate):
def getName():
return 'bm_cc'
def getBilletFileName():
return 'benchmark_crosscheck.json'
def printResult(commitPath, outLogger, getCommitInfo):
print("\n*****************<Comm... | 64 | 2,716 |
mlflow | mlflow/sagemaker/cli.py | .py | import json
import os
import tempfile
import click
import mlflow.models.docker_utils
import mlflow.sagemaker
from mlflow.sagemaker import DEFAULT_IMAGE_NAME as IMAGE
from mlflow.utils import cli_args
from mlflow.utils import env_manager as em
@click.group("sagemaker")
def commands():
"""
Serve models on Sag... | 394 | 13,547 |
sphinx | sphinx/writers/text.py | .py | """Custom docutils writer for plain text."""
from __future__ import annotations
import math
import os
import re
import textwrap
from itertools import chain, groupby, pairwise
from typing import TYPE_CHECKING, cast
from docutils import nodes, writers
from docutils.utils import column_width
from sphinx import addnode... | 1,374 | 45,229 |
coremltools | coremltools/converters/mil/frontend/milproto/__init__.py | .py | # Copyright (c) 2022, 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 . import load
| 7 | 235 |
onnx | onnx/backend/test/case/node/softmaxcrossentropy.py | .py | # Copyright (c) ONNX Project Contributors
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from typing import Any
import numpy as np
import onnx
from onnx.backend.test.case.base import Base
from onnx.backend.test.case.node import expect
def softmaxcrossentropy(
x: np.ndarray,
targ... | 1,159 | 35,653 |
onnx | onnx/backend/test/case/node/gatherelements.py | .py | # Copyright (c) ONNX Project Contributors
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import numpy as np
import onnx
from onnx.backend.test.case.base import Base
from onnx.backend.test.case.node import expect
# The below GatherElements' numpy implementation is from https://stackoverfl... | 93 | 2,669 |
kombu | t/unit/test_exceptions.py | .py | from __future__ import annotations
from unittest.mock import Mock
from kombu.exceptions import HttpError
class test_HttpError:
def test_str(self) -> None:
assert str(HttpError(200, 'msg', Mock(name='response')))
| 12 | 229 |
saleor | saleor/graphql/page/mutations/page_type_update.py | .py | from collections import defaultdict
import graphene
from django.core.exceptions import ValidationError
from ....page import models
from ....page.error_codes import PageErrorCode
from ....page.utils import mark_pages_search_vector_as_dirty_in_batches
from ....permission.enums import PageTypePermissions
from ...core im... | 104 | 3,928 |
sphinx | tests/test_intl/test_locale.py | .py | """Test locale."""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from sphinx import locale
if TYPE_CHECKING:
from collections.abc import Callable, Iterator
from pathlib import Path
from sphinx.testing.util import SphinxTestApp
@pytest.fixture(autouse=True)
def _cl... | 90 | 2,961 |
mlflow | mlflow/models/rag_signatures.py | .py | from dataclasses import dataclass, field
from mlflow.models import ModelSignature
from mlflow.types.schema import (
Array,
ColSpec,
DataType,
Object,
Property,
Schema,
)
from mlflow.utils.annotations import deprecated
@deprecated("mlflow.types.llm.ChatMessage")
@dataclass
class Message:
r... | 118 | 3,091 |
saleor | saleor/graphql/account/tests/mutations/authentication/test_set_password.py | .py | from unittest.mock import patch
from freezegun import freeze_time
from ......account import events as account_events
from ......account.error_codes import AccountErrorCode
from ......account.tests.fixtures.user import dangerously_create_test_user
from ......core.tokens import (
account_confirm_token_generator,
... | 297 | 9,932 |
openvino | tests/e2e_tests/common/comparator/__init__.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from . import classification
from . import dummy
from . import eltwise
from . import object_detection
from . import ocr
from . import semantic_segmentation
from . import ssim
from . import ssim_4d
| 12 | 280 |
beam | learning/katas/python/Common Transforms/WithKeys/WithKeys/task.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... | 36 | 1,287 |
pyro | pyro/optim/pytorch_optimizers.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import torch
from pyro.optim import PyroOptim
from pyro.optim.lr_scheduler import PyroLRScheduler
__all__ = []
# Programmatically load all optimizers from PyTorch.
for _name, _Optim in torch.optim.__dict__.items():
if not isi... | 61 | 1,805 |
mlflow | mlflow/entities/trace_state.py | .py | from enum import Enum
from opentelemetry import trace as trace_api
from mlflow.protos import service_pb2 as pb
class TraceState(str, Enum):
"""Enum representing the state of a trace.
- ``STATE_UNSPECIFIED``: Unspecified trace state.
- ``OK``: Trace successfully completed.
- ``ERROR``: Trace encount... | 43 | 1,169 |
sqlmap | plugins/dbms/hana/enumeration.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
from lib.core.data import logger
from plugins.generic.enumeration import Enumeration as GenericEnumeration
class Enumeration(GenericEnumeration):
def getPasswordHashes(self):... | 17 | 461 |
textual | docs/examples/styles/column_span.py | .py | from textual.app import App
from textual.containers import Grid
from textual.widgets import Placeholder
class MyApp(App):
CSS_PATH = "column_span.tcss"
def compose(self):
yield Grid(
Placeholder(id="p1"),
Placeholder(id="p2"),
Placeholder(id="p3"),
Plac... | 24 | 511 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.