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 |
|---|---|---|---|---|---|
beam | sdks/python/apache_beam/examples/complete/game/leader_board.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... | 369 | 13,292 |
scikit-optimize | examples/parallel-optimization.py | .py | """
=====================
Parallel optimization
=====================
Iaroslav Shcherbatyi, May 2017.
Reviewed by Manoj Kumar and Tim Head.
Reformatted by Holger Nahrstaedt 2020
.. currentmodule:: skopt
Introduction
============
For many practical black box optimization problems expensive objective can be
evaluated... | 82 | 3,174 |
probability | tensorflow_probability/python/bijectors/gompertz_cdf.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... | 156 | 5,902 |
mlflow | tests/models/test_auth_policy.py | .py | from mlflow.models.auth_policy import AuthPolicy, SystemAuthPolicy, UserAuthPolicy
from mlflow.models.resources import (
DatabricksFunction,
DatabricksServingEndpoint,
DatabricksUCConnection,
DatabricksVectorSearchIndex,
)
def test_complete_auth_policy():
system_auth_policy = SystemAuthPolicy(
... | 121 | 4,075 |
saleor | saleor/checkout/tests/webhooks/subscriptions/test_list_shipping_methods.py | .py | import json
import graphene
import pytest
from .....shipping.interface import ShippingMethodData
from .....shipping.models import ShippingMethod
from .....shipping.utils import convert_to_shipping_method_data
from .....webhook.event_types import WebhookEventSyncType
from .....webhook.transport.asynchronous.transport ... | 114 | 3,323 |
biopython | Bio/Graphics/GenomeDiagram/_FeatureSet.py | .py | # Copyright 2003-2008 by Leighton Pritchard. 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.
#
# Contact: ... | 208 | 7,774 |
astropy | astropy/units/deprecated.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This package defines deprecated units.
These units are not available in the top-level `astropy.units`
namespace. To use these units, you must import the `astropy.units.deprecated`
module::
>>> from astropy.units import deprecated
>>> q = 10. ... | 72 | 2,333 |
openvino | tools/ovc/unit_tests/moc_tf_fe/test_models/placeholder_with_default.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import tensorflow.compat.v1 as tf
tf.reset_default_graph()
with tf.Session() as sess:
x = tf.placeholder(tf.int32, [None, 3], 'x')
y = tf.placeholder_with_default(tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int32),
... | 17 | 517 |
openvino | src/frontends/paddle/tests/test_models/gen_scripts/generate_reduce_prod.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
# reduce_prod paddle model generator
#
import numpy as np
import sys
from save_model import saveModel
def reduce_prod(name : str, x, axis=None, keepdim=False):
import paddle
paddle.enable_static()
with paddle.static.pro... | 47 | 1,490 |
mlflow | mlflow/utils/nfs_on_spark.py | .py | import os
import shutil
import uuid
from mlflow.utils._spark_utils import _get_active_spark_session
from mlflow.utils.databricks_utils import (
get_databricks_nfs_temp_dir,
is_databricks_connect,
is_in_databricks_runtime,
is_in_databricks_serverless_runtime,
)
# Set spark config "spark.mlflow.nfs.root... | 63 | 2,698 |
ipython | IPython/utils/generics.py | .py | """Generic functions for extending IPython."""
from __future__ import annotations
import warnings
from typing import Any
from IPython.core.error import TryNext
from functools import singledispatch
@singledispatch
def _inspect_object(obj: Any) -> None:
"""Called when you do obj?
.. deprecated:: 9.15
... | 52 | 1,498 |
pyomo | pyomo/contrib/pyros/tests/test_config.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... | 800 | 27,590 |
hydra | plugins/hydra_rq_launcher/hydra_plugins/hydra_rq_launcher/serializer.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import cloudpickle # type: ignore
class CloudpickleSerializer:
dumps = cloudpickle.dumps
loads = cloudpickle.loads
| 9 | 198 |
onnxruntime | onnxruntime/python/tools/transformers/constants.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
class Operators:
ATTENTION = "Attention"
LAYERNORM = "LayerNor... | 48 | 1,080 |
cvxpy | cvxpy/reductions/dgp2dcp/canonicalizers/eye_minus_inv_canon.py | .py | from cvxpy.atoms.affine.binary_operators import matmul
from cvxpy.atoms.affine.diag import diag
from cvxpy.atoms.one_minus_pos import one_minus_pos
from cvxpy.expressions.variable import Variable
from cvxpy.reductions.dgp2dcp.canonicalizers.mulexpression_canon import (
mulexpression_canon,
)
from cvxpy.reductions.d... | 44 | 1,434 |
wandb | wandb/sdk/lib/urls.py | .py | """Validation for URLs."""
from pydantic_core import SchemaValidator, core_schema
_URL_VALIDATOR = SchemaValidator(
core_schema.url_schema(
allowed_schemes=["http", "https"],
strict=True,
)
)
def validate_url(url: object) -> None:
"""Validate a URL.
Args:
url: The URL to val... | 27 | 587 |
wandb | wandb/sdk/artifacts/storage_handlers/s3_handler.py | .py | """S3 storage handler."""
from __future__ import annotations
import os
import re
from pathlib import PurePosixPath
from typing import TYPE_CHECKING
from urllib.parse import parse_qsl, urlparse
from wandb import util
from wandb._strutils import ensureprefix
from wandb.errors import CommError
from wandb.errors.term im... | 343 | 12,853 |
mlflow | tests/store/artifact/test_databricks_run_artifact_repo.py | .py | from pathlib import Path
from unittest import mock
import pytest
from databricks.sdk.service.files import DirectoryEntry
from mlflow.entities.file_info import FileInfo
from mlflow.store.artifact.databricks_run_artifact_repo import DatabricksRunArtifactRepository
@pytest.fixture(autouse=True)
def set_fake_databricks... | 279 | 10,699 |
wagtail | wagtail/images/tests/test_api_v3/test_custom_image_model.py | .py | from django.contrib.auth.models import Group, Permission
from django.test import TestCase, override_settings
from ninja import Schema
from wagtail.api.v3.schemas import create_generator, patch_generator, read_generator
from wagtail.api.v3.schemas.base import BaseSchema
from wagtail.images.api.v3.form_data import build... | 97 | 4,227 |
openvino | src/bindings/python/tests/conftest.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import pytest
def pytest_configure(config):
# register additional markers
config.addinivalue_line("markers", "skip_on_cpu: Skip test on CPU")
config.addinivalue_line("markers", "skip_on_gp... | 24 | 886 |
openvino | tests/layer_tests/pytorch_tests/test_resolve_conj_neg.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
from pytorch_layer_test_class import PytorchLayerTest
class TestResolveConjNeg(PytorchLayerTest):
def _prepare_input(self, dtype="float32"):
import numpy as np
return (self.random.randn(2, 4, dtype=dt... | 58 | 1,924 |
tqdm | tqdm/contrib/telegram.py | .py | """
Sends updates to a Telegram bot.
Usage:
>>> from tqdm.contrib.telegram import tqdm, trange
>>> for i in trange(10, token='{token}', chat_id='{chat_id}'):
... ...

