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 |
|---|---|---|---|---|---|
textual | tests/test_data_bind.py | .py | import pytest
from textual.app import App, ComposeResult
from textual.reactive import ReactiveError, reactive
from textual.widgets import Label
class FooLabel(Label):
foo = reactive("Foo")
def render(self) -> str:
return self.foo
class DataBindApp(App):
bar = reactive("Bar")
def compose(s... | 87 | 2,350 |
onnxruntime | orttraining/orttraining/python/training/ortmodule/_fallback.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
import os
from enum import IntFlag
from logging import Logger
import to... | 189 | 7,959 |
pyomo | pyomo/repn/util.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,029 | 37,812 |
jupytext | tests/unit/test_formats.py | .py | import pytest
from jupyter_server.utils import ensure_async
from nbformat.v4.nbbase import new_notebook
import jupytext
from jupytext.compare import compare
from jupytext.formats import (
JupytextFormatError,
divine_format,
get_format_implementation,
guess_format,
long_form_multiple_formats,
re... | 422 | 10,853 |
mlflow | mlflow/store/db_migrations/versions/3da73c924c2f_add_outputs_to_dataset_record.py | .py | """add outputs to dataset record
Create Date: 2025-01-16 12:00:00.000000
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mssql
# revision identifiers, used by Alembic.
revision = "3da73c924c2f"
down_revision = "71994744cf8e"
branch_labels = None
depends_on = None
def _get_json_t... | 41 | 1,147 |
saleor | saleor/menu/error_codes.py | .py | from enum import Enum
class MenuErrorCode(Enum):
CANNOT_ASSIGN_NODE = "cannot_assign_node"
GRAPHQL_ERROR = "graphql_error"
INVALID = "invalid"
INVALID_MENU_ITEM = "invalid_menu_item"
NO_MENU_ITEM_PROVIDED = "no_item_provided"
NOT_FOUND = "not_found"
REQUIRED = "required"
TOO_MANY_MENU_... | 14 | 367 |
saleor | saleor/graphql/attribute/types.py | .py | from datetime import date, datetime
from typing import cast
import graphene
from promise import Promise
from ...attribute import AttributeEntityType, AttributeInputType, models
from ...page import models as page_models
from ...permission.enums import (
PagePermissions,
PageTypePermissions,
ProductPermissi... | 1,705 | 60,690 |
openvino | tests/layer_tests/pytorch_tests/test_replication_pad.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
from pytorch_layer_test_class import PytorchLayerTest
class TestReplicationPad(PytorchLayerTest):
def _prepare_input(self, n):
return (self.random.randn(*(2, 5, 6, 7, 8)[:n+2]),)
def create_model(self, p... | 56 | 1,703 |
openvino | tests/layer_tests/tensorflow_tests/test_tf_AssignVariableOps.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
rng = np.random.default_rng()
class TestAssignVariableOps(CommonTFLayerTest):
def _prepare_input(self, inputs_info):... | 49 | 2,354 |
mkdocs-material | material/plugins/tags/structure/listing/manager/__init__.py | .py | # Copyright (c) 2016-2025 Martin Donath <martin.donath@squidfunk.com>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, c... | 522 | 18,572 |
coremltools | coremltools/test/optimize/torch/conversion/pruning/test_pruning_conversion.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 pytest
ct = pytest.importorskip("coremltools")
import coremltools.test.optimize.torch.convers... | 89 | 2,394 |
kombu | t/unit/transport/test_redis.py | .py | from __future__ import annotations
import base64
import copy
import socket
import types
from collections import defaultdict
from itertools import count
from queue import Empty
from queue import Queue as _Queue
from typing import TYPE_CHECKING
from unittest.mock import ANY, Mock, call, patch
import pytest
from kombu ... | 2,694 | 99,808 |
sqlmap | tests/test_dbms_enum.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
DBMS-specific enumeration overrides (plugins/dbms/<dbms>/enumeration.py),
driven through each full DBMS handler with the injection layer mocked, so the
dialect-specific table/column/u... | 727 | 27,235 |
beam | sdks/python/apache_beam/transforms/enrichment_handlers/cloudsql.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... | 664 | 25,771 |
textual | src/textual/css/_style_properties.py | .py | """
Style properties are descriptors which allow the ``Styles`` object to accept different types when
setting attributes. This gives the developer more freedom in how to express style information.
Descriptors also play nicely with Mypy, which is aware that attributes can have different types
when setting and getting.
... | 1,259 | 43,257 |
pyro | tests/contrib/conftest.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import pytest
def pytest_collection_modifyitems(items):
for item in items:
if item.nodeid.startswith("tests/contrib"):
if "stage" not in item.keywords:
item.add_marker(pytest.mark.stage("in... | 14 | 449 |
probability | tensorflow_probability/python/distributions/lambertw_f_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... | 212 | 8,396 |
mlflow | mlflow/entities/lifecycle_stage.py | .py | from mlflow.entities.view_type import ViewType
from mlflow.exceptions import MlflowException
class LifecycleStage:
ACTIVE = "active"
DELETED = "deleted"
_VALID_STAGES = {ACTIVE, DELETED}
@classmethod
def view_type_to_stages(cls, view_type=ViewType.ALL):
stages = []
if view_type in... | 36 | 1,202 |
conda | conda/cli/main_package.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""CLI implementation for `conda package`.
Provides some low-level tools for creating conda packages.
"""
import hashlib
import os
import re
import tarfile
import tempfile
from argparse import ArgumentParser, Namespace, _SubParsersAction
from ... | 304 | 8,743 |
openvino | src/frontends/tensorflow/tests/test_models/models_pbtxt/model_tf1_while.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import tensorflow.compat.v1 as tf
tf.reset_default_graph()
# Note: run this script in TensorFlow 1 environment to generate model_tf1_while.pbtxt
# The model with Switch, NextIteration and other TF1 While stuff cannot be generated in TF... | 20 | 673 |
mlflow | tests/llama_index/test_llama_index_pyfunc_wrapper.py | .py | import llama_index.core
import numpy as np
import pandas as pd
import pytest
from llama_index.core import QueryBundle
from llama_index.core.llms import ChatMessage
from packaging.version import Version
import mlflow
from mlflow.llama_index.pyfunc_wrapper import (
_CHAT_MESSAGE_HISTORY_PARAMETER_NAME,
CHAT_ENGI... | 324 | 10,712 |
tqdm | examples/tqdm_requests.py | .py | """An example of wrapping manual tqdm updates for `requests.get`.
See also: tqdm_wget.py.
Usage:
tqdm_requests.py [options]
Options:
-h, --help
Print this help message and exit
-u URL, --url URL : string, optional
The url to fetch.
[default: https://cgi.cdcl.ml/matryoshka.zip]
-o FILE, --output FILE ... | 50 | 1,462 |
astropy | astropy/io/fits/hdu/base.py | .py | # Licensed under a 3-clause BSD style license - see PYFITS.rst
import datetime
import numbers
import os
import sys
import warnings
from contextlib import suppress
from inspect import Parameter, signature
import numpy as np
from astropy.io.fits import conf
from astropy.io.fits.file import _File
from astropy.io.fits.... | 1,616 | 58,787 |
python-prompt-toolkit | src/prompt_toolkit/key_binding/bindings/mouse.py | .py | from __future__ import annotations
import sys
from typing import TYPE_CHECKING
from prompt_toolkit.data_structures import Point
from prompt_toolkit.key_binding.key_processor import KeyPress, KeyPressEvent
from prompt_toolkit.keys import Keys
from prompt_toolkit.mouse_events import (
MouseButton,
MouseEvent,
... | 349 | 18,586 |
mlflow | tests/projects/test_projects_cli.py | .py | import hashlib
import json
import logging
import os
import shutil
from pathlib import Path
from unittest import mock
import pytest
from click.testing import CliRunner
from mlflow import MlflowClient, cli
from mlflow.utils import process
from mlflow.utils.environment import _PythonEnv
from mlflow.utils.virtualenv impo... | 245 | 8,369 |
conda | tests/plugins/test_package_extractors.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from contextlib import nullcontext
from typing import TYPE_CHECKING
import pytest
from conda import plugins
from conda.base.context import context
from conda.exceptions import PluginError
from conda.plugins.... | 143 | 4,701 |
coremltools | coremltools/converters/mil/mil/passes/defs/cleanup/fuse_reduce_mean.py | .py | # Copyright (c) 2023, 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 Builder as mb
from coremltools.converters.mil.mil.passes.... | 128 | 4,394 |
readthedocs.org | readthedocs/organizations/tests/test_forms.py | .py | import django_dynamic_fixture as fixture
from allauth.account.models import EmailAddress
from django_dynamic_fixture import get
from django.contrib.auth.models import User
from django.test import TestCase, override_settings
from django.urls import reverse
from readthedocs.invitations.models import Invitation
from read... | 256 | 9,787 |
saleor | saleor/core/editorjs/models.py | .py | from typing import Annotated, Literal, Union
from django.conf import settings
from django.core.exceptions import ValidationError
from pydantic import (
AfterValidator,
BeforeValidator,
ConfigDict,
Field,
)
from pydantic import (
BaseModel as UnsafeBaseModel,
)
from .cleaners import (
_clean_me... | 514 | 12,252 |
saleor | saleor/graphql/app/tests/benchmarks/test_apps.py | .py | import graphene
import pytest
from .....app.models import App, AppToken
from .....webhook.models import Webhook
from ....tests.utils import get_graphql_content
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
def test_apps_for_federation_query_count(
staff_api_client,
permission_manage_apps,
... | 141 | 3,625 |
saleor | saleor/tests/e2e/checkout/test_checkout_complete_with_transaction_and_gift_card.py | .py | import pytest
from ..gift_cards.utils import create_gift_card
from ..orders.utils import order_query
from ..product.utils.preparing_product import prepare_product
from ..shop.utils import prepare_shop
from ..transactions.utils import create_transaction
from ..utils import assign_permissions
from .utils import (
ch... | 372 | 11,462 |
coremltools | coremltools/converters/mil/__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 .frontend.tensorflow.tf_op_registry import register_tf_op
from .frontend.torch import register_... | 44 | 879 |
returns | tests/test_result/test_result_functions/test_safe.py | .py | import pytest
from returns.result import Success, safe
@safe
def _function(number: int) -> float:
return number / number
@safe(exceptions=(ZeroDivisionError,))
def _function_two(number: int | str) -> float:
assert isinstance(number, int)
return number / number
@safe((ZeroDivisionError,)) # no name
d... | 47 | 1,245 |
wandb | wandb/sdk/data_types/_private.py | .py | import atexit
import tempfile
# Staging directory, so we can encode raw data into files, then hash them before
# we put them into the Run directory to be uploaded.
MEDIA_TMP = tempfile.TemporaryDirectory("wandb-media")
def _cleanup_media_tmp_dir() -> None:
atexit.register(MEDIA_TMP.cleanup)
| 11 | 299 |
pymc | tests/variational/test_approximations.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... | 174 | 6,554 |
openvino | tests/layer_tests/pytorch_tests/test_pooling.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import platform
import pytest
import torch
import openvino as ov
from pytorch_layer_test_class import PytorchLayerTest
import numpy as np
d2_params = [{'kernel_size': [3, 3], 'stride': 1, 'padding': 0},
{'kernel_size': [3... | 498 | 28,061 |
gunicorn | examples/log_app.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import logging
log = logging.getLogger(__name__)
log.addHandler(logging.StreamHandler())
def app_factory(global_options, **local_options):
return app
def app(environ, start_response):
start_response("20... | 21 | 478 |
coremltools | coremltools/test/xgboost_tests/test_decision_tree_classifier_numeric.py | .py | # Copyright (c) 2017, 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 unittest
import numpy as np
import pandas as pd
import pytest
from packaging.ve... | 138 | 5,025 |
hatch | src/hatch/template/files_feature_ci.py | .py | from hatch.template import File
from hatch.utils.fs import Path
class CommandLinePackage(File):
TEMPLATE = """\
name: test
on:
push:
branches: [main, master]
pull_request:
branches: [main, master]
concurrency:
group: test-${{ github.head_ref }}
cancel-in-progress: true
env:
PYTHONUNBUFFERED: ... | 57 | 1,416 |
pyomo | pyomo/dataportal/plugins/datacommands.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... | 59 | 1,984 |
loguru | tests/exceptions/source/modern/type_hints.py | .py | # fmt: off
import sys
from typing import TypeVar, Tuple
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", colorize=True, backtrace=False, diagnose=True)
T = TypeVar("T")
Name = str
def foo(a: int, b: Tuple[Name, float], c: "Name") -> T: 1 / 0
def main():
bar: Name = foo(1, 2, 3)
... | 24 | 352 |
astropy | astropy/samp/tests/web_profile_test_helpers.py | .py | import threading
import time
import xmlrpc.client as xmlrpc
from astropy.samp.client import SAMPClient
from astropy.samp.errors import SAMPClientError, SAMPHubError
from astropy.samp.hub import WebProfileDialog
from astropy.samp.hub_proxy import SAMPHubProxy
from astropy.samp.integrated_client import SAMPIntegratedCli... | 283 | 9,422 |
openvino | tests/layer_tests/pytorch_tests/test_inverse.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
import torch
from pytorch_layer_test_class import PytorchLayerTest
class aten_inverse(torch.nn.Module):
def __init__(self) -> None:
torch.nn.Module.__init__(self)
def forward(self, inp... | 112 | 3,320 |
wandb | wandb/integration/kfp/helpers.py | .py | import json
def add_wandb_visualization(run, mlpipeline_ui_metadata_path):
"""NOTE: To use this, you must modify your component to have an output called `mlpipeline_ui_metadata_path` AND call `wandb.init` yourself inside that component.
Example usage:
def my_component(..., mlpipeline_ui_metadata_path: O... | 29 | 1,016 |
lemur | lemur/plugins/views.py | .py | """
.. module: lemur.plugins.views
:platform: Unix
:synopsis: This module contains all of the accounts view code.
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from flask import Bluepr... | 125 | 3,340 |
mlflow | mlflow/keras/load.py | .py | """Functions for loading Keras models saved with MLflow."""
import os
import keras
import numpy as np
import pandas as pd
from mlflow.exceptions import INVALID_PARAMETER_VALUE, MlflowException
from mlflow.models import Model
from mlflow.models.model import MLMODEL_FILE_NAME
from mlflow.tracking.artifact_utils import... | 157 | 5,710 |
metrics | src/torchmetrics/audio/pesq.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... | 176 | 7,348 |
beam | sdks/python/apache_beam/ml/rag/chunking/base.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... | 92 | 3,509 |
loguru | tests/test_filesink_delay.py | .py | import datetime
import time
from loguru import logger
from .conftest import check_dir
def test_file_not_delayed(tmp_path):
file = tmp_path / "test.log"
logger.add(file, format="{message}", delay=False)
assert file.read_text() == ""
logger.debug("Not delayed")
assert file.read_text() == "Not dela... | 118 | 3,435 |
python-prompt-toolkit | src/prompt_toolkit/widgets/menus.py | .py | from __future__ import annotations
from collections.abc import Callable, Iterable, Sequence
from prompt_toolkit.application.current import get_app
from prompt_toolkit.filters import Condition
from prompt_toolkit.formatted_text.base import OneStyleAndTextTuple, StyleAndTextTuples
from prompt_toolkit.key_binding.key_bi... | 375 | 13,428 |
onnx | onnx/reference/ops/op_attribute_has_value.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 AttributeHasValue(OpRun):
def _run(
self,
value_float=None, # noqa: ARG002
value_floats=None, # noqa: ARG... | 34 | 1,084 |
astropy | astropy/cosmology/_src/tests/io/test_latex.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
from astropy.cosmology._src.io.builtin.latex import _FORMAT_TABLE, write_latex
from astropy.io.registry.base import IORegistryError
from astropy.table import QTable, Table
from .base import ReadWriteDirectTestBase, ReadWriteTestMixinBase
... | 87 | 3,639 |
pyro | pyro/ops/linalg.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import math
import warnings
from contextlib import contextmanager
import torch
@contextmanager
def ignore_torch_deprecation_warnings():
with warnings.catch_warnings():
# Ignore deprecation warning until funsor update... | 107 | 3,577 |
astropy | astropy/coordinates/representation/spherical.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Spherical representations and differentials."""
import operator
import numpy as np
from erfa import ufunc as erfa_ufunc
import astropy.units as u
from astropy.coordinates.angles import Angle, Latitude, Longitude
from astropy.coordinates.distances imp... | 1,493 | 59,776 |
saleor | saleor/checkout/tests/webhooks/static_payloads/test_calculate_taxes.py | .py | import json
from decimal import Decimal
from unittest.mock import Mock, patch
import graphene
import pytest
from prices import Money
from .....core.prices import quantize_price
from .....discount import DiscountType, RewardValueType
from .....discount.models import CheckoutDiscount, CheckoutLineDiscount, PromotionRul... | 877 | 32,664 |
mlflow | dev/clint/src/clint/rules/assign_before_append.py | .py | import ast
from clint.rules.base import Rule
class AssignBeforeAppend(Rule):
def _message(self) -> str:
return (
"Avoid unnecessary assignment before appending to a list. "
"Use a list comprehension instead."
)
@staticmethod
def check(node: ast.For, prev_stmt: ast... | 65 | 2,027 |
astropy | astropy/io/fits/scripts/fitscheck.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
``fitscheck`` is a command line script based on astropy.io.fits for verifying
and updating the CHECKSUM and DATASUM keywords of .fits files. ``fitscheck``
can also detect and often fix other FITS standards violations. ``fitscheck``
facilitates re-wri... | 273 | 8,285 |
conda | tests/notices/test_core.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
import pytest
from conda.base.constants import NOTICES_DECORATOR_DISPLAY_INTERVAL
from conda.base.context import reset_context
from conda.notices import core as notices
from conda.testing.notices.helpers import (
DummyArgs,
add_resp_to_... | 188 | 5,361 |
pyomo | pyomo/gdp/disjunct.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... | 819 | 29,908 |
saleor | saleor/graphql/discount/tests/benchmark/test_promotion_create.py | .py | import datetime
from decimal import Decimal
import graphene
import pytest
from django.utils import timezone
from ....tests.utils import get_graphql_content
from ...enums import PromotionTypeEnum, RewardTypeEnum, RewardValueTypeEnum
PROMOTION_CREATE_MUTATION = """
mutation promotionCreate($input: PromotionCreateI... | 207 | 6,637 |
readthedocs.org | readthedocs/organizations/tests/test_querysets.py | .py | from datetime import timedelta
from django.contrib.auth.models import User
from django.test import TestCase, override_settings
from django.utils import timezone
from django_dynamic_fixture import get
from djstripe import models as djstripe
from djstripe.enums import InvoiceStatus, SubscriptionStatus
from readthedocs.... | 222 | 7,471 |
mlflow | tests/dev/test_check_init_py.py | .py | import subprocess
import sys
from pathlib import Path
import pytest
def get_check_init_py_script() -> Path:
return Path(__file__).resolve().parents[2] / "dev" / "check_init_py.py"
@pytest.fixture
def temp_git_repo(tmp_path: Path) -> Path:
subprocess.check_call(["git", "init"], cwd=tmp_path)
subprocess.... | 227 | 7,376 |
openvino | src/bindings/python/tests/test_graph/test_manager.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import numpy as np
import pytest
import openvino.opset10 as ops
from openvino import Core, Model
from openvino.passes import Manager, Serialize, ConstantFolding, Version
from tests.test_graph.util imp... | 191 | 6,548 |
sphinx | sphinx/ext/autodoc/__init__.py | .py | """Extension to create automatic documentation from code docstrings.
Automatically insert docstrings for functions, classes or whole modules into
the doctree, thus avoiding duplication between docstrings and documentation
for those who like elaborate docstrings.
"""
from __future__ import annotations
from typing imp... | 254 | 7,667 |
onnxruntime | tools/python/wgsl_template/errors.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Exception types for the WGSL template engine."""
from __future__ import annotations
class WgslTemplateError(Exception):
"""Base class for all WGSL template errors."""
def __init__(
self,
message:... | 39 | 989 |
mlflow | mlflow/paddle/_paddle_autolog.py | .py | import paddle
import mlflow
from mlflow.tracking.fluent import _initialize_logged_model
from mlflow.utils.autologging_utils import (
BatchMetricsLogger,
ExceptionSafeAbstractClass,
MlflowAutologgingQueueingClient,
get_autologging_config,
)
class __MlflowPaddleCallback(paddle.callbacks.Callback, metac... | 142 | 5,123 |
mlflow | mlflow/tracing/utils/processor.py | .py | import logging
from mlflow.exceptions import MlflowException
_logger = logging.getLogger(__name__)
def apply_span_processors(span):
"""Apply configured span processors sequentially to the span."""
from mlflow.tracing.config import get_config
config = get_config()
if not config.span_processors:
... | 55 | 1,809 |
ipython | IPython/core/inputtransformer2.py | .py | """Input transformer machinery to support IPython special syntax.
This includes the machinery to recognise and transform ``%magic`` commands,
``!system`` commands, ``help?`` querying, prompt stripping, and so forth.
Added: IPython 7.0. Replaces inputsplitter and inputtransformer which were
deprecated in 7.0 and remov... | 945 | 33,166 |
metrics | tests/unittests/image/test_ssim.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... | 391 | 14,536 |
returns | returns/pointfree/unify.py | .py | from collections.abc import Callable
from typing import TypeVar
from returns.interfaces.failable import DiverseFailableN
from returns.primitives.hkt import Kinded, KindN, kinded
_FirstType = TypeVar('_FirstType')
_NewFirstType = TypeVar('_NewFirstType')
_SecondType = TypeVar('_SecondType')
_NewSecondType = TypeVar('_... | 80 | 2,225 |
cvxpy | cvxpy/atoms/affine/binary_operators.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... | 663 | 22,630 |
wagtail | wagtail/contrib/simple_translation/wagtail_hooks.py | .py | import swapper
from django.conf import settings
from django.contrib.admin.utils import quote
from django.contrib.auth.models import Permission
from django.urls import include, path, reverse
from django.utils.translation import gettext as _
from wagtail import hooks
from wagtail.admin import widgets as wagtailadmin_wid... | 139 | 5,155 |
mlflow | mlflow/utils/autologging_utils/safety.py | .py | import abc
import functools
import inspect
import itertools
import uuid
from contextlib import asynccontextmanager, contextmanager
from typing import Any, Callable, NamedTuple
import mlflow
import mlflow.utils.autologging_utils
from mlflow.entities.run_status import RunStatus
from mlflow.environment_variables import _... | 1,158 | 53,597 |
probability | tensorflow_probability/python/experimental/distributions/multitask_gaussian_process_regression_model.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... | 940 | 43,196 |
textual | tests/test_wrap.py | .py | import pytest
from textual._wrap import chunks, compute_wrap_offsets
@pytest.mark.parametrize(
"input_text, expected_output",
[
("", []),
(" ", [(0, 4, " ")]),
("\t", [(0, 1, "\t")]),
("foo", [(0, 3, "foo")]),
(" foo ", [(0, 2, " "), (2, 7, "foo ")]),
... | 44 | 1,472 |
jupytext | tests/data/notebooks/outputs/ipynb_to_hydrogen/text_outputs_and_images.py | .py | # ---
# jupyter:
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# This notebook contains outputs of many different types: text, HTML, plots and errors.
# %% [markdown]
# # Text outputs
#
# Using `print`, `sys.stdout` and `sys.stderr`
# %%
import sys
prin... | 74 | 1,248 |
lemur | lemur/tests/test_schemas.py | .py | import json
import pytest
from marshmallow.exceptions import ValidationError
from lemur.tests.factories import RoleFactory
def test_get_object_attribute():
from lemur.schemas import get_object_attribute
with pytest.raises(ValidationError):
get_object_attribute({})
with pytest.raises(ValidationE... | 131 | 3,852 |
coremltools | deps/protobuf/kokoro/linux/make_test_output.py | .py | """Gathers output from test runs and create an XML file in JUnit format.
The output files from the individual tests have been written in a directory
structure like:
$DIR/joblog (output from "parallel --joblog joblog")
$DIR/logs/1/cpp/stdout
$DIR/logs/1/cpp/stderr
$DIR/logs/1/csharp/stdout
$DIR/logs/1/cshar... | 95 | 2,620 |
conda | tests/shell/test_fish.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from conda.activate import FishActivator
from conda.common.compat import on_win
if TYPE_CHECKING:
from . import Shell
pytestmark = [
pytest.mark.integ... | 74 | 2,241 |
jupytext | tests/data/notebooks/outputs/ipynb_to_sphinx/convert_to_py_then_test_with_update83.py | .py | # ---
# jupyter:
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %%time
print('asdf')
"""
Thanks for jupytext!
"""
| 18 | 168 |
sphinx | sphinx/builders/gettext.py | .py | """The MessageCatalogBuilder class."""
from __future__ import annotations
import operator
import os
import os.path
import time
from collections import defaultdict
from os import getenv, walk
from pathlib import Path
from typing import TYPE_CHECKING
from uuid import uuid4
from docutils import nodes
from sphinx impor... | 365 | 12,219 |
saleor | saleor/graphql/plugins/enums.py | .py | from typing import Final
import graphene
from ...graphql.core.enums import to_enum
from ...plugins.base_plugin import ConfigurationTypeField
ConfigurationTypeFieldEnum: Final[graphene.Enum] = to_enum(ConfigurationTypeField)
class PluginConfigurationType(graphene.Enum):
PER_CHANNEL = "per_channel"
GLOBAL = ... | 14 | 329 |
deap | doc/code/benchmarks/schwefel.py | .py | from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
try:
import numpy as np
except:
exit()
from deap import benchmarks
def schwefel_arg0(sol):
return benchmarks.schwefel(sol)[0]
fig = plt.figure()
# ax = Axes3D(fig, azim = -29, elev = 50)
ax = Axes3D(fig)
X ... | 28 | 636 |
wandb | wandb/integration/diffusers/resolvers/utils.py | .py | from __future__ import annotations
import inspect
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any
import wandb
from wandb.util import get_module
if TYPE_CHECKING:
np_array = get_module("numpy.array")
torch_float_tensor = get_module("torch.FloatTensor")
def chunkify(input_list, ch... | 105 | 3,842 |
beam | sdks/python/apache_beam/coders/coders_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... | 288 | 10,227 |
pyomo | pyomo/core/tests/unit/test_concrete.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... | 69 | 2,534 |
metrics | src/torchmetrics/functional/pairwise/linear.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... | 85 | 3,176 |
saleor | saleor/graphql/conftest.py | .py | import pytest
from django.contrib.sites.models import Site
from .storefront_traffic import set_allow_storefront_traffic_cache
@pytest.fixture(autouse=True)
def _warm_storefront_traffic_cache():
"""Keep the storefront-traffic guard from adding DB queries per request.
``is_storefront_traffic_blocked`` resolve... | 23 | 919 |
saleor | saleor/core/search.py | .py | import re
from typing import TYPE_CHECKING
from django.contrib.postgres.search import SearchQuery, SearchRank
from django.db.models import F, Value
from .utils.text import strip_accents
if TYPE_CHECKING:
from django.db.models import QuerySet
def _sanitize_word(word: str) -> str:
"""Remove PostgreSQL tsquer... | 180 | 5,614 |
pyro | pyro/distributions/empirical.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import torch
from torch.distributions import constraints
from pyro.distributions.torch import Categorical
from pyro.distributions.torch_distribution import TorchDistribution
from pyro.distributions.util import copy_docs_from
@co... | 177 | 6,765 |
onnx | onnx/backend/test/case/node/einsum.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
def einsum_reference_implementation(
Eqn: str, Operands: tuple[np.ndarra... | 93 | 2,693 |
coveragepy | tests/test_testing.py | .py | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/coveragepy/coveragepy/blob/main/NOTICE.txt
"""Tests that our test infrastructure is really working!"""
from __future__ import annotations
import datetime
import os
import re
import sys
import warnings
... | 494 | 17,907 |
scikit-bio | skbio/stats/ordination/_mmvec.py | .py | # ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# --------------------------------------------... | 1,731 | 61,682 |
mlflow | mlflow/genai/judges/prompts/completeness.py | .py | # NB: User-facing name for the completeness assessment.
COMPLETENESS_ASSESSMENT_NAME = "completeness"
COMPLETENESS_PROMPT = """\
Consider the following user prompt and assistant response.
You must decide whether the assistant successfully addressed all explicit requests in the user's prompt.
Output only "yes" or "no" ... | 21 | 1,295 |
beam | sdks/python/apache_beam/testing/benchmarks/nexmark/nexmark_util.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... | 272 | 9,260 |
wandb | wandb/filesync/step_upload.py | .py | """Batching file prepare requests to our API."""
from __future__ import annotations
import concurrent.futures
import logging
import queue
import sys
import threading
from collections.abc import Callable, MutableMapping, MutableSequence, MutableSet
from typing import TYPE_CHECKING, NamedTuple
from wandb.errors.term i... | 282 | 10,221 |
openvino | tests/layer_tests/pytorch_tests/test_cond.py | .py | # Copyright (C) 2018-2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
import numpy as np
from pytorch_layer_test_class import PytorchLayerTest
class TestCondFX(PytorchLayerTest):
"""Test torch.cond operation for FX export mode."""
def _prepare_input(self):
return (self.rand... | 95 | 3,489 |
pyomo | pyomo/core/expr/logical_expr.py | .py | # -*- coding: utf-8 -*-
# ____________________________________________________________________________________
#
# 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 En... | 639 | 16,648 |
tablib | src/tablib/formats/_xlsx.py | .py | """ Tablib - XLSX Support.
"""
__lazy_modules__ = {
"io",
"openpyxl",
"openpyxl.reader",
"openpyxl.reader.excel",
"openpyxl.styles",
"openpyxl.utils",
"openpyxl.workbook",
}
import re
from io import BytesIO
from openpyxl.reader.excel import ExcelReader, load_workbook
from openpyxl.styles ... | 219 | 7,228 |
sphinx | sphinx/search/tr.py | .py | """Turkish search language."""
from __future__ import annotations
import snowballstemmer
from sphinx.search import SearchLanguage
class SearchTurkish(SearchLanguage):
lang = 'tr'
language_name = 'Turkish'
js_stemmer_rawcode = 'turkish-stemmer.js'
stopwords = frozenset()
def __init__(self, opti... | 22 | 532 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.