repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
pyomo | pyomo/contrib/piecewise/tests/test_disaggregated_logarithmic.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... | 279 | 11,403 |
textual | tests/test_logger.py | .py | import inspect
from typing import Any
from textual import work
from textual._log import LogGroup, LogVerbosity
from textual.app import App
async def test_log_from_worker() -> None:
"""Check that log calls from threaded workers call app._log"""
log_messages: list[tuple] = []
class LogApp(App):
... | 43 | 1,066 |
onnx | docs/docsgen/source/onnx_sphinx.py | .py | # Copyright (c) ONNX Project Contributors
#
# SPDX-License-Identifier: Apache-2.0
"""Automates the generation of ONNX operators."""
from __future__ import annotations
import difflib
import importlib
import inspect
import keyword
import os
import pathlib
import re
import shutil
import sys
import textwrap
from typing i... | 995 | 32,773 |
textual | docs/examples/styles/width.py | .py | from textual.app import App
from textual.widget import Widget
class WidthApp(App):
CSS_PATH = "width.tcss"
def compose(self):
yield Widget()
if __name__ == "__main__":
app = WidthApp()
app.run()
| 15 | 224 |
astropy | astropy/coordinates/builtin_frames/gcrs.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from astropy import units as u
from astropy.coordinates.attributes import (
CartesianRepresentationAttribute,
TimeAttribute,
)
from astropy.coordinates.baseframe import base_doc
from astropy.utils.decorators import format_doc
from .baseradec impo... | 125 | 5,289 |
metrics | src/torchmetrics/functional/classification/f_beta.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... | 842 | 37,936 |
django-cms | menus/exceptions.py | .py | class NamespaceAlreadyRegistered(Exception):
pass
class NoParentFound(Exception):
pass
| 7 | 97 |
openvino | tests/layer_tests/pytorch_tests/test_log_softmax.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
import torch
import torch.nn.functional as F
from pytorch_layer_test_class import PytorchLayerTest
class aten_log_softmax(torch.nn.Module):
def __init__(self, dim, dtype) -> None:
super().__init__()
se... | 70 | 2,264 |
astropy | astropy/cosmology/_src/tests/io/test_row.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
from astropy.cosmology._src.core import _COSMOLOGY_CLASSES, Cosmology
from astropy.cosmology._src.io.builtin.row import from_row, to_row
from astropy.table import Row
from .base import ToFromDirectTestBase, ToFromTestMixinBase
###########... | 146 | 5,437 |
lemur | lemur/plugins/lemur_cfssl/plugin.py | .py | """
.. module: lemur.plugins.lemur_cfssl.plugin
:platform: Unix
:synopsis: This module is responsible for communicating with the CFSSL private CA.
:copyright: (c) 2018 by Thomson Reuters
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Charles Hendrie <chad.hendrie@tr.com>
"""
import ... | 134 | 4,557 |
saleor | saleor/app/tests/test_models.py | .py | import pytest
from django.db import IntegrityError
from django.db.transaction import atomic
from ...app.models import App
from ...webhook.event_types import WebhookEventSyncType
from ..models import AppExtension, AppInstallation
def test_qs_for_event_type(payment_app):
qs = App.objects.for_event_type(WebhookEven... | 135 | 4,196 |
biopython | Bio/Data/PDBData.py | .py | # Copyright 2022 Joao Rodrigues. 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.
"""Alphabets used by the ww... | 389 | 22,894 |
pyro | examples/rsa/search_inference.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
"""
Inference algorithms and utilities used in the RSA example models.
Adapted from: http://dippl.org/chapters/03-enumeration.html
"""
import collections
import functools
import queue
import torch
import pyro.distributions as d... | 224 | 7,562 |
wandb | tests/unit_tests/test_registries/test_addonly_list.py | .py | from __future__ import annotations
from collections import deque
from collections.abc import Iterable
from itertools import tee, zip_longest
from typing import TypeVar
from hypothesis import given
from hypothesis.strategies import (
SearchStrategy,
integers,
iterables,
lists,
slices,
text,
)
f... | 292 | 9,231 |
pymc | tests/helpers.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... | 225 | 7,763 |
mlflow | mlflow/cli/skills.py | .py | """CLI commands for inspecting MLflow Assistant skills."""
import click
from mlflow.assistant.skill_installer import BundledSkill, list_bundled_skills
def _echo_skill_details(skill: BundledSkill):
skill_name_styled = click.style(skill.name, fg="cyan", bold=True)
skill_path_styled = click.style(f" ({skill.pa... | 47 | 1,475 |
eve | eve/io/mongo/validation.py | .py | # -*- coding: utf-8 -*-
"""
eve.io.mongo.validation
~~~~~~~~~~~~~~~~~~~~~~~
This module implements the mongo Validator class, used to validate that
objects incoming via POST/PATCH requests conform to the API domain.
An extension of Cerberus Validator.
:copyright: (c) 2017 by Nicola Iarocci.
... | 301 | 10,949 |
pyomo | pyomo/contrib/mpc/examples/cstr/run_mpc.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... | 153 | 5,238 |
saleor | saleor/core/tests/test_rlimit.py | .py | import resource
from unittest.mock import patch
import pytest
from django.core.exceptions import ImproperlyConfigured
from ..rlimit import RLIMIT_TYPE, validate_and_set_rlimit
@patch("saleor.core.rlimit.resource.setrlimit")
def test_limit_passed_as_string(mock_setrlimit):
# given
soft_limit = "1000"
har... | 160 | 3,790 |
mlflow | mlflow/genai/judges/utils/telemetry_utils.py | .py | from __future__ import annotations
import logging
_logger = logging.getLogger(__name__)
def _record_judge_model_usage_success_databricks_telemetry(
*,
request_id: str | None,
model_provider: str,
endpoint_name: str,
num_prompt_tokens: int | None,
num_completion_tokens: int | None,
) -> None:... | 70 | 2,158 |
pyfilesystem2 | tests/mark.py | .py | def slow(cls):
return cls
| 3 | 30 |
ipython | tests/test_display_functions.py | .py | """Tests for IPython.core.display_functions."""
import pytest
from unittest import mock
from IPython.core.display_functions import (
DisplayHandle,
_merge,
_new_id,
display,
update_display,
)
# ---------------------------------------------------------------------------
# _merge
# ---------------... | 222 | 5,912 |
biopython | Scripts/xbbtools/xbb_help.py | .py | #!/usr/bin/env python
# Copyright 2000 by Thomas Sicheritz-Ponten.
# Copyright 2016 by Markus Piotrowski.
# All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
# Created: Tue Sep 4 ... | 105 | 3,209 |
kombu | kombu/abstract.py | .py | """Object utilities."""
from __future__ import annotations
from copy import copy
from typing import TYPE_CHECKING, Any, Callable, TypeVar
from .connection import maybe_channel
from .exceptions import NotBoundError
from .utils.functional import ChannelPromise
if TYPE_CHECKING:
from kombu.connection import Connec... | 144 | 4,426 |
returns | returns/trampolines.py | .py | from collections.abc import Callable
from functools import wraps
from typing import Generic, TypeVar, final
from typing_extensions import ParamSpec
_ReturnType = TypeVar('_ReturnType')
_FuncParams = ParamSpec('_FuncParams')
@final
class Trampoline(Generic[_ReturnType]):
"""
Represents a wrapped function cal... | 96 | 2,914 |
clearml | clearml/utilities/plotlympl/mplexporter/renderers/vega_renderer.py | .py | import json
import random
import warnings
from typing import Dict, Union, List, Tuple, Optional, Any
from .base import Renderer
from ..exporter import Exporter
class VegaRenderer(Renderer):
def open_figure(self, fig: Any, props: Dict[str, Union[int, float]]) -> None:
self.props = props
self.figwi... | 174 | 5,480 |
wagtail | wagtail/tests/streamfield_migrations/test_nested_structures.py | .py | from django.test import TestCase
from wagtail.blocks.migrations.operations import (
RemoveStreamChildrenOperation,
RemoveStructChildrenOperation,
RenameStreamChildrenOperation,
RenameStructChildrenOperation,
)
from wagtail.blocks.migrations.utils import apply_changes_to_raw_data
from wagtail.test.strea... | 784 | 32,238 |
wagtail | wagtail/admin/tests/api/test_documents.py | .py | import json
from django.urls import reverse
from wagtail.api.v2.tests.test_documents import (
TestDocumentDetail,
TestDocumentListing,
TestDocumentListingSearch,
)
from wagtail.documents.models import Document
from .utils import AdminAPITestCase
class TestAdminDocumentListing(AdminAPITestCase, TestDocu... | 152 | 5,051 |
conda | conda/gateways/connection/download.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Download logic for conda indices and packages."""
from __future__ import annotations
import hashlib
import os
import tempfile
import warnings
from contextlib import contextmanager
from logging import DEBUG, getLogger
from os.path import bas... | 470 | 16,681 |
mlflow | mlflow/genai/judges/optimizers/dspy.py | .py | """DSPy-based alignment optimizer implementation."""
import logging
from abc import abstractmethod
from typing import Any, Callable, ClassVar, Collection
from mlflow.entities.assessment import Feedback
from mlflow.entities.trace import Trace
from mlflow.exceptions import MlflowException
from mlflow.genai.judges impor... | 262 | 10,115 |
mlflow | mlflow/server/jobs/_huey_consumer.py | .py | """
This module is used for launching Huey consumer
the command is like:
```
export _MLFLOW_HUEY_STORAGE_PATH={huey_store_dir}
export _MLFLOW_HUEY_INSTANCE_KEY={huey_instance_key}
huey_consumer.py mlflow.server.jobs.huey_consumer.huey_instance -w {max_workers}
```
It launches the Huey consumer that polls tasks from ... | 39 | 1,142 |
pyro | pyro/infer/__init__.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
from pyro.infer.abstract_infer import EmpiricalMarginal, TracePosterior, TracePredictive
from pyro.infer.csis import CSIS
from pyro.infer.discrete import infer_discrete
from pyro.infer.elbo import ELBO
from pyro.infer.energy_distan... | 68 | 2,195 |
scikit-bio | skbio/alignment/_repr.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.
# --------------------------------------------... | 67 | 2,586 |
sphinx | tests/test_builders/xpath_util.py | .py | from __future__ import annotations
import re
import textwrap
from typing import TYPE_CHECKING
from xml.etree.ElementTree import tostring
if TYPE_CHECKING:
import os
from collections.abc import Callable, Iterable, Sequence
from xml.etree.ElementTree import Element, ElementTree
def _get_text(node: Element... | 86 | 2,644 |
toolz | toolz/_signatures.py | .py | """Internal module for better introspection of builtins.
The main functions are ``is_builtin_valid_args``, ``is_builtin_partial_args``,
and ``has_unknown_args``. Other functions in this module support these three.
Notably, we create a ``signatures`` registry to enable introspection of
builtin functions in any Python... | 785 | 20,555 |
voila | tests/server/execute_cpp_test.py | .py | import os
import pytest
TEST_XEUS_CPP = os.environ.get("VOILA_TEST_XEUS_CPP", "") == "1"
@pytest.fixture
def cpp_file_url(base_url):
return base_url + "voila/render/print.xcpp"
@pytest.fixture
def jupyter_server_args_extra():
return ['--VoilaConfiguration.extension_language_mapping={".xcpp": "C++23"}']
... | 30 | 800 |
omegaconf | omegaconf/nodes.py | .py | import copy
import math
import sys
from abc import abstractmethod
from enum import Enum
from pathlib import Path
from typing import Any, Dict, Optional, Type, Union
from omegaconf._utils import (
NoneType,
ValueKind,
_is_interpolation,
get_type_of,
get_value_kind,
is_literal_annotation,
is_... | 637 | 20,578 |
mlflow | tests/autologging/async_helper.py | .py | import asyncio
import inspect
from concurrent.futures import ThreadPoolExecutor
from mlflow.utils.autologging_utils.safety import update_wrapper_extended
def asyncify(is_async):
"""
Decorator that converts a function to an async function if `is_async` is True. This is useful
for testing purposes, where w... | 45 | 1,696 |
beam | learning/katas/python/Common Transforms/Aggregation/Smallest/tests/test_task.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... | 35 | 1,192 |
textual | tests/test_segment_tools.py | .py | from rich.segment import Segment
from rich.style import Style
from textual._segment_tools import align_lines, line_crop, line_pad, line_trim
from textual.geometry import Size
def test_line_crop():
bold = Style(bold=True)
italic = Style(italic=True)
segments = [
Segment("Hello", bold),
Seg... | 196 | 6,131 |
pyro | pyro/infer/util.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import math
import numbers
from collections import Counter, defaultdict
from contextlib import contextmanager
from dataclasses import fields
import torch
from opt_einsum import shared_intermediates
from opt_einsum.sharing import c... | 381 | 13,697 |
saleor | saleor/graphql/app/schema.py | .py | import graphene
from ...core.exceptions import PermissionDenied
from ...permission.auth_filters import AuthorizationFilters
from ...permission.enums import AppPermission
from ..core import ResolveInfo
from ..core.connection import create_connection_slice, filter_connection_queryset
from ..core.doc_category import DOC_... | 200 | 6,688 |
openvino | src/bindings/python/src/openvino/opset17/ops.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Factory functions for ops added to openvino opset17."""
from functools import partial
from typing import Optional
from openvino import Node
from openvino.utils.decorators import nameable_op, unary_op
from open... | 66 | 2,443 |
clearml | clearml/router/router.py | .py | from typing import Optional, Callable, Dict, Union, List, Any # noqa
from fastapi import Request, Response # noqa
from .proxy import HttpProxy
class HttpRouter:
"""
A router class to manage HTTP routing for an application.
Allows the creation, deployment, and management of local and external endpoints... | 247 | 11,838 |
django-cms | cms/models/aliaspluginmodel.py | .py | from django.db import models
from django.db.models import Q
from django.utils.encoding import force_str
from cms.models import CMSPlugin, Placeholder
class AliasPluginModel(CMSPlugin):
"""
AliasPlugin is deprecated,
and it will be removed;
please use the package djangocms-alias instead
"""
cm... | 65 | 1,828 |
probability | tensorflow_probability/python/bijectors/soft_clip.py | .py | # Copyright 2019 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 333 | 12,698 |
hydra | tests/test_internal_utils.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import Any, Callable, Optional
from omegaconf import DictConfig, OmegaConf
from pytest import mark, param, raises
from hydra._internal import utils
from hydra._internal.utils import get_args
from tests import data
@mark.parametrize(
... | 105 | 3,064 |
scikit-bio | skbio/util/tests/test_decorator.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.
# --------------------------------------------... | 270 | 7,213 |
mlflow | mlflow/cli/crypto.py | .py | import os
import click
from mlflow.exceptions import MlflowException
from mlflow.tracking import _get_store
from mlflow.utils.crypto import (
CRYPTO_KEK_PASSPHRASE_ENV_VAR,
CRYPTO_KEK_VERSION_ENV_VAR,
KEKManager,
rotate_secret_encryption,
)
@click.group("crypto", help="Commands for managing MLflow's... | 212 | 8,346 |
textual | docs/examples/widgets/radio_button.py | .py | from rich.text import Text
from textual.app import App, ComposeResult
from textual.widgets import RadioButton, RadioSet
class RadioChoicesApp(App[None]):
CSS_PATH = "radio_button.tcss"
def compose(self) -> ComposeResult:
with RadioSet():
yield RadioButton("Battlestar Galactica")
... | 32 | 995 |
readthedocs.org | readthedocs/search/signals.py | .py | """We define custom Django signals to trigger before executing searches."""
import structlog
from django.db.models.signals import post_save
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from django_elasticsearch_dsl.apps import DEDConfig
from readthedocs.projects.models import P... | 57 | 1,724 |
saleor | saleor/graphql/order/mutations/order_note_update.py | .py | import graphene
from django.db import transaction
from ....order import OrderEvents, error_codes, events, models
from ....order.search import update_order_search_vector
from ....permission.enums import OrderPermissions
from ...app.dataloaders import get_app_promise
from ...core import ResolveInfo
from ...core.context ... | 73 | 2,719 |
saleor | saleor/graphql/giftcard/schema.py | .py | import graphene
from graphql.error import GraphQLError
from ...core.search import prefix_search
from ...giftcard import models
from ...permission.enums import GiftcardPermissions
from ..core import ResolveInfo
from ..core.connection import create_connection_slice, filter_connection_queryset
from ..core.context import ... | 156 | 5,672 |
sphinx | tests/test_ext_autosummary/test_ext_autosummary_imports.py | .py | """Test autosummary for import cycles."""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from docutils import nodes
from sphinx import addnodes
from sphinx.ext.autosummary import autosummary_table
from sphinx.testing.util import assert_node
from tests.utils import extract_node
i... | 80 | 2,247 |
saleor | saleor/graphql/core/mutations.py | .py | import os.path
import secrets
from collections.abc import Collection, Iterable
from enum import Enum
from itertools import chain
from typing import Any, TypeVar, cast, overload
from uuid import UUID
import graphene
from django.core.exceptions import (
NON_FIELD_ERRORS,
ImproperlyConfigured,
ValidationError... | 1,252 | 43,704 |
saleor | saleor/menu/models.py | .py | from django.db import models
from mptt.managers import TreeManager
from mptt.models import MPTTModel
from ..core.models import ModelWithMetadata, SortableModel
from ..core.utils.translations import Translation
from ..page.models import Page
from ..permission.enums import MenuPermissions
from ..product.models import Ca... | 87 | 2,718 |
saleor | saleor/checkout/tests/test_order_from_checkout.py | .py | from decimal import Decimal
from unittest import mock
from unittest.mock import patch
import pytest
from django.core.exceptions import ValidationError
from django.test import override_settings
from prices import Money, TaxedMoney
from promise import Promise
from ...channel import MarkAsPaidStrategy
from ...checkout.m... | 1,073 | 35,548 |
onnxruntime | docs/python/examples/plot_backend.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""
.. _l-example-backend-api:
ONNX Runtime Backend for ONNX
=============================
*ONNX Runtime* extends the
`onnx backend API <https://github.com/onnx/onnx/blob/main/docs/ImplementingAnOnnxBackend.md>`_
to run pr... | 60 | 1,605 |
astropy | astropy/cosmology/_src/tests/flrw/test_w.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Testing :mod:`astropy.cosmology.FLRW` neutrinos."""
import numpy as np
import pytest
import astropy.units as u
from astropy.cosmology import FLRW, wCDM
from astropy.utils.compat.optional_deps import HAS_SCIPY
########################################... | 90 | 2,916 |
readthedocs.org | readthedocs/rtd_tests/tests/test_notifications.py | .py | """Notification tests."""
from unittest import mock
import django_dynamic_fixture as fixture
from django.conf import settings
from django.contrib.auth.models import User
from django.test import TestCase
from django.test.utils import override_settings
from readthedocs.builds.models import Build
from readthedocs.noti... | 104 | 3,427 |
astropy | astropy/modeling/spline.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Spline models and fitters."""
# pylint: disable=line-too-long, too-many-lines, too-many-arguments, invalid-name
import abc
import functools
import warnings
import numpy as np
from astropy.utils.exceptions import AstropyUserWarning
from .core import... | 910 | 27,532 |
pyomo | pyomo/repn/tests/ampl/small1_testCase.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... | 27 | 1,056 |
pymc | pymc/ode/__init__.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... | 38 | 1,783 |
textual | docs/examples/guide/compound/byte02.py | .py | from __future__ import annotations
from textual.app import App, ComposeResult
from textual.containers import Container
from textual.message import Message
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import Input, Label, Switch
class BitSwitch(Widget):
"""A Switch ... | 107 | 2,581 |
saleor | saleor/graphql/product/schema.py | .py | import graphene
from django.db.models import Exists, OuterRef
from promise import Promise
from ...core.search import prefix_search
from ...permission.enums import ProductPermissions
from ...permission.utils import has_one_of_permissions
from ...product import models
from ...product.models import ALL_PRODUCTS_PERMISSIO... | 702 | 26,378 |
pyomo | pyomo/repn/plugins/gams_writer.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,215 | 40,880 |
mlflow | mlflow/onnx/__init__.py | .py | """
The ``mlflow.onnx`` module provides APIs for logging and loading ONNX models in the MLflow Model
format. This module exports MLflow Models with the following flavors:
ONNX (native) format
This is the main flavor that can be loaded back as an ONNX model object.
:py:mod:`mlflow.pyfunc`
Produced for use by ge... | 613 | 25,827 |
textual | src/textual/geometry.py | .py | """
Functions and classes to manage terminal geometry (anything involving coordinates or dimensions).
"""
from __future__ import annotations
import os
from functools import lru_cache
from operator import attrgetter, itemgetter
from typing import (
TYPE_CHECKING,
Any,
Collection,
Iterable,
Literal... | 1,501 | 45,783 |
beam | learning/tour-of-beam/learning-content/common-transforms/motivating-challenge/python-challenge/task.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"); y... | 71 | 2,205 |
confluent-kafka-python | examples/json_consumer_encryption.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2024 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | 129 | 4,693 |
mlflow | mlflow/pyfunc/utils/data_validation.py | .py | import inspect
import warnings
from functools import lru_cache, wraps
from typing import Any, NamedTuple
import pydantic
from mlflow.exceptions import MlflowException
from mlflow.models.signature import (
_extract_type_hints,
_is_context_in_predict_function_signature,
)
from mlflow.types.type_hints import (
... | 226 | 8,709 |
probability | tensorflow_probability/python/experimental/mcmc/initialization.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... | 299 | 13,922 |
onnxruntime | onnxruntime/python/tools/transformers/models/bart/utils/export_summarization_enc_dec_past.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import ... | 271 | 10,288 |
django-cms | cms/test_utils/project/custom_templates/__init__.py | .py | from django.utils.translation import gettext_lazy as _
TEMPLATES = {
'wrong_col_two.html': _('Two columns'),
'wrong_col_three.html': _('Three columns'),
}
| 7 | 164 |
wandb | wandb/integration/sklearn/calculate/silhouette.py | .py | from warnings import simplefilter
import numpy as np
from sklearn.metrics import silhouette_samples, silhouette_score
from sklearn.preprocessing import LabelEncoder
import wandb
from wandb.integration.sklearn import utils
# ignore all future warnings
simplefilter(action="ignore", category=FutureWarning)
def silhou... | 119 | 3,321 |
astropy | docs/wcs/examples/programmatic.py | .py | # Set the WCS information manually by setting properties of the WCS
# object.
import numpy as np
from astropy import wcs
from astropy.io import fits
# Create a new WCS object. The number of axes must be set
# from the start
w = wcs.WCS(naxis=2)
# Set up an "Airy's zenithal" projection
# Vector properties may be se... | 59 | 1,862 |
onnxruntime | tools/python/cherry_pick_utils.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import re
import subprocess
import sys
def run_command(command_list, cwd=None, silent=False):
"""Run a command using a list of arguments for security (no shell=True)."""
try:
result = subprocess.run(command_... | 102 | 3,901 |
pyomo | pyomo/contrib/pynumero/examples/external_grey_box/react_example/maximize_cb_ratio_residuals.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... | 233 | 9,965 |
openvino | tools/ovc/unit_tests/moc_tf_fe/test_models/model_fp32.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.float32, [2, 2], 'in1')
y = tf.placeholder(tf.float32, [2, 2], 'in2')
tf.add(x, y, name="add")
tf.global_variab... | 16 | 425 |
saleor | saleor/graphql/order/tests/deprecated/test_order.py | .py | import warnings
from decimal import Decimal
from functools import partial
from unittest.mock import ANY, patch
import graphene
import pytest
from prices import Money, TaxedMoney, fixed_discount
from .....channel.utils import DEPRECATION_WARNING_MESSAGE
from .....core.prices import quantize_price
from .....discount im... | 756 | 23,753 |
pymc | tests/logprob/test_basic.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... | 501 | 16,024 |
pyro | tests/poutine/test_nesting.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import logging
import pyro
import pyro.distributions as dist
import pyro.poutine as poutine
import pyro.poutine.runtime
logger = logging.getLogger(__name__)
def test_nested_reset():
def nested_model():
pyro.sample("... | 32 | 1,068 |
rq | rq/cli/__main__.py | .py | import sys
from . import main
if __name__ == '__main__':
sys.exit(main())
| 7 | 80 |
rq | rq/worker/__init__.py | .py | from ..defaults import DEFAULT_RESULT_TTL
from .base import (
SHUTDOWN_SIGNAL,
DequeueStrategy,
WorkerStatus,
_signames,
logger,
signal_name,
)
from .base import BaseWorker as BaseWorker
from .worker_classes import (
HerokuWorker,
RandomWorker,
RoundRobinWorker,
SimpleWorker,
... | 36 | 640 |
pyomo | pyomo/gdp/tests/common_tests.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,978 | 74,909 |
loguru | tests/exceptions/source/others/catch_as_decorator_without_parentheses.py | .py | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", diagnose=False, backtrace=False, colorize=False)
@logger.catch
def c(a, b=0):
a / b
c(2)
| 15 | 186 |
kombu | t/unit/utils/test_div.py | .py | from __future__ import annotations
import pickle
from io import BytesIO, StringIO
from kombu.utils.div import emergency_dump_state
class MyStringIO(StringIO):
def close(self):
pass
class MyBytesIO(BytesIO):
def close(self):
pass
class test_emergency_dump_state:
def test_dump(self,... | 72 | 1,899 |
rq | tests/test_group.py | .py | from time import sleep
import pytest
from rq import Queue, SimpleWorker
from rq.exceptions import NoSuchGroupError
from rq.group import Group
from rq.job import Job
from rq.utils import as_text
from tests import RQTestCase
from tests.fixtures import say_hello
class TestGroup(RQTestCase):
job_1_data = Queue.prep... | 161 | 6,660 |
sqlmap | extra/esperanto/extraction.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
import binascii
from .atlas import _FREQ_ORDER
from .atlas import _hardWarnings
from .atlas import _HEX_Q_ENCODINGS
from .atlas import _HEXDIGITS
from .atlas import _HEXFN
from .... | 831 | 44,701 |
mkdocs | mkdocs/exceptions.py | .py | from __future__ import annotations
from click import ClickException, echo
class MkDocsException(ClickException):
"""
The base class which all MkDocs exceptions inherit from. This should
not be raised directly. One of the subclasses should be raised instead.
"""
class Abort(MkDocsException, SystemEx... | 42 | 1,018 |
bazel | scripts/docs/rewriter_test.py | .py | # Copyright 2022 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | 63 | 2,140 |
eve | tests/test_io/flask_pymongo.py | .py | import pytest
from pymongo import MongoClient
from pymongo.errors import OperationFailure
from eve.io.mongo.flask_pymongo import PyMongo
from tests import TestBase
from tests.test_settings import (
MONGO1_DBNAME,
MONGO1_PASSWORD,
MONGO1_USERNAME,
MONGO_HOST,
MONGO_PORT,
)
class TestPyMongo(TestBa... | 84 | 2,843 |
probability | tensorflow_probability/python/distributions/horseshoe.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... | 237 | 9,138 |
openvino | src/bindings/python/tests/test_package_versions.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import openvino.preprocess as ov_pre
import openvino as ov
import openvino.frontend as ov_front
import openvino._offline_transformations as ov_off_transf
import openvino._pyopenvino as ov_py
def test_get_version... | 30 | 728 |
hatch | tests/helpers/templates/sdist/standard_default_support_legacy.py | .py | from hatch.template import File
from hatch.utils.fs import Path
from hatchling.metadata.spec import DEFAULT_METADATA_VERSION
from ..new.feature_no_src_layout import get_files as get_template_files
def get_files(**kwargs):
relative_root = kwargs.get("relative_root", "")
files = [File(Path(relative_root, f.pa... | 40 | 906 |
conda | conda/plugins/prefix_data_loaders/pypi/pkg_format.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Common Python package format utilities."""
from __future__ import annotations
import platform
import re
import sys
import warnings
from base64 import urlsafe_b64decode
from collections import namedtuple
from configparser import ConfigParser... | 1,304 | 48,840 |
django-cms | cms/management/commands/startcmsproject.py | .py | #!/usr/bin/env python
import argparse
import difflib
import io
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import tarfile
import urllib.error
import urllib.request
import zipfile
from django.core.checks.security.base import SECRET_KEY_INSECURE_PREFIX
from django.core.managem... | 1,293 | 60,676 |
hatch | scripts/validate_history.py | .py | import re
import sys
from utils import ROOT
HEADER_PATTERN = (
r"^\[([a-z0-9.]+)\]\(https://github\.com/pypa/hatch/releases/tag/({package}-v\1)\)"
r" - [0-9]{{4}}-[0-9]{{2}}-[0-9]{{2}} ## \{{: #\2 \}}$"
)
def main():
for package in ("hatch", "hatchling"):
history_file = ROOT / "docs" / "history"... | 36 | 1,000 |
wandb | wandb/integration/ultralytics/mask_utils.py | .py | from __future__ import annotations
import cv2
import numpy as np
from tqdm.auto import tqdm
from ultralytics.engine.results import Results
from ultralytics.models.yolo.segment import SegmentationPredictor
from ultralytics.utils.ops import scale_image
import wandb
from wandb.integration.ultralytics.bbox_utils import (... | 203 | 7,068 |
mlflow | mlflow/store/db_migrations/versions/181f10493468_allow_nulls_for_metric_values.py | .py | """allow nulls for metric values
Create Date: 2019-07-10 22:40:18.787993
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "181f10493468"
down_revision = "90e64c465722"
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table("metrics... | 34 | 877 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.