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 |
|---|---|---|---|---|---|
wandb | wandb/integration/keras/callbacks/tables_builder.py | .py | from __future__ import annotations
import abc
from typing import Any
from tensorflow.keras.callbacks import Callback # type: ignore
import wandb
from wandb.sdk.lib import telemetry
class WandbEvalCallback(Callback, abc.ABC):
"""Abstract base class to build Keras callbacks for model prediction visualization.
... | 231 | 8,880 |
mlflow | mlflow/protos/unity_catalog_service_pb2.py | .py |
import google.protobuf
from packaging.version import Version
if Version(google.protobuf.__version__).major >= 5:
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: unity_catalog_service.proto
# Protobuf Python Version: 5.26.0
"""Generated protocol buffer code."""
f... | 151 | 23,362 |
saleor | saleor/attribute/utils.py | .py | from collections import defaultdict
from collections.abc import Iterable
from django.db import transaction
from django.db.models import Exists, OuterRef, Q
from ..account.models import User
from ..page.models import Page
from ..product.models import Product, ProductVariant
from . import AttributeInputType
from .lock_... | 297 | 10,661 |
gunicorn | tests/dirty/__init__.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
"""Tests for dirty worker streaming functionality."""
| 6 | 160 |
sqlmap | tests/test_kerberos.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
Tests for the dependency-free Kerberos stack under extra/kerberos: the AES core (FIPS-197), the
RFC 3961/3962 etype crypto (n-fold, string-to-key, authenticated encryption) and the AS... | 323 | 15,742 |
mlflow | tests/pyfunc/test_responses_agent.py | .py | import functools
import pathlib
import pickle
from typing import Generator
from uuid import uuid4
import pytest
import mlflow
from mlflow.entities.span import SpanType
from mlflow.exceptions import MlflowException
from mlflow.models.signature import ModelSignature
from mlflow.pyfunc.loaders.responses_agent import _Re... | 1,491 | 56,626 |
textual | tests/snapshot_tests/snapshot_apps/data_table_style_order.py | .py | from typing_extensions import Literal
from textual.app import App, ComposeResult
from textual.widgets import DataTable, Label
data = [
"Severance",
"Foundation",
"Dark",
]
def make_datatable(
foreground_priority: Literal["css", "renderable"],
background_priority: Literal["css", "renderable"],
) ... | 63 | 1,716 |
python-prompt-toolkit | tests/test_filter.py | .py | from __future__ import annotations
import pytest
from prompt_toolkit.filters import Always, Condition, Filter, Never, to_filter
from prompt_toolkit.filters.base import _AndList, _OrList
def test_never():
assert not Never()()
def test_always():
assert Always()()
def test_invert():
assert not (~Always... | 132 | 3,532 |
clearml | clearml/backend_interface/util.py | .py | import getpass
import re
from _socket import gethostname
from datetime import datetime, timezone
from typing import Optional, Any, Tuple, Union
from ..backend_api.services import projects, queues
from ..debugging.log import get_logger, LoggerRoot
def make_message(s: str, **kwargs: Any) -> str:
# noinspection PyB... | 299 | 10,084 |
django-cms | cms/tests/test_log_entries.py | .py | from django.contrib.admin.models import ADDITION, CHANGE, DELETION, LogEntry
from django.forms.models import model_to_dict
from django.utils.translation import gettext_lazy as _
from cms.api import add_plugin, create_page, create_page_content
from cms.forms.wizards import CreateCMSPageForm
from cms.models import Page,... | 582 | 26,054 |
mlflow | mlflow/gemini/chat.py | .py | import json
import logging
from typing import TYPE_CHECKING
from mlflow.types.chat import (
ChatTool,
Function,
FunctionParams,
FunctionToolDefinition,
ParamProperty,
ToolCall,
)
if TYPE_CHECKING:
from google import genai
_logger = logging.getLogger(__name__)
def convert_gemini_func_to_... | 113 | 3,462 |
readthedocs.org | readthedocs/subscriptions/event_handlers.py | .py | """
Dj-stripe webhook handlers.
https://docs.dj-stripe.dev/en/master/usage/webhooks/.
"""
import requests
import structlog
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.humanize.templatetags import humanize
from django.db.models import Sum
from django.utils import ti... | 390 | 15,129 |
wandb | tests/system_tests/test_core/test_data_types_full.py | .py | import json
import platform
from pathlib import Path
from unittest import mock
import moviepy.video.io.ImageSequenceClip
import numpy as np
import PIL.Image
import pytest
import soundfile as sf
import wandb
from bokeh.document import Document
from bokeh.plotting import figure
def create_image(temp_dir) -> Path:
... | 248 | 6,977 |
wandb | wandb/sdk/artifacts/storage_handlers/wb_local_artifact_handler.py | .py | """WB local artifact storage handler."""
from __future__ import annotations
import os
from typing import TYPE_CHECKING, Literal
from urllib.parse import urlparse
import wandb
from wandb.sdk.artifacts.artifact_instance_cache import (
artifact_instance_cache_by_client_id,
)
from wandb.sdk.artifacts.artifact_manife... | 83 | 2,672 |
textual | tests/command_palette/test_escaping.py | .py | from textual.app import App
from textual.command import CommandPalette, Hit, Hits, Provider
class SimpleSource(Provider):
async def search(self, query: str) -> Hits:
def goes_nowhere_does_nothing() -> None:
pass
yield Hit(1, query, goes_nowhere_does_nothing, query)
class CommandPale... | 26 | 781 |
saleor | saleor/plugins/admin_email/tests/test_tasks.py | .py | from unittest import mock
from ....account.notifications import get_default_user_payload
from ....csv import ExportEvents
from ....csv.models import ExportEvent
from ....csv.notifications import get_default_export_payload
from ....order.notifications import get_default_order_payload
from ...email_common import EmailCo... | 357 | 11,085 |
django-cms | cms/test_utils/project/placeholderapp/views.py | .py | from django.http import HttpResponse
from django.shortcuts import render
from django.template import RequestContext
from django.template.engine import Engine
from django.views.generic import DetailView
from cms.test_utils.project.placeholderapp.models import (
CharPksExample,
Example1,
)
def example_view(req... | 87 | 2,916 |
openvino | tests/e2e_tests/common/preprocessors/transformers.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from .provider import ClassProvider
import cv2
from random import randint
import numpy as np
import logging as log
import sys
log.basicConfig(format="[ %(levelname)s ] %(message)s", level=log.INFO, stream=sys.stdout)
class CVFlip(Clas... | 188 | 8,665 |
mlflow | tests/entities/conftest.py | .py | import random
import uuid
import pytest
from mlflow.entities import (
Dataset,
DatasetInput,
InputTag,
LifecycleStage,
Metric,
Param,
RunData,
RunInfo,
RunInputs,
RunStatus,
RunTag,
)
from mlflow.utils.time import get_current_time_millis
from tests.helper_functions import ... | 92 | 2,192 |
metrics | tests/unittests/classification/test_eer.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... | 376 | 15,157 |
conda | tests/plugins/subcommands/doctor/health_checks/test_file_locking.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Tests for the file locking health check."""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from conda.base.constants import OK_MARK, X_MARK
from conda.base.context import context, reset_context
from cond... | 56 | 1,515 |
qutip | qutip/tests/core/data/test_block_operations.py | .py | import pytest
import numpy as np
from qutip.core import data as _data
from qutip.core.data import csr, Dense
from . import conftest
@pytest.mark.parametrize('outtype', _data.to.dtypes)
def test_empty_block_build(outtype):
"""block_build with no blocks should return a zero matrix"""
block_rows = np.array([], d... | 247 | 9,641 |
hydra | examples/tutorials/structured_configs/1_minimal/my_app_type_error.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from dataclasses import dataclass
import hydra
from hydra.core.config_store import ConfigStore
@dataclass
class MySQLConfig:
host: str = "localhost"
port: int = 3306
cs = ConfigStore.instance()
# Registering the Config class with the na... | 28 | 595 |
saleor | saleor/graphql/order/mutations/order_line_delete.py | .py | import graphene
from ....core.taxes import zero_taxed_money
from ....core.tracing import traced_atomic_transaction
from ....order import events
from ....order.error_codes import OrderErrorCode
from ....order.fetch import OrderLineInfo
from ....order.lock_objects import order_qs_select_for_update
from ....order.search ... | 135 | 4,996 |
pymc | tests/test_data.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... | 557 | 20,614 |
pyomo | pyomo/contrib/pynumero/algorithms/solvers/tests/test_scipy_solvers.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... | 551 | 22,688 |
probability | tensorflow_probability/python/internal/tensor_util_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... | 182 | 5,867 |
mlflow | mlflow/types/chat.py | .py | from __future__ import annotations
import warnings
from typing import Annotated, Any, Literal
from uuid import uuid4
from pydantic import BaseModel, ConfigDict, Field, model_serializer
class TextContentPart(BaseModel):
type: Literal["text"]
text: str
class ImageUrl(BaseModel):
"""
Represents an im... | 369 | 11,530 |
loguru | tests/exceptions/source/others/sys_tracebacklimit.py | .py | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", diagnose=False, backtrace=False, colorize=False)
logger.add(sys.stderr, format="", diagnose=True, backtrace=False, colorize=False)
logger.add(sys.stderr, format="", diagnose=False, backtrace=True, colorize=False)
logger.add(sys.std... | 58 | 673 |
saleor | saleor/tests/e2e/orders/discounts/test_order_voucher_usage_includes_draft_orders.py | .py | import pytest
from ... import DEFAULT_ADDRESS
from ...product.utils.preparing_product import prepare_product
from ...shop.utils.preparing_shop import prepare_shop
from ...utils import assign_permissions
from ...vouchers.utils import (
create_voucher,
create_voucher_channel_listing,
get_voucher,
)
from ..ut... | 155 | 5,086 |
saleor | saleor/plugins/avatax/tests/test_avatax.py | .py | import datetime
from copy import deepcopy
from decimal import Decimal
from json import JSONDecodeError
from unittest.mock import Mock, patch
import graphene
import pytest
from django.core.exceptions import ValidationError
from django.test import override_settings
from prices import Money, TaxedMoney
from requests impo... | 6,864 | 224,633 |
beam | sdks/python/apache_beam/runners/portability/__init__.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... | 19 | 859 |
bazel | third_party/py/abseil/absl/testing/flagsaver.py | .py | # Copyright 2017 The Abseil Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | 195 | 6,552 |
pyomo | pyomo/solvers/plugins/solvers/ASL.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... | 256 | 9,380 |
saleor | saleor/graphql/payment/tests/queries/test_payment_refund.py | .py | import graphene
from ....tests.utils import get_graphql_content
QUERY_PAYMENT_REFUND_AMOUNT = """
query payment($id: ID!) {
payment(id: $id) {
id,
availableRefundAmount{
amount
}
availableCaptureAmount{
amount
}
... | 54 | 1,387 |
biopython | Tests/test_Medline.py | .py | # Copyright 2008 Michiel de Hoon
#
# 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.
"""Tests for Medline module."""
import unittest... | 369 | 20,479 |
mlflow | mlflow/deployments/base.py | .py | """
This module contains the base interface implemented by MLflow model deployment plugins.
In particular, a valid deployment plugin module must implement:
1. Exactly one client class subclassed from :py:class:`BaseDeploymentClient`, exposing the primary
user-facing APIs used to manage deployments.
2. :py:func:`run... | 359 | 16,159 |
mamba | docs/source/tools/mermaid_inheritance.py | .py | r"""
mermaid_inheritance
~~~~~~~~~~~~~~~~~~~
Modified by the CoSApp team from sphinx.ext.inheritance_diagram
https://gitlab.com/cosapp/cosapp
Defines a docutils directive for inserting inheritance diagrams.
Provide the directive with one or more classes or modules (separated
by whitespace)... | 304 | 10,205 |
pymc | tests/distributions/test_custom.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... | 786 | 28,961 |
biopython | Tests/test_SearchIO_write.py | .py | # Copyright 2012 by Wibowo Arindrarto. 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.
"""Tests for SearchIO writing."""
import os
import unittest
from search_tests_common imp... | 223 | 9,439 |
beam | release/src/main/scripts/download_github_actions_artifacts.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... | 350 | 12,959 |
openvino | tests/layer_tests/pytorch_tests/test_tuple_unpack.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
import torch
from pytorch_layer_test_class import PytorchLayerTest
class TestTupleUnpack(PytorchLayerTest):
def _prepare_input(self):
return (self.random.randn(2, 4, 6, 8),)
def create_model(self):
... | 110 | 4,076 |
probability | tensorflow_probability/python/experimental/mcmc/__init__.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... | 145 | 9,131 |
coremltools | coremltools/optimize/_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 math
from collections import namedtuple
from typing import Collection, Dict, List, Optional, Tupl... | 962 | 39,878 |
readthedocs.org | readthedocs/builds/admin.py | .py | """Django admin interface for `~builds.models.Build` and related models."""
from django.contrib import admin
from django.contrib import messages
from readthedocs.builds.models import Build
from readthedocs.builds.models import BuildCommandResult
from readthedocs.builds.models import BuildConfig
from readthedocs.build... | 140 | 4,277 |
textual | docs/examples/how-to/center05.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Static
QUOTE = "Could not find you in Seattle and no terminal is in operation at your classified address."
class CenterApp(App):
"""How to center things."""
CSS = """
Screen {
align: center middle;
}
#hello {
... | 30 | 578 |
coremltools | coremltools/converters/mil/mil/types/type_tuple.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 . import type_int, type_unknown
from .annotate import annotate
from .get_type_info import get_ty... | 54 | 1,263 |
cvxpy | cvxpy/reductions/dcp2cone/canonicalizers/huber_canon.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... | 100 | 3,702 |
deap | doc/code/tutorials/part_2/2_3_5_seeding_a_population.py | .py | # 2.3.5 Seeding a population
import json
from deap import base
from deap import creator
creator.create("FitnessMax", base.Fitness, weights=(1.0, 1.0))
creator.create("Individual", list, fitness=creator.FitnessMax)
def initIndividual(icls, content):
return icls(content)
def initPopulation(pcls, ind_init, filenam... | 24 | 695 |
probability | tensorflow_probability/python/distributions/internal/statistical_testing.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,593 | 74,869 |
scikit-bio | skbio/tree/tests/test_upgma.py | .py | import io
from unittest import TestCase, main
from skbio import DistanceMatrix, TreeNode
from skbio.util import get_data_path
from skbio.tree._upgma import upgma
class UpgmaTests(TestCase):
def setUp(self):
data = [[0, 5, 9, 9, 8],
[5, 0, 10, 10, 9],
[9, 10, 0, 8,... | 57 | 2,099 |
onnxruntime | onnxruntime/python/backend/__init__.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
from .backend import is_compatible, prepare, run, supports_device # noq... | 7 | 328 |
wagtail | wagtail/actions/delete_page.py | .py | from django.core.exceptions import PermissionDenied
from wagtail.actions.base import BaseAction
from wagtail.log_actions import log
class DeletePagePermissionError(PermissionDenied):
"""
Raised when the page delete cannot be performed due to insufficient permissions.
"""
pass
class DeletePageActio... | 54 | 1,563 |
sphinx | tests/roots/test-directive-code/conf.py | .py | exclude_patterns = ['_build']
numfig = True
| 3 | 44 |
coremltools | coremltools/converters/sklearn/_converter_internal.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
"""
The primary file for converting Scikit-learn models.
"""
from ..._deps import _HAS_SKLEARN
from ...... | 349 | 12,900 |
sqlmap | plugins/dbms/hsqldb/fingerprint.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
import re
from lib.core.common import Backend
from lib.core.common import Format
from lib.core.common import unArrayizeValue
from lib.core.data import conf
from lib.core.data imp... | 154 | 5,283 |
hydra | tools/configen/tests/test_modules/generated.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Generated by configen, do not edit.
# See https://github.com/hydra-ecosystem/hydra/tree/main/tools/configen
# fmt: off
# isort:skip_file
# flake8: noqa
from dataclasses import dataclass, field
from omegaconf import MISSING
from tests.test_modules... | 102 | 2,616 |
probability | tensorflow_probability/python/distributions/dirichlet_multinomial.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... | 401 | 15,939 |
hypercorn | compliance/h2spec/server.py | .py | async def app(scope, receive, send):
while True:
event = await receive()
if event['type'] == 'http.disconnect':
break
elif event['type'] == 'http.request' and not event.get('more_body', False):
await send_data(send)
break
elif event['type'] == 'lif... | 26 | 808 |
loguru | tests/exceptions/source/backtrace/suppressed_expression_direct.py | .py | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", colorize=False, backtrace=True, diagnose=False)
def a(x, y):
x / y
@logger.catch
def b_decorated():
try:
a(1, 0)
except ZeroDivisionError as e:
raise ValueError("NOK") from e
def b_not_decorated():... | 47 | 693 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/layer_norm_t5_gen.py | .py | import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
def GenerateModel(model_name, has_casts=False): # noqa: N802
nodes = [ # SimplifiedLayerNorm subgraph
helper.make_node("Pow", ["cast_A" if has_casts else "A", "pow_in_2"], ["pow_out"], "pow"),
helper.make_node("ReduceMean", ["p... | 64 | 2,359 |
bazel | third_party/py/concurrent/__init__.py | .py | from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
| 4 | 76 |
probability | tensorflow_probability/python/distributions/deterministic.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... | 468 | 16,917 |
saleor | saleor/graphql/product/tests/test_product_filtering_and_sorting_with_channels.py | .py | import datetime
import uuid
from decimal import Decimal
import pytest
from freezegun import freeze_time
from ....product import ProductTypeKind
from ....product.models import (
Product,
ProductChannelListing,
ProductType,
ProductVariant,
ProductVariantChannelListing,
)
from ....tests.utils import ... | 831 | 25,658 |
pdm | tests/fixtures/projects/test-plugin-pdm/hello.py | .py | from pdm.cli.commands.base import BaseCommand
class HelloCommand(BaseCommand):
"""Say hello to somebody"""
def add_arguments(self, parser):
parser.add_argument("-n", "--name", help="the person's name")
def handle(self, project, options):
print(f"Hello, {options.name or 'world'}")
def m... | 16 | 380 |
python-prompt-toolkit | examples/print-text/pygments-tokens.py | .py | #!/usr/bin/env python
"""
Printing a list of Pygments (Token, text) tuples,
or an output of a Pygments lexer.
"""
import pygments
from pygments.lexers.python import PythonLexer
from pygments.token import Token
from prompt_toolkit import print_formatted_text
from prompt_toolkit.formatted_text import PygmentsTokens
fro... | 46 | 1,231 |
onnxruntime | onnxruntime/test/testdata/transform/computation_reduction/reshape/mlm_bert_e2e.py | .py | import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
# inputs and outputs
hidden = 1024
head = 16
vocab_size = 30522
inputs = [
helper.make_tensor_value_info("input", TensorProto.FLOAT, ["batch_size", "sequence_length", hidden]),
helper.make_tensor_value_info("attention_mask", TensorProto.INT64... | 262 | 13,155 |
probability | tensorflow_probability/python/distributions/gamma_gamma.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... | 298 | 12,112 |
pyomo | pyomo/core/kernel/container_utils.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... | 91 | 3,066 |
openvino | tests/layer_tests/pytorch_tests/test_leaky_relu.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
from pytorch_layer_test_class import PytorchLayerTest, skip_check
class TestLeakyRelu(PytorchLayerTest):
def _prepare_input(self):
return (self.random.randn(1, 3, 224, 224),)
def create_model(self, alpha... | 37 | 1,246 |
pyomo | examples/pyomo/draft/diet2.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... | 83 | 2,112 |
beam | sdks/python/apache_beam/runners/worker/logger_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... | 221 | 8,091 |
django-cms | cms/test_utils/util/static_analysis.py | .py | import os
from io import StringIO
from pyflakes import api
from pyflakes.checker import Checker
from pyflakes.reporter import Reporter
def _pyflakes_report_with_nopyflakes(self, messageClass, node, *args, **kwargs):
with open(self.filename) as code:
if code.readlines()[node.lineno - 1].strip().endswith('... | 48 | 1,555 |
metrics | tests/unittests/segmentation/test_generalized_dice_score.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... | 125 | 4,992 |
onnx | onnx/reference/ops/op_optional_get_element.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from onnx.reference.op_run import OpRun
class OptionalGetElement(OpRun):
def _run(self, x):
if x is None:
raise ValueError("The requested optional input has no value.")
... | 14 | 332 |
onnxruntime | onnxruntime/test/testdata/transform/computation_reduction/gathernd/e2e.py | .py | import numpy as np
import onnx
from onnx import OperatorSetIdProto, TensorProto, helper, numpy_helper
vocab_size = 256
X = helper.make_tensor_value_info("input", TensorProto.FLOAT, ["batch", "seqlen", 128])
unsqueezed_masked_lm_positions = helper.make_tensor_value_info(
"unsqueezed_masked_lm_positions",
Tenso... | 160 | 5,514 |
pyomo | pyomo/common/plugins.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... | 13 | 569 |
python-prompt-toolkit | examples/prompts/get-input.py | .py | #!/usr/bin/env python
"""
The most simple prompt example.
"""
from prompt_toolkit import prompt
if __name__ == "__main__":
answer = prompt("Give me some input: ")
print(f"You said: {answer}")
| 11 | 202 |
pyomo | pyomo/contrib/sensitivity_toolbox/k_aug.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... | 135 | 4,786 |
probability | tensorflow_probability/python/internal/backend/numpy/gen/linear_operator_householder.py | .py | # Copyright 2020 The TensorFlow Probability Authors. All Rights Reserved.
# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
# THIS FILE IS AUTO-GENERATED BY `gen_linear_operators.py`.
# DO NOT MODIFY DIRECTLY.
# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@... | 322 | 13,263 |
mkdocs | mkdocs/tests/plugin_tests.py | .py | #!/usr/bin/env python
from __future__ import annotations
import os
import unittest
from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
from typing_extensions import assert_type
from mkdocs.structure.nav import Navigation
else:
def assert_type(val, typ):
return None
from mkdocs import ... | 329 | 11,953 |
hatch | tests/project/test_core.py | .py | import pytest
from hatch.project.core import Project
class TestFindProjectRoot:
def test_no_project(self, temp_dir):
project = Project(temp_dir)
assert project.find_project_root() is None
@pytest.mark.parametrize("file_name", ["pyproject.toml", "setup.py"])
def test_direct(self, temp_dir... | 245 | 8,142 |
django-cms | cms/exceptions.py | .py | class PluginAlreadyRegistered(Exception):
pass
class PluginNotRegistered(Exception):
pass
class PluginLimitReached(Exception):
"""Gets triggered when a placeholder has reached its plugin limit."""
pass
class AppAlreadyRegistered(Exception):
pass
class ToolbarAlreadyRegistered(Exception):
... | 86 | 1,311 |
mlflow | dev/flavors/tests/test_cli.py | .py | import subprocess
import sys
from unittest import mock
import pytest
from flavors import _cli
def _run(*args: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[sys.executable, "-m", "flavors._cli", *args],
capture_output=True,
text=True,
check=False,
)
@pytes... | 46 | 1,339 |
cvxpy | cvxpy/reductions/solvers/conic_solvers/gurobi_conif.py | .py | """
Copyright 2013 Steven Diamond, 2017 Robin Verschueren
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... | 417 | 15,130 |
scikit-optimize | skopt/tests/test_common.py | .py | from functools import partial
from itertools import product
import numpy as np
from scipy.optimize import OptimizeResult
import pytest
from numpy.testing import assert_almost_equal
from numpy.testing import assert_array_less
from numpy.testing import assert_array_equal
from numpy.testing import assert_array_almost_e... | 439 | 15,956 |
mlflow | mlflow/server/graphql/graphql_no_batching.py | .py | from typing import NamedTuple
from graphql.error import GraphQLError
from graphql.execution import ExecutionResult
from graphql.language.ast import DocumentNode, FieldNode
from mlflow.environment_variables import (
MLFLOW_SERVER_GRAPHQL_MAX_ALIASES,
MLFLOW_SERVER_GRAPHQL_MAX_ROOT_FIELDS,
)
_MAX_DEPTH = 10
_M... | 90 | 2,959 |
mlflow | tests/gateway/test_gateway_budget.py | .py | from unittest.mock import MagicMock, patch
import fastapi
import pytest
import mlflow
import mlflow.gateway.budget_tracker as _bt_module
from mlflow.entities import SpanStatusCode, SpanType
from mlflow.entities.gateway_budget_policy import (
BudgetAction,
BudgetDuration,
BudgetDurationUnit,
BudgetTarg... | 781 | 28,015 |
pyomo | pyomo/contrib/gdpopt/solve_discrete_problem.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... | 214 | 9,469 |
probability | tensorflow_probability/python/bijectors/sigmoid.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... | 191 | 7,276 |
sqlmap | extra/kerberos/crypto.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
# Dependency-free Kerberos "simplified profile" crypto (RFC 3961) for the AES-CTS-HMAC-SHA1-96 etypes
# (RFC 3962: aes128-cts-hmac-sha1-96 = etype 17, aes256-cts-hmac-sha1-96 = et... | 264 | 10,571 |
mlflow | mlflow/genai/judges/prompts/summarization.py | .py | # NB: User-facing name for the summarization assessment.
SUMMARIZATION_ASSESSMENT_NAME = "summarization"
SUMMARIZATION_PROMPT = """\
Consider the following source document and candidate summary.
You must decide whether the summary is an acceptable summary of the document.
Output only "yes" or "no" based on whether the... | 27 | 1,969 |
conda | tests/shards/test_shards.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""
Test sharded repodata.
"""
from __future__ import annotations
import hashlib
import json
import logging
import os
import sqlite3
import tempfile
import threading
import time
import warnings
from pathlib import Path
from typing import TYPE_... | 1,655 | 54,534 |
mlflow | tests/pyfunc/test_pyfunc_schema_enforcement_pyspark.py | .py | from datetime import datetime
import pytest
from pyspark.sql import Row, SparkSession
from pyspark.sql.types import (
ArrayType,
BinaryType,
BooleanType,
DateType,
DoubleType,
FloatType,
IntegerType,
LongType,
ShortType,
StringType,
StructField,
StructType,
Timestamp... | 338 | 10,510 |
metrics | tests/unittests/classification/test_matthews_corrcoef.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... | 418 | 17,204 |
sqlmap | tests/test_entries.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
Unit tests for plugins/generic/entries.py (Entries), exercising dumpTable /
dumpAll / dumpFoundTables / dumpFoundColumn by MOCKING the injection layer
(lib.request.inject.getValue) an... | 807 | 30,445 |
openvino | tests/model_hub_tests/pytorch/test_speech-transformer.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import subprocess
import sys
import tempfile
import pytest
import torch
from torch_utils import TestTorchConvertModel
# To make tests reproducible we seed the random generator
torch.manual_seed(0)
class TestSpeechTransform... | 62 | 2,368 |
omegaconf | subprojects/omegaconf-pydevd/pydevd_plugins/extensions/pydevd_plugin_omegaconf.py | .py | # based on https://github.com/fabioz/PyDev.Debugger/tree/main/pydevd_plugins/extensions
import os
import sys
from typing import Any, Dict
from _pydevd_bundle.pydevd_extension_api import ( # type: ignore
StrPresentationProvider,
TypeResolveProvider,
)
DEBUG = False
def print_debug(msg: str) -> None: # prag... | 127 | 4,251 |
saleor | saleor/graphql/payment/tests/mutations/test_payment_void.py | .py | import graphene
from .....payment import ChargeStatus, TransactionKind
from ....tests.utils import assert_no_permission, get_graphql_content
VOID_QUERY = """
mutation PaymentVoid($paymentId: ID!) {
paymentVoid(paymentId: $paymentId) {
payment {
id,
chargeStatus
... | 155 | 5,072 |
returns | tests/test_pipeline/test_managed/test_managed_reader_future_result.py | .py | import pytest
from returns.context import NoDeps, ReaderFutureResult
from returns.io import IOFailure, IOSuccess
from returns.pipeline import managed
from returns.result import Failure, Result, Success
def _acquire_success() -> ReaderFutureResult[str, str, NoDeps]:
return ReaderFutureResult.from_value('acquire s... | 138 | 3,820 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.