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 |
|---|---|---|---|---|---|
saleor | saleor/shipping/tests/test_tasks.py | .py | import datetime
from django.utils import timezone
from freezegun import freeze_time
from ...checkout.models import Checkout
from ...order import OrderStatus
from ...order.models import Order
from ..tasks import drop_invalid_shipping_methods_relations_for_given_channels
@freeze_time()
def test_drop_invalid_shipping_... | 111 | 3,832 |
saleor | saleor/__main__.py | .py | import uvicorn
config = uvicorn.Config(
"saleor.asgi:application", port=8000, reload=True, lifespan="on"
)
server = uvicorn.Server(config)
server.run()
| 8 | 157 |
pyomo | pyomo/core/tests/unit/kernel/test_dict_container.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... | 972 | 36,991 |
pyomo | examples/pyomo/piecewise/convex.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... | 50 | 1,763 |
kombu | t/unit/utils/test_debug.py | .py | from __future__ import annotations
import logging
from unittest.mock import Mock, patch
import pytest
from kombu.utils.debug import Logwrapped, setup_logging
class test_setup_logging:
def test_adds_handlers_sets_level(self):
with patch('kombu.utils.debug.get_logger') as get_logger:
logger ... | 116 | 3,830 |
python-prompt-toolkit | src/prompt_toolkit/contrib/ssh/__init__.py | .py | from __future__ import annotations
from .server import PromptToolkitSSHServer, PromptToolkitSSHSession
__all__ = [
"PromptToolkitSSHSession",
"PromptToolkitSSHServer",
]
| 9 | 180 |
qutip | qutip/core/semidefinite.py | .py | """
This module implements internal-use functions for semidefinite programming.
"""
import collections
import functools
import numpy as np
import scipy.sparse as sp
# Conditionally import CVXPY
try:
import cvxpy
__all__ = ["dnorm_problem", "dnorm_sparse_problem"]
except ImportError:
cvxpy = None
__al... | 162 | 4,886 |
hydra | tests/test_apps/app_with_pickle_job_info_callback/my_app.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
import pickle
from pathlib import Path
from typing import Any
from omegaconf import DictConfig
import hydra
from hydra.core.hydra_config import HydraConfig
from hydra.utils import target_whitelist
log = logging.getLogger(__name__)... | 35 | 912 |
sphinx | tests/roots/test-ext-autodoc/target/docstring_signature.py | .py | class A:
"""A(foo, bar)"""
class B:
"""B(foo, bar)"""
def __init__(self):
"""B(foo, bar, baz)"""
class C:
"""C(foo, bar)"""
def __new__(cls):
"""C(foo, bar, baz)"""
class D:
def __init__(self):
"""D(foo, bar, baz)"""
class E:
def __init__(self):
r"""... | 36 | 672 |
saleor | saleor/tests/e2e/checkout/discounts/vouchers/test_checkout_unable_to_use_expired_voucher.py | .py | import datetime
import pytest
from django.utils import timezone
from ....product.utils.preparing_product import prepare_product
from ....shop.utils import prepare_default_shop
from ....utils import assign_permissions
from ....vouchers.utils import (
create_voucher,
create_voucher_channel_listing,
get_vouc... | 166 | 4,828 |
probability | tensorflow_probability/python/optimizer/convergence_criteria/successive_gradients_are_uncorrelated_test.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... | 95 | 4,047 |
astropy | astropy/visualization/wcsaxes/grid_paths.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from matplotlib.lines import Path
from astropy.coordinates import angular_separation
# Tolerance for WCS round-tripping, relative to the scale size
ROUND_TRIP_RTOL = 1.0
# Tolerance for discontinuities relative to the median
DISCONT... | 121 | 3,977 |
saleor | saleor/graphql/shipping/mutations/shipping_zone_update.py | .py | import graphene
from ....permission.enums import ShippingPermissions
from ....shipping import models
from ...core import ResolveInfo
from ...core.context import ChannelContext
from ...core.doc_category import DOC_CATEGORY_SHIPPING
from ...core.mutations import DeprecatedModelMutation
from ...core.types import NonNullL... | 56 | 1,958 |
onnxruntime | onnxruntime/python/tools/transformers/models/whisper/whisper_encoder.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import ... | 166 | 6,208 |
beam | sdks/python/apache_beam/examples/snippets/transforms/aggregation/sample_fixed_size_globally.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");... | 60 | 1,779 |
coremltools | coremltools/converters/mil/mil/passes/defs/optimize_gelu_sigmoid.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
from coremltools.converters.mil.mil import Builder as mb
from coremltools.converters.mil.mil.passes.g... | 140 | 4,508 |
textual | docs/examples/guide/testing/test_rgb.py | .py | from rgb import RGBApp
from textual.color import Color
async def test_keys(): # (1)!
"""Test pressing keys has the desired result."""
app = RGBApp()
async with app.run_test() as pilot: # (2)!
# Test pressing the R key
await pilot.press("r") # (3)!
assert app.screen.styles.backg... | 43 | 1,387 |
coremltools | coremltools/optimize/coreml/_post_training_quantization.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 collections import OrderedDict
from typing import Dict, List, Optional
import numpy as np
from att... | 759 | 29,982 |
metrics | src/torchmetrics/classification/roc.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... | 597 | 30,543 |
onnxruntime | onnxruntime/python/tools/transformers/models/bart/export.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import ... | 99 | 4,187 |
django-cms | cms/management/commands/cms.py | .py | from collections import OrderedDict
import cms
from .subcommands.base import SubcommandsCommand
from .subcommands.check import CheckInstallation
from .subcommands.copy import CopyCommand
from .subcommands.delete_orphaned_plugins import DeleteOrphanedPluginsCommand
from .subcommands.list import ListCommand
from .subco... | 34 | 1,084 |
django-cms | cms/forms/validators.py | .py | from typing import TYPE_CHECKING, Optional
from urllib.parse import urlsplit
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator, URLValidator
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.translation import gettext... | 103 | 3,878 |
pyomo | examples/pyomobook/gdp-ch/gdp_uc.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... | 123 | 3,592 |
mlflow | tests/store/tracking/sqlalchemy_store/test_sqlalchemy_store_runs.py | .py | import contextlib
import json
import math
import re
import time
import uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from unittest import mock
import pytest
import sqlalchemy
from packaging.version import Version
import mlflow
from mlflow import entities
from mlflow.entities import (... | 4,264 | 158,872 |
saleor | saleor/graphql/csv/types.py | .py | import graphene
from ...core.utils import build_absolute_uri
from ...csv import models
from ...permission.auth_filters import AuthorizationFilters
from ...permission.enums import AccountPermissions, AppPermission
from ..account.types import User
from ..account.utils import check_is_owner_or_has_one_of_perms
from ..app... | 124 | 4,457 |
kafka | tests/kafkatest/tests/core/transactions_mixed_versions_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 use ... | 247 | 12,527 |
qutip | qutip/core/blochredfield.py | .py | # Required for Sphinx to follow autodoc_type_aliases
from __future__ import annotations
import os
import inspect
import numpy as np
from typing import overload, Union
from qutip.settings import settings as qset
from . import Qobj, QobjEvo, liouvillian, coefficient, sprepost
from ._brtools import SpectraCoefficient, _... | 428 | 15,144 |
sqlmap | tests/test_bigarray.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
BigArray disk-spill semantics (lib/core/bigarray.py).
BigArray is the structure that lets sqlmap dump tables far larger than RAM: once
the in-memory chunk exceeds chunk_size it is pi... | 167 | 6,189 |
gunicorn | tests/docker/asgi_compliance/apps/http_app.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
"""
HTTP test application for ASGI compliance testing.
Provides various endpoints to test HTTP request/response handling,
headers, body processing, and ASGI scope inspection.
"""
import json
import time
async d... | 603 | 16,869 |
wandb | wandb/sdk/internal/sender_config.py | .py | from __future__ import annotations
import json
from collections.abc import Sequence
from typing import Any, NewType
from wandb.proto import wandb_internal_pb2
from wandb.sdk.lib import proto_util, telemetry
BackendConfigDict = NewType("BackendConfigDict", dict[str, Any])
"""Run config dictionary in the format used b... | 207 | 7,171 |
probability | tensorflow_probability/python/experimental/nn/affine_layers.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... | 601 | 22,879 |
saleor | saleor/tax/calculations/__init__.py | .py | from decimal import Decimal
from prices import Money, TaxedMoney
from ...core.prices import quantize_price
def calculate_flat_rate_tax(
money: "Money", tax_rate: "Decimal", prices_entered_with_tax: bool
) -> TaxedMoney:
currency = money.currency
tax_rate = Decimal(1 + tax_rate / 100)
if prices_ente... | 47 | 1,411 |
coremltools | coremltools/test/modelpackage/test_mlmodel_temp_cleanup.py | .py | # Copyright (c) 2026, 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
"""Regression tests for MLModel temporary .mlpackage cleanup.
Historically `MLModel` constructed from a... | 128 | 5,070 |
saleor | saleor/graphql/core/tests/test_file_upload.py | .py | import os
from unittest.mock import patch
from urllib.parse import urlparse
from django.core.files.storage import default_storage
from django.core.files.uploadedfile import SimpleUploadedFile
from ....core.error_codes import UploadErrorCode
from ....product.tests.utils import create_image
from ...tests.utils import (... | 283 | 9,158 |
python-prompt-toolkit | examples/full-screen/simple-demos/focus.py | .py | #!/usr/bin/env python
"""
Demonstration of how to programmatically focus a certain widget.
"""
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.document import Document
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.layout.container... | 100 | 2,774 |
probability | tensorflow_probability/python/bijectors/restructure.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... | 349 | 12,544 |
openvino | src/frontends/paddle/tests/test_models/gen_scripts/generate_hard_swish.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
# sigmoid paddle model generator
#
import numpy as np
from save_model import saveModel
import paddle
import sys
def hard_swish(name: str, x, threshold=6.0, scale=6.0, offset=3.0, data_type='float32'):
paddle.enable_static()
... | 46 | 1,390 |
onnx | onnx/reference/ops/aionnx_preview_training/_op_list.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
__all__ = [
"load_op",
"Adagrad",
"Adam",
"Momentum",
]
import textwrap
from typing import Any
from onnx.reference.op_run import OpFunction, OpRun
from onnx.reference.ops._helpers impor... | 90 | 2,864 |
onnx | onnx/reference/ops/op_resize.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import math
from typing import TYPE_CHECKING, Any
import numpy as np
import onnx
from onnx.reference.op_run import OpRun
if TYPE_CHECKING:
from collections.abc import Callable
def _cartesian(arr... | 666 | 23,331 |
coremltools | deps/pybind11/tests/test_constants_and_functions.py | .py | from __future__ import annotations
import pytest
m = pytest.importorskip("pybind11_tests.constants_and_functions")
def test_constants():
assert m.some_constant == 14
def test_function_overloading():
assert m.test_function() == "test_function()"
assert m.test_function(7) == "test_function(7)"
asser... | 59 | 1,587 |
mlflow | mlflow/pyfunc/spark_model_cache.py | .py | from mlflow.utils._spark_utils import _SparkDirectoryDistributor
class SparkModelCache:
"""Caches models in memory on Spark Executors, to avoid continually reloading from disk.
This class has to be part of a different module than the one that _uses_ it. This is
because Spark will pickle classes that are ... | 49 | 2,091 |
probability | tensorflow_probability/python/internal/backend/numpy/tensor_array_ops_test.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... | 98 | 3,207 |
saleor | saleor/graphql/discount/mutations/__init__.py | .py | from .promotion.promotion_bulk_delete import PromotionBulkDelete
from .promotion.promotion_create import PromotionCreate
from .promotion.promotion_delete import PromotionDelete
from .promotion.promotion_rule_create import PromotionRuleCreate
from .promotion.promotion_rule_delete import PromotionRuleDelete
from .promoti... | 44 | 1,691 |
conda | conda/_private/shards/typing.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""
TypedDict declarations for shards.
These are helpful for auto-complete, but do not validate at runtime and are not
normative. They are intentionally not shared with another project (conda) to
reduce coupling.
"""
from __future__ import ann... | 72 | 1,652 |
django-cms | cms/plugin_rendering.py | .py | import contextlib
import logging
import sys
from collections import OrderedDict
from collections.abc import Generator
from functools import partial
from typing import Any
from classytags.utils import flatten_context
from django.conf import settings
from django.contrib.sites.models import Site
from django.db import mod... | 799 | 31,315 |
saleor | saleor/thumbnail/utils.py | .py | import mimetypes
import os
import secrets
from io import BytesIO
from typing import TYPE_CHECKING, Optional
from urllib.parse import urlparse
import graphene
import magic
from django.core.files import File
from django.core.files.storage import default_storage
from django.urls import reverse
from PIL import Image
from... | 287 | 10,218 |
saleor | saleor/tests/e2e/orders/test_bulk_delete_draft_orders.py | .py | import pytest
from .. import DEFAULT_ADDRESS
from ..product.utils.preparing_product import prepare_product
from ..shop.utils.preparing_shop import prepare_default_shop
from ..utils import assign_permissions
from .utils import (
draft_order_bulk_delete,
draft_order_create,
order_lines_create,
order_quer... | 83 | 2,214 |
loguru | tests/exceptions/source/ownership/catch_decorator_from_lib.py | .py | import sys
import _init
from somelib import callme, divide
from loguru import logger
def test(*, backtrace, colorize, diagnose):
logger.remove()
logger.add(sys.stderr, format="", colorize=colorize, backtrace=backtrace, diagnose=diagnose)
@logger.catch
def callback():
divide(1, 0)
callm... | 25 | 596 |
textual | docs/examples/guide/structure.py | .py | from datetime import datetime
from textual.app import App
from textual.widget import Widget
class Clock(Widget):
"""A clock app."""
DEFAULT_CSS = """
Clock {
content-align: center middle;
}
"""
def on_mount(self):
self.set_interval(1, self.refresh)
def render(self):
... | 31 | 494 |
openvino | tests/layer_tests/common/utils/tflite_utils.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import itertools
import os
import warnings
import numpy as np
import tensorflow as tf
from common.utils.tf_utils import summarize_graph
def make_positive_array(inputs_dict):
for input in inputs_dict.keys():
inputs_dict[in... | 148 | 4,796 |
returns | tests/test_iterables/test_fold/test_collect.py | .py | import sys
from collections.abc import Iterable, Sequence
import pytest
from returns.context import (
NoDeps,
Reader,
ReaderFutureResult,
ReaderIOResult,
ReaderResult,
)
from returns.future import Future, FutureFailure, FutureResult, FutureSuccess
from returns.io import IO, IOFailure, IOSuccess
fr... | 227 | 7,065 |
scikit-bio | skbio/sequence/_substitution.py | .py | # ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# --------------------------------------------... | 733 | 30,824 |
kombu | t/unit/transport/test_native_delayed_delivery.py | .py | from __future__ import annotations
import logging
from unittest.mock import Mock, call
import pytest
from kombu.transport.native_delayed_delivery import (
CELERY_DELAYED_DELIVERY_EXCHANGE,
bind_queue_to_native_delayed_delivery_exchange, calculate_routing_key,
declare_native_delayed_delivery_exchanges_and... | 169 | 6,401 |
wandb | tests/system_tests/test_functional/keras/keras_model_checkpoint.py | .py | import numpy as np
import tensorflow as tf
import wandb
from wandb.integration.keras import WandbModelCheckpoint
run = wandb.init(project="keras")
x = np.random.randint(255, size=(100, 28, 28, 1))
y = np.random.randint(10, size=(100,))
dataset = (x, y)
def get_model():
m = tf.keras.Sequential()
m.add(tf.ke... | 47 | 991 |
sphinx | sphinx/ext/viewcode.py | .py | """Add links to module code in Python object descriptions."""
from __future__ import annotations
import importlib
import operator
import posixpath
import traceback
from types import NoneType
from typing import TYPE_CHECKING, cast
from docutils import nodes
from docutils.nodes import Element
import sphinx
from sphin... | 418 | 15,350 |
pyomo | examples/pyomobook/abstract-ch/param8a.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... | 24 | 839 |
pyro | pyro/nn/dense_nn.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
from typing import List, Sequence, Union
import torch
class ConditionalDenseNN(torch.nn.Module):
"""
An implementation of a simple dense feedforward network taking a context variable, for use in, e.g.,
some condition... | 141 | 5,615 |
cvxpy | cvxpy/reductions/dcp2cone/canonicalizers/quad/quad_over_lin_canon.py | .py | """
Copyright 2017 Robin Verschueren
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, softw... | 122 | 4,243 |
saleor | saleor/graphql/attribute/sorters.py | .py | from ..core.doc_category import DOC_CATEGORY_ATTRIBUTES
from ..core.types import BaseEnum, SortInputObjectType
class AttributeSortField(BaseEnum):
NAME = ["name", "slug"]
SLUG = ["slug"]
VALUE_REQUIRED = ["value_required", "name", "slug"]
IS_VARIANT_ONLY = ["is_variant_only", "name", "slug"]
VISIB... | 83 | 3,901 |
httpie | httpie/output/processing.py | .py | import re
from typing import Optional, List
from ..plugins import ConverterPlugin
from ..plugins.registry import plugin_manager
from ..context import Environment
MIME_RE = re.compile(r'^[^/]+/[^/]+$')
def is_valid_mime(mime):
return mime and MIME_RE.match(mime)
class Conversion:
@staticmethod
def ge... | 59 | 1,763 |
jupytext | tests/data/notebooks/outputs/ipynb_to_hydrogen/convert_to_py_then_test_with_update83.py | .py | # ---
# jupyter:
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %%
%%time
print('asdf')
# %% [markdown]
# Thanks for jupytext!
# %%
| 18 | 185 |
onnxruntime | onnxruntime/core/flatbuffers/ort_flatbuffers_py/fbs/DeprecatedNodeIndexAndKernelDefHash.py | .py | # automatically generated by the FlatBuffers compiler, do not modify
# namespace: fbs
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()
# deprecated: no longer using kernel def hashes
class DeprecatedNodeIndexAndKernelDefHash(object):
__slots__ = ['_tab']
@classmethod
de... | 69 | 2,458 |
onnx | onnx/reference/ops/aionnxml/op_feature_vectorizer.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.aionnxml._op_run_aionnxml import OpRunAiOnnxMl
class FeatureVectorizer(OpRunAiOnnxMl):
def _preprocess(self, a, cut):
if len(a.shape) == 1:
... | 32 | 936 |
probability | tensorflow_probability/python/bijectors/categorical_to_discrete_test.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... | 133 | 5,754 |
deap | doc/code/tutorials/part_3/multistats.py | .py | import operator
import random
import numpy
from deap import algorithms
from deap import base
from deap import creator
from deap import gp
from deap import tools
random.seed(0)
stats_fit = tools.Statistics(key=lambda ind: ind.fitness.values)
stats_size = tools.Statistics(key=len)
mstats = tools.MultiStatistics(fitne... | 56 | 1,792 |
loguru | tests/exceptions/source/backtrace/nested_decorator_catch_up.py | .py | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", colorize=False, backtrace=False, diagnose=False)
logger.add(sys.stderr, format="", colorize=False, backtrace=True, diagnose=False)
@logger.catch(ZeroDivisionError)
def foo():
bar()
@logger.catch(NotImplementedError)
def bar... | 21 | 342 |
openvino | tests/layer_tests/pytorch_tests/test_gelu.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
from pytorch_layer_test_class import PytorchLayerTest
class TestGelu(PytorchLayerTest):
def _prepare_input(self):
return (self.random.randn(2, 3),)
def create_model(self, approximate):
import tor... | 34 | 1,004 |
textual | tests/test_content_switcher.py | .py | from __future__ import annotations
import pytest
from textual.app import App, ComposeResult
from textual.css.query import NoMatches
from textual.widget import Widget
from textual.widgets import ContentSwitcher
class SwitcherApp(App[None]):
def __init__(self, initial: str | None = None) -> None:
super().... | 123 | 5,202 |
hatch | src/hatch/cli/publish/__init__.py | .py | import click
from hatch.config.constants import PublishEnvVars
@click.command(short_help="Publish build artifacts")
@click.argument("artifacts", nargs=-1)
@click.option(
"--repo",
"-r",
envvar=PublishEnvVars.REPO,
help="The repository with which to publish artifacts [env var: `HATCH_INDEX_REPO`]",
)
... | 116 | 3,628 |
astropy | astropy/visualization/wcsaxes/tests/test_transform_coord_meta.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from matplotlib.figure import Figure
from astropy import units as u
from astropy.tests.figures import figure_test
from astropy.visualization.wcsaxes import WCSAxes
from astropy.visualization.wcsaxes.transforms import CurvedTransform
f... | 156 | 4,721 |
pyomo | pyomo/solvers/tests/piecewise_linear/kernel_problems/concave_var.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... | 53 | 1,680 |
wagtail | wagtail/admin/tests/pages/test_convert_alias.py | .py | from django.contrib.auth.models import Permission
from django.test import TestCase
from django.urls import reverse
from wagtail.models import PageLogEntry
from wagtail.test.testapp.models import SimplePage
from wagtail.test.utils import Page, WagtailTestUtils
class TestConvertAlias(WagtailTestUtils, TestCase):
d... | 90 | 3,065 |
sphinx | tests/roots/test-ext-autosummary-import_cycle/spam/eggs.py | .py | """``spam.eggs`` module docstring."""
import spam # Required for test.
class Ham:
"""``spam.eggs.Ham`` class docstring."""
a = 1
b = 2
c = 3
| 12 | 162 |
probability | tensorflow_probability/python/math/psd_kernels/internal/test_util_test.py | .py | # Copyright 2022 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... | 41 | 1,702 |
saleor | saleor/graphql/product/tests/queries/variants_where/test_over_attributes_date.py | .py | import datetime
import pytest
from ......attribute import AttributeInputType, AttributeType
from ......attribute.models import Attribute
from ......attribute.utils import associate_attribute_values_to_instance
from .....tests.utils import get_graphql_content
from .shared import PRODUCT_VARIANTS_WHERE_QUERY
@pytest.... | 105 | 3,307 |
loguru | tests/exceptions/source/others/message_formatting_with_decorator.py | .py | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="{message}", diagnose=False, backtrace=False, colorize=False)
@logger.catch(message="{record[name]} {record[file].name} {record[function]} {record[line]}")
def a():
1 / 0
a()
| 15 | 268 |
textual | src/textual/demo/_project_stargazer_updater.py | .py | import httpx
import os
import json
from rich.console import Console
# Not using the Absolute reference because
# I can't get python to run it.
from _project_data import PROJECTS
console = Console()
error_console = Console(stderr=True, style="bold red")
def main() -> None:
STARS = {}
for project in PROJECTS... | 51 | 1,523 |
saleor | saleor/tests/e2e/checkout/test_checkout_create_order_with_no_payment.py | .py | import pytest
from ..product.utils.preparing_product import prepare_product
from ..shop.utils import prepare_shop
from ..utils import assign_permissions
from .utils import (
checkout_create,
checkout_delivery_method_update,
raw_checkout_complete,
)
@pytest.mark.e2e
def test_should_be_able_to_create_order... | 108 | 3,016 |
returns | tests/test_primitives/test_exceptions/test_pickle_unwrap_failed_error.py | .py | import pickle # noqa: S403
from returns.maybe import Nothing
from returns.primitives.exceptions import UnwrapFailedError
from returns.result import Failure
def test_pickle_unwrap_failed_error_from_maybe():
"""Ensures that UnwrapFailedError with Maybe can be pickled."""
serialized = None
try:
Not... | 30 | 1,010 |
textual | docs/examples/widgets/button.py | .py | from textual.app import App, ComposeResult
from textual.containers import Horizontal, VerticalScroll
from textual.widgets import Button, Static
class ButtonsApp(App[str]):
CSS_PATH = "button.tcss"
def compose(self) -> ComposeResult:
yield Horizontal(
VerticalScroll(
Static... | 52 | 2,008 |
textual | docs/examples/tutorial/stopwatch06.py | .py | from time import monotonic
from textual.app import App, ComposeResult
from textual.containers import HorizontalGroup, VerticalScroll
from textual.reactive import reactive
from textual.widgets import Button, Digits, Footer, Header
class TimeDisplay(Digits):
"""A widget to display elapsed time."""
start_time ... | 93 | 2,960 |
saleor | saleor/graphql/discount/tests/benchmark/test_sales.py | .py | import pytest
from ....tests.utils import get_graphql_content
SALES_QUERY = """
query GetSales($channel: String){
sales(last: 10, channel: $channel) {
edges {
node {
id
name
type
startDate
endDate
categories(first: 10) {
edges {
node {
... | 100 | 1,999 |
onnxruntime | tools/ci_build/github/linux/ort_minimal/readelf_utils.py | .py | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""
Utilities to help analyze the sections in a binary using readelf.
"""
import argparse
import collections
import os
import re
import subprocess
import sys
def get_section_sizes(binary_path, readelf... | 130 | 4,401 |
conda | tests/core/test_link.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
import pytest
from conda.core import link
from conda.core.link import UnlinkLinkTransaction
from conda.core.path_actions import RemoveLinkedPackageRecordAction
from conda.models.records import PackageRecord, PrefixRecord
def test_make_unlink... | 308 | 8,929 |
onnx | onnx/reference/ops/op_sinh.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 OpRunUnaryNum
class Sinh(OpRunUnaryNum):
def _run(self, x):
return (np.sinh(x),)
| 14 | 267 |
hatch | tests/cli/check/test_check_group.py | .py | from __future__ import annotations
import pytest
from hatch.config.constants import ConfigEnvVars
class TestNoSubcommand:
"""Tests that `hatch check` with no subcommand runs all checks."""
def test_runs_all_checks(self, hatch, temp_dir, config_file, env_run):
config_file.model.template.plugins["def... | 139 | 5,149 |
onnxruntime | onnxruntime/python/tools/transformers/models/whisper/benchmark.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import ... | 586 | 21,862 |
wandb | wandb/sandbox/_sandbox.py | .py | from __future__ import annotations
from collections.abc import Callable, Mapping, Sequence
from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar
from cwsandbox import RemoteFunction, SandboxDefaults
from cwsandbox import Sandbox as _BaseSandbox
from cwsandbox import Session as _BaseSession
from wandb.errors impo... | 142 | 4,332 |
hypercorn | tests/asyncio/helpers.py | .py | from __future__ import annotations
import asyncio
from ..helpers import MockSocket
class MockSSLObject:
def selected_alpn_protocol(self) -> str:
return "h2"
class MemoryReader:
def __init__(self) -> None:
self.data: asyncio.Queue = asyncio.Queue()
self.eof = False
async def se... | 67 | 1,594 |
textual | src/textual/clock.py | .py | from __future__ import annotations
from time import monotonic
from typing import Callable
import rich.repr
@rich.repr.auto(angular=True)
class Clock:
"""An object to get relative time.
The `time` attribute of clock will return the time in seconds since the
Clock was created or reset.
"""
def ... | 75 | 2,022 |
openvino | src/bindings/python/src/openvino/opset1/__init__.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.opset1.ops import absolute
from openvino.opset1.ops import absolute as abs
from openvino.opset1.ops import acos
from openvino.opset1.ops import add
from openvino.opset1.ops import asin
from openvino.... | 112 | 4,633 |
kafka | tests/kafkatest/tests/verifiable_share_consumer_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 use ... | 106 | 5,523 |
black | tests/data/cases/collections.py | .py | import core, time, a
from . import A, B, C
# keeps existing trailing comma
from foo import (
bar,
)
# also keeps existing structure
from foo import (
baz,
qux,
)
# `as` works as well
from foo import (
xyzzy as magic,
)
a = {1,2,3,}
b = {
1,2,
3}
c = {
1,
2,
3,
}
x = 1,
y = narf(),
... | 175 | 3,294 |
readthedocs.org | readthedocs/oauth/tests/test_githubapp_webhook.py | .py | import json
from unittest import mock
from readthedocs.builds.constants import ALL_VERSIONS
from readthedocs.projects.models import AutomationRule
import requests_mock
from allauth.socialaccount.models import SocialAccount
from django.conf import settings
from django.contrib.auth.models import User
from django.test im... | 1,838 | 66,915 |
black | src/blib2to3/pgen2/grammar.py | .py | # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""This module defines the data structures used to represent a grammar.
These are a bit arcane because they are derived from the data
structures used by Python's 'pgen' parser generator.
There's also ... | 229 | 6,846 |
onnxruntime | onnxruntime/test/testdata/test_shape_data_propagation_decline_combined.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# Combined lock fixture for the two custom data-propagation DECLINE paths guarded by
# microsoft/onnxruntime#29072, exercised through a SINGLE shared graph so the regression
# is covered by one onnxruntime::Model::Load instea... | 97 | 5,928 |
luigi | test/contrib/dataproc_test.py | .py | """This is an integration test for the Dataproc-luigi binding.
This test requires credentials that can access GCS & access to a bucket below.
Follow the directions in the gcloud tools to set up local credentials.
"""
import unittest
try:
import google.auth
from googleapiclient import discovery
from luig... | 169 | 6,362 |
onnxruntime | onnxruntime/test/testdata/shape_then_slice_and_gather.py | .py | from pathlib import Path
import onnx
from onnx import helper
from onnx.onnx_pb import TensorProto
nodes = [
helper.make_node("Shape", ["X"], ["X_shape"]),
helper.make_node("Gather", ["X_shape", "gather_indices"], ["gather_out"], axis=0),
helper.make_node("Slice", ["X_shape", "slice_starts", "slice_ends", ... | 34 | 1,264 |
sphinx | sphinx/ext/napoleon/docstring.py | .py | """Classes for docstring parsing and formatting."""
from __future__ import annotations
import collections
import contextlib
import inspect
import re
from functools import partial
from itertools import starmap
from typing import TYPE_CHECKING, Any
from sphinx.locale import _, __
from sphinx.util import logging
from s... | 1,438 | 51,058 |
attrs | src/attrs/filters.py | .py | # SPDX-License-Identifier: MIT
from attr.filters import * # noqa: F403
| 4 | 73 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.