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 |
|---|---|---|---|---|---|
jupytext | tests/unit/test_landing_page_notebook.py | .py | """
Tests for the landing page "Quarterly Sales" example notebook.
Verifies that:
1. The notebook executes without errors.
2. Conversion to each text format matches the snapshot files in data/landing_page/.
To update snapshots after a format change, run:
UPDATE_SNAPSHOTS=1 pytest tests/unit/test_landing_page_not... | 118 | 4,028 |
textual | docs/blog/images/gen_inspect.py | .py | from rich import inspect
from rich.console import Console
c = Console(record=True, width=110)
f = open("foo.txt", "w")
inspect(f, console=c)
c.save_svg("inspect1.svg")
inspect(f, console=c, methods=True)
c.save_svg("inspect2.svg")
inspect(f, console=c, methods=True, help=True)
c.save_svg("inspect3.svg")
| 18 | 312 |
textual | src/textual/_extrema.py | .py | from __future__ import annotations
from fractions import Fraction
from typing import NamedTuple
from textual.geometry import Size
class Extrema(NamedTuple):
"""Specifies minimum and maximum dimensions."""
min_width: Fraction | None = None
max_width: Fraction | None = None
min_height: Fraction | Non... | 65 | 1,662 |
ipython | IPython/lib/demo.py | .py | """Module for interactive demos using IPython.
This module implements a few classes for running Python scripts interactively
in IPython for demonstrations. With very simple markup (a few tags in
comments), you can control points where the script stops executing and returns
control to IPython.
Provided classes
-----... | 672 | 24,451 |
coremltools | coremltools/converters/mil/frontend/torch/exir_utils.py | .py | # Copyright (c) 2023, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from typing import Dict, List, Tuple
import sympy
import torch
from coremltools import _logger as ... | 372 | 14,280 |
pyomo | pyomo/contrib/piecewise/tests/test_piecewise_linear_function.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... | 667 | 22,914 |
pyomo | pyomo/core/tests/unit/test_matrix_constraint.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... | 97 | 3,774 |
pyomo | examples/pyomo/suffixes/gurobi_ampl_example.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... | 133 | 4,644 |
textual | docs/examples/guide/layout/combining_layouts.py | .py | from textual.app import App, ComposeResult
from textual.containers import Container, Horizontal, VerticalScroll
from textual.widgets import Header, Static
class CombiningLayoutsExample(App):
CSS_PATH = "combining_layouts.tcss"
def compose(self) -> ComposeResult:
yield Header()
with Container(... | 31 | 1,050 |
gunicorn | tests/requests/invalid/rfc9112_target_asterisk_non_options_01.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
# RFC 9112 section 3.2.4: asterisk-form ("*") only targets the server itself
# and is only valid with the OPTIONS method. Any other method must be
# rejected as an ill-formed request-line.
from gunicorn.http.errors... | 10 | 376 |
openvino | tests/layer_tests/tensorflow_lite_tests/test_tfl_TopKV2.py | .py | import pytest
import tensorflow as tf
from common.tflite_layer_test_class import TFLiteLayerTest
test_params = [
{'shape': [2], 'k': 2, 'sorted': True},
{'shape': [2, 3], 'k': 1, 'sorted': False},
{'shape': [2, 3, 5], 'k': 2, 'sorted': True},
{'shape': [2, 3, 5, 10], 'k': 9, 'sorted': False},
]
clas... | 34 | 1,191 |
beam | sdks/python/apache_beam/metrics/execution_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... | 123 | 4,966 |
saleor | saleor/graphql/core/federation/entities.py | .py | from typing import TypeVar
import graphene
federated_entities: dict[str, graphene.ObjectType] = {}
T = TypeVar("T", bound=graphene.ObjectType)
def federated_entity(key_fields: str):
def federate_entity(graphql_type: T) -> T:
# Add entity to registry
federated_entities[graphql_type.__name__] = ... | 30 | 729 |
sphinx | sphinx/util/parsing.py | .py | """Docutils utility functions for parsing text."""
from __future__ import annotations
import contextlib
from typing import TYPE_CHECKING
from docutils.nodes import Element
from docutils.statemachine import StringList, string2lines
if TYPE_CHECKING:
from collections.abc import Iterator
from docutils.nodes i... | 100 | 3,539 |
coremltools | coremltools/converters/mil/mil/passes/tests/test_symbol_transform.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 itertools
import numpy as np
import pytest
from coremltools.converters.mil.mil import Build... | 186 | 7,044 |
metrics | src/torchmetrics/functional/clustering/fowlkes_mallows_index.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... | 78 | 2,477 |
probability | tensorflow_probability/python/mcmc/simple_step_size_adaptation_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... | 596 | 21,178 |
astropy | astropy/tests/tests/test_run_tests.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
# test helper.run_tests function
from astropy import test as run_tests
from astropy.utils.exceptions import AstropyDeprecationWarning
# run_tests should raise ValueError when asked to run on a module it can't find
def test_module_not_found... | 25 | 770 |
pyomo | pyomo/contrib/cp/scheduling_expr/sequence_expressions.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... | 172 | 5,517 |
wagtail | wagtail/tests/test_search_fields.py | .py | from contextlib import contextmanager
from django.core import checks
from django.test import TestCase
from wagtail.test.testapp.models import (
TaggedChildPage,
TaggedGrandchildPage,
TaggedPage,
)
from wagtail.test.utils import Page
@contextmanager
def patch_search_fields(model, new_search_fields):
... | 70 | 2,292 |
hydra | hydra/initialize.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import os
from typing import Any, Optional
from hydra import version
from hydra._internal.hydra import Hydra
from hydra._internal.utils import (
create_config_search_path,
detect_calling_file_or_module_from_stack_frame,
dete... | 155 | 5,233 |
openvino | src/bindings/python/src/openvino/preprocess/torchvision/torchvision_preprocessing.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: disable-error-code="no-redef"
import numbers
import logging
import copy
import numpy as np
from abc import ABCMeta, abstractmethod
from functools import singledispatch
from typing import Any, Union
from c... | 362 | 13,861 |
kombu | conftest.py | .py | from __future__ import annotations
import pytest
def pytest_addoption(parser):
parser.addoption(
"-E",
action="append",
metavar="NAME",
help="only run tests matching the environment NAME.",
)
def pytest_configure(config):
# register an additional marker
config.addini... | 36 | 1,063 |
openvino | src/bindings/python/tests/test_transformations/test_compression.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
from openvino.op import Parameter, Constant
from openvino.opset13 import add, multiply
import openvino as ov
from tests.utils.helpers import create_filenames_for_ir
def make_constant(values, ... | 114 | 4,745 |
wagtail | wagtail/test/streamfield_migrations/factories.py | .py | import factory
from factory.django import DjangoModelFactory
from wagtail.test.utils import wagtail_factories
from . import models
class SimpleStructBlockFactory(wagtail_factories.StructBlockFactory):
char1 = "Char Block 1"
char2 = "Char Block 2"
class Meta:
model = models.SimpleStructBlock
c... | 72 | 2,270 |
astropy | astropy/io/fits/hdu/__init__.py | .py | # Licensed under a 3-clause BSD style license - see PYFITS.rst
from .base import BITPIX2DTYPE, DELAYED, DTYPE2BITPIX, register_hdu, unregister_hdu
from .compressed import CompImageHDU
from .groups import Group, GroupData, GroupsHDU
from .hdulist import HDUList
from .image import ImageHDU, PrimaryHDU
from .nonstandard ... | 30 | 710 |
probability | tensorflow_probability/python/internal/distribute_lib_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... | 884 | 30,947 |
deap | tests/test_algorithms.py | .py | # This file is part of DEAP.
#
# DEAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# DEAP is distributed ... | 244 | 8,745 |
pyro | tests/distributions/test_omt_mvn.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
import torch
from pyro.distributions import (
AVFMultivariateNormal,
MultivariateNormal,
OMTMultivariateNormal,
)
from tests.common import assert_equal
def analytic_grad(L11=1.0, L22=... | 129 | 4,649 |
conda | conda/cli/main_info.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""CLI implementation for `conda info`.
Display information about current conda installation.
"""
from __future__ import annotations
import os
import re
import sys
from argparse import SUPPRESS
from functools import cached_property
from loggi... | 658 | 20,536 |
pyfilesystem2 | tests/test_archives.py | .py | # -*- encoding: UTF-8
from __future__ import unicode_literals
import os
import stat
from six import text_type
from fs import errors, walk
from fs.enums import ResourceType
from fs.opener import open_fs
from fs.test import UNICODE_TEXT
class ArchiveTestCases(object):
def make_source_fs(self):
return open... | 137 | 4,451 |
jupytext | tests/data/notebooks/outputs/ipynb_to_sphinx/sample_rise_notebook_66.py | .py | # ---
# jupyter:
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
"""
A markdown cell
"""
1+1
###############################################################################
# Markdown cell two
| 17 | 242 |
astropy | astropy/modeling/functional_models.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Mathematical models."""
# pylint: disable=line-too-long, too-many-lines, too-many-arguments, invalid-name
import warnings
import numpy as np
from astropy import units as u
from astropy.units import Quantity, UnitsError
from astropy.utils.compat impo... | 3,926 | 121,081 |
conda | tests/shards/test_shards_subset.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import concurrent.futures
import json
import queue
import random
import threading
import time
import urllib.parse
from contextlib import suppress
from pathlib import Path
from queue import Empty, SimpleQueue
f... | 1,350 | 45,258 |
wandb | tests/system_tests/test_functional/console_capture/infinite_loop.py | .py | """Fails if tasks started by console callbacks invoke more callbacks."""
from __future__ import annotations
import asyncio
import sys
from wandb.sdk.lib import asyncio_manager, console_capture
def _info(msg: str) -> None:
sys.stderr.write(msg + "\n")
class _Tester:
def __init__(self) -> None:
sel... | 69 | 1,991 |
hydra | tools/release/release.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
from dataclasses import dataclass
from enum import Enum
from functools import lru_cache
from pathlib import Path
from typing import Dict, List,... | 777 | 25,499 |
openvino | tests/layer_tests/pytorch_tests/test_outer.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
from pytorch_layer_test_class import PytorchLayerTest, skip_if_export
class TestOuter(PytorchLayerTest):
def _prepare_input(self, x_shape, y_shape, x_dtype, y_dtype, out=False):
import numpy as np
x =... | 57 | 2,211 |
coremltools | deps/pybind11/tests/test_custom_type_setup.py | .py | from __future__ import annotations
import gc
import weakref
import pytest
import env # noqa: F401
from pybind11_tests import custom_type_setup as m
@pytest.fixture()
def gc_tester():
"""Tests that an object is garbage collected.
Assumes that any unreferenced objects are fully collected after calling
... | 51 | 1,127 |
clearml | examples/frameworks/ignite/cifar_ignite.py | .py | from pathlib import Path
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from ignite.contrib.handlers import TensorboardLogger
from ignite.engine import Eve... | 192 | 7,140 |
pyro | pyro/infer/traceenum_elbo.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import queue
import warnings
import weakref
from collections import OrderedDict
import torch
from opt_einsum import shared_intermediates
import pyro
import pyro.distributions as dist
import pyro.ops.jit
import pyro.poutine as pou... | 570 | 23,531 |
gunicorn | examples/streaming_chat/test_streaming.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
"""Integration tests for the streaming chat example."""
import json
import os
import requests
def test_health_endpoint():
"""Test the health check endpoint."""
base_url = os.environ.get("STREAMING_CHAT_U... | 154 | 4,619 |
textual | docs/examples/guide/input/key02.py | .py | from textual import events
from textual.app import App, ComposeResult
from textual.widgets import RichLog
class InputApp(App):
"""App to display key events."""
def compose(self) -> ComposeResult:
yield RichLog()
def on_key(self, event: events.Key) -> None:
self.query_one(RichLog).write(e... | 22 | 444 |
jupytext | src/jupytext/__init__.py | .py | """Read and write Jupyter notebooks as text files"""
from .formats import NOTEBOOK_EXTENSIONS, get_format_implementation, guess_format
from .jupytext import read, reads, write, writes
from .reraise import reraise
from .version import __version__
try:
from .sync_contentsmanager import build_sync_jupytext_contents_... | 42 | 1,223 |
textual | tests/test_data_table.py | .py | from __future__ import annotations
import pytest
from rich.panel import Panel
from rich.text import Text
from textual._wait import wait_for_idle
from textual.actions import SkipAction
from textual.app import App, ComposeResult, RenderableType
from textual.coordinate import Coordinate
from textual.geometry import Offs... | 1,492 | 52,375 |
hydra | tools/configen/example/config/configen/samples/my_module.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
@dataclass
class User... | 25 | 590 |
saleor | saleor/tests/e2e/shop/utils/preparing_shop.py | .py | from ...channel.utils import create_channel
from ...shipping_zone.utils import (
create_shipping_method,
create_shipping_method_channel_listing,
create_shipping_zone,
)
from ...taxes.utils import (
create_tax_class,
get_tax_configurations,
update_tax_class,
update_tax_configuration,
)
from .... | 173 | 6,001 |
wandb | tests/system_tests/test_core/test_wandb_run.py | .py | import math
import os
import pickle
import sys
from pathlib import Path
import numpy as np
import PIL.Image
import pytest
import wandb
from wandb.errors import UsageError
from tests.fixtures.mock_wandb_log import MockWandbLog
from tests.fixtures.wandb_backend_spy import WandbBackendSpy
def test_log_nan_inf(wandb_ba... | 408 | 12,799 |
kombu | kombu/transport/SQS/SNS.py | .py | """Amazon SNS fanout support for the AWS SQS transport module for Kombu.
This module provides a `SNS` class that can be used to manage SNS topics and subscriptions.
It's primarily used to provide fanout support via AWS Simple Notification Service (SNS)
topics and subscriptions. The module also provides methods for han... | 708 | 30,013 |
cvxpy | cvxpy/atoms/errormsg.py | .py | SECOND_ARG_SHOULD_NOT_BE_EXPRESSION_ERROR_MESSAGE = """
The second argument has type cvxpy.Expression. However, that is not allowed.
Most likely, you want to call this atom by using cvxpy.hstack to combine the
two arguments into a vector.
"""
| 6 | 243 |
mlflow | mlflow/data/dataset_source_registry.py | .py | import warnings
from typing import Any
from mlflow.data.dataset_source import DatasetSource
from mlflow.data.http_dataset_source import HTTPDatasetSource
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import RESOURCE_DOES_NOT_EXIST
from mlflow.utils.plugins import get_entry_points
cl... | 234 | 8,743 |
mkdocs | mkdocs/tests/build_tests.py | .py | #!/usr/bin/env python
from __future__ import annotations
import contextlib
import io
import os.path
import re
import textwrap
import unittest
from pathlib import Path
from typing import TYPE_CHECKING
from unittest import mock
import markdown.preprocessors
from mkdocs.commands import build
from mkdocs.config import b... | 959 | 40,269 |
pyfilesystem2 | fs/subfs.py | .py | """Manage a directory in a *parent* filesystem.
"""
from __future__ import print_function, unicode_literals
import typing
import six
from .path import abspath, join, normpath, relpath
from .wrapfs import WrapFS
if typing.TYPE_CHECKING:
from typing import Text, Tuple
from .base import FS # noqa: F401
_F... | 64 | 1,654 |
confluent-kafka-python | src/confluent_kafka/aio/_common.py | .py | # Copyright 2025 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... | 87 | 2,889 |
metrics | tests/unittests/clustering/test_adjusted_mutual_info_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... | 102 | 4,118 |
sqlmap | extra/kerberos/spnego.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
# Minimal GSS-API / SPNEGO (RFC 2743, RFC 4178) wrapping of a Kerberos AP-REQ into the token carried
# by the HTTP "Authorization: Negotiate <base64>" header. Only the initiator's... | 34 | 1,401 |
astropy | astropy/visualization/wcsaxes/_auto.py | .py | from itertools import permutations
import numpy as np
__all__ = ["auto_assign_coord_positions"]
def auto_assign_coord_positions(ax):
"""
Given a ``WCSAxes`` instance, automatically update any dynamic tick, tick
label and axis label positions.
This function operates in-place on the axes and assumes ... | 124 | 5,134 |
beam | sdks/python/apache_beam/examples/cookbook/bigquery_side_input_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... | 66 | 2,166 |
onnxruntime | onnxruntime/test/testdata/transform/concat_graph_gen.py | .py | import numpy as np
import onnx
from onnx import TensorProto, helper
def GenerateModel(model_name): # noqa: N802
nodes = [
helper.make_node("Gather", ["embed_weights", "input_1"], ["gather_out"], "gather"),
helper.make_node("Add", ["gather_out", "add_q_weight"], ["add_q_out"], "add_q"),
he... | 88 | 2,643 |
tablib | src/tablib/formats/_ods.py | .py | """ Tablib - ODF Support.
"""
__lazy_modules__ = {"datetime", "io", "numbers"}
import datetime as dt
import numbers
from io import BytesIO
from odf import number, opendocument, style, table, text
import tablib
bold = style.Style(name="bold", family="paragraph")
bold.addElement(style.TextProperties(
fontweight=... | 258 | 8,793 |
mamba | micromamba/tests/conftest.py | .py | import copy
import os
import pathlib
import platform
from typing import Any, Optional
from collections.abc import Generator, Mapping
import pytest
from . import helpers
####################
# Config options #
####################
def pytest_addoption(parser):
"""Add command line argument to pytest."""
pa... | 195 | 6,400 |
pdm | tests/models/test_candidates.py | .py | from __future__ import annotations
import shutil
import pytest
from unearth import Link
from pdm.exceptions import RequirementError
from pdm.models.candidates import Candidate
from pdm.models.requirements import Requirement, parse_requirement
from pdm.models.specifiers import PySpecSet
from pdm.utils import is_path_... | 320 | 12,931 |
pyomo | doc/OnlineDocs/src/data/set2a.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... | 21 | 735 |
black | tests/test_schema.py | .py | import importlib.metadata
def test_schema_entrypoint() -> None:
(black_ep,) = importlib.metadata.entry_points(
group="validate_pyproject.tool_schema", name="black"
)
black_fn = black_ep.load()
schema = black_fn()
assert schema == black_fn("black")
assert schema["properties"]["line-len... | 13 | 347 |
gunicorn | gunicorn/workers/ggevent.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
import sys
from datetime import datetime
from functools import partial
import time
try:
import gevent
except ImportError:
raise RuntimeError("gevent worker requires gevent 24.10.1 or higher")
els... | 191 | 5,885 |
voila | voila/shutdown_kernel_handler.py | .py | import tornado
from jupyter_server.base.handlers import APIHandler
from jupyter_core.utils import ensure_async
class VoilaShutdownKernelHandler(APIHandler):
"""Handler to shut down kernel on page's `beforeunload` event."""
@tornado.web.authenticated
async def post(self, kernel_id):
await ensure_a... | 14 | 424 |
black | tests/data/cases/stub.py | .py | # flags: --pyi
X: int
def f(): ...
class D:
...
class C:
...
class B:
this_lack_of_newline_should_be_kept: int
def b(self) -> None: ...
but_this_newline_should_also_be_kept: int
class A:
attr: int
attr2: str
def f(self) -> int:
...
def g(self) -> str: ...
def g(... | 153 | 2,281 |
openvino | tests/layer_tests/ovc_python_api_tests/test_tf_unsupported_ops.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import re
import tempfile
import unittest
from pathlib import Path
import pytest
import tensorflow as tf
from openvino.frontend import OpConversionFailure
from common import constants
from common.utils.tf_utils import save_to_pb
@tf.... | 99 | 3,757 |
returns | tests/test_io/test_io_container/test_io_pickle.py | .py | from returns.io import IO
def test_io_pickle():
"""Tests how pickle protocol works for containers."""
assert IO(1).__getstate__() == {'container_value': 1}
def test_io_pickle_restore():
"""Ensures that object can be restored."""
container = IO(2)
container.__setstate__({'container_value': 1})
... | 14 | 348 |
mlflow | tests/db/test_mcp_server_registry.py | .py | from pathlib import Path
import pytest
from mlflow.entities.mcp_server import MCPStatus
from mlflow.environment_variables import MLFLOW_TRACKING_URI
from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore
pytestmark = pytest.mark.notrackingurimock
@pytest.fixture
def store(tmp_path: Path):
artifact_... | 161 | 5,343 |
openvino | src/frontends/tensorflow_lite/tests/test_models/gen_scripts/generate_densify.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import sys
import tensorflow as tf
# Create the graph and model
class SampleGraph(tf.Module):
def __init__(self):
super(SampleGraph, self).__init__()
self.var1 = tf.constant([[[[0,0,1,0],[0,0,0,0],[0,2,1,0]],[[0,0,0... | 35 | 1,287 |
structlog | src/structlog/testing.py | .py | # SPDX-License-Identifier: MIT OR Apache-2.0
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the MIT License. See the LICENSE file in the root of this
# repository for complete details.
"""
Helpers to test your application's logging behavior.
.. versionadded:: 20.1.0
See :doc:... | 223 | 5,772 |
conda | conda/env/specs/cep_24.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Define cep-0024 compliant YAML spec."""
from __future__ import annotations
from logging import getLogger
from typing import TYPE_CHECKING
from ...common.io import dashlist
from ...common.serialize import yaml
from ...exceptions import Cond... | 59 | 1,643 |
jupytext | tests/external/pre_commit/test_pre_commit_1_sync.py | .py | import shutil
import pytest
from git.exc import HookExecutionError
from nbformat.v4.nbbase import new_markdown_cell
from pre_commit.main import main as pre_commit
from jupytext import read, write
from jupytext.cli import jupytext
def test_pre_commit_hook_sync(
tmpdir,
cwd_tmpdir,
tmp_repo,
jupytext_... | 109 | 3,161 |
gunicorn | docs/macros.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from importlib import import_module
def define_env(env):
"""Register template variables for MkDocs macros."""
gunicorn = import_module("gunicorn")
env.variables.update(
release=gunicorn.__versi... | 16 | 508 |
coremltools | coremltools/models/neural_network/update_optimizer_utils.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
"""
Neural Network optimizer utilities.
"""
class AdamParams:
"""
Adam - A Method for Stochast... | 192 | 4,775 |
openvino | src/bindings/python/src/openvino/utils/node_factory.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from functools import singledispatchmethod
from typing import Any, Optional, Union
from pathlib import Path
from openvino._pyopenvino import NodeFactory as _NodeFactory
from openvino import Node, Output, Extens... | 135 | 5,199 |
beam | sdks/python/apache_beam/runners/interactive/extensions/apache-beam-jupyterlab-sidepanel/apache_beam_jupyterlab_sidepanel/_version.py | .py | # isort: skip_file
# 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
# ... | 19 | 859 |
textual | docs/examples/guide/widgets/fizzbuzz02.py | .py | from rich.table import Table
from textual.app import App, ComposeResult
from textual.geometry import Size
from textual.widgets import Static
class FizzBuzz(Static):
def on_mount(self) -> None:
table = Table("Number", "Fizz?", "Buzz?", expand=True)
for n in range(1, 16):
fizz = not n %... | 36 | 848 |
textual | tests/snapshot_tests/snapshot_apps/data_table_row_cursor.py | .py | import csv
import io
from textual.app import App, ComposeResult
from textual.widgets import DataTable
CSV = """lane,swimmer,country,time
4,Joseph Schooling,Singapore,50.39
2,Michael Phelps,United States,51.14
5,Chad le Clos,South Africa,51.14
6,László Cseh,Hungary,51.14
3,Li Zhuhao,China,51.26
8,Mehdy Metella,France,... | 37 | 880 |
pymc | pymc/pytensorf.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... | 1,129 | 37,470 |
biopython | Bio/SeqIO/AceIO.py | .py | # Copyright 2008-2015 by Peter Cock. 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.
"""Bio.SeqIO support fo... | 124 | 4,830 |
wandb | tests/unit_tests/test_kfp.py | .py | """Unit tests for the Kubeflow Pipelines (kfp) v2 integration."""
import inspect
import json
import os
from typing import NamedTuple
from unittest.mock import MagicMock, patch
from kfp import dsl
from kfp.compiler import Compiler
from kfp.dsl import Artifact, Dataset, Input, InputPath, Output
from wandb.integration.k... | 762 | 22,566 |
gunicorn | examples/longpoll.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import sys
import time
class TestIter:
def __iter__(self):
lines = [b'line 1\n', b'line 2\n']
for line in lines:
yield line
time.sleep(20)
def app(environ, start_resp... | 28 | 707 |
wandb | wandb/sdk/launch/environment/aws_environment.py | .py | """Implements the AWS environment."""
from __future__ import annotations
import logging
import os
from wandb.sdk.launch.errors import LaunchError
from wandb.util import get_module
from ..utils import ARN_PARTITION_RE, S3_URI_RE, event_loop_thread_exec
from .abstract import AbstractEnvironment
boto3 = get_module(
... | 324 | 12,515 |
saleor | saleor/graphql/checkout/tests/mutations/test_checkout_email_update.py | .py | from unittest.mock import ANY, patch
import pytest
from django.test import override_settings
from django.utils import timezone
from freezegun import freeze_time
from .....checkout.actions import call_checkout_event
from .....checkout.error_codes import CheckoutErrorCode
from .....core.models import EventDelivery
from... | 284 | 9,437 |
textual | src/textual/_layout_resolve.py | .py | from __future__ import annotations
from fractions import Fraction
from typing import Sequence, cast
from typing_extensions import Protocol
class EdgeProtocol(Protocol):
"""Any object that defines an edge (such as Layout)."""
# Size of edge in cells, or None for no fixed size
size: int | None
# Port... | 86 | 3,274 |
pyomo | pyomo/solvers/plugins/solvers/mosek_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... | 1,288 | 54,697 |
lemur | lemur/roles/models.py | .py | """
.. module: lemur.roles.models
:platform: unix
:synopsis: This module contains all of the models need to create a role within Lemur
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
... | 56 | 1,652 |
hatch | backend/src/hatchling/utils/constants.py | .py | DEFAULT_BUILD_SCRIPT = "hatch_build.py"
DEFAULT_CONFIG_FILE = "hatch.toml"
class VersionEnvVars:
VALIDATE_BUMP = "HATCH_VERSION_VALIDATE_BUMP"
| 7 | 149 |
django-cms | cms/test_utils/runners.py | .py | import operator
import time
from django.test.simple import DjangoTestSuiteRunner
from django.utils.encoding import force_str
from django.utils.unittest import TestSuite
TIMINGS = {}
def time_it(func):
def _inner(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
end = time.time(... | 42 | 1,095 |
wagtail | wagtail/users/tests/test_admin_views.py | .py | import unittest.mock
from django.apps import apps
from django.conf import settings
from django.contrib.admin.utils import quote
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions ... | 3,071 | 122,984 |
mlflow | mlflow/genai/optimize/optimizers/gepa_optimizer.py | .py | import json
import logging
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING, Any
import mlflow
from mlflow.exceptions import MlflowException
from mlflow.genai.optimize.optimizers.base import BasePromptOptimizer, _EvalFunc
from mlflow.genai.optimize.types import EvaluationResultRecord, PromptOp... | 418 | 17,149 |
beam | sdks/python/apache_beam/transforms/deduplicate.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... | 132 | 5,132 |
pyomo | pyomo/opt/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... | 13 | 611 |
metrics | src/torchmetrics/clustering/cluster_accuracy.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... | 149 | 6,034 |
biopython | Bio/Phylo/PAML/_paml.py | .py | # Copyright (C) 2011 by Brandon Invergo (b.invergo@gmail.com)
#
# 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.
"""Base class for t... | 134 | 5,118 |
beam | learning/katas/python/Core Transforms/Partition/Partition/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... | 48 | 1,658 |
onnx | onnx/reference/ops/op_leaky_relu.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from typing import TYPE_CHECKING
from onnx.reference.ops._op import OpRunUnaryNum
if TYPE_CHECKING:
import numpy as np
def _leaky_relu(x: np.ndarray, alpha: float) -> np.ndarray:
sign = (x > ... | 24 | 569 |
deap | examples/coev/coop_niche.py | .py | # This file is part of DEAP.
#
# DEAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# DEAP is distributed ... | 102 | 3,365 |
probability | tensorflow_probability/python/math/psd_kernels/internal/util.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... | 318 | 13,176 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.