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 |
|---|---|---|---|---|---|
saleor | saleor/checkout/tests/utils.py | .py | from decimal import Decimal
from typing import Optional
from django.utils import timezone
from ...core.exceptions import ProductNotPublished
from ...product import models as product_models
from ...warehouse.availability import check_stock_and_preorder_quantity
from ..fetch import CheckoutInfo
from ..models import Che... | 129 | 4,225 |
django-cms | cms/plugin_pool.py | .py | import fnmatch
from collections import defaultdict
from functools import lru_cache
from operator import attrgetter
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.template import TemplateDoesNotExist, TemplateSyntaxError
from django.template.defaultfilters import slugif... | 408 | 17,965 |
pyfilesystem2 | examples/upload.py | .py | """
Upload a file to a server (or other filesystem)
Usage:
python upload.py FILENAME <FS URL>
example:
python upload.py foo.txt ftp://example.org/uploads/
"""
import sys
import os
from fs import open_fs
_, file_path, fs_url = sys.argv
filename = os.path.basename(file_path)
with open_fs(fs_url) as fs:... | 31 | 524 |
sphinx | tests/roots/test-ext-autodoc/target/overload2.py | .py | from target.overload import Bar
class Baz(Bar):
pass
| 6 | 59 |
openvino | docs/optimization_guide/nncf/ptq/code/ptq_onnx.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#! [dataset]
import nncf
import torch
calibration_loader = torch.utils.data.DataLoader(...)
def transform_fn(data_item):
images, _ = data_item
return {input_name: images.numpy()} # input_name should be taken from the model,
... | 43 | 1,142 |
onnxruntime | onnxruntime/test/testdata/transform/scalar_const_not_share.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
import onnx
import onnxscript
from onnx import numpy_helper
from onnxscript import opset17 as op
@onnxscript.script()
def build_model(x: onnxscript.FLOAT):
y_scale = op.Constant(value_float=1.0)
y... | 20 | 563 |
beam | sdks/python/apache_beam/ml/inference/anthropic_inference.py | .py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | 297 | 10,808 |
beam | sdks/python/apache_beam/runners/portability/prism_runner.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... | 507 | 19,526 |
clearml | clearml/datasets/dataset.py | .py | import calendar
import itertools
import json
import logging
import mimetypes
import os
import re
import shutil
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy, copy
from multiprocessing.pool import ThreadPool
from tempfile import mkdtemp
from typing import Union, Optional, Sequence, List, Di... | 4,282 | 189,643 |
omegaconf | tests/test_nodes.py | .py | import copy
import functools
import re
import sys
from enum import Enum
from functools import partial
from pathlib import Path
from typing import Any, Callable, Dict, Literal, Tuple, Type, Union
from pytest import fixture, mark, param, raises
from omegaconf import (
AnyNode,
BooleanNode,
BytesNode,
Di... | 1,140 | 36,530 |
saleor | saleor/graphql/product/tests/test_variant_pricing.py | .py | from decimal import Decimal
from unittest.mock import patch
import graphene
import pytest
from prices import Money, TaxedMoney
from ....product.models import ProductVariant, ProductVariantChannelListing
from ....product.utils.availability import get_variant_availability
from ....tax import TaxCalculationStrategy
from... | 646 | 20,130 |
saleor | saleor/graphql/order/utils.py | .py | from collections import defaultdict
from collections.abc import Iterable
from decimal import Decimal
from typing import TYPE_CHECKING, Optional, Union
import graphene
from django.conf import settings
from django.core.exceptions import ValidationError
from promise import Promise
from ...core.exceptions import Insuffic... | 451 | 15,472 |
confluent-kafka-python | src/confluent_kafka/schema_registry/rules/encryption/hcvault/hcvault_driver.py | .py | # 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 required by applicable law or agreed to in writing, s... | 93 | 3,868 |
saleor | saleor/graphql/checkout/tests/test_utils.py | .py | from ..mutations.utils import apply_gift_reward_if_applicable_on_checkout_creation
def test_apply_gift_reward_if_applicable(
checkout_with_item, gift_promotion_rule, order_promotion_rule, promotion_rule
):
# given
checkout = checkout_with_item
lines_count = checkout.lines.count()
# when
apply... | 51 | 1,479 |
openvino | src/frontends/paddle/tests/test_models/gen_scripts/generate_full_like.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
# full_like paddle model generator
#
import numpy as np
from save_model import saveModel
import paddle
import sys
data_type = 'float32'
def full_like(name:str, x, value, dtype=None):
paddle.enable_static()
with paddle.static... | 53 | 1,669 |
beam | sdks/python/apache_beam/typehints/intrinsic_one_ops_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... | 39 | 1,340 |
saleor | saleor/graphql/checkout/tests/deprecated/test_checkout_lines_update.py | .py | from unittest import mock
import graphene
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.utils import calculate_checkout_quantity
from .....plugins.manager import get_plugins_manager
from ....tests.utils import get_g... | 163 | 5,584 |
sphinx | sphinx/builders/__init__.py | .py | """Builder superclass for all builders."""
from __future__ import annotations
import pickle
import re
import time
from contextlib import nullcontext
from pathlib import Path
from typing import TYPE_CHECKING, final
from docutils import nodes
from docutils.utils import DependencyList
from sphinx._cli.util.colour impo... | 891 | 32,607 |
pyro | tests/contrib/randomvariable/test_random_variable.py | .py | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import math
import torch
from pyro.distributions import Uniform
N_SAMPLES = 100
def test_add():
X = Uniform(0, 1).rv # (0, 1)
X = X + 1 # (1, 2)
X = 1 + X # (2, 3)
X += 1 # (3, 4)
x = X.dist.sample([N_SAMPL... | 84 | 1,893 |
astropy | astropy/units/tests/test_docgen.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# ruff: noqa: FLY002
import textwrap
from importlib.util import module_from_spec, spec_from_file_location
import pytest
from astropy.tests.helper import _skip_docstring_tests_with_optimized_python
def test_composite_unit_definition(tmp_path):
# R... | 140 | 4,116 |
tablib | src/tablib/_vendor/dbfpy/utils.py | .py | import datetime
import time
__version__ = "$Revision: 1.4 $"[11:-2]
__date__ = "$Date: 2007/02/11 08:57:17 $"[7:-2]
"""String utilities.
TODO:
- allow strings in getDateTime routine;
"""
"""History (most recent first):
11-feb-2007 [als] added INVALID_VALUE
10-feb-2007 [als] allow date strings padded with spac... | 170 | 4,834 |
astropy | astropy/modeling/tests/test_models.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst:
"""
Tests for model evaluation.
Compare the results of some models with other programs.
"""
import unittest.mock as mk
import numpy as np
# pylint: disable=invalid-name, no-member
import pytest
from numpy.testing import assert_allclose, assert_equal
... | 1,214 | 41,848 |
lemur | lemur/plugins/lemur_statsd/lemur_statsd/plugin.py | .py | import lemur_statsd as plug
from flask import current_app
from lemur.plugins.bases.metric import MetricPlugin
from datadog import DogStatsd
class StatsdMetricPlugin(MetricPlugin):
title = "Statsd"
slug = "statsd-metrics"
description = "Adds support for sending metrics to Statsd"
version = plug.VERSIO... | 50 | 1,693 |
pyomo | pyomo/contrib/pynumero/algorithms/solvers/pyomo_ext_cyipopt.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... | 392 | 16,815 |
wagtail | wagtail/contrib/simple_translation/forms.py | .py | from django import forms
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy, ngettext
from wagtail.models import AbstractPage, Locale
class CheckboxSelectMultipleWithDisabledOptions(forms.CheckboxSelectMultiple):
option_template_name = ... | 133 | 5,350 |
mlflow | mlflow/smolagents/chat.py | .py | import logging
_logger = logging.getLogger(__name__)
| 4 | 54 |
luigi | luigi/contrib/hdfs/hadoopcli_clients.py | .py | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... | 263 | 9,424 |
mlflow | tests/server/auth/test_custom_auth_bridge.py | .py | from unittest import mock
import pytest
from fastapi import FastAPI
from flask import Response as FlaskResponse
from starlette.responses import Response as StarletteResponse
from starlette.testclient import TestClient
from werkzeug.datastructures import Authorization
from mlflow.exceptions import MlflowException
from... | 205 | 7,436 |
voila | voila/configuration.py | .py | #############################################################################
# Copyright (c) 2018, QuantStack #
# Copyright (c) 2018, Voilà Contributors #
# #
# Distri... | 278 | 9,615 |
wagtail | wagtail/contrib/sitemaps/tests.py | .py | import datetime
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.shortcuts import get_current_site
from django.test import RequestFactory, TestCase, override_settings
from django.utils import timezone
from wagtail.models import PageViewRestriction, ... | 290 | 10,153 |
mlflow | tests/genai/judges/test_custom_prompt_judge.py | .py | import json
from unittest import mock
import pytest
from mlflow.entities.assessment import AssessmentError
from mlflow.entities.assessment_source import AssessmentSourceType
from mlflow.genai.judges.adapters.gateway_adapter import InvokeOutput
from mlflow.genai.judges.custom_prompt_judge import _remove_choice_bracket... | 184 | 5,913 |
saleor | saleor/graphql/product/tests/mutations/test_assign_variant_media.py | .py | from graphql_relay import to_global_id
from .....product.error_codes import ProductErrorCode
from .....product.models import ProductMedia
from ....tests.utils import (
assert_no_permission,
get_graphql_content,
get_graphql_content_from_response,
)
ASSIGN_VARIANT_QUERY = """
mutation assignVariantMedia... | 96 | 3,075 |
cvxpy | cvxpy/transforms/indicator.py | .py | """
Copyright 2017 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... | 149 | 4,161 |
textual | docs/examples/events/prevent.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Button, Input
class PreventApp(App):
"""Demonstrates `prevent` context manager."""
def compose(self) -> ComposeResult:
yield Input()
yield Button("Clear", id="clear")
def on_button_pressed(self) -> None:
"""Cl... | 26 | 636 |
probability | tensorflow_probability/python/bijectors/bijector_properties_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,043 | 43,528 |
wandb | tests/unit_tests/test_internal_api.py | .py | from __future__ import annotations
import base64
import hashlib
import os
import pathlib
import tempfile
from collections.abc import Callable, Mapping
from itertools import chain
from pathlib import Path
from typing import TypeVar
from unittest.mock import Mock, patch
import pytest
import requests
import wandb.errors... | 882 | 29,187 |
ipython | tools/tests/heartbeat/hb_gil.py | .py | """
Run this script in the qtconsole with one of:
%load hb_gil.py
or
%run hb_gil.py
Holding the GIL for too long could disrupt the heartbeat.
See Issue #1260: https://github.com/ipython/ipython/issues/1260
"""
import sys
import time
from cython import inline
def gilsleep(t):
"""gil-holding sleep wit... | 32 | 574 |
wagtail | wagtail/admin/panels/page_utils.py | .py | from django.utils.translation import gettext_lazy
from wagtail.utils.decorators import cached_classmethod
from .group import ObjectList, TabbedInterface
@cached_classmethod
def _get_page_edit_handler(cls):
"""
Get the panel to use in the Wagtail admin when editing this page type.
"""
if hasattr(cls,... | 32 | 1,067 |
django-cms | cms/tests/test_app_registration.py | .py | from importlib import import_module
from unittest.mock import Mock, patch
from django.apps import AppConfig, apps
from django.core.exceptions import ImproperlyConfigured
from django.test import override_settings
from cms import app_registration
from cms.apps import CMSConfig
from cms.test_utils.testcases import CMSTe... | 560 | 24,519 |
omegaconf | omegaconf/__init__.py | .py | from .base import Container, DictKeyType, Node, SCMode, UnionNode
from .dictconfig import DictConfig
from .errors import (
KeyValidationError,
MissingMandatoryValue,
ReadonlyConfigError,
UnsupportedValueType,
ValidationError,
)
from .listconfig import ListConfig
from .nodes import (
AnyNode,
... | 72 | 1,337 |
onnxruntime | onnxruntime/python/tools/microbench/fast_gelu.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
import argparse
from dataclasses import dataclass
import numpy as np
fr... | 72 | 2,045 |
mamba | micromamba/tests/test_menuinst.py | .py | import os
import shutil
import sys
from pathlib import Path
import pytest
from .helpers import create, random_string, remove
if sys.platform.startswith("win"):
import menuinst
import win32com.client
class TestMenuinst:
root_prefix = os.environ["MAMBA_ROOT_PREFIX"]
current_prefix = os.environ["CONDA... | 121 | 4,214 |
jupytext | tests/data/notebooks/outputs/ipynb_to_script_vim_folding_markers/jupyter_with_raw_cell_on_top.py | .py | # ---
# title: Quick test
# output:
# ioslides_presentation:
# widescreen: true
# smaller: true
# editor_options:
# chunk_output_type: console
# jupyter:
# jupytext:
# cell_markers: '{{{,}}}'
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
1+2+3
| 21 | 313 |
openvino | tests/layer_tests/jax_tests/jax_layer_test_class.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import itertools
import jax
import numpy as np
import os
from common.constants import test_device, test_precision
from copy import deepcopy
from openvino import Core
class JaxLayerTest:
@staticmethod
def _check_kind_exist(jaxp... | 179 | 6,896 |
metrics | src/conftest.py | .py | from pathlib import Path
from typing import Optional
from lightning_utilities.core.imports import package_available
if package_available("pytest") and package_available("doctest"):
import doctest
import pytest
MANUAL_SEED = doctest.register_optionflag("MANUAL_SEED")
@pytest.fixture(autouse=True)
... | 41 | 1,388 |
kafka | tests/kafkatest/services/monitor/jmx.py | .py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | 161 | 7,971 |
cvxpy | cvxpy/atoms/affine/reshape.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... | 187 | 6,100 |
pyomo | pyomo/opt/tests/base/__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 | 573 |
coremltools | deps/protobuf/python/google/protobuf/internal/message_listener.py | .py | # Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redi... | 79 | 3,367 |
onnxruntime | onnxruntime/test/python/transformers/test_data/bert_squad_tensorflow2.1_keras2onnx_opset11/generate_tiny_keras2onnx_bert_models.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
"""
Convert a Bert large model exported by Keras2Onnx to a tiny model fo... | 447 | 18,102 |
astropy | astropy/constants/codata2014.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astronomical and physics constants in SI units. See :mod:`astropy.constants`
for a complete listing of constants defined in Astropy.
"""
import numpy as np
from .constant import Constant, EMConstant
# PHYSICAL CONSTANTS
class CODATA2014(Constant)... | 158 | 3,480 |
biopython | Bio/SCOP/Dom.py | .py | # Copyright 2000 by Jeffrey Chang. All rights reserved.
# Revisions copyright 2001 by Gavin E. Crooks. 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 ... | 77 | 2,466 |
coremltools | coremltools/converters/mil/frontend/tensorflow/ssa_passes/test_passes.py | .py | # Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import copy
import pytest
from coremltools.converters.mil.mil import Builder as mb
from coremltools... | 57 | 2,071 |
astropy | astropy/io/ascii/tests/test_ecsv.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module tests some of the methods related to the ``ECSV``
reader/writer.
"""
import copy
import io
import os
import sys
from contextlib import nullcontext
from io import StringIO
from pprint import pformat
import numpy as np
import pytest
import... | 1,397 | 42,628 |
lemur | lemur/plugins/lemur_acme/tests/test_route53.py | .py | from unittest.mock import MagicMock
import pytest
from lemur.plugins.lemur_acme.route53 import _find_zone_id
from lemur.tests.conftest import app # noqa
def test_zone_selection(app): # noqa
# Mocking AWS client
client = MagicMock()
zones = [
{"Config": {"PrivateZone": False}, "Name": "acme.id... | 35 | 1,404 |
beam | learning/katas/python/test_helper.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... | 56 | 1,868 |
loguru | tests/test_locks.py | .py | import gc
import pickle
import sys
import threading
import time
import pytest
from loguru import logger
class CyclicReference:
"""A minimal cyclic reference.
Cyclical references are garbage collected using the generational collector rather than
via reference counting. This is important here, because th... | 135 | 3,791 |
astropy | astropy/time/tests/test_corrs.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
from astropy import units as u
from astropy.coordinates import EarthLocation, SkyCoord, solar_system_ephemeris
from astropy.time import Time, TimeDelta
from astropy.utils import iers
from astropy.utils.compat.optional_deps import HAS_JPLEPHE... | 74 | 3,040 |
saleor | saleor/plugins/tests/fixtures/plugin_configuration.py | .py | import copy
import pytest
from ...base_plugin import ConfigurationTypeField
from ...models import PluginConfiguration
from ..sample_plugins import (
ChannelPluginSample,
PluginInactive,
PluginSample,
)
@pytest.fixture
def plugin_configuration(db):
configuration, _ = PluginConfiguration.objects.get_o... | 92 | 2,629 |
beam | sdks/python/apache_beam/examples/snippets/transforms/elementwise/partition_function.py | .py | # coding=utf-8
#
# 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");... | 71 | 2,432 |
wandb | wandb/plot/pr_curve.py | .py | from __future__ import annotations
import numbers
from collections.abc import Iterable
from typing import TYPE_CHECKING, TypeVar
import wandb
from wandb import util
from wandb.plot.custom_chart import plot_table
from wandb.plot.utils import test_missing, test_types
if TYPE_CHECKING:
from wandb.plot.custom_chart ... | 188 | 6,636 |
eve | tests/test_io/mongo.py | .py | # -*- coding: utf-8 -*-
from datetime import datetime
from unittest import TestCase
import simplejson as json
from bson import ObjectId, decimal128
from bson.dbref import DBRef
from cerberus import SchemaError
from eve.io.mongo import Mongo, MongoJSONEncoder, Validator
from eve.io.mongo.parser import ParseError, pars... | 485 | 16,744 |
wandb | wandb/integration/keras/keras.py | .py | """Keras integration helpers."""
import sys
import wandb
from wandb.util import add_import_hook
def _check_keras_version() -> None:
from keras import __version__ as keras_version
from packaging.version import parse
if parse(keras_version) < parse("2.4.0"):
wandb.termwarn(
f"Keras ve... | 28 | 643 |
beam | learning/tour-of-beam/learning-content/io/text-io/text-io-local-write/python-example/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... | 41 | 1,367 |
pyomo | pyomo/contrib/solver/solvers/scip/scip_direct.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... | 405 | 14,520 |
textual | tests/snapshot_tests/snapshot_apps/margin_multiple.py | .py | from textual.app import App, ComposeResult
from textual.containers import Container, ScrollableContainer, Horizontal
from textual.widgets import Label
class CompoundWidget(ScrollableContainer):
DEFAULT_CSS = """
#inner {
width: 1fr;
background: $panel;
align: center middle;
mar... | 44 | 860 |
saleor | saleor/graphql/account/tests/mutations/account/test_account_request_deletion.py | .py | from unittest.mock import ANY, patch
from urllib.parse import urlencode
from django.utils import timezone
from freezegun import freeze_time
from ......account.error_codes import AccountErrorCode
from ......account.notifications import get_default_user_payload
from ......core.notify import NotifyEventType
from ......c... | 253 | 8,816 |
pyomo | pyomo/common/tests/test_orderedset.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... | 92 | 3,012 |
pyomo | pyomo/core/base/set.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... | 4,706 | 159,192 |
textual | tests/snapshot_tests/snapshot_apps/notification_through_modes.py | .py | from textual.app import App, ComposeResult
from textual.screen import Screen
from textual.widgets import Label
class Mode(Screen):
def compose(self) -> ComposeResult:
yield Label("This is a mode screen")
class NotifyThroughModesApp(App[None]):
MODES = {
"test": Mode
}
def compose(s... | 27 | 558 |
coremltools | deps/pybind11/tests/conftest.py | .py | """pytest configuration
Extends output capture as needed by pybind11: ignore constructors, optional unordered lines.
Adds docstring and exceptions message sanitizers.
"""
from __future__ import annotations
import contextlib
import difflib
import gc
import multiprocessing
import re
import sys
import textwrap
import t... | 225 | 5,728 |
wandb | wandb/apis/_generated/create_service_account.py | .py | # Generated by ariadne-codegen
# Source: tools/graphql_codegen/api/
from __future__ import annotations
from wandb._pydantic import GQLId, GQLResult
class CreateServiceAccount(GQLResult):
result: CreateServiceAccountResult | None
class CreateServiceAccountResult(GQLResult):
user: CreateServiceAccountResult... | 23 | 479 |
ipython | IPython/testing/plugin/simple.py | .py | """Simple example using doctests.
This file just contains doctests both using plain python and IPython prompts.
All tests should be loaded by Pytest.
"""
def pyfunc():
"""Some pure python tests...
>>> pyfunc()
'pyfunc'
>>> import os
>>> 2+3
5
>>> for i in range(3):
... print(i... | 46 | 727 |
openvino | tests/layer_tests/py_frontend_tests/test_torchvision_preprocessor.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import copy
import platform
import numpy as np
import pytest
import torch
import torch.nn.functional as f
import torchvision.transforms as transforms
from PIL import Image
from openvino import Type, Core
from ope... | 273 | 10,313 |
probability | tensorflow_probability/python/math/psd_kernels/feature_scaled.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... | 142 | 6,052 |
textual | src/textual/widgets/directory_tree.py | .py | from textual.widgets._directory_tree import DirEntry
__all__ = ["DirEntry"]
| 4 | 77 |
wagtail | wagtail/project_template/search/views.py | .py | from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.template.response import TemplateResponse
from wagtail.models import Page
# To enable logging of search queries for use with the "Promoted search results" module
# <https://docs.wagtail.org/en/stable/reference/contrib/searchpromotion... | 47 | 1,421 |
saleor | saleor/graphql/webhook/mutations/webhook_trigger.py | .py | from dataclasses import asdict
import graphene
from celery.exceptions import Retry
from django.db.models import Exists, OuterRef
from graphene.utils.str_converters import to_camel_case
from ....app.models import App
from ....core import EventDeliveryStatus
from ....core import models as core_models
from ....core.tele... | 210 | 8,509 |
pyro | pyro/distributions/multivariate_studentt.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import math
import torch
from torch.distributions import constraints
from torch.distributions.utils import lazy_property
from pyro.distributions.torch import Chi2
from pyro.distributions.torch_distribution import TorchDistributio... | 135 | 5,193 |
biopython | Bio/KEGG/Map/__init__.py | .py | # Copyright 2001 by Tarjei Mikkelsen. All rights reserved.
# Copyright 2007 by Michiel de Hoon. 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 i... | 50 | 1,642 |
black | src/black/rusty.py | .py | """An error-handling model influenced by that used by the Rust programming language
See https://doc.rust-lang.org/book/ch09-00-error-handling.html.
"""
from typing import Generic, TypeVar, Union
T = TypeVar("T")
E = TypeVar("E", bound=Exception)
class Ok(Generic[T]):
def __init__(self, value: T) -> None:
... | 29 | 557 |
sphinx | tests/test_domains/test_domain_cpp.py | .py | """Tests the C++ Domain"""
from __future__ import annotations
import itertools
import re
import zlib
from typing import TYPE_CHECKING
import pytest
import sphinx.domains.cpp
from sphinx import addnodes
from sphinx.addnodes import (
desc,
desc_content,
desc_name,
desc_parameter,
desc_parameterlis... | 2,476 | 86,322 |
luigi | test/event_callbacks_test.py | .py | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... | 320 | 10,087 |
mlflow | tests/gateway/providers/test_xai.py | .py | from unittest import mock
import pytest
from fastapi.encoders import jsonable_encoder
from mlflow.gateway.config import EndpointConfig
from mlflow.gateway.providers.xai import XAIProvider
from mlflow.gateway.schemas import chat
from tests.gateway.tools import MockAsyncResponse, mock_http_client
def _make_provider(... | 78 | 2,128 |
wagtail | wagtail/models/workflows.py | .py | import swapper
from django import forms
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.core import checks
from django.core.exceptions im... | 1,372 | 48,002 |
coremltools | coremltools/test/optimize/torch/test_utils/test_fsdp_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 pytest
import torch
from coremltools.optimize.torch._utils.fsdp_utils import (
ModuleWrap... | 55 | 1,649 |
mlflow | mlflow/genai/judges/utils/prompt_utils.py | .py | """Prompt formatting and manipulation utilities for judge models."""
from __future__ import annotations
import re
from typing import TYPE_CHECKING, Any, Literal, NamedTuple, get_origin
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import BAD_REQUEST
if TYPE_CHECKING:
from mlflo... | 115 | 4,073 |
scikit-bio | skbio/stats/composition/tests/test_ancom.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.
# --------------------------------------------... | 672 | 30,454 |
ipython | tests/test_logger_unit.py | .py | """Unit tests for IPython.core.logger.Logger"""
import os
import pytest
from IPython.core.logger import Logger
@pytest.fixture
def logger(tmp_path):
return Logger(home_dir=str(tmp_path))
# ---------------------------------------------------------------------------
# logmode property
# -----------------------... | 193 | 5,744 |
gunicorn | examples/http2_features/http2_app.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
"""
HTTP/2 ASGI application demonstrating priority and trailers.
This example shows how to:
- Access stream priority information from HTTP/2 requests
- Send response trailers (useful for gRPC, checksums, etc.)
Ru... | 271 | 8,660 |
onnx | onnx/reference/ops/op_cos.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import numpy as np
from onnx.reference.ops._op import OpRunUnaryNum
class Cos(OpRunUnaryNum):
def _run(self, x):
return (np.cos(x),)
| 14 | 265 |
lemur | lemur/plugins/lemur_aws/sns.py | .py | """
.. module: lemur.plugins.lemur_aws.sts
:platform: Unix
:copyright: (c) 2020 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Jasmine Schladen <jschladen@netflix.com>
"""
import json
import arrow
import boto3
from flask import current_app
from lemu... | 79 | 2,787 |
onnx | onnx/numpy_helper.py | .py | # Copyright (c) ONNX Project Contributors
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import math
import sys
from typing import TYPE_CHECKING, Any
import ml_dtypes
import numpy as np
import numpy.typing as npt
import onnx.external_data_helper
from onnx import helper
if TYPE_CHECKING:
... | 663 | 22,186 |
gunicorn | tests/requests/invalid/chunked_03.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from gunicorn.http.errors import InvalidHeader
request = InvalidHeader
| 7 | 179 |
hatch | tests/helpers/templates/sdist/standard_include.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 = []
for f in get_template_f... | 53 | 1,272 |
mlflow | mlflow/utils/process.py | .py | import functools
import os
import subprocess
import sys
from mlflow.utils.databricks_utils import is_in_databricks_runtime
from mlflow.utils.os import is_windows
class ShellCommandException(Exception):
@classmethod
def from_completed_process(cls, process):
lines = [
f"Non-zero exit code: ... | 182 | 6,522 |
bazel | third_party/py/dataclasses/dataclasses/__init__.py | .py | import sys
import copy
import types
import inspect
__all__ = ['dataclass',
'field',
'Field',
'FrozenInstanceError',
'InitVar',
'MISSING',
# Helper functions.
'fields',
'asdict',
'astuple',
'make_dataclass',
... | 1,057 | 40,539 |
ipython | IPython/core/magics/display.py | .py | """Simple magics for display formats"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012 The IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#----... | 94 | 3,130 |
wandb | wandb/cli/leet.py | .py | """The `wandb leet` command.
W&B LEET, the Lightweight Experiment Exploration Tool, is a terminal UI
for viewing W&B runs.
"""
from __future__ import annotations
import dataclasses
import os
import pathlib
import subprocess
import sys
import urllib.parse
from typing import Any
import click
from typing_extensions im... | 330 | 10,110 |
mlflow | tests/metrics/test_metric_base.py | .py | from mlflow.metrics.base import MetricValue
def test_metric_value():
metricValue1 = MetricValue(
scores=[1, 2, 3],
justifications=["foo", "bar", "baz"],
aggregate_results={"mean": 2},
)
metricValue2 = MetricValue(
scores=[1, 2, 3],
justifications=["foo", "bar", "ba... | 39 | 1,144 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.