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 |
|---|---|---|---|---|---|
loguru | tests/exceptions/source/others/catch_as_decorator_with_parentheses.py | .py | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", diagnose=False, backtrace=False, colorize=False)
@logger.catch()
def c(a, b):
a / b
c(5, b=0)
| 15 | 191 |
qutip | qutip/tests/core/data/test_properties.py | .py | import numpy as np
import pytest
import qutip
from qutip import data as _data
from qutip import CoreOptions
from . import conftest
from qutip.core.data.dia import clean_dia
@pytest.fixture(params=[_data.CSR, _data.Dense, _data.Dia], ids=["CSR", "Dense", "Dia"])
def datatype(request):
return request.param
class ... | 257 | 10,244 |
kafka | tests/kafkatest/tests/streams/streams_upgrade_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 use ... | 550 | 30,540 |
coremltools | deps/pybind11/tests/test_docstring_options.py | .py | from __future__ import annotations
from pybind11_tests import docstring_options as m
def test_docstring_options():
# options.disable_function_signatures()
assert not m.test_function1.__doc__
assert m.test_function2.__doc__ == "A custom docstring"
# docstring specified on just the first overload def... | 67 | 2,459 |
conda | tests/common/path/test_python.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import pytest
from conda.common.path.python import is_valid_import_path
@pytest.mark.parametrize(
"path,result",
[
("python", True),
("python.path", True),
("python._path0123... | 40 | 1,084 |
python-prompt-toolkit | src/prompt_toolkit/contrib/regular_languages/regex_parser.py | .py | """
Parser for parsing a regular expression.
Take a string representing a regular expression and return the root node of its
parse tree.
usage::
root_node = parse_regex('(hello|world)')
Remarks:
- The regex parser processes multiline, it ignores all whitespace and supports
multiple named groups with the same n... | 280 | 7,732 |
black | tests/test_concurrency_manager_shutdown.py | .py | from __future__ import annotations
import asyncio
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any, Optional
import black.concurrency as concurrency
from black import Mode, WriteBack
from black.report import Report
class FakeManager:
shutdown_called: bool
de... | 67 | 1,821 |
wandb | wandb/sdk/lib/wbauth/authenticate.py | .py | from __future__ import annotations
import os
import threading
from wandb import env
from wandb.errors import AuthenticationError, UsageError, term
from wandb.sdk import wandb_setup
from . import prompt, wbnetrc
from .auth import Auth, AuthApiKey, AuthIdentityTokenFile, AuthWithSource
from .host_url import HostUrl
fr... | 281 | 8,450 |
sphinx | sphinx/ext/autodoc/_generate.py | .py | from __future__ import annotations
import sys
from typing import TYPE_CHECKING
from docutils.statemachine import StringList
from sphinx.errors import PycodeError
from sphinx.ext.autodoc._dynamic._loader import _load_object_by_name
from sphinx.ext.autodoc._dynamic._member_finder import _gather_members
from sphinx.ext... | 407 | 14,182 |
sqlmap | plugins/dbms/cache/syntax.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
from lib.core.convert import getOrds
from plugins.generic.syntax import Syntax as GenericSyntax
class Syntax(GenericSyntax):
@staticmethod
def escape(expression, quote=Tr... | 24 | 734 |
scikit-bio | doc/source/autoinherit.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.
# --------------------------------------------... | 85 | 2,743 |
sphinx | doc/usage/extensions/example_google.py | .py | """Example Google style docstrings.
This module demonstrates documentation as specified by the `Google Python
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
with a section header and a colon followed by a block of indented text.
Example:
Examples can be given using either the ``Exa... | 312 | 9,689 |
textual | tests/test_getters.py | .py | import pytest
from textual import containers, getters
from textual.app import App, ComposeResult
from textual.css.query import NoMatches, WrongType
from textual.widget import Widget
from textual.widgets import Input, Label
async def test_getters() -> None:
"""Check the getter descriptors work, and return expecte... | 62 | 1,779 |
django-cms | cms/apphook_pool.py | .py | import warnings
from django.core.exceptions import ImproperlyConfigured
from django.utils.module_loading import autodiscover_modules, import_string
from django.utils.translation import gettext as _
from cms.app_base import CMSApp
from cms.exceptions import AppAlreadyRegistered
from cms.utils.conf import get_cms_setti... | 103 | 3,040 |
pyomo | examples/pyomobook/abstract-ch/abstract5.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... | 36 | 1,089 |
hydra | hydra/_internal/core_plugins/bash_completion.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
import os
import sys
from typing import Optional
from hydra.plugins.completion_plugin import CompletionPlugin
log = logging.getLogger(__name__)
class BashCompletion(CompletionPlugin):
def install(self) -> None:
# Recor... | 104 | 3,077 |
loguru | tests/exceptions/source/others/repeated_lines.py | .py | from loguru import logger
import sys
logger.remove()
logger.add(sys.stderr, format="", diagnose=False, backtrace=False, colorize=False)
logger.add(sys.stderr, format="", diagnose=False, backtrace=True, colorize=False)
logger.add(sys.stderr, format="", diagnose=False, backtrace=False, colorize=True)
logger.add(sys.std... | 24 | 670 |
mlflow | dev/check_actions.py | .py | """Validate GitHub Actions workflow and action files.
Complements `.github/policy.rego` with checks that need cross-file or remote
context.
"""
import json
import re
import subprocess
import sys
from collections import defaultdict
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib imp... | 281 | 8,951 |
sqlmap | plugins/dbms/altibase/fingerprint.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
from lib.core.common import Backend
from lib.core.common import Format
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.e... | 96 | 2,656 |
wandb | wandb/apis/public/automations.py | .py | """W&B Public API for Automation objects."""
from __future__ import annotations
from collections.abc import Iterator, Mapping
from typing import TYPE_CHECKING, Any, ClassVar, TypeAlias
from pydantic import ValidationError
from typing_extensions import override
from wandb.apis.paginator import RelayPaginator
if TYP... | 214 | 6,853 |
python-prompt-toolkit | examples/full-screen/simple-demos/float-transparency.py | .py | #!/usr/bin/env python
"""
Example of the 'transparency' attribute of `Window' when used in a Float.
"""
from prompt_toolkit.application import Application
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.layout.containers import Float, FloatContainer... | 89 | 2,742 |
saleor | saleor/graphql/shop/tests/mutations/test_shop_settings_update.py | .py | import functools
from unittest.mock import ANY, patch
import pytest
from .....core.error_codes import ShopErrorCode
from .....core.jwt import JWT_OWNER_FIELD
from .....site.models import Site
from ....storefront_traffic import (
get_allow_storefront_traffic,
set_allow_storefront_traffic_cache,
)
from ....test... | 949 | 29,907 |
conda | tests/gateways/disk/test_read.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from pathlib import Path
from pprint import pprint
from conda.common.compat import on_win
from conda.common.path import get_python_site_packages_short_path
from conda.common.serialize import json
from conda.p... | 411 | 14,318 |
sqlmap | plugins/generic/entries.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
import re
from lib.core.agent import agent
from lib.core.bigarray import BigArray
from lib.core.common import Backend
from lib.core.common import clearConsoleLine
from lib.core.c... | 767 | 41,186 |
rq | rq/maintenance.py | .py | import warnings
from typing import TYPE_CHECKING
from .intermediate_queue import IntermediateQueue
from .queue import Queue
if TYPE_CHECKING:
from .worker import BaseWorker
def clean_intermediate_queue(worker: 'BaseWorker', queue: Queue) -> None:
"""
Check whether there are any jobs stuck in the interme... | 27 | 940 |
mlflow | examples/flower_classifier/train.py | .py | """
Example of image classification with MLflow using Keras to classify flowers from photos. The data is
taken from ``http://download.tensorflow.org/example_images/flower_photos.tgz`` and may be
downloaded during running this project if it is missing.
"""
import math
import os
import tarfile
import click
import keras... | 245 | 9,361 |
cvxpy | cvxpy/reductions/flip_objective.py | .py | """
Copyright 2017 Robin Verschueren
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softw... | 68 | 2,051 |
mkdocs | mkdocs/tests/config/base_tests.py | .py | import os
import unittest
from mkdocs import exceptions
from mkdocs.config import base
from mkdocs.config import config_options as c
from mkdocs.config import defaults
from mkdocs.config.base import ValidationError
from mkdocs.tests.base import change_dir, tempdir
class ConfigBaseTests(unittest.TestCase):
def te... | 275 | 10,551 |
pyomo | pyomo/contrib/solver/tests/unit/test_base.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... | 308 | 12,152 |
gunicorn | tests/requests/invalid/003c.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from gunicorn.http.errors import InvalidRequestMethod
request = InvalidRequestMethod
| 7 | 191 |
wagtail | wagtail/documents/api/v2/views.py | .py | from wagtail.api.v2.filters import FieldsFilter, OrderingFilter, SearchFilter
from wagtail.api.v2.views import BaseAPIViewSet
from wagtail.models import CollectionViewRestriction
from ... import get_document_model
from .serializers import DocumentSerializer
class DocumentsAPIViewSet(BaseAPIViewSet):
base_seriali... | 35 | 1,252 |
beam | sdks/python/apache_beam/runners/interactive/caching/expression_cache_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... | 129 | 4,577 |
openvino | tests/layer_tests/pytorch_tests/test_quantized_hardswish.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import platform
import numpy as np
import pytest
import torch
from pytorch_layer_test_class import PytorchLayerTest
class quantized_hardswish(torch.nn.Module):
def __init__(self, scale, zero_point, dtype) -> None:
torch.n... | 51 | 1,702 |
coremltools | coremltools/converters/sklearn/_decision_tree_classifier.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
from ..._deps import _HAS_SKLEARN
from ...models import MLModel as _MLModel
from ._tree_ensemble import ... | 72 | 1,775 |
sphinx | tests/roots/test-ext-apidoc/src/my_package.py | .py | """An example module."""
def example_function(a: str) -> str:
"""An example function."""
return a
| 7 | 108 |
mlflow | examples/openai/spark_udf.py | .py | import os
import openai
from pyspark.sql import SparkSession
import mlflow
assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY environment variable."
with mlflow.start_run():
model_info = mlflow.openai.log_model(
model="gpt-4o-mini",
task=openai.chat.completions,
messag... | 31 | 855 |
pyomo | pyomo/core/tests/unit/test_deprecation.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... | 50 | 1,794 |
saleor | saleor/tests/e2e/vouchers/utils/voucher_code_bulk_delete.py | .py | from ...utils import get_graphql_content
VOUCHER_CODE_BULK_DELETE_MUTATION = """
mutation VoucherCodeBulkDelete ($ids: [ID!]!) {
voucherCodeBulkDelete(ids: $ids) {
errors {
message
code
voucherCodes
}
}
}
"""
def voucher_code_bulk_delete(staff_api_client, voucher_code_ids):
variable... | 31 | 661 |
sqlmap | plugins/dbms/hsqldb/takeover.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
from lib.core.exception import SqlmapUnsupportedFeatureException
from plugins.generic.takeover import Takeover as GenericTakeover
class Takeover(GenericTakeover):
def osCmd(s... | 29 | 970 |
textual | docs/examples/styles/padding.py | .py | from textual.app import App
from textual.widgets import Label
TEXT = """I must not fear.
Fear is the mind-killer.
Fear is the little-death that brings total obliteration.
I will face my fear.
I will permit it to pass over me and through me.
And when it has gone past, I will turn the inner eye to see its path.
Where th... | 23 | 553 |
sqlmap | tests/test_misc.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
Assorted pure helpers: stats, set ops, value predicates, value/counter stacks,
enum helpers, DBMS alias/version checks, column prioritization.
"""
import os
import sys
import unittes... | 130 | 4,725 |
biopython | Tests/test_Affy.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 Affy module."""
import os
import struct
import unittest
try:
import numpy.testing
from numpy import array
except ImportError:
... | 342 | 13,848 |
saleor | saleor/account/management/commands/changepassword.py | .py | from django.contrib.auth.management.commands.changepassword import Command
__all__ = ["Command"]
| 4 | 98 |
readthedocs.org | readthedocs/builds/views.py | .py | """Views for builds app."""
import textwrap
from urllib.parse import urlparse
import structlog
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseForbidden
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import rev... | 160 | 4,956 |
beam | learning/tour-of-beam/learning-content/windowing/session-window/python-example/task.py | .py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); y... | 51 | 1,721 |
probability | tensorflow_probability/python/bijectors/tanh.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... | 84 | 2,570 |
django-cms | cms/test_utils/project/extensionapp/models.py | .py | from django.conf import settings
from django.db import models
from cms.extensions import PageContentExtension, PageExtension
from cms.extensions.extension_pool import extension_pool
class MyPageExtension(PageExtension):
extra = models.CharField(blank=True, default='', max_length=255)
favorite_users = models.... | 48 | 1,593 |
jupytext | src/jupytext/marimo.py | .py | """Jupyter notebook to Marimo py format and back, using Marimo"""
import os
from packaging.version import parse
import tempfile
import subprocess
import nbformat
MARIMO_MIN_VERSION = "0.16.3"
class MarimoError(OSError):
"""An error related to Marimo"""
def is_marimo_available(min_version=MARIMO_MIN_VERSION, m... | 156 | 5,344 |
pyomo | examples/pyomobook/abstract-ch/concrete1.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... | 18 | 904 |
funcy | funcy/__init__.py | .py | import sys
from .calc import *
from .colls import *
from .tree import *
from .decorators import *
from .funcolls import *
from .funcs import *
from .seqs import *
from .types import *
from .strings import *
from .flow import *
from .objects import *
from .debug import *
from .primitives import *
# Setup __all__
modu... | 22 | 535 |
rq | tests/fixtures.py | .py | """
This file contains all jobs that are used in tests. Each of these test
fixtures has a slightly different characteristics.
"""
from __future__ import annotations
import os
import signal
import subprocess
import sys
import time
from multiprocessing import Process
from redis import Redis
from rq import Queue, get... | 376 | 10,227 |
wandb | core/hatch.py | .py | """Builds wandb-core."""
from __future__ import annotations
import os
import pathlib
import shutil
import subprocess
from collections.abc import Mapping
def build_wandb_core(
go_binary: pathlib.Path,
output_path: pathlib.PurePath,
with_code_coverage: bool,
with_race_detection: bool,
with_cgo: bo... | 161 | 5,345 |
pyomo | pyomo/contrib/trustregion/util.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... | 158 | 4,825 |
kombu | t/unit/test_mixins.py | .py | from __future__ import annotations
import socket
from unittest.mock import Mock, patch
import pytest
from kombu.mixins import ConsumerMixin
from t.mocks import ContextMock
def Message(body, content_type='text/plain', content_encoding='utf-8'):
m = Mock(name='Message')
m.body = body
m.content_type = con... | 260 | 8,605 |
textual | tests/css/test_screen_css.py | .py | from textual.app import App
from textual.color import Color
from textual.screen import Screen
from textual.widgets import Label
RED = Color(255, 0, 0)
GREEN = Color(0, 255, 0)
BLUE = Color(0, 0, 255)
class BaseScreen(Screen):
def compose(self):
yield Label("Hello, world!", id="app-css")
yield Lab... | 309 | 8,637 |
onnx | onnx/reference/ops/op_attention.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.reference.op_run import OpRun
def _softmax(x: np.ndarray, axis: int = -1) -> np.ndarray:
x_max = np.max(x, axis=axis, keepdims=True)
# A fully-masked r... | 337 | 14,743 |
rq | tests/test_results.py | .py | import tempfile
import time
from datetime import timedelta
from rq.defaults import UNSERIALIZABLE_RETURN_VALUE_PAYLOAD
from rq.executions import prepare_execution
from rq.job import Job, Retry
from rq.queue import Queue
from rq.registry import StartedJobRegistry
from rq.results import Result, get_key
from rq.utils imp... | 335 | 13,712 |
bazel | src/test/shell/bazel/remote/uds_proxy.py | .py | # Copyright 2019 The Bazel Authors. All rights reserved.
#
# 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 la... | 64 | 1,896 |
hatch | src/hatch/cli/check/fmt.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING
import click
if TYPE_CHECKING:
from hatch.cli.application import Application
@click.command(short_help="Verify formatting", context_settings={"ignore_unknown_options": True})
@click.argument("args", nargs=-1)
@click.option("--fix", is_flag=Tru... | 75 | 2,777 |
textual | tests/test_switch.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Switch
async def test_switch_click_doesnt_bubble_up():
"""Regression test for https://github.com/Textualize/textual/issues/2366"""
class SwitchApp(App[None]):
def compose(self) -> ComposeResult:
yield Switch()
... | 19 | 571 |
mlflow | mlflow/protos/databricks_tracing_pb2.py | .py |
import google.protobuf
from packaging.version import Version
if Version(google.protobuf.__version__).major >= 5:
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: databricks_tracing.proto
# Protobuf Python Version: 5.26.0
"""Generated protocol buffer code."""
from... | 1,065 | 105,420 |
mlflow | mlflow/utils/search_utils.py | .py | import ast
import base64
import json
import math
import operator
import re
import shlex
from dataclasses import asdict, dataclass
from typing import TYPE_CHECKING, Any, Callable
import sqlparse
from packaging.version import Version
from sqlparse.sql import (
Comparison,
Identifier,
Parenthesis,
Stateme... | 2,888 | 118,188 |
wandb | wandb/plot/histogram.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING
from wandb.plot.custom_chart import plot_table
if TYPE_CHECKING:
import wandb
from wandb.plot.custom_chart import CustomChart
def histogram(
table: wandb.Table,
value: str,
title: str = "",
split_table: bool = False,
) -> C... | 67 | 1,701 |
django-cms | cms/tests/test_plugins.py | .py | import datetime
import pickle
import warnings
from contextlib import contextmanager
from unittest import mock, skipIf
from django import http
from django.conf import settings
from django.contrib import admin
from django.contrib.admin.widgets import FilteredSelectMultiple, RelatedFieldWidgetWrapper
from django.core.exc... | 2,173 | 98,418 |
luigi | test/contrib/redis_test.py | .py | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | 68 | 2,043 |
sphinx | sphinx/ext/autodoc/_dynamic/_importer.py | .py | """Importer utilities for autodoc"""
from __future__ import annotations
import contextlib
import importlib
import os
import sys
import traceback
import typing
from importlib.abc import FileLoader
from importlib.machinery import EXTENSION_SUFFIXES
from importlib.util import decode_source, find_spec, module_from_spec, ... | 432 | 14,519 |
probability | tensorflow_probability/python/experimental/mcmc/sample_discarding_kernel_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... | 313 | 13,192 |
jupytext | src/jupytext/header.py | .py | """Parse header of text notebooks"""
import logging
import re
import nbformat
import yaml
from nbformat.v4.nbbase import new_raw_cell
from yaml.representer import SafeRepresenter
from .languages import (
_SCRIPT_EXTENSIONS,
comment_lines,
default_language_from_metadata_and_ext,
)
from .metadata_filter im... | 342 | 12,122 |
beam | sdks/python/apache_beam/examples/cookbook/bigquery_tornadoes_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... | 58 | 1,887 |
saleor | saleor/graphql/csv/resolvers.py | .py | from ...csv import models
from ..core.context import get_database_connection_name
def resolve_export_file(info, id):
return (
models.ExportFile.objects.using(get_database_connection_name(info.context))
.filter(id=id)
.first()
)
def resolve_export_files(info):
return models.Export... | 17 | 403 |
sqlmap | extra/kerberos/client.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
# Dependency-free Kerberos 5 client (RFC 4120) built on the in-tree DER codec and RFC 3961/3962
# crypto. Implements the AS exchange (password -> TGT) with PA-ENC-TIMESTAMP pre-au... | 412 | 20,597 |
qutip | qutip/legacy/nonmarkov/memorycascade.py | .py | # @author: Arne L. Grimsmo
# @email1: arne.grimsmo@gmail.com
# @organization: University of Sherbrooke
"""
This module is an implementation of the method introduced in [1], for
solving open quantum systems subject to coherent feedback with a single
discrete time-delay. This method is referred to as the ``memory cascad... | 432 | 12,909 |
sphinx | tests/roots/test-ext-autodoc/circular_import/b.py | .py | import typing
if typing.TYPE_CHECKING:
from circular_import import SomeClass
| 5 | 82 |
mlflow | mlflow/utils/huggingface_utils.py | .py | import functools
import logging
import os
import time
from mlflow.environment_variables import _MLFLOW_TESTING
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import RESOURCE_DOES_NOT_EXIST
_logger = logging.getLogger(__name__)
# NB: The maxsize=1 is added for encouraging the cache r... | 83 | 2,966 |
onnxruntime | orttraining/orttraining/test/python/orttraining_test_ortmodule_fairscale_sharded_optimizer.py | .py | import argparse
import os
import time
import numpy as np
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import torchvision
from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP
from fairscale.optim.oss import OSS
from torch.nn.parallel import DistributedDataParallel... | 277 | 10,519 |
coremltools | deps/kmeans1d/kmeans1d/core.py | .py | # MIT License
#
# Copyright (c) 2019 Daniel Steinberg
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, me... | 75 | 2,551 |
conda | tests/core/test_subdir_data.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from logging import getLogger
from os.path import join
from pathlib import Path
from time import sleep
from typing import TYPE_CHECKING
import pytest
from conda import CondaError
from conda.base.context impo... | 447 | 15,304 |
saleor | saleor/tests/e2e/account/utils/staff_create.py | .py | from ...utils import get_graphql_content
STAFF_CREATE_MUTATION = """
mutation CreateStaff($input: StaffCreateInput!){
staffCreate(input:$input) {
user {
id
metadata {
key
value
}
privateMetadata {
key
value
}
}
errors {
field
messa... | 43 | 712 |
saleor | saleor/webhook/tests/subscription_webhooks/test_create_deliveries_for_transaction_initialize_session.py | .py | import json
import uuid
from decimal import Decimal
import graphene
from ....channel import TransactionFlowStrategy
from ....payment.interface import (
PaymentGatewayData,
TransactionProcessActionData,
TransactionSessionData,
)
from ...event_types import WebhookEventSyncType
from ...models import Webhook
... | 409 | 12,130 |
readthedocs.org | readthedocs/core/signals.py | .py | """Signal handling for core app."""
import requests
import structlog
from allauth.account.signals import email_confirmed
from django.conf import settings
from django.db.models.signals import post_save
from django.db.models.signals import pre_delete
from django.dispatch import Signal
from django.dispatch import receive... | 121 | 4,127 |
saleor | saleor/graphql/page/bulk_mutations.py | .py | import graphene
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Exists, OuterRef
from ...attribute import AttributeInputType
from ...attribute import models as attribute_models
from ...attribute.lock_objects import attri... | 211 | 7,950 |
saleor | saleor/graphql/app/tests/queries/test_app_problems.py | .py | import graphene
from .....app.models import AppProblem
from ....tests.utils import get_graphql_content, get_graphql_content_from_response
QUERY_APP_PROBLEMS = """
query ($id: ID) {
app(id: $id) {
id
problems {
id
message
key
... | 640 | 19,008 |
astropy | astropy/tests/__init__.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This package contains utilities to run the astropy test suite, tools
for writing tests, and general tests that are not associated with a
particular package.
"""
| 7 | 229 |
beam | sdks/python/apache_beam/testing/pipeline_verifiers_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... | 161 | 5,953 |
mlflow | tests/test_mlflow_version_comp.py | .py | import os
import subprocess
import sys
import uuid
from pathlib import Path
import numpy as np
import sklearn
from pyspark.sql import SparkSession
from sklearn.linear_model import LinearRegression
import mlflow
from mlflow.models import Model
def check_load(model_uri: str) -> None:
Model.load(model_uri)
mod... | 230 | 9,038 |
saleor | saleor/payment/tests/fixtures/payment.py | .py | import pytest
from ....payment import ChargeStatus, TransactionKind
from ....payment.models import Payment
from ....webhook.transport.utils import to_payment_app_id
@pytest.fixture
def payment_dummy(db, order_with_lines):
return Payment.objects.create(
gateway="mirumee.payments.dummy",
order=orde... | 192 | 5,942 |
cvxpy | cvxpy/reductions/dgp2dcp/canonicalizers/geo_mean_canon.py | .py | def geo_mean_canon(expr, args):
out = 0.0
for x_i, p_i in zip(args[0], expr.p):
out += p_i * x_i
return (1 / sum(expr.p)) * out, []
| 6 | 152 |
scikit-bio | skbio/stats/distance/tests/test_permanova.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.
# --------------------------------------------... | 514 | 23,967 |
qutip | qutip/solver/integrator/krylov.py | .py | import numpy as np
from qutip.core import data as _data
from ..integrator import IntegratorException, Integrator
from ..sesolve import SESolver
from ..mesolve import MESolver
__all__ = ["IntegratorKrylov"]
class IntegratorKrylov(Integrator):
"""
Evolve the state ("rho0") finding an approximation for the tim... | 345 | 12,577 |
textual | tests/document/test_document_insert.py | .py | from textual.widgets.text_area import Document
TEXT = """I must not fear.
Fear is the mind-killer."""
def test_insert_no_newlines():
document = Document(TEXT)
document.replace_range((0, 1), (0, 1), " really")
assert document.lines == [
"I really must not fear.",
"Fear is the mind-killer."... | 108 | 2,958 |
probability | spinoffs/inference_gym/inference_gym/using_tensorflow.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... | 24 | 833 |
beam | sdks/python/apache_beam/portability/python_urns.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... | 71 | 3,027 |
sqlmap | tests/test_fingerprint.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
DBMS version/fork fingerprinting (plugins/dbms/<dbms>/fingerprint.py). Each
plugin's getFingerprint()/checkDbms() probes the backend with a cascade of
boolean expressions (inject.chec... | 214 | 10,187 |
coremltools | coremltools/converters/mil/mil/ops/defs/iOS15/conv.py | .py | # Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from coremltools.converters.mil.mil import Operation, types
from coremltools.converters.mil.mil.block... | 432 | 16,928 |
qutip | doc/guide/scripts/ex_bloch_animation.py | .py | import numpy as np
import qutip
def qubit_integrate(w, theta, gamma1, gamma2, psi0, tlist):
# operators and the hamiltonian
sx = qutip.sigmax()
sy = qutip.sigmay()
sz = qutip.sigmaz()
sm = qutip.sigmam()
H = w * (np.cos(theta) * sz + np.sin(theta) * sx)
# collapse operators
c_op_list = ... | 35 | 1,267 |
django-cms | cms/templatetags/cms_static.py | .py | from django import template
from django.templatetags.static import StaticNode
from cms.utils.urlutils import static_with_version
register = template.Library()
@register.tag('static_with_version')
def do_static_with_version(parser, token):
"""
Joins the given path with the STATIC_URL setting
and appends ... | 33 | 972 |
openvino | src/bindings/python/src/openvino/opset16/ops.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Factory functions for ops added to openvino opset16."""
from functools import partial
from typing import Optional, Literal
from openvino import Node
from openvino.utils.decorators import nameable_op
from openv... | 219 | 8,360 |
readthedocs.org | readthedocs/api/v2/admin.py | .py | from django.contrib import admin
from rest_framework_api_key.admin import APIKeyModelAdmin
from readthedocs.api.v2.models import BuildAPIKey
@admin.register(BuildAPIKey)
class BuildAPIKeyAdmin(APIKeyModelAdmin):
raw_id_fields = ["project"]
search_fields = [*APIKeyModelAdmin.search_fields, "project__slug"]
| 11 | 318 |
saleor | saleor/tests/e2e/vouchers/utils/voucher_bulk_delete.py | .py | from ...utils import get_graphql_content
VOUCHER_BULK_DELETE_MUTATION = """
mutation VoucherBulkDelete ($ids: [ID!]!) {
voucherBulkDelete(ids: $ids) {
errors {
voucherCodes
message
field
code
}
count
}
}
"""
def voucher_bulk_delete(staff_api_client, voucher_ids):
variables... | 33 | 646 |
saleor | saleor/graphql/order/tests/dataloaders/test_order_shipping_methods.py | .py | import uuid
from .....shipping.interface import ShippingMethodData
from ....context import SaleorContext
from ...dataloaders import OrderShippingMethodsByOrderIdAndWebhookSyncLoader
def _build_context():
context = SaleorContext()
context.app = None
context.user = None
context.allow_replica = False
... | 62 | 1,729 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.