repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
openvino | tools/benchmark_tool/openvino/__init__.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
# Required for Windows OS platforms
# Note: always top-level
try:
from openvino.package_utils import _add_openvino_libs_to_search_path
_add... | 109 | 3,489 |
metrics | src/torchmetrics/functional/image/psnrb.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... | 143 | 4,858 |
mlflow | tests/resources/example_virtualenv_conda_project/entrypoint.py | .py | import argparse
import os
import sys
import numpy as np
import sklearn
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
import mlflow
parser = argparse.ArgumentParser()
parser.add_argument(
"--test",
action="store_true",
help="If spec... | 34 | 911 |
coremltools | deps/pybind11/tests/test_type_caster_pyobject_ptr.py | .py | from __future__ import annotations
import pytest
from pybind11_tests import type_caster_pyobject_ptr as m
# For use as a temporary user-defined object, to maximize sensitivity of the tests below.
class ValueHolder:
def __init__(self, value):
self.value = value
def test_cast_from_pyobject_ptr():
as... | 123 | 3,866 |
saleor | saleor/graphql/meta/tests/queries/test_shop.py | .py | from ....tests.utils import assert_no_permission, get_graphql_content
from .utils import PRIVATE_KEY, PRIVATE_VALUE, PUBLIC_KEY, PUBLIC_VALUE
SHOP_PRIVATE_AND_PUBLIC_METADATA_QUERY = """
query shopMetadata($key: String!, $privateKey: String!) {
shop {
metadata {
key
... | 104 | 3,192 |
pyro | pyro/contrib/gp/likelihoods/binary.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import torch
import pyro
import pyro.distributions as dist
from pyro.contrib.gp.likelihoods.likelihood import Likelihood
class Binary(Likelihood):
"""
Implementation of Binary likelihood, which is used for binary classif... | 56 | 1,988 |
pyomo | examples/gdp/two_rxn_lee/two_rxn_model.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... | 89 | 3,204 |
clearml | examples/datasets/urbansounds_dataset_preprocessing.py | .py | import os.path
from pathlib import Path
import matplotlib as mpl
import numpy as np
from tqdm import tqdm
import torchaudio
import torch
from clearml import Task, Dataset
task = Task.init(project_name="examples/Urbansounds", task_name="preprocessing")
# Let's preprocess the data and create a new ClearML dataset from... | 144 | 6,708 |
coremltools | deps/protobuf/python/google/protobuf/internal/unknown_fields_test.py | .py | # -*- coding: utf-8 -*-
# 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 a... | 478 | 20,145 |
mlflow | tests/xgboost/test_xgboost_model_export.py | .py | import json
import os
from pathlib import Path
from typing import Any, NamedTuple
from unittest import mock
import numpy as np
import pandas as pd
import pytest
import xgboost as xgb
import yaml
from sklearn import datasets
from sklearn.pipeline import Pipeline
import mlflow.pyfunc.scoring_server as pyfunc_scoring_se... | 696 | 27,191 |
loguru | tests/exceptions/source/modern/grouped_simple.py | .py | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", diagnose=True, backtrace=True, colorize=False)
def a():
x = 1
y = 0
x / y
def b():
a()
def c(f):
f()
@logger.catch
def main():
try:
c(b)
except Exception as error_1:
try:
... | 42 | 718 |
saleor | saleor/checkout/__init__.py | .py | import logging
logger = logging.getLogger(__name__)
class AddressType:
BILLING = "billing"
SHIPPING = "shipping"
CHOICES = [
(BILLING, "Billing"),
(SHIPPING, "Shipping"),
]
class CheckoutChargeStatus:
"""Determine the current charge status for the checkout.
The checkout is... | 70 | 2,164 |
cvxpy | cvxpy/utilities/psd_utils.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
... | 148 | 5,122 |
openvino | src/bindings/python/src/openvino/_ov_api.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import io
from types import TracebackType
from typing import Any, Union, Optional
from collections.abc import Iterator
from pathlib import Path
import traceback # noqa: F811
from openvino._pyopenvino import Mod... | 747 | 30,292 |
openvino | tests/layer_tests/tensorflow_tests/test_tf_Reciprocal.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 TestReciprocal(CommonTFLayerTest):
def _prepare_input(self, inputs_info):
assert 'x:0' in inputs_info
... | 82 | 3,236 |
conda | tests/shards/test_cache.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Tests for cache functionality with concurrent access and WAL mode."""
from __future__ import annotations
import platform
import threading
import pytest
from conda._private import zstd
from conda._private.shards.cache import AnnotatedRawSh... | 123 | 4,459 |
structlog | src/structlog/__init__.py | .py | # SPDX-License-Identifier: MIT OR Apache-2.0
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the MIT License. See the LICENSE file in the root of this
# repository for complete details.
from __future__ import annotations
from structlog import (
contextvars,
dev,
pr... | 129 | 2,911 |
pymc | tests/distributions/test_mixture.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... | 1,757 | 68,640 |
kombu | kombu/transport/SQS/exceptions.py | .py | """AWS SQS and SNS exceptions."""
from __future__ import annotations
from kombu.exceptions import KombuError
class UndefinedQueueException(KombuError):
"""Predefined queues are being used and an undefined queue was used."""
class UndefinedExchangeException(KombuError):
"""Predefined exchanges are being us... | 38 | 1,052 |
confluent-kafka-python | examples/adminapi_logger.py | .py | import logging
import sys
from confluent_kafka.admin import AdminClient
if len(sys.argv) != 2:
sys.stderr.write("Usage: %s <broker>\n" % sys.argv[0])
sys.exit(1)
broker = sys.argv[1]
# Custom logger
logger = logging.getLogger('AdminClient')
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
ha... | 52 | 1,706 |
openvino | src/frontends/paddle/tests/test_models/gen_scripts/generate_conv2d_relu.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import paddle
import numpy as np
import sys
from save_model import saveModel
if paddle.__version__ >= '2.6.0':
import paddle.base as fluid
else:
from paddle import fluid
paddle.enable_static()
inp_blob = np.random.randn(1, 3,... | 40 | 1,371 |
openvino | src/frontends/paddle/tests/test_models/gen_scripts/generate_swish.py | .py | #
# swish paddle model generator
#
import numpy as np
from save_model import saveModel
import paddle
import sys
def swish(name: str, x, data_type):
paddle.enable_static()
with paddle.static.program_guard(paddle.static.Program(), paddle.static.Program()):
node_x = paddle.static.data(
name=... | 49 | 1,332 |
openvino | src/frontends/paddle/tests/test_models/gen_scripts/generate_tensorarray.py | .py | import os
import sys
import numpy as np
import paddle
from save_model import exportModel
""""""""""""""""""""""""""""""""""""""""""""""""""""""
# tensorarray case: conditional_block + slice[0]
""""""""""""""""""""""""""""""""""""""""""""""""""""""
def test_conditional_block_slice0():
def test(model_name, inputs:... | 361 | 14,068 |
mlflow | tests/store/artifact/test_models_artifact_repo.py | .py | from pathlib import Path
from unittest import mock
import pytest
from mlflow import MlflowClient
from mlflow.entities.model_registry import ModelVersion
from mlflow.environment_variables import MLFLOW_TRACE_ARCHIVAL_CONFIG
from mlflow.store.artifact.databricks_models_artifact_repo import DatabricksModelsArtifactRepos... | 312 | 12,087 |
mlflow | mlflow/genai/evaluation/base.py | .py | import inspect
import logging
import os
import time
from contextlib import nullcontext
from typing import TYPE_CHECKING, Any, Callable, NamedTuple
import mlflow
from mlflow.data.dataset import Dataset
from mlflow.entities.dataset_input import DatasetInput
from mlflow.entities.evaluation_dataset import EvaluationDatase... | 715 | 28,358 |
mlflow | tests/resources/data/dataset.py | .py | import base64
import hashlib
import json
from typing import Any
import numpy as np
import pandas as pd
from mlflow.data.dataset import Dataset
from mlflow.types import Schema
from mlflow.types.utils import _infer_schema
from tests.resources.data.dataset_source import SampleDatasetSource
class SampleDataset(Dataset... | 68 | 1,881 |
kombu | t/unit/test_pidbox.py | .py | from __future__ import annotations
import multiprocessing
import socket
import warnings
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from unittest.mock import Mock, patch
import pytest
from kombu import Connection, pidbox
from kombu.exceptions import ContentDisallowed, InconsistencyError
fr... | 449 | 15,086 |
loguru | loguru/_string_parsers.py | .py | import datetime
import re
from typing import Optional, Tuple
class Frequencies:
"""Provide static methods to compute the next occurrence of various time frequencies.
Includes hourly, daily, weekly, monthly, and yearly frequencies
based on a given datetime object.
"""
@staticmethod
def hourly... | 361 | 9,326 |
wagtail | wagtail/contrib/redirects/tests/test_permissions.py | .py | from django.test import TestCase
from wagtail.contrib.redirects.models import Redirect
from wagtail.permission_policies import ModelPermissionPolicy
from wagtail.permissions import policy_registry
from wagtail.utils.deprecation import RemovedInWagtail90Warning
class TestRedirectPermissions(TestCase):
def test_pe... | 25 | 1,074 |
coremltools | coremltools/converters/mil/mil/ops/defs/iOS16/image_resizing.py | .py | # Copyright (c) 2022, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from coremltools.converters.mil.mil import types
from coremltools.converters.mil.mil.input_type import ... | 87 | 3,411 |
mlflow | mlflow/genai/scorers/trulens/models.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Any
import pydantic
from mlflow.exceptions import MlflowException
from mlflow.genai.scorers.llm_backend import ScorerLLMClient
from mlflow.genai.utils.message_utils import serialize_chat_messages_to_prompts
if TYPE_CHECKING:
from typing import... | 123 | 4,241 |
beam | sdks/python/apache_beam/ml/inference/huggingface_inference_it_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... | 149 | 5,952 |
biopython | Bio/TogoWS/__init__.py | .py | # Copyright 2010-2011, 2013-2014, 2016-2018 by Peter Cock. 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.
"... | 375 | 13,966 |
onnx | onnx/backend/test/case/node/gather.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 Gather(Base):
@staticmethod
def export_gather_0() -> None:
... | 92 | 2,378 |
pymc | pymc/step_methods/metropolis.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... | 1,258 | 43,178 |
saleor | saleor/graphql/account/tests/mutations/authentication/test_password_change.py | .py | from ......account import events as account_events
from ......site import PasswordLoginMode
from .....tests.utils import get_graphql_content, get_graphql_content_from_response
CHANGE_PASSWORD_MUTATION = """
mutation PasswordChange($oldPassword: String, $newPassword: String!) {
passwordChange(oldPassword: $... | 157 | 5,745 |
biopython | Bio/Sequencing/Ace.py | .py | # Copyright 2004 by Frank Kauff and Cymon J. Cox. 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.
"""Parser ... | 606 | 20,432 |
readthedocs.org | readthedocs/core/resolver.py | .py | """URL resolver for documentation."""
from functools import cache
from urllib.parse import urlunparse
import structlog
from django.conf import settings
from readthedocs.builds.constants import EXTERNAL
from readthedocs.builds.constants import INTERNAL
from readthedocs.core.utils.url import unsafe_join_url_path
from ... | 392 | 14,705 |
onnx | onnx/reference/ops/op_shrink.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import numpy as np
from onnx.reference.op_run import OpRun
class Shrink(OpRun):
def _run(self, x, bias=None, lambd=None):
return (
np.where(
x < -lambd,
... | 20 | 430 |
clearml | clearml/backend_api/services/v2_13/tasks.py | .py | """
tasks service
Provides a management API for tasks in the system.
"""
from typing import List, Optional, Any
import enum
from datetime import datetime
import six
from clearml.backend_api.session import (
Request,
BatchRequest,
Response,
NonStrictDataModel,
schema_property,
StringEnum,
)
from... | 12,079 | 422,228 |
readthedocs.org | readthedocs/api/v3/tests/test_builds.py | .py | from unittest import mock
from django.test import override_settings
from django.urls import reverse
from readthedocs.builds.constants import EXTERNAL
from readthedocs.projects.constants import PRIVATE, PUBLIC
from readthedocs.subscriptions.constants import TYPE_CONCURRENT_BUILDS
from readthedocs.subscriptions.product... | 678 | 25,480 |
loguru | tests/exceptions/source/diagnose/keyword_argument.py | .py | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", colorize=True, backtrace=False, diagnose=True)
def f(x):
return 1 / x
y = 0
with logger.catch():
f(x=y)
x = 0
with logger.catch():
f(x=x)
| 22 | 246 |
pyomo | pyomo/common/_command.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... | 45 | 1,221 |
mlflow | mlflow/xgboost/_autolog.py | .py | import logging
import xgboost
from packaging.version import Version
# Suppress a false positive pylint error: https://github.com/PyCQA/pylint/issues/1630
from mlflow.utils.autologging_utils import ExceptionSafeAbstractClass
_logger = logging.getLogger(__name__)
def _patch_metric_names(metric_dict):
# XGBoost p... | 74 | 2,774 |
openvino | src/frontends/tensorflow_lite/tests/test_models/gen_scripts/generate_sparse_oob.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# Generates malicious .tflite files for testing sparse tensor index validation.
# These files are structurally valid FlatBuffers but contain semantically invalid
# sparse index values that should be rejected during deserialization.
#
# T... | 365 | 12,676 |
gunicorn | tests/ctl/__init__.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
| 4 | 105 |
saleor | saleor/graphql/core/tests/test_file_validation.py | .py | from io import BytesIO
from unittest.mock import Mock, patch
import pytest
from django.core.exceptions import ValidationError
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import override_settings
from PIL import Image
from ....core.error_codes import UploadErrorCode
from ....product.... | 397 | 12,103 |
hydra | tests/standalone_apps/initialization_test_app/tests/test_app.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import subprocess
import sys
from typing import List
from pytest import mark, param
@mark.parametrize(
"run_cmd",
[
param(["initialization-test-app", "module_installed"], id="run_as_app"),
param(
[sys.executabl... | 25 | 684 |
returns | returns/pointfree/bind_async_future_result.py | .py | from collections.abc import Awaitable, Callable
from typing import TypeVar
from returns.future import FutureResult
from returns.interfaces.specific.future_result import FutureResultLikeN
from returns.primitives.hkt import Kinded, KindN, kinded
_FirstType = TypeVar('_FirstType')
_SecondType = TypeVar('_SecondType')
_T... | 80 | 2,334 |
pyomo | pyomo/core/base/units_container.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 1,544 | 58,852 |
beam | sdks/python/apache_beam/ml/inference/tensorflow_inference.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... | 374 | 14,711 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/dynamic_quantize_matmul.py | .py | import onnx
from onnx import TensorProto, helper
def GenerateModel(model_name, b_has_zp=True, has_bias=False, bias_ND=False): # noqa: N802
mul_output = "Mul_output" if has_bias else "output"
nodes = [ # construct graph
helper.make_node(
"DynamicQuantizeLinear",
["input"],
... | 77 | 2,654 |
astropy | astropy/visualization/wcsaxes/transforms.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# Note: This file includes code derived from pywcsgrid2
#
# This file contains Matplotlib transformation objects (e.g. from pixel to world
# coordinates, but also world-to-world).
import abc
import numpy as np
from matplotlib.path import Path
from matp... | 223 | 6,411 |
pyfilesystem2 | fs/opener/base.py | .py | # coding: utf-8
"""`Opener` abstract base class.
"""
import typing
import abc
import six
if typing.TYPE_CHECKING:
from typing import List, Text
from ..base import FS
from .parse import ParseResult
@six.add_metaclass(abc.ABCMeta)
class Opener(object):
"""The base class for filesystem openers.
... | 62 | 1,522 |
probability | tensorflow_probability/python/math/interpolation.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... | 1,211 | 49,832 |
mlflow | examples/mlflow-3/sklearn_autolog.py | .py | """
python examples/mlflow-3/sklearn_autolog.py
"""
import os
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, train_test_split
import mlflow
os.environ["MLFLOW_AUTOLOGGING_TESTING"] = "true"
mlflow.sklearn.autolog()
X, y ... | 41 | 996 |
mlflow | tests/store/model_registry/test_rest_store.py | .py | import json
import uuid
from unittest import mock
import pytest
from mlflow.entities.model_registry import ModelVersion, ModelVersionTag, RegisteredModelTag
from mlflow.entities.model_registry.model_version_status import ModelVersionStatus
from mlflow.exceptions import MlflowException
from mlflow.prompt.registry_util... | 517 | 16,369 |
toolz | bench/test_sliding_window.py | .py | from toolz import sliding_window
seq = range(1000000)
def test_sliding_window():
list(sliding_window(3, seq))
| 8 | 117 |
hydra | hydra/_internal/config_loader_impl.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import os
import sys
import warnings
from textwrap import dedent
from typing import Any, List, MutableSequence, Optional, Tuple, Union
from omegaconf import (
Container,
DictConfig,
ListConfig,
OmegaConf,
flag_overri... | 640 | 25,369 |
scikit-bio | skbio/io/util.py | .py | r"""I/O utilities (:mod:`skbio.io.util`)
====================================
.. currentmodule:: skbio.io.util
This module provides utility functions to deal with files and I/O in general.
Functions
---------
.. autosummary::
:toctree:
open
open_file
open_files
""" # noqa: D205, D415
# -------------... | 297 | 11,076 |
marshmallow | tests/mypy_test_cases/test_validation_error.py | .py | from __future__ import annotations
import marshmallow as ma
# OK types for 'message'
ma.ValidationError("foo")
ma.ValidationError(["foo"])
ma.ValidationError({"foo": "bar"})
# non-OK types for 'message'
ma.ValidationError(0) # type: ignore[arg-type]
# 'messages' is a dict|list
err = ma.ValidationError("foo")
a: di... | 21 | 579 |
mlflow | tests/pytorch/test_tensorboard_autolog.py | .py | import time
import mlflow
import mlflow.pytorch
NUM_EPOCHS = 20
START_STEP = 3
def test_pytorch_autolog_logs_expected_data(tmp_path):
from torch.utils.tensorboard import SummaryWriter
mlflow.pytorch.autolog(log_every_n_step=1)
writer = SummaryWriter(str(tmp_path))
timestamps = []
with mlflow.s... | 39 | 1,248 |
conda | tests/common/test_io_deferred_imports.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Verify that importing conda.common.io does not eagerly load concurrency modules."""
from __future__ import annotations
import subprocess
import sys
import textwrap
def test_io_does_not_eagerly_import_concurrent_futures() -> None:
"""c... | 51 | 1,622 |
kombu | kombu/asynchronous/http/__init__.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING
from kombu.asynchronous import get_event_loop
from kombu.asynchronous.http.base import Headers, Request, Response
from kombu.asynchronous.hub import Hub
if TYPE_CHECKING:
from kombu.asynchronous.http.curl import CurlClient
__all__ = ('Client', ... | 29 | 863 |
astropy | astropy/cosmology/_src/funcs/__init__.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Functions for `astropy.cosmology`."""
from .comparison import *
from .optimize import *
| 6 | 156 |
flit | flit_core/tests_core/test_wheel.py | .py | from pathlib import Path
from zipfile import ZipFile
from testpath import assert_isfile
from flit_core.wheel import make_wheel_in, main
samples_dir = Path(__file__).parent / 'samples'
def test_licenses_dir(tmp_path):
# Smoketest for https://github.com/pypa/flit/issues/399
info = make_wheel_in(samples_dir / ... | 56 | 2,072 |
structlog | tests/test_contextvars.py | .py | # SPDX-License-Identifier: MIT OR Apache-2.0
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the MIT License. See the LICENSE file in the root of this
# repository for complete details.
import asyncio
import inspect
import secrets
import pytest
import structlog
from structlog... | 305 | 9,087 |
pyomo | pyomo/contrib/mpc/data/get_cuid.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... | 94 | 4,452 |
cvxpy | cvxpy/tests/test_quad_dpp.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
... | 372 | 13,509 |
readthedocs.org | readthedocs/projects/filters.py | .py | """Filters used in project dashboard."""
import structlog
from django.db.models import Count
from django.db.models import F
from django.db.models import Max
from django.utils.translation import gettext_lazy as _
from django_filters import ChoiceFilter
from django_filters import OrderingFilter
from readthedocs.core.fi... | 279 | 9,864 |
gunicorn | gunicorn/workers/gtornado.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
import sys
try:
import tornado
except ImportError:
raise RuntimeError("You need tornado installed to use this worker.")
import tornado.web
import tornado.httpserver
from tornado.ioloop import IOL... | 125 | 3,905 |
pyro | tests/contrib/epidemiology/test_util.py | .py | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import pytest
import torch
from pyro.contrib.epidemiology.util import cat2, clamp
from tests.common import assert_equal
@pytest.mark.parametrize("min", [None, 0.0, (), (2,)], ids=str)
@pytest.mark.parametrize("max", [None, 1.0, (), ... | 45 | 1,492 |
saleor | saleor/product/tests/test_category.py | .py | from unittest.mock import patch
from ...discount.utils.promotion import get_active_catalogue_promotion_rules
from ...plugins.manager import get_plugins_manager
from ..models import Category
from ..utils import collect_categories_tree_products, delete_categories
def test_collect_categories_tree_products(categories_tr... | 75 | 2,529 |
wagtail | wagtail/contrib/redirects/views.py | .py | import os
from django.core.exceptions import SuspiciousOperation
from django.db import transaction
from django.shortcuts import redirect, render
from django.urls import reverse
from django.utils.encoding import force_str
from django.utils.functional import cached_property
from django.utils.translation import gettext a... | 424 | 13,206 |
wagtail | wagtail/admin/views/generic/permissions.py | .py | from django.core.exceptions import PermissionDenied
from django.utils.functional import cached_property
from wagtail.permissions import policy_registry
class PermissionCheckedMixin:
"""
Mixin for class-based views to enforce permission checks according to
a permission policy (see wagtail.permission_polic... | 56 | 2,003 |
pyro | pyro/distributions/diag_normal_mixture_shared_cov.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import math
import torch
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.distributions import Categorical, constraints
from pyro.distributions.torch_distribution import Torch... | 209 | 9,065 |
openvino | tests/e2e_tests/common/ref_collector/provider.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import inspect
from e2e_tests.common.common.base_provider import BaseProvider, BaseStepProvider
class ClassProvider(BaseProvider):
registry = {}
@classmethod
def validate(cls):
methods = [
f[0] for f in... | 35 | 1,064 |
probability | tensorflow_probability/python/experimental/mcmc/kernel_builder_test.py | .py | # Copyright 2020 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 126 | 5,123 |
gunicorn | examples/frameworks/cherryapp.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import cherrypy
class Root:
@cherrypy.expose
def index(self):
return 'Hello World!'
cherrypy.config.update({'environment': 'embedded'})
app = cherrypy.tree.mount(Root())
| 16 | 296 |
astropy | astropy/visualization/basic_rgb.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Combine 3 images to produce properly-scaled RGB images with arbitrary scaling.
The three images must be aligned and have the same pixel scale and size.
"""
import numpy as np
from astropy.visualization.interval import ManualInterval
from astropy.vis... | 218 | 7,277 |
wandb | wandb/integration/kfp/wandb_log_v1.py | .py | def wandb_log( # noqa: C901
func=None,
# /, # py38 only
log_component_file=True,
):
"""Wrap a kfp v1 python functional component and log to W&B.
Requires kfp<2.0.0. Deprecated -- please upgrade to kfp>=2.0.0.
"""
import json
import os
from functools import wraps
from inspect i... | 197 | 6,768 |
pyro | pyro/contrib/oed/glmm/__init__.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
"""
.. warning :: This module will eventually be deprecated in favor of `brmp <https://github.com/pyro-ppl/brmp/>`_
The :mod:`pyro.contrib.oed.glmm` module provides models and guides for
generalised linear mixed models (GLMM). It ... | 41 | 1,551 |
wandb | wandb/cli/cli.py | .py | from __future__ import annotations
import asyncio
import getpass
import json
import logging
import os
import pathlib
import shlex
import shutil
import subprocess
import sys
import tempfile
import textwrap
import time
import traceback
from functools import wraps
from typing import Any
import click
import yaml
from cli... | 3,755 | 118,910 |
saleor | saleor/core/views.py | .py | import logging
import os
from django.conf import settings
from django.http import FileResponse, Http404, HttpRequest, HttpResponse, JsonResponse
from django.template.response import TemplateResponse
from django.views.static import serve
from .jwt_manager import get_jwt_manager
logger = logging.getLogger(__name__)
... | 62 | 2,274 |
wagtail | wagtail/api/v3/tests/test_page_actions.py | .py | import json
from django.contrib.auth.models import AnonymousUser, Group, Permission
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from wagtail.api.v3.tests.base import TestV3Base
from wagtail.models import GroupPagePermission, Locale
from wagtail... | 1,009 | 40,925 |
gunicorn | gunicorn/workers/workertmp.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
import time
import platform
import tempfile
from gunicorn import util
PLATFORM = platform.system()
IS_CYGWIN = PLATFORM.startswith('CYGWIN')
class WorkerTmp:
def __init__(self, cfg):
old_... | 54 | 1,604 |
onnx | onnx/reference/ops/_op.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import numpy as np
from onnx.reference.op_run import OpRun, RuntimeTypeError
if TYPE_CHECKING:
from onnx.onnx_pb import NodeProto
class OpRunUnary(OpRun):
... | 183 | 6,219 |
readthedocs.org | readthedocs/api/v2/serializers.py | .py | """Defines serializers for each of our models."""
from allauth.socialaccount.models import SocialAccount
from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import gettext as _
from generic_relations.relations import GenericRelatedField
from rest_framework import serializers
from readt... | 429 | 14,428 |
pyomo | pyomo/contrib/preprocessing/tests/test_bounds_to_vars_xfrm.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... | 116 | 3,904 |
wagtail | wagtail/contrib/frontend_cache/apps.py | .py | from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
from wagtail.contrib.frontend_cache.signal_handlers import register_signal_handlers
class WagtailFrontendCacheAppConfig(AppConfig):
name = "wagtail.contrib.frontend_cache"
label = "wagtailfrontendcache"
verbose_name ... | 14 | 407 |
clearml | examples/frameworks/keras/keras_v3.py | .py | import numpy as np
import keras
from clearml import Task
def get_model():
# Create a simple model.
inputs = keras.Input(shape=(32,))
outputs = keras.layers.Dense(1)(inputs)
model = keras.Model(inputs, outputs)
model.compile(optimizer=keras.optimizers.Adam(), loss="mean_squared_error")
return m... | 29 | 719 |
coremltools | coremltools/converters/mil/mil/ops/defs/iOS15/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 math
import numpy as np
from coremltools.converters.mil.mil import types
from coremltools.co... | 622 | 15,398 |
textual | docs/examples/guide/reactivity/world_clock02.py | .py | from datetime import datetime
from pytz import timezone
from textual.app import App, ComposeResult
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import Digits, Label
class WorldClock(Widget):
time: reactive[datetime] = reactive(datetime.now)
def __init__(self... | 48 | 1,310 |
probability | tensorflow_probability/python/internal/backend/numpy/initializers.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... | 38 | 1,201 |
kafka | tests/kafkatest/version.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 ... | 266 | 8,386 |
textual | src/textual/widgets/_welcome.py | .py | """Provides a Textual welcome widget."""
from rich.markdown import Markdown
from textual.app import ComposeResult
from textual.containers import Container
from textual.widgets._button import Button
from textual.widgets._static import Static
WELCOME_MD = """\
# Welcome!
Textual is a TUI, or *Text User Interface*, fr... | 60 | 1,535 |
python-prompt-toolkit | src/prompt_toolkit/log.py | .py | """
Logging configuration.
"""
from __future__ import annotations
import logging
__all__ = [
"logger",
]
logger = logging.getLogger(__package__)
| 14 | 153 |
pyomo | pyomo/contrib/piecewise/tests/test_triangulations.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... | 244 | 9,310 |
mlflow | examples/sktime/test_sktime_model_export.py | .py | import os
from pathlib import Path
from unittest import mock
import boto3
import flavor
import moto
import numpy as np
import pandas as pd
import pytest
from botocore.config import Config
from sktime.datasets import load_airline, load_longley
from sktime.datatypes import convert
from sktime.forecasting.arima import Au... | 388 | 15,194 |
sqlmap | tamper/versionedmorekeywords.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
import os
import re
from lib.core.common import singleTimeWarnMessage
from lib.core.data import kb
from lib.core.enums import DBMS
from lib.core.enums import PRIORITY
from lib.co... | 54 | 1,742 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.