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 |
|---|---|---|---|---|---|
ipython | IPython/utils/ipstruct.py | .py | """A dict subclass that supports attribute style access.
Authors:
* Fernando Perez (original)
* Brian Granger (refactoring to a dict subclass)
"""
from __future__ import annotations
from typing import Any
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The I... | 380 | 11,927 |
onnxruntime | onnxruntime/python/tools/transformers/models/phi2/inference_example.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
import time
import numpy as np
import torch
from transformers import Au... | 415 | 17,291 |
pymc | tests/gp/test_mean.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... | 91 | 3,003 |
metrics | tests/integrations/lightning/boring_model.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... | 128 | 3,947 |
pyomo | pyomo/scripting/commands.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... | 43 | 1,497 |
saleor | saleor/webhook/circuit_breaker/storage.py | .py | import logging
import time
import uuid
from django.core.cache import cache
from redis import RedisError
from ...graphql.app.enums import CircuitBreakerState
logger = logging.getLogger(__name__)
class Storage:
def set_app_state(self, app_id: int, state: CircuitBreakerState, changed_at: int):
pass
d... | 123 | 4,045 |
pymc | pymc/smc/__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... | 21 | 759 |
pyomo | doc/OnlineDocs/src/data/ABCD2.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... | 24 | 970 |
onnxruntime | onnxruntime/python/tools/quantization/operators/gather.py | .py | from ..quant_utils import TENSOR_NAME_QUANT_SUFFIX, QuantizedValue, QuantizedValueType
from .base_operator import QuantOperatorBase
from .qdq_base_operator import QDQOperatorBase
"""
Quantize Gather
"""
class GatherQuant(QuantOperatorBase):
def __init__(self, onnx_quantizer, onnx_node):
super().__ini... | 65 | 2,166 |
mlflow | mlflow/server/validation.py | .py | from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE
def _validate_content_type(flask_request, allowed_content_types: list[str]):
"""
Validates that the request content type is one of the allowed content types.
Args:
flask_request: Flask r... | 31 | 1,095 |
textual | tests/option_list/test_option_removal.py | .py | """Test removing options from an option list."""
from __future__ import annotations
import pytest
from textual.app import App, ComposeResult
from textual.geometry import Offset
from textual.widgets import OptionList
from textual.widgets.option_list import Option, OptionDoesNotExist
class OptionListApp(App[None]):
... | 113 | 4,429 |
gunicorn | tests/requests/valid/029.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from gunicorn.config import Config
cfg = Config()
request = {
"method": "GET",
"uri": uri("/stuff/here?foo=bar"),
"version": (1, 1),
"headers": [
('TRANSFER-ENCODING', 'identity'),
... | 19 | 385 |
saleor | saleor/graphql/product/tests/queries/test_products_query_with_filter.py | .py | import datetime
from decimal import Decimal
import graphene
import pytest
from django.utils import timezone
from .....attribute import AttributeInputType, AttributeType
from .....attribute.models import Attribute, AttributeValue
from .....attribute.tests.model_helpers import (
get_product_attribute_values,
ge... | 2,076 | 64,337 |
beam | sdks/python/apache_beam/transforms/dofn_lifecycle_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... | 106 | 4,075 |
astropy | astropy/utils/iers/tests/test_iers.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
import re
import warnings
from pathlib import Path
import numpy as np
import pytest
from astropy_iers_data import (
IERS_A_README,
IERS_B_FILE,
IERS_B_README,
IERS_LEAP_SECOND_FILE,
)
from astropy import units as u
from astropy... | 583 | 23,760 |
hatch | tests/helpers/templates/wheel/standard_default_single_module.py | .py | from hatch.template import File
from hatch.utils.fs import Path
from hatchling.__about__ import __version__
from hatchling.metadata.spec import DEFAULT_METADATA_VERSION
from ..new.feature_no_src_layout import get_files as get_template_files
from .utils import update_record_file_contents
def get_files(**kwargs):
... | 47 | 1,206 |
metrics | src/torchmetrics/wrappers/tracker.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... | 365 | 18,135 |
omegaconf | tests/test_errors.py | .py | import gc
import re
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from textwrap import dedent
from typing import Any, Callable, Dict, List, Optional, Type, Union
from pytest import mark, param, raises, warns
import tests
from omegaconf import (
BytesNode,
DictConfig,
Flo... | 1,995 | 66,397 |
clearml | examples/scheduler/cron_example.py | .py | from clearml import Task
from clearml.automation import TaskScheduler
def simple_function():
print('This code is executed in a background thread, '
'on the same machine as the TaskScheduler process')
# add some logic here
print('done')
# Create the scheduler controller
scheduler = TaskSchedule... | 62 | 2,341 |
astropy | astropy/tests/tests/test_imports.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pkgutil
import subprocess
import sys
from pathlib import Path
from textwrap import dedent
from types import ModuleType
import pytest
import astropy
@pytest.mark.parametrize(
"subpkg",
[subpkg.name for subpkg in pkgutil.walk_packages(ast... | 70 | 1,872 |
ipython | tests/test_ipapp.py | .py | """Tests for IPython.terminal.ipapp, exercised in-process.
These tests build real ``TerminalIPythonApp`` instances pointed at the
temporary IPYTHONDIR set up by ``tests/conftest.py``. Because
``TerminalInteractiveShell`` is a singleton (created by conftest), every app
attaches to the same shell; the ``make_app`` fixt... | 442 | 14,903 |
qutip | qutip/tomography.py | .py | __all__ = ['qpt_plot', 'qpt_plot_combined', 'qpt']
from numpy import hstack, real, imag
import scipy.linalg as la
from . import tensor, spre, spost, stack_columns, unstack_columns
from .visualization import matrix_histogram
import itertools
try:
import matplotlib.pyplot as plt
except ImportError:
pass
def _... | 190 | 5,326 |
ipython | IPython/extensions/deduperreload/deduperreload.py | .py | from __future__ import annotations
import ast
import builtins
import contextlib
import itertools
import logging
import os
import pickle
import platform
import sys
import textwrap
import tokenize
from types import ModuleType
from typing import TYPE_CHECKING, Any, NamedTuple, cast
from collections.abc import Generator, I... | 643 | 26,301 |
python-prompt-toolkit | src/prompt_toolkit/output/color_depth.py | .py | from __future__ import annotations
import os
from enum import Enum
__all__ = [
"ColorDepth",
]
class ColorDepth(str, Enum):
"""
Possible color depth values for the output.
"""
value: str
#: One color only.
DEPTH_1_BIT = "DEPTH_1_BIT"
#: ANSI Colors.
DEPTH_4_BIT = "DEPTH_4_BIT"... | 65 | 1,569 |
astropy | astropy/cosmology/_src/flrw/w0wzcdm.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
__all__ = ("Flatw0wzCDM", "w0wzCDM")
from numpy import exp
from numpy.typing import ArrayLike
from astropy.cosmology._src.core import dataclass_decorator
from astropy.cosmology._src.parameter import Parameter
from astropy.cosmology._src.typing import FA... | 298 | 10,322 |
loguru | tests/exceptions/source/others/catch_as_context_manager.py | .py | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", diagnose=False, backtrace=False, colorize=False)
with logger.catch():
1 / 0
| 11 | 171 |
conda | tests/plugins/data/test-plugin/test_plugin/blocked.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
# see tests.plugins.test_manager.test_load_entrypoints_blocked
# simulate a blocked plugin
| 5 | 166 |
cvxpy | cvxpy/atoms/elementwise/neg.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... | 26 | 765 |
beam | sdks/python/apache_beam/io/gcp/tests/pubsub_matcher.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... | 204 | 7,766 |
jupytext | tests/data/notebooks/outputs/ipynb_to_sphinx/notebook_with_complex_metadata.py | .py | # ---
# jupyter:
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
| 10 | 113 |
probability | tensorflow_probability/python/distributions/mvn_diag.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... | 234 | 8,401 |
pyomo | pyomo/contrib/cp/interval_var.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... | 223 | 8,054 |
mlflow | mlflow/demo/generators/judges.py | .py | from __future__ import annotations
import logging
from mlflow.demo.base import (
DEMO_EXPERIMENT_NAME,
DEMO_PROMPT_PREFIX,
BaseDemoGenerator,
DemoFeature,
DemoResult,
)
from mlflow.genai.scorers.registry import delete_scorer, list_scorers
from mlflow.tracking._tracking_service.utils import _get_st... | 145 | 5,916 |
beam | sdks/python/apache_beam/ml/gcp/recommendations_ai_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... | 215 | 7,456 |
pyro | pyro/distributions/transforms/block_autoregressive.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
# This implementation is adapted in part from https://github.com/nicola-decao/BNAF under the MIT license.
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .. import constraints
from ..torch_tran... | 311 | 11,699 |
conda | conda/_private/zstd.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Internal zstd backend selector.
Import ``zstd`` for library API (``zstd.ZstdFile``, ``zstd.compress``, …).
Import ``ZstdError`` for exception handling.
Import ``capped_decompress`` for bounded one-shot decompression of untrusted data (mimics... | 47 | 1,570 |
saleor | saleor/discount/tests/fixtures/benchmark.py | .py | from decimal import Decimal
import graphene
import pytest
from ....discount import RewardValueType
from ....discount.models import (
Promotion,
PromotionRule,
PromotionRuleTranslation,
PromotionTranslation,
)
@pytest.fixture
def promotion_list_for_benchmark(channel_USD, channel_PLN, product_list):
... | 107 | 3,286 |
clearml | clearml/backend_config/errors.py | .py | from typing import Optional, Any
class ConfigurationError(Exception):
"""Exception class to be raised when a configuration file is invalid."""
def __init__(self, msg: str, file_path: Optional[str] = None, *args: Any) -> None:
super(ConfigurationError, self).__init__(msg, *args)
self.file_path... | 10 | 333 |
onnx | onnx/reference/ops/aionnxml/op_imputer.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 Imputer(OpRunAiOnnxMl):
def _run(
self,
x,
imputed_value_floats=None,
... | 48 | 1,568 |
onnxruntime | onnxruntime/test/python/transformers/test_data/gpt2_pytorch1.5_opset11/generate_tiny_gpt2_model.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
# This tool generates a tiny GPT2 model for testing fusion script.
# You... | 529 | 21,550 |
pyomo | pyomo/solvers/tests/solvers.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 481 | 13,621 |
readthedocs.org | readthedocs/redirects/tests/test_views.py | .py | from django.contrib.auth.models import User
from django.test import TestCase, override_settings
from django.urls import reverse
from django_dynamic_fixture import get
from readthedocs.organizations.models import Organization
from readthedocs.projects.models import Project
from readthedocs.redirects.constants import (
... | 329 | 11,285 |
ipython | tests/test_compilerop.py | .py | # coding: utf-8
"""Tests for the compilerop module."""
# -----------------------------------------------------------------------------
# Copyright (C) 2010-2011 The IPython Development Team.
#
# Distributed under the terms of the BSD License.
#
# The full license is in the file COPYING.txt, distributed with this sof... | 66 | 1,808 |
saleor | saleor/graphql/tax/tests/fragments.py | .py | TAX_CONFIGURATION_FRAGMENT = """
fragment TaxConfiguration on TaxConfiguration {
id
channel {
id
name
}
chargeTaxes
taxCalculationStrategy
displayGrossPrices
pricesEnteredWithTax
useWeightedTaxForShipping
countries {
country {
code
country
}
... | 65 | 961 |
biopython | Bio/Nexus/Nexus.py | .py | # Copyright 2005-2008 by Frank Kauff & Cymon J. Cox. All rights reserved.
# Revisions copyright 2014-2015 by Joe Cora (standard data)
#
# 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 s... | 2,132 | 83,836 |
beam | sdks/python/apache_beam/testing/benchmarks/inference/table_row_inference_benchmark.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... | 114 | 4,429 |
mlflow | mlflow/genai/evaluation/entities.py | .py | """Entities for evaluation."""
import hashlib
import json
from dataclasses import dataclass, field
from typing import Any, Callable
import pandas as pd
from mlflow.entities.assessment import Expectation, Feedback
from mlflow.entities.assessment_source import AssessmentSource, AssessmentSourceType
from mlflow.entitie... | 338 | 12,121 |
ipython | IPython/core/display.py | .py | """Top-level display functions for displaying object in different formats."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import annotations
from enum import Enum
from dataclasses import dataclass, KW_ONLY
from binascii import b2a_base64, hexli... | 1,263 | 40,834 |
mlflow | mlflow/tracking/context/databricks_notebook_context.py | .py | from mlflow.entities import SourceType
from mlflow.tracking.context.abstract_context import RunContextProvider
from mlflow.utils import databricks_utils
from mlflow.utils.mlflow_tags import (
MLFLOW_DATABRICKS_NOTEBOOK_ID,
MLFLOW_DATABRICKS_NOTEBOOK_PATH,
MLFLOW_DATABRICKS_WEBAPP_URL,
MLFLOW_DATABRICKS_... | 44 | 1,785 |
probability | spinoffs/autobnn/autobnn/likelihoods.py | .py | # Copyright 2023 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... | 175 | 5,870 |
ipython | tests/test_module_paths.py | .py | # encoding: utf-8
"""Tests for IPython.utils.module_paths.py"""
# -----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part ... | 113 | 3,277 |
gunicorn | tests/requests/invalid/invalid_field_value_01.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from gunicorn.config import Config
from gunicorn.http.errors import InvalidHeader
cfg = Config()
request = InvalidHeader
| 10 | 228 |
saleor | saleor/csv/events.py | .py | from typing import TYPE_CHECKING, Optional
from ..core.db.connection import allow_writer
from . import ExportEvents
from .models import ExportEvent
if TYPE_CHECKING:
from ..account.models import User
from ..app.models import App
from .models import ExportFile
@allow_writer()
def export_started_event(
... | 83 | 2,035 |
probability | tensorflow_probability/python/distributions/independent_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... | 634 | 25,942 |
biopython | Tests/test_UniProt.py | .py | """Tests for the UniProt module."""
import unittest
from itertools import islice
import requires_internet
from Bio import UniProt
requires_internet.check()
class SearchTests(unittest.TestCase):
def test_search_result_count(self):
query = "(organism_id:2697049) AND (reviewed:true)"
results = Un... | 89 | 3,384 |
coveragepy | coverage/core.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
"""Management of core choices."""
from __future__ import annotations
import os
import sys
from typing import Any
from coverage import env
from coverage.config ... | 142 | 5,504 |
hydra | examples/plugins/example_searchpath_plugin/hydra_plugins/example_searchpath_plugin/example_searchpath_plugin.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from hydra.core.config_search_path import ConfigSearchPath
from hydra.plugins.search_path_plugin import SearchPathPlugin
class ExampleSearchPathPlugin(SearchPathPlugin):
def manipulate_search_path(self, search_path: ConfigSearchPath) -> None:
... | 17 | 858 |
rq | rq/worker/worker_classes.py | .py | from __future__ import annotations
import contextlib
import errno
import os
import signal
import sys
import time
from random import shuffle
from typing import TYPE_CHECKING
from ..connections import get_connection_kwargs
from ..defaults import DEFAULT_WORKER_TTL
from ..exceptions import InvalidJobOperation, ShutDownI... | 317 | 12,588 |
saleor | saleor/plugins/tests/fixtures/plugin_manager.py | .py | import pytest
from ...manager import PluginsManager
from ..sample_plugins import ALL_PLUGINS
@pytest.fixture
def plugins_manager():
return PluginsManager(plugins=[])
@pytest.fixture
def all_plugins_manager():
plugins_as_module_paths = [p.__module__ + "." + p.__name__ for p in ALL_PLUGINS]
return Plugin... | 16 | 362 |
eve | setup.py | .py | #!/usr/bin/env python
import io
import re
from collections import OrderedDict
from setuptools import find_packages, setup
DESCRIPTION = "Python REST API for Humans."
with open("README.rst") as f:
LONG_DESCRIPTION = f.read()
with io.open("eve/__init__.py", "rt", encoding="utf8") as f:
VERSION = re.search(r"__... | 69 | 2,191 |
wagtail | wagtail/admin/views/pages/copy.py | .py | import swapper
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse
from django.utils.translation import gettext as _
from django.views.generic import FormView
from wagtail import hooks
from wagtail.actions.copy_page import CopyPag... | 127 | 4,903 |
saleor | saleor/graphql/attribute/tests/benchmark/test_attribute.py | .py | import graphene
import pytest
from .....attribute.models import AttributeTranslation, AttributeValueTranslation
from .....attribute.utils import associate_attribute_values_to_instance
from ....tests.utils import get_graphql_content
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
def test_query_attri... | 179 | 5,149 |
wagtail | wagtail/admin/api/actions/publish.py | .py | from django.core.exceptions import ValidationError as DjangoValidationError
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.serializers import Serializer
from wagtail.actions.publish_page_revision import PublishPag... | 35 | 1,253 |
pyomo | pyomo/solvers/tests/checks/test_gurobi_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... | 383 | 13,645 |
pyro | tests/integration_tests/test_conjugate_gaussian_models.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import logging
import os
import time
from unittest import TestCase
import numpy as np
import pytest
import torch
import pyro
import pyro.distributions as dist
import pyro.optim as optim
from pyro.distributions.testing import fake... | 653 | 25,477 |
textual | tests/test_placeholder.py | .py | import pytest
from textual.widgets import Placeholder
from textual.widgets._placeholder import InvalidPlaceholderVariant
async def test_invalid_placeholder_variant():
with pytest.raises(InvalidPlaceholderVariant):
Placeholder(variant="this is clearly not a valid variant!")
async def test_invalid_reacti... | 16 | 473 |
conda | tests/plugins/test_plugin_manager.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import json
from importlib import import_module
from typing import TYPE_CHECKING
import pytest
if TYPE_CHECKING:
from conda.plugins.manager import CondaPluginManager
from conda.testing.fixtures impor... | 124 | 3,313 |
mlflow | mlflow/genai/utils/data_validation.py | .py | import inspect
import logging
from typing import Any, Callable
from mlflow.exceptions import MlflowException
from mlflow.tracing.provider import trace_disabled
_logger = logging.getLogger(__name__)
def check_model_prediction(predict_fn: Callable[..., Any], sample_input: Any):
"""
Validate if the predict fun... | 149 | 5,071 |
onnxruntime | orttraining/orttraining/test/python/qat_poc_example/utils.py | .py | import logging
import os
def makedir(dir_path):
"""Creates a directory if one does not already exist"""
if not os.path.exists(dir_path):
logging.info(f"Creating directory: {dir_path}")
os.makedirs(dir_path, exist_ok=True)
else:
logging.info(f"Directory already exists: {dir_path}. W... | 12 | 370 |
cvxpy | cvxpy/tests/test_linalg_utils.py | .py | """
Copyright 2023, 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, soft... | 184 | 6,985 |
sphinx | sphinx/search/_stopwords/en.py | .py | # automatically generated by utils/generate-snowball.py
# from https://github.com/snowballstem/snowball-website/raw/efb4ae4d65769fb1652acbe608c0c817e746c730/algorithms/english/stop.txt
from __future__ import annotations
ENGLISH_STOPWORDS = frozenset({
'a',
'about',
'above',
'after',
'again',
'... | 182 | 2,429 |
onnxruntime | onnxruntime/test/python/quantization/test_op_gather_elems.py | .py | #!/usr/bin/env python
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# ---------------------------------------------------------------... | 111 | 4,145 |
saleor | saleor/checkout/error_codes.py | .py | from enum import Enum
class CheckoutErrorCode(Enum):
BILLING_ADDRESS_NOT_SET = "billing_address_not_set"
CHECKOUT_NOT_FULLY_PAID = "checkout_not_fully_paid"
GRAPHQL_ERROR = "graphql_error"
PRODUCT_NOT_PUBLISHED = "product_not_published"
PRODUCT_UNAVAILABLE_FOR_PURCHASE = "product_unavailable_for_p... | 72 | 3,019 |
pyro | pyro/distributions/transforms/ordered.py | .py | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import torch
from torch.distributions.transforms import Transform
from .. import constraints
class OrderedTransform(Transform):
"""
Transforms a real vector into an ordered vector.
Specifically, enforces monotonically i... | 33 | 921 |
onnxruntime | onnxruntime/core/flatbuffers/ort_flatbuffers_py/fbs/Shape.py | .py | # automatically generated by the FlatBuffers compiler, do not modify
# namespace: fbs
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()
class Shape(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffer... | 79 | 2,274 |
sphinx | sphinx/search/_stopwords/es.py | .py | # automatically generated by utils/generate-snowball.py
# from https://github.com/snowballstem/snowball-website/raw/efb4ae4d65769fb1652acbe608c0c817e746c730/algorithms/spanish/stop.txt
from __future__ import annotations
SPANISH_STOPWORDS = frozenset({
'a',
'al',
'algo',
'algunas',
'algunos',
'... | 316 | 4,543 |
textual | tests/snapshot_tests/snapshot_apps/markdown_theme_switcher.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Markdown
TEST_CODE_MARKDOWN = """
# This is a H1
```python
def main():
print("Hello world!")
```
"""
class MarkdownThemeSwitcherApp(App[None]):
BINDINGS = [
("t", "toggle_theme"),
("d", "switch_dark"),
("l", "switc... | 37 | 877 |
scikit-optimize | skopt/learning/gaussian_process/__init__.py | .py | from .gpr import GaussianProcessRegressor
__all__ = ("GaussianProcessRegressor")
| 4 | 82 |
loguru | tests/test_add_option_diagnose.py | .py | from loguru import logger
# See "test_catch_exceptions.py" for extended testing
def test_diagnose(writer):
logger.add(writer, format="{message}", diagnose=True)
try:
1 / 0 # noqa: B018
except Exception:
logger.exception("")
result_with = writer.read().strip()
logger.remove()
... | 25 | 604 |
scikit-bio | skbio/tree/_tree.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.
# --------------------------------------------... | 6,446 | 221,965 |
probability | tensorflow_probability/python/experimental/mcmc/sample_fold.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... | 293 | 12,748 |
ipython | IPython/utils/frame.py | .py | """
Utilities for working with stack frames.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software... | 32 | 1,145 |
beam | sdks/python/apache_beam/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... | 1,658 | 61,978 |
onnx | onnx/reference/ops/op_greater_or_equal.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 OpRunBinaryComparison
class GreaterOrEqual(OpRunBinaryComparison):
def _run(self, a, b):
return (np.greater_equal(a, b),)
| 14 | 308 |
ipython | IPython/terminal/pt_inputhooks/tk.py | .py | # Code borrowed from ptpython
# https://github.com/jonathanslenders/ptpython/blob/86b71a89626114b18898a0af463978bdb32eeb70/ptpython/eventloop.py
# Copyright (c) 2015, Jonathan Slenders
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided t... | 94 | 3,651 |
hydra | tests/test_examples/test_instantiate_examples.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from pathlib import Path
from textwrap import dedent
from typing import List
from pytest import mark, param
from hydra.test_utils.test_utils import (
assert_text_same,
chdir_hydra_root,
run_python_script,
)
chdir_hydra_root()
@mark.... | 145 | 3,987 |
python-dotenv | tests/conftest.py | .py | import pytest
from click.testing import CliRunner
@pytest.fixture
def cli():
runner = CliRunner()
with runner.isolated_filesystem():
yield runner
@pytest.fixture
def dotenv_path(tmp_path):
path = tmp_path / ".env"
path.write_bytes(b"")
yield path
| 17 | 279 |
probability | tensorflow_probability/python/internal/backend/numpy/nest.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... | 488 | 17,094 |
mlflow | examples/hyperparam/search_hyperopt.py | .py | """
Example of hyperparameter search in MLflow using Hyperopt.
The run method will instantiate and run Hyperopt optimizer. Each parameter configuration is
evaluated in a new MLflow run invoking main entry point with selected parameters.
The runs are evaluated based on validation set loss. Test set score is calculated... | 166 | 6,374 |
textual | docs/examples/widgets/link.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Link
class LabelApp(App):
AUTO_FOCUS = None
CSS = """
Screen {
align: center middle;
}
"""
def compose(self) -> ComposeResult:
yield Link(
"Go to textualize.io",
url="https://textual... | 24 | 435 |
conda | tests/test_codesigned.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import os
from functools import cache
from pathlib import Path
from shutil import which
from subprocess import CalledProcessError, check_output, run
import pytest
from conda import CONDA_PACKAGE_ROOT
from co... | 94 | 3,268 |
biopython | Tests/test_pairwise2.py | .py | # This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Tests for pairwise2 module using the default C functions.
This test file imports the TestCases from ``pairwise2_testCases.py``.
If you want to add ... | 29 | 844 |
coremltools | deps/pybind11/tests/test_numpy_vectorize.py | .py | from __future__ import annotations
import pytest
from pybind11_tests import numpy_vectorize as m
np = pytest.importorskip("numpy")
def test_vectorize(capture):
assert np.isclose(m.vectorized_func3(np.array(3 + 7j)), [6 + 14j])
for f in [m.vectorized_func, m.vectorized_func2]:
with capture:
... | 269 | 9,694 |
wandb | tests/unit_tests/test_sandbox/test_cli_beta_sandbox.py | .py | from __future__ import annotations
import cwsandbox.cli.list as cwsandbox_list
import pytest
from click.testing import CliRunner
from wandb.cli import cli
from wandb.sandbox import CWSandboxError
@pytest.mark.parametrize(
("argv", "expected_strings"),
[
(
["sandbox", "--help"],
... | 80 | 2,127 |
coremltools | deps/pybind11/setup.py | .py | #!/usr/bin/env python3
# Setup script for PyPI; use CMakeFile.txt to build extension modules
from __future__ import annotations
import contextlib
import os
import re
import shutil
import string
import subprocess
import sys
from collections.abc import Generator
from pathlib import Path
from tempfile import TemporaryDi... | 150 | 4,882 |
probability | tensorflow_probability/python/experimental/psd_kernels/feature_scaled_with_categorical_test.py | .py | # Copyright 2023 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... | 243 | 10,441 |
pdm | tests/cli/test_utils.py | .py | def test_help_with_unknown_arguments(pdm):
result = pdm(["add", "--unknown-args"])
assert "usage: pdm add " in result.stderr.lower()
assert result.exit_code == 2
def test_output_similar_command_when_typo(pdm):
result = pdm(["instal"])
assert "install" in result.stderr
assert result.exit_code =... | 11 | 324 |
saleor | saleor/graphql/order/tests/mutations/test_draft_order_update.py | .py | from datetime import timedelta
from decimal import Decimal
from unittest.mock import ANY, patch
import graphene
import pytest
from django.test import override_settings
from django.utils import timezone
from prices import TaxedMoney
from .....core.models import EventDelivery
from .....core.prices import quantize_price... | 4,005 | 131,755 |
scikit-bio | skbio/stats/ordination/_ordination_results.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.
# --------------------------------------------... | 690 | 25,836 |
hydra | tests/test_hydra_context_warnings.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import re
from typing import Any, List, Sequence, Union
from unittest.mock import Mock
from omegaconf import DictConfig, OmegaConf
from pytest import mark, raises
from hydra import TaskFunction
from hydra._internal.callbacks import Callbacks
from ... | 89 | 2,813 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.