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
textual
tests/snapshot_tests/snapshot_apps/button_markup.py
.py
from textual.app import App, ComposeResult from textual.widgets import Button class ButtonsWithMarkupApp(App): def compose(self) -> ComposeResult: yield Button("[italic red]Focused[/] Button") yield Button("[italic red]Blurred[/] Button") yield Button("[italic red]Disabled[/] Button", disa...
15
407
mlflow
mlflow/genai/judges/tools/base.py
.py
""" Base classes for MLflow GenAI tools that can be used by judges. This module provides the foundational interfaces for tools that judges can use to enhance their evaluation capabilities. """ from abc import ABC, abstractmethod from typing import Any from mlflow.entities.trace import Trace from mlflow.types.llm imp...
54
1,418
pyomo
examples/pyomo/amplbook2/econ2min.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...
81
2,072
cvxpy
cvxpy/atoms/affine/affine_atom.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...
181
6,231
gunicorn
tests/test_systemd.py
.py
# # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. from contextlib import contextmanager import os from unittest import mock import pytest from gunicorn import systemd @contextmanager def check_environ(unset=True): """ A context manager that asserts pos...
61
2,027
onnx
onnx/reference/ops/op_dropout.py
.py
# Copyright (c) ONNX Project Contributors # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import numpy as np from numpy.random import RandomState from onnx.reference.op_run import OpRun def _dropout( X: np.ndarray, drop_probability: float = 0.5, seed: int | None = None, tra...
67
1,779
mlflow
mlflow/store/db_migrations/versions/2d6e25af4d3e_increase_max_param_val_length.py
.py
"""increase max param val length from 500 to 8000 Create Date: 2023-09-25 13:59:04.231744 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "2d6e25af4d3e" down_revision = "7f2a7d5fae7d" branch_labels = None depends_on = None def upgrade(): with op.batch_alt...
32
731
saleor
saleor/core/anonymize.py
.py
def obfuscate_email(value): string_rep = str(value) if "@" not in str(string_rep): return obfuscate_string(string_rep) local_part, domain = str(string_rep).split("@") return f"{local_part[:1]}...@{domain}" def obfuscate_string(value, phone=False): if not value: return "" strin...
29
960
conda
conda/env/specs/yaml_file.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause """Define YAML spec.""" from __future__ import annotations from logging import getLogger from typing import TYPE_CHECKING from ...common.serialize import yaml from ...deprecations import deprecated from ...exceptions import CondaValueError, P...
75
2,364
pymc
pymc/model/__init__.py
.py
# Copyright 2024 - present The PyMC Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
19
711
onnxruntime
onnxruntime/python/tools/transformers/onnx_model_mmdit.py
.py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -------------------------------------------------------------------------- import logging from fusion_layernorm import FusionLayerNormalization f...
120
4,459
onnx
onnx/backend/test/case/node/constantofshape.py
.py
# Copyright (c) ONNX Project Contributors # # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import numpy as np import onnx from onnx.backend.test.case.base import Base from onnx.backend.test.case.node import expect class ConstantOfShape(Base): @staticmethod def export_float_ones() -...
65
1,872
readthedocs.org
readthedocs/config/config.py
.py
"""Build configuration for rtd.""" import copy import datetime import os import re from contextlib import contextmanager from functools import lru_cache import pytz from django.conf import settings from pydantic import BaseModel from readthedocs.config.utils import list_to_dict from readthedocs.core.utils.filesystem...
1,106
40,174
jupytext
src/jupytext/pairs.py
.py
"""Functions to read or write paired notebooks""" from collections import namedtuple from .formats import long_form_multiple_formats, long_form_one_format from .paired_paths import paired_paths NotebookFile = namedtuple("notebook_file", "path fmt timestamp") class PairedFilesDiffer(ValueError): """An error whe...
56
2,226
onnx
onnx/reference/ops/op_round.py
.py
# Copyright (c) ONNX Project Contributors # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import numpy as np from onnx.reference.ops._op import OpRunUnaryNum class Round(OpRunUnaryNum): def _run(self, x): return (np.round(x).astype(x.dtype),)
14
285
coremltools
coremltools/test/ml_program/experimental/test_debugging_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 import re from typing import Callable import numpy as np import pytest import coremltools as ct fro...
367
14,511
pymc
tests/logprob/test_order.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...
452
16,104
readthedocs.org
readthedocs/config/tests/test_parser.py
.py
from io import StringIO from pytest import raises from readthedocs.config.parser import ParseError, parse def test_parse_empty_config_file(): buf = StringIO("") with raises(ParseError): parse(buf) def test_parse_invalid_yaml(): buf = StringIO("- - !asdf") with raises(ParseError): p...
70
1,305
textual
src/textual/renderables/_blend_colors.py
.py
from __future__ import annotations from rich.color import Color def blend_colors(color1: Color, color2: Color, ratio: float) -> Color: """Given two RGB colors, return a color that sits some distance between them in RGB color space. Args: color1: The first color. color2: The second color....
28
732
jupytext
tests/functional/simple_notebooks/test_ipynb_to_rmd.py
.py
import nbformat import jupytext from jupytext.compare import compare_notebooks def test_identity_source_write_read(ipynb_py_R_jl_file): """Test that writing the notebook with rmd, and read again, is the same as removing outputs""" with open(ipynb_py_R_jl_file) as fp: nb1 = nbformat.read(fp, as_v...
18
446
textual
tests/test_suspend.py
.py
import sys import pytest from textual.app import App, SuspendNotSupported from textual.drivers.headless_driver import HeadlessDriver async def test_suspend_not_supported() -> None: """Suspending when not supported should raise an error.""" async with App().run_test() as pilot: # Pilot uses the headl...
64
2,119
saleor
saleor/graphql/giftcard/tests/mutations/test_gift_card_activate.py
.py
import datetime import json from unittest import mock import graphene from django.utils.functional import SimpleLazyObject from freezegun import freeze_time from .....core.utils.json_serializer import CustomJsonEncoder from .....giftcard import GiftCardEvents from .....giftcard.error_codes import GiftCardErrorCode fr...
251
7,137
probability
tensorflow_probability/python/experimental/mcmc/preconditioning_utils.py
.py
# Copyright 2021 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...
166
7,472
sphinx
sphinx/testing/restructuredtext.py
.py
from __future__ import annotations from typing import TYPE_CHECKING from sphinx.parsers import RSTParser from sphinx.util.docutils import _parse_str_to_doctree if TYPE_CHECKING: from docutils import nodes from sphinx.application import Sphinx def parse(app: Sphinx, text: str, docname: str = 'index') -> no...
47
1,157
wandb
wandb/sdk/artifacts/_validators.py
.py
"""Internal validation utilities that are specific to artifacts.""" from __future__ import annotations import json import os import re from collections.abc import Callable from dataclasses import dataclass, field, replace from functools import singledispatch, wraps from pathlib import PureWindowsPath from typing impo...
373
12,993
wagtail
wagtail/api/v3/tests/test_page_revisions.py
.py
from django.contrib.auth.models import Group, Permission from django.test import TestCase from django.urls import reverse from wagtail.api.v3.tests.base import TestV3Base from wagtail.models import GroupPagePermission from wagtail.test.utils import Page, WagtailTestUtils class TestV3PageRevisionsBase(TestV3Base, Wag...
307
11,349
astropy
astropy/coordinates/builtin_frames/galactic.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst from astropy import units as u from astropy.coordinates import Angle from astropy.coordinates import representation as r from astropy.coordinates.baseframe import ( BaseCoordinateFrame, RepresentationMapping, base_doc, ) from astropy.utils.dec...
102
4,082
saleor
saleor/graphql/discount/mutations/voucher/voucher_code_bulk_delete.py
.py
import graphene from .....core.tracing import traced_atomic_transaction from .....discount import models from .....permission.enums import DiscountPermissions from .....webhook.event_types import WebhookEventAsyncType from ....core.doc_category import DOC_CATEGORY_DISCOUNTS from ....core.enums import VoucherCodeBulkDe...
101
3,304
biopython
Bio/PDB/ResidueDepth.py
.py
# Copyright (C) 2002, Thomas Hamelryck (thamelry@binf.ku.dk) # Copyright (C) 2017, Joao Rodrigues (j.p.g.l.m.rodrigues@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 shoul...
618
22,252
kombu
kombu/utils/imports.py
.py
"""Import related utilities.""" from __future__ import annotations import importlib import sys from kombu.exceptions import reraise def symbol_by_name(name, aliases=None, imp=None, package=None, sep='.', default=None, **kwargs): """Get symbol by qualified name. The name should be the fu...
69
2,089
wagtail
wagtail/locks.py
.py
import swapper from django.conf import settings from django.utils.html import format_html from django.utils.safestring import mark_safe from django.utils.text import capfirst from django.utils.translation import gettext as _ from wagtail.admin.utils import get_latest_str, get_user_display_name from wagtail.utils.times...
265
10,037
conda
tests/models/test_records.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause import pytest from conda.base.context import context from conda.core.prefix_data import PrefixData from conda.models.channel import Channel from conda.models.enums import PackageType from conda.models.match_spec import MatchSpec from conda.mode...
256
7,795
pyomo
doc/OnlineDocs/src/scripting/abstract2piece.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...
61
1,890
python-prompt-toolkit
examples/dialogs/messagebox.py
.py
#!/usr/bin/env python """ Example of a message box window. """ from prompt_toolkit.shortcuts import message_dialog def main(): message_dialog( title="Example dialog window", text="Do you want to continue?\nPress ENTER to quit.", ).run() if __name__ == "__main__": main()
18
304
mlflow
tests/utils/test_resources/dummy_package/pandas.py
.py
# This module is meant to test shadowing of the 3rd party module raise Exception( "This package should not have been imported! " "This means that the sys.path was not configured correctly" )
6
199
python-prompt-toolkit
src/prompt_toolkit/token.py
.py
""" """ from __future__ import annotations __all__ = [ "ZeroWidthEscape", ] ZeroWidthEscape = "[ZeroWidthEscape]"
10
121
wandb
wandb/filesync/step_prepare.py
.py
"""Batching file prepare requests to our API.""" from __future__ import annotations import queue import threading import time from collections.abc import Callable, Mapping, Sequence from typing import TYPE_CHECKING, NamedTuple if TYPE_CHECKING: from wandb.sdk.internal.internal_api import ( Api, C...
172
5,438
saleor
saleor/payment/tasks.py
.py
import datetime import logging import uuid import graphene from django.conf import settings from django.db import transaction from django.db.models import DateTimeField, Exists, ExpressionWrapper, OuterRef, Q from ..celeryconf import app from ..channel.models import Channel from ..checkout import CheckoutAuthorizeSta...
220
8,910
conda
tests/common/test_path.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause from __future__ import annotations import ntpath import re from contextlib import nullcontext from logging import getLogger from pathlib import PureWindowsPath from typing import TYPE_CHECKING import pytest from conda.base.context import con...
465
19,050
mlflow
mlflow/demo/generators/evaluation.py
.py
from __future__ import annotations import contextlib import hashlib import io import logging import os from collections.abc import Callable from typing import TYPE_CHECKING, Literal import mlflow if TYPE_CHECKING: from mlflow.genai.datasets import EvaluationDataset from mlflow.demo.base import ( DEMO_EXPERI...
404
15,123
wandb
tests/system_tests/test_launch/test_launch.py
.py
from unittest import mock from unittest.mock import MagicMock import pytest import wandb from wandb.errors import CommError from wandb.sdk.internal.internal_api import Api as InternalApi from wandb.sdk.launch._launch import _launch from wandb.sdk.launch.errors import LaunchError class MockBuilder: def __init__(s...
127
3,377
pyomo
pyomo/dataportal/TableData.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...
269
9,271
mlflow
tests/gateway/providers/test_openrouter.py
.py
from unittest import mock import pytest from fastapi.encoders import jsonable_encoder from mlflow.gateway.config import EndpointConfig from mlflow.gateway.providers.openrouter import OpenRouterProvider from mlflow.gateway.schemas import chat from tests.gateway.tools import MockAsyncResponse, mock_http_client def _...
77
2,193
wandb
wandb/sdk/artifacts/_generated/delete_artifact_portfolio.py
.py
# Generated by ariadne-codegen # Source: tools/graphql_codegen/artifacts/ from __future__ import annotations from typing import Literal from pydantic import Field from wandb._pydantic import GQLResult, Typename from .enums import ArtifactCollectionState class DeleteArtifactPortfolio(GQLResult): result: Delet...
34
827
pyro
pyro/optim/adagrad_rmsprop.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 from typing import Any, Callable, Optional import torch from torch.optim.optimizer import Optimizer class AdagradRMSProp(Optimizer): """ Implements a mash-up of the Adagrad algorithm and RMSProp. For the precise upda...
88
3,060
astropy
astropy/modeling/fitting.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module implements classes (called Fitters) which combine optimization algorithms (typically from `scipy.optimize`) with statistic functions to perform fitting. Fitters are implemented as callable classes. In addition to the data to fit, the ``__c...
2,372
89,369
black
tests/data/cases/fmtskip11.py
.py
def foo(): pass # comment 1 # fmt: skip # comment 2 [ (1, 2), # # fmt: off # (3, # 4), # # fmt: on (5, 6), ] [ (1, 2), # # fmt: off # (3, # 4), # fmt: on (5, 6), ] [ (1, 2), # fmt: off # (3, # 4), # # fmt: on (5, 6), ] [ (...
89
769
coveragepy
ci/update_rtfd.py
.py
""" Update ReadTheDocs to show and hide releases. """ import re import sys from session import get_session # How many from each level to show. NUM_MAJORS = 3 NUM_MINORS = 3 OLD_MINORS = 1 NUM_MICROS = 1 OLD_MICROS = 1 def get_all_versions(project): """Pull all the versions for a project from ReadTheDocs.""" ...
108
3,002
luigi
luigi/contrib/hdfs/format.py
.py
import logging import os import luigi.format from luigi.contrib.hdfs import config as hdfs_config from luigi.contrib.hdfs.clients import exists, listdir, mkdir, remove, rename from luigi.contrib.hdfs.config import load_hadoop_cmd from luigi.contrib.hdfs.error import HDFSCliError logger = logging.getLogger("luigi-inte...
182
5,975
beam
sdks/python/apache_beam/examples/complete/juliaset/juliaset/juliaset.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...
130
4,390
mlflow
tests/strands/test_strands_tracing.py
.py
import json from collections.abc import AsyncIterator, Sequence from typing import Any from strands import Agent from strands.models.model import Model from strands.tools.tools import PythonAgentTool import mlflow from mlflow.entities import SpanType from mlflow.environment_variables import MLFLOW_USE_DEFAULT_TRACER_...
323
10,130
mkdocs
mkdocs/config/__init__.py
.py
from mkdocs.config.base import Config, load_config __all__ = ['load_config', 'Config']
4
88
probability
tensorflow_probability/python/internal/numerics_testing_test.py
.py
# Copyright 2021 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...
65
2,314
probability
tensorflow_probability/python/distributions/pert.py
.py
# Copyright 2019 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
262
9,805
ipython
tests/test_events.py
.py
import pytest from unittest.mock import Mock from IPython.core import events import IPython.testing.tools as tt @events._define_event def ping_received(): pass @events._define_event def event_with_argument(argument): pass @pytest.fixture def em(): return events.EventManager( get_ipython(), ...
89
1,898
wandb
wandb/_filters/__init__.py
.py
from .expressions import FIELD_REGEX, FilterableField, FilterExpr, MongoLikeFilter from .filterutils import simplify_expr from .operators import ( All, And, BaseOp, Contains, Eq, Exists, Gt, Gte, In, Lt, Lte, Ne, Nor, Not, NotIn, Op, Or, Regex, ...
51
666
pyomo
pyomo/solvers/tests/models/LP_piecewise.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...
62
1,879
astropy
astropy/table/tests/test_operations.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import re from collections import OrderedDict from contextlib import nullcontext import numpy as np import pytest from numpy.testing import assert_array_equal import astropy.table.operations as ato from astropy import table from astropy import units as ...
2,748
94,970
pynacl
src/nacl/bindings/crypto_core.py
.py
# Copyright 2018 Donald Stufft and individual contributors # # 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...
449
15,101
probability
conftest.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...
40
1,346
openvino
src/frontends/paddle/tests/test_models/gen_scripts/generate_reduce_any.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # # fill_const paddle model generator # import numpy as np from save_model import saveModel import paddle import sys def reduce_any(name : str, x, axis=None, keepdim=False): paddle.enable_static() with paddle.static.program_gua...
46
1,755
mlflow
mlflow/utils/virtualenv.py
.py
import logging import os import re import shutil import tempfile import uuid from pathlib import Path from typing import Literal from packaging.version import Version import mlflow from mlflow.environment_variables import _MLFLOW_TESTING, MLFLOW_ENV_ROOT from mlflow.exceptions import MlflowException from mlflow.model...
463
18,821
wandb
tests/system_tests/test_functional/console_capture/test_console_capture.py
.py
import pathlib import subprocess def test_deadlocks(): script = pathlib.Path(__file__).parent / "deadlocks.py" subprocess.check_call(["python", str(script)], timeout=5) def test_infinite_loop(): script = pathlib.Path(__file__).parent / "infinite_loop.py" subprocess.check_call(["python", str(script)]...
44
1,289
beam
sdks/python/apache_beam/options/pipeline_options_validator.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...
461
18,498
beam
sdks/python/apache_beam/runners/interactive/options/capture_limiters_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...
68
2,299
astropy
astropy/wcs/wcsapi/tests/test_utils.py
.py
import pytest from astropy import units as u from astropy.tests.helper import assert_quantity_allclose from astropy.wcs import WCS from astropy.wcs.wcsapi.utils import deserialize_class, wcs_info_str def test_construct(): result = deserialize_class(("astropy.units.Quantity", (10,), {"unit": "deg"})) assert_q...
56
1,475
mlflow
tests/genai/scorers/test_validation.py
.py
from unittest import mock import pandas as pd import pytest import mlflow from mlflow.exceptions import MlflowException from mlflow.genai.evaluation.utils import _convert_to_eval_set from mlflow.genai.scorers.base import Scorer, scorer from mlflow.genai.scorers.builtin_scorers import ( Correctness, Expectatio...
240
7,851
sphinx
sphinx/ext/autodoc/directive.py
.py
from __future__ import annotations from collections.abc import Callable from typing import TYPE_CHECKING from docutils.statemachine import StringList from docutils.utils import assemble_option_dict from sphinx.ext.autodoc._legacy_class_based._directive_options import Options from sphinx.ext.autodoc._shared import LO...
179
5,913
textual
tests/test_unmount.py
.py
from __future__ import annotations from textual import events from textual.app import App, ComposeResult from textual.containers import Container from textual.screen import Screen async def test_unmount() -> None: """Test unmount events are received in reverse DOM order.""" unmount_ids: list[str] = [] c...
55
1,646
ipython
IPython/utils/io.py
.py
""" IO related utilities. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. import sys from pathlib import Path from .capture import CapturedIO, capture_output from io import StringIO class Tee: """A class to duplicate an output stream to stdout/err. ...
133
3,951
openvino
tests/layer_tests/tensorflow_lite_tests/test_tfl_Pack.py
.py
import pytest import tensorflow as tf from common.tflite_layer_test_class import TFLiteLayerTest test_params = [ {'shape': [3], 'num_tensors': 2}, {'shape': [1, 22], 'num_tensors': 10}, {'shape': [1, 1, 8], 'num_tensors': 5}, {'shape': [1, 22, 22, 8], 'num_tensors': 5}, {'shape': [1, 22, 22, 8, 3]...
41
1,447
coremltools
coremltools/converters/sklearn/_sklearn_util.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 def check_fitted(model, func): """Check if a model is fitted. Raise error if not. Parameters ...
38
1,032
beam
sdks/python/apache_beam/examples/ml_transform/mltransform_one_hot_encoding.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...
267
8,873
tomli
setup.py
.py
import os from setuptools import setup # type: ignore[import-untyped] if os.environ.get("TOMLI_USE_MYPYC") == "1": import glob from mypyc.build import mypycify files = glob.glob("src/**/*.py", recursive=True) ext_modules = mypycify(files) else: ext_modules = [] setup(ext_modules=ext_modules)
16
319
python-prompt-toolkit
examples/print-text/html.py
.py
#!/usr/bin/env python """ Demonstration of how to print using the HTML class. """ from prompt_toolkit import HTML, print_formatted_text print = print_formatted_text def title(text): print(HTML("\n<u><b>{}</b></u>").format(text)) def main(): title("Special formatting") print(HTML(" <b>Bold</b>")) ...
55
1,368
sqlmap
sqlmapapi.py
.py
#!/usr/bin/env python """ Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org) See the file 'LICENSE' for copying permission """ import sys sys.dont_write_bytecode = True __import__("lib.utils.versioncheck") # this has to be the first non-standard import import logging import os import warnings warning...
121
4,358
saleor
saleor/graphql/invoice/types.py
.py
import graphene from ...invoice import models from ..core.context import SyncWebhookControlContext from ..core.scalars import DateTime from ..core.types import Job, ModelObjectType from ..meta.types import ObjectWithMetadata from ..order.dataloaders import OrderByIdLoader class Invoice(ModelObjectType[models.Invoice...
46
1,570
sphinx
tests/roots/test-latex-equations/conf.py
.py
root_doc = 'equations' extensions = ['sphinx.ext.imgmath']
3
59
pyro
tests/test_examples.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import logging import os import sys from subprocess import check_call import pytest import torch from tests.common import ( EXAMPLES_DIR, requires_cuda, requires_funsor, requires_horovod, requires_lightning, ...
410
22,086
hatch
backend/src/hatchling/plugin/utils.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, TypeVar if TYPE_CHECKING: from hatchling.builders.hooks.plugin.interface import BuildHookInterface from hatchling.builders.plugin.interface import BuilderInterface from hatchling.metadata.plugin.interface import MetadataHookInterface ...
49
1,638
httpie
httpie/cli/nested_json/tokens.py
.py
from enum import Enum, auto from typing import NamedTuple, Union, Optional, List EMPTY_STRING = '' HIGHLIGHTER = '^' OPEN_BRACKET = '[' CLOSE_BRACKET = ']' BACKSLASH = '\\' class TokenKind(Enum): TEXT = auto() NUMBER = auto() LEFT_BRACKET = auto() RIGHT_BRACKET = auto() PSEUDO = auto() # Not a r...
81
1,912
metrics
tests/unittests/audio/test_si_snr.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...
150
5,475
saleor
saleor/core/telemetry/tests/test_metric.py
.py
from unittest.mock import MagicMock, patch import pytest from opentelemetry.metrics import Synchronous from opentelemetry.sdk.metrics.export import HistogramDataPoint from ....tests.utils import get_metric_data from .. import meter from ..metric import ( DuplicateMetricError, Meter, MeterProxy, Metric...
447
13,148
pyro
tests/distributions/test_kl.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import pytest import torch from torch.distributions import kl_divergence, transforms import pyro.distributions as dist from pyro.distributions.util import sum_rightmost from tests.common import assert_close @pytest.mark.parametr...
93
3,702
beam
sdks/python/apache_beam/internal/gcp/json_value.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...
166
5,978
mlflow
tests/llama_index/sample_code/basic_retriever.py
.py
from llama_index.core import Document, VectorStoreIndex import mlflow index = VectorStoreIndex.from_documents(documents=[Document.example()]) retriever = index.as_retriever() mlflow.models.set_model(retriever)
9
213
astropy
astropy/utils/metadata/core.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Classes for handling metadata.""" __all__ = ["MetaAttribute", "MetaData"] import inspect from collections import OrderedDict from collections.abc import Mapping from copy import deepcopy from dataclasses import is_dataclass class MetaData: """ ...
215
7,678
sphinx
tests/roots/test-ext-imgmockconverter/conf.py
.py
import sys from pathlib import Path sys.path.insert(0, str(Path.cwd().resolve())) extensions = ['mocksvgconverter']
7
118
conda
conda/gateways/__init__.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause """ Gateways isolate interaction of conda code with the outside world. Disk manipulation, database interaction, and remote requests should all be through various gateways. Functions and methods in ``conda.gateways`` must use ``conda.models`` f...
28
732
probability
tensorflow_probability/python/bijectors/cholesky_to_inv_cholesky.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...
129
4,649
conda
tests/plugins/data/test-plugin/test_plugin/importerror.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause # see tests.plugins.test_manager.test_load_entrypoints_importerror # simulate an ImportError import package_that_does_not_exist # noqa
6
211
cvxpy
cvxpy/reductions/dcp2cone/canonicalizers/log_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...
36
1,288
clearml
clearml/backend_interface/task/__init__.py
.py
from .task import Task __all__ = ["Task"]
4
43
beam
sdks/python/apache_beam/examples/rate_limiter_simple.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...
98
3,076
saleor
saleor/schedulers/schedulers.py
.py
import copy import logging import time from typing import Any, NamedTuple import celery.beat import celery.schedules from celery.signals import setup_logging from django_celery_beat import models as base_models from django_celery_beat.clockedschedule import clocked from django_celery_beat.schedulers import DatabaseSch...
170
5,908
saleor
saleor/graphql/account/mutations/staff/address_create.py
.py
import graphene from .....account import models from .....account.search import update_user_search_vector from .....account.utils import ( remove_the_oldest_user_address_if_address_limit_is_reached, ) from .....core.tracing import traced_atomic_transaction from .....permission.enums import AccountPermissions from ...
73
2,899
wandb
wandb/apis/public/service_api.py
.py
from __future__ import annotations import json import logging from collections.abc import Callable, Iterable, Mapping from dataclasses import dataclass from typing import Any, TypeVar, cast from wandb.proto import wandb_internal_pb2 as pb from wandb.proto import wandb_server_pb2 as spb from wandb.proto.wandb_api_pb2 ...
344
12,384
omegaconf
tests/test_basic_ops_tuple.py
.py
import copy import pickle from collections.abc import MutableSequence, Sequence from typing import Any, Optional, Tuple from pytest import mark, param, raises from omegaconf import ( MISSING, DictConfig, ListConfig, Node, OmegaConf, TupleConfig, ValidationError, ) from omegaconf.errors imp...
412
12,802
qutip
qutip/core/expect.py
.py
__all__ = ['expect', 'variance'] from typing import overload, Sequence from .qobj import Qobj from . import data as _data from ..settings import settings from ..core.numpy_backend import np @overload def expect(oper: Qobj, state: Qobj) -> complex: ... @overload def expect( oper: Qobj, state: Qobj | Sequence...
129
3,537
sphinx
tests/test_builders/test_build_all.py
.py
"""Test all builders. This test skips building docs for some builders that have independent testcases. (html, changes, epub, latex, texinfo and manpage) """ from __future__ import annotations import shutil from typing import TYPE_CHECKING from unittest import mock import pytest from sphinx.testing.util import Sphi...
100
2,599