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 |
|---|---|---|---|---|---|
coveragepy | tests/modules/pkg1/sub/ps1a.py | .py | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/coveragepy/coveragepy/blob/main/NOTICE.txt
d = 1
e = 2
f = 3
| 7 | 176 |
cvxpy | cvxpy/reductions/solvers/conic_solvers/cuclarabel_conif.py | .py | """
Copyright 2022, the CVXPY 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 writing, sof... | 213 | 7,172 |
pyro | tests/contrib/funsor/test_valid_models_plate.py | .py | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import logging
import pytest
import torch
from pyro.ops.indexing import Vindex
from tests.common import xfail_param
# put all funsor-related imports here, so test collection works without funsor
try:
import funsor
import py... | 201 | 7,546 |
biopython | Bio/Graphics/GenomeDiagram/_Feature.py | .py | # Copyright 2003-2008 by Leighton Pritchard. All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
#
# Contact: ... | 198 | 8,064 |
notebook | ui-tests/test/jupyter_server_config.py | .py | from typing import Any
from jupyterlab.galata import configure_jupyter_server
c: Any
c.JupyterNotebookApp.expose_app_in_browser = True
configure_jupyter_server(c)
| 9 | 166 |
kombu | kombu/utils/uuid.py | .py | """UUID utilities."""
from __future__ import annotations
from typing import Callable
from uuid import UUID, uuid4
def uuid(_uuid: Callable[[], UUID] = uuid4) -> str:
"""Generate unique id in UUID4 format.
See Also
--------
For now this is provided by :func:`uuid.uuid4`.
"""
return str(_u... | 16 | 327 |
onnxruntime | tools/ci_build/github/windows/jar_packaging_test.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import zipfile
from pathlib import Path
import jar_packaging # The refactored script
import pytest
# Helper to create an empty file
def create_empty_file(path):
Path(path).touch()
# Helper to create a dummy JAR file... | 145 | 6,757 |
mamba | micromamba/tests/test_repoquery.py | .py | import platform
from pathlib import Path
import pytest
from . import helpers
@pytest.fixture
def yaml_env(tmp_prefix: Path) -> None:
helpers.install(
"--channel",
"conda-forge",
"yaml=0.2.5",
"pyyaml=6.0.0",
no_dry_run=True,
)
@pytest.mark.parametrize("shared_pkgs_d... | 642 | 25,238 |
eve | eve/io/__init__.py | .py | # -*- coding: utf-8 -*-
"""
eve.io
~~~~~~
This package implements the data layers supported by Eve.
:copyright: (c) 2017 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
# flake8: noqa
from eve.io.base import ConnectionException, DataLayer
| 15 | 283 |
coremltools | deps/protobuf/python/google/protobuf/internal/generator_test.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... | 358 | 15,219 |
mlflow | tests/utils/test_server_info.py | .py | import os
import select
import signal
import threading
from unittest import mock
import pytest
from mlflow.utils import server_info
from mlflow.utils.rest_utils import MlflowHostCreds
from mlflow.utils.server_info import (
SERVER_INFO_ENDPOINT,
ServerInfoRequestError,
ServerInfoResponse,
_clear_server... | 570 | 19,117 |
saleor | saleor/graphql/order/mutations/order_void.py | .py | import graphene
from django.core.exceptions import ValidationError
from ....order.actions import order_voided
from ....order.error_codes import OrderErrorCode
from ....payment import TransactionKind, gateway
from ....payment import models as payment_models
from ....permission.enums import OrderPermissions
from ...app.... | 81 | 2,769 |
luigi | luigi/task_register.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... | 257 | 8,071 |
pyomo | pyomo/gdp/plugins/__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... | 41 | 1,252 |
jupytext | tests/functional/cli/test_cli.py | .py | import os
import sys
import time
import unittest.mock as mock
import warnings
from argparse import ArgumentTypeError
from io import StringIO
from shutil import copyfile
from subprocess import check_call
import nbformat
import pytest
from jupyter_client.kernelspec import find_kernel_specs, get_kernel_spec
from jupyter_... | 1,538 | 48,329 |
scikit-bio | skbio/io/registry.py | .py | r"""I/O Registry (:mod:`skbio.io.registry`)
=======================================
.. currentmodule:: skbio.io.registry
Classes
-------
.. autosummary::
:toctree:
IORegistry
Format
Functions
---------
.. autosummary::
:toctree:
create_format
Exceptions
----------
.. autosummary::
DuplicateR... | 1,089 | 39,939 |
textual | docs/examples/styles/max_width.py | .py | from textual.app import App
from textual.containers import VerticalScroll
from textual.widgets import Placeholder
class MaxWidthApp(App):
CSS_PATH = "max_width.tcss"
def compose(self):
yield VerticalScroll(
Placeholder("max-width: 50h", id="p1"),
Placeholder("max-width: 999", ... | 21 | 510 |
astropy | astropy/coordinates/tests/accuracy/test_icrs_fk5.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from astropy import units as u
from astropy.coordinates import angular_separation
from astropy.coordinates.builtin_frames import FK5, ICRS
from astropy.table import Table
from astropy.time import Time
from astropy.utils.data import ge... | 68 | 1,880 |
mlflow | mlflow/server/job_api.py | .py | """
Internal job APIs for UI invocation
"""
import json
from typing import Any
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from mlflow.entities._job import Job as JobEntity
from mlflow.entities._job_status import JobStatus
from mlflow.exceptions import MlflowException
job_api_router ... | 136 | 3,657 |
confluent-kafka-python | tests/ducktape/producer_benchmark_metrics.py | .py | """
Producer benchmark metrics collection and validation for Kafka performance testing.
Implements comprehensive metrics tracking including latency percentiles,
per-topic/partition breakdowns, memory monitoring, and batch efficiency analysis.
"""
import json
import os
import statistics
import time
from collections im... | 419 | 17,159 |
astropy | astropy/cosmology/_src/tests/parameter/test_parameter.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Testing :mod:`astropy.cosmology._src.parameter`."""
from collections.abc import Callable
import numpy as np
import pytest
import astropy.units as u
from astropy.cosmology import Cosmology, Parameter
from astropy.cosmology._src.core import _COSMOLOGY... | 448 | 15,772 |
textual | tests/test_app.py | .py | import asyncio
import contextlib
import pytest
from rich.terminal_theme import DIMMED_MONOKAI, MONOKAI, NIGHT_OWLISH
from textual import events
from textual.app import App, ComposeResult
from textual.command import SimpleCommand
from textual.pilot import Pilot, _get_mouse_message_arguments
from textual.screen import ... | 426 | 11,790 |
onnxruntime | orttraining/orttraining/python/training/ortmodule/torch_cpp_extensions/cpu/torch_interop_utils/setup.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
import os
from setuptools import Extension, setup # noqa: F401
from to... | 39 | 1,128 |
onnxruntime | orttraining/tools/ci_test/run_gpt2_perf_test.py | .py | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import os
import subprocess
import sys
from collections import namedtuple
SCRIPT_DIR = os.path.realpath(os.path.dirname(__file__))
def parse_args():
parser = argparse.ArgumentPars... | 72 | 2,297 |
beam | sdks/python/apache_beam/transforms/environments.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... | 940 | 32,277 |
pymc | pymc/tuning/scaling.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... | 139 | 3,898 |
funcy | tests/py38_decorators.py | .py | import pytest
from funcy.decorators import decorator
def test_decorator_access_args():
@decorator
def return_x(call):
return call.x
# no arg
with pytest.raises(AttributeError): return_x(lambda y: None)(10)
# pos arg
assert return_x(lambda x: None)(10) == 10
with pytest.raises(Att... | 43 | 1,540 |
saleor | saleor/tests/e2e/product/utils/product_update.py | .py | from ...utils import get_graphql_content
PRODUCT_UPDATE_MUTATION = """
mutation ProductUpdate($id: ID!, $input: ProductInput!) {
productUpdate(id: $id, input: $input) {
errors {
field
message
code
}
product {
id
name
productType {
id
}
category {
... | 61 | 1,031 |
confluent-kafka-python | tests/test_Producer.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import gc
import threading
import time
from struct import pack
import pytest
from confluent_kafka import Consumer, KafkaError, KafkaException, Producer, SerializingProducer, TopicPartition
from confluent_kafka.avro import AvroProducer
# Additional imports for batch integ... | 1,386 | 49,498 |
mlflow | tests/db/test_schema.py | .py | import difflib
import logging
import re
from pathlib import Path
from typing import NamedTuple
import pytest
from sqlalchemy import create_engine, inspect
from sqlalchemy.schema import CreateTable, MetaData, UniqueConstraint
_logger = logging.getLogger(__name__)
_DIALECT_REFLECTED_UNIQUE_CONSTRAINTS = {
"mysql":... | 257 | 8,207 |
beam | sdks/python/apache_beam/io/hadoopfilesystem_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... | 675 | 22,668 |
qutip | qutip/tests/core/test_coefficient.py | .py | import pytest
import pickle
import qutip
import numpy as np
import scipy.interpolate as interp
from functools import partial
from qutip.core.coefficient import (coefficient, norm, conj, const,
CompilationOptions, Coefficient,
clean_compiled_coeffic... | 501 | 16,460 |
black | tests/data/cases/fmtskip_in_parens.py | .py | # Regression tests for https://github.com/psf/black/issues/4513.
# Fixed by #4903 ("Improve fmt:skip handling in nested expressions with checks").
# Each of the three inputs below used to crash with a "Cannot parse" error.
# Case A: triple-quoted string inside parens with a leading `# fmt: skip` line.
(
# fmt: skip
""... | 50 | 1,183 |
wagtail | wagtail/tests/permission_policies/test_site_permission_policies.py | .py | from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from wagtail.models import Site
from wagtail.permission_policies.sites import SitePermissionPolicy
from wagtail.test.testapp.models import ImportantPagesSiteSetting, Test... | 285 | 9,776 |
onnx | tests/python/version_converter/automatic_upgrade_test.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from typing import ClassVar
import automatic_conversion_test_base
import numpy as np
import onnx
from onnx import TensorProto, helper
##################################################################... | 2,116 | 65,164 |
beam | sdks/python/apache_beam/runners/interactive/augmented_pipeline_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... | 85 | 2,773 |
pyomo | pyomo/solvers/plugins/solvers/cplex_persistent.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... | 157 | 6,272 |
saleor | saleor/graphql/discount/mutations/sale/sale_create.py | .py | import datetime
import graphene
from django.core.exceptions import ValidationError
from .....core.tracing import traced_atomic_transaction
from .....discount import PromotionType, models
from .....discount.error_codes import DiscountErrorCode
from .....discount.models import Promotion
from .....discount.utils.promoti... | 150 | 5,827 |
saleor | saleor/warehouse/error_codes.py | .py | from enum import Enum
class WarehouseErrorCode(str, Enum):
ALREADY_EXISTS = "already_exists"
GRAPHQL_ERROR = "graphql_error"
INVALID = "invalid"
NOT_FOUND = "not_found"
REQUIRED = "required"
UNIQUE = "unique"
class StockErrorCode(str, Enum):
ALREADY_EXISTS = "already_exists"
GRAPHQL_... | 27 | 603 |
pyro | pyro/ops/einsum/adjoint.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import weakref
from abc import ABCMeta, abstractmethod
import torch
from pyro.ops import packed
from pyro.util import jit_iter
SAMPLE_SYMBOL = " " # must be unique and precede alphanumeric characters
class Backward(object, me... | 151 | 4,971 |
biopython | Tests/test_phenotype_fit.py | .py | # Copyright 2014-2016 Marco Galardini. All rights reserved.
# Adapted from test_Mymodule.py by Jeff Chang
#
# 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... | 78 | 2,482 |
pyomo | pyomo/contrib/incidence_analysis/visualize.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... | 217 | 7,636 |
loguru | tests/exceptions/source/modern/t_string.py | .py | # fmt: off
import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", colorize=True, backtrace=False, diagnose=True)
def hello():
output = t"Hello" + t' ' + t"""World""" and world()
def world():
name = "world"
t = 1
t"{name} -> { t }" and {} or t'{{ {t / 0} }}'
with l... | 22 | 347 |
clearml | examples/frameworks/pytorch/pytorch_abseil.py | .py | # Example of MNIST training with PyTorch and abseil integration
from __future__ import print_function
import os
from tempfile import gettempdir
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from absl import app, flags
from torchvision import datasets, transforms
from... | 187 | 5,346 |
hydra | examples/tutorials/structured_configs/5.2_structured_config_schema_different_config_group/my_app.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from dataclasses import dataclass
import database_lib
from omegaconf import MISSING, OmegaConf
import hydra
from hydra.core.config_store import ConfigStore
@dataclass
class Config:
db: database_lib.DBConfig = MISSING
debug: bool = False
... | 35 | 659 |
openvino | tests/layer_tests/tensorflow2_keras_tests/test_tf2_keras_avg_pool_3D.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
import tensorflow as tf
from common.tf2_layer_test_class import CommonTF2LayerTest
class TestKerasAvgPool3D(CommonTF2LayerTest):
def create_keras_avg_pool_3D_net(self, pool_size, strides, padding, data_format, input_... | 56 | 2,675 |
kombu | t/unit/test_serialization.py | .py | #!/usr/bin/python
from __future__ import annotations
from base64 import b64decode
from unittest.mock import call, patch
import pytest
import t.skip
from kombu.exceptions import ContentDisallowed, DecodeError, EncodeError
from kombu.serialization import (SerializerNotInstalled,
disab... | 318 | 11,162 |
clearml | examples/reporting/text_reporting.py | .py | # ClearML - Example of manual graphs and statistics reporting
#
from __future__ import print_function
import logging
import sys
import six
from clearml import Logger, Task
def report_logs(logger):
# type: (Logger) -> None
"""
reporting text to logs section
:param logger: The task.logger to use for... | 93 | 2,832 |
mlflow | tests/genai/scorers/test_registered_scorers_scheduling.py | .py | from unittest.mock import patch
import pytest
from mlflow.exceptions import MlflowException
from mlflow.genai.scorers import Guidelines, scorer
from mlflow.genai.scorers.base import Scorer, ScorerSamplingConfig
@pytest.fixture(autouse=True)
def mock_databricks_runtime():
from mlflow.genai.scorers.registry impor... | 419 | 15,130 |
saleor | saleor/graphql/product/mutations/product_type/product_type_update.py | .py | import graphene
from .....permission.enums import ProductTypePermissions
from .....product import models
from .....product.tasks import update_variants_names
from .....product.utils.search_helpers import (
mark_products_search_vector_as_dirty_in_batches,
)
from ....core import ResolveInfo
from ....core.types impor... | 59 | 2,237 |
astropy | astropy/table/tests/test_index.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import io
import warnings
import numpy as np
import numpy.testing as npt
import pytest
from astropy import units as u
from astropy.table import Column, QTable, Row, Table, hstack
from astropy.table.bst import BST
from astropy.table.column import BaseCol... | 1,179 | 39,782 |
black | tests/data/cases/yield_singleton_tuple.py | .py | # flags: --preview
def f():
yield x,
# output
def f():
yield (x,)
| 12 | 79 |
pyomo | pyomo/solvers/tests/mip/test_convert.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... | 375 | 12,809 |
scikit-optimize | skopt/learning/gbrt.py | .py | import numpy as np
from sklearn.base import clone
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.utils import check_random_state
from joblib import Parallel, delayed
def _parallel_fit(regressor, X, y):
return regressor.fit(X, y)
class ... | 124 | 4,649 |
saleor | saleor/payment/error_codes.py | .py | from enum import Enum
class PaymentErrorCode(Enum):
BILLING_ADDRESS_NOT_SET = "billing_address_not_set"
GRAPHQL_ERROR = "graphql_error"
INVALID = "invalid"
NOT_FOUND = "not_found"
REQUIRED = "required"
UNIQUE = "unique"
PARTIAL_PAYMENT_NOT_ALLOWED = "partial_payment_not_allowed"
SHIPPI... | 135 | 4,187 |
flit | tests/samples/module2.py | .py | """
Docstring formatted like this.
"""
__version__ = '7.0'
| 6 | 60 |
textual | tests/test_widget_removing.py | .py | from textual.app import App, ComposeResult
from textual.containers import Container, Vertical
from textual.widgets import Button, Label, Static
async def test_remove_single_widget():
"""It should be possible to the only widget on a screen."""
async with App().run_test() as pilot:
widget = Static()
... | 228 | 8,442 |
mlflow | tests/models/test_model_config.py | .py | import os
from unittest import mock
import pytest
from mlflow.exceptions import MlflowException
from mlflow.models import ModelConfig
dir_path = os.path.dirname(os.path.abspath(__file__))
VALID_CONFIG_PATH = os.path.join(dir_path, "configs/config.yaml")
VALID_CONFIG_PATH_2 = os.path.join(dir_path, "configs/config_2.... | 93 | 3,666 |
black | src/black/comments.py | .py | import re
from collections.abc import Collection, Iterator
from dataclasses import dataclass
from functools import lru_cache
from typing import Final, Union
from black.mode import Mode
from black.nodes import (
CLOSING_BRACKETS,
OPENING_BRACKETS,
STANDALONE_COMMENT,
STATEMENT,
WHITESPACE,
conta... | 946 | 34,642 |
onnx | onnx/reference/ops/aionnxml/op_linear_regressor.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.aionnxml._op_run_aionnxml import OpRunAiOnnxMl
class LinearRegressor(OpRunAiOnnxMl):
def _run(
self, x, coefficients=None, intercepts=None, targe... | 27 | 863 |
metrics | src/torchmetrics/regression/log_cosh.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... | 143 | 5,440 |
confluent-kafka-python | tools/generate_kafka_error_stub_codes.py | .py | #!/usr/bin/env python3
"""
Generate KafkaError codes to be exposed in KafkaError stub class in cimpl.pyi
This script introspects the compiled C extension to extract all error codes
and generates the KafkaError class error codes
Usage:
python3 tools/generate_kafka_error_stub_codes.py # Prints the error co... | 139 | 4,660 |
beam | learning/tour-of-beam/learning-content/windowing/sliding-time-window/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... | 51 | 1,735 |
tqdm | tqdm/std.py | .py | """
Customisable progress bar decorator for iterators.
Includes a default `range` iterator printing to `stderr`.
Usage:
>>> from tqdm import trange, tqdm
>>> for i in trange(10):
... ...
"""
import sys
from collections import OrderedDict, defaultdict
from contextlib import contextmanager
from datetime import datet... | 1,534 | 58,074 |
pyfilesystem2 | fs/_bulk.py | .py | """
Implements a thread pool for parallel copying of files.
"""
from __future__ import unicode_literals
import typing
import threading
from six.moves.queue import Queue
from .copy import copy_file_internal, copy_modified_time
from .errors import BulkCopyFailed
from .tools import copy_file_data
if typing.TYPE_CHE... | 157 | 4,667 |
wagtail | wagtail/admin/compare.py | .py | import difflib
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils.encoding import force_str
from django.utils.html import escape, format_html, format_html_join
from django.utils.safestring import mark_safe
from django.utils.text import capfirst
from django.utils.tran... | 875 | 29,523 |
gunicorn | examples/http2_gevent/app.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
"""
Example WSGI application demonstrating HTTP/2 with gevent worker.
This application showcases various HTTP/2 features including:
- Basic request/response handling
- Large file transfers (streaming)
- Concurrent... | 135 | 4,162 |
beam | sdks/python/apache_beam/runners/direct/sdf_direct_runner_test.py | .py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | 275 | 8,833 |
scikit-bio | skbio/__init__.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.
# --------------------------------------------... | 101 | 2,592 |
hydra | hydra/conf/__init__.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
from omegaconf import MISSING
from hydra.core.config_store import ConfigStore
from hydra.types import RunMode
@dataclass
class HelpConf:
app_name: str = MI... | 181 | 5,183 |
pyro | pyro/optim/dct_adam.py | .py | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import math
from typing import Callable, Dict, Optional, Tuple
import torch
from torch.nn.functional import pad
from torch.optim.optimizer import Optimizer
from pyro.ops.tensor_utils import dct, idct, next_fast_len
def _transform_f... | 215 | 7,641 |
mlflow | mlflow/genai/judges/prompts/knowledge_retention.py | .py | # NB: User-facing name for the knowledge retention assessment.
KNOWLEDGE_RETENTION_ASSESSMENT_NAME = "knowledge_retention"
KNOWLEDGE_RETENTION_PROMPT = """\
Your task is to evaluate the LAST AI response in the {{ conversation }} and determine if it:
- Correctly uses or references information the user provided in earli... | 29 | 1,594 |
gunicorn | examples/dirty_example/test_stash_integration.py | .py | #!/usr/bin/env python3
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
"""
Integration tests for stash (shared state) functionality.
These tests verify that stash works correctly across multiple dirty workers,
demonstrating that state is truly shared.
Run with... | 227 | 6,713 |
openvino | tests/layer_tests/onnx_tests/test_sqrt.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
pytest.importorskip("openvino.tools.mo", reason="Ticket - 157136")
from common.layer_test_class import check_ir_version
from common.onnx_layer_test_class import OnnxRuntimeLayerTest, onnx_make_model
fro... | 191 | 6,589 |
pyfilesystem2 | fs/errors.py | .py | """Exception classes thrown by filesystem operations.
Errors relating to the underlying filesystem are translated in
to one of the following exceptions.
All Exception classes are derived from `~fs.errors.FSError`
which may be used as a catch-all filesystem exception.
"""
from __future__ import print_function, unico... | 377 | 10,109 |
textual | docs/examples/guide/screens/modes01.py | .py | from textual.app import App, ComposeResult
from textual.screen import Screen
from textual.widgets import Footer, Placeholder
class DashboardScreen(Screen):
def compose(self) -> ComposeResult:
yield Placeholder("Dashboard Screen")
yield Footer()
class SettingsScreen(Screen):
def compose(self)... | 43 | 1,022 |
eve | tests/endpoints.py | .py | # -*- coding: utf-8 -*-
import os
from datetime import datetime
from uuid import UUID
import pytest
import simplejson as json
from werkzeug.routing import BaseConverter
from eve import Eve
from eve.io.base import BaseJSONEncoder
from eve.io.mongo import Validator
from eve.utils import config
from . import TestBase, ... | 367 | 13,439 |
sqlmap | extra/esperanto/handler.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
from .engine import Esperanto
from .records import OracleUndecided
def _sanitize(s):
"""Escape C0/DEL/C1 control bytes in recovered DB content before it is logged - a stored... | 284 | 15,447 |
mlflow | mlflow/genai/label_schemas/validation.py | .py | """
Server-side validation for label schemas.
Type immutability post-create is enforced server-side (the field is
documented as immutable but the entity does not enforce it on its own).
The validation surface is intentionally split:
- :py:func:`validate_schema_for_create` is called from the store layer's
create pa... | 320 | 12,453 |
pyomo | pyomo/contrib/pynumero/linalg/tests/test_ma57.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... | 159 | 6,392 |
openvino | tests/layer_tests/tensorflow_tests/test_tf_BroadcastTo.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
from common.tf_layer_test_class import CommonTFLayerTest
# Testing BroadcastTo operation
# Documentation: https://www.tensorflow.org/api_docs/python/tf/raw_ops/BroadcastTo
class TestBroadcastTo(CommonT... | 51 | 1,771 |
coremltools | deps/pybind11/tests/test_smart_ptr.py | .py | from __future__ import annotations
import pytest
m = pytest.importorskip("pybind11_tests.smart_ptr")
from pybind11_tests import ConstructorStats # noqa: E402
def test_smart_ptr(capture):
# Object1
for i, o in enumerate(
[m.make_object_1(), m.make_object_2(), m.MyObject1(3)], start=1
):
... | 318 | 9,566 |
luigi | luigi/contrib/sge_runner.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... | 95 | 2,833 |
mlflow | tests/langgraph/sample_code/langgraph_with_autolog.py | .py | from dataclasses import dataclass
from langchain.tools import tool
from langgraph.graph import END, StateGraph
import mlflow
mlflow.langchain.autolog()
@dataclass
class OverallState:
name: str = "LangChain" # add whatever fields you need
@tool
def my_tool():
"""
Called as the very first node.
Si... | 34 | 778 |
sphinx | sphinx/ext/intersphinx/_shared.py | .py | """This module contains code shared between intersphinx modules."""
from __future__ import annotations
from typing import TYPE_CHECKING
from sphinx.util import logging
if TYPE_CHECKING:
from collections.abc import Sequence
from typing import Any, Final, NoReturn
from sphinx.environment import BuildEnvi... | 149 | 5,473 |
wandb | wandb/integration/sklearn/calculate/decision_boundaries.py | .py | from warnings import simplefilter
import wandb
# ignore all future warnings
simplefilter(action="ignore", category=FutureWarning)
def decision_boundaries(
decision_boundary_x,
decision_boundary_y,
decision_boundary_color,
train_x,
train_y,
train_color,
test_x,
test_y,
test_color,... | 41 | 1,087 |
pyomo | doc/OnlineDocs/src/data/import1.tab.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... | 23 | 864 |
saleor | saleor/graphql/page/tests/queries/pages_with_where/test_with_where_page_type.py | .py | import graphene
from ......page.models import Page, PageType
from .....tests.utils import get_graphql_content
from .shared import QUERY_PAGES_WITH_WHERE
def test_pages_with_where_page_type_eq(staff_api_client, page_type_list):
# given
page = Page.objects.first()
assigned_page_type = page.page_type
pa... | 54 | 1,703 |
django-cms | cms/utils/page.py | .py | import re
from django.urls import NoReverseMatch, reverse
from django.utils.encoding import force_str
from cms.constants import PAGE_USERNAME_MAX_LENGTH
from cms.utils import get_current_site, get_language_from_request
from cms.utils.conf import get_cms_setting
SUFFIX_REGEX = re.compile(r'^(.*)-(\d+)$')
def get_pa... | 147 | 4,561 |
cvxpy | cvxpy/atoms/prod.py | .py | """
Copyright 2018 Akshay Agrawal
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... | 163 | 5,199 |
onnxruntime | onnxruntime/python/tools/transformers/metrics.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 ... | 164 | 5,060 |
conda | conda/core/subdir_data.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Tools for managing a subdir's repodata.json."""
from __future__ import annotations
import pickle
from collections import UserList, defaultdict
from functools import partial
from itertools import chain
from logging import getLogger
from os.p... | 889 | 33,212 |
pdm | tests/fixtures/projects/demo-combined-extras/demo.py | .py | import os
print(os.name)
| 4 | 26 |
pyomo | doc/OnlineDocs/src/data/table1.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... | 19 | 749 |
probability | tensorflow_probability/python/bijectors/shifted_gompertz_cdf_test.py | .py | # Copyright 2020 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 71 | 2,798 |
pyomo | examples/pyomo/callbacks/sc_script.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... | 38 | 1,063 |
pdm | src/pdm/cli/commands/python.py | .py | from __future__ import annotations
import os
import shutil
import sys
import tempfile
from argparse import ArgumentParser
from pathlib import Path
from typing import TYPE_CHECKING, cast
from pdm.cli.commands.base import BaseCommand
from pdm.cli.options import verbose_option
from pdm.exceptions import InstallationErro... | 264 | 11,231 |
saleor | saleor/order/interface.py | .py | from dataclasses import dataclass
from prices import TaxedMoney
@dataclass
class OrderTaxedPricesData:
"""Store an order prices data with applied taxes.
'price_with_discounts' includes voucher discount and sale discount if any valid
exists.
'undiscounted_price' is a price without any sale and vouche... | 17 | 404 |
textual | tests/workers/test_worker_manager.py | .py | import asyncio
import time
from textual.app import App, ComposeResult
from textual.widget import Widget
from textual.worker import Worker, WorkerState
def test_worker_manager_init():
app = App()
assert isinstance(repr(app.workers), str)
assert not bool(app.workers)
assert len(app.workers) == 0
as... | 134 | 3,619 |
pyomo | pyomo/gdp/tests/test_transform_current_disjunctive_state.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... | 352 | 13,248 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.