"""
from warnings import warn
from requests import Session
from ..auto import tq... | 153 | 5,081 |
kombu | t/unit/utils/test_time.py | .py | from __future__ import annotations
import pytest
from kombu.utils.time import maybe_s_to_ms
@pytest.mark.parametrize('input,expected', [
(3, 3000),
(3.0, 3000),
(303, 303000),
(303.33, 303330),
(303.333, 303333),
(303.3334, 303333),
(None, None),
(0, 0),
])
def test_maybe_s_to_ms(inp... | 24 | 459 |
saleor | saleor/permission/models.py | .py | from django.contrib import auth
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.db import models
from django.utils.translation import gettext_lazy as _
def _user_has_perm(user, perm, obj):
"""Backend can raise `PermissionDenied` to short-c... | 164 | 6,026 |
coremltools | coremltools/optimize/torch/pruning/_utils.py | .py | # Copyright (c) 2024, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import logging as _logging
from typing import List as _List
from typing import Optional as _Optional
... | 242 | 8,804 |
mlflow | mlflow/server/graphql/autogenerated_graphql_schema.py | .py | # GENERATED FILE. PLEASE DON'T MODIFY.
# Run uv run ./dev/proto_to_graphql/code_generator.py to regenerate.
import graphene
import mlflow
from mlflow.server.graphql.graphql_custom_scalars import LongString
from mlflow.server.graphql.graphql_errors import ApiError
from mlflow.utils.proto_json_utils import parse_dict
c... | 356 | 11,751 |
openvino | tests/layer_tests/onnx_tests/test_unsqueeze.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
from common.onnx_layer_test_class import OnnxRuntimeLayerTest, onnx_make_model
class TestUnsqueeze(OnnxRuntimeLayerTest):
def create_unsqueeze_net(self, axes, input_shape, output_shape, ir_version):
"""
... | 223 | 9,296 |
textual | tests/test_overflow_change.py | .py | """Regression test for #1616 https://github.com/Textualize/textual/issues/1616"""
from textual.app import App
from textual.containers import VerticalScroll
async def test_overflow_change_updates_virtual_size_appropriately():
class MyApp(App):
def compose(self):
yield VerticalScroll()
app... | 36 | 1,049 |
probability | tensorflow_probability/python/distributions/linear_gaussian_ssm_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... | 1,776 | 73,987 |
beam | sdks/python/apache_beam/runners/worker/log_handler_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... | 327 | 11,538 |
confluent-kafka-python | tests/integration/admin/test_describe_operations.py | .py | # -*- coding: utf-8 -*-
# Copyright 2022 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | 246 | 7,693 |
mlflow | mlflow/anthropic/autolog.py | .py | import logging
from typing import Any
import mlflow.anthropic
from mlflow.anthropic.chat import convert_tool_to_mlflow_chat_tool
from mlflow.entities import SpanType
from mlflow.entities.span import LiveSpan
from mlflow.tracing.constant import SpanAttributeKey, TokenUsageKey
from mlflow.tracing.distributed import _get... | 204 | 8,186 |
cvxpy | cvxpy/reductions/dgp2dcp/canonicalizers/xexp_canon.py | .py | from cvxpy.atoms.elementwise.exp import exp
def xexp_canon(expr, args):
del expr
return args[0] + exp(args[0]), []
| 7 | 125 |
openvino | samples/python/benchmark/throughput_benchmark/throughput_benchmark.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import logging as log
import sys
import statistics
from time import perf_counter
import numpy as np
import openvino as ov
from openvino.utils.types import get_dtype
def fill_tensor_random... | 89 | 3,420 |
mlflow | mlflow/genai/judges/tools/get_trace_info.py | .py | """
Get trace info tool for MLflow GenAI judges.
This module provides a tool for retrieving trace metadata including
timing, location, state, and other high-level information.
"""
from mlflow.entities.trace import Trace
from mlflow.entities.trace_info import TraceInfo
from mlflow.genai.judges.tools.base import JudgeT... | 61 | 1,871 |
saleor | saleor/payment/gateways/utils.py | .py | import warnings
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..interface import GatewayConfig
def get_supported_currencies(config: "GatewayConfig", gateway_name: str) -> list[str]:
"""Return supported currencies for given gateway configuration.
If supported currencies are not specified, the d... | 26 | 798 |
saleor | saleor/graphql/translations/mutations/promotion_translate.py | .py | import graphene
from ....discount import models as discount_models
from ....permission.enums import SitePermissions
from ...core import ResolveInfo
from ...core.descriptions import RICH_CONTENT
from ...core.enums import LanguageCodeEnum
from ...core.scalars import JSON
from ...core.types import TranslationError
from .... | 62 | 2,350 |
astropy | astropy/config/paths.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""This module contains functions to determine where configuration and
data/cache files used by Astropy should be placed.
"""
import os
import re
import shutil
import sys
from collections.abc import Callable, Generator
from contextlib import contextmanage... | 818 | 26,549 |
mlflow | mlflow/genai/datasets/databricks_evaluation_dataset_source.py | .py | from typing import Any
from mlflow.data.dataset_source import DatasetSource
class DatabricksEvaluationDatasetSource(DatasetSource):
"""
Represents a Databricks Evaluation Dataset source.
This source is used for datasets managed by the Databricks agents SDK.
"""
def __init__(
self,
... | 103 | 3,057 |
mamba | micromamba/tests/test_update.py | .py | import os
import platform
import shutil
import sys
from pathlib import Path
import pytest
import yaml
# Need to import everything to get fixtures
from .helpers import * # noqa: F403
from . import helpers
env_yaml_content_pip_deps = """
channels:
- conda-forge
dependencies:
- pip
- pip:
- numpy
"""
@pytest.mark.... | 587 | 21,407 |
onnxruntime | orttraining/orttraining/python/training/optim/_modifier_registry.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
from __future__ import annotations
import warnings
from typing import C... | 62 | 2,513 |
mlflow | tests/tracking/context/test_databricks_repo_context.py | .py | from unittest import mock
from mlflow.tracking.context.databricks_repo_context import DatabricksRepoRunContext
from mlflow.utils.mlflow_tags import (
MLFLOW_DATABRICKS_GIT_REPO_COMMIT,
MLFLOW_DATABRICKS_GIT_REPO_PROVIDER,
MLFLOW_DATABRICKS_GIT_REPO_REFERENCE,
MLFLOW_DATABRICKS_GIT_REPO_REFERENCE_TYPE,
... | 85 | 3,804 |
wagtail | wagtail/admin/views/collection_privacy.py | .py | from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404
from django.urls import reverse
from wagtail.admin.forms.collections import CollectionViewRestrictionForm
from wagtail.admin.modal_workflow import render_modal_workflow
from wagtail.models import Collection, CollectionVi... | 86 | 3,238 |
probability | tensorflow_probability/python/distributions/onehot_categorical.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... | 376 | 15,130 |
hatch | tests/backend/version/scheme/test_standard.py | .py | import pytest
from packaging.version import _parse_letter_version # noqa: PLC2701
from hatch.utils.structures import EnvVars
from hatchling.utils.constants import VersionEnvVars
from hatchling.version.scheme.standard import StandardScheme
def test_not_higher(isolation):
scheme = StandardScheme(str(isolation), {... | 149 | 5,092 |
beam | sdks/python/apache_beam/testing/analyzers/perf_analysis_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... | 275 | 10,530 |
wandb | wandb/sdk/lib/printer.py | .py | """Terminal, Jupyter and file output for W&B."""
from __future__ import annotations
import abc
import contextlib
import itertools
import platform
import sys
from collections.abc import Callable, Generator
import click
from typing_extensions import override
import wandb
import wandb.util
from wandb.errors import ter... | 559 | 15,879 |
funcy | tests/test_decorators.py | .py | import sys
import pytest
from funcy.decorators import *
def test_decorator_no_args():
@decorator
def inc(call):
return call() + 1
@inc
def ten():
return 10
assert ten() == 11
def test_decorator_with_args():
@decorator
def add(call, n):
return call() + n
@ad... | 168 | 3,475 |
openvino | tests/layer_tests/pytorch_tests/test_hadsigmoid.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
from pytorch_layer_test_class import PytorchLayerTest, skip_if_export
class TestHardSigmoid(PytorchLayerTest):
def _prepare_input(self, shape, dtype):
return (self.random.randn(*shape, dtype=dtype),)
def... | 36 | 1,319 |
saleor | saleor/graphql/account/mutations/permission_group/__init__.py | .py | from .permission_group_create import PermissionGroupCreate
from .permission_group_delete import PermissionGroupDelete
from .permission_group_update import PermissionGroupUpdate
__all__ = [
"PermissionGroupCreate",
"PermissionGroupDelete",
"PermissionGroupUpdate",
]
| 10 | 279 |
pyro | pyro/infer/tracetmc_elbo.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import queue
import warnings
import torch
import pyro.poutine as poutine
from pyro.distributions.util import is_identically_zero
from pyro.infer.elbo import ELBO
from pyro.infer.enum import (
get_importance_trace,
iter_di... | 230 | 8,714 |
biopython | Bio/PDB/Chain.py | .py | # Copyright (C) 2002, Thomas Hamelryck (thamelry@binf.ku.dk)
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Chain class, used... | 227 | 7,101 |
openvino | tests/layer_tests/tensorflow_tests/test_tf_EnsureShape.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 TestEnsureShape(CommonTFLayerTest):
def _prepare_input(self, inputs_info):
assert 'tensor:0' in inputs_... | 45 | 1,761 |
clearml | clearml/utilities/lowlevel/file_access.py | .py | import os
import sys
from functools import partial
from typing import Optional, Callable, Any
def __buffer_writer_close_patch(self) -> None:
self._trains_org_close()
# noinspection PyBroadException
try:
self._trains_close_cb(self)
except Exception:
pass
def buffer_writer_close_cb(buf... | 90 | 3,365 |
django-cms | cms/tests/test_page.py | .py | import datetime
import functools
import os.path
from unittest import skipIf
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.sites.models import Site
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.db import models
fr... | 1,105 | 47,642 |
beam | sdks/python/apache_beam/runners/worker/data_sampler_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... | 628 | 24,305 |
black | tests/data/cases/allow_empty_first_line.py | .py | def foo():
"""
Docstring
"""
# Here we go
if x:
# This is also now fine
a = 123
else:
# But not necessary
a = 123
if y:
while True:
"""
Long comment here
"""
a = 123
if z:
for _ in... | 167 | 1,794 |
astropy | astropy/units/quantity_helper/erfa.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Quantity helpers for the ERFA ufuncs."""
# Tests for these are in coordinates, not in units.
# Note that when this is imported, the unit definitions have not yet
# been completed, so we import units locally.
# We also avoid importing erfa up front since... | 534 | 15,415 |
sqlmap | thirdparty/colorama/winterm.py | .py | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
try:
from msvcrt import get_osfhandle
except ImportError:
def get_osfhandle(_):
raise OSError("This isn't windows!")
from . import win32
# from wincon.h
class WinColor(object):
BLACK = 0
BLUE = 1
GREEN = 2
... | 196 | 7,134 |
hatch | backend/src/hatchling/builders/hooks/plugin/hooks.py | .py | from __future__ import annotations
import typing
from hatchling.builders.hooks.custom import CustomBuildHook
from hatchling.builders.hooks.version import VersionBuildHook
from hatchling.plugin import hookimpl
if typing.TYPE_CHECKING:
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
@hoo... | 17 | 545 |
beam | sdks/python/apache_beam/yaml/readme_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... | 395 | 13,389 |
openvino | tests/layer_tests/jax_tests/test_reduce_window_sum.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
from jax import lax
from jax import numpy as jnp
from jax_layer_test_class import JaxLayerTest
class TestReduceWindoSum(JaxLayerTest):
def _prepare_input(self):
inp = jnp.array(np.random.ra... | 54 | 1,838 |
coremltools | coremltools/converters/mil/mil/types/type_str.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
from .annotate import annotate, class_annotate, delay_type
from .type_spec import Type
@class_annot... | 23 | 641 |
python-prompt-toolkit | examples/prompts/auto-completion/combine-multiple-completers.py | .py | #!/usr/bin/env python
"""
Example of multiple individual completers that are combined into one.
"""
from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter, merge_completers
animal_completer = WordCompleter(
[
"alligator",
"ant",
"ape",
"bat",
... | 78 | 1,388 |
beam | sdks/python/apache_beam/examples/inference/huggingface_question_answering.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,991 |
sphinx | tests/test_ext_autodoc/test_ext_autodoc_autoproperty.py | .py | """Test the autodoc extension.
This tests mainly the Documenters; the auto directives are tested in a test
source file translated by test_build.
"""
from __future__ import annotations
import sys
import pytest
from tests.test_ext_autodoc.autodoc_util import do_autodoc
pytestmark = pytest.mark.usefixtures('inject_a... | 112 | 2,846 |
metrics | tests/unittests/regression/test_mean_error.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... | 393 | 16,728 |
sqlmap | lib/core/threads.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
from __future__ import print_function
import difflib
import sqlite3
import threading
import time
import traceback
from lib.core.compat import WichmannHill
from lib.core.compat i... | 272 | 8,741 |
astropy | astropy/cosmology/realizations.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Built-in cosmologies.
See :attr:`~astropy.cosmology.realizations.available` for a full list.
"""
__all__ = [ # noqa: F822, RUF022
"available",
"default_cosmology",
# ----
"WMAP1",
"WMAP3",
"WMAP5",
"WMAP7",
"WMAP9",
... | 76 | 1,684 |
textual | src/textual/demo/projects.py | .py | from __future__ import annotations
from textual import events, on
from textual.app import ComposeResult
from textual.binding import Binding
from textual.containers import Center, Horizontal, ItemGrid, Vertical, VerticalScroll
from textual.demo._project_data import PROJECTS, ProjectInfo
from textual.demo._project_stars... | 138 | 3,824 |
mlflow | tests/projects/conftest.py | .py | import os
import shutil
import git
import pytest
from tests.projects.utils import GIT_PROJECT_BRANCH, TEST_PROJECT_DIR
@pytest.fixture
def local_git_repo(tmp_path):
local_git = str(tmp_path.joinpath("git_repo"))
repo = git.Repo.init(local_git)
shutil.copytree(src=TEST_PROJECT_DIR, dst=local_git, dirs_ex... | 25 | 657 |
wagtail | wagtail/tests/test_signals.py | .py | from unittest import mock
from django.conf import settings
from django.test import TestCase
from wagtail.models import Locale, Site
from wagtail.signals import copy_for_translation_done, page_slug_changed
from wagtail.test.testapp.models import EventCategory, SimplePage
from wagtail.test.utils import WagtailTestUtils... | 166 | 6,122 |
pyro | pyro/contrib/examples/bart.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import argparse
import bz2
import csv
import datetime
import logging
import multiprocessing
import os
import subprocess
import sys
import urllib
from functools import partial
import torch
from pyro.contrib.examples.util import _m... | 189 | 6,858 |
mlflow | tests/metrics/genai/test_model_utils.py | .py | import copy
import json
import sys
from unittest import mock
import pytest
import requests
from mlflow.exceptions import MlflowException
from mlflow.genai.utils.gateway_utils import GatewayConfig
from mlflow.metrics.genai import model_utils
from mlflow.metrics.genai.model_utils import (
_MODELS_WITHOUT_OUTPUT_CON... | 842 | 29,498 |
wagtail | wagtail/contrib/legacy/richtext/tests/test_templatetag.py | .py | from django.test import TestCase
from wagtail.templatetags.wagtailcore_tags import richtext
class TestTemplateTag(TestCase):
def test_no_contrib_legacy_richtext_no_wrapper(self):
self.assertEqual(richtext("Foo"), "Foo")
def test_contrib_legacy_richtext_renders_wrapper(self):
with self.modify... | 15 | 502 |
cvxpy | cvxpy/lin_ops/__init__.py | .py | """
Copyright 2013 Steven Diamond
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... | 19 | 684 |
mlflow | tests/store/artifact/test_artifact_repo_attachments.py | .py | import json
import uuid
import pytest
from mlflow.exceptions import MlflowException, MlflowTraceDataNotFound
from mlflow.store.artifact.local_artifact_repo import LocalArtifactRepository
def test_upload_attachment(tmp_path):
repo = LocalArtifactRepository(str(tmp_path))
attachment_id = str(uuid.uuid4())
... | 120 | 3,951 |
saleor | saleor/graphql/payment/schema.py | .py | import graphene
from ...permission.enums import OrderPermissions, PaymentPermissions
from ..core import ResolveInfo
from ..core.connection import create_connection_slice, filter_connection_queryset
from ..core.descriptions import (
ADDED_IN_322,
ADDED_IN_323,
DEPRECATED_LEGACY_PAYMENTS,
)
from ..core.doc_c... | 197 | 6,912 |
omegaconf | tests/examples/dataclass_postponed_annotations.py | .py | # `from __future__` has to be the very first thing in a module
# otherwise a syntax error is raised
from __future__ import annotations
from dataclasses import dataclass, fields
from enum import Enum
from pathlib import Path
from pytest import raises
from omegaconf import OmegaConf, ValidationError
class Height(Enu... | 57 | 1,477 |
saleor | saleor/graphql/attribute/tests/queries/test_attribute_query.py | .py | import graphene
import pytest
from django.db.models import Q
from graphene.utils.str_converters import to_camel_case
from .....attribute import AttributeInputType, AttributeType
from .....attribute.models import Attribute
from .....product import ProductTypeKind
from .....product.models import Category, Collection, Pr... | 1,296 | 41,822 |
biopython | Bio/SearchIO/InterproscanIO/interproscan_xml.py | .py | # Copyright 2018 by Adhemar Zerlotini. 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.
"""Bio.SearchIO parse... | 197 | 7,547 |
tqdm | examples/redirect_print.py | .py | """Redirecting writing
If using a library that can print messages to the console, editing the library
by replacing `print()` with `tqdm.write()` may not be desirable.
In that case, redirecting `sys.stdout` to `tqdm.write()` is an option.
To redirect `sys.stdout`, create a file-like class that will write
any input st... | 51 | 1,484 |
openvino | tests/layer_tests/pytorch_tests/test_trilu.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
from pytorch_layer_test_class import PytorchLayerTest
class TestTriuTril(PytorchLayerTest):
def _prepare_input(self, shape, dtype):
return (self.random.randn(*shape, dtype=dtype),)
def create_model(self,... | 92 | 2,969 |
openvino | tests/layer_tests/onnx_tests/test_transpose.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import itertools
import numpy as np
import pytest
from common.onnx_layer_test_class import OnnxRuntimeLayerTest, onnx_make_model
class TestTranspose(OnnxRuntimeLayerTest):
def create_net(self, shape, perm, ir_version):
"""... | 183 | 5,786 |
readthedocs.org | readthedocs/rtd_tests/tests/test_oauth_sync.py | .py | import django_dynamic_fixture as fixture
import requests_mock
from allauth.socialaccount.models import SocialAccount, SocialToken
from allauth.socialaccount.providers.github.provider import GitHubProvider
from django.contrib.auth.models import User
from django.test import TestCase
from readthedocs.oauth.constants impo... | 316 | 12,003 |
hydra | examples/plugins/example_launcher_plugin/hydra_plugins/example_launcher_plugin/example_launcher.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from dataclasses import dataclass
import logging
from pathlib import Path
from typing import Optional, Sequence
from hydra.types import HydraContext
from hydra.core.config_store import ConfigStore
from hydra.core.singleton import Singleton
from hy... | 128 | 4,952 |
httpie | httpie/manager/tasks/check_updates.py | .py | import argparse
from httpie.context import Environment
from httpie.status import ExitStatus
from httpie.internal.update_warnings import fetch_updates, get_update_status
def cli_check_updates(env: Environment, args: argparse.Namespace) -> ExitStatus:
fetch_updates(env, lazy=False)
env.stdout.write(get_update_s... | 11 | 362 |
coremltools | coremltools/converters/mil/frontend/tensorflow/tf_graph_pass/__init__.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
from .cond_to_where import cond_to_where
from .constant_propagation import constant_propagation
# gr... | 20 | 847 |
coremltools | coremltools/models/ml_program/experimental/async_wrapper.py | .py | # Copyright (c) 2025, 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 atexit
import os
import shutil
import tempfile
from abc import ABC, abstractmethod
from pathlib i... | 453 | 15,124 |
hydra | tests/standalone_apps/initialization_test_app/setup.py | .py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from setuptools import find_packages, setup
setup(
name="initialization-test-app",
version="0.1",
packages=find_packages(include=["initialization_test_app"]),
entry_points={
"console_scripts": [
... | 19 | 476 |
saleor | saleor/graphql/product/tests/benchmark/test_product.py | .py | import json
import graphene
import pytest
from graphene import Node
from .....attribute.tests.model_helpers import (
get_product_attribute_values,
get_product_attributes,
)
from .....attribute.utils import associate_attribute_values_to_instance
from .....channel.models import Channel
from .....core.taxes impo... | 927 | 25,881 |
sphinx | tests/roots/test-linkcheck-localserver-warn-redirects/conf.py | .py | exclude_patterns = ['_build']
linkcheck_timeout = 0.25
| 3 | 55 |
hydra | examples/tutorials/structured_configs/3_config_groups/my_app.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from dataclasses import dataclass
from typing import Any
from omegaconf import OmegaConf
import hydra
from hydra.core.config_store import ConfigStore
@dataclass
class MySQLConfig:
driver: str = "mysql"
host: str = "localhost"
port: i... | 45 | 881 |
metrics | src/torchmetrics/functional/regression/symmetric_mape.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... | 98 | 3,298 |
pyomo | pyomo/repn/tests/gams/__init__.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 12 | 576 |
python-prompt-toolkit | src/prompt_toolkit/formatted_text/ansi.py | .py | from __future__ import annotations
from collections.abc import Generator
from string import Formatter
from prompt_toolkit.output.vt100 import BG_ANSI_COLORS, FG_ANSI_COLORS
from prompt_toolkit.output.vt100 import _256_colors as _256_colors_table
from .base import StyleAndTextTuples
__all__ = [
"ANSI",
"ansi... | 303 | 9,833 |
mlflow | tests/tracking/test_tracking.py | .py | import filecmp
import io
import json
import os
import pathlib
import posixpath
import random
import re
from datetime import datetime, timezone
from typing import NamedTuple
from unittest import mock
import pytest
import yaml
import mlflow
from mlflow import MlflowClient, tracking
from mlflow.entities import Lifecycle... | 1,376 | 54,372 |
textual | tests/snapshot_tests/snapshot_apps/datatable_hot_reloading.py | .py | from pathlib import Path
from textual.app import App, ComposeResult
from textual.widgets import DataTable
CSS_PATH = (Path(__file__) / "../datatable_hot_reloading.tcss").resolve()
# Write some CSS to the file before the app loads.
# Then, the test will clear all the CSS to see if the
# hot reloading applies the chan... | 59 | 1,260 |
saleor | saleor/csv/tests/export/test_export.py | .py | import datetime
import json
import shutil
from tempfile import NamedTemporaryFile
from unittest.mock import ANY, MagicMock, patch
import graphene
import openpyxl
import petl as etl
import pytest
from django.core.files import File
from freezegun import freeze_time
from ....core import JobStatus
from ....discount.model... | 1,188 | 34,476 |
deap | examples/ga/xkcd.py | .py | # This file is part of DEAP.
#
# DEAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# DEAP is distributed ... | 115 | 4,336 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.