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
pyomo
pyomo/solvers/tests/checks/test_CPLEXPersistent.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,171
mlflow
mlflow/tracing/archival.py
.py
_ERROR_MSG = ( "The `databricks-agents` package is required to use databricks trace archival. " "Please install it with `pip install databricks-agents`." ) def enable_databricks_trace_archival( *, delta_table_fullname: str, experiment_id: str | None = None, ) -> None: """ Enable archiving ...
71
2,086
saleor
saleor/graphql/shop/tests/mutations/test_staff_notification_recipient_update.py
.py
import graphene from ....tests.utils import get_graphql_content MUTATION_STAFF_NOTIFICATION_RECIPIENT_UPDATE = """ mutation StaffNotificationRecipient ( $id: ID!, $input: StaffNotificationRecipientInput! ) { staffNotificationRecipientUpdate(id: $id, input: $input) { staffNo...
125
3,544
astropy
astropy/io/fits/hdu/compressed/tests/test_tiled_compression.py
.py
import hashlib from pathlib import Path import numpy as np import pytest from numpy.testing import assert_allclose, assert_equal from astropy.io import fits from astropy.io.fits.hdu.compressed._codecs import PLIO1 from astropy.io.fits.hdu.compressed._compression import CfitsioException from astropy.utils.exceptions i...
288
10,552
gunicorn
tests/docker/asgi_framework_compat/frameworks/django_app/consumers.py
.py
""" Django Channels WebSocket consumers for ASGI compatibility testing. """ import json from channels.generic.websocket import AsyncWebsocketConsumer def serialize_scope(scope: dict) -> dict: """Convert ASGI scope to JSON-serializable dict.""" result = {} for key, value in scope.items(): if key =...
111
3,138
metrics
src/torchmetrics/shape/__init__.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...
17
675
probability
tensorflow_probability/python/experimental/linalg/no_pivot_ldl_test.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...
118
4,791
scikit-optimize
skopt/space/space.py
.py
import numbers import numpy as np import yaml from scipy.stats.distributions import randint from scipy.stats.distributions import rv_discrete from scipy.stats.distributions import uniform from sklearn.utils import check_random_state from sklearn.utils.fixes import sp_version from .transformers import CategoricalEnco...
1,141
38,720
mlflow
tests/test_mismatch.py
.py
import warnings from importlib.metadata import PackageNotFoundError from unittest import mock import pytest from mlflow.mismatch import _check_version_mismatch @pytest.mark.parametrize( ("mlflow_version", "skinny_version"), [ ("1.0.0", "1.0.0"), ("1.0.0.dev0", "1.0.0"), ("1.0.0", "1....
85
2,706
sphinx
tests/test_theming/test_theming.py
.py
"""Test the Theme class.""" from __future__ import annotations import shutil from pathlib import Path from typing import TYPE_CHECKING from xml.etree.ElementTree import ParseError import pytest from defusedxml.ElementTree import parse as xml_parse import sphinx.builders.html from sphinx.builders.html import Standal...
269
8,311
readthedocs.org
readthedocs/subscriptions/signals.py
.py
"""Subscriptions signals.""" import stripe import structlog from django.db.models.signals import post_save from django.dispatch import receiver from readthedocs.organizations.models import Organization from readthedocs.payments.utils import get_stripe_client log = structlog.get_logger(__name__) # pylint: disable=...
60
1,969
onnx
onnx/backend/base.py
.py
# Copyright (c) ONNX Project Contributors # # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations from collections import namedtuple from typing import TYPE_CHECKING, Any, NewType import onnx.checker import onnx.onnx_cpp2py_export.checker as c_checker from onnx import IR_VERSION, ModelProto, NodePr...
149
4,862
pymc
pymc/backends/mcbackend.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...
313
11,250
sqlmap
plugins/dbms/h2/enumeration.py
.py
#!/usr/bin/env python """ Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org) See the file 'LICENSE' for copying permission """ from lib.core.common import unArrayizeValue from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.data import queries from lib...
56
1,579
sphinx
tests/roots/test-ext-autodoc/target/uninitialized_attributes.py
.py
class Base: attr1: int #: docstring attr2: str class Derived(Base): attr3: int #: docstring attr4: str
9
123
beam
sdks/python/apache_beam/examples/wordcount_xlang.py
.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
130
3,942
ipython
IPython/core/application.py
.py
""" An application for IPython. All top-level applications should use the classes in this module for handling configuration and creating configurables. The job of an :class:`Application` is to create the master configuration object and then create the configurable objects, passing the config to them. """ # Copyright...
500
19,274
saleor
saleor/checkout/tests/test_checkout_complete.py
.py
import datetime from decimal import Decimal from unittest import mock import pytest from django.core.exceptions import ValidationError from django.test import override_settings from django.utils import timezone from prices import TaxedMoney from ...account import CustomerEvents from ...account.models import CustomerE...
2,863
97,352
openvino
src/frontends/pytorch/src/scripts/get_supported_ops.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import re def get_ops_in_specific_map(map_name: str, lines: list) -> list: ops = [] start_found = False for line in lines: if start_found: if "};" in line: break res...
34
1,021
confluent-kafka-python
tests/schema_registry/_async/test_dlq_serdes.py
.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2026 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...
659
26,958
saleor
saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_order_updated.py
.py
import json from unittest.mock import patch import graphene from django.test import override_settings from ......core.models import EventDelivery from ......graphql.webhook.subscription_query import SubscriptionQuery from ......webhook.event_types import WebhookEventAsyncType from .....manager import get_plugins_mana...
232
6,970
beam
sdks/python/apache_beam/runners/direct/consumer_tracking_pipeline_visitor_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...
164
5,847
saleor
saleor/graphql/channel/schema.py
.py
import graphene from ...permission.auth_filters import AuthorizationFilters from ..core import ResolveInfo from ..core.doc_category import DOC_CATEGORY_CHANNELS from ..core.fields import BaseField, PermissionsField from ..core.types import NonNullList from .mutations import ( ChannelActivate, ChannelCreate, ...
60
1,862
hatch
backend/src/hatchling/cli/dep/core.py
.py
from __future__ import annotations import re import sys from importlib.metadata import Distribution, DistributionFinder from packaging.markers import default_environment from packaging.requirements import Requirement class DistributionCache: def __init__(self, sys_path: list[str]) -> None: self._resolve...
133
5,316
onnx
onnx/helper.py
.py
# Copyright (c) ONNX Project Contributors # # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import collections.abc import functools import math import numbers import typing from typing import TYPE_CHECKING, Any, TypeVar import google.protobuf.message import numpy as np import typing_extension...
1,382
46,471
sqlmap
plugins/dbms/presto/connector.py
.py
#!/usr/bin/env python """ Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org) See the file 'LICENSE' for copying permission """ try: import prestodb except: pass import logging import struct from lib.core.common import getSafeExString from lib.core.data import conf from lib.core.data import logge...
71
2,203
wagtail
wagtail/models/locking.py
.py
from django.conf import settings from django.core import checks from django.db import models from django.utils.translation import gettext_lazy as _ from wagtail.locks import BasicLock from .revisions import RevisionMixin class LockableMixin(models.Model): locked = models.BooleanField( verbose_name=_("lo...
83
2,313
ipython
IPython/external/__init__.py
.py
""" This package contains all third-party modules bundled with IPython. """ __all__: list[str] = []
6
101
onnxruntime
onnxruntime/test/providers/cpu/rnn/LSTM.py
.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import numpy as np DebugOutput = True np.set_printoptions(suppress=True) # , precision=16, floatmode='maxprec') def print_with_shape(name, a, force_output=False): if force_output or DebugOutput: print(name + ...
744
25,978
onnx
onnx/backend/test/case/node/string_concat.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 StringConcat(Base): @staticmethod def export() -> None: ...
70
1,980
django-cms
cms/test_utils/project/pluginapp/plugins/caching/cms_plugins.py
.py
from datetime import datetime, timedelta from django.utils import timezone from cms.plugin_base import CMSPluginBase class NoCachePlugin(CMSPluginBase): name = 'NoCache' module = 'Test' render_plugin = True cache = False render_template = "plugins/nocache.html" def render(self, context, ins...
109
3,147
saleor
saleor/permission/enums.py
.py
from collections.abc import Iterable from enum import Enum from django.conf import settings from django.db.models import QuerySet from .models import Permission class BasePermissionEnum(Enum): @property def codename(self): return self.value.split(".")[1] class AccountPermissions(BasePermissionEnum...
183
4,888
saleor
saleor/graphql/product/bulk_mutations/category_bulk_delete.py
.py
import graphene from django.conf import settings from ....permission.enums import ProductPermissions from ....product import models from ....product.utils import delete_categories from ...core.mutations import ModelBulkDeleteMutation from ...core.types import NonNullList, ProductError from ...plugins.dataloaders impor...
37
1,294
clearml
examples/frameworks/fire/fire_grouping_cmd.py
.py
# ClearML - Example of Python Fire integration, with commands grouped inside classes # from clearml import Task import fire class Other: def status(self): return "Other" class IngestionStage: def __init__(self): self.other = Other() def run(self): return "Ingesting! Nom nom nom...
45
861
wagtail
wagtail/blocks/stream_block.py
.py
import json import uuid from collections import OrderedDict, defaultdict from collections.abc import Mapping, MutableSequence from pickle import PickleError from django import forms from django.core.exceptions import ValidationError from django.db.models.fields import _load_field from django.forms.utils import ErrorLi...
898
33,649
beam
sdks/python/apache_beam/ml/rag/ingestion/__init__.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...
21
917
coremltools
deps/protobuf/python/google/protobuf/internal/_parameterized.py
.py
#! /usr/bin/env python # # 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 ...
448
15,475
saleor
saleor/graphql/checkout/tests/test_checkouts_query.py
.py
from decimal import Decimal from unittest.mock import patch from django.utils import timezone from ....webhook.event_types import WebhookEventSyncType from ...tests.utils import get_graphql_content CHECKOUTS_QUERY = """ query CheckoutsQuery { checkouts(first: 1) { edges { node { deliveryMethod { ...
293
8,887
onnxruntime
orttraining/orttraining/test/external_custom_ops/testdata/gen_model.py
.py
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import onnx from onnx import helper graph = helper.make_graph( [helper.make_node("Foo", ["input1"], ["output1"], "", "", "com.examples")], "external_custom_op_example_model", [helper.make_tensor_value_info("input1", helper.TensorProt...
20
608
hydra
examples/advanced/package_overrides/simple.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from omegaconf import DictConfig, OmegaConf import hydra @hydra.main(config_path="conf", config_name="simple") def my_app(cfg: DictConfig) -> None: print(OmegaConf.to_yaml(cfg)) if __name__ == "__main__": my_app()
14
298
django-cms
cms/test_utils/project/mti_pluginapp/models.py
.py
from django.db import models from cms.models import CMSPlugin class SomeParent: pass class TestPluginAlphaModel(SomeParent, CMSPlugin): """ Nothing interesting here, move along. """ alpha = models.CharField('name', blank=False, default='test plugin alpha', max_length=32) def get_add_url(se...
93
2,347
bazel
src/test/py/bazel/bzlmod/external_repo_completion_test.py
.py
# pylint: disable=g-backslash-continuation # Copyright 2023 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/LICEN...
305
11,200
saleor
saleor/graphql/product/mutations/product_variant/variant_media_unassign.py
.py
import graphene from django.core.exceptions import ValidationError from .....permission.enums import ProductPermissions from .....product import models from .....product.error_codes import ProductErrorCode from ....core import ResolveInfo from ....core.context import ChannelContext from ....core.doc_category import DO...
66
2,460
coremltools
coremltools/converters/mil/mil/types/type_tensor.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 numpy as np import sympy as sm from coremltools import _logger as logger from .get_type_info...
214
6,668
python-prompt-toolkit
examples/prompts/auto-completion/colored-completions-with-formatted-text.py
.py
#!/usr/bin/env python """ Demonstration of a custom completer class and the possibility of styling completions independently by passing formatted text objects to the "display" and "display_meta" arguments of "Completion". """ from prompt_toolkit.completion import Completer, Completion from prompt_toolkit.formatted_tex...
139
3,759
probability
tensorflow_probability/python/experimental/linalg/linear_operator_row_block_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...
70
2,522
openvino
tests/layer_tests/tensorflow_lite_tests/test_tfl_BinaryWithActivation.py
.py
import pytest import tensorflow as tf from common.tflite_layer_test_class import TFLiteLayerTest from common.utils.tflite_utils import additional_test_params, activation_helper from common.utils.tflite_utils import parametrize_tests test_ops = [ {'op_name': 'ADD', 'op_func': 'tf.math.add'}, {'op_name': 'DIV',...
48
1,970
pyomo
pyomo/contrib/gdpopt/enumerate.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...
185
7,846
textual
tests/tree/test_tree_messages.py
.py
from __future__ import annotations from typing import Any from textual.app import App, ComposeResult from textual.containers import Vertical from textual.widgets import Button, Tree class MyTree(Tree[None]): pass class TreeApp(App[None]): """Test tree app.""" def __init__(self, *args: Any, **kwargs: ...
255
8,875
readthedocs.org
readthedocs/projects/tests/test_models.py
.py
import pytest from django.core.exceptions import ValidationError from django.test import TestCase from django_dynamic_fixture import get from readthedocs.analytics.models import PageView from readthedocs.builds.models import Build, Version from readthedocs.oauth.models import RemoteRepository from readthedocs.projects...
286
11,221
probability
tensorflow_probability/python/internal/batched_rejection_sampler.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...
198
8,871
onnxruntime
onnxruntime/python/tools/quantization/operators/matmul.py
.py
import itertools import logging import onnx from ..quant_utils import ( FLOAT8_TYPES, TENSOR_NAME_QUANT_SUFFIX, QuantizedValue, QuantizedValueType, find_by_name, get_mul_node, ) from .base_operator import QuantOperatorBase from .qdq_base_operator import QDQOperatorBase class QOpMatMul(QuantO...
228
7,995
mlflow
tests/openai/test_openai_autolog.py
.py
import json import re import sys from unittest import mock import httpx import openai import pytest from openai.resources.chat.completions import Completions as ChatCompletions from openai.resources.completions import Completions from openai.resources.embeddings import Embeddings from packaging.version import Version ...
1,295
44,527
saleor
saleor/plugins/tests/test_email_common.py
.py
import json from unittest.mock import ANY, patch import pytest from django.core.exceptions import ValidationError from ...order.notifications import get_image_payload from ..email_common import ( DEFAULT_EMAIL_CONFIGURATION, EmailConfig, get_plain_text_message_for_email, get_product_image_thumbnail, ...
191
6,103
saleor
saleor/tests/e2e/checkout/test_unlogged_customer_should_not_be_able_to_buy_product_without_shipping_option.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, raw_checkout_dummy_payment_create @pytest.mark.e2e def test_unlogged_customer_unable_to_buy_product_without_shipping_option_CORE...
88
2,519
jupytext
tests/functional/others/test_preserve_empty_cells.py
.py
import pytest from nbformat.v4.nbbase import new_code_cell, new_markdown_cell, new_notebook import jupytext from jupytext.compare import compare, compare_notebooks @pytest.mark.parametrize("blank_lines", range(1, 6)) def test_file_with_blank_lines(blank_lines): py_script = """# Markdown cell{0} # Another one{0} ...
33
1,051
saleor
saleor/graphql/tax/sorters.py
.py
from ..core.doc_category import DOC_CATEGORY_TAXES from ..core.types import BaseEnum, SortInputObjectType class TaxClassSortField(BaseEnum): NAME = ["name", "pk"] class Meta: doc_category = DOC_CATEGORY_TAXES @property def description(self): if self.name in TaxClassSortField.__enum__...
24
699
hatch
backend/src/hatchling/plugin/__init__.py
.py
import pluggy hookimpl = pluggy.HookimplMarker("hatch")
4
57
kafka
tests/kafkatest/sanity_checks/__init__.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 ...
14
779
probability
tensorflow_probability/python/experimental/auto_batching/lowering.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...
480
21,061
probability
tensorflow_probability/python/distributions/chi_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...
166
6,134
wandb
wandb/integration/catboost/catboost.py
.py
"""catboost init.""" from __future__ import annotations from pathlib import Path from types import SimpleNamespace from catboost import CatBoostClassifier, CatBoostRegressor # type: ignore import wandb from wandb.sdk.lib import telemetry as wb_telemetry class WandbCallback: """`WandbCallback` automatically i...
186
6,009
rq
tests/test_job.py
.py
import json import queue import time import zlib from datetime import datetime, timezone from pickle import dumps, loads from uuid import uuid4 from rq.defaults import CALLBACK_TIMEOUT from rq.exceptions import DeserializationError, InvalidJobOperation, NoSuchJobError from rq.executions import Execution from rq.job im...
905
36,278
pyomo
pyomo/util/check_units.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...
305
9,979
pyomo
doc/OnlineDocs/src/scripting/driveabs2.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...
46
1,527
wandb
wandb/sdk/artifacts/_models/pagination.py
.py
"""Artifacts-specific data models for handling paginated results from GraphQL queries.""" from wandb._pydantic import Connection, ConnectionWithTotal from .._generated.fragments import ( ArtifactCollectionFragment, ArtifactFragment, ArtifactMembershipFragment, ArtifactTypeFragment, FileFragment, ...
28
985
sqlmap
tamper/sleep2getlock.py
.py
#!/usr/bin/env python """ Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org) See the file 'LICENSE' for copying permission """ from lib.core.data import kb from lib.core.enums import PRIORITY __priority__ = PRIORITY.HIGHEST def dependencies(): pass def tamper(payload, **kwargs): """ Replace...
40
867
wandb
tests/unit_tests/test_handler.py
.py
import queue from unittest.mock import MagicMock from wandb.proto import wandb_internal_pb2 as pb from wandb.sdk.internal import handler, settings_static def test_handle_sampled_history_empty(test_settings): result_q = queue.Queue() settings = test_settings({}) hm = handler.HandleManager( setting...
27
736
pyfilesystem2
fs/zipfs.py
.py
"""Manage the filesystem in a Zip archive. """ from __future__ import print_function, unicode_literals import sys import typing import six import zipfile from datetime import datetime from . import errors from ._url_tools import url_quote from .base import FS from .compress import write_zip from .enums import Resou...
512
17,756
wagtail
wagtail/documents/views/documents.py
.py
import os from django.contrib.admin.utils import quote from django.core.exceptions import PermissionDenied from django.http.response import HttpResponse as HttpResponse from django.utils.functional import cached_property from django.utils.http import urlencode from django.utils.translation import gettext as _ from dja...
334
11,666
returns
tests/test_io/test_ioresult_container/test_ioresulte_cast.py
.py
from returns.io import IOFailure, IOResult, IOResultE, IOSuccess from returns.pipeline import is_successful def _function(arg: int) -> IOResultE[float]: if arg == 0: return IOFailure(ZeroDivisionError('Divided by 0')) return IOSuccess(10 / arg) def test_ioresulte(): """Ensures that IOResultE cor...
18
512
mlflow
tests/store/artifact/test_unity_catalog_oss_models_artifact_repo.py
.py
import json from unittest import mock from unittest.mock import ANY from requests import Response from mlflow import MlflowClient from mlflow.store.artifact.optimized_s3_artifact_repo import OptimizedS3ArtifactRepository from mlflow.store.artifact.unity_catalog_oss_models_artifact_repo import ( UnityCatalogOSSMod...
84
3,350
readthedocs.org
readthedocs/embed/v3/tests/conftest.py
.py
import os import shutil import pytest from .utils import srcdir @pytest.fixture(autouse=True, scope="module") def remove_sphinx_build_output(): """Remove _build/ folder, if exist.""" for path in (srcdir,): build_path = os.path.join(path, "_build") if os.path.exists(build_path): sh...
15
344
saleor
saleor/order/tests/test_order_search.py
.py
from decimal import Decimal from ...discount import DiscountValueType from ..models import OrderLine from ..search import prepare_order_search_vector_value, update_order_search_vector def test_update_order_search_vector_auto_save(order): # given order.search_vector = "" order.save(update_fields=["search_...
115
3,134
mlflow
dev/clint/tests/rules/test_mlflow_class_name.py
.py
from pathlib import Path from clint.config import Config from clint.index import SymbolIndex from clint.linter import Position, Range, lint_file from clint.rules.mlflow_class_name import MlflowClassName def test_mlflow_class_name(index: SymbolIndex) -> None: code = """ # Bad - using MLflow class MLflowClient: ...
43
1,156
attrs
tests/strategies.py
.py
# SPDX-License-Identifier: MIT """ Testing strategies for Hypothesis-based tests. """ import functools import keyword import string from collections import OrderedDict from hypothesis import strategies as st import attr from .utils import make_class optional_bool = st.one_of(st.none(), st.booleans()) def gen_...
219
6,219
confluent-kafka-python
tests/schema_registry/_async/test_json.py
.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2023 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...
199
6,938
saleor
saleor/graphql/warehouse/mutations/warehouse_create.py
.py
from ....permission.enums import ProductPermissions from ....warehouse import models from ...account.i18n import I18nMixin from ...account.mixins import AddressMetadataMixin from ...core import ResolveInfo from ...core.mutations import DeprecatedModelMutation from ...core.types import WarehouseError from ...plugins.dat...
52
2,022
saleor
saleor/checkout/complete_checkout.py
.py
import datetime import logging from collections.abc import Iterable from decimal import Decimal from typing import TYPE_CHECKING, Any, Optional, cast from uuid import UUID import graphene from django.conf import settings from django.contrib.sites.models import Site from django.core.exceptions import ValidationError fr...
2,035
71,492
sqlmap
lib/core/decorators.py
.py
#!/usr/bin/env python """ Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org) See the file 'LICENSE' for copying permission """ import functools import threading from lib.core.datatype import LRUDict from lib.core.settings import MAX_CACHE_ITEMS from lib.core.threads import getCurrentThreadData _cache = ...
138
3,657
beam
sdks/python/apache_beam/runners/dataflow/template_runner_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...
80
2,965
conda
tests/core/test_index.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause from __future__ import annotations import copy from contextlib import nullcontext from logging import getLogger from typing import TYPE_CHECKING import pytest import conda from conda.base.constants import DEFAULTS_CHANNEL_NAME from conda.base...
556
18,824
probability
tensorflow_probability/python/mcmc/diagnostic.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...
590
25,387
probability
tensorflow_probability/substrates/meta/rewrite.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...
292
12,126
python-prompt-toolkit
examples/choices/with-frame.py
.py
from __future__ import annotations from prompt_toolkit.filters import is_done from prompt_toolkit.formatted_text import HTML from prompt_toolkit.shortcuts import choice from prompt_toolkit.styles import Style def main() -> None: style = Style.from_dict( { "frame.border": "#884444", ...
35
904
mlflow
mlflow/telemetry/schemas.py
.py
import json import platform import sys from dataclasses import dataclass from enum import Enum from typing import Any from mlflow.version import IS_MLFLOW_SKINNY, IS_TRACING_SDK_ONLY, VERSION class Status(str, Enum): UNKNOWN = "unknown" SUCCESS = "success" FAILURE = "failure" @dataclass class Record: ...
114
3,551
sphinx
tests/test_ext_autodoc/test_ext_autodoc_configs.py
.py
"""Test the autodoc extension. This tests mainly for config variables""" from __future__ import annotations import logging import platform import sys import pytest from sphinx.ext.autodoc._shared import _AutodocConfig from tests.test_ext_autodoc.autodoc_util import do_autodoc pytestmark = pytest.mark.usefixtures...
1,010
31,126
scikit-optimize
examples/sampler/initial-sampling-method.py
.py
""" ================================== Comparing initial sampling methods ================================== Holger Nahrstaedt 2020 Sigurd Carlsen October 2019 .. currentmodule:: skopt When doing baysian optimization we often want to reserve some of the early part of the optimization to pure exploration. By default...
170
5,407
pyomo
pyomo/repn/standard_aux.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...
36
1,456
beam
sdks/python/apache_beam/io/gcp/gcsio_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...
965
34,615
coremltools
coremltools/converters/mil/mil/ops/tests/iOS14/test_activation.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 itertools import numpy as np import pytest import scipy import coremltools as ct from coreml...
1,081
37,742
sqlmap
plugins/dbms/hana/__init__.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.enums import DBMS from lib.core.settings import HANA_SYSTEM_DBS from lib.core.unescaper import unescaper from plugins.dbms.hana.enumeration import Enumeration from p...
30
892
kombu
t/unit/test_log.py
.py
from __future__ import annotations import logging import sys from unittest.mock import ANY, Mock, patch from kombu.log import (Log, LogMixin, get_logger, get_loglevel, safeify_format, setup_logging) class test_get_logger: def test_when_string(self): logger = get_logger('foo') ...
148
4,803
beam
playground/infrastructure/api/v1/api_pb2_grpc.py
.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc from api.v1 import api_pb2 as api_dot_v1_dot_api__pb2 class PlaygroundServiceStub(object): """Missing associated documentation comment in .proto file.""" ...
713
34,221
pyomo
pyomo/opt/tests/base/test_convert.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...
218
6,990
wandb
wandb/_iterutils.py
.py
from __future__ import annotations from collections.abc import Hashable, Iterable from typing import TYPE_CHECKING, Any, TypeVar, overload if TYPE_CHECKING: T = TypeVar("T") HashableT = TypeVar("HashableT", bound=Hashable) ClassInfo = type[T] | tuple[type[T], ...] @overload def always_list(obj: Iterable...
74
2,726
saleor
saleor/checkout/fetch.py
.py
from collections.abc import Iterable from dataclasses import dataclass, field from decimal import Decimal from functools import cached_property from typing import TYPE_CHECKING, Optional from uuid import UUID from django.conf import settings from prices import Money from ..core.prices import quantize_price from ..cor...
388
13,848
flit
flit/vcs/hg.py
.py
import os from subprocess import check_output name = 'hg' def find_repo_root(directory): for p in [directory] + list(directory.parents): if (p / '.hg').is_dir(): return p def _repo_paths_to_directory_paths(paths, directory): # 'hg status' gives paths from repo root, which may not be our d...
35
1,258
clearml
examples/frameworks/pytorch-lightning/pytorch_lightning_example.py
.py
import sys from argparse import ArgumentParser import pytorch_lightning as pl import torch from torch.nn import functional as F from torch.utils.data import DataLoader, random_split from torchvision import transforms from torchvision.datasets.mnist import MNIST from clearml import Task class LitClassifier(pl.Lightn...
96
2,935
hydra
hydra/_internal/defaults_list.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import copy from dataclasses import dataclass, field from textwrap import dedent from typing import Callable, Dict, List, Optional, Set, Tuple, Union from omegaconf import OmegaConf from hydra import MissingConfigException from hydra._internal.co...
1,004
36,085