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 |
|---|---|---|---|---|---|
bazel | tools/aquery_differ/aquery_differ.py | .py | # Copyright 2020 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | 314 | 11,418 |
scikit-bio | skbio/io/format/tests/test_embl.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.
# --------------------------------------------... | 889 | 36,313 |
saleor | saleor/graphql/core/fields.py | .py | from functools import wraps
from json import JSONDecodeError
import graphene
from django.conf import settings
from graphene.relay import Connection, is_node
from ...permission.utils import message_one_of_permissions_required
from ..decorators import one_of_permissions_required
from .connection import FILTERS_NAME, FI... | 177 | 6,367 |
pyomo | pyomo/contrib/piecewise/ordered_3d_j1_triangulation_data.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... | 3,118 | 116,096 |
pyomo | pyomo/contrib/iis/__init__.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... | 12 | 659 |
mlflow | examples/pytorch/CaptumExample/Titanic_Captum_Interpret.py | .py | """
Getting started with Captum - Titanic Data Analysis
"""
# Initial imports
import os
from argparse import ArgumentParser
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
from captum.attr import IntegratedGradients, LayerConductance, NeuronConductance
from prettytable import Prett... | 347 | 14,340 |
sphinx | tests/roots/test-ext-autodoc/target/singledispatchmethod.py | .py | from functools import singledispatchmethod
class Foo:
"""docstring"""
@singledispatchmethod
def meth(self, arg, kwarg=None):
"""A method for general use."""
pass
@meth.register(int)
@meth.register(float)
def _meth_int(self, arg, kwarg=None):
"""A method for int."""
... | 28 | 628 |
biopython | Tests/test_SearchIO_infernal_tab.py | .py | # Copyright 2024 by Samuel Prince. 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.
"""Tests for SearchIO In... | 507 | 20,153 |
python-prompt-toolkit | examples/progress-bar/styled-tqdm-1.py | .py | #!/usr/bin/env python
"""
Styled similar to tqdm, another progress bar implementation in Python.
See: https://github.com/noamraph/tqdm
"""
import time
from prompt_toolkit.shortcuts import ProgressBar
from prompt_toolkit.shortcuts.progress_bar import formatters
from prompt_toolkit.styles import Style
style = Style.f... | 42 | 1,109 |
cvxpy | cvxpy/utilities/bounds.py | .py | """
Copyright 2026 The 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, so... | 902 | 26,681 |
textual | tests/tree/test_tree_node_parent.py | .py | from textual.widgets import Tree
async def test_tree_node_parent() -> None:
"""It should be possible to access a TreeNode's parent."""
tree = Tree[None]("Anakin")
child = tree.root.add("Leia")
grandchild = child.add("Ben")
assert tree.root.parent is None
assert grandchild.parent == child
a... | 12 | 352 |
saleor | saleor/graphql/menu/enums.py | .py | import graphene
class NavigationType(graphene.Enum):
MAIN = "main"
SECONDARY = "secondary"
@property
def description(self):
if self == NavigationType.MAIN:
return "Main storefront navigation."
if self == NavigationType.SECONDARY:
return "Secondary storefront na... | 15 | 397 |
beam | learning/tour-of-beam/learning-content/windowing/motivating-challenge/python-solution/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"); y... | 74 | 2,256 |
onnxruntime | onnxruntime/test/python/onnxruntime_test_python_iobinding.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# pylint: disable=C0115,W0212,C0103,C0114
import unittest
import numpy as np
from helper import get_name
from numpy.testing import assert_almost_equal
from onnx import TensorProto, helper
import onnxruntime as onnxrt
from o... | 477 | 21,874 |
coremltools | coremltools/proto/Gazetteer_pb2.py | .py | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: Gazetteer.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from go... | 42 | 1,765 |
probability | tensorflow_probability/python/internal/backend/numpy/functional_ops.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... | 185 | 5,825 |
mlflow | tests/genai/utils/test_data_validation.py | .py | import pytest
import mlflow
from mlflow.exceptions import MlflowException
from mlflow.genai.utils.data_validation import check_model_prediction
from tests.tracing.helper import get_traces
def _extract_code_example(e: MlflowException) -> str:
"""Extract the code example from the exception message."""
return ... | 202 | 6,041 |
beam | sdks/python/apache_beam/typehints/native_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... | 579 | 22,054 |
conda | conda/cli/helpers.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""
Collection of helper functions to standardize reused CLI arguments.
"""
from __future__ import annotations
from argparse import (
SUPPRESS,
Action,
BooleanOptionalAction,
_AppendAction,
_HelpAction,
_StoreAction,
)
... | 673 | 21,937 |
pdm | src/pdm/cli/commands/fix/fixers.py | .py | import abc
import re
import shutil
from pathlib import Path
from pdm.project import Config, Project
from pdm.project.lockfile import FLAG_CROSS_PLATFORM
from pdm.termui import Verbosity
from pdm.utils import parse_version
class BaseFixer(abc.ABC):
"""Base class for fixers"""
# A unique identifier for the fi... | 160 | 5,607 |
hypercorn | src/hypercorn/protocol/quic.py | .py | from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from functools import partial
from aioquic.buffer import Buffer
from aioquic.h3.connection import H3_ALPN
from aioquic.quic.configuration import QuicConfiguration
from aioquic.quic.connection import Qu... | 158 | 5,761 |
saleor | saleor/discount/interface.py | .py | from dataclasses import dataclass
from decimal import Decimal
from typing import TYPE_CHECKING, NamedTuple, Optional
from . import DiscountType, DiscountValueType
from .models import PromotionRule, Voucher
if TYPE_CHECKING:
from ..product.models import (
ProductVariantChannelListing,
VariantChanne... | 135 | 4,318 |
django-cms | cms/tests/test_permmod.py | .py | from unittest.mock import patch
from django.contrib.admin.sites import site
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, Group, Permission
from django.contrib.sites.models import Site
from django.db.models import Q
from django.test.client import RequestFactory
fr... | 676 | 27,912 |
astropy | astropy/units/core.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Core units classes and functions.
"""
import inspect
import operator
import textwrap
import unicodedata
import warnings
from collections.abc import Collection, Iterable, Mapping, MutableMapping, Sequence
from contextlib import ContextDecorator
from f... | 2,835 | 97,924 |
textual | docs/examples/widgets/text_area_custom_language.py | .py | from pathlib import Path
from tree_sitter_languages import get_language
from textual.app import App, ComposeResult
from textual.widgets import TextArea
java_language = get_language("java")
java_highlight_query = (Path(__file__).parent / "java_highlights.scm").read_text()
java_code = """\
class HelloWorld {
publi... | 35 | 885 |
qutip | qutip/solver/brmesolve.py | .py | """
This module provides solvers for the Lindblad master equation and von Neumann
equation.
"""
# Required for Sphinx to follow autodoc_type_aliases
from __future__ import annotations
__all__ = ['brmesolve', 'BRSolver']
from typing import Any
import warnings
import numpy as np
from numpy.typing import ArrayLike
impor... | 419 | 15,988 |
sphinx | tests/roots/test-ext-autodoc/circular_import/c.py | .py | import circular_import.a
import circular_import.b
class SomeClass:
X = circular_import.a.X
| 7 | 97 |
astropy | astropy/units/cds.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This package defines units used in the CDS format, both the units
defined in `Centre de Données astronomiques de Strasbourg
<https://cds.unistra.fr/>`_ `Standards for Astronomical Catalogues 2.0
<https://vizier.unistra.fr/vizier/doc/catstd-3.2.htx>`_ ... | 213 | 7,638 |
pyro | pyro/distributions/transforms/affine_autoregressive.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
from functools import partial
import torch
import torch.nn as nn
from pyro.nn import AutoRegressiveNN, ConditionalAutoRegressiveNN
from .. import constraints
from ..conditional import ConditionalTransformModule
from ..torch_tran... | 410 | 16,342 |
saleor | saleor/graphql/shipping/tests/mutations/test_shipping_zone_delete.py | .py | import json
from unittest import mock
import graphene
import pytest
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
from .....core.utils.json_serializer import CustomJsonEncoder
from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.payloads import generate... | 103 | 3,029 |
readthedocs.org | readthedocs/aws/tests/test_security_token_service.py | .py | import json
from unittest import mock
from django.contrib.auth.models import User
from django.test import TestCase, override_settings
from django_dynamic_fixture import get
from readthedocs.builds.constants import EXTERNAL
from readthedocs.builds.models import Build
from readthedocs.projects.models import Project
fro... | 294 | 12,421 |
wagtail | wagtail/tasks.py | .py | from django.apps import apps
from django.db import transaction
from django.utils.module_loading import import_string
from django_tasks import task
from modelcluster.fields import ParentalKey
from wagtail.models import ReferenceIndex
@task()
def update_reference_index_task(app_label, model_name, pk):
model = apps... | 42 | 1,328 |
saleor | saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_payment_method_request_delete.py | .py | import json
import graphene
from ....payment.interface import StoredPaymentMethodRequestDeleteData
from ...event_types import WebhookEventSyncType
from ...transport.asynchronous import create_deliveries_for_subscriptions
STORED_PAYMENT_METHOD_DELETE_REQUESTED = """
subscription {
event {
... on StoredPaymentMe... | 55 | 1,486 |
saleor | saleor/graphql/order/mutations/order_capture.py | .py | import graphene
from django.core.exceptions import ValidationError
from ....order.actions import order_charged
from ....order.error_codes import OrderErrorCode
from ....order.fetch import fetch_order_info
from ....payment import TransactionKind, gateway
from ....payment import models as payment_models
from ....permiss... | 103 | 3,546 |
django-cms | cms/middleware/user.py | .py | """This is ugly, but seems there's no other way how to do what we need for
permission system.
This middleware is required only when CMS_PERMISSION = True.
"""
class CurrentUserMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
from cms... | 22 | 712 |
flit | flit_core/tests_core/test_sdist.py | .py | from io import BytesIO
import os.path as osp
from pathlib import Path
import tarfile
from testpath import assert_isfile
from flit_core import sdist
samples_dir = Path(__file__).parent / 'samples'
def test_make_sdist(tmp_path):
# Smoke test of making a complete sdist
builder = sdist.SdistBuilder.from_ini_path... | 85 | 2,616 |
saleor | saleor/webhook/observability/tests/conftest.py | .py | import json
from unittest.mock import patch
import fakeredis
import pytest
from django.core.cache import cache
from graphql import get_default_backend
from redis import ConnectionPool
from ....graphql.api import schema
from ..buffers import RedisBuffer
from ..utils import GraphQLOperationResponse, get_buffer_name
ba... | 80 | 2,002 |
coremltools | deps/pybind11/tests/test_pickling.py | .py | from __future__ import annotations
import pickle
import re
import pytest
import env
from pybind11_tests import pickling as m
def test_pickle_simple_callable():
assert m.simple_callable() == 20220426
if env.PYPY:
serialized = pickle.dumps(m.simple_callable)
deserialized = pickle.loads(serial... | 96 | 2,756 |
mamba | libmambapy/tests/test_legacy.py | .py | import libmambapy
def test_context_instance_scoped():
ctx = libmambapy.Context() # Initialize and then terminate libmamba internals
assert ctx is not None
def test_context_no_log_nor_signal_handling():
ctx = libmambapy.Context(
libmambapy.ContextOptions(enable_logging=False, enable_signal_handl... | 28 | 952 |
metrics | src/torchmetrics/classification/specificity.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... | 514 | 23,645 |
wagtail | wagtail/utils/decorators.py | .py | import functools
from django.utils.functional import cached_property
# Need to inherit from object explicitly, to turn ``cached_classmethod`` in to
# a new-style class. WeakKeyDictionary is an old-style class, which do not
# support descriptors.
class cached_classmethod(dict):
"""
Cache the result of a no-ar... | 83 | 2,435 |
pyro | pyro/distributions/one_two_matching.py | .py | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import logging
import math
import warnings
import torch
from torch.distributions import constraints
from torch.distributions.utils import lazy_property
from .torch import Categorical
from .torch_distribution import TorchDistribution
... | 213 | 8,193 |
beam | sdks/python/apache_beam/io/azure/blobstoragefilesystem.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... | 332 | 10,973 |
pyfilesystem2 | tests/test_filesize.py | .py | from __future__ import unicode_literals
import unittest
from fs import filesize
class TestFilesize(unittest.TestCase):
def test_traditional(self):
self.assertEqual(filesize.traditional(0), "0 bytes")
self.assertEqual(filesize.traditional(1), "1 byte")
self.assertEqual(filesize.tradition... | 52 | 1,666 |
readthedocs.org | readthedocs/projects/notifications.py | .py | """Notifications related to projects."""
import textwrap
from django.utils.translation import gettext_noop as _
from readthedocs.notifications.constants import ERROR
from readthedocs.notifications.constants import INFO
from readthedocs.notifications.constants import WARNING
from readthedocs.notifications.messages im... | 244 | 9,001 |
black | tests/data/cases/fmtskip4.py | .py | a = 2
# fmt: skip
l = [1, 2, 3,]
# output
a = 2
# fmt: skip
l = [
1,
2,
3,
] | 13 | 92 |
saleor | saleor/tests/e2e/orders/taxes/test_order_calculate_simple_taxes_based_on_shipping_address.py | .py | import pytest
from ... import ADDRESS_DE
from ...product.utils.preparing_product import prepare_product
from ...shop.utils.preparing_shop import prepare_shop
from ...taxes.utils import update_country_tax_rates
from ...utils import assign_permissions
from ..utils import (
draft_order_complete,
draft_order_creat... | 184 | 6,132 |
probability | tensorflow_probability/python/internal/backend/numpy/variable_utils.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... | 24 | 818 |
mlflow | tests/assistant/providers/test_codex_provider.py | .py | import json
import os
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from mlflow.assistant.providers.base import clear_config_cache
from mlflow.assistant.providers.codex import CodexProvider
from mlflow.assistant.types import EventType
def _make_stdout_lines(*dicts) -> ... | 808 | 27,553 |
probability | tensorflow_probability/python/internal/dtype_util.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... | 431 | 14,758 |
pyomo | examples/pyomobook/optimization-ch/ConcHLinScript.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,491 |
openvino | tools/ovc/unit_tests/ovc/convert/meta_data_test.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import tempfile
from openvino import get_version as get_rt_version
from openvino import serialize
from openvino.tools.ovc import convert_model
from pathlib import Path
from unit_tests.ovc.unit_test_with_mocked_telemetry import ... | 88 | 3,091 |
probability | tensorflow_probability/python/sts/components/smooth_seasonal.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... | 486 | 18,844 |
readthedocs.org | readthedocs/domains/tests/test_tasks.py | .py | from unittest import mock
from django.conf import settings
from django.contrib.auth.models import User
from django.test import TestCase, override_settings
from django.utils import timezone
from django_dynamic_fixture import get
from readthedocs.domains.tasks import email_pending_custom_domains
from readthedocs.organi... | 148 | 5,602 |
kombu | kombu/utils/json.py | .py | """JSON Serialization Utilities."""
from __future__ import annotations
import base64
import json
import uuid
from datetime import date, datetime, time
from decimal import Decimal
from typing import Any, Callable, TypeVar
textual_types = ()
try:
from django.utils.functional import Promise
textual_types += (... | 147 | 4,088 |
probability | tensorflow_probability/python/bijectors/generalized_pareto.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... | 165 | 6,046 |
sphinx | tests/test_util/test_util_inspect_py314.py | .py | # noqa: I002 as 'from __future__ import annotations' prevents Python 3.14
# forward references from causing issues, so we must skip it here.
import pytest
from sphinx.util import inspect
from sphinx.util.typing import stringify_annotation
try:
from annotationlib import ForwardRef # type: ignore[import-not-found... | 53 | 1,553 |
wandb | tests/unit_tests/test_lib/test_filesystem.py | .py | import ctypes
import errno
import os
import platform
import re
import shutil
import tempfile
import time
from pathlib import Path
from unittest import mock
from unittest.mock import Mock, patch
import pytest
# from pyfakefs.fake_filesystem import OSType
from wandb.sdk.lib import filesystem
from wandb.sdk.lib.filesyst... | 611 | 21,225 |
attrs | tests/test_import.py | .py | # SPDX-License-Identifier: MIT
import attr
import attrs
class TestImportStar:
def test_from_attr_import_star(self):
"""
import * from attr
"""
# attr_import_star contains `from attr import *`, which cannot
# be done here because *-imports are only allowed on module level.
... | 35 | 1,001 |
wandb | wandb/sdk/launch/utils.py | .py | from __future__ import annotations
import asyncio
import copy
import json
import logging
import os
import platform
import re
import subprocess
import sys
from collections import defaultdict
from collections.abc import Iterator
from typing import TYPE_CHECKING, Any, cast
import click
import wandb
import wandb.docker ... | 1,105 | 39,349 |
scikit-optimize | doc/conftest.py | .py | import os
from os.path import exists
from os.path import join
import warnings
import numpy as np
from skopt import IS_PYPY
def pytest_runtest_setup(item):
fname = item.fspath.strpath
| 13 | 191 |
jupyterlab | jupyterlab/tests/test_custom_css_handler.py | .py | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import pytest
CUSTOM_CSS = """body #top-panel-wrapper,
#jp-top-bar {
background-color: #aecad4 !important;
}
body h1 {
font-size: 22px;
margin-bottom: 40px;
color: #10929e;
text-decoration: under... | 38 | 1,066 |
gunicorn | tests/requests/valid/014.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
request = {
"method": "GET",
"uri": uri('/with_"quotes"?foo="bar"'),
"version": (1, 1),
"headers": [],
"body": b""
}
| 12 | 243 |
mlflow | tests/johnsnowlabs/test_johnsnowlabs_model_export.py | .py | import json
import os
from pathlib import Path
from unittest import mock
import pandas as pd
import pyspark
import pytest
from johnsnowlabs import nlp
from packaging.version import Version
import mlflow
from mlflow import pyfunc
from mlflow.environment_variables import MLFLOW_DFS_TMP
from mlflow.models import Model, ... | 748 | 28,889 |
wandb | tests/unit_tests/test_lib/test_service_finalizer.py | .py | from collections.abc import Generator
from unittest.mock import AsyncMock
import pytest
from wandb.proto import wandb_server_pb2 as spb
from wandb.sdk.lib import asyncio_manager
from wandb.sdk.lib.service.service_finalizer import ServiceFinalizer
@pytest.fixture(scope="module")
def asyncer() -> Generator[asyncio_man... | 39 | 1,066 |
onnxruntime | orttraining/orttraining/test/python/orttraining_test_ortmodule_autograd_dist.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import copy
import os
import sys
import _test_helpers
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP # noqa: N817
from torch.nn... | 131 | 4,374 |
textual | examples/code_browser.py | .py | """
Code browser example.
Run with:
python code_browser.py PATH
"""
from __future__ import annotations
import sys
from pathlib import Path
from rich.traceback import Traceback
from textual.app import App, ComposeResult
from textual.containers import Container, VerticalScroll
from textual.highlight import high... | 89 | 2,561 |
mlflow | mlflow/store/tracking/gateway/rest_mixin.py | .py | """REST Gateway Store Mixin - Gateway API implementation for REST-based tracking stores."""
from __future__ import annotations
from typing import Any
from mlflow.entities import (
GatewayEndpoint,
GatewayEndpointBinding,
GatewayEndpointModelConfig,
GatewayEndpointModelMapping,
GatewayEndpointTag,... | 818 | 31,112 |
openvino | tools/ovc/unit_tests/moc_tf_fe/test_models/model_mul_with_undefined_constant.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import tensorflow.compat.v1 as tf
tf.reset_default_graph()
# Create the graph and model
with tf.Session() as sess:
x = tf.placeholder(tf.int32, [2], 'x')
const = tf.constant(value=[], dtype=tf.int32, shape=[], name='Const')
... | 14 | 489 |
openvino | src/frontends/tensorflow/tests/test_models/models_pbtxt/concat_with_non_constant_axis.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import tensorflow.compat.v1 as tf
tf.reset_default_graph()
with tf.Session() as sess:
x = tf.placeholder(dtype=tf.float32, shape=[4, 3], name='x')
y = tf.placeholder(dtype=tf.float32, shape=[2, 3], name='y')
z = tf.placeho... | 20 | 665 |
openvino | tests/layer_tests/onnx_tests/test_reciprocal.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
from common.onnx_layer_test_class import OnnxRuntimeLayerTest, onnx_make_model
class TestReciprocal(OnnxRuntimeLayerTest):
def create_net(self, shape, ir_version):
"""
ONNX net ... | 174 | 5,306 |
ipython | tests/test_embed.py | .py | """Test embedding of IPython"""
# -----------------------------------------------------------------------------
# Copyright (C) 2013 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 software.
# ------------------... | 504 | 17,725 |
mlflow | examples/jwt_auth/__init__.py | .py | """The jwt_auth.py example in this module directory is also used by
tests/server/auth/test_auth.py.
"""
| 4 | 104 |
confluent-kafka-python | tests/avro/test_mock_client.py | .py | #!/usr/bin/env python
#
# Copyright 2016 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 required by applicable law or... | 121 | 4,177 |
sphinx | tests/test_ext_imgconverter/test_ext_imgmockconverter.py | .py | """Test image converter with identical basenames"""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
if TYPE_CHECKING:
from sphinx.testing.util import SphinxTestApp
@pytest.mark.sphinx('latex', testroot='ext-imgmockconverter')
def test_ext_imgmockconverter(app: SphinxTestApp) ... | 25 | 767 |
sphinx | sphinx/util/math.py | .py | """Utility functions for math."""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from docutils import nodes
from sphinx.writers.html5 import HTML5Translator
def get_node_equation_number(writer: HTML5Translator, node: nodes.math_block) -> str:
if writer.builder.co... | 63 | 1,958 |
scikit-bio | skbio/stats/tests/test_power.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.
# --------------------------------------------... | 514 | 22,129 |
beam | sdks/python/apache_beam/examples/snippets/transforms/elementwise/regex_all_matches.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");... | 64 | 2,011 |
probability | tensorflow_probability/python/experimental/mcmc/windowed_sampling.py | .py | # Copyright 2021 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... | 962 | 40,413 |
beam | sdks/python/apache_beam/io/flink/flink_streaming_impulse_source.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... | 81 | 2,799 |
probability | tensorflow_probability/python/bijectors/expm1_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... | 92 | 3,447 |
sqlmap | plugins/dbms/virtuoso/syntax.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.convert import getOrds
from plugins.generic.syntax import Syntax as GenericSyntax
class Syntax(GenericSyntax):
@staticmethod
def escape(expression, quote=Tr... | 23 | 677 |
pdm | src/pdm/builders/wheel.py | .py | from __future__ import annotations
import os
from pdm.builders.base import EnvBuilder, wrap_error
class WheelBuilder(EnvBuilder):
"""Build wheel in isolated env with managed Python."""
@wrap_error
def prepare_metadata(self, out_dir: str) -> str:
if self.isolated:
self.install(self._... | 28 | 1,042 |
tqdm | tests/tests_rich.py | .py | """Test `tqdm.rich`."""
from pytest import importorskip, mark
@mark.filterwarnings("ignore:rich is experimental/alpha:"
"tqdm.std.TqdmExperimentalWarning")
def test_rich_no_total(capsys):
"""Test `tqdm.rich` on an iterable without a length, e.g. a generator"""
rich = importorskip('tqdm.ri... | 33 | 912 |
scikit-bio | skbio/util/_array.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.
# --------------------------------------------... | 271 | 8,601 |
saleor | saleor/tests/utils.py | .py | import json
import math
from decimal import Decimal
from typing import Any, Literal, overload
import pytest
from django.conf import settings
from django.db import connections
from opentelemetry.sdk.metrics.export import DataPointT, Metric, MetricsData
from opentelemetry.sdk.trace import ReadableSpan
from ..core.db.co... | 143 | 5,254 |
readthedocs.org | readthedocs/gold/urls.py | .py | """Gold subscription URLs."""
from django.urls import path
from readthedocs.gold import views
urlpatterns = [
path(
"",
views.GoldSubscription.as_view(),
name="gold_detail",
),
path(
"subscription/checkout/create/",
views.GoldCreateCheckoutSession.as_view(),
... | 31 | 729 |
loguru | tests/test_add_option_colorize.py | .py | import os
import pytest
from loguru import logger
from .conftest import StreamIsattyException, StreamIsattyFalse, StreamIsattyTrue, parse
@pytest.mark.parametrize(
("format", "message", "expected"),
[
("<red>{message}</red>", "Foo", parse("<red>Foo</red>\n")),
(lambda _: "<red>{message}</re... | 96 | 3,231 |
beam | sdks/python/apache_beam/utils/windowed_value_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... | 169 | 6,410 |
textual | src/textual/_win_sleep.py | .py | """
A version of `time.sleep` that is more accurate than the standard library (even on Python 3.11).
This should only be imported on Windows.
"""
from __future__ import annotations
import asyncio
from time import sleep as time_sleep
from typing import Coroutine
__all__ = ["sleep"]
INFINITE = 0xFFFFFFFF
WAIT_FAILE... | 122 | 3,773 |
beam | sdks/python/apache_beam/runners/internal/names.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... | 36 | 1,427 |
pyomo | pyomo/contrib/mpc/interfaces/__init__.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... | 17 | 819 |
pyro | pyro/contrib/funsor/infer/discrete.py | .py | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import functools
import funsor
from pyro.contrib.funsor.handlers import enum, replay, trace
from pyro.contrib.funsor.handlers.enum_messenger import _get_support_value
from pyro.contrib.funsor.infer.traceenum_elbo import terms_from_tr... | 73 | 2,921 |
python-prompt-toolkit | examples/prompts/system-prompt.py | .py | #!/usr/bin/env python
from prompt_toolkit import prompt
if __name__ == "__main__":
# System prompt.
print(
"(1/3) If you press meta-! or esc-! at the following prompt, you can enter system commands."
)
answer = prompt("Give me some input: ", enable_system_prompt=True)
print(f"You said: {ans... | 21 | 741 |
httpie | httpie/manager/compat.py | .py | import sys
import shutil
import subprocess
from contextlib import suppress
from typing import List, Optional
from httpie.compat import is_frozen
class PipError(Exception):
"""An exception that occurs when pip exits with an error status code."""
def __init__(self, stdout, stderr):
self.stdout = stdou... | 69 | 2,001 |
biopython | Bio/PDB/Dice.py | .py | # Copyright (C) 2002, Thomas Hamelryck (thamelry@binf.ku.dk)
#
# 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.
"""Code for chopping... | 79 | 2,315 |
metrics | src/torchmetrics/functional/classification/jaccard.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... | 376 | 17,235 |
pyomo | pyomo/contrib/mpc/modeling/tests/test_terminal.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... | 92 | 3,770 |
saleor | saleor/product/tests/test_tasks.py | .py | import datetime
import logging
from contextlib import contextmanager
from decimal import Decimal
from io import BytesIO
from unittest.mock import MagicMock, patch
import pytest
from django.utils import timezone
from faker import Faker
from PIL import Image
from requests.exceptions import HTTPError, InvalidSchema, Requ... | 713 | 23,345 |
pyomo | pyomo/_archive/current.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... | 157 | 3,891 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.