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
biopython
Bio/Data/__init__.py
.py
# Copyright 2000 Andrew Dalke. 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. """Collections of various bi...
9
353
saleor
saleor/tests/e2e/checkout/discounts/sales/test_checkout_with_fixed_sale_should_not_result_in_negative_price.py
.py
import pytest from ......product.tasks import recalculate_discounted_price_for_products_task from ....product.utils import get_product from ....product.utils.preparing_product import prepare_products from ....sales.utils import ( create_sale, create_sale_channel_listing, sale_catalogues_add, ) from ....sho...
336
11,843
wandb
wandb/sdk/artifacts/_generated/project_artifact_collections.py
.py
# Generated by ariadne-codegen # Source: tools/graphql_codegen/artifacts/ from __future__ import annotations from pydantic import Field from wandb._pydantic import GQLResult from .fragments import ArtifactCollectionFragment, PageInfoFragment class ProjectArtifactCollections(GQLResult): project: ProjectArtifac...
37
1,176
beam
sdks/python/apache_beam/runners/common.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...
1,956
77,016
coremltools
deps/protobuf/python/google/protobuf/internal/wire_format_test.py
.py
# Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # https://developers.google.com/protocol-buffers/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redi...
253
10,840
sphinx
tests/roots/test-ext-autodoc/target/decorator.py
.py
from functools import wraps def deco1(func): """docstring for deco1""" @wraps(func) def wrapper(): return func() return wrapper def deco2(condition, message): """docstring for deco2""" def decorator(func): def wrapper(): return func() return wrapper ...
57
767
pyro
pyro/infer/autoguide/gaussian.py
.py
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 import itertools from abc import ABCMeta, abstractmethod from collections import OrderedDict, defaultdict from contextlib import ExitStack from operator import attrgetter from types import SimpleNamespace from typing import Callable, D...
631
26,020
wagtail
wagtail/users/views/bulk_actions/assign_role.py
.py
from django import forms from django.contrib.auth.models import Group from django.utils.translation import gettext_lazy as _ from django.utils.translation import ngettext from wagtail.users.views.bulk_actions.user_bulk_action import UserBulkAction from wagtail.users.views.users import change_user_perm class RoleForm...
47
1,569
sphinx
tests/test_builders/xpath_html_util.py
.py
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from collections.abc import Sequence from xml.etree.ElementTree import Element def _intradocument_hyperlink_check(nodes: Sequence[Element]) -> None: """Confirm that a series of nodes are all HTML hyperlinks to the curr...
20
809
pyro
pyro/infer/predictive.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import warnings from dataclasses import dataclass, fields from functools import reduce from typing import Callable, List, Union import torch import pyro import pyro.poutine as poutine from pyro.infer.autoguide.initialization impo...
642
25,969
beam
sdks/python/apache_beam/runners/dataflow/dataflow_runner.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...
881
35,812
scikit-optimize
skopt/learning/forest.py
.py
import numpy as np from sklearn.ensemble import RandomForestRegressor as _sk_RandomForestRegressor from sklearn.ensemble import ExtraTreesRegressor as _sk_ExtraTreesRegressor def _return_std(X, trees, predictions, min_variance): """ Returns `std(Y | X)`. Can be calculated by E[Var(Y | Tree)] + Var(E[Y | ...
446
18,516
readthedocs.org
readthedocs/oauth/tests/test_tasks.py
.py
from unittest import mock from allauth.socialaccount.models import SocialAccount from allauth.socialaccount.models import SocialToken from allauth.socialaccount.providers.github.provider import GitHubProvider from django.contrib.auth.models import User from django.test import TestCase from django_dynamic_fixture impor...
186
7,148
textual
docs/examples/how-to/center09.py
.py
from textual.app import App, ComposeResult from textual.widgets import Static class CenterApp(App): """How to center things.""" CSS = """ Screen { align: center middle; } .words { background: blue 50%; border: wide white; width: auto; } """ def compos...
28
525
pyomo
pyomo/solvers/plugins/solvers/xpress_direct.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,386
56,337
saleor
saleor/webhook/transport/shipping_helpers.py
.py
import base64 from ...app.models import App from ..const import APP_ID_PREFIX def to_shipping_app_id(app: App, shipping_method_id: str) -> str: app_identifier = app.identifier or app.id return base64.b64encode( str.encode(f"{APP_ID_PREFIX}:{app_identifier}:{shipping_method_id}") ).decode("utf-8")...
12
321
gunicorn
tests/requests/valid/padding_01.py
.py
# # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. request = { "method": "GET", "uri": uri("/"), "version": (1, 1), "headers": [ ("HOST", "localhost"), ("NAME", "value") ], "body": b"", }
16
284
pymc
tests/models.py
.py
# Copyright 2024 - present The PyMC Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
198
5,397
readthedocs.org
readthedocs/rtd_tests/tests/test_api.py
.py
import datetime import json from unittest import mock import dateutil from allauth.socialaccount.models import SocialAccount from django.contrib.auth.models import User from django.test import TestCase, override_settings from django.urls import reverse from django.utils import timezone from django_dynamic_fixture impo...
3,677
135,872
kafka
tests/kafkatest/services/trogdor/kibosh.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 ...
157
6,581
kombu
t/unit/transport/test_azurestoragequeues.py
.py
from __future__ import annotations from unittest.mock import patch import pytest from azure.identity import DefaultAzureCredential, ManagedIdentityCredential from kombu import Connection pytest.importorskip('azure.storage.queue') from kombu.transport import azurestoragequeues # noqa URL_NOCREDS = 'azurestorageque...
86
3,454
openvino
src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/execute.py
.py
# -*- coding: utf-8 -*- # Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # mypy: ignore-errors from copy import deepcopy from dataclasses import dataclass from functools import lru_cache from types import MappingProxyType from warnings import warn import torch import torch.overrides ...
227
7,345
saleor
saleor/graphql/checkout/tests/mutations/test_checkout_customer_detach.py
.py
from unittest.mock import ANY, patch import pytest from django.test import override_settings from django.utils import timezone from freezegun import freeze_time from .....account.tests.fixtures.user import dangerously_create_test_user from .....checkout.actions import call_checkout_event from .....core.models import ...
285
9,332
saleor
saleor/graphql/order/mutations/order_confirm.py
.py
from typing import cast import graphene from django.core.exceptions import ValidationError from django.db import transaction from ....account.models import User from ....core.tracing import traced_atomic_transaction from ....order import models from ....order.actions import ( WEBHOOK_EVENTS_FOR_ORDER_CHARGED, ...
119
4,668
onnx
onnx/backend/test/case/node/sigmoid.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 class Sigmoid(Base): @staticmethod def export() -> None: nod...
31
853
gunicorn
tests/test_asgi_uwsgi.py
.py
# # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. """ Tests for ASGI uWSGI protocol parser. """ import pytest from gunicorn.asgi.unreader import AsyncUnreader from gunicorn.asgi.uwsgi import AsyncUWSGIRequest from gunicorn.uwsgi.errors import ( InvalidUWSGIH...
473
13,252
saleor
saleor/graphql/discount/mutations/sale/sale_channel_listing_update.py
.py
from collections import defaultdict from collections.abc import Callable from typing import Any, cast import graphene from django.core.exceptions import ValidationError from django.db.models import Exists, OuterRef from .....channel.models import Channel from .....core.tracing import traced_atomic_transaction from .....
281
10,893
onnxruntime
onnxruntime/test/testdata/transform/id-elim.py
.py
import onnx from onnx import OperatorSetIdProto, TensorProto, helper X1 = helper.make_tensor_value_info("x1", TensorProto.INT64, [4, 4]) X2 = helper.make_tensor_value_info("x2", TensorProto.INT64, [4, 4]) Y1 = helper.make_tensor_value_info("output1", TensorProto.INT64, [4, 4]) Y2 = helper.make_tensor_value_info("outpu...
34
1,321
sqlmap
plugins/dbms/sqlite/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
643
cvxpy
cvxpy/atoms/affine/broadcast_to.py
.py
""" Copyright, the CVXPY authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software ...
81
2,296
astropy
astropy/io/votable/tests/test_schema_versions.py
.py
import re import sys import pytest from astropy.io.votable.xmlutil import validate_schema from astropy.utils.data import get_pkg_data_filename # Each test file uses a feature that is new with its version. V_1_2_TABLE = get_pkg_data_filename("data/empty_table.xml") V_1_3_TABLE = get_pkg_data_filename("data/binary2_ma...
79
2,480
loguru
tests/exceptions/source/backtrace/nested_explicit_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) def foo(): bar() @logger.catch(NotImplementedError) def bar(): 1 / 0 try: foo() ex...
23
369
openvino
tests/layer_tests/pytorch_tests/test_nonzero.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np import pytest from pytorch_layer_test_class import PytorchLayerTest class TestNonZero(PytorchLayerTest): def _prepare_input(self, mask_fill='ones', mask_dtype=bool): input_shape = [2, 10, 2] mask...
50
1,705
astropy
astropy/cosmology/_src/tests/conftest.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Configure the tests for :mod:`astropy.cosmology`.""" from astropy.cosmology._src.tests.helper import clean_registry # noqa: F401 from astropy.tests.helper import pickle_protocol # noqa: F401
7
262
metrics
src/torchmetrics/detection/giou.py
.py
# Copyright The PyTorch 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 i...
191
7,899
confluent-kafka-python
src/confluent_kafka/schema_registry/__init__.py
.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2020 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...
254
7,955
astropy
astropy/coordinates/tests/test_unit_representation.py
.py
""" This file tests the behavior of subclasses of Representation and Frames """ from copy import deepcopy import astropy.coordinates import astropy.units as u from astropy.coordinates import ICRS, Latitude, Longitude from astropy.coordinates.baseframe import RepresentationMapping, frame_transform_graph from astropy.c...
79
2,745
textual
docs/examples/guide/content/renderables.py
.py
from rich.syntax import Syntax from textual.app import App, ComposeResult, RenderResult from textual.reactive import reactive from textual.widget import Widget class CodeView(Widget): """Widget to display Python code.""" DEFAULT_CSS = """ CodeView { height: auto; } """ code = reactive("") ...
37
883
mlflow
tests/genai/test_genai_import_without_agent_sdk.py
.py
import json from unittest import mock from unittest.mock import patch import pytest from mlflow.genai.datasets import create_dataset, delete_dataset, get_dataset from mlflow.genai.scorers import ( Guidelines, delete_scorer, get_scorer, list_scorers, ) from mlflow.genai.scorers.base import Scorer from ...
175
6,406
bazel
examples/py_native/bin.py
.py
# pylint: disable=superfluous-parens """A tiny example binary for the native Python rules of Bazel.""" from examples.py_native.lib import GetNumber from fib import Fib print("The number is %d" % GetNumber()) print("Fib(5) == %d" % Fib(5))
8
240
clearml
clearml/backend_interface/base.py
.py
from abc import ABC, abstractmethod import logging from typing import Any, Optional import requests.exceptions import jsonschema from ..backend_api import Session, CallResult from ..backend_api.session.session import MaxRequestSizeError from ..backend_api.session.response import ResponseMeta from ..backend_api.sessio...
235
8,030
bazel
third_party/py/mock/tests/support_with.py
.py
from __future__ import with_statement import sys __all__ = ['nested', 'catch_warnings', 'examine_warnings'] try: from contextlib import nested except ImportError: from contextlib import contextmanager @contextmanager def nested(*managers): exits = [] vars = [] exc = (None, No...
94
2,972
beam
sdks/python/apache_beam/programming_guide_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...
51
1,743
pyfilesystem2
fs/time.py
.py
"""Time related tools. """ from __future__ import print_function, unicode_literals import typing from calendar import timegm from datetime import datetime try: from datetime import timezone except ImportError: from ._tzcompat import timezone # type: ignore if typing.TYPE_CHECKING: from typing import O...
44
870
pyomo
examples/doc/samples/comparisons/sched/pyomo/sched.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...
91
2,547
clearml
examples/datasets/single_parent_child_dataset.py
.py
from pathlib2 import Path from clearml import Dataset, StorageManager def main(): manager = StorageManager() print("STEP1 : Downloading mnist dataset") mnist_dataset = Path( manager.get_local_copy(remote_url="https://allegro-datasets.s3.amazonaws.com/datasets/MNIST.zip", name="MNIST") ) ...
35
1,166
mlflow
mlflow/langchain/chat_agent_langgraph.py
.py
from __future__ import annotations import json from typing import Annotated, Any, TypedDict from uuid import uuid4 from packaging.version import Version from mlflow.utils import get_installed_version try: from langchain_core.messages import AnyMessage, BaseMessage, convert_to_messages from langchain_core.ru...
369
14,445
openvino
src/frontends/tensorflow/tests/test_models/gen_scripts/generate_saved_model_parameter_result.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import sys import tensorflow as tf # This test model aims to cover conversion of SavedModel with multiple tensor names for output # among which TF FE needs to remain only user specific names and exclude internal tensor names...
26
877
dirty-equals
tests/test_pytest_report.py
.py
def test_anything_diff(pytester): # see https://github.com/samuelcolvin/dirty-equals/issues/108 pytester.makepyfile(""" from dirty_equals import AnyThing def test_dirty_equals_1(): leftdct = {"id": 1, "name": "AAA", "anything": [1, 2, 3]} rightdct = {"id": 1, "name": "BBB", "anything": AnyThing()} ...
95
3,077
wandb
tools/bench/_load_profiles.py
.py
#!/usr/bin/env python import itertools VARIANTS = { "mode=online": {}, "mode=offline": { "mode": "offline", }, "core=false": {}, "core=true": { "core": "true", }, } ALL_VARIANTS = { "mode": ("offline", "online"), "core": ("false", "true"), } PROFILES = { "v1-empty...
80
2,028
pyomo
pyomo/contrib/sensitivity_toolbox/tests/test_sens_unit.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...
877
34,928
pyfilesystem2
tests/test_opener.py
.py
from __future__ import unicode_literals import sys import os import pkg_resources import shutil import tempfile import unittest from fs import open_fs, opener from fs.appfs import UserDataFS from fs.memoryfs import MemoryFS from fs.opener import errors, registry from fs.opener.parse import ParseResult from fs.opener...
338
11,892
python-prompt-toolkit
examples/full-screen/simple-demos/autocompletion.py
.py
#!/usr/bin/env python """ An example of a BufferControl in a full screen layout that offers auto completion. Important is to make sure that there is a `CompletionsMenu` in the layout, otherwise the completions won't be visible. """ from prompt_toolkit.application import Application from prompt_toolkit.buffer import B...
102
2,138
gunicorn
tests/requests/valid/pp_02.py
.py
# # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. from gunicorn.config import Config cfg = Config() cfg.set("proxy_protocol", True) req1 = { "method": "GET", "uri": uri("/stuff/here?foo=bar"), "version": (1, 1), "headers": [ ("SERVER", "h...
35
745
wandb
wandb/integration/sklearn/calculate/elbow_curve.py
.py
import time from warnings import simplefilter import numpy as np from joblib import Parallel, delayed from sklearn.base import clone import wandb # ignore all future warnings simplefilter(action="ignore", category=FutureWarning) def elbow_curve(clusterer, X, cluster_ranges, n_jobs, show_cluster_time): # noqa: N80...
56
1,482
textual
tests/test_style_properties.py
.py
import pytest from rich.style import Style from textual.color import Color from textual.css.errors import StyleValueError from textual.css.styles import Styles def test_box_normalization(): """Check that none or hidden is normalized to empty string.""" styles = Styles() styles.border_left = ("none", "red...
33
1,120
textual
tests/test_color.py
.py
import pytest from rich.color import Color as RichColor from textual.color import Color, Gradient, Lab, lab_to_rgb, rgb_to_lab def test_rich_color(): """Check conversion to Rich color.""" assert Color(10, 20, 30, 1.0).rich_color == RichColor.from_rgb(10, 20, 30) assert Color.from_rich_color(RichColor.fro...
325
10,482
metrics
src/torchmetrics/wrappers/transformations.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...
181
7,083
sphinx
tests/roots/test-ext-autodoc/target/__init__.py
.py
import enum from io import StringIO from ._functions_to_import import function_to_be_imported __all__ = ['Class'] #: documentation for the integer integer = 1 def raises(exc, func, *args, **kwds): """Raise AssertionError if ``func(*args, **kwds)`` does not raise *exc*.""" pass class CustomEx(Exception): ...
214
4,543
probability
spinoffs/autobnn/autobnn/bnn_test.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...
69
2,252
pyomo
pyomo/solvers/tests/models/LP_duals_minimize.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...
115
4,223
astropy
astropy/coordinates/sky_coordinate.py
.py
import copy import operator import re import warnings from collections.abc import Callable from typing import Union import erfa import numpy as np from astropy import units as u from astropy.constants import c as speed_of_light from astropy.time import Time from astropy.utils import ShapedLikeNDArray from astropy.uti...
1,870
78,816
pyomo
examples/kernel/expressions.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...
62
1,413
saleor
saleor/graphql/page/tests/queries/pages_with_where/test_with_where_metadata.py
.py
import graphene import pytest from ......page.models import Page from .....tests.utils import get_graphql_content from .shared import QUERY_PAGES_WITH_WHERE @pytest.mark.parametrize( ("metadata", "expected_indexes"), [ ({"key": "foo"}, [0, 1]), ({"key": "foo", "value": {"eq": "bar"}}, [0]), ...
59
1,587
pyro
tests/distributions/test_mvn.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import pytest import torch from pyro.distributions import MultivariateNormal from tests.common import assert_equal def random_mvn(loc_shape, cov_shape, dim): """ Generate a random MultivariateNormal distribution for test...
57
1,425
lemur
lemur/plugins/lemur_kubernetes/plugin.py
.py
""" .. module: lemur.plugins.lemur_kubernetes.plugin :platform: Unix :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. The plugin inserts certificates and the private key as Kubernetes secret that can later be used to secure service endpoin...
317
11,077
mlflow
tests/genai/scorers/test_scorer_description.py
.py
from unittest.mock import patch import pytest from mlflow.genai import scorer from mlflow.genai.judges import make_judge from mlflow.genai.judges.instructions_judge import InstructionsJudge from mlflow.genai.scorers import RelevanceToQuery @pytest.fixture(autouse=True) def mock_databricks_runtime(): with patch(...
158
4,375
jupytext
tests/functional/simple_notebooks/test_ipynb_to_py.py
.py
import nbformat import jupytext from jupytext.compare import compare_notebooks def test_identity_source_write_read(ipynb_py_file): """Test that writing the notebook with jupytext, and read again, is the same as removing outputs""" with open(ipynb_py_file) as fp: nb1 = nbformat.read(fp, as_versio...
18
430
astropy
astropy/coordinates/tests/test_shape_manipulation.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np import pytest from numpy.testing import assert_array_equal from astropy import units as u from astropy.coordinates import EarthLocation, Latitude, Longitude, SkyCoord # test on frame with most complicated frame attributes. from astrop...
396
20,082
luigi
test/date_interval_test.py
.py
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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...
135
5,444
mlflow
mlflow/models/flavor_backend.py
.py
from abc import ABCMeta, abstractmethod from mlflow.utils.annotations import developer_stable @developer_stable class FlavorBackend: """ Abstract class for Flavor Backend. This class defines the API interface for local model deployment of MLflow model flavors. """ __metaclass__ = ABCMeta de...
104
3,321
saleor
saleor/core/editorjs/utils.py
.py
from typing import Any def maybe_to_int(o: Any) -> int: """Cast a given object to an integer if it's possible, otherwise it raises. It's a lenient parsing for backward compatibility. """ if isinstance(o, str): if o.isnumeric() is False: raise ValueError("Value must be an integer"...
19
448
readthedocs.org
readthedocs/core/querysets.py
.py
class NoReprQuerySet: """ Basic queryset to override `__repr__` function due to logging issues. This may be a temporary solution for now and it can be improved to detect if we are under DEBUG and/or on an interactive shell. https://github.com/readthedocs/readthedocs.org/issues/10954 https://gi...
15
554
coremltools
coremltools/converters/mil/mil/types/type_int.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 math import numpy as np import sympy as sm from coremltools import _logger as logger from ....
232
6,951
saleor
saleor/tests/e2e/translations/utils.py
.py
from ..utils import get_graphql_content TRANSLATIONS_QUERY = """ query Translations($language: LanguageCodeEnum!, $first: Int, $kind: TranslatableKinds!) { translations( kind: $kind first: $first ) { totalCount edges { node { ...PromotionTranslation ...PromotionRuleTranslation...
66
1,093
jupytext
tests/functional/metadata/test_metadata_filters_from_config.py
.py
import nbformat import pytest import yaml from nbformat.v4.nbbase import new_code_cell, new_markdown_cell, new_notebook from jupytext.cli import jupytext as jupytext_cli from jupytext.compare import compare, compare_notebooks from jupytext.header import _JUPYTER_METADATA_NAMESPACE def test_metadata_filters_from_conf...
81
2,458
wandb
tests/system_tests/test_api/test_public_api_organizations.py
.py
"""System tests for `Api.organization()` and the public `Organization` model.""" from __future__ import annotations from collections.abc import Callable from typing import TYPE_CHECKING from pytest import fixture, raises from wandb import CommError if TYPE_CHECKING: from wandb import Api @fixture def org_name...
45
1,382
astropy
astropy/wcs/wcsapi/tests/test_high_level_api.py
.py
import re import numpy as np import pytest from numpy.testing import assert_allclose from astropy import units as u from astropy.coordinates import SkyCoord from astropy.units import Quantity from astropy.wcs import WCS from astropy.wcs.wcsapi.high_level_api import ( HighLevelWCSMixin, high_level_objects_to_v...
358
9,945
openvino
tests/layer_tests/onnx_tests/test_identity.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np import pytest pytest.importorskip("openvino.tools.mo", reason="Ticket - 157136") from common.layer_test_class import check_ir_version from common.onnx_layer_test_class import OnnxRuntimeLayerTest, onnx_make_model fro...
187
6,188
onnx
onnx/backend/test/case/model/sign.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.model import expect class SingleSign(Base): @staticmethod def export() -> None: ...
37
1,151
saleor
saleor/tests/e2e/shop/utils/shop_update_settings.py
.py
from ...utils import get_graphql_content SHOP_SETTING_UPDATE_MUTATION = """ mutation ShopSettingsUpdate($input: ShopSettingsInput!) { shopSettingsUpdate(input: $input) { errors { field message code } shop { enableAccountConfirmationByEmail fulfillmentAutoApprove fulfil...
42
993
saleor
saleor/site/__init__.py
.py
class PasswordLoginMode: """Controls whether password-based authentication is allowed. ENABLED - any user can log in with a password. This is the default behavior. CUSTOMERS_ONLY - only customer users can log in with a password. If a staff user logs in with a password, they will be treated as a cus...
72
2,050
pdm
src/pdm/cli/commands/new.py
.py
import argparse import os from pdm.cli.commands.base import verbose_option from pdm.cli.commands.init import Command as InitCommand from pdm.project.core import Project class Command(InitCommand): """Create a new Python project at <project_path>""" supports_other_generator = False arguments = (verbose_...
25
811
gunicorn
tests/requests/valid/023.py
.py
# # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. req1 = { "method": "POST", "uri": uri("/two_chunks_mult_zero_end"), "version": (1, 1), "headers": [ ("TRANSFER-ENCODING", "chunked") ], "body": b"hello world" } req2 = { "method...
24
441
pyomo
examples/gdp/jobshop.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...
98
3,714
textual
tests/snapshot_tests/snapshot_apps/grid_auto.py
.py
from textual.app import App, ComposeResult from textual.containers import Grid from textual.widgets import Placeholder class KeylineApp(App): CSS = """ Grid { grid-size: 3 3; grid-gutter: 1; grid-columns: 2; grid-rows: 1; keyline: thin; width: auto; heig...
35
799
pyomo
examples/pyomobook/abstract-ch/param3c.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...
35
1,143
saleor
saleor/graphql/discount/dataloaders.py
.py
from collections import defaultdict from typing import TYPE_CHECKING from uuid import UUID from django.db.models import Exists, F, OuterRef, Sum from django.db.models.functions import Coalesce from promise import Promise from ...channel.models import Channel from ...discount.interface import VoucherInfo from ...disco...
505
19,264
openvino
tests/layer_tests/tensorflow_tests/test_tf_DynamicPartition.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np import pytest import tensorflow as tf from common.tf_layer_test_class import CommonTFLayerTest class TestDynamicPartition(CommonTFLayerTest): def _prepare_input(self, inputs_info): assert 'data:0' in inpu...
65
3,046
pymc
pymc/printing.py
.py
# Copyright 2024 - present The PyMC Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
570
19,866
probability
spinoffs/autobnn/autobnn/kernels.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...
344
11,677
openvino
tests/layer_tests/pytorch_tests/test_gcd.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np import pytest import torch from pytorch_layer_test_class import PytorchLayerTest class TestGcd(PytorchLayerTest): def _prepare_input(self): return self.input_data def create_model_tensor_input(self)...
123
3,636
astropy
astropy/stats/jackknife.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst from collections.abc import Callable from typing import TypeVar import numpy as np from numpy.typing import NDArray __all__ = ["jackknife_resampling", "jackknife_stats"] __doctest_requires__ = {"jackknife_stats": ["scipy"]} DT = TypeVar("DT", bound=np....
188
6,218
saleor
saleor/app/headers.py
.py
class AppHeaders: DOMAIN = "Saleor-Domain" EVENT_TYPE = "Saleor-Event" SIGNATURE = "Saleor-Signature" API_URL = "Saleor-Api-Url" SCHEMA_VERSION = "Saleor-Schema-Version" class DeprecatedAppHeaders: DOMAIN = "X-Saleor-Domain" EVENT_TYPE = "X-Saleor-Event" SIGNATURE = "X-Saleor-Signature...
13
322
lemur
lemur/certificates/verify.py
.py
""" .. module: lemur.certificates.verify :platform: Unix :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Kevin Glisson <kglisson@netflix.com> """ import ipaddress import requests import socket import subprocess from collections imp...
310
11,005
mlflow
tests/genai/optimize/optimizers/test_metaprompt_optimizer.py
.py
import json from typing import Any from unittest.mock import Mock, patch import pytest from mlflow.exceptions import MlflowException from mlflow.genai.optimize.optimizers.metaprompt_optimizer import MetaPromptOptimizer from mlflow.genai.optimize.types import EvaluationResultRecord, PromptOptimizerOutput _CALL_LLM = ...
523
19,286
probability
tensorflow_probability/python/math/psd_kernels/changepoint.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...
268
10,912
onnxruntime
onnxruntime/python/tools/transformers/models/whisper/whisper_helper.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 j...
1,039
50,551
marshmallow
tests/test_decorators.py
.py
import pytest from marshmallow import ( EXCLUDE, INCLUDE, RAISE, Schema, ValidationError, fields, post_dump, post_load, pre_dump, pre_load, validate, validates, validates_schema, ) from tests.base import predicate @pytest.mark.parametrize("partial_val", (True, Fals...
988
34,392
luigi
test/config_env_test.py
.py
# -*- coding: utf-8 -*- # # Copyright 2018 Vote 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 ag...
119
3,